Parse.cpp 507 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641
  1. //-------------------------------------------------------------------------------------------------------
  2. // Copyright (C) Microsoft. All rights reserved.
  3. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
  4. //-------------------------------------------------------------------------------------------------------
  5. #include "ParserPch.h"
  6. #include "FormalsUtil.h"
  7. #include "../Runtime/Language/SourceDynamicProfileManager.h"
  8. #include "ByteCode/ByteCodeSerializer.h"
  9. #if DBG_DUMP
  10. void PrintPnodeWIndent(ParseNode *pnode, int indentAmt);
  11. #endif
  12. const char* const nopNames[knopLim] = {
  13. #define PTNODE(nop,sn,pc,nk,grfnop,json) sn,
  14. #include "ptlist.h"
  15. };
  16. void printNop(int nop) {
  17. Output::Print(_u("%S\n"), nopNames[nop]);
  18. }
  19. const uint ParseNode::mpnopgrfnop[knopLim] =
  20. {
  21. #define PTNODE(nop,sn,pc,nk,grfnop,json) grfnop,
  22. #include "ptlist.h"
  23. };
  24. bool Parser::IsES6DestructuringEnabled() const
  25. {
  26. return m_scriptContext->GetConfig()->IsES6DestructuringEnabled();
  27. }
  28. struct BlockInfoStack
  29. {
  30. StmtNest pstmt;
  31. ParseNodeBlock *pnodeBlock;
  32. ParseNodePtr *m_ppnodeLex; // lexical variable list tail
  33. BlockInfoStack *pBlockInfoOuter; // containing block's BlockInfoStack
  34. BlockInfoStack *pBlockInfoFunction; // nearest function's BlockInfoStack (if pnodeBlock is a function, this points to itself)
  35. };
  36. #if DEBUG
  37. Parser::Parser(Js::ScriptContext* scriptContext, BOOL strictMode, PageAllocator *alloc, bool isBackground, size_t size)
  38. #else
  39. Parser::Parser(Js::ScriptContext* scriptContext, BOOL strictMode, PageAllocator *alloc, bool isBackground)
  40. #endif
  41. : m_nodeAllocator(_u("Parser"), alloc ? alloc : scriptContext->GetThreadContext()->GetPageAllocator(), Parser::OutOfMemory),
  42. m_cactIdentToNodeLookup(0),
  43. m_grfscr(fscrNil),
  44. m_length(0),
  45. m_originalLength(0),
  46. m_nextFunctionId(nullptr),
  47. m_sourceContextInfo(nullptr),
  48. #if ENABLE_BACKGROUND_PARSING
  49. m_isInBackground(isBackground),
  50. m_hasParallelJob(false),
  51. m_doingFastScan(false),
  52. #endif
  53. m_nextBlockId(0),
  54. m_tempGuestArenaReleased(false),
  55. m_tempGuestArena(scriptContext->GetTemporaryGuestAllocator(_u("ParserRegex")), scriptContext->GetRecycler()),
  56. // use the GuestArena directly for keeping the RegexPattern* alive during byte code generation
  57. m_registeredRegexPatterns(m_tempGuestArena->GetAllocator()),
  58. m_scriptContext(scriptContext),
  59. m_token(), // should initialize to 0/nullptrs
  60. m_scan(this, &m_token, scriptContext),
  61. m_currentNodeNonLambdaFunc(nullptr),
  62. m_currentNodeNonLambdaDeferredFunc(nullptr),
  63. m_currentNodeFunc(nullptr),
  64. m_currentNodeDeferredFunc(nullptr),
  65. m_currentNodeProg(nullptr),
  66. m_currDeferredStub(nullptr),
  67. m_currDeferredStubCount(0),
  68. m_pCurrentAstSize(nullptr),
  69. m_ppnodeScope(nullptr),
  70. m_ppnodeExprScope(nullptr),
  71. m_ppnodeVar(nullptr),
  72. m_inDeferredNestedFunc(false),
  73. m_reparsingLambdaParams(false),
  74. m_disallowImportExportStmt(false),
  75. m_isInParsingArgList(false),
  76. m_hasDestructuringPattern(false),
  77. m_hasDeferredShorthandInitError(false),
  78. m_deferCommaError(false),
  79. m_pnestedCount(nullptr),
  80. wellKnownPropertyPids(), // should initialize to nullptrs
  81. m_sourceLim(0),
  82. m_functionBody(nullptr),
  83. m_parseType(ParseType_Upfront),
  84. m_arrayDepth(0),
  85. m_funcInArrayDepth(0),
  86. m_funcInArray(0),
  87. m_scopeCountNoAst(0),
  88. m_funcParenExprDepth(0),
  89. m_deferEllipsisError(false),
  90. m_deferEllipsisErrorLoc(), // calls default initializer
  91. m_deferCommaErrorLoc(),
  92. m_tryCatchOrFinallyDepth(0),
  93. m_pstmtCur(nullptr),
  94. m_currentBlockInfo(nullptr),
  95. m_currentScope(nullptr),
  96. currBackgroundParseItem(nullptr),
  97. backgroundParseItems(nullptr),
  98. fastScannedRegExpNodes(nullptr),
  99. m_currentDynamicBlock(nullptr),
  100. m_UsesArgumentsAtGlobal(false),
  101. m_fUseStrictMode(strictMode),
  102. m_InAsmMode(false),
  103. m_deferAsmJs(true),
  104. m_fExpectExternalSource(FALSE),
  105. m_deferringAST(FALSE),
  106. m_stoppedDeferredParse(FALSE)
  107. {
  108. AssertMsg(size == sizeof(Parser), "verify conditionals affecting the size of Parser agree");
  109. Assert(scriptContext != nullptr);
  110. // init PID members
  111. InitPids();
  112. }
  113. Parser::~Parser(void)
  114. {
  115. this->ReleaseTemporaryGuestArena();
  116. #if ENABLE_BACKGROUND_PARSING
  117. if (this->m_hasParallelJob)
  118. {
  119. // Let the background threads know that they can decommit their arena pages.
  120. BackgroundParser *bgp = m_scriptContext->GetBackgroundParser();
  121. Assert(bgp);
  122. if (bgp->Processor()->ProcessesInBackground())
  123. {
  124. JsUtil::BackgroundJobProcessor *processor = static_cast<JsUtil::BackgroundJobProcessor*>(bgp->Processor());
  125. bool result = processor->IterateBackgroundThreads([&](JsUtil::ParallelThreadData *threadData)->bool {
  126. threadData->canDecommit = true;
  127. return false;
  128. });
  129. Assert(result);
  130. }
  131. }
  132. #endif
  133. }
  134. void Parser::OutOfMemory()
  135. {
  136. throw ParseExceptionObject(ERRnoMemory);
  137. }
  138. LPCWSTR Parser::GetTokenString(tokens token)
  139. {
  140. switch (token)
  141. {
  142. case tkNone : return _u("");
  143. case tkEOF : return _u("end of script");
  144. case tkIntCon : return _u("integer literal");
  145. case tkFltCon : return _u("float literal");
  146. case tkStrCon : return _u("string literal");
  147. case tkRegExp : return _u("regular expression literal");
  148. // keywords
  149. case tkABSTRACT : return _u("abstract");
  150. case tkASSERT : return _u("assert");
  151. case tkAWAIT : return _u("await");
  152. case tkBOOLEAN : return _u("boolean");
  153. case tkBREAK : return _u("break");
  154. case tkBYTE : return _u("byte");
  155. case tkCASE : return _u("case");
  156. case tkCATCH : return _u("catch");
  157. case tkCHAR : return _u("char");
  158. case tkCONTINUE : return _u("continue");
  159. case tkDEBUGGER : return _u("debugger");
  160. case tkDECIMAL : return _u("decimal");
  161. case tkDEFAULT : return _u("default");
  162. case tkDELETE : return _u("delete");
  163. case tkDO : return _u("do");
  164. case tkDOUBLE : return _u("double");
  165. case tkELSE : return _u("else");
  166. case tkENSURE : return _u("ensure");
  167. case tkEVENT : return _u("event");
  168. case tkFALSE : return _u("false");
  169. case tkFINAL : return _u("final");
  170. case tkFINALLY : return _u("finally");
  171. case tkFLOAT : return _u("float");
  172. case tkFOR : return _u("for");
  173. case tkFUNCTION : return _u("function");
  174. case tkGET : return _u("get");
  175. case tkGOTO : return _u("goto");
  176. case tkIF : return _u("if");
  177. case tkIN : return _u("in");
  178. case tkINSTANCEOF : return _u("instanceof");
  179. case tkINT : return _u("int");
  180. case tkINTERNAL : return _u("internal");
  181. case tkINVARIANT : return _u("invariant");
  182. case tkLONG : return _u("long");
  183. case tkNAMESPACE : return _u("namespace");
  184. case tkNATIVE : return _u("native");
  185. case tkNEW : return _u("new");
  186. case tkNULL : return _u("null");
  187. case tkREQUIRE : return _u("require");
  188. case tkRETURN : return _u("return");
  189. case tkSBYTE : return _u("sbyte");
  190. case tkSET : return _u("set");
  191. case tkSHORT : return _u("short");
  192. case tkSWITCH : return _u("switch");
  193. case tkSYNCHRONIZED : return _u("synchronized");
  194. case tkTHIS : return _u("this");
  195. case tkTHROW : return _u("throw");
  196. case tkTHROWS : return _u("throws");
  197. case tkTRANSIENT : return _u("transient");
  198. case tkTRUE : return _u("true");
  199. case tkTRY : return _u("try");
  200. case tkTYPEOF : return _u("typeof");
  201. case tkUINT : return _u("uint");
  202. case tkULONG : return _u("ulong");
  203. case tkUSE : return _u("use");
  204. case tkUSHORT : return _u("ushort");
  205. case tkVAR : return _u("var");
  206. case tkVOID : return _u("void");
  207. case tkVOLATILE : return _u("volatile");
  208. case tkWHILE : return _u("while");
  209. case tkWITH : return _u("with");
  210. // Future reserved words that become keywords in ES6
  211. case tkCLASS : return _u("class");
  212. case tkCONST : return _u("const");
  213. case tkEXPORT : return _u("export");
  214. case tkEXTENDS : return _u("extends");
  215. case tkIMPORT : return _u("import");
  216. case tkLET : return _u("let");
  217. case tkSUPER : return _u("super");
  218. case tkYIELD : return _u("yield");
  219. // Future reserved words in strict and non-strict modes
  220. case tkENUM : return _u("enum");
  221. // Additional future reserved words in strict mode
  222. case tkIMPLEMENTS : return _u("implements");
  223. case tkINTERFACE : return _u("interface");
  224. case tkPACKAGE : return _u("package");
  225. case tkPRIVATE : return _u("private");
  226. case tkPROTECTED : return _u("protected");
  227. case tkPUBLIC : return _u("public");
  228. case tkSTATIC : return _u("static");
  229. case tkID: return _u("identifier");
  230. // Non-operator non-identifier tokens
  231. case tkSColon: return _u(";");
  232. case tkRParen: return _u(")");
  233. case tkRBrack: return _u("]");
  234. case tkLCurly: return _u("{");
  235. case tkRCurly: return _u("}");
  236. // Operator non-identifier tokens
  237. case tkComma: return _u(",");
  238. case tkDArrow: return _u("=>");
  239. case tkAsg: return _u("=");
  240. case tkAsgAdd: return _u("+=");
  241. case tkAsgSub: return _u("-=");
  242. case tkAsgMul: return _u("*=");
  243. case tkAsgDiv: return _u("/=");
  244. case tkAsgExpo: return _u("**=");
  245. case tkAsgMod: return _u("%=");
  246. case tkAsgAnd: return _u("&=");
  247. case tkAsgXor: return _u("^=");
  248. case tkAsgOr: return _u("|=");
  249. case tkAsgLsh: return _u("<<=");
  250. case tkAsgRsh: return _u(">>=");
  251. case tkAsgRs2: return _u(">>>=");
  252. case tkQMark: return _u("?");
  253. case tkColon: return _u(":");
  254. case tkLogOr: return _u("||");
  255. case tkLogAnd: return _u("&&");
  256. case tkOr: return _u("|");
  257. case tkXor: return _u("^");
  258. case tkAnd: return _u("&");
  259. case tkEQ: return _u("==");
  260. case tkNE: return _u("!=");
  261. case tkEqv: return _u("===");
  262. case tkNEqv: return _u("!==");
  263. case tkLT: return _u("<");
  264. case tkLE: return _u("<=");
  265. case tkGT: return _u(">");
  266. case tkGE: return _u(">=");
  267. case tkLsh: return _u("<<");
  268. case tkRsh: return _u(">>");
  269. case tkRs2: return _u(">>>");
  270. case tkAdd: return _u("+");
  271. case tkSub: return _u("-");
  272. case tkExpo: return _u("**");
  273. case tkStar: return _u("*");
  274. case tkDiv: return _u("/");
  275. case tkPct: return _u("%");
  276. case tkTilde: return _u("~");
  277. case tkBang: return _u("!");
  278. case tkInc: return _u("++");
  279. case tkDec: return _u("--");
  280. case tkEllipsis: return _u("...");
  281. case tkLParen: return _u("(");
  282. case tkLBrack: return _u("[");
  283. case tkDot: return _u(".");
  284. default:
  285. return _u("unknown token");
  286. }
  287. }
  288. void Parser::Error(HRESULT hr, LPCWSTR stringOne, LPCWSTR stringTwo)
  289. {
  290. throw ParseExceptionObject(hr, stringOne, stringTwo);
  291. }
  292. void Parser::Error(HRESULT hr, ParseNodePtr pnode)
  293. {
  294. if (pnode && pnode->ichLim)
  295. {
  296. Error(hr, pnode->ichMin, pnode->ichLim);
  297. }
  298. else
  299. {
  300. Error(hr);
  301. }
  302. }
  303. void Parser::Error(HRESULT hr, charcount_t ichMin, charcount_t ichLim, LPCWSTR stringOne, LPCWSTR stringTwo)
  304. {
  305. this->GetScanner()->SetErrorPosition(ichMin, ichLim);
  306. Error(hr, stringOne, stringTwo);
  307. }
  308. void Parser::IdentifierExpectedError(const Token& token)
  309. {
  310. Assert(token.tk != tkID);
  311. HRESULT hr;
  312. if (token.IsReservedWord())
  313. {
  314. if (token.IsKeyword())
  315. {
  316. hr = ERRKeywordNotId;
  317. }
  318. else
  319. {
  320. Assert(token.IsFutureReservedWord(true));
  321. if (token.IsFutureReservedWord(false))
  322. {
  323. // Future reserved word in strict and non-strict modes
  324. hr = ERRFutureReservedWordNotId;
  325. }
  326. else
  327. {
  328. // Future reserved word only in strict mode. The token would have been converted to tkID by the scanner if not
  329. // in strict mode.
  330. Assert(IsStrictMode());
  331. hr = ERRFutureReservedWordInStrictModeNotId;
  332. }
  333. }
  334. }
  335. else
  336. {
  337. hr = ERRnoIdent;
  338. }
  339. Error(hr);
  340. }
  341. HRESULT Parser::ValidateSyntax(LPCUTF8 pszSrc, size_t encodedCharCount, bool isGenerator, bool isAsync, CompileScriptException *pse, void (Parser::*validateFunction)())
  342. {
  343. Assert(pszSrc);
  344. PROBE_STACK_NO_DISPOSE(m_scriptContext, Js::Constants::MinStackDefault);
  345. HRESULT hr;
  346. SmartFPUControl smartFpuControl;
  347. bool handled = false;
  348. BOOL fDeferSave = m_deferringAST;
  349. try
  350. {
  351. hr = NOERROR;
  352. m_length = encodedCharCount;
  353. m_originalLength = encodedCharCount;
  354. // make sure deferred parsing is turned off
  355. ULONG grfscr = fscrNil;
  356. // Give the scanner the source and get the first token
  357. this->GetScanner()->SetText(pszSrc, 0, encodedCharCount, 0, false, grfscr);
  358. this->GetScanner()->SetYieldIsKeywordRegion(isGenerator);
  359. this->GetScanner()->SetAwaitIsKeywordRegion(isAsync);
  360. this->GetScanner()->Scan();
  361. uint nestedCount = 0;
  362. m_pnestedCount = &nestedCount;
  363. ParseNodePtr pnodeScope = nullptr;
  364. m_ppnodeScope = &pnodeScope;
  365. m_ppnodeExprScope = nullptr;
  366. uint nextFunctionId = 0;
  367. m_nextFunctionId = &nextFunctionId;
  368. m_inDeferredNestedFunc = false;
  369. m_deferringAST = true;
  370. m_nextBlockId = 0;
  371. ParseNodeFnc *pnodeFnc = CreateAllowDeferNodeForOpT<knopFncDecl>();
  372. pnodeFnc->SetIsGenerator(isGenerator);
  373. pnodeFnc->SetIsAsync(isAsync);
  374. m_ppnodeVar = &pnodeFnc->pnodeVars;
  375. m_currentNodeFunc = pnodeFnc;
  376. m_currentNodeDeferredFunc = NULL;
  377. m_sourceContextInfo = nullptr;
  378. AssertMsg(m_pstmtCur == NULL, "Statement stack should be empty when we start parse function body");
  379. ParseNodeBlock * block = StartParseBlock<false>(PnodeBlockType::Function, ScopeType_FunctionBody);
  380. (this->*validateFunction)();
  381. FinishParseBlock(block);
  382. pnodeFnc->ichLim = this->GetScanner()->IchLimTok();
  383. pnodeFnc->cbLim = this->GetScanner()->IecpLimTok();
  384. pnodeFnc->pnodeVars = nullptr;
  385. // there should be nothing after successful parsing for a given construct
  386. if (m_token.tk != tkEOF)
  387. Error(ERRsyntax);
  388. m_deferringAST = fDeferSave;
  389. }
  390. catch (ParseExceptionObject& e)
  391. {
  392. m_deferringAST = fDeferSave;
  393. hr = e.GetError();
  394. hr = pse->ProcessError(this->GetScanner(), hr, /* pnodeBase */ NULL, e.GetStringOne(), e.GetStringTwo());
  395. handled = true;
  396. }
  397. if (handled == false && nullptr != pse && FAILED(hr))
  398. {
  399. hr = pse->ProcessError(this->GetScanner(), hr, /* pnodeBase */ NULL);
  400. }
  401. return hr;
  402. }
  403. HRESULT Parser::ParseSourceInternal(
  404. __out ParseNodeProg ** parseTree, LPCUTF8 pszSrc, size_t offsetInBytes, size_t encodedCharCount, charcount_t offsetInChars,
  405. bool isUtf8, ULONG grfscr, CompileScriptException *pse, Js::LocalFunctionId * nextFunctionId, ULONG lineNumber, SourceContextInfo * sourceContextInfo)
  406. {
  407. Assert(parseTree);
  408. Assert(pszSrc);
  409. if (this->IsBackgroundParser())
  410. {
  411. PROBE_STACK_NO_DISPOSE(m_scriptContext, Js::Constants::MinStackDefault);
  412. }
  413. else
  414. {
  415. PROBE_STACK(m_scriptContext, Js::Constants::MinStackDefault);
  416. }
  417. #ifdef PROFILE_EXEC
  418. m_scriptContext->ProfileBegin(Js::ParsePhase);
  419. #endif
  420. JS_ETW_INTERNAL(EventWriteJSCRIPT_PARSE_START(m_scriptContext, 0));
  421. *parseTree = NULL;
  422. m_sourceLim = 0;
  423. m_grfscr = grfscr;
  424. m_sourceContextInfo = sourceContextInfo;
  425. ParseNodeProg * pnodeBase = NULL;
  426. HRESULT hr;
  427. SmartFPUControl smartFpuControl;
  428. bool handled = false;
  429. try
  430. {
  431. if ((grfscr & fscrIsModuleCode) != 0)
  432. {
  433. // Module source flag should not be enabled unless module is enabled
  434. Assert(m_scriptContext->GetConfig()->IsES6ModuleEnabled());
  435. // Module code is always strict mode code.
  436. this->m_fUseStrictMode = TRUE;
  437. }
  438. if ((grfscr & fscrUseStrictMode) != 0)
  439. {
  440. this->m_fUseStrictMode = TRUE;
  441. }
  442. // parse the source
  443. pnodeBase = Parse(pszSrc, offsetInBytes, encodedCharCount, offsetInChars, isUtf8, grfscr, lineNumber, nextFunctionId, pse);
  444. Assert(pnodeBase);
  445. // Record the actual number of words parsed.
  446. m_sourceLim = pnodeBase->ichLim - offsetInChars;
  447. // TODO: The assert can be false positive in some scenarios and chuckj to fix it later
  448. // Assert(utf8::ByteIndexIntoCharacterIndex(pszSrc + offsetInBytes, encodedCharCount, isUtf8 ? utf8::doDefault : utf8::doAllowThreeByteSurrogates) == m_sourceLim);
  449. #if DBG_DUMP
  450. if (Js::Configuration::Global.flags.Trace.IsEnabled(Js::ParsePhase))
  451. {
  452. PrintPnodeWIndent(pnodeBase, 4);
  453. fflush(stdout);
  454. }
  455. #endif
  456. *parseTree = pnodeBase;
  457. hr = NOERROR;
  458. }
  459. catch (ParseExceptionObject& e)
  460. {
  461. hr = e.GetError();
  462. hr = pse->ProcessError(this->GetScanner(), hr, pnodeBase, e.GetStringOne(), e.GetStringTwo());
  463. handled = true;
  464. }
  465. catch (Js::AsmJsParseException&)
  466. {
  467. hr = JSERR_AsmJsCompileError;
  468. }
  469. if (handled == false && FAILED(hr))
  470. {
  471. hr = pse->ProcessError(this->GetScanner(), hr, pnodeBase);
  472. }
  473. #if ENABLE_BACKGROUND_PARSING
  474. if (this->m_hasParallelJob)
  475. {
  476. ///// Wait here for remaining jobs to finish. Then look for errors, do final const bindings.
  477. // pleath TODO: If there are remaining jobs, let the main thread help finish them.
  478. BackgroundParser *bgp = m_scriptContext->GetBackgroundParser();
  479. Assert(bgp);
  480. CompileScriptException se;
  481. this->WaitForBackgroundJobs(bgp, &se);
  482. BackgroundParseItem *failedItem = bgp->GetFailedBackgroundParseItem();
  483. if (failedItem)
  484. {
  485. CompileScriptException *bgPse = failedItem->GetPSE();
  486. Assert(bgPse);
  487. *pse = *bgPse;
  488. hr = failedItem->GetHR();
  489. bgp->SetFailedBackgroundParseItem(nullptr);
  490. }
  491. if (this->fastScannedRegExpNodes != nullptr)
  492. {
  493. this->FinishBackgroundRegExpNodes();
  494. }
  495. for (BackgroundParseItem *item = this->backgroundParseItems; item; item = item->GetNext())
  496. {
  497. Parser *parser = item->GetParser();
  498. parser->FinishBackgroundPidRefs(item, this != parser);
  499. }
  500. }
  501. #endif
  502. // done with the scanner
  503. this->GetScanner()->Clear();
  504. #ifdef PROFILE_EXEC
  505. m_scriptContext->ProfileEnd(Js::ParsePhase);
  506. #endif
  507. JS_ETW_INTERNAL(EventWriteJSCRIPT_PARSE_STOP(m_scriptContext, 0));
  508. return hr;
  509. }
  510. #if ENABLE_BACKGROUND_PARSING
  511. void Parser::WaitForBackgroundJobs(BackgroundParser *bgp, CompileScriptException *pse)
  512. {
  513. // The scan of the script is done, but there may be unfinished background jobs in the queue.
  514. // Enlist the main thread to help with those.
  515. BackgroundParseItem *item;
  516. if (!*bgp->GetPendingBackgroundItemsPtr())
  517. {
  518. // We're done.
  519. return;
  520. }
  521. // Save parser state, since we'll need to restore it in order to bind references correctly later.
  522. this->m_isInBackground = true;
  523. this->SetCurrBackgroundParseItem(nullptr);
  524. uint blockIdSave = this->m_nextBlockId;
  525. uint functionIdSave = *this->m_nextFunctionId;
  526. StmtNest *pstmtSave = this->m_pstmtCur;
  527. if (!bgp->Processor()->ProcessesInBackground())
  528. {
  529. // No background thread. Just walk the jobs with no locking and process them.
  530. for (item = bgp->GetNextUnprocessedItem(); item; item = bgp->GetNextUnprocessedItem())
  531. {
  532. bgp->Processor()->RemoveJob(item);
  533. bool succeeded = bgp->Process(item, this, pse);
  534. bgp->JobProcessed(item, succeeded);
  535. }
  536. Assert(!*bgp->GetPendingBackgroundItemsPtr());
  537. }
  538. else
  539. {
  540. // Background threads. We need to have the critical section in order to:
  541. // - Check for unprocessed jobs;
  542. // - Remove jobs from the processor queue;
  543. // - Do JobsProcessed work (such as removing jobs from the BackgroundParser's unprocessed list).
  544. CriticalSection *pcs = static_cast<JsUtil::BackgroundJobProcessor*>(bgp->Processor())->GetCriticalSection();
  545. pcs->Enter();
  546. for (;;)
  547. {
  548. // Grab a job (in lock)
  549. item = bgp->GetNextUnprocessedItem();
  550. if (item == nullptr)
  551. {
  552. break;
  553. }
  554. bgp->Processor()->RemoveJob(item);
  555. pcs->Leave();
  556. // Process job (if there is one) (outside lock)
  557. bool succeeded = bgp->Process(item, this, pse);
  558. pcs->Enter();
  559. bgp->JobProcessed(item, succeeded);
  560. }
  561. pcs->Leave();
  562. // Wait for the background threads to finish jobs they're already processing (if any).
  563. // TODO: Replace with a proper semaphore.
  564. while (*bgp->GetPendingBackgroundItemsPtr());
  565. }
  566. Assert(!*bgp->GetPendingBackgroundItemsPtr());
  567. // Restore parser state.
  568. this->m_pstmtCur = pstmtSave;
  569. this->m_isInBackground = false;
  570. this->m_nextBlockId = blockIdSave;
  571. *this->m_nextFunctionId = functionIdSave;
  572. }
  573. void Parser::FinishBackgroundPidRefs(BackgroundParseItem *item, bool isOtherParser)
  574. {
  575. for (BlockInfoStack *blockInfo = item->GetParseContext()->currentBlockInfo; blockInfo; blockInfo = blockInfo->pBlockInfoOuter)
  576. {
  577. if (isOtherParser)
  578. {
  579. this->BindPidRefs<true>(blockInfo, item->GetMaxBlockId());
  580. }
  581. else
  582. {
  583. this->BindPidRefs<false>(blockInfo, item->GetMaxBlockId());
  584. }
  585. }
  586. }
  587. void Parser::FinishBackgroundRegExpNodes()
  588. {
  589. // We have a list of RegExp nodes that we saw on the UI thread in functions we're parallel parsing,
  590. // and for each background job we have a list of RegExp nodes for which we couldn't allocate patterns.
  591. // We need to copy the pattern pointers from the UI thread nodes to the corresponding nodes on the
  592. // background nodes.
  593. // There may be UI thread nodes for which there are no background thread equivalents, because the UI thread
  594. // has to assume that the background thread won't defer anything.
  595. // Note that because these lists (and the list of background jobs) are SList's built by prepending, they are
  596. // all in reverse lexical order.
  597. Assert(!this->IsBackgroundParser());
  598. Assert(this->fastScannedRegExpNodes);
  599. Assert(this->backgroundParseItems != nullptr);
  600. BackgroundParseItem *currBackgroundItem;
  601. #if DBG
  602. for (currBackgroundItem = this->backgroundParseItems;
  603. currBackgroundItem;
  604. currBackgroundItem = currBackgroundItem->GetNext())
  605. {
  606. if (currBackgroundItem->RegExpNodeList())
  607. {
  608. FOREACH_DLIST_ENTRY(ParseNodePtr, ArenaAllocator, pnode, currBackgroundItem->RegExpNodeList())
  609. {
  610. Assert(pnode->AsParseNodeRegExp()->regexPattern == nullptr);
  611. }
  612. NEXT_DLIST_ENTRY;
  613. }
  614. }
  615. #endif
  616. // Hook up the patterns allocated on the main thread to the nodes created on the background thread.
  617. // Walk the list of foreground nodes, advancing through the work items and looking up each item.
  618. // Note that the background thread may have chosen to defer a given RegEx literal, so not every foreground
  619. // node will have a matching background node. Doesn't matter for correctness.
  620. // (It's inefficient, of course, to have to restart the inner loop from the beginning of the work item's
  621. // list, but it should be unusual to have many RegExes in a single work item's chunk of code. Figure out how
  622. // to start the inner loop from a known internal node within the list if that turns out to be important.)
  623. currBackgroundItem = this->backgroundParseItems;
  624. FOREACH_DLIST_ENTRY(ParseNodePtr, ArenaAllocator, pnodeFgnd, this->fastScannedRegExpNodes)
  625. {
  626. Assert(pnodeFgnd->nop == knopRegExp);
  627. Assert(pnodeFgnd->AsParseNodeRegExp()->regexPattern != nullptr);
  628. bool quit = false;
  629. while (!quit)
  630. {
  631. // Find the next work item with a RegEx in it.
  632. while (currBackgroundItem && currBackgroundItem->RegExpNodeList() == nullptr)
  633. {
  634. currBackgroundItem = currBackgroundItem->GetNext();
  635. }
  636. if (!currBackgroundItem)
  637. {
  638. break;
  639. }
  640. // Walk the RegExps in the work item.
  641. FOREACH_DLIST_ENTRY(ParseNodePtr, ArenaAllocator, pnodeBgnd, currBackgroundItem->RegExpNodeList())
  642. {
  643. Assert(pnodeBgnd->nop == knopRegExp);
  644. if (pnodeFgnd->ichMin <= pnodeBgnd->ichMin)
  645. {
  646. // Either we found a match, or the next background node is past the foreground node.
  647. // In any case, we can stop searching.
  648. if (pnodeFgnd->ichMin == pnodeBgnd->ichMin)
  649. {
  650. Assert(pnodeFgnd->ichLim == pnodeBgnd->ichLim);
  651. pnodeBgnd->AsParseNodeRegExp()->regexPattern = pnodeFgnd->AsParseNodeRegExp()->regexPattern;
  652. }
  653. quit = true;
  654. break;
  655. }
  656. }
  657. NEXT_DLIST_ENTRY;
  658. if (!quit)
  659. {
  660. // Need to advance to the next work item.
  661. currBackgroundItem = currBackgroundItem->GetNext();
  662. }
  663. }
  664. }
  665. NEXT_DLIST_ENTRY;
  666. #if DBG
  667. for (currBackgroundItem = this->backgroundParseItems;
  668. currBackgroundItem;
  669. currBackgroundItem = currBackgroundItem->GetNext())
  670. {
  671. if (currBackgroundItem->RegExpNodeList())
  672. {
  673. FOREACH_DLIST_ENTRY(ParseNodePtr, ArenaAllocator, pnode, currBackgroundItem->RegExpNodeList())
  674. {
  675. Assert(pnode->AsParseNodeRegExp()->regexPattern != nullptr);
  676. }
  677. NEXT_DLIST_ENTRY;
  678. }
  679. }
  680. #endif
  681. }
  682. #endif
  683. LabelId* Parser::CreateLabelId(IdentPtr pid)
  684. {
  685. LabelId* pLabelId;
  686. pLabelId = (LabelId*)m_nodeAllocator.Alloc(sizeof(LabelId));
  687. if (NULL == pLabelId)
  688. Error(ERRnoMemory);
  689. pLabelId->pid = pid;
  690. pLabelId->next = NULL;
  691. return pLabelId;
  692. }
  693. /*****************************************************************************
  694. The following set of routines allocate parse tree nodes of various kinds.
  695. They catch an exception on out of memory.
  696. *****************************************************************************/
  697. void
  698. Parser::AddAstSize(int size)
  699. {
  700. Assert(!this->m_deferringAST);
  701. Assert(m_pCurrentAstSize != NULL);
  702. *m_pCurrentAstSize += size;
  703. }
  704. void
  705. Parser::AddAstSizeAllowDefer(int size)
  706. {
  707. if (!this->m_deferringAST)
  708. {
  709. AddAstSize(size);
  710. }
  711. }
  712. // StaticCreate
  713. ParseNodeVar * Parser::StaticCreateTempNode(ParseNode* initExpr, ArenaAllocator * alloc)
  714. {
  715. ParseNodeVar * pnode = Anew(alloc, ParseNodeVar, knopTemp, 0, 0, nullptr);
  716. pnode->pnodeInit = initExpr;
  717. return pnode;
  718. }
  719. ParseNodeUni * Parser::StaticCreateTempRef(ParseNode* tempNode, ArenaAllocator * alloc)
  720. {
  721. return Anew(alloc, ParseNodeUni, knopTempRef, 0, 0, tempNode);
  722. }
  723. // Create Node with limit
  724. template <OpCode nop>
  725. typename OpCodeTrait<nop>::ParseNodeType * Parser::CreateNodeForOpT(charcount_t ichMin, charcount_t ichLim)
  726. {
  727. Assert(!this->m_deferringAST);
  728. typename OpCodeTrait<nop>::ParseNodeType * pnode = StaticCreateNodeT<nop>(&m_nodeAllocator, ichMin, ichLim);
  729. AddAstSize(sizeof(typename OpCodeTrait<nop>::ParseNodeType));
  730. return pnode;
  731. }
  732. template <OpCode nop>
  733. typename OpCodeTrait<nop>::ParseNodeType * Parser::CreateAllowDeferNodeForOpT(charcount_t ichMin, charcount_t ichLim)
  734. {
  735. CompileAssert(OpCodeTrait<nop>::AllowDefer);
  736. typename OpCodeTrait<nop>::ParseNodeType * pnode = StaticCreateNodeT<nop>(&m_nodeAllocator, ichMin, ichLim);
  737. AddAstSizeAllowDefer(sizeof(typename OpCodeTrait<nop>::ParseNodeType));
  738. return pnode;
  739. }
  740. #if DBG
  741. static const int g_mpnopcbNode[] =
  742. {
  743. #define PTNODE(nop,sn,pc,nk,ok,json) sizeof(ParseNode##nk),
  744. #include "ptlist.h"
  745. };
  746. void VerifyNodeSize(OpCode nop, int size)
  747. {
  748. Assert(nop >= 0 && nop < knopLim);
  749. __analysis_assume(nop < knopLim);
  750. Assert(g_mpnopcbNode[nop] == size);
  751. }
  752. #endif
  753. // Create ParseNodeUni
  754. ParseNodeUni * Parser::CreateUniNode(OpCode nop, ParseNodePtr pnode1)
  755. {
  756. charcount_t ichMin;
  757. charcount_t ichLim;
  758. if (nullptr == pnode1)
  759. {
  760. // no ops
  761. ichMin = this->GetScanner()->IchMinTok();
  762. ichLim = this->GetScanner()->IchLimTok();
  763. }
  764. else
  765. {
  766. // 1 op
  767. ichMin = pnode1->ichMin;
  768. ichLim = pnode1->ichLim;
  769. this->CheckArguments(pnode1);
  770. }
  771. return CreateUniNode(nop, pnode1, ichMin, ichLim);
  772. }
  773. ParseNodeUni * Parser::CreateUniNode(OpCode nop, ParseNodePtr pnode1, charcount_t ichMin, charcount_t ichLim)
  774. {
  775. Assert(!this->m_deferringAST);
  776. DebugOnly(VerifyNodeSize(nop, sizeof(ParseNodeUni)));
  777. ParseNodeUni * pnode = Anew(&m_nodeAllocator, ParseNodeUni, nop, ichMin, ichLim, pnode1);
  778. AddAstSize(sizeof(ParseNodeUni));
  779. return pnode;
  780. }
  781. // Create ParseNodeBin
  782. ParseNodeBin * Parser::StaticCreateBinNode(OpCode nop, ParseNodePtr pnode1, ParseNodePtr pnode2, ArenaAllocator* alloc, charcount_t ichMin, charcount_t ichLim)
  783. {
  784. DebugOnly(VerifyNodeSize(nop, sizeof(ParseNodeBin)));
  785. return Anew(alloc, ParseNodeBin, nop, ichMin, ichLim, pnode1, pnode2);
  786. }
  787. ParseNodeBin * Parser::CreateBinNode(OpCode nop, ParseNodePtr pnode1, ParseNodePtr pnode2)
  788. {
  789. Assert(!this->m_deferringAST);
  790. charcount_t ichMin;
  791. charcount_t ichLim;
  792. if (nullptr == pnode1)
  793. {
  794. // no ops
  795. Assert(nullptr == pnode2);
  796. ichMin = this->GetScanner()->IchMinTok();
  797. ichLim = this->GetScanner()->IchLimTok();
  798. }
  799. else
  800. {
  801. if (nullptr == pnode2)
  802. {
  803. // 1 op
  804. ichMin = pnode1->ichMin;
  805. ichLim = pnode1->ichLim;
  806. }
  807. else
  808. {
  809. // 2 ops
  810. ichMin = pnode1->ichMin;
  811. ichLim = pnode2->ichLim;
  812. if (nop != knopDot && nop != knopIndex)
  813. {
  814. this->CheckArguments(pnode2);
  815. }
  816. }
  817. if (nop != knopDot && nop != knopIndex)
  818. {
  819. this->CheckArguments(pnode1);
  820. }
  821. }
  822. return CreateBinNode(nop, pnode1, pnode2, ichMin, ichLim);
  823. }
  824. ParseNodeBin * Parser::CreateBinNode(OpCode nop, ParseNodePtr pnode1,
  825. ParseNodePtr pnode2, charcount_t ichMin, charcount_t ichLim)
  826. {
  827. Assert(!this->m_deferringAST);
  828. ParseNodeBin * pnode = StaticCreateBinNode(nop, pnode1, pnode2, &m_nodeAllocator, ichMin, ichLim);
  829. AddAstSize(sizeof(ParseNodeBin));
  830. return pnode;
  831. }
  832. // Create ParseNodeTri
  833. ParseNodeTri * Parser::CreateTriNode(OpCode nop, ParseNodePtr pnode1,
  834. ParseNodePtr pnode2, ParseNodePtr pnode3)
  835. {
  836. charcount_t ichMin;
  837. charcount_t ichLim;
  838. if (nullptr == pnode1)
  839. {
  840. // no ops
  841. Assert(nullptr == pnode2);
  842. Assert(nullptr == pnode3);
  843. ichMin = this->GetScanner()->IchMinTok();
  844. ichLim = this->GetScanner()->IchLimTok();
  845. }
  846. else if (nullptr == pnode2)
  847. {
  848. // 1 op
  849. Assert(nullptr == pnode3);
  850. ichMin = pnode1->ichMin;
  851. ichLim = pnode1->ichLim;
  852. }
  853. else if (nullptr == pnode3)
  854. {
  855. // 2 op
  856. ichMin = pnode1->ichMin;
  857. ichLim = pnode2->ichLim;
  858. }
  859. else
  860. {
  861. // 3 ops
  862. ichMin = pnode1->ichMin;
  863. ichLim = pnode3->ichLim;
  864. }
  865. return CreateTriNode(nop, pnode1, pnode2, pnode3, ichMin, ichLim);
  866. }
  867. ParseNodeTri * Parser::CreateTriNode(OpCode nop, ParseNodePtr pnode1,
  868. ParseNodePtr pnode2, ParseNodePtr pnode3,
  869. charcount_t ichMin, charcount_t ichLim)
  870. {
  871. Assert(!this->m_deferringAST);
  872. DebugOnly(VerifyNodeSize(nop, sizeof(ParseNodeTri)));
  873. ParseNodeTri * pnode = Anew(&m_nodeAllocator, ParseNodeTri, nop, ichMin, ichLim);
  874. AddAstSize(sizeof(ParseNodeTri));
  875. pnode->pnode1 = pnode1;
  876. pnode->pnode2 = pnode2;
  877. pnode->pnode3 = pnode3;
  878. return pnode;
  879. }
  880. // Create ParseNodeBlock
  881. ParseNodeBlock *
  882. Parser::StaticCreateBlockNode(ArenaAllocator* alloc, charcount_t ichMin, charcount_t ichLim, int blockId, PnodeBlockType blockType)
  883. {
  884. return Anew(alloc, ParseNodeBlock, ichMin, ichLim, blockId, blockType);
  885. }
  886. ParseNodeBlock * Parser::CreateBlockNode(PnodeBlockType blockType)
  887. {
  888. return CreateBlockNode(this->GetScanner()->IchMinTok(), this->GetScanner()->IchLimTok(), blockType);
  889. }
  890. ParseNodeBlock * Parser::CreateBlockNode(charcount_t ichMin, charcount_t ichLim, PnodeBlockType blockType)
  891. {
  892. Assert(OpCodeTrait<knopBlock>::AllowDefer);
  893. ParseNodeBlock * pnode = StaticCreateBlockNode(&m_nodeAllocator, ichMin, ichLim, this->m_nextBlockId++, blockType);
  894. AddAstSizeAllowDefer(sizeof(ParseNodeBlock));
  895. return pnode;
  896. }
  897. // Create ParseNodeVar
  898. ParseNodeVar * Parser::CreateDeclNode(OpCode nop, IdentPtr pid, SymbolType symbolType, bool errorOnRedecl)
  899. {
  900. Assert(nop == knopVarDecl || nop == knopLetDecl || nop == knopConstDecl);
  901. ParseNodeVar * pnode = Anew(&m_nodeAllocator, ParseNodeVar, nop, this->GetScanner()->IchMinTok(), this->GetScanner()->IchLimTok(), pid);
  902. if (symbolType != STUnknown)
  903. {
  904. pnode->sym = AddDeclForPid(pnode, pid, symbolType, errorOnRedecl);
  905. }
  906. return pnode;
  907. }
  908. ParseNodeInt * Parser::CreateIntNode(int32 lw)
  909. {
  910. Assert(!this->m_deferringAST);
  911. ParseNodeInt * pnode = Anew(&m_nodeAllocator, ParseNodeInt, this->GetScanner()->IchMinTok(), this->GetScanner()->IchLimTok(), lw);
  912. AddAstSize(sizeof(ParseNodeInt));
  913. return pnode;
  914. }
  915. ParseNodeStr * Parser::CreateStrNode(IdentPtr pid)
  916. {
  917. Assert(!this->m_deferringAST);
  918. ParseNodeStr * pnode = Anew(&m_nodeAllocator, ParseNodeStr, this->GetScanner()->IchMinTok(), this->GetScanner()->IchLimTok(), pid);
  919. pnode->grfpn |= PNodeFlags::fpnCanFlattenConcatExpr;
  920. AddAstSize(sizeof(ParseNodeStr));
  921. return pnode;
  922. }
  923. ParseNodeBigInt * Parser::CreateBigIntNode(IdentPtr pid)
  924. {
  925. Assert(!this->m_deferringAST);
  926. ParseNodeBigInt * pnode = Anew(&m_nodeAllocator, ParseNodeBigInt, this->GetScanner()->IchMinTok(), this->GetScanner()->IchLimTok(), pid);
  927. pnode->isNegative = false;
  928. AddAstSize(sizeof(ParseNodeBigInt));
  929. return pnode;
  930. }
  931. ParseNodeName * Parser::CreateNameNode(IdentPtr pid)
  932. {
  933. ParseNodeName * pnode = Anew(&m_nodeAllocator, ParseNodeName, this->GetScanner()->IchMinTok(), this->GetScanner()->IchLimTok(), pid);
  934. AddAstSizeAllowDefer(sizeof(ParseNodeName));
  935. return pnode;
  936. }
  937. ParseNodeName * Parser::CreateNameNode(IdentPtr pid, PidRefStack * ref, charcount_t ichMin, charcount_t ichLim)
  938. {
  939. ParseNodeName * pnode = Anew(&m_nodeAllocator, ParseNodeName, ichMin, ichLim, pid);
  940. pnode->SetSymRef(ref);
  941. AddAstSize(sizeof(ParseNodeName));
  942. return pnode;
  943. }
  944. ParseNodeSpecialName * Parser::CreateSpecialNameNode(IdentPtr pid, PidRefStack * ref, charcount_t ichMin, charcount_t ichLim)
  945. {
  946. Assert(!this->m_deferringAST);
  947. ParseNodeSpecialName * pnode = Anew(&m_nodeAllocator, ParseNodeSpecialName, ichMin, ichLim, pid);
  948. pnode->SetSymRef(ref);
  949. if (pid == wellKnownPropertyPids._this)
  950. {
  951. pnode->isThis = true;
  952. }
  953. else if (pid == wellKnownPropertyPids._super || pid == wellKnownPropertyPids._superConstructor)
  954. {
  955. pnode->isSuper = true;
  956. }
  957. AddAstSize(sizeof(ParseNodeSpecialName));
  958. return pnode;
  959. }
  960. ParseNodeSuperReference * Parser::CreateSuperReferenceNode(OpCode nop, ParseNodeSpecialName * pnode1, ParseNodePtr pnode2)
  961. {
  962. Assert(!this->m_deferringAST);
  963. Assert(pnode1 && pnode1->isSuper);
  964. Assert(pnode2 != nullptr);
  965. Assert(nop == knopDot || nop == knopIndex);
  966. ParseNodeSuperReference * pnode = Anew(&m_nodeAllocator, ParseNodeSuperReference, nop, pnode1->ichMin, pnode2->ichLim, pnode1, pnode2);
  967. AddAstSize(sizeof(ParseNodeSuperReference));
  968. return pnode;
  969. }
  970. ParseNodeProg * Parser::CreateProgNode(bool isModuleSource, ULONG lineNumber)
  971. {
  972. ParseNodeProg * pnodeProg;
  973. if (isModuleSource)
  974. {
  975. pnodeProg = CreateNodeForOpT<knopModule>();
  976. // knopModule is not actually handled anywhere since we would need to handle it everywhere we could
  977. // have knopProg and it would be treated exactly the same except for import/export statements.
  978. // We are only using it as a way to get the correct size for PnModule.
  979. // Consider: Should we add a flag to PnProg which is false but set to true in PnModule?
  980. // If we do, it can't be a virtual method since the parse nodes are all in a union.
  981. pnodeProg->nop = knopProg;
  982. }
  983. else
  984. {
  985. pnodeProg = CreateNodeForOpT<knopProg>();
  986. }
  987. pnodeProg->cbMin = this->GetScanner()->IecpMinTok();
  988. pnodeProg->cbStringMin = pnodeProg->cbMin;
  989. pnodeProg->cbStringLim = pnodeProg->cbLim;
  990. pnodeProg->lineNumber = lineNumber;
  991. pnodeProg->homeObjLocation = Js::Constants::NoRegister;
  992. pnodeProg->superRestrictionState = SuperRestrictionState::Disallowed;
  993. return pnodeProg;
  994. }
  995. ParseNodeCall * Parser::CreateCallNode(OpCode nop, ParseNodePtr pnode1, ParseNodePtr pnode2)
  996. {
  997. charcount_t ichMin;
  998. charcount_t ichLim;
  999. if (nullptr == pnode1)
  1000. {
  1001. Assert(nullptr == pnode2);
  1002. ichMin = this->GetScanner()->IchMinTok();
  1003. ichLim = this->GetScanner()->IchLimTok();
  1004. }
  1005. else
  1006. {
  1007. ichMin = pnode1->ichMin;
  1008. ichLim = pnode2 == nullptr ? pnode1->ichLim : pnode2->ichLim;
  1009. if (pnode1->nop == knopDot || pnode1->nop == knopIndex)
  1010. {
  1011. this->CheckArguments(pnode1->AsParseNodeBin()->pnode1);
  1012. }
  1013. }
  1014. return CreateCallNode(nop, pnode1, pnode2, ichMin, ichLim);
  1015. }
  1016. ParseNodeCall * Parser::CreateCallNode(OpCode nop, ParseNodePtr pnode1, ParseNodePtr pnode2, charcount_t ichMin, charcount_t ichLim)
  1017. {
  1018. Assert(!this->m_deferringAST);
  1019. // Classes, derived from ParseNodeCall, can be created here as well,
  1020. // as long as their size matches kcbPnCall (that is, they don't add
  1021. // any data members of their own).
  1022. DebugOnly(VerifyNodeSize(nop, sizeof(ParseNodeCall)));
  1023. ParseNodeCall* pnode = Anew(&m_nodeAllocator, ParseNodeCall, nop, ichMin, ichLim, pnode1, pnode2);
  1024. AddAstSize(sizeof(ParseNodeCall));
  1025. return pnode;
  1026. }
  1027. ParseNodeSuperCall * Parser::CreateSuperCallNode(ParseNodeSpecialName * pnode1, ParseNodePtr pnode2)
  1028. {
  1029. Assert(!this->m_deferringAST);
  1030. Assert(pnode1 && pnode1->isSuper);
  1031. ParseNodeSuperCall* pnode = Anew(&m_nodeAllocator, ParseNodeSuperCall, knopCall, pnode1->ichMin, pnode2 == nullptr ? pnode1->ichLim : pnode2->ichLim, pnode1, pnode2);
  1032. AddAstSize(sizeof(ParseNodeSuperCall));
  1033. return pnode;
  1034. }
  1035. ParseNodeParamPattern * Parser::CreateParamPatternNode(ParseNode * pnode1)
  1036. {
  1037. ParseNodeParamPattern * paramPatternNode = CreateNodeForOpT<knopParamPattern>(pnode1->ichMin, pnode1->ichLim);
  1038. paramPatternNode->pnode1 = pnode1;
  1039. paramPatternNode->pnodeNext = nullptr;
  1040. paramPatternNode->location = Js::Constants::NoRegister;
  1041. return paramPatternNode;
  1042. }
  1043. ParseNodeParamPattern * Parser::CreateDummyParamPatternNode(charcount_t ichMin)
  1044. {
  1045. ParseNodeParamPattern * paramPatternNode = CreateNodeForOpT<knopParamPattern>(ichMin);
  1046. paramPatternNode->pnode1 = nullptr;
  1047. paramPatternNode->pnodeNext = nullptr;
  1048. paramPatternNode->location = Js::Constants::NoRegister;
  1049. return paramPatternNode;
  1050. }
  1051. ParseNodeObjLit * Parser::CreateObjectPatternNode(ParseNodePtr pnodeMemberList, charcount_t ichMin, charcount_t ichLim, bool convertToPattern) {
  1052. // Count the number of non-rest members in the object
  1053. uint32 staticCount = 0;
  1054. uint32 computedCount = 0;
  1055. bool hasRest = false;
  1056. ParseNodePtr pnodeMemberNodeList = convertToPattern ? nullptr : pnodeMemberList;
  1057. if (pnodeMemberList != nullptr)
  1058. {
  1059. Assert(pnodeMemberList->nop == knopList ||
  1060. (!convertToPattern && pnodeMemberList->nop == knopObjectPatternMember) ||
  1061. convertToPattern ||
  1062. pnodeMemberList->nop == knopEllipsis);
  1063. ForEachItemInList(pnodeMemberList, [&](ParseNodePtr item) {
  1064. ParseNodePtr memberNode = convertToPattern ? ConvertMemberToMemberPattern(item) : item;
  1065. if (convertToPattern)
  1066. {
  1067. AppendToList(&pnodeMemberNodeList, memberNode);
  1068. }
  1069. if (memberNode->nop != knopEllipsis)
  1070. {
  1071. ParseNodePtr nameNode = memberNode->AsParseNodeBin()->pnode1;
  1072. Assert(nameNode->nop == knopComputedName || nameNode->nop == knopStr);
  1073. if (nameNode->nop == knopComputedName)
  1074. {
  1075. computedCount++;
  1076. }
  1077. else
  1078. {
  1079. staticCount++;
  1080. }
  1081. }
  1082. else
  1083. {
  1084. hasRest = true;
  1085. }
  1086. });
  1087. }
  1088. ParseNodeObjLit * objectPatternNode = CreateNodeForOpT<knopObjectPattern>(ichMin, ichLim);
  1089. objectPatternNode->pnode1 = pnodeMemberNodeList;
  1090. objectPatternNode->computedCount = computedCount;
  1091. objectPatternNode->staticCount = staticCount;
  1092. objectPatternNode->hasRest = hasRest;
  1093. return objectPatternNode;
  1094. }
  1095. Symbol* Parser::AddDeclForPid(ParseNodeVar * pnodeVar, IdentPtr pid, SymbolType symbolType, bool errorOnRedecl)
  1096. {
  1097. Assert(pnodeVar->IsVarLetOrConst());
  1098. PidRefStack *refForUse = nullptr, *refForDecl = nullptr;
  1099. BlockInfoStack *blockInfo;
  1100. bool fBlockScope = false;
  1101. if (pnodeVar->nop != knopVarDecl || symbolType == STFunction)
  1102. {
  1103. Assert(m_pstmtCur);
  1104. if (m_pstmtCur->GetNop() != knopBlock)
  1105. {
  1106. // Let/const declared in a bare statement context.
  1107. Error(ERRDeclOutOfStmt);
  1108. }
  1109. if (m_pstmtCur->pstmtOuter && m_pstmtCur->pstmtOuter->GetNop() == knopSwitch)
  1110. {
  1111. // Let/const declared inside a switch block (requiring conservative use-before-decl check).
  1112. pnodeVar->isSwitchStmtDecl = true;
  1113. }
  1114. fBlockScope = pnodeVar->nop != knopVarDecl ||
  1115. (
  1116. !GetCurrentBlockInfo()->pnodeBlock->scope ||
  1117. GetCurrentBlockInfo()->pnodeBlock->scope->GetScopeType() != ScopeType_GlobalEvalBlock
  1118. );
  1119. }
  1120. if (fBlockScope)
  1121. {
  1122. blockInfo = GetCurrentBlockInfo();
  1123. }
  1124. else
  1125. {
  1126. blockInfo = GetCurrentFunctionBlockInfo();
  1127. }
  1128. refForDecl = this->FindOrAddPidRef(pid, blockInfo->pnodeBlock->blockId, GetCurrentFunctionNode()->functionId);
  1129. if (refForDecl == nullptr)
  1130. {
  1131. Error(ERRnoMemory);
  1132. }
  1133. if (refForDecl->funcId != GetCurrentFunctionNode()->functionId)
  1134. {
  1135. // Fix up the function id, which is incorrect if we're reparsing lambda parameters
  1136. Assert(this->m_reparsingLambdaParams);
  1137. refForDecl->funcId = GetCurrentFunctionNode()->functionId;
  1138. }
  1139. if (blockInfo == GetCurrentBlockInfo())
  1140. {
  1141. refForUse = refForDecl;
  1142. }
  1143. else
  1144. {
  1145. refForUse = this->PushPidRef(pid);
  1146. }
  1147. pnodeVar->symRef = refForUse->GetSymRef();
  1148. Symbol *sym = refForDecl->GetSym();
  1149. if (sym != nullptr)
  1150. {
  1151. // Multiple declarations in the same scope. 3 possibilities: error, existing one wins, new one wins.
  1152. switch (pnodeVar->nop)
  1153. {
  1154. case knopLetDecl:
  1155. case knopConstDecl:
  1156. if (!sym->GetDecl()->AsParseNodeVar()->isBlockScopeFncDeclVar && !sym->IsArguments())
  1157. {
  1158. // If the built-in arguments is shadowed then don't throw
  1159. Assert(errorOnRedecl);
  1160. // Redeclaration error.
  1161. Error(ERRRedeclaration);
  1162. }
  1163. else
  1164. {
  1165. // (New) let/const hides the (old) var
  1166. sym->SetSymbolType(symbolType);
  1167. sym->SetDecl(pnodeVar);
  1168. }
  1169. break;
  1170. case knopVarDecl:
  1171. if (m_currentScope->GetScopeType() == ScopeType_Parameter && !sym->IsArguments())
  1172. {
  1173. // If this is a parameter list, mark the scope to indicate that it has duplicate definition unless it is shadowing the default arguments symbol.
  1174. // 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.
  1175. m_currentScope->SetHasDuplicateFormals();
  1176. }
  1177. if (sym->GetDecl() == nullptr)
  1178. {
  1179. sym->SetDecl(pnodeVar);
  1180. break;
  1181. }
  1182. switch (sym->GetDecl()->nop)
  1183. {
  1184. case knopLetDecl:
  1185. case knopConstDecl:
  1186. // Destructuring made possible to have the formals to be the let bind. But that shouldn't throw the error.
  1187. if (errorOnRedecl && (!IsES6DestructuringEnabled() || sym->GetSymbolType() != STFormal))
  1188. {
  1189. Error(ERRRedeclaration);
  1190. }
  1191. // If !errorOnRedecl, (old) let/const hides the (new) var, so do nothing.
  1192. break;
  1193. case knopVarDecl:
  1194. // Legal redeclaration. Who wins?
  1195. if (errorOnRedecl || sym->GetDecl()->AsParseNodeVar()->isBlockScopeFncDeclVar || sym->IsArguments())
  1196. {
  1197. if (symbolType == STFormal ||
  1198. (symbolType == STFunction && sym->GetSymbolType() != STFormal) ||
  1199. sym->GetSymbolType() == STVariable)
  1200. {
  1201. // New decl wins.
  1202. sym->SetSymbolType(symbolType);
  1203. sym->SetDecl(pnodeVar);
  1204. }
  1205. }
  1206. break;
  1207. }
  1208. break;
  1209. }
  1210. }
  1211. else
  1212. {
  1213. Scope *scope = blockInfo->pnodeBlock->scope;
  1214. if (scope == nullptr)
  1215. {
  1216. Assert(blockInfo->pnodeBlock->blockType == PnodeBlockType::Regular);
  1217. scope = Anew(&m_nodeAllocator, Scope, &m_nodeAllocator, ScopeType_Block);
  1218. if (this->IsCurBlockInLoop())
  1219. {
  1220. scope->SetIsBlockInLoop();
  1221. }
  1222. blockInfo->pnodeBlock->scope = scope;
  1223. PushScope(scope);
  1224. }
  1225. ParseNodeFnc * pnodeFnc = GetCurrentFunctionNode();
  1226. if (scope->GetScopeType() == ScopeType_GlobalEvalBlock)
  1227. {
  1228. Assert(fBlockScope);
  1229. Assert(scope->GetEnclosingScope() == m_currentNodeProg->scope);
  1230. // Check for same-named decl in Global scope.
  1231. CheckRedeclarationErrorForBlockId(pid, 0);
  1232. }
  1233. else if (scope->GetScopeType() == ScopeType_Global && (this->m_grfscr & fscrEvalCode) &&
  1234. !(m_functionBody && m_functionBody->GetScopeInfo()))
  1235. {
  1236. // Check for same-named decl in GlobalEvalBlock scope. Note that this is not necessary
  1237. // if we're compiling a deferred nested function and the global scope was restored from cached info,
  1238. // because in that case we don't need a GlobalEvalScope.
  1239. Assert(!fBlockScope || (this->m_grfscr & fscrConsoleScopeEval) == fscrConsoleScopeEval);
  1240. CheckRedeclarationErrorForBlockId(pid, 1);
  1241. }
  1242. else if (!pnodeFnc->IsBodyAndParamScopeMerged()
  1243. && scope->GetScopeType() == ScopeType_FunctionBody
  1244. && (pnodeVar->nop == knopLetDecl || pnodeVar->nop == knopConstDecl))
  1245. {
  1246. // In case of split scope function when we add a new let or const declaration to the body
  1247. // we have to check whether the param scope already has the same symbol defined.
  1248. CheckRedeclarationErrorForBlockId(pid, pnodeFnc->pnodeScopes->blockId);
  1249. }
  1250. if (!sym)
  1251. {
  1252. const char16 *name = reinterpret_cast<const char16*>(pid->Psz());
  1253. int nameLength = pid->Cch();
  1254. SymbolName const symName(name, nameLength);
  1255. Assert(!scope->FindLocalSymbol(symName));
  1256. sym = Anew(&m_nodeAllocator, Symbol, symName, pnodeVar, symbolType);
  1257. scope->AddNewSymbol(sym);
  1258. sym->SetPid(pid);
  1259. }
  1260. refForDecl->SetSym(sym);
  1261. }
  1262. return sym;
  1263. }
  1264. void Parser::CheckRedeclarationErrorForBlockId(IdentPtr pid, int blockId)
  1265. {
  1266. // If the ref stack entry for the blockId contains a sym then throw redeclaration error
  1267. PidRefStack *pidRefOld = pid->GetPidRefForScopeId(blockId);
  1268. if (pidRefOld && pidRefOld->GetSym() && !pidRefOld->GetSym()->IsArguments())
  1269. {
  1270. Error(ERRRedeclaration);
  1271. }
  1272. }
  1273. bool Parser::IsCurBlockInLoop() const
  1274. {
  1275. for (StmtNest *stmt = this->m_pstmtCur; stmt != nullptr; stmt = stmt->pstmtOuter)
  1276. {
  1277. OpCode nop = stmt->GetNop();
  1278. if (ParseNode::Grfnop(nop) & fnopContinue)
  1279. {
  1280. return true;
  1281. }
  1282. if (nop == knopFncDecl)
  1283. {
  1284. return false;
  1285. }
  1286. }
  1287. return false;
  1288. }
  1289. void Parser::RestorePidRefForSym(Symbol *sym)
  1290. {
  1291. IdentPtr pid = this->GetHashTbl()->PidHashNameLen(sym->GetName().GetBuffer(), sym->GetName().GetLength());
  1292. Assert(pid);
  1293. sym->SetPid(pid);
  1294. PidRefStack *ref = this->PushPidRef(pid);
  1295. ref->SetSym(sym);
  1296. }
  1297. void Parser::CheckPidIsValid(IdentPtr pid, bool autoArgumentsObject)
  1298. {
  1299. if (IsStrictMode())
  1300. {
  1301. // in strict mode, variable named 'eval' cannot be created
  1302. if (pid == wellKnownPropertyPids.eval)
  1303. {
  1304. Error(ERREvalUsage);
  1305. }
  1306. else if (pid == wellKnownPropertyPids.arguments && !autoArgumentsObject)
  1307. {
  1308. Error(ERRArgsUsage);
  1309. }
  1310. }
  1311. }
  1312. // CreateVarDecl needs m_ppnodeVar to be pointing to the right function.
  1313. // Post-parsing rewriting during bytecode gen may have m_ppnodeVar pointing to the last parsed function.
  1314. // This function sets up m_ppnodeVar to point to the given pnodeFnc and creates the new var declaration.
  1315. // This prevents accidentally adding var declarations to the last parsed function.
  1316. ParseNodeVar * Parser::AddVarDeclNode(IdentPtr pid, ParseNodeFnc * pnodeFnc)
  1317. {
  1318. AnalysisAssert(pnodeFnc);
  1319. ParseNodePtr *const ppnodeVarSave = m_ppnodeVar;
  1320. m_ppnodeVar = &pnodeFnc->pnodeVars;
  1321. while (*m_ppnodeVar != nullptr)
  1322. {
  1323. m_ppnodeVar = &(*m_ppnodeVar)->AsParseNodeVar()->pnodeNext;
  1324. }
  1325. ParseNodeVar * pnode = CreateVarDeclNode(pid, STUnknown, false, 0, /* checkReDecl = */ false);
  1326. m_ppnodeVar = ppnodeVarSave;
  1327. return pnode;
  1328. }
  1329. ParseNodeVar * Parser::CreateModuleImportDeclNode(IdentPtr localName)
  1330. {
  1331. ParseNodeVar * declNode = CreateBlockScopedDeclNode(localName, knopConstDecl);
  1332. Symbol* sym = declNode->sym;
  1333. sym->SetIsModuleExportStorage(true);
  1334. sym->SetIsModuleImport(true);
  1335. return declNode;
  1336. }
  1337. ParseNodeVar * Parser::CreateVarDeclNode(IdentPtr pid, SymbolType symbolType, bool autoArgumentsObject, ParseNodePtr pnodeFnc, bool errorOnRedecl)
  1338. {
  1339. ParseNodeVar * pnode = CreateDeclNode(knopVarDecl, pid, symbolType, errorOnRedecl);
  1340. // Append the variable to the end of the current variable list.
  1341. Assert(m_ppnodeVar);
  1342. pnode->pnodeNext = *m_ppnodeVar;
  1343. *m_ppnodeVar = pnode;
  1344. if (nullptr != pid)
  1345. {
  1346. // this is not a temp - make sure temps go after this node
  1347. Assert(pid);
  1348. m_ppnodeVar = &pnode->pnodeNext;
  1349. CheckPidIsValid(pid, autoArgumentsObject);
  1350. }
  1351. return pnode;
  1352. }
  1353. ParseNodeVar * Parser::CreateBlockScopedDeclNode(IdentPtr pid, OpCode nodeType)
  1354. {
  1355. Assert(nodeType == knopConstDecl || nodeType == knopLetDecl);
  1356. ParseNodeVar * pnode = CreateDeclNode(nodeType, pid, STVariable, true);
  1357. if (nullptr != pid)
  1358. {
  1359. Assert(pid);
  1360. AddVarDeclToBlock(pnode);
  1361. CheckPidIsValid(pid);
  1362. }
  1363. return pnode;
  1364. }
  1365. void Parser::AddVarDeclToBlock(ParseNodeVar *pnode)
  1366. {
  1367. Assert(pnode->nop == knopConstDecl || pnode->nop == knopLetDecl);
  1368. // Maintain a combined list of let and const declarations to keep
  1369. // track of declaration order.
  1370. Assert(m_currentBlockInfo->m_ppnodeLex);
  1371. *m_currentBlockInfo->m_ppnodeLex = pnode;
  1372. m_currentBlockInfo->m_ppnodeLex = &pnode->pnodeNext;
  1373. pnode->pnodeNext = nullptr;
  1374. }
  1375. void Parser::SetCurrentStatement(StmtNest *stmt)
  1376. {
  1377. m_pstmtCur = stmt;
  1378. }
  1379. template<bool buildAST>
  1380. ParseNodeBlock * Parser::StartParseBlockWithCapacity(PnodeBlockType blockType, ScopeType scopeType, int capacity)
  1381. {
  1382. Scope *scope = nullptr;
  1383. // Block scopes are not created lazily in the case where we're repopulating a persisted scope.
  1384. scope = Anew(&m_nodeAllocator, Scope, &m_nodeAllocator, scopeType, capacity);
  1385. PushScope(scope);
  1386. return StartParseBlockHelper<buildAST>(blockType, scope, nullptr);
  1387. }
  1388. template<bool buildAST>
  1389. ParseNodeBlock * Parser::StartParseBlock(PnodeBlockType blockType, ScopeType scopeType, LabelId* pLabelId)
  1390. {
  1391. Scope *scope = nullptr;
  1392. // Block scopes are created lazily when we discover block-scoped content.
  1393. if (scopeType != ScopeType_Unknown && scopeType != ScopeType_Block)
  1394. {
  1395. scope = Anew(&m_nodeAllocator, Scope, &m_nodeAllocator, scopeType);
  1396. PushScope(scope);
  1397. }
  1398. return StartParseBlockHelper<buildAST>(blockType, scope, pLabelId);
  1399. }
  1400. template<bool buildAST>
  1401. ParseNodeBlock * Parser::StartParseBlockHelper(PnodeBlockType blockType, Scope *scope, LabelId* pLabelId)
  1402. {
  1403. ParseNodeBlock * pnodeBlock = CreateBlockNode(blockType);
  1404. pnodeBlock->scope = scope;
  1405. BlockInfoStack *newBlockInfo = PushBlockInfo(pnodeBlock);
  1406. PushStmt<buildAST>(&newBlockInfo->pstmt, pnodeBlock, knopBlock, pLabelId);
  1407. return pnodeBlock;
  1408. }
  1409. void Parser::PushScope(Scope *scope)
  1410. {
  1411. Assert(scope);
  1412. scope->SetEnclosingScope(m_currentScope);
  1413. m_currentScope = scope;
  1414. }
  1415. void Parser::PopScope(Scope *scope)
  1416. {
  1417. Assert(scope == m_currentScope);
  1418. m_currentScope = scope->GetEnclosingScope();
  1419. scope->SetEnclosingScope(nullptr);
  1420. }
  1421. void Parser::PushFuncBlockScope(ParseNodeBlock * pnodeBlock, ParseNodePtr **ppnodeScopeSave, ParseNodePtr **ppnodeExprScopeSave)
  1422. {
  1423. // Maintain the scope tree.
  1424. pnodeBlock->pnodeScopes = nullptr;
  1425. pnodeBlock->pnodeNext = nullptr;
  1426. // Insert this block into the active list of scopes (m_ppnodeExprScope or m_ppnodeScope).
  1427. // Save the current block's "next" pointer as the new endpoint of that list.
  1428. if (m_ppnodeExprScope)
  1429. {
  1430. *ppnodeScopeSave = m_ppnodeScope;
  1431. Assert(*m_ppnodeExprScope == nullptr);
  1432. *m_ppnodeExprScope = pnodeBlock;
  1433. *ppnodeExprScopeSave = &pnodeBlock->pnodeNext;
  1434. }
  1435. else
  1436. {
  1437. Assert(m_ppnodeScope);
  1438. Assert(*m_ppnodeScope == nullptr);
  1439. *m_ppnodeScope = pnodeBlock;
  1440. *ppnodeScopeSave = &pnodeBlock->pnodeNext;
  1441. *ppnodeExprScopeSave = m_ppnodeExprScope;
  1442. }
  1443. // Advance the global scope list pointer to the new block's child list.
  1444. m_ppnodeScope = &pnodeBlock->pnodeScopes;
  1445. // Set m_ppnodeExprScope to NULL to make that list inactive.
  1446. m_ppnodeExprScope = nullptr;
  1447. }
  1448. void Parser::PopFuncBlockScope(ParseNodePtr *ppnodeScopeSave, ParseNodePtr *ppnodeExprScopeSave)
  1449. {
  1450. Assert(m_ppnodeExprScope == nullptr || *m_ppnodeExprScope == nullptr);
  1451. m_ppnodeExprScope = ppnodeExprScopeSave;
  1452. Assert(m_ppnodeScope);
  1453. Assert(nullptr == *m_ppnodeScope);
  1454. m_ppnodeScope = ppnodeScopeSave;
  1455. }
  1456. template<bool buildAST>
  1457. ParseNodeBlock * Parser::ParseBlock(LabelId* pLabelId)
  1458. {
  1459. ParseNodeBlock * pnodeBlock = nullptr;
  1460. ParseNodePtr *ppnodeScopeSave = nullptr;
  1461. ParseNodePtr *ppnodeExprScopeSave = nullptr;
  1462. pnodeBlock = StartParseBlock<buildAST>(PnodeBlockType::Regular, ScopeType_Block, pLabelId);
  1463. BlockInfoStack* outerBlockInfo = m_currentBlockInfo->pBlockInfoOuter;
  1464. if (outerBlockInfo != nullptr && outerBlockInfo->pnodeBlock != nullptr
  1465. && outerBlockInfo->pnodeBlock->scope != nullptr
  1466. && outerBlockInfo->pnodeBlock->scope->GetScopeType() == ScopeType_CatchParamPattern)
  1467. {
  1468. // If we are parsing the catch block then destructured params can have let declarations. Let's add them to the new block.
  1469. for (ParseNodePtr pnode = m_currentBlockInfo->pBlockInfoOuter->pnodeBlock->pnodeLexVars; pnode; pnode = pnode->AsParseNodeVar()->pnodeNext)
  1470. {
  1471. PidRefStack* ref = PushPidRef(pnode->AsParseNodeVar()->sym->GetPid());
  1472. ref->SetSym(pnode->AsParseNodeVar()->sym);
  1473. }
  1474. }
  1475. ChkCurTok(tkLCurly, ERRnoLcurly);
  1476. ParseNodePtr * ppnodeList = nullptr;
  1477. if (buildAST)
  1478. {
  1479. PushFuncBlockScope(pnodeBlock, &ppnodeScopeSave, &ppnodeExprScopeSave);
  1480. ppnodeList = &pnodeBlock->pnodeStmt;
  1481. }
  1482. ParseStmtList<buildAST>(ppnodeList);
  1483. if (buildAST)
  1484. {
  1485. PopFuncBlockScope(ppnodeScopeSave, ppnodeExprScopeSave);
  1486. }
  1487. FinishParseBlock(pnodeBlock);
  1488. ChkCurTok(tkRCurly, ERRnoRcurly);
  1489. return pnodeBlock;
  1490. }
  1491. bool Parser::IsSpecialName(IdentPtr pid)
  1492. {
  1493. return pid == wellKnownPropertyPids._this ||
  1494. pid == wellKnownPropertyPids._super ||
  1495. pid == wellKnownPropertyPids._superConstructor ||
  1496. pid == wellKnownPropertyPids._newTarget ||
  1497. pid == wellKnownPropertyPids._importMeta;
  1498. }
  1499. ParseNodeSpecialName * Parser::ReferenceSpecialName(IdentPtr pid, charcount_t ichMin, charcount_t ichLim, bool createNode)
  1500. {
  1501. PidRefStack* ref = this->PushPidRef(pid);
  1502. if (!createNode)
  1503. {
  1504. return nullptr;
  1505. }
  1506. return CreateSpecialNameNode(pid, ref, ichMin, ichLim);
  1507. }
  1508. ParseNodeVar * Parser::CreateSpecialVarDeclIfNeeded(ParseNodeFnc * pnodeFnc, IdentPtr pid, bool forceCreate)
  1509. {
  1510. Assert(pid != nullptr);
  1511. PidRefStack* ref = pid->GetTopRef();
  1512. // If the function has a reference to pid or we set forceCreate, make a special var decl
  1513. if (forceCreate || (ref && (ref->GetScopeId() >= m_currentBlockInfo->pnodeBlock->blockId && ref->GetFuncScopeId() >= pnodeFnc->functionId)))
  1514. {
  1515. return this->CreateSpecialVarDeclNode(pnodeFnc, pid);
  1516. }
  1517. return nullptr;
  1518. }
  1519. void Parser::CreateSpecialSymbolDeclarations(ParseNodeFnc * pnodeFnc)
  1520. {
  1521. // Lambda function cannot have any special bindings.
  1522. if (pnodeFnc->IsLambda())
  1523. {
  1524. return;
  1525. }
  1526. bool isTopLevelEventHandler = (this->m_grfscr & fscrImplicitThis) && !pnodeFnc->IsNested();
  1527. // Create a 'this' symbol for non-lambda functions with references to 'this', and all class constructors and top level event hanlders.
  1528. ParseNodePtr varDeclNode = CreateSpecialVarDeclIfNeeded(pnodeFnc, wellKnownPropertyPids._this, pnodeFnc->IsClassConstructor() || isTopLevelEventHandler);
  1529. if (varDeclNode)
  1530. {
  1531. varDeclNode->AsParseNodeVar()->sym->SetIsThis(true);
  1532. if (pnodeFnc->IsDerivedClassConstructor())
  1533. {
  1534. varDeclNode->AsParseNodeVar()->sym->SetNeedDeclaration(true);
  1535. }
  1536. }
  1537. // Create a 'new.target' symbol for any ordinary function with a reference and all class constructors.
  1538. varDeclNode = CreateSpecialVarDeclIfNeeded(pnodeFnc, wellKnownPropertyPids._newTarget, pnodeFnc->IsClassConstructor());
  1539. if (varDeclNode)
  1540. {
  1541. varDeclNode->AsParseNodeVar()->sym->SetIsNewTarget(true);
  1542. }
  1543. // Create a 'import.meta' symbol.
  1544. varDeclNode = CreateSpecialVarDeclIfNeeded(pnodeFnc, wellKnownPropertyPids._importMeta);
  1545. if (varDeclNode)
  1546. {
  1547. varDeclNode->AsParseNodeVar()->sym->SetIsImportMeta(true);
  1548. }
  1549. // Create a 'super' (as a reference) symbol.
  1550. varDeclNode = CreateSpecialVarDeclIfNeeded(pnodeFnc, wellKnownPropertyPids._super);
  1551. if (varDeclNode)
  1552. {
  1553. varDeclNode->AsParseNodeVar()->sym->SetIsSuper(true);
  1554. }
  1555. // Create a 'super' (as the call target for super()) symbol only for derived class constructors.
  1556. varDeclNode = CreateSpecialVarDeclIfNeeded(pnodeFnc, wellKnownPropertyPids._superConstructor);
  1557. if (varDeclNode)
  1558. {
  1559. varDeclNode->AsParseNodeVar()->sym->SetIsSuperConstructor(true);
  1560. }
  1561. }
  1562. void Parser::FinishParseBlock(ParseNodeBlock *pnodeBlock, bool needScanRCurly)
  1563. {
  1564. Assert(m_currentBlockInfo != nullptr && pnodeBlock == m_currentBlockInfo->pnodeBlock);
  1565. if (needScanRCurly)
  1566. {
  1567. // Only update the ichLim if we were expecting an RCurly. If there is an
  1568. // expression body without a necessary RCurly, the correct ichLim will
  1569. // have been set already.
  1570. pnodeBlock->ichLim = this->GetScanner()->IchLimTok();
  1571. }
  1572. BindPidRefs<false>(GetCurrentBlockInfo(), m_nextBlockId - 1);
  1573. PopStmt(&m_currentBlockInfo->pstmt);
  1574. PopBlockInfo();
  1575. Scope *scope = pnodeBlock->scope;
  1576. if (scope)
  1577. {
  1578. PopScope(scope);
  1579. }
  1580. }
  1581. void Parser::FinishParseFncExprScope(ParseNodeFnc * pnodeFnc, ParseNodeBlock * pnodeFncExprScope)
  1582. {
  1583. int fncExprScopeId = pnodeFncExprScope->blockId;
  1584. ParseNodePtr pnodeName = pnodeFnc->pnodeName;
  1585. if (pnodeName)
  1586. {
  1587. Assert(pnodeName->nop == knopVarDecl);
  1588. BindPidRefsInScope(pnodeName->AsParseNodeVar()->pid, pnodeName->AsParseNodeVar()->sym, fncExprScopeId, m_nextBlockId - 1);
  1589. }
  1590. FinishParseBlock(pnodeFncExprScope);
  1591. }
  1592. template <const bool backgroundPidRef>
  1593. void Parser::BindPidRefs(BlockInfoStack *blockInfo, uint maxBlockId)
  1594. {
  1595. // We need to bind all assignments in order to emit assignment to 'const' error
  1596. int blockId = blockInfo->pnodeBlock->blockId;
  1597. Scope *scope = blockInfo->pnodeBlock->scope;
  1598. if (scope)
  1599. {
  1600. auto bindPidRefs = [blockId, maxBlockId, this](Symbol *sym)
  1601. {
  1602. ParseNodePtr pnode = sym->GetDecl();
  1603. IdentPtr pid;
  1604. #if PROFILE_DICTIONARY
  1605. int depth = 0;
  1606. #endif
  1607. Assert(pnode);
  1608. switch (pnode->nop)
  1609. {
  1610. case knopVarDecl:
  1611. case knopLetDecl:
  1612. case knopConstDecl:
  1613. pid = pnode->AsParseNodeVar()->pid;
  1614. if (backgroundPidRef)
  1615. {
  1616. pid = this->GetHashTbl()->FindExistingPid(pid->Psz(), pid->Psz() + pid->Cch(), pid->Cch(), pid->Hash(), nullptr, nullptr
  1617. #if PROFILE_DICTIONARY
  1618. , depth
  1619. #endif
  1620. );
  1621. if (pid == nullptr)
  1622. {
  1623. break;
  1624. }
  1625. }
  1626. this->BindPidRefsInScope(pid, sym, blockId, maxBlockId);
  1627. break;
  1628. case knopName:
  1629. pid = pnode->AsParseNodeName()->pid;
  1630. if (backgroundPidRef)
  1631. {
  1632. pid = this->GetHashTbl()->FindExistingPid(pid->Psz(), pid->Psz() + pid->Cch(), pid->Cch(), pid->Hash(), nullptr, nullptr
  1633. #if PROFILE_DICTIONARY
  1634. , depth
  1635. #endif
  1636. );
  1637. if (pid == nullptr)
  1638. {
  1639. break;
  1640. }
  1641. }
  1642. this->BindPidRefsInScope(pid, sym, blockId, maxBlockId);
  1643. break;
  1644. default:
  1645. Assert(0);
  1646. break;
  1647. }
  1648. };
  1649. scope->ForEachSymbol(bindPidRefs);
  1650. }
  1651. }
  1652. void Parser::BindPidRefsInScope(IdentPtr pid, Symbol *sym, int blockId, uint maxBlockId)
  1653. {
  1654. PidRefStack *ref, *nextRef, *lastRef = nullptr;
  1655. Js::LocalFunctionId funcId = GetCurrentFunctionNode()->functionId;
  1656. Assert(sym);
  1657. if (pid->GetIsModuleExport() && IsTopLevelModuleFunc())
  1658. {
  1659. sym->SetIsModuleExportStorage(true);
  1660. }
  1661. bool hasFuncAssignment = sym->GetHasFuncAssignment();
  1662. bool doesEscape = false;
  1663. for (ref = pid->GetTopRef(); ref && ref->GetScopeId() >= blockId; ref = nextRef)
  1664. {
  1665. // Fix up sym* on PID ref.
  1666. Assert(!ref->GetSym() || ref->GetSym() == sym);
  1667. nextRef = ref->prev;
  1668. Assert(ref->GetScopeId() >= 0);
  1669. if ((uint)ref->GetScopeId() > maxBlockId)
  1670. {
  1671. lastRef = ref;
  1672. continue;
  1673. }
  1674. ref->SetSym(sym);
  1675. this->RemovePrevPidRef(pid, lastRef);
  1676. if (ref->IsUsedInLdElem())
  1677. {
  1678. sym->SetIsUsedInLdElem(true);
  1679. }
  1680. if (ref->IsAssignment())
  1681. {
  1682. sym->PromoteAssignmentState();
  1683. if (sym->GetIsFormal())
  1684. {
  1685. GetCurrentFunctionNode()->SetHasAnyWriteToFormals(true);
  1686. }
  1687. }
  1688. if (ref->GetFuncScopeId() != funcId && !sym->GetIsGlobal() && !sym->GetIsModuleExportStorage())
  1689. {
  1690. Assert(ref->GetFuncScopeId() > funcId);
  1691. sym->SetHasNonLocalReference();
  1692. if (ref->IsDynamicBinding())
  1693. {
  1694. sym->SetNeedsScopeObject();
  1695. }
  1696. }
  1697. if (ref->IsFuncAssignment())
  1698. {
  1699. hasFuncAssignment = true;
  1700. }
  1701. if (ref->IsEscape())
  1702. {
  1703. doesEscape = true;
  1704. }
  1705. if (m_currentNodeFunc && doesEscape && hasFuncAssignment)
  1706. {
  1707. if (m_sourceContextInfo ?
  1708. !PHASE_OFF_RAW(Js::DisableStackFuncOnDeferredEscapePhase, m_sourceContextInfo->sourceContextId, m_currentNodeFunc->functionId) :
  1709. !PHASE_OFF1(Js::DisableStackFuncOnDeferredEscapePhase))
  1710. {
  1711. m_currentNodeFunc->SetNestedFuncEscapes();
  1712. }
  1713. }
  1714. if (m_currentNodeFunc && m_currentNodeFunc->pnodeName && pid == m_currentNodeFunc->pnodeName->pid && !m_currentNodeFunc->IsDeclaration() && m_currentNodeFunc->IsBodyAndParamScopeMerged())
  1715. {
  1716. Scope* funcExprScope = m_currentNodeFunc->scope;
  1717. Assert(funcExprScope->GetScopeType() == ScopeType_FuncExpr);
  1718. ParseNodeBlock* bodyScope = m_currentNodeFunc->pnodeBodyScope;
  1719. if (bodyScope && ref->GetScopeId() < bodyScope->blockId && ref->GetScopeId() > blockId)
  1720. {
  1721. Assert(bodyScope->blockType == PnodeBlockType::Function);
  1722. funcExprScope->SetIsObject();
  1723. }
  1724. }
  1725. if (ref->GetScopeId() == blockId)
  1726. {
  1727. break;
  1728. }
  1729. }
  1730. }
  1731. void Parser::MarkEscapingRef(ParseNodePtr pnode, IdentToken *pToken)
  1732. {
  1733. if (m_currentNodeFunc == nullptr)
  1734. {
  1735. return;
  1736. }
  1737. if (pnode && pnode->nop == knopFncDecl)
  1738. {
  1739. this->SetNestedFuncEscapes();
  1740. }
  1741. else if (pToken->pid)
  1742. {
  1743. PidRefStack *pidRef = pToken->pid->GetTopRef();
  1744. if (pidRef->sym)
  1745. {
  1746. if (pidRef->sym->GetSymbolType() == STFunction)
  1747. {
  1748. this->SetNestedFuncEscapes();
  1749. }
  1750. }
  1751. else
  1752. {
  1753. pidRef->isEscape = true;
  1754. }
  1755. }
  1756. }
  1757. void Parser::SetNestedFuncEscapes() const
  1758. {
  1759. if (m_sourceContextInfo ?
  1760. !PHASE_OFF_RAW(Js::DisableStackFuncOnDeferredEscapePhase, m_sourceContextInfo->sourceContextId, m_currentNodeFunc->functionId) :
  1761. !PHASE_OFF1(Js::DisableStackFuncOnDeferredEscapePhase))
  1762. {
  1763. m_currentNodeFunc->SetNestedFuncEscapes();
  1764. }
  1765. }
  1766. void Parser::PopStmt(StmtNest *pStmt)
  1767. {
  1768. Assert(pStmt == m_pstmtCur);
  1769. SetCurrentStatement(m_pstmtCur->pstmtOuter);
  1770. }
  1771. BlockInfoStack *Parser::PushBlockInfo(ParseNodeBlock * pnodeBlock)
  1772. {
  1773. BlockInfoStack *newBlockInfo = (BlockInfoStack *)m_nodeAllocator.Alloc(sizeof(BlockInfoStack));
  1774. Assert(nullptr != newBlockInfo);
  1775. newBlockInfo->pnodeBlock = pnodeBlock;
  1776. newBlockInfo->pBlockInfoOuter = m_currentBlockInfo;
  1777. newBlockInfo->m_ppnodeLex = &pnodeBlock->pnodeLexVars;
  1778. if (pnodeBlock->blockType != PnodeBlockType::Regular)
  1779. {
  1780. newBlockInfo->pBlockInfoFunction = newBlockInfo;
  1781. }
  1782. else
  1783. {
  1784. Assert(m_currentBlockInfo);
  1785. newBlockInfo->pBlockInfoFunction = m_currentBlockInfo->pBlockInfoFunction;
  1786. }
  1787. m_currentBlockInfo = newBlockInfo;
  1788. return newBlockInfo;
  1789. }
  1790. void Parser::PopBlockInfo()
  1791. {
  1792. Assert(m_currentBlockInfo);
  1793. PopDynamicBlock();
  1794. m_currentBlockInfo = m_currentBlockInfo->pBlockInfoOuter;
  1795. }
  1796. void Parser::PushDynamicBlock()
  1797. {
  1798. Assert(GetCurrentBlock());
  1799. int blockId = GetCurrentBlock()->blockId;
  1800. if (m_currentDynamicBlock && m_currentDynamicBlock->id == blockId)
  1801. {
  1802. return;
  1803. }
  1804. BlockIdsStack *info = (BlockIdsStack *)m_nodeAllocator.Alloc(sizeof(BlockIdsStack));
  1805. if (nullptr == info)
  1806. {
  1807. Error(ERRnoMemory);
  1808. }
  1809. info->id = blockId;
  1810. info->prev = m_currentDynamicBlock;
  1811. m_currentDynamicBlock = info;
  1812. }
  1813. void Parser::PopDynamicBlock()
  1814. {
  1815. int blockId = GetCurrentDynamicBlockId();
  1816. if (GetCurrentBlock()->blockId != blockId || blockId == -1)
  1817. {
  1818. return;
  1819. }
  1820. Assert(m_currentDynamicBlock);
  1821. this->GetHashTbl()->VisitPids([&](IdentPtr pid) {
  1822. for (PidRefStack *ref = pid->GetTopRef(); ref && ref->GetScopeId() >= blockId; ref = ref->prev)
  1823. {
  1824. ref->SetDynamicBinding();
  1825. }
  1826. });
  1827. m_currentDynamicBlock = m_currentDynamicBlock->prev;
  1828. }
  1829. int Parser::GetCurrentDynamicBlockId() const
  1830. {
  1831. return m_currentDynamicBlock ? m_currentDynamicBlock->id : -1;
  1832. }
  1833. ParseNodeFnc *Parser::GetCurrentFunctionNode()
  1834. {
  1835. if (m_currentNodeDeferredFunc != nullptr)
  1836. {
  1837. return m_currentNodeDeferredFunc;
  1838. }
  1839. else if (m_currentNodeFunc != nullptr)
  1840. {
  1841. return m_currentNodeFunc;
  1842. }
  1843. else
  1844. {
  1845. AssertMsg(GetFunctionBlock()->blockType == PnodeBlockType::Global,
  1846. "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'");
  1847. return m_currentNodeProg;
  1848. }
  1849. }
  1850. ParseNodeFnc *Parser::GetCurrentNonLambdaFunctionNode()
  1851. {
  1852. if (m_currentNodeNonLambdaDeferredFunc != nullptr)
  1853. {
  1854. return m_currentNodeNonLambdaDeferredFunc;
  1855. }
  1856. return m_currentNodeNonLambdaFunc;
  1857. }
  1858. void Parser::RegisterRegexPattern(UnifiedRegex::RegexPattern *const regexPattern)
  1859. {
  1860. Assert(regexPattern);
  1861. // ensure a no-throw add behavior here, to catch out of memory exceptions, using the guest arena allocator
  1862. if (!m_registeredRegexPatterns.PrependNoThrow(m_tempGuestArena->GetAllocator(), regexPattern))
  1863. {
  1864. Parser::Error(ERRnoMemory);
  1865. }
  1866. }
  1867. void Parser::CaptureState(ParserState *state)
  1868. {
  1869. Assert(state != nullptr);
  1870. state->m_funcInArraySave = m_funcInArray;
  1871. state->m_funcInArrayDepthSave = m_funcInArrayDepth;
  1872. state->m_nestedCountSave = *m_pnestedCount;
  1873. state->m_ppnodeScopeSave = m_ppnodeScope;
  1874. state->m_ppnodeExprScopeSave = m_ppnodeExprScope;
  1875. state->m_pCurrentAstSizeSave = m_pCurrentAstSize;
  1876. state->m_nextBlockId = m_nextBlockId;
  1877. Assert(state->m_ppnodeScopeSave == nullptr || *state->m_ppnodeScopeSave == nullptr);
  1878. Assert(state->m_ppnodeExprScopeSave == nullptr || *state->m_ppnodeExprScopeSave == nullptr);
  1879. #if DEBUG
  1880. state->m_currentBlockInfo = m_currentBlockInfo;
  1881. #endif
  1882. }
  1883. void Parser::RestoreStateFrom(ParserState *state)
  1884. {
  1885. Assert(state != nullptr);
  1886. Assert(state->m_currentBlockInfo == m_currentBlockInfo);
  1887. m_funcInArray = state->m_funcInArraySave;
  1888. m_funcInArrayDepth = state->m_funcInArrayDepthSave;
  1889. *m_pnestedCount = state->m_nestedCountSave;
  1890. m_pCurrentAstSize = state->m_pCurrentAstSizeSave;
  1891. m_nextBlockId = state->m_nextBlockId;
  1892. if (state->m_ppnodeScopeSave != nullptr)
  1893. {
  1894. *state->m_ppnodeScopeSave = nullptr;
  1895. }
  1896. if (state->m_ppnodeExprScopeSave != nullptr)
  1897. {
  1898. *state->m_ppnodeExprScopeSave = nullptr;
  1899. }
  1900. m_ppnodeScope = state->m_ppnodeScopeSave;
  1901. m_ppnodeExprScope = state->m_ppnodeExprScopeSave;
  1902. }
  1903. void Parser::AddToNodeListEscapedUse(ParseNode ** ppnodeList, ParseNode *** pppnodeLast,
  1904. ParseNode * pnodeAdd)
  1905. {
  1906. AddToNodeList(ppnodeList, pppnodeLast, pnodeAdd);
  1907. pnodeAdd->SetIsInList();
  1908. }
  1909. void Parser::AddToNodeList(ParseNode ** ppnodeList, ParseNode *** pppnodeLast,
  1910. ParseNode * pnodeAdd)
  1911. {
  1912. Assert(!this->m_deferringAST);
  1913. if (nullptr == *pppnodeLast)
  1914. {
  1915. // should be an empty list
  1916. Assert(nullptr == *ppnodeList);
  1917. *ppnodeList = pnodeAdd;
  1918. *pppnodeLast = ppnodeList;
  1919. }
  1920. else
  1921. {
  1922. Assert(*ppnodeList);
  1923. Assert(**pppnodeLast);
  1924. ParseNode *pnodeT = CreateBinNode(knopList, **pppnodeLast, pnodeAdd);
  1925. **pppnodeLast = pnodeT;
  1926. *pppnodeLast = &pnodeT->AsParseNodeBin()->pnode2;
  1927. }
  1928. }
  1929. // Check reference to "arguments" that indicates the object may escape.
  1930. void Parser::CheckArguments(ParseNodePtr pnode)
  1931. {
  1932. if (m_currentNodeFunc && this->NodeIsIdent(pnode, wellKnownPropertyPids.arguments))
  1933. {
  1934. m_currentNodeFunc->SetHasHeapArguments();
  1935. }
  1936. }
  1937. // Check use of "arguments" that requires instantiation of the object.
  1938. void Parser::CheckArgumentsUse(IdentPtr pid, ParseNodeFnc * pnodeFnc)
  1939. {
  1940. if (pid == wellKnownPropertyPids.arguments)
  1941. {
  1942. if (pnodeFnc != nullptr && pnodeFnc != m_currentNodeProg)
  1943. {
  1944. pnodeFnc->SetUsesArguments(TRUE);
  1945. }
  1946. else
  1947. {
  1948. m_UsesArgumentsAtGlobal = true;
  1949. }
  1950. }
  1951. }
  1952. void Parser::CheckStrictModeEvalArgumentsUsage(IdentPtr pid, ParseNodePtr pnode)
  1953. {
  1954. if (pid != nullptr)
  1955. {
  1956. // In strict mode, 'eval' / 'arguments' cannot be assigned to.
  1957. if (pid == wellKnownPropertyPids.eval)
  1958. {
  1959. Error(ERREvalUsage, pnode);
  1960. }
  1961. if (pid == wellKnownPropertyPids.arguments)
  1962. {
  1963. Error(ERRArgsUsage, pnode);
  1964. }
  1965. }
  1966. }
  1967. void Parser::ReduceDeferredScriptLength(size_t chars)
  1968. {
  1969. // If we're in deferred mode, subtract the given char count from the total length,
  1970. // and see if this puts us under the deferral threshold.
  1971. if (((m_grfscr & (fscrCanDeferFncParse | fscrWillDeferFncParse)) == (fscrCanDeferFncParse | fscrWillDeferFncParse)) &&
  1972. (
  1973. PHASE_OFF1(Js::DeferEventHandlersPhase) ||
  1974. (m_grfscr & fscrGlobalCode)
  1975. )
  1976. )
  1977. {
  1978. if (m_length > chars)
  1979. {
  1980. m_length -= chars;
  1981. }
  1982. else
  1983. {
  1984. m_length = 0;
  1985. }
  1986. if (m_length < Parser::GetDeferralThreshold(this->m_sourceContextInfo->IsSourceProfileLoaded()))
  1987. {
  1988. // Stop deferring.
  1989. m_grfscr &= ~fscrWillDeferFncParse;
  1990. m_stoppedDeferredParse = TRUE;
  1991. }
  1992. }
  1993. }
  1994. void Parser::EnsureStackAvailable()
  1995. {
  1996. bool isInterrupt = false;
  1997. if (!m_scriptContext->GetThreadContext()->IsStackAvailable(Js::Constants::MinStackCompile, &isInterrupt))
  1998. {
  1999. Error(isInterrupt ? E_ABORT : VBSERR_OutOfStack);
  2000. }
  2001. }
  2002. void Parser::ThrowNewTargetSyntaxErrForGlobalScope()
  2003. {
  2004. // If we are parsing a previously deferred function, we can skip throwing the SyntaxError for `new.target` at global scope.
  2005. // If we are at global scope, we would have thrown a SyntaxError when we did the Upfront parse pass and we would not have
  2006. // deferred the function in order to come back now and reparse it.
  2007. if (m_parseType == ParseType_Deferred)
  2008. {
  2009. return;
  2010. }
  2011. if (GetCurrentNonLambdaFunctionNode() != nullptr)
  2012. {
  2013. return;
  2014. }
  2015. if ((this->m_grfscr & fscrEval) != 0)
  2016. {
  2017. Js::JavascriptFunction * caller = nullptr;
  2018. if (Js::JavascriptStackWalker::GetCaller(&caller, m_scriptContext))
  2019. {
  2020. Js::FunctionBody * callerBody = caller->GetFunctionBody();
  2021. Assert(callerBody);
  2022. if (!callerBody->GetIsGlobalFunc() && !(callerBody->IsLambda() && callerBody->GetEnclosedByGlobalFunc()))
  2023. {
  2024. return;
  2025. }
  2026. }
  2027. }
  2028. Error(ERRInvalidNewTarget);
  2029. }
  2030. template<bool buildAST>
  2031. IdentPtr Parser::ParseMetaProperty(tokens metaParentKeyword, charcount_t ichMin, _Out_opt_ BOOL* pfCanAssign)
  2032. {
  2033. AssertMsg(metaParentKeyword == tkNEW || metaParentKeyword == tkIMPORT, "Only supported for tkNEW and tkIMPORT parent keywords");
  2034. AssertMsg(this->m_token.tk == tkDot, "We must be currently sitting on the dot after the parent keyword");
  2035. this->GetScanner()->Scan();
  2036. if (this->m_token.tk == tkID)
  2037. {
  2038. IdentPtr id = this->m_token.GetIdentifier(this->GetHashTbl());
  2039. switch (metaParentKeyword)
  2040. {
  2041. case tkNEW:
  2042. if (id == this->GetTargetPid())
  2043. {
  2044. ThrowNewTargetSyntaxErrForGlobalScope();
  2045. if (pfCanAssign)
  2046. {
  2047. *pfCanAssign = FALSE;
  2048. }
  2049. return wellKnownPropertyPids._newTarget;
  2050. }
  2051. break;
  2052. case tkIMPORT:
  2053. if (id == this->GetMetaPid())
  2054. {
  2055. if (pfCanAssign)
  2056. {
  2057. *pfCanAssign = FALSE;
  2058. }
  2059. return wellKnownPropertyPids._importMeta;
  2060. }
  2061. break;
  2062. }
  2063. }
  2064. if (metaParentKeyword == tkNEW)
  2065. {
  2066. Error(ERRValidIfFollowedBy, _u("'new.'"), _u("'target'"));
  2067. }
  2068. else
  2069. {
  2070. Error(ERRValidIfFollowedBy, _u("'import.'"), _u("'meta'"));
  2071. }
  2072. }
  2073. template<bool buildAST>
  2074. void Parser::ParseNamedImportOrExportClause(ModuleImportOrExportEntryList* importOrExportEntryList, bool isExportClause)
  2075. {
  2076. Assert(m_token.tk == tkLCurly);
  2077. Assert(importOrExportEntryList != nullptr);
  2078. this->GetScanner()->Scan();
  2079. while (m_token.tk != tkRCurly && m_token.tk != tkEOF)
  2080. {
  2081. tokens firstToken = m_token.tk;
  2082. if (!(m_token.IsIdentifier() || m_token.IsReservedWord()))
  2083. {
  2084. Error(ERRTokenAfter, GetTokenString(m_token.tk), GetTokenString(GetScanner()->GetPrevious()));
  2085. }
  2086. IdentPtr identifierName = m_token.GetIdentifier(this->GetHashTbl());
  2087. IdentPtr identifierAs = identifierName;
  2088. charcount_t offsetForError = this->GetScanner()->IchMinTok();
  2089. this->GetScanner()->Scan();
  2090. if (m_token.tk == tkID)
  2091. {
  2092. // We have the pattern "IdentifierName as"
  2093. if (!CheckContextualKeyword(wellKnownPropertyPids.as))
  2094. {
  2095. Error(ERRInvalidIdentifier, m_token.GetIdentifier(this->GetHashTbl())->Psz(), identifierName->Psz());
  2096. }
  2097. this->GetScanner()->Scan();
  2098. // If we are parsing an import statement, the token after 'as' must be a BindingIdentifier.
  2099. if (!isExportClause)
  2100. {
  2101. ChkCurTokNoScan(tkID, ERRValidIfFollowedBy, _u("'as'"), _u("an identifier."));
  2102. }
  2103. if (!(m_token.IsIdentifier() || m_token.IsReservedWord()))
  2104. {
  2105. Error(ERRValidIfFollowedBy, _u("'as'"), _u("an identifier."));
  2106. }
  2107. identifierAs = m_token.GetIdentifier(this->GetHashTbl());
  2108. // Scan to the next token.
  2109. this->GetScanner()->Scan();
  2110. }
  2111. else if (!isExportClause && firstToken != tkID)
  2112. {
  2113. // If we are parsing an import statement and this ImportSpecifier clause did not have
  2114. // 'as ImportedBinding' at the end of it, identifierName must be a BindingIdentifier.
  2115. Error(ERRnoIdent);
  2116. }
  2117. if (m_token.tk == tkComma)
  2118. {
  2119. // Consume a trailing comma
  2120. this->GetScanner()->Scan();
  2121. }
  2122. if (isExportClause)
  2123. {
  2124. identifierName->SetIsModuleExport();
  2125. AddModuleImportOrExportEntry(importOrExportEntryList, nullptr, identifierName, identifierAs, nullptr, offsetForError);
  2126. }
  2127. else if (buildAST)
  2128. {
  2129. // The name we will use 'as' this import/export is a binding identifier in import statements.
  2130. CreateModuleImportDeclNode(identifierAs);
  2131. AddModuleImportOrExportEntry(importOrExportEntryList, identifierName, identifierAs, nullptr, nullptr);
  2132. }
  2133. }
  2134. // Final token in a named import or export clause must be a '}'
  2135. ChkCurTokNoScan(tkRCurly, ERRnoRcurly);
  2136. }
  2137. IdentPtrList* Parser::GetRequestedModulesList()
  2138. {
  2139. return m_currentNodeProg->AsParseNodeModule()->requestedModules;
  2140. }
  2141. void Parser::VerifyModuleLocalExportEntries()
  2142. {
  2143. ModuleImportOrExportEntryList* localExportRecordList = GetModuleLocalExportEntryList();
  2144. if (localExportRecordList != nullptr)
  2145. {
  2146. localExportRecordList->Map([=](ModuleImportOrExportEntry exportEntry) {
  2147. if (exportEntry.pidRefStack!=nullptr)
  2148. {
  2149. if (exportEntry.pidRefStack->GetSym() == nullptr)
  2150. {
  2151. Error(ERRUndeclaredExportName, exportEntry.offset, exportEntry.localName->Cch(), exportEntry.localName->Psz());
  2152. }
  2153. }
  2154. });
  2155. }
  2156. }
  2157. ModuleImportOrExportEntryList* Parser::GetModuleImportEntryList()
  2158. {
  2159. return m_currentNodeProg->AsParseNodeModule()->importEntries;
  2160. }
  2161. ModuleImportOrExportEntryList* Parser::GetModuleLocalExportEntryList()
  2162. {
  2163. return m_currentNodeProg->AsParseNodeModule()->localExportEntries;
  2164. }
  2165. ModuleImportOrExportEntryList* Parser::GetModuleIndirectExportEntryList()
  2166. {
  2167. return m_currentNodeProg->AsParseNodeModule()->indirectExportEntries;
  2168. }
  2169. ModuleImportOrExportEntryList* Parser::GetModuleStarExportEntryList()
  2170. {
  2171. return m_currentNodeProg->AsParseNodeModule()->starExportEntries;
  2172. }
  2173. IdentPtrList* Parser::EnsureRequestedModulesList()
  2174. {
  2175. if (m_currentNodeProg->AsParseNodeModule()->requestedModules == nullptr)
  2176. {
  2177. m_currentNodeProg->AsParseNodeModule()->requestedModules = Anew(&m_nodeAllocator, IdentPtrList, &m_nodeAllocator);
  2178. }
  2179. return m_currentNodeProg->AsParseNodeModule()->requestedModules;
  2180. }
  2181. ModuleImportOrExportEntryList* Parser::EnsureModuleImportEntryList()
  2182. {
  2183. if (m_currentNodeProg->AsParseNodeModule()->importEntries == nullptr)
  2184. {
  2185. m_currentNodeProg->AsParseNodeModule()->importEntries = Anew(&m_nodeAllocator, ModuleImportOrExportEntryList, &m_nodeAllocator);
  2186. }
  2187. return m_currentNodeProg->AsParseNodeModule()->importEntries;
  2188. }
  2189. ModuleImportOrExportEntryList* Parser::EnsureModuleLocalExportEntryList()
  2190. {
  2191. if (m_currentNodeProg->AsParseNodeModule()->localExportEntries == nullptr)
  2192. {
  2193. m_currentNodeProg->AsParseNodeModule()->localExportEntries = Anew(&m_nodeAllocator, ModuleImportOrExportEntryList, &m_nodeAllocator);
  2194. }
  2195. return m_currentNodeProg->AsParseNodeModule()->localExportEntries;
  2196. }
  2197. ModuleImportOrExportEntryList* Parser::EnsureModuleIndirectExportEntryList()
  2198. {
  2199. if (m_currentNodeProg->AsParseNodeModule()->indirectExportEntries == nullptr)
  2200. {
  2201. m_currentNodeProg->AsParseNodeModule()->indirectExportEntries = Anew(&m_nodeAllocator, ModuleImportOrExportEntryList, &m_nodeAllocator);
  2202. }
  2203. return m_currentNodeProg->AsParseNodeModule()->indirectExportEntries;
  2204. }
  2205. ModuleImportOrExportEntryList* Parser::EnsureModuleStarExportEntryList()
  2206. {
  2207. if (m_currentNodeProg->AsParseNodeModule()->starExportEntries == nullptr)
  2208. {
  2209. m_currentNodeProg->AsParseNodeModule()->starExportEntries = Anew(&m_nodeAllocator, ModuleImportOrExportEntryList, &m_nodeAllocator);
  2210. }
  2211. return m_currentNodeProg->AsParseNodeModule()->starExportEntries;
  2212. }
  2213. void Parser::AddModuleSpecifier(IdentPtr moduleRequest)
  2214. {
  2215. IdentPtrList* requestedModulesList = EnsureRequestedModulesList();
  2216. if (!requestedModulesList->Has(moduleRequest))
  2217. {
  2218. requestedModulesList->Prepend(moduleRequest);
  2219. }
  2220. }
  2221. ModuleImportOrExportEntry* Parser::AddModuleImportOrExportEntry(ModuleImportOrExportEntryList* importOrExportEntryList, ModuleImportOrExportEntry* importOrExportEntry)
  2222. {
  2223. if (importOrExportEntry->exportName != nullptr)
  2224. {
  2225. CheckForDuplicateExportEntry(importOrExportEntry->exportName);
  2226. }
  2227. importOrExportEntryList->Prepend(*importOrExportEntry);
  2228. return importOrExportEntry;
  2229. }
  2230. ModuleImportOrExportEntry* Parser::AddModuleImportOrExportEntry(ModuleImportOrExportEntryList* importOrExportEntryList, IdentPtr importName, IdentPtr localName, IdentPtr exportName, IdentPtr moduleRequest, charcount_t offsetForError)
  2231. {
  2232. ModuleImportOrExportEntry* importOrExportEntry = Anew(&m_nodeAllocator, ModuleImportOrExportEntry);
  2233. importOrExportEntry->importName = importName;
  2234. importOrExportEntry->localName = localName;
  2235. importOrExportEntry->exportName = exportName;
  2236. importOrExportEntry->moduleRequest = moduleRequest;
  2237. importOrExportEntry->pidRefStack = offsetForError == 0 ? nullptr : PushPidRef(localName);
  2238. importOrExportEntry->offset = offsetForError;
  2239. return AddModuleImportOrExportEntry(importOrExportEntryList, importOrExportEntry);
  2240. }
  2241. void Parser::AddModuleLocalExportEntry(ParseNodePtr varDeclNode)
  2242. {
  2243. AssertOrFailFast(varDeclNode->nop == knopVarDecl || varDeclNode->nop == knopLetDecl || varDeclNode->nop == knopConstDecl);
  2244. IdentPtr localName = varDeclNode->AsParseNodeVar()->pid;
  2245. varDeclNode->AsParseNodeVar()->sym->SetIsModuleExportStorage(true);
  2246. AddModuleImportOrExportEntry(EnsureModuleLocalExportEntryList(), nullptr, localName, localName, nullptr);
  2247. }
  2248. void Parser::CheckForDuplicateExportEntry(IdentPtr exportName)
  2249. {
  2250. if (m_currentNodeProg->AsParseNodeModule()->indirectExportEntries != nullptr)
  2251. {
  2252. CheckForDuplicateExportEntry(m_currentNodeProg->AsParseNodeModule()->indirectExportEntries, exportName);
  2253. }
  2254. if (m_currentNodeProg->AsParseNodeModule()->localExportEntries != nullptr)
  2255. {
  2256. CheckForDuplicateExportEntry(m_currentNodeProg->AsParseNodeModule()->localExportEntries, exportName);
  2257. }
  2258. }
  2259. void Parser::CheckForDuplicateExportEntry(ModuleImportOrExportEntryList* exportEntryList, IdentPtr exportName)
  2260. {
  2261. ModuleImportOrExportEntry* findResult = exportEntryList->Find([&](ModuleImportOrExportEntry exportEntry)
  2262. {
  2263. if (exportName == exportEntry.exportName)
  2264. {
  2265. return true;
  2266. }
  2267. return false;
  2268. });
  2269. if (findResult != nullptr)
  2270. {
  2271. Error(ERRDuplicateExport, exportName->Psz());
  2272. }
  2273. }
  2274. template<bool buildAST>
  2275. void Parser::ParseImportClause(ModuleImportOrExportEntryList* importEntryList, bool parsingAfterComma)
  2276. {
  2277. bool parsedNamespaceOrNamedImport = false;
  2278. switch (m_token.tk)
  2279. {
  2280. case tkID:
  2281. // This is the default binding identifier.
  2282. // If we already saw a comma in the import clause, this is a syntax error.
  2283. if (parsingAfterComma)
  2284. {
  2285. Error(ERRsyntax);
  2286. }
  2287. if (buildAST)
  2288. {
  2289. IdentPtr localName = m_token.GetIdentifier(this->GetHashTbl());
  2290. IdentPtr importName = wellKnownPropertyPids._default;
  2291. CreateModuleImportDeclNode(localName);
  2292. AddModuleImportOrExportEntry(importEntryList, importName, localName, nullptr, nullptr);
  2293. }
  2294. break;
  2295. case tkLCurly:
  2296. // This begins a list of named imports.
  2297. ParseNamedImportOrExportClause<buildAST>(importEntryList, false);
  2298. parsedNamespaceOrNamedImport = true;
  2299. break;
  2300. case tkStar:
  2301. // This begins a namespace import clause.
  2302. // "* as ImportedBinding"
  2303. // Token following * must be the identifier 'as'
  2304. this->GetScanner()->Scan();
  2305. if (!CheckContextualKeyword(wellKnownPropertyPids.as))
  2306. {
  2307. Error(ERRValidIfFollowedBy, _u("import *"), _u("as"));
  2308. }
  2309. // Token following 'as' must be a binding identifier.
  2310. this->GetScanner()->Scan();
  2311. ChkCurTokNoScan(tkID, ERRnoIdent);
  2312. if (buildAST)
  2313. {
  2314. IdentPtr localName = m_token.GetIdentifier(this->GetHashTbl());
  2315. IdentPtr importName = wellKnownPropertyPids._star;
  2316. CreateModuleImportDeclNode(localName);
  2317. AddModuleImportOrExportEntry(importEntryList, importName, localName, nullptr, nullptr);
  2318. }
  2319. parsedNamespaceOrNamedImport = true;
  2320. break;
  2321. default:
  2322. Error(ERRTokenAfter, GetTokenString(m_token.tk), GetTokenString(this->GetScanner()->GetPrevious()));
  2323. }
  2324. this->GetScanner()->Scan();
  2325. if (m_token.tk == tkComma)
  2326. {
  2327. // There cannot be more than one comma in a module import clause.
  2328. // There cannot be a namespace import or named imports list on the left of the comma in a module import clause.
  2329. if (parsingAfterComma || parsedNamespaceOrNamedImport)
  2330. {
  2331. Error(ERRTokenAfter, _u(","), GetTokenString(this->GetScanner()->GetPrevious()));
  2332. }
  2333. this->GetScanner()->Scan();
  2334. ParseImportClause<buildAST>(importEntryList, true);
  2335. }
  2336. }
  2337. void Parser::CheckIfImportOrExportStatementValidHere()
  2338. {
  2339. ParseNodeFnc * curFunc = GetCurrentFunctionNode();
  2340. if (curFunc->nop != knopFncDecl || !curFunc->IsModule())
  2341. {
  2342. Error(ERRModuleImportOrExportInScript);
  2343. }
  2344. if (this->m_currentBlockInfo->pnodeBlock != curFunc->pnodeBodyScope
  2345. || (this->m_grfscr & fscrEvalCode) == fscrEvalCode
  2346. || this->m_tryCatchOrFinallyDepth != 0
  2347. || this->m_disallowImportExportStmt)
  2348. {
  2349. Error(ERRInvalidModuleImportOrExport);
  2350. }
  2351. }
  2352. bool Parser::IsTopLevelModuleFunc()
  2353. {
  2354. ParseNodeFnc * curFunc = GetCurrentFunctionNode();
  2355. return curFunc->nop == knopFncDecl && curFunc->IsModule();
  2356. }
  2357. template<bool buildAST> ParseNodePtr Parser::ParseImportCall()
  2358. {
  2359. this->GetScanner()->Scan();
  2360. ParseNodePtr specifier = ParseExpr<buildAST>(koplCma, nullptr, /* fAllowIn */FALSE, /* fAllowEllipsis */FALSE);
  2361. if (m_token.tk != tkRParen)
  2362. {
  2363. Error(ERRnoRparen);
  2364. }
  2365. this->GetScanner()->Scan();
  2366. return buildAST ? CreateCallNode(knopCall, CreateNodeForOpT<knopImport>(), specifier) : nullptr;
  2367. }
  2368. template<bool buildAST>
  2369. ParseNodePtr Parser::ParseImport()
  2370. {
  2371. Assert(m_scriptContext->GetConfig()->IsES6ModuleEnabled());
  2372. Assert(m_token.tk == tkIMPORT);
  2373. charcount_t ichMin = this->GetScanner()->IchMinTok();
  2374. RestorePoint parsedImport;
  2375. this->GetScanner()->Capture(&parsedImport);
  2376. this->GetScanner()->Scan();
  2377. // import()
  2378. if (m_token.tk == tkLParen)
  2379. {
  2380. if (!m_scriptContext->GetConfig()->IsESDynamicImportEnabled())
  2381. {
  2382. Error(ERRExperimental);
  2383. }
  2384. ParseNodePtr pnode = ParseImportCall<buildAST>();
  2385. BOOL fCanAssign;
  2386. IdentToken token;
  2387. return ParsePostfixOperators<buildAST>(pnode, TRUE, FALSE, FALSE, TRUE, &fCanAssign, &token);
  2388. }
  2389. else if (m_token.tk == tkDot && m_scriptContext->GetConfig()->IsESImportMetaEnabled())
  2390. {
  2391. BOOL fCanAssign;
  2392. ParseMetaProperty<buildAST>(tkIMPORT, ichMin, &fCanAssign);
  2393. this->GetScanner()->SeekTo(parsedImport);
  2394. return ParseExpr<buildAST>();
  2395. }
  2396. this->GetScanner()->SeekTo(parsedImport);
  2397. CheckIfImportOrExportStatementValidHere();
  2398. // We just parsed an import token. Next valid token is *, {, string constant, or binding identifier.
  2399. this->GetScanner()->Scan();
  2400. if (m_token.tk == tkStrCon)
  2401. {
  2402. // This import declaration has no import clause.
  2403. // "import ModuleSpecifier;"
  2404. if (buildAST)
  2405. {
  2406. AddModuleSpecifier(m_token.GetStr());
  2407. }
  2408. // Scan past the module identifier.
  2409. this->GetScanner()->Scan();
  2410. }
  2411. else
  2412. {
  2413. ModuleImportOrExportEntryList importEntryList(&m_nodeAllocator);
  2414. // Parse the import clause (default binding can only exist before the comma).
  2415. ParseImportClause<buildAST>(&importEntryList);
  2416. // Token following import clause must be the identifier 'from'
  2417. IdentPtr moduleSpecifier = ParseImportOrExportFromClause<buildAST>(true);
  2418. if (buildAST)
  2419. {
  2420. Assert(moduleSpecifier != nullptr);
  2421. AddModuleSpecifier(moduleSpecifier);
  2422. importEntryList.Map([this, moduleSpecifier](ModuleImportOrExportEntry& importEntry) {
  2423. importEntry.moduleRequest = moduleSpecifier;
  2424. AddModuleImportOrExportEntry(EnsureModuleImportEntryList(), &importEntry);
  2425. });
  2426. }
  2427. importEntryList.Clear();
  2428. }
  2429. // Import statement is actually a nop, we hoist all the imported bindings to the top of the module.
  2430. return nullptr;
  2431. }
  2432. template<bool buildAST>
  2433. IdentPtr Parser::ParseImportOrExportFromClause(bool throwIfNotFound)
  2434. {
  2435. IdentPtr moduleSpecifier = nullptr;
  2436. if (CheckContextualKeyword(wellKnownPropertyPids.from))
  2437. {
  2438. this->GetScanner()->Scan();
  2439. // Token following the 'from' token must be a string constant - the module specifier.
  2440. ChkCurTokNoScan(tkStrCon, ERRValidIfFollowedBy, _u("'from'"), _u("a module specifier."));
  2441. if (buildAST)
  2442. {
  2443. moduleSpecifier = m_token.GetStr();
  2444. }
  2445. this->GetScanner()->Scan();
  2446. }
  2447. else if (throwIfNotFound)
  2448. {
  2449. Error(ERRMissingFrom);
  2450. }
  2451. return moduleSpecifier;
  2452. }
  2453. template<bool buildAST>
  2454. ParseNodePtr Parser::ParseDefaultExportClause()
  2455. {
  2456. Assert(m_token.tk == tkDEFAULT);
  2457. this->GetScanner()->Scan();
  2458. ParseNodePtr pnode = nullptr;
  2459. ushort flags = fFncNoFlgs;
  2460. switch (m_token.tk)
  2461. {
  2462. case tkCLASS:
  2463. {
  2464. if (!m_scriptContext->GetConfig()->IsES6ClassAndExtendsEnabled())
  2465. {
  2466. goto LDefault;
  2467. }
  2468. // Before we parse the class itself we need to know if the class has an identifier name.
  2469. // If it does, we'll treat this class as an ordinary class declaration which will bind
  2470. // it to that name. Otherwise the class should parse as a nameless class expression and
  2471. // bind only to the export binding.
  2472. BOOL classHasName = false;
  2473. RestorePoint parsedClass;
  2474. this->GetScanner()->Capture(&parsedClass);
  2475. this->GetScanner()->Scan();
  2476. if (m_token.tk == tkID)
  2477. {
  2478. classHasName = true;
  2479. }
  2480. this->GetScanner()->SeekTo(parsedClass);
  2481. ParseNodeClass * pnodeClass;
  2482. pnode = pnodeClass = ParseClassDecl<buildAST>(classHasName, nullptr, nullptr, nullptr);
  2483. if (buildAST)
  2484. {
  2485. AnalysisAssert(pnode != nullptr);
  2486. Assert(pnode->nop == knopClassDecl);
  2487. pnodeClass->SetIsDefaultModuleExport(true);
  2488. }
  2489. break;
  2490. }
  2491. case tkID:
  2492. // If we parsed an async token, it could either modify the next token (if it is a
  2493. // function token) or it could be an identifier (let async = 0; export default async;).
  2494. // To handle both cases, when we parse an async token we need to keep the parser state
  2495. // and rewind if the next token is not function.
  2496. if (CheckContextualKeyword(wellKnownPropertyPids.async))
  2497. {
  2498. RestorePoint parsedAsync;
  2499. this->GetScanner()->Capture(&parsedAsync);
  2500. this->GetScanner()->Scan();
  2501. if (m_token.tk == tkFUNCTION)
  2502. {
  2503. // Token after async is function, consume the async token and continue to parse the
  2504. // function as an async function.
  2505. flags |= fFncAsync;
  2506. goto LFunction;
  2507. }
  2508. // Token after async is not function, no idea what the async token is supposed to mean
  2509. // so rewind and let the default case handle it.
  2510. this->GetScanner()->SeekTo(parsedAsync);
  2511. }
  2512. goto LDefault;
  2513. break;
  2514. case tkFUNCTION:
  2515. {
  2516. LFunction:
  2517. // We just parsed a function token but we need to figure out if the function
  2518. // has an identifier name or not before we call the helper.
  2519. RestorePoint parsedFunction;
  2520. this->GetScanner()->Capture(&parsedFunction);
  2521. this->GetScanner()->Scan();
  2522. if (m_token.tk == tkStar)
  2523. {
  2524. // If we saw 'function*' that indicates we are going to parse a generator,
  2525. // but doesn't tell us if the generator has an identifier or not.
  2526. // Skip the '*' token for now as it doesn't matter yet.
  2527. this->GetScanner()->Scan();
  2528. }
  2529. // We say that if the function has an identifier name, it is a 'normal' declaration
  2530. // and should create a binding to that identifier as well as one for our default export.
  2531. if (m_token.tk == tkID)
  2532. {
  2533. flags |= fFncDeclaration;
  2534. }
  2535. else
  2536. {
  2537. flags |= fFncNoName;
  2538. }
  2539. // Rewind back to the function token and let the helper handle the parsing.
  2540. this->GetScanner()->SeekTo(parsedFunction);
  2541. pnode = ParseFncDeclCheckScope<buildAST>(flags);
  2542. if (buildAST)
  2543. {
  2544. AnalysisAssert(pnode != nullptr);
  2545. Assert(pnode->nop == knopFncDecl);
  2546. pnode->AsParseNodeFnc()->SetIsDefaultModuleExport(true);
  2547. }
  2548. break;
  2549. }
  2550. default:
  2551. LDefault:
  2552. {
  2553. ParseNodePtr pnodeExpression = ParseExpr<buildAST>();
  2554. // Consider: Can we detect this syntax error earlier?
  2555. if (pnodeExpression && pnodeExpression->nop == knopComma)
  2556. {
  2557. Error(ERRsyntax);
  2558. }
  2559. if (buildAST)
  2560. {
  2561. AnalysisAssert(pnodeExpression != nullptr);
  2562. // Mark this node as the default module export. We need to make sure it is put into the correct
  2563. // module export slot when we emit the node.
  2564. ParseNodeExportDefault * pnodeExportDefault;
  2565. pnode = pnodeExportDefault = CreateNodeForOpT<knopExportDefault>();
  2566. pnode->AsParseNodeExportDefault()->pnodeExpr = pnodeExpression;
  2567. }
  2568. break;
  2569. }
  2570. }
  2571. IdentPtr exportName = wellKnownPropertyPids._default;
  2572. AddModuleImportOrExportEntry(EnsureModuleLocalExportEntryList(), nullptr, exportName, exportName, nullptr);
  2573. return pnode;
  2574. }
  2575. template<bool buildAST>
  2576. ParseNodePtr Parser::ParseExportDeclaration(bool *needTerminator)
  2577. {
  2578. Assert(m_scriptContext->GetConfig()->IsES6ModuleEnabled());
  2579. Assert(m_token.tk == tkEXPORT);
  2580. CheckIfImportOrExportStatementValidHere();
  2581. ParseNodePtr pnode = nullptr;
  2582. IdentPtr moduleIdentifier = nullptr;
  2583. tokens declarationType;
  2584. if (needTerminator != nullptr)
  2585. {
  2586. *needTerminator = false;
  2587. }
  2588. // We just parsed an export token. Next valid tokens are *, {, var, let, const, async, function, class, default.
  2589. this->GetScanner()->Scan();
  2590. switch (m_token.tk)
  2591. {
  2592. case tkStar:
  2593. {
  2594. this->GetScanner()->Scan();
  2595. IdentPtr exportName = nullptr;
  2596. if (m_scriptContext->GetConfig()->IsESExportNsAsEnabled())
  2597. {
  2598. // check for 'as'
  2599. if (CheckContextualKeyword(wellKnownPropertyPids.as))
  2600. {
  2601. // scan to the next token
  2602. this->GetScanner()->Scan();
  2603. // token after as must be an identifier
  2604. if (!(m_token.IsIdentifier() || m_token.IsReservedWord()))
  2605. {
  2606. Error(ERRValidIfFollowedBy, _u("'as'"), _u("an identifier."));
  2607. }
  2608. exportName = m_token.GetIdentifier(this->GetHashTbl());
  2609. // scan to next token
  2610. this->GetScanner()->Scan();
  2611. }
  2612. }
  2613. // A star token in an export declaration must be followed by a from clause which begins with a token 'from'.
  2614. moduleIdentifier = ParseImportOrExportFromClause<buildAST>(true);
  2615. if (buildAST)
  2616. {
  2617. Assert(moduleIdentifier != nullptr);
  2618. AddModuleSpecifier(moduleIdentifier);
  2619. if (!exportName)
  2620. {
  2621. AddModuleImportOrExportEntry(EnsureModuleStarExportEntryList(), wellKnownPropertyPids._star, nullptr, nullptr, moduleIdentifier);
  2622. }
  2623. else
  2624. {
  2625. CheckForDuplicateExportEntry(exportName);
  2626. AddModuleImportOrExportEntry(EnsureModuleIndirectExportEntryList(), wellKnownPropertyPids._star, nullptr, exportName, moduleIdentifier);
  2627. }
  2628. }
  2629. if (needTerminator != nullptr)
  2630. {
  2631. *needTerminator = true;
  2632. }
  2633. break;
  2634. }
  2635. case tkLCurly:
  2636. {
  2637. ModuleImportOrExportEntryList exportEntryList(&m_nodeAllocator);
  2638. ParseNamedImportOrExportClause<buildAST>(&exportEntryList, true);
  2639. this->GetScanner()->Scan();
  2640. // Export clause may be followed by a from clause.
  2641. moduleIdentifier = ParseImportOrExportFromClause<buildAST>(false);
  2642. if (buildAST)
  2643. {
  2644. if (moduleIdentifier != nullptr)
  2645. {
  2646. AddModuleSpecifier(moduleIdentifier);
  2647. }
  2648. exportEntryList.Map([this, moduleIdentifier](ModuleImportOrExportEntry& exportEntry) {
  2649. if (moduleIdentifier != nullptr)
  2650. {
  2651. exportEntry.moduleRequest = moduleIdentifier;
  2652. // We need to swap localname and importname when this is a re-export.
  2653. exportEntry.importName = exportEntry.localName;
  2654. exportEntry.localName = nullptr;
  2655. AddModuleImportOrExportEntry(EnsureModuleIndirectExportEntryList(), &exportEntry);
  2656. }
  2657. else
  2658. {
  2659. AddModuleImportOrExportEntry(EnsureModuleLocalExportEntryList(), &exportEntry);
  2660. }
  2661. });
  2662. exportEntryList.Clear();
  2663. }
  2664. }
  2665. if (needTerminator != nullptr)
  2666. {
  2667. *needTerminator = true;
  2668. }
  2669. break;
  2670. case tkID:
  2671. {
  2672. IdentPtr pid = nullptr;
  2673. if (!this->GetScanner()->LastIdentifierHasEscape())
  2674. {
  2675. pid = m_token.GetIdentifier(this->GetHashTbl());
  2676. }
  2677. if (pid == wellKnownPropertyPids.let)
  2678. {
  2679. declarationType = tkLET;
  2680. goto ParseVarDecl;
  2681. }
  2682. if (pid == wellKnownPropertyPids.async && m_scriptContext->GetConfig()->IsES7AsyncAndAwaitEnabled())
  2683. {
  2684. // In module export statements, async token is only valid if it's followed by function.
  2685. // We need to check here because ParseStatement would think 'async = 20' is a var decl.
  2686. RestorePoint parsedAsync;
  2687. this->GetScanner()->Capture(&parsedAsync);
  2688. this->GetScanner()->Scan();
  2689. if (m_token.tk == tkFUNCTION)
  2690. {
  2691. // Token after async is function, rewind to the async token and let ParseStatement handle it.
  2692. this->GetScanner()->SeekTo(parsedAsync);
  2693. goto ParseFunctionDecl;
  2694. }
  2695. // Token after async is not function, it's a syntax error.
  2696. }
  2697. goto ErrorToken;
  2698. }
  2699. case tkVAR:
  2700. case tkLET:
  2701. case tkCONST:
  2702. {
  2703. declarationType = m_token.tk;
  2704. ParseVarDecl:
  2705. this->GetScanner()->Scan();
  2706. pnode = ParseVariableDeclaration<buildAST>(declarationType, this->GetScanner()->IchMinTok());
  2707. if (buildAST)
  2708. {
  2709. ForEachItemInList(pnode, [&](ParseNodePtr item) {
  2710. if (item->nop == knopAsg)
  2711. {
  2712. Parser::MapBindIdentifier(item, [&](ParseNodePtr subItem)
  2713. {
  2714. AddModuleLocalExportEntry(subItem);
  2715. });
  2716. }
  2717. else
  2718. {
  2719. AddModuleLocalExportEntry(item);
  2720. }
  2721. });
  2722. }
  2723. }
  2724. break;
  2725. case tkFUNCTION:
  2726. case tkCLASS:
  2727. {
  2728. ParseFunctionDecl:
  2729. pnode = ParseStatement<buildAST>();
  2730. if (buildAST)
  2731. {
  2732. IdentPtr localName;
  2733. if (pnode->nop == knopClassDecl)
  2734. {
  2735. ParseNodeClass * pnodeClass = pnode->AsParseNodeClass();
  2736. pnodeClass->pnodeDeclName->sym->SetIsModuleExportStorage(true);
  2737. localName = pnodeClass->pnodeName->pid;
  2738. }
  2739. else
  2740. {
  2741. Assert(pnode->nop == knopFncDecl);
  2742. ParseNodeFnc * pnodeFnc = pnode->AsParseNodeFnc();
  2743. pnodeFnc->GetFuncSymbol()->SetIsModuleExportStorage(true);
  2744. localName = pnodeFnc->pid;
  2745. }
  2746. Assert(localName != nullptr);
  2747. AddModuleImportOrExportEntry(EnsureModuleLocalExportEntryList(), nullptr, localName, localName, nullptr);
  2748. }
  2749. }
  2750. break;
  2751. case tkDEFAULT:
  2752. {
  2753. pnode = ParseDefaultExportClause<buildAST>();
  2754. }
  2755. break;
  2756. default:
  2757. {
  2758. ErrorToken:
  2759. Error(ERRsyntax);
  2760. }
  2761. }
  2762. return pnode;
  2763. }
  2764. /***************************************************************************
  2765. Parse an expression term.
  2766. ***************************************************************************/
  2767. template<bool buildAST>
  2768. ParseNodePtr Parser::ParseTerm(BOOL fAllowCall,
  2769. LPCOLESTR pNameHint,
  2770. uint32 *pHintLength,
  2771. uint32 *pShortNameOffset,
  2772. _Inout_opt_ IdentToken* pToken /*= nullptr*/,
  2773. bool fUnaryOrParen /*= false*/,
  2774. BOOL fCanAssignToCall /*= TRUE*/,
  2775. _Out_opt_ BOOL* pfCanAssign /*= nullptr*/,
  2776. _Inout_opt_ BOOL* pfLikelyPattern /*= nullptr*/,
  2777. _Out_opt_ bool* pfIsDotOrIndex /*= nullptr*/,
  2778. _Inout_opt_ charcount_t *plastRParen /*= nullptr*/)
  2779. {
  2780. ParseNodePtr pnode = nullptr;
  2781. PidRefStack *savedTopAsyncRef = nullptr;
  2782. charcount_t ichMin = 0;
  2783. charcount_t ichLim = 0;
  2784. size_t iecpMin = 0;
  2785. size_t iecpLim = 0;
  2786. size_t iuMin;
  2787. IdentToken term;
  2788. BOOL fInNew = FALSE;
  2789. BOOL fCanAssign = TRUE;
  2790. bool isAsyncExpr = false;
  2791. bool isLambdaExpr = false;
  2792. bool isSpecialName = false;
  2793. IdentPtr pid = nullptr;
  2794. Assert(pToken == nullptr || pToken->tk == tkNone); // Must be empty initially
  2795. PROBE_STACK_NO_DISPOSE(m_scriptContext, Js::Constants::MinStackParseOneTerm);
  2796. switch (m_token.tk)
  2797. {
  2798. case tkID:
  2799. {
  2800. pid = m_token.GetIdentifier(this->GetHashTbl());
  2801. ichMin = this->GetScanner()->IchMinTok();
  2802. iecpMin = this->GetScanner()->IecpMinTok();
  2803. ichLim = this->GetScanner()->IchLimTok();
  2804. iecpLim = this->GetScanner()->IecpLimTok();
  2805. if (pid == wellKnownPropertyPids.async &&
  2806. !this->GetScanner()->LastIdentifierHasEscape() &&
  2807. m_scriptContext->GetConfig()->IsES7AsyncAndAwaitEnabled())
  2808. {
  2809. isAsyncExpr = true;
  2810. }
  2811. // Put this into a block to avoid previousAwaitIsKeyword being not initialized after jump to LIdentifier
  2812. {
  2813. bool previousAwaitIsKeyword = this->GetScanner()->SetAwaitIsKeywordRegion(isAsyncExpr);
  2814. this->GetScanner()->Scan();
  2815. this->GetScanner()->SetAwaitIsKeywordRegion(previousAwaitIsKeyword);
  2816. }
  2817. // We search for an Async expression (a function declaration or an async lambda expression)
  2818. if (isAsyncExpr && !this->GetScanner()->FHadNewLine())
  2819. {
  2820. if (m_token.tk == tkFUNCTION)
  2821. {
  2822. goto LFunction;
  2823. }
  2824. else if (m_token.tk == tkID || m_token.tk == tkAWAIT)
  2825. {
  2826. isLambdaExpr = true;
  2827. goto LFunction;
  2828. }
  2829. else if (m_token.tk == tkLParen)
  2830. {
  2831. // This is potentially an async arrow function. Save the state of the async references
  2832. // in case it needs to be restored. (Note that the case of a single parameter with no ()'s
  2833. // is detected upstream and need not be handled here.)
  2834. savedTopAsyncRef = pid->GetTopRef();
  2835. }
  2836. }
  2837. CheckArgumentsUse(pid, GetCurrentFunctionNode());
  2838. // Assume this pid is not special - overwrite when we parse a special name
  2839. isSpecialName = false;
  2840. LIdentifier:
  2841. PidRefStack * ref = nullptr;
  2842. // Don't push a reference if this is a single lambda parameter, because we'll reparse with
  2843. // a correct function ID.
  2844. if (m_token.tk != tkDArrow)
  2845. {
  2846. ref = this->PushPidRef(pid);
  2847. }
  2848. if (buildAST)
  2849. {
  2850. if (isSpecialName)
  2851. {
  2852. pnode = CreateSpecialNameNode(pid, ref, ichMin, ichLim);
  2853. }
  2854. else
  2855. {
  2856. pnode = CreateNameNode(pid, ref, ichMin, ichLim);
  2857. }
  2858. }
  2859. else
  2860. {
  2861. // Remember the identifier start and end in case it turns out to be a statement label.
  2862. term.tk = tkID;
  2863. term.pid = pid; // Record the identifier for detection of eval
  2864. term.ichMin = static_cast<charcount_t>(iecpMin);
  2865. term.ichLim = static_cast<charcount_t>(iecpLim);
  2866. }
  2867. break;
  2868. }
  2869. case tkSUPER:
  2870. ichMin = this->GetScanner()->IchMinTok();
  2871. iecpMin = this->GetScanner()->IecpMinTok();
  2872. ichLim = this->GetScanner()->IchLimTok();
  2873. iecpLim = this->GetScanner()->IecpLimTok();
  2874. if (!m_scriptContext->GetConfig()->IsES6ClassAndExtendsEnabled())
  2875. {
  2876. goto LUnknown;
  2877. }
  2878. this->GetScanner()->Scan();
  2879. pid = ParseSuper<buildAST>(!!fAllowCall);
  2880. isSpecialName = true;
  2881. fCanAssign = FALSE;
  2882. // Super reference and super call need to push a pid ref to 'this' even when not building an AST
  2883. ReferenceSpecialName(wellKnownPropertyPids._this, ichMin, ichLim);
  2884. // Super call needs to reference 'new.target'
  2885. if (pid == wellKnownPropertyPids._superConstructor)
  2886. {
  2887. // super() will write to "this", so track the assignment.
  2888. PidRefStack *thisRef = wellKnownPropertyPids._this->GetTopRef();
  2889. thisRef->isAsg = true;
  2890. ReferenceSpecialName(wellKnownPropertyPids._newTarget, ichMin, ichLim);
  2891. }
  2892. goto LIdentifier;
  2893. case tkTHIS:
  2894. ichMin = this->GetScanner()->IchMinTok();
  2895. iecpMin = this->GetScanner()->IecpMinTok();
  2896. ichLim = this->GetScanner()->IchLimTok();
  2897. iecpLim = this->GetScanner()->IecpLimTok();
  2898. pid = wellKnownPropertyPids._this;
  2899. this->GetScanner()->Scan();
  2900. isSpecialName = true;
  2901. fCanAssign = FALSE;
  2902. goto LIdentifier;
  2903. case tkLParen:
  2904. {
  2905. ichMin = this->GetScanner()->IchMinTok();
  2906. iuMin = this->GetScanner()->IecpMinTok();
  2907. // If we are undeferring a function which has deferred stubs, we can check to see if the next deferred stub
  2908. // is a lambda at the current character. If it is, we know this LParen is the beginning of a lambda nested
  2909. // function and we can avoid parsing the next series of tokens as a parenthetical expression and reparsing
  2910. // after finding the => token.
  2911. if (buildAST && m_currDeferredStub != nullptr && GetCurrentFunctionNode() != nullptr && GetCurrentFunctionNode()->nestedCount < m_currDeferredStubCount)
  2912. {
  2913. DeferredFunctionStub* stub = m_currDeferredStub + GetCurrentFunctionNode()->nestedCount;
  2914. if (stub->ichMin == ichMin)
  2915. {
  2916. Assert((stub->fncFlags & kFunctionIsLambda) == kFunctionIsLambda);
  2917. pnode = ParseFncDeclCheckScope<true>(fFncLambda);
  2918. break;
  2919. }
  2920. }
  2921. this->GetScanner()->Scan();
  2922. if (m_token.tk == tkRParen)
  2923. {
  2924. // Empty parens can only be legal as an empty parameter list to a lambda declaration.
  2925. // We're in a lambda if the next token is =>.
  2926. fAllowCall = FALSE;
  2927. this->GetScanner()->Scan();
  2928. // If the token after the right paren is not => or if there was a newline between () and => this is a syntax error
  2929. if (!IsDoingFastScan() && (m_token.tk != tkDArrow || this->GetScanner()->FHadNewLine()))
  2930. {
  2931. Error(ERRValidIfFollowedBy, _u("Lambda parameter list"), _u("'=>' on the same line"));
  2932. }
  2933. if (buildAST)
  2934. {
  2935. pnode = CreateNodeForOpT<knopEmpty>();
  2936. }
  2937. break;
  2938. }
  2939. // Advance the block ID here in case this parenthetical expression turns out to be a lambda parameter list.
  2940. // That way the pid ref stacks will be created in their correct final form, and we can simply fix
  2941. // up function ID's.
  2942. uint saveNextBlockId = m_nextBlockId;
  2943. uint saveCurrBlockId = GetCurrentBlock()->blockId;
  2944. GetCurrentBlock()->blockId = m_nextBlockId++;
  2945. AutoDeferErrorsRestore deferErrorRestore(this);
  2946. this->m_funcParenExprDepth++;
  2947. pnode = ParseExpr<buildAST>(koplNo, &fCanAssign, TRUE, FALSE, nullptr, nullptr /*nameLength*/, nullptr /*pShortNameOffset*/, &term, true, nullptr, plastRParen);
  2948. this->m_funcParenExprDepth--;
  2949. if (buildAST && plastRParen)
  2950. {
  2951. *plastRParen = this->GetScanner()->IchLimTok();
  2952. }
  2953. ChkCurTok(tkRParen, ERRnoRparen);
  2954. GetCurrentBlock()->blockId = saveCurrBlockId;
  2955. if (m_token.tk == tkDArrow)
  2956. {
  2957. // We're going to rewind and reinterpret the expression as a parameter list.
  2958. // Put back the original next-block-ID so the existing pid ref stacks will be correct.
  2959. m_nextBlockId = saveNextBlockId;
  2960. }
  2961. else
  2962. {
  2963. // Emit a deferred ... error if one was parsed.
  2964. if (m_deferEllipsisError)
  2965. {
  2966. this->GetScanner()->SeekTo(m_deferEllipsisErrorLoc);
  2967. Error(ERRInvalidSpreadUse);
  2968. }
  2969. else if (m_deferCommaError)
  2970. {
  2971. // Emit a comma error if that was deferred.
  2972. this->GetScanner()->SeekTo(m_deferCommaErrorLoc);
  2973. Error(ERRsyntax);
  2974. }
  2975. }
  2976. break;
  2977. }
  2978. case tkIntCon:
  2979. if (IsStrictMode() && this->GetScanner()->IsOctOrLeadingZeroOnLastTKNumber())
  2980. {
  2981. Error(ERRES5NoOctal);
  2982. }
  2983. if (buildAST)
  2984. {
  2985. pnode = CreateIntNode(m_token.GetLong());
  2986. }
  2987. fCanAssign = FALSE;
  2988. this->GetScanner()->Scan();
  2989. break;
  2990. case tkBigIntCon:
  2991. if (IsStrictMode() && this->GetScanner()->IsOctOrLeadingZeroOnLastTKNumber())
  2992. {
  2993. Error(ERRES5NoOctal);
  2994. }
  2995. if (buildAST)
  2996. {
  2997. pnode = CreateBigIntNode(m_token.GetBigInt());
  2998. }
  2999. fCanAssign = FALSE;
  3000. this->GetScanner()->Scan();
  3001. break;
  3002. case tkFltCon:
  3003. if (IsStrictMode() && this->GetScanner()->IsOctOrLeadingZeroOnLastTKNumber())
  3004. {
  3005. Error(ERRES5NoOctal);
  3006. }
  3007. if (buildAST)
  3008. {
  3009. ParseNodeFloat * pnodeFloat;
  3010. pnode = pnodeFloat = CreateNodeForOpT<knopFlt>();
  3011. pnodeFloat->dbl = m_token.GetDouble();
  3012. pnodeFloat->maybeInt = m_token.GetDoubleMayBeInt();
  3013. }
  3014. fCanAssign = FALSE;
  3015. this->GetScanner()->Scan();
  3016. break;
  3017. case tkStrCon:
  3018. if (IsStrictMode() && this->GetScanner()->IsOctOrLeadingZeroOnLastTKNumber())
  3019. {
  3020. Error(ERRES5NoOctal);
  3021. }
  3022. if (buildAST)
  3023. {
  3024. pnode = CreateStrNode(m_token.GetStr());
  3025. }
  3026. else
  3027. {
  3028. // Subtract the string literal length from the total char count for the purpose
  3029. // of deciding whether to defer parsing and byte code generation.
  3030. this->ReduceDeferredScriptLength(this->GetScanner()->IchLimTok() - this->GetScanner()->IchMinTok());
  3031. }
  3032. fCanAssign = FALSE;
  3033. this->GetScanner()->Scan();
  3034. break;
  3035. case tkTRUE:
  3036. if (buildAST)
  3037. {
  3038. pnode = CreateNodeForOpT<knopTrue>();
  3039. }
  3040. fCanAssign = FALSE;
  3041. this->GetScanner()->Scan();
  3042. break;
  3043. case tkFALSE:
  3044. if (buildAST)
  3045. {
  3046. pnode = CreateNodeForOpT<knopFalse>();
  3047. }
  3048. fCanAssign = FALSE;
  3049. this->GetScanner()->Scan();
  3050. break;
  3051. case tkNULL:
  3052. if (buildAST)
  3053. {
  3054. pnode = CreateNodeForOpT<knopNull>();
  3055. }
  3056. fCanAssign = FALSE;
  3057. this->GetScanner()->Scan();
  3058. break;
  3059. case tkDiv:
  3060. case tkAsgDiv:
  3061. pnode = ParseRegExp<buildAST>();
  3062. fCanAssign = FALSE;
  3063. this->GetScanner()->Scan();
  3064. break;
  3065. case tkNEW:
  3066. {
  3067. ichMin = this->GetScanner()->IchMinTok();
  3068. iecpMin = this->GetScanner()->IecpMinTok();
  3069. this->GetScanner()->Scan();
  3070. if (m_token.tk == tkDot && m_scriptContext->GetConfig()->IsES6ClassAndExtendsEnabled())
  3071. {
  3072. pid = ParseMetaProperty<buildAST>(tkNEW, ichMin, &fCanAssign);
  3073. ichLim = this->GetScanner()->IchLimTok();
  3074. iecpLim = this->GetScanner()->IecpLimTok();
  3075. this->GetScanner()->Scan();
  3076. isSpecialName = true;
  3077. fCanAssign = FALSE;
  3078. goto LIdentifier;
  3079. }
  3080. else
  3081. {
  3082. ParseNodePtr pnodeExpr = ParseTerm<buildAST>(FALSE, pNameHint, pHintLength, pShortNameOffset, nullptr, false, TRUE, nullptr, nullptr, nullptr, plastRParen);
  3083. if (buildAST)
  3084. {
  3085. pnode = CreateCallNode(knopNew, pnodeExpr, nullptr);
  3086. pnode->ichMin = ichMin;
  3087. }
  3088. fInNew = TRUE;
  3089. fCanAssign = FALSE;
  3090. }
  3091. break;
  3092. }
  3093. case tkLBrack:
  3094. {
  3095. ichMin = this->GetScanner()->IchMinTok();
  3096. this->GetScanner()->Scan();
  3097. pnode = ParseArrayLiteral<buildAST>();
  3098. if (buildAST)
  3099. {
  3100. pnode->ichMin = ichMin;
  3101. pnode->ichLim = this->GetScanner()->IchLimTok();
  3102. }
  3103. if (this->m_arrayDepth == 0)
  3104. {
  3105. Assert(this->GetScanner()->IchLimTok() - ichMin > m_funcInArray);
  3106. this->ReduceDeferredScriptLength(this->GetScanner()->IchLimTok() - ichMin - this->m_funcInArray);
  3107. this->m_funcInArray = 0;
  3108. this->m_funcInArrayDepth = 0;
  3109. }
  3110. ChkCurTok(tkRBrack, ERRnoRbrack);
  3111. if (IsES6DestructuringEnabled() && pfLikelyPattern != nullptr && !IsPostFixOperators())
  3112. {
  3113. *pfLikelyPattern = TRUE;
  3114. }
  3115. fCanAssign = FALSE;
  3116. break;
  3117. }
  3118. case tkLCurly:
  3119. {
  3120. ichMin = this->GetScanner()->IchMinTok();
  3121. this->GetScanner()->ScanForcingPid();
  3122. ParseNodePtr pnodeMemberList = ParseMemberList<buildAST>(pNameHint, pHintLength);
  3123. if (buildAST)
  3124. {
  3125. pnode = CreateUniNode(knopObject, pnodeMemberList);
  3126. pnode->ichMin = ichMin;
  3127. pnode->ichLim = this->GetScanner()->IchLimTok();
  3128. }
  3129. ChkCurTok(tkRCurly, ERRnoRcurly);
  3130. if (IsES6DestructuringEnabled() && pfLikelyPattern != nullptr && !IsPostFixOperators())
  3131. {
  3132. *pfLikelyPattern = TRUE;
  3133. }
  3134. fCanAssign = FALSE;
  3135. break;
  3136. }
  3137. case tkFUNCTION:
  3138. {
  3139. LFunction:
  3140. if (m_grfscr & fscrDeferredFncExpression)
  3141. {
  3142. // The top-level deferred function body was defined by a function expression whose parsing was deferred. We are now
  3143. // parsing it, so unset the flag so that any nested functions are parsed normally. This flag is only applicable the
  3144. // first time we see it.
  3145. //
  3146. // Normally, deferred functions will be parsed in ParseStatement upon encountering the 'function' token. The first
  3147. // token of the source code of the function may not a 'function' token though, so we still need to reset this flag
  3148. // for the first function we parse. This can happen in compat modes, for instance, for a function expression enclosed
  3149. // in parentheses, where the legacy behavior was to include the parentheses in the function's source code.
  3150. m_grfscr &= ~fscrDeferredFncExpression;
  3151. }
  3152. ushort flags = fFncNoFlgs;
  3153. if (isLambdaExpr)
  3154. {
  3155. flags |= fFncLambda;
  3156. }
  3157. if (isAsyncExpr)
  3158. {
  3159. flags |= fFncAsync;
  3160. }
  3161. pnode = ParseFncDeclNoCheckScope<buildAST>(flags, SuperRestrictionState::Disallowed, pNameHint, /* needsPIDOnRCurlyScan */ false, fUnaryOrParen);
  3162. if (isAsyncExpr)
  3163. {
  3164. pnode->AsParseNodeFnc()->cbStringMin = iecpMin;
  3165. pnode->AsParseNodeFnc()->cbStringLim = pnode->AsParseNodeFnc()->cbLim;
  3166. }
  3167. fCanAssign = FALSE;
  3168. break;
  3169. }
  3170. case tkCLASS:
  3171. if (m_scriptContext->GetConfig()->IsES6ClassAndExtendsEnabled())
  3172. {
  3173. pnode = ParseClassDecl<buildAST>(FALSE, pNameHint, pHintLength, pShortNameOffset);
  3174. }
  3175. else
  3176. {
  3177. goto LUnknown;
  3178. }
  3179. fCanAssign = FALSE;
  3180. break;
  3181. case tkStrTmplBasic:
  3182. case tkStrTmplBegin:
  3183. pnode = ParseStringTemplateDecl<buildAST>(nullptr);
  3184. fCanAssign = FALSE;
  3185. break;
  3186. case tkIMPORT:
  3187. if (m_scriptContext->GetConfig()->IsES6ModuleEnabled())
  3188. {
  3189. ichMin = this->GetScanner()->IchMinTok();
  3190. iecpMin = this->GetScanner()->IecpMinTok();
  3191. this->GetScanner()->Scan();
  3192. switch (m_token.tk)
  3193. {
  3194. case tkLParen:
  3195. if (!m_scriptContext->GetConfig()->IsESDynamicImportEnabled())
  3196. {
  3197. goto LUnknown;
  3198. }
  3199. if (!fAllowCall)
  3200. {
  3201. Error(ERRTokenAfter, _u("import"), _u("new"));
  3202. }
  3203. pnode = ParseImportCall<buildAST>();
  3204. break;
  3205. case tkDot:
  3206. if (!(m_grfscr & fscrIsModuleCode) || !m_scriptContext->GetConfig()->IsESImportMetaEnabled())
  3207. {
  3208. goto LUnknown;
  3209. }
  3210. pid = ParseMetaProperty<buildAST>(tkIMPORT, ichMin, &fCanAssign);
  3211. ichLim = this->GetScanner()->IchLimTok();
  3212. iecpLim = this->GetScanner()->IecpLimTok();
  3213. this->GetScanner()->Scan();
  3214. isSpecialName = true;
  3215. goto LIdentifier;
  3216. default:
  3217. Error(ERRsyntax);
  3218. }
  3219. }
  3220. else
  3221. {
  3222. goto LUnknown;
  3223. }
  3224. break;
  3225. #if ENABLE_BACKGROUND_PARSING
  3226. case tkCASE:
  3227. {
  3228. if (!m_doingFastScan)
  3229. {
  3230. goto LUnknown;
  3231. }
  3232. ParseNodePtr pnodeUnused;
  3233. pnode = ParseCase<buildAST>(&pnodeUnused);
  3234. break;
  3235. }
  3236. case tkELSE:
  3237. if (!m_doingFastScan)
  3238. {
  3239. goto LUnknown;
  3240. }
  3241. this->GetScanner()->Scan();
  3242. ParseStatement<buildAST>();
  3243. break;
  3244. #endif
  3245. default:
  3246. LUnknown:
  3247. if (m_token.tk == tkNone)
  3248. {
  3249. Error(ERRInvalidIdentifier, m_token.GetIdentifier(this->GetHashTbl())->Psz(), GetTokenString(GetScanner()->GetPrevious()));
  3250. }
  3251. else if (m_token.IsKeyword())
  3252. {
  3253. Error(ERRKeywordAfter, GetTokenString(m_token.tk), GetTokenString(GetScanner()->GetPrevious()));
  3254. }
  3255. else
  3256. {
  3257. Error(ERRTokenAfter, GetTokenString(m_token.tk), GetTokenString(GetScanner()->GetPrevious()));
  3258. }
  3259. break;
  3260. }
  3261. pnode = ParsePostfixOperators<buildAST>(pnode, fAllowCall, fInNew, isAsyncExpr, fCanAssignToCall, &fCanAssign, &term, pfIsDotOrIndex);
  3262. if (savedTopAsyncRef != nullptr &&
  3263. this->m_token.tk == tkDArrow)
  3264. {
  3265. // This is an async arrow function; we're going to back up and reparse it.
  3266. // Make sure we don't leave behind a bogus reference to the 'async' identifier.
  3267. for (pid = wellKnownPropertyPids.async; pid->GetTopRef() != savedTopAsyncRef;)
  3268. {
  3269. Assert(pid->GetTopRef() != nullptr);
  3270. pid->RemovePrevPidRef(nullptr);
  3271. }
  3272. }
  3273. // Pass back identifier if requested
  3274. if (pToken && term.tk == tkID)
  3275. {
  3276. *pToken = term;
  3277. }
  3278. if (pfCanAssign)
  3279. {
  3280. *pfCanAssign = fCanAssign;
  3281. }
  3282. return pnode;
  3283. }
  3284. template <bool buildAST>
  3285. ParseNodeRegExp * Parser::ParseRegExp()
  3286. {
  3287. ParseNodeRegExp * pnode = nullptr;
  3288. if (buildAST || IsDoingFastScan())
  3289. {
  3290. this->GetScanner()->RescanRegExp();
  3291. #if ENABLE_BACKGROUND_PARSING
  3292. BOOL saveDeferringAST = this->m_deferringAST;
  3293. if (m_doingFastScan)
  3294. {
  3295. this->m_deferringAST = false;
  3296. }
  3297. #endif
  3298. pnode = CreateNodeForOpT<knopRegExp>();
  3299. pnode->regexPattern = m_token.GetRegex();
  3300. #if ENABLE_BACKGROUND_PARSING
  3301. if (m_doingFastScan)
  3302. {
  3303. this->m_deferringAST = saveDeferringAST;
  3304. this->AddFastScannedRegExpNode(pnode);
  3305. if (!buildAST)
  3306. {
  3307. pnode = nullptr;
  3308. }
  3309. }
  3310. else if (this->IsBackgroundParser())
  3311. {
  3312. Assert(pnode->regexPattern == nullptr);
  3313. this->AddBackgroundRegExpNode(pnode);
  3314. }
  3315. #endif
  3316. }
  3317. else
  3318. {
  3319. this->GetScanner()->RescanRegExpNoAST();
  3320. }
  3321. Assert(m_token.tk == tkRegExp);
  3322. return pnode;
  3323. }
  3324. BOOL Parser::NodeIsEvalName(ParseNodePtr pnode)
  3325. {
  3326. //WOOB 1107758 Special case of indirect eval binds to local scope in standards mode
  3327. return pnode->nop == knopName && (pnode->AsParseNodeName()->pid == wellKnownPropertyPids.eval);
  3328. }
  3329. BOOL Parser::NodeIsSuperName(ParseNodePtr pnode)
  3330. {
  3331. return pnode->nop == knopName && (pnode->AsParseNodeName()->pid == wellKnownPropertyPids._superConstructor);
  3332. }
  3333. BOOL Parser::NodeEqualsName(ParseNodePtr pnode, LPCOLESTR sz, uint32 cch)
  3334. {
  3335. return pnode->nop == knopName &&
  3336. pnode->AsParseNodeName()->pid->Cch() == cch &&
  3337. !wmemcmp(pnode->AsParseNodeName()->pid->Psz(), sz, cch);
  3338. }
  3339. BOOL Parser::NodeIsIdent(ParseNodePtr pnode, IdentPtr pid)
  3340. {
  3341. for (;;)
  3342. {
  3343. switch (pnode->nop)
  3344. {
  3345. case knopName:
  3346. return (pnode->AsParseNodeName()->pid == pid);
  3347. case knopComma:
  3348. pnode = pnode->AsParseNodeBin()->pnode2;
  3349. break;
  3350. default:
  3351. return FALSE;
  3352. }
  3353. }
  3354. }
  3355. template<bool buildAST>
  3356. ParseNodePtr Parser::ParsePostfixOperators(
  3357. ParseNodePtr pnode,
  3358. BOOL fAllowCall,
  3359. BOOL fInNew,
  3360. BOOL isAsyncExpr,
  3361. BOOL fCanAssignToCallResult,
  3362. BOOL *pfCanAssign,
  3363. _Inout_ IdentToken* pToken,
  3364. _Out_opt_ bool* pfIsDotOrIndex /*= nullptr */)
  3365. {
  3366. uint16 count = 0;
  3367. bool callOfConstants = false;
  3368. if (pfIsDotOrIndex)
  3369. {
  3370. *pfIsDotOrIndex = false;
  3371. }
  3372. for (;;)
  3373. {
  3374. uint16 spreadArgCount = 0;
  3375. switch (m_token.tk)
  3376. {
  3377. case tkLParen:
  3378. {
  3379. AutoMarkInParsingArgs autoMarkInParsingArgs(this);
  3380. if (fInNew)
  3381. {
  3382. ParseNodePtr pnodeArgs = ParseArgList<buildAST>(&callOfConstants, &spreadArgCount, &count);
  3383. if (buildAST)
  3384. {
  3385. Assert(pnode->nop == knopNew);
  3386. Assert(pnode->AsParseNodeCall()->pnodeArgs == nullptr);
  3387. pnode->AsParseNodeCall()->pnodeArgs = pnodeArgs;
  3388. pnode->AsParseNodeCall()->callOfConstants = callOfConstants;
  3389. pnode->AsParseNodeCall()->isApplyCall = false;
  3390. pnode->AsParseNodeCall()->isEvalCall = false;
  3391. pnode->AsParseNodeCall()->isSuperCall = false;
  3392. pnode->AsParseNodeCall()->hasDestructuring = m_hasDestructuringPattern;
  3393. Assert(!m_hasDestructuringPattern || count > 0);
  3394. pnode->AsParseNodeCall()->argCount = count;
  3395. pnode->AsParseNodeCall()->spreadArgCount = spreadArgCount;
  3396. pnode->ichLim = this->GetScanner()->IchLimTok();
  3397. }
  3398. else
  3399. {
  3400. pnode = nullptr;
  3401. pToken->tk = tkNone; // This is no longer an identifier
  3402. }
  3403. fInNew = FALSE;
  3404. ChkCurTok(tkRParen, ERRnoRparen);
  3405. }
  3406. else
  3407. {
  3408. if (!fAllowCall)
  3409. {
  3410. return pnode;
  3411. }
  3412. uint saveNextBlockId = m_nextBlockId;
  3413. uint saveCurrBlockId = GetCurrentBlock()->blockId;
  3414. if (isAsyncExpr)
  3415. {
  3416. // Advance the block ID here in case this parenthetical expression turns out to be a lambda parameter list.
  3417. // That way the pid ref stacks will be created in their correct final form, and we can simply fix
  3418. // up function ID's.
  3419. GetCurrentBlock()->blockId = m_nextBlockId++;
  3420. }
  3421. ParseNodePtr pnodeArgs = ParseArgList<buildAST>(&callOfConstants, &spreadArgCount, &count);
  3422. // We used to un-defer a deferred function body here if it was called as part of the expression that declared it.
  3423. // We now detect this case up front in ParseFncDecl, which is cheaper and simpler.
  3424. if (buildAST)
  3425. {
  3426. bool fCallIsEval = false;
  3427. // Detect super()
  3428. if (this->NodeIsSuperName(pnode))
  3429. {
  3430. pnode = CreateSuperCallNode(pnode->AsParseNodeSpecialName(), pnodeArgs);
  3431. Assert(pnode);
  3432. pnode->AsParseNodeSuperCall()->pnodeThis = ReferenceSpecialName(wellKnownPropertyPids._this, pnode->ichMin, this->GetScanner()->IchLimTok(), true);
  3433. pnode->AsParseNodeSuperCall()->pnodeNewTarget = ReferenceSpecialName(wellKnownPropertyPids._newTarget, pnode->ichMin, this->GetScanner()->IchLimTok(), true);
  3434. }
  3435. else
  3436. {
  3437. pnode = CreateCallNode(knopCall, pnode, pnodeArgs);
  3438. Assert(pnode);
  3439. }
  3440. // Detect call to "eval" and record it on the function.
  3441. // Note: we used to leave it up to the byte code generator to detect eval calls
  3442. // at global scope, but now it relies on the flag the parser sets, so set it here.
  3443. if (count > 0 && this->NodeIsEvalName(pnode->AsParseNodeCall()->pnodeTarget))
  3444. {
  3445. this->MarkEvalCaller();
  3446. fCallIsEval = true;
  3447. // Eval may reference any of the special symbols so we need to push refs to them here.
  3448. ReferenceSpecialName(wellKnownPropertyPids._this);
  3449. ReferenceSpecialName(wellKnownPropertyPids._newTarget);
  3450. ReferenceSpecialName(wellKnownPropertyPids._super);
  3451. ReferenceSpecialName(wellKnownPropertyPids._superConstructor);
  3452. ReferenceSpecialName(wellKnownPropertyPids.arguments);
  3453. }
  3454. pnode->AsParseNodeCall()->callOfConstants = callOfConstants;
  3455. pnode->AsParseNodeCall()->spreadArgCount = spreadArgCount;
  3456. pnode->AsParseNodeCall()->isApplyCall = false;
  3457. pnode->AsParseNodeCall()->isEvalCall = fCallIsEval;
  3458. pnode->AsParseNodeCall()->hasDestructuring = m_hasDestructuringPattern;
  3459. Assert(!m_hasDestructuringPattern || count > 0);
  3460. pnode->AsParseNodeCall()->argCount = count;
  3461. pnode->ichLim = this->GetScanner()->IchLimTok();
  3462. }
  3463. else
  3464. {
  3465. pnode = nullptr;
  3466. if (pToken->tk == tkID && pToken->pid == wellKnownPropertyPids.eval && count > 0) // Detect eval
  3467. {
  3468. this->MarkEvalCaller();
  3469. ReferenceSpecialName(wellKnownPropertyPids._this);
  3470. ReferenceSpecialName(wellKnownPropertyPids._newTarget);
  3471. ReferenceSpecialName(wellKnownPropertyPids._super);
  3472. ReferenceSpecialName(wellKnownPropertyPids._superConstructor);
  3473. ReferenceSpecialName(wellKnownPropertyPids.arguments);
  3474. }
  3475. pToken->tk = tkNone; // This is no longer an identifier
  3476. }
  3477. ChkCurTok(tkRParen, ERRnoRparen);
  3478. if (isAsyncExpr)
  3479. {
  3480. GetCurrentBlock()->blockId = saveCurrBlockId;
  3481. if (m_token.tk == tkDArrow)
  3482. {
  3483. // We're going to rewind and reinterpret the expression as a parameter list.
  3484. // Put back the original next-block-ID so the existing pid ref stacks will be correct.
  3485. m_nextBlockId = saveNextBlockId;
  3486. }
  3487. }
  3488. }
  3489. if (pfCanAssign)
  3490. {
  3491. *pfCanAssign = fCanAssignToCallResult &&
  3492. (m_sourceContextInfo ?
  3493. !PHASE_ON_RAW(Js::EarlyErrorOnAssignToCallPhase, m_sourceContextInfo->sourceContextId, GetCurrentFunctionNode()->functionId) :
  3494. !PHASE_ON1(Js::EarlyErrorOnAssignToCallPhase));
  3495. }
  3496. if (pfIsDotOrIndex)
  3497. {
  3498. *pfIsDotOrIndex = false;
  3499. }
  3500. break;
  3501. }
  3502. case tkLBrack:
  3503. {
  3504. this->GetScanner()->Scan();
  3505. IdentToken tok;
  3506. ParseNodePtr pnodeExpr = ParseExpr<buildAST>(0, FALSE, TRUE, FALSE, nullptr, nullptr, nullptr, &tok);
  3507. if (buildAST)
  3508. {
  3509. AnalysisAssert(pnodeExpr);
  3510. if (pnode && pnode->nop == knopName && pnode->AsParseNodeName()->IsSpecialName() && pnode->AsParseNodeSpecialName()->isSuper)
  3511. {
  3512. pnode = CreateSuperReferenceNode(knopIndex, pnode->AsParseNodeSpecialName(), pnodeExpr);
  3513. pnode->AsParseNodeSuperReference()->pnodeThis = ReferenceSpecialName(wellKnownPropertyPids._this, pnode->ichMin, pnode->ichLim, true);
  3514. }
  3515. else
  3516. {
  3517. pnode = CreateBinNode(knopIndex, pnode, pnodeExpr);
  3518. }
  3519. AnalysisAssert(pnode);
  3520. pnode->ichLim = this->GetScanner()->IchLimTok();
  3521. }
  3522. else
  3523. {
  3524. pnode = nullptr;
  3525. pToken->tk = tkNone; // This is no longer an identifier
  3526. }
  3527. ChkCurTok(tkRBrack, ERRnoRbrack);
  3528. if (pfCanAssign)
  3529. {
  3530. *pfCanAssign = TRUE;
  3531. }
  3532. if (pfIsDotOrIndex)
  3533. {
  3534. *pfIsDotOrIndex = true;
  3535. }
  3536. PidRefStack * topPidRef = nullptr;
  3537. if (buildAST)
  3538. {
  3539. if (pnodeExpr && pnodeExpr->nop == knopName)
  3540. {
  3541. topPidRef = pnodeExpr->AsParseNodeName()->pid->GetTopRef();
  3542. }
  3543. }
  3544. else if (tok.tk == tkID)
  3545. {
  3546. topPidRef = tok.pid->GetTopRef();
  3547. }
  3548. if (topPidRef)
  3549. {
  3550. topPidRef->SetIsUsedInLdElem(true);
  3551. }
  3552. if (!buildAST)
  3553. {
  3554. break;
  3555. }
  3556. bool shouldConvertToDot = false;
  3557. if (pnode->AsParseNodeBin()->pnode2->nop == knopStr)
  3558. {
  3559. // if the string is empty or contains escape character, we will not convert them to dot node
  3560. shouldConvertToDot = pnode->AsParseNodeBin()->pnode2->AsParseNodeStr()->pid->Cch() > 0 && !this->GetScanner()->IsEscapeOnLastTkStrCon();
  3561. }
  3562. if (shouldConvertToDot)
  3563. {
  3564. LPCOLESTR str = pnode->AsParseNodeBin()->pnode2->AsParseNodeStr()->pid->Psz();
  3565. // See if we can convert o["p"] into o.p and o["0"] into o[0] since they're equivalent and the latter forms
  3566. // are faster
  3567. uint32 uintValue;
  3568. if (Js::JavascriptOperators::TryConvertToUInt32(
  3569. str,
  3570. pnode->AsParseNodeBin()->pnode2->AsParseNodeStr()->pid->Cch(),
  3571. &uintValue) &&
  3572. !Js::TaggedInt::IsOverflow(uintValue)) // the optimization is not very useful if the number can't be represented as a TaggedInt
  3573. {
  3574. // No need to verify that uintValue != JavascriptArray::InvalidIndex since all nonnegative TaggedInts are valid indexes
  3575. auto intNode = CreateIntNode(uintValue); // implicit conversion from uint32 to int32
  3576. pnode->AsParseNodeBin()->pnode2 = intNode;
  3577. }
  3578. // Field optimization (see GlobOpt::KillLiveElems) checks for value being a Number,
  3579. // and since NaN/Infinity is a number it won't kill o.NaN/o.Infinity which would cause a problem
  3580. // if we decide to hoist o.NaN/o.Infinity.
  3581. // We need to keep o["NaN"] and o["+/-Infinity"] as array element access (we don't hoist that but we may hoist field access),
  3582. // so no matter if it's killed by o[x] inside a loop, we make sure that we never hoist these.
  3583. // We need to follow same logic for strings that convert to a floating point number.
  3584. else
  3585. {
  3586. bool doConvertToProperty = false; // Convert a["x"] -> a.x.
  3587. if (!Parser::IsNaNOrInfinityLiteral<true>(str))
  3588. {
  3589. const OLECHAR* terminalChar;
  3590. double dbl = Js::NumberUtilities::StrToDbl(str, &terminalChar, m_scriptContext);
  3591. bool convertsToFloat = !Js::NumberUtilities::IsNan(dbl);
  3592. doConvertToProperty = !convertsToFloat;
  3593. }
  3594. if (doConvertToProperty)
  3595. {
  3596. ParseNodeName * pnodeNewExpr = CreateNameNode(pnodeExpr->AsParseNodeStr()->pid);
  3597. pnodeNewExpr->ichMin = pnodeExpr->ichMin;
  3598. pnodeNewExpr->ichLim = pnodeExpr->ichLim;
  3599. pnode->AsParseNodeBin()->pnode2 = pnodeNewExpr;
  3600. pnode->nop = knopDot;
  3601. pnode->grfpn |= PNodeFlags::fpnIndexOperator;
  3602. }
  3603. }
  3604. }
  3605. }
  3606. break;
  3607. case tkDot:
  3608. {
  3609. ParseNodePtr name = nullptr;
  3610. OpCode opCode = knopDot;
  3611. this->GetScanner()->Scan();
  3612. if (!m_token.IsIdentifier())
  3613. {
  3614. //allow reserved words in ES5 mode
  3615. if (!(m_token.IsReservedWord()))
  3616. {
  3617. IdentifierExpectedError(m_token);
  3618. }
  3619. }
  3620. // Note: see comment above about field optimization WRT NaN/Infinity/-Infinity.
  3621. // Convert a.Nan, a.Infinity into a["NaN"], a["Infinity"].
  3622. // We don't care about -Infinity case here because x.-Infinity is invalid in JavaScript.
  3623. // Both NaN and Infinity are identifiers.
  3624. else if (buildAST && Parser::IsNaNOrInfinityLiteral<false>(m_token.GetIdentifier(this->GetHashTbl())->Psz()))
  3625. {
  3626. opCode = knopIndex;
  3627. }
  3628. if (buildAST)
  3629. {
  3630. if (opCode == knopDot)
  3631. {
  3632. name = CreateNameNode(m_token.GetIdentifier(this->GetHashTbl()));
  3633. }
  3634. else
  3635. {
  3636. Assert(opCode == knopIndex);
  3637. name = CreateStrNode(m_token.GetIdentifier(this->GetHashTbl()));
  3638. }
  3639. if (pnode && pnode->nop == knopName && pnode->AsParseNodeName()->IsSpecialName() && pnode->AsParseNodeSpecialName()->isSuper)
  3640. {
  3641. pnode = CreateSuperReferenceNode(opCode, pnode->AsParseNodeSpecialName(), name);
  3642. pnode->AsParseNodeSuperReference()->pnodeThis = ReferenceSpecialName(wellKnownPropertyPids._this, pnode->ichMin, pnode->ichLim, true);
  3643. }
  3644. else
  3645. {
  3646. pnode = CreateBinNode(opCode, pnode, name);
  3647. }
  3648. }
  3649. else
  3650. {
  3651. pnode = nullptr;
  3652. pToken->tk = tkNone;
  3653. }
  3654. if (pfCanAssign)
  3655. {
  3656. *pfCanAssign = TRUE;
  3657. }
  3658. if (pfIsDotOrIndex)
  3659. {
  3660. *pfIsDotOrIndex = true;
  3661. }
  3662. this->GetScanner()->Scan();
  3663. break;
  3664. }
  3665. case tkStrTmplBasic:
  3666. case tkStrTmplBegin:
  3667. {
  3668. ParseNode* templateNode = nullptr;
  3669. if (pnode != nullptr)
  3670. {
  3671. AutoMarkInParsingArgs autoMarkInParsingArgs(this);
  3672. templateNode = ParseStringTemplateDecl<buildAST>(pnode);
  3673. }
  3674. else
  3675. {
  3676. templateNode = ParseStringTemplateDecl<buildAST>(pnode);
  3677. }
  3678. if (!buildAST)
  3679. {
  3680. pToken->tk = tkNone; // This is no longer an identifier
  3681. }
  3682. pnode = templateNode;
  3683. if (pfCanAssign)
  3684. {
  3685. *pfCanAssign = FALSE;
  3686. }
  3687. if (pfIsDotOrIndex)
  3688. {
  3689. *pfIsDotOrIndex = false;
  3690. }
  3691. break;
  3692. }
  3693. default:
  3694. return pnode;
  3695. }
  3696. }
  3697. }
  3698. /***************************************************************************
  3699. Look for an existing label with the given name.
  3700. ***************************************************************************/
  3701. bool Parser::LabelExists(IdentPtr pid, LabelId* pLabelIdList)
  3702. {
  3703. StmtNest dummy;
  3704. dummy.pLabelId = pLabelIdList;
  3705. dummy.pstmtOuter = m_pstmtCur;
  3706. // Look through each label list for the current stack of statements
  3707. for (StmtNest* pStmt = &dummy; pStmt != nullptr; pStmt = pStmt->pstmtOuter)
  3708. {
  3709. for (LabelId* pLabelId = pStmt->pLabelId; pLabelId != nullptr; pLabelId = pLabelId->next)
  3710. {
  3711. if (pLabelId->pid == pid)
  3712. return true;
  3713. }
  3714. }
  3715. return false;
  3716. }
  3717. // Currently only ints and floats are treated as constants in function call
  3718. // TODO: Check if we need for other constants as well
  3719. BOOL Parser::IsConstantInFunctionCall(ParseNodePtr pnode)
  3720. {
  3721. if (pnode->nop == knopInt && !Js::TaggedInt::IsOverflow(pnode->AsParseNodeInt()->lw))
  3722. {
  3723. return TRUE;
  3724. }
  3725. if (pnode->nop == knopFlt)
  3726. {
  3727. return TRUE;
  3728. }
  3729. return FALSE;
  3730. }
  3731. /***************************************************************************
  3732. Parse a list of arguments.
  3733. ***************************************************************************/
  3734. template<bool buildAST>
  3735. ParseNodePtr Parser::ParseArgList(bool *pCallOfConstants, uint16 *pSpreadArgCount, uint16 * pCount)
  3736. {
  3737. ParseNodePtr pnodeArg;
  3738. ParseNodePtr pnodeList = nullptr;
  3739. ParseNodePtr *lastNodeRef = nullptr;
  3740. // Check for an empty list
  3741. Assert(m_token.tk == tkLParen);
  3742. if (this->GetScanner()->Scan() == tkRParen)
  3743. {
  3744. return nullptr;
  3745. }
  3746. *pCallOfConstants = true;
  3747. *pSpreadArgCount = 0;
  3748. int count = 0;
  3749. while (true)
  3750. {
  3751. if (count >= Js::Constants::MaxAllowedArgs)
  3752. {
  3753. Error(ERRTooManyArgs);
  3754. }
  3755. // Allow spread in argument lists.
  3756. IdentToken token;
  3757. pnodeArg = ParseExpr<buildAST>(koplCma, nullptr, TRUE, /* fAllowEllipsis */TRUE, NULL, nullptr, nullptr, &token);
  3758. ++count;
  3759. this->MarkEscapingRef(pnodeArg, &token);
  3760. if (buildAST)
  3761. {
  3762. this->CheckArguments(pnodeArg);
  3763. if (*pCallOfConstants && !IsConstantInFunctionCall(pnodeArg))
  3764. {
  3765. *pCallOfConstants = false;
  3766. }
  3767. if (pnodeArg->nop == knopEllipsis)
  3768. {
  3769. (*pSpreadArgCount)++;
  3770. }
  3771. AddToNodeListEscapedUse(&pnodeList, &lastNodeRef, pnodeArg);
  3772. }
  3773. if (m_token.tk != tkComma)
  3774. {
  3775. break;
  3776. }
  3777. this->GetScanner()->Scan();
  3778. if (m_token.tk == tkRParen && m_scriptContext->GetConfig()->IsES7TrailingCommaEnabled())
  3779. {
  3780. break;
  3781. }
  3782. }
  3783. if (pSpreadArgCount != nullptr && (*pSpreadArgCount) > 0) {
  3784. CHAKRATEL_LANGSTATS_INC_LANGFEATURECOUNT(ES6, SpreadFeature, m_scriptContext);
  3785. }
  3786. *pCount = static_cast<uint16>(count);
  3787. if (buildAST)
  3788. {
  3789. Assert(lastNodeRef);
  3790. Assert(*lastNodeRef);
  3791. pnodeList->ichLim = (*lastNodeRef)->ichLim;
  3792. }
  3793. return pnodeList;
  3794. }
  3795. // Currently only ints are treated as constants in ArrayLiterals
  3796. BOOL Parser::IsConstantInArrayLiteral(ParseNodePtr pnode)
  3797. {
  3798. if (pnode->nop == knopInt && !Js::TaggedInt::IsOverflow(pnode->AsParseNodeInt()->lw))
  3799. {
  3800. return TRUE;
  3801. }
  3802. return FALSE;
  3803. }
  3804. template<bool buildAST>
  3805. ParseNodeArrLit * Parser::ParseArrayLiteral()
  3806. {
  3807. ParseNodeArrLit * pnode = nullptr;
  3808. bool arrayOfTaggedInts = false;
  3809. bool arrayOfInts = false;
  3810. bool arrayOfNumbers = false;
  3811. bool hasMissingValues = false;
  3812. uint count = 0;
  3813. uint spreadCount = 0;
  3814. ParseNodePtr pnode1 = ParseArrayList<buildAST>(&arrayOfTaggedInts, &arrayOfInts, &arrayOfNumbers, &hasMissingValues, &count, &spreadCount);
  3815. if (buildAST)
  3816. {
  3817. pnode = CreateNodeForOpT<knopArray>();
  3818. pnode->pnode1 = pnode1;
  3819. pnode->arrayOfTaggedInts = arrayOfTaggedInts;
  3820. pnode->arrayOfInts = arrayOfInts;
  3821. pnode->arrayOfNumbers = arrayOfNumbers;
  3822. pnode->hasMissingValues = hasMissingValues;
  3823. pnode->count = count;
  3824. pnode->spreadCount = spreadCount;
  3825. if (pnode->pnode1)
  3826. {
  3827. this->CheckArguments(pnode->pnode1);
  3828. }
  3829. }
  3830. return pnode;
  3831. }
  3832. /***************************************************************************
  3833. Create an ArrayLiteral node
  3834. Parse a list of array elements. [ a, b, , c, ]
  3835. ***************************************************************************/
  3836. template<bool buildAST>
  3837. ParseNodePtr Parser::ParseArrayList(bool *pArrayOfTaggedInts, bool *pArrayOfInts, bool *pArrayOfNumbers, bool *pHasMissingValues, uint *count, uint *spreadCount)
  3838. {
  3839. ParseNodePtr pnodeArg = nullptr;
  3840. ParseNodePtr pnodeList = nullptr;
  3841. ParseNodePtr *lastNodeRef = nullptr;
  3842. *count = 0;
  3843. // Check for an empty list
  3844. if (tkRBrack == m_token.tk)
  3845. {
  3846. return nullptr;
  3847. }
  3848. this->m_arrayDepth++;
  3849. bool arrayOfTaggedInts = buildAST;
  3850. bool arrayOfInts = buildAST;
  3851. bool arrayOfNumbers = buildAST;
  3852. bool arrayOfVarInts = false;
  3853. bool hasMissingValues = false;
  3854. for (;;)
  3855. {
  3856. (*count)++;
  3857. if (tkComma == m_token.tk || tkRBrack == m_token.tk)
  3858. {
  3859. hasMissingValues = true;
  3860. arrayOfTaggedInts = false;
  3861. arrayOfInts = false;
  3862. arrayOfNumbers = false;
  3863. if (buildAST)
  3864. {
  3865. pnodeArg = CreateNodeForOpT<knopEmpty>();
  3866. }
  3867. }
  3868. else
  3869. {
  3870. // Allow Spread in array literals.
  3871. pnodeArg = ParseExpr<buildAST>(koplCma, nullptr, TRUE, /* fAllowEllipsis */ TRUE);
  3872. if (buildAST)
  3873. {
  3874. if (pnodeArg->nop == knopEllipsis)
  3875. {
  3876. (*spreadCount)++;
  3877. }
  3878. this->CheckArguments(pnodeArg);
  3879. }
  3880. }
  3881. #if DEBUG
  3882. if (m_grfscr & fscrEnforceJSON && !IsJSONValid(pnodeArg))
  3883. {
  3884. Error(ERRsyntax);
  3885. }
  3886. #endif
  3887. if (buildAST)
  3888. {
  3889. if (arrayOfNumbers)
  3890. {
  3891. if (pnodeArg->nop != knopInt)
  3892. {
  3893. arrayOfTaggedInts = false;
  3894. if (pnodeArg->nop != knopFlt)
  3895. {
  3896. // Not an array of constants.
  3897. arrayOfInts = false;
  3898. arrayOfNumbers = false;
  3899. }
  3900. else if (arrayOfInts && Js::JavascriptNumber::IsInt32OrUInt32(pnodeArg->AsParseNodeFloat()->dbl) && (!Js::JavascriptNumber::IsInt32(pnodeArg->AsParseNodeFloat()->dbl) || pnodeArg->AsParseNodeFloat()->dbl == -2147483648.0))
  3901. {
  3902. // We've seen nothing but ints, and this is a uint32 but not an int32.
  3903. // Unless we see an actual float at some point, we want an array of vars
  3904. // so we can work with tagged ints.
  3905. arrayOfVarInts = true;
  3906. }
  3907. else
  3908. {
  3909. // Not an int array, but it may still be a float array.
  3910. arrayOfInts = false;
  3911. }
  3912. }
  3913. else
  3914. {
  3915. if (Js::SparseArraySegment<int32>::IsMissingItem((int32*)&pnodeArg->AsParseNodeInt()->lw))
  3916. {
  3917. arrayOfInts = false;
  3918. }
  3919. if (Js::TaggedInt::IsOverflow(pnodeArg->AsParseNodeInt()->lw))
  3920. {
  3921. arrayOfTaggedInts = false;
  3922. }
  3923. }
  3924. }
  3925. AddToNodeListEscapedUse(&pnodeList, &lastNodeRef, pnodeArg);
  3926. }
  3927. if (tkComma != m_token.tk)
  3928. {
  3929. break;
  3930. }
  3931. this->GetScanner()->Scan();
  3932. if (tkRBrack == m_token.tk)
  3933. {
  3934. break;
  3935. }
  3936. }
  3937. if (spreadCount != nullptr && *spreadCount > 0) {
  3938. CHAKRATEL_LANGSTATS_INC_LANGFEATURECOUNT(ES6, SpreadFeature, m_scriptContext);
  3939. }
  3940. if (buildAST)
  3941. {
  3942. Assert(lastNodeRef);
  3943. Assert(*lastNodeRef);
  3944. pnodeList->ichLim = (*lastNodeRef)->ichLim;
  3945. if (arrayOfVarInts && arrayOfInts)
  3946. {
  3947. arrayOfInts = false;
  3948. arrayOfNumbers = false;
  3949. }
  3950. *pArrayOfTaggedInts = arrayOfTaggedInts;
  3951. *pArrayOfInts = arrayOfInts;
  3952. *pArrayOfNumbers = arrayOfNumbers;
  3953. *pHasMissingValues = hasMissingValues;
  3954. }
  3955. this->m_arrayDepth--;
  3956. return pnodeList;
  3957. }
  3958. Parser::MemberNameToTypeMap* Parser::CreateMemberNameMap(ArenaAllocator* pAllocator)
  3959. {
  3960. Assert(pAllocator);
  3961. return Anew(pAllocator, MemberNameToTypeMap, pAllocator, 5);
  3962. }
  3963. template<bool buildAST> void Parser::ParseComputedName(ParseNodePtr* ppnodeName, LPCOLESTR* ppNameHint, LPCOLESTR* ppFullNameHint, uint32 *pNameLength, uint32 *pShortNameOffset)
  3964. {
  3965. this->GetScanner()->Scan();
  3966. ParseNodePtr pnodeNameExpr = ParseExpr<buildAST>(koplCma, nullptr, TRUE, FALSE, *ppNameHint, pNameLength, pShortNameOffset);
  3967. if (buildAST)
  3968. {
  3969. *ppnodeName = CreateUniNode(knopComputedName, pnodeNameExpr, pnodeNameExpr->ichMin, pnodeNameExpr->ichLim);
  3970. }
  3971. if (ppFullNameHint && buildAST && CONFIG_FLAG(UseFullName))
  3972. {
  3973. *ppFullNameHint = FormatPropertyString(*ppNameHint, pnodeNameExpr, pNameLength, pShortNameOffset);
  3974. }
  3975. ChkCurTokNoScan(tkRBrack, ERRnoRbrack);
  3976. }
  3977. /***************************************************************************
  3978. Parse a list of object set/get members, e.g.:
  3979. { get foo(){ ... }, set bar(arg) { ... } }
  3980. ***************************************************************************/
  3981. template<bool buildAST>
  3982. ParseNodeBin * Parser::ParseMemberGetSet(OpCode nop, LPCOLESTR* ppNameHint, size_t iecpMin, charcount_t ichMin)
  3983. {
  3984. ParseNodePtr pnodeName = nullptr;
  3985. Assert(nop == knopGetMember || nop == knopSetMember);
  3986. Assert(ppNameHint);
  3987. IdentPtr pid = nullptr;
  3988. bool isComputedName = false;
  3989. *ppNameHint = nullptr;
  3990. switch (m_token.tk)
  3991. {
  3992. default:
  3993. if (!m_token.IsReservedWord())
  3994. {
  3995. Error(ERRnoMemberIdent);
  3996. }
  3997. // fall through
  3998. case tkID:
  3999. pid = m_token.GetIdentifier(this->GetHashTbl());
  4000. *ppNameHint = pid->Psz();
  4001. if (buildAST)
  4002. {
  4003. pnodeName = CreateStrNode(pid);
  4004. }
  4005. break;
  4006. case tkStrCon:
  4007. if (IsStrictMode() && this->GetScanner()->IsOctOrLeadingZeroOnLastTKNumber())
  4008. {
  4009. Error(ERRES5NoOctal);
  4010. }
  4011. pid = m_token.GetStr();
  4012. *ppNameHint = pid->Psz();
  4013. if (buildAST)
  4014. {
  4015. pnodeName = CreateStrNode(pid);
  4016. }
  4017. break;
  4018. case tkIntCon:
  4019. if (IsStrictMode() && this->GetScanner()->IsOctOrLeadingZeroOnLastTKNumber())
  4020. {
  4021. Error(ERRES5NoOctal);
  4022. }
  4023. pid = this->GetScanner()->PidFromLong(m_token.GetLong());
  4024. if (buildAST)
  4025. {
  4026. pnodeName = CreateStrNode(pid);
  4027. }
  4028. break;
  4029. case tkFltCon:
  4030. if (IsStrictMode() && this->GetScanner()->IsOctOrLeadingZeroOnLastTKNumber())
  4031. {
  4032. Error(ERRES5NoOctal);
  4033. }
  4034. pid = this->GetScanner()->PidFromDbl(m_token.GetDouble());
  4035. if (buildAST)
  4036. {
  4037. pnodeName = CreateStrNode(pid);
  4038. }
  4039. break;
  4040. case tkLBrack:
  4041. // Computed property name: get|set [expr] () { }
  4042. if (!m_scriptContext->GetConfig()->IsES6ObjectLiteralsEnabled())
  4043. {
  4044. Error(ERRnoMemberIdent);
  4045. }
  4046. LPCOLESTR emptyHint = nullptr;
  4047. uint32 offset = 0;
  4048. ParseComputedName<buildAST>(&pnodeName, &emptyHint, ppNameHint, &offset);
  4049. isComputedName = true;
  4050. break;
  4051. }
  4052. MemberType memberType;
  4053. ushort flags = fFncMethod | fFncNoName;
  4054. if (nop == knopGetMember)
  4055. {
  4056. memberType = MemberTypeGetter;
  4057. flags |= fFncNoArg;
  4058. }
  4059. else
  4060. {
  4061. Assert(nop == knopSetMember);
  4062. memberType = MemberTypeSetter;
  4063. flags |= fFncOneArg;
  4064. }
  4065. ParseNodeFnc * pnodeFnc = ParseFncDeclNoCheckScope<buildAST>(flags, SuperRestrictionState::PropertyAllowed, *ppNameHint,
  4066. /*needsPIDOnRCurlyScan*/ false);
  4067. pnodeFnc->cbStringMin = iecpMin;
  4068. pnodeFnc->cbStringLim = pnodeFnc->cbLim;
  4069. if (isComputedName)
  4070. {
  4071. pnodeFnc->SetHasComputedName();
  4072. }
  4073. pnodeFnc->SetHasHomeObj();
  4074. pnodeFnc->SetIsAccessor();
  4075. if (buildAST)
  4076. {
  4077. return CreateBinNode(nop, pnodeName, pnodeFnc);
  4078. }
  4079. else
  4080. {
  4081. return nullptr;
  4082. }
  4083. }
  4084. /***************************************************************************
  4085. Parse a list of object members. e.g. { x:foo, 'y me':bar }
  4086. ***************************************************************************/
  4087. template<bool buildAST>
  4088. ParseNodePtr Parser::ParseMemberList(LPCOLESTR pNameHint, uint32* pNameHintLength, tokens declarationType)
  4089. {
  4090. ParseNodeBin * pnodeArg = nullptr;
  4091. ParseNodePtr pnodeEllipsis = nullptr;
  4092. ParseNodePtr pnodeName = nullptr;
  4093. ParseNodePtr pnodeList = nullptr;
  4094. ParseNodePtr *lastNodeRef = nullptr;
  4095. LPCOLESTR pFullNameHint = nullptr; // A calculated full name
  4096. uint32 fullNameHintLength = pNameHintLength ? *pNameHintLength : 0;
  4097. uint32 shortNameOffset = 0;
  4098. bool isProtoDeclared = false;
  4099. bool seenRest = false;
  4100. // we get declaration tkLCurly - when the possible object pattern found under the expression.
  4101. bool isObjectPattern = (declarationType == tkVAR || declarationType == tkLET || declarationType == tkCONST || declarationType == tkLCurly) && IsES6DestructuringEnabled();
  4102. // Check for an empty list
  4103. if (tkRCurly == m_token.tk)
  4104. {
  4105. return nullptr;
  4106. }
  4107. ArenaAllocator tempAllocator(_u("MemberNames"), m_nodeAllocator.GetPageAllocator(), Parser::OutOfMemory);
  4108. bool hasDeferredInitError = false;
  4109. for (;;)
  4110. {
  4111. bool isComputedName = false;
  4112. #if DEBUG
  4113. if ((m_grfscr & fscrEnforceJSON) && (tkStrCon != m_token.tk || !(this->GetScanner()->IsDoubleQuoteOnLastTkStrCon())))
  4114. {
  4115. Error(ERRsyntax);
  4116. }
  4117. #endif
  4118. bool isAsyncMethod = false;
  4119. charcount_t ichMin = this->GetScanner()->IchMinTok();
  4120. size_t iecpMin = this->GetScanner()->IecpMinTok();
  4121. if (CheckContextualKeyword(wellKnownPropertyPids.async) && m_scriptContext->GetConfig()->IsES7AsyncAndAwaitEnabled())
  4122. {
  4123. RestorePoint parsedAsync;
  4124. this->GetScanner()->Capture(&parsedAsync);
  4125. ichMin = this->GetScanner()->IchMinTok();
  4126. iecpMin = this->GetScanner()->IecpMinTok();
  4127. this->GetScanner()->ScanForcingPid();
  4128. if (m_token.tk == tkLParen || m_token.tk == tkColon || m_token.tk == tkRCurly || this->GetScanner()->FHadNewLine() || m_token.tk == tkComma)
  4129. {
  4130. this->GetScanner()->SeekTo(parsedAsync);
  4131. }
  4132. else
  4133. {
  4134. isAsyncMethod = true;
  4135. }
  4136. }
  4137. bool isGenerator = m_scriptContext->GetConfig()->IsES6GeneratorsEnabled() &&
  4138. m_token.tk == tkStar;
  4139. ushort fncDeclFlags = fFncNoName | fFncMethod;
  4140. if (isGenerator)
  4141. {
  4142. if (isAsyncMethod && !m_scriptContext->GetConfig()->IsES2018AsyncIterationEnabled())
  4143. {
  4144. Error(ERRExperimental);
  4145. }
  4146. // Include star character in the function extents
  4147. ichMin = this->GetScanner()->IchMinTok();
  4148. iecpMin = this->GetScanner()->IecpMinTok();
  4149. this->GetScanner()->ScanForcingPid();
  4150. fncDeclFlags |= fFncGenerator;
  4151. }
  4152. IdentPtr pidHint = nullptr; // A name scoped to current expression
  4153. Token tkHint = m_token;
  4154. charcount_t idHintIchMin = static_cast<charcount_t>(this->GetScanner()->IecpMinTok());
  4155. charcount_t idHintIchLim = static_cast<charcount_t>(this->GetScanner()->IecpLimTok());
  4156. bool wrapInBrackets = false;
  4157. bool seenEllipsis = false;
  4158. bool maybeKeyword = false;
  4159. switch (m_token.tk)
  4160. {
  4161. default:
  4162. if (!m_token.IsReservedWord())
  4163. {
  4164. Error(ERRnoMemberIdent);
  4165. }
  4166. // allow reserved words
  4167. wrapInBrackets = true;
  4168. // fall-through
  4169. case tkID:
  4170. pidHint = m_token.GetIdentifier(this->GetHashTbl());
  4171. maybeKeyword = !this->GetScanner()->LastIdentifierHasEscape();
  4172. if (buildAST)
  4173. {
  4174. pnodeName = CreateStrNode(pidHint);
  4175. }
  4176. break;
  4177. case tkStrCon:
  4178. if (IsStrictMode() && this->GetScanner()->IsOctOrLeadingZeroOnLastTKNumber())
  4179. {
  4180. Error(ERRES5NoOctal);
  4181. }
  4182. wrapInBrackets = true;
  4183. pidHint = m_token.GetStr();
  4184. if (buildAST)
  4185. {
  4186. pnodeName = CreateStrNode(pidHint);
  4187. }
  4188. break;
  4189. case tkIntCon:
  4190. // Object initializers with numeric labels allowed in JS6
  4191. if (IsStrictMode() && this->GetScanner()->IsOctOrLeadingZeroOnLastTKNumber())
  4192. {
  4193. Error(ERRES5NoOctal);
  4194. }
  4195. pidHint = this->GetScanner()->PidFromLong(m_token.GetLong());
  4196. if (buildAST)
  4197. {
  4198. pnodeName = CreateStrNode(pidHint);
  4199. }
  4200. break;
  4201. case tkFltCon:
  4202. if (IsStrictMode() && this->GetScanner()->IsOctOrLeadingZeroOnLastTKNumber())
  4203. {
  4204. Error(ERRES5NoOctal);
  4205. }
  4206. pidHint = this->GetScanner()->PidFromDbl(m_token.GetDouble());
  4207. if (buildAST)
  4208. {
  4209. pnodeName = CreateStrNode(pidHint);
  4210. }
  4211. wrapInBrackets = true;
  4212. break;
  4213. case tkLBrack:
  4214. // Computed property name: [expr] : value
  4215. if (!m_scriptContext->GetConfig()->IsES6ObjectLiteralsEnabled())
  4216. {
  4217. Error(ERRnoMemberIdent);
  4218. }
  4219. ParseComputedName<buildAST>(&pnodeName, &pNameHint, &pFullNameHint, &fullNameHintLength, &shortNameOffset);
  4220. isComputedName = true;
  4221. break;
  4222. case tkEllipsis:
  4223. if (CONFIG_FLAG(ES2018ObjectRestSpread))
  4224. {
  4225. seenEllipsis = true;
  4226. }
  4227. else
  4228. {
  4229. Error(ERRnoMemberIdent);
  4230. }
  4231. break;
  4232. }
  4233. if (pFullNameHint == nullptr)
  4234. {
  4235. if (CONFIG_FLAG(UseFullName))
  4236. {
  4237. pFullNameHint = AppendNameHints(pNameHint, pidHint, &fullNameHintLength, &shortNameOffset, false, wrapInBrackets);
  4238. }
  4239. else
  4240. {
  4241. pFullNameHint = pidHint ? pidHint->Psz() : nullptr;
  4242. fullNameHintLength = pidHint ? pidHint->Cch() : 0;
  4243. shortNameOffset = 0;
  4244. }
  4245. }
  4246. RestorePoint atPid;
  4247. // Only move to next token if spread op was not seen
  4248. if (!seenEllipsis)
  4249. {
  4250. this->GetScanner()->Capture(&atPid);
  4251. this->GetScanner()->ScanForcingPid();
  4252. }
  4253. if (isGenerator && m_token.tk != tkLParen)
  4254. {
  4255. Error(ERRnoLparen);
  4256. }
  4257. if (tkColon == m_token.tk)
  4258. {
  4259. // It is a syntax error if the production of the form __proto__ : <> occurs more than once. From B.3.1 in spec.
  4260. // Note that previous scan is important because only after that we can determine we have a variable.
  4261. if (!isComputedName && pidHint == wellKnownPropertyPids.__proto__)
  4262. {
  4263. if (isProtoDeclared)
  4264. {
  4265. Error(ERRsyntax);
  4266. }
  4267. else
  4268. {
  4269. isProtoDeclared = true;
  4270. }
  4271. }
  4272. this->GetScanner()->Scan();
  4273. ParseNodePtr pnodeExpr = nullptr;
  4274. if (isObjectPattern)
  4275. {
  4276. if (m_token.tk == tkEllipsis)
  4277. {
  4278. Error(ERRUnexpectedEllipsis);
  4279. }
  4280. RestorePoint atExpression;
  4281. if (!buildAST && declarationType == tkLCurly && IsPossiblePatternStart())
  4282. {
  4283. this->GetScanner()->Capture(&atExpression);
  4284. int saveNextBlockId = m_nextBlockId;
  4285. // It is possible that we might encounter the shorthand init error. Lets find that out.
  4286. bool savedDeferredInitError = m_hasDeferredShorthandInitError;
  4287. m_hasDeferredShorthandInitError = false;
  4288. IdentToken token;
  4289. BOOL fLikelyPattern = false;
  4290. // First identify that the current expression is indeed the object/array literal. Otherwise we will just use the ParsrExpr to parse that.
  4291. ParseTerm<buildAST>(/* fAllowCall */ m_token.tk != tkSUPER, nullptr /*pNameHint*/, nullptr /*pHintLength*/, nullptr /*pShortNameOffset*/, &token, false /*fUnaryOrParen*/,
  4292. TRUE, nullptr /*pfCanAssign*/, &fLikelyPattern);
  4293. m_nextBlockId = saveNextBlockId;
  4294. this->GetScanner()->SeekTo(atExpression);
  4295. if (fLikelyPattern)
  4296. {
  4297. pnodeExpr = ParseDestructuredVarDecl<buildAST>(declarationType, declarationType != tkLCurly, &seenRest/* *hasSeenRest*/, false /*topLevel*/, false /*allowEmptyExpression*/, true /*isObjectPattern*/);
  4298. if (m_token.tk != tkComma && m_token.tk != tkRCurly)
  4299. {
  4300. if (m_token.IsOperator())
  4301. {
  4302. Error(ERRDestructNoOper);
  4303. }
  4304. Error(ERRsyntax);
  4305. }
  4306. }
  4307. else
  4308. {
  4309. if (m_hasDeferredShorthandInitError)
  4310. {
  4311. Error(ERRnoColon);
  4312. }
  4313. pnodeExpr = ParseExpr<buildAST>(koplCma, nullptr/*pfCantAssign*/, TRUE/*fAllowIn*/, FALSE/*fAllowEllipsis*/, pFullNameHint, &fullNameHintLength, &shortNameOffset);
  4314. }
  4315. m_hasDeferredShorthandInitError = savedDeferredInitError;
  4316. }
  4317. else
  4318. {
  4319. pnodeExpr = ParseDestructuredVarDecl<buildAST>(declarationType, declarationType != tkLCurly, &seenRest/* *hasSeenRest*/, false /*topLevel*/, false /*allowEmptyExpression*/, true /*isObjectPattern*/);
  4320. if (m_token.tk != tkComma && m_token.tk != tkRCurly)
  4321. {
  4322. if (m_token.IsOperator())
  4323. {
  4324. Error(ERRDestructNoOper);
  4325. }
  4326. Error(ERRsyntax);
  4327. }
  4328. }
  4329. }
  4330. else
  4331. {
  4332. pnodeExpr = ParseExpr<buildAST>(koplCma, nullptr/*pfCantAssign*/, TRUE/*fAllowIn*/, FALSE/*fAllowEllipsis*/, pFullNameHint, &fullNameHintLength, &shortNameOffset);
  4333. ParseNodeFnc* funcNode = nullptr;
  4334. if (pnodeExpr)
  4335. {
  4336. if (pnodeExpr->nop == knopFncDecl)
  4337. {
  4338. funcNode = pnodeExpr->AsParseNodeFnc();
  4339. funcNode->SetHasHomeObj();
  4340. }
  4341. else if (pnodeExpr->nop == knopClassDecl)
  4342. {
  4343. funcNode = pnodeExpr->AsParseNodeClass()->pnodeConstructor;
  4344. }
  4345. if (funcNode && funcNode->pnodeName == nullptr && isComputedName)
  4346. {
  4347. funcNode->SetHasComputedName();
  4348. }
  4349. }
  4350. }
  4351. #if DEBUG
  4352. if ((m_grfscr & fscrEnforceJSON) && !IsJSONValid(pnodeExpr))
  4353. {
  4354. Error(ERRsyntax);
  4355. }
  4356. #endif
  4357. if (buildAST)
  4358. {
  4359. pnodeArg = CreateBinNode(isObjectPattern ? knopObjectPatternMember : knopMember, pnodeName, pnodeExpr);
  4360. if (pnodeArg->pnode1->nop == knopStr)
  4361. {
  4362. pnodeArg->pnode1->AsParseNodeStr()->pid->PromoteAssignmentState();
  4363. }
  4364. }
  4365. }
  4366. else if (m_token.tk == tkLParen && m_scriptContext->GetConfig()->IsES6ObjectLiteralsEnabled())
  4367. {
  4368. if (isObjectPattern)
  4369. {
  4370. Error(ERRInvalidAssignmentTarget);
  4371. }
  4372. // Shorthand syntax: foo() {} -> foo: function() {}
  4373. // Rewind to the PID and parse a function expression.
  4374. this->GetScanner()->SeekTo(atPid);
  4375. ParseNodeFnc * pnodeFnc = ParseFncDeclNoCheckScope<buildAST>(fncDeclFlags | (isAsyncMethod ? fFncAsync : fFncNoFlgs), SuperRestrictionState::PropertyAllowed, pFullNameHint,
  4376. /*needsPIDOnRCurlyScan*/ false);
  4377. if (isAsyncMethod || isGenerator)
  4378. {
  4379. pnodeFnc->cbStringMin = iecpMin;
  4380. pnodeFnc->cbStringLim = pnodeFnc->cbLim;
  4381. }
  4382. if (isComputedName)
  4383. {
  4384. pnodeFnc->SetHasComputedName();
  4385. pnodeFnc->cbStringMin = iecpMin;
  4386. pnodeFnc->cbStringLim = pnodeFnc->cbLim;
  4387. }
  4388. pnodeFnc->SetHasHomeObj();
  4389. if (buildAST)
  4390. {
  4391. pnodeArg = CreateBinNode(knopMember, pnodeName, pnodeFnc);
  4392. }
  4393. }
  4394. else if (seenEllipsis)
  4395. {
  4396. if (!isObjectPattern)
  4397. {
  4398. pnodeEllipsis = ParseExpr<buildAST>(koplCma, nullptr, TRUE, /* fAllowEllipsis */ TRUE);
  4399. }
  4400. else
  4401. {
  4402. pnodeEllipsis = ParseDestructuredVarDecl<buildAST>(declarationType, declarationType != tkLCurly, &seenRest/* *hasSeenRest*/, false /*topLevel*/, false /*allowEmptyExpression*/, true /*isObjectPattern*/);
  4403. }
  4404. if (buildAST)
  4405. {
  4406. this->CheckArguments(pnodeEllipsis);
  4407. }
  4408. }
  4409. else if (nullptr != pidHint) //It's either tkID/tkStrCon/tkFloatCon/tkIntCon
  4410. {
  4411. Assert(pidHint->Psz() != nullptr);
  4412. // get/set are only pseudo keywords when they are identifiers (i.e. not strings)
  4413. if ((pidHint == wellKnownPropertyPids.get || pidHint == wellKnownPropertyPids.set) &&
  4414. maybeKeyword &&
  4415. NextTokenIsPropertyNameStart())
  4416. {
  4417. if (isObjectPattern)
  4418. {
  4419. Error(ERRInvalidAssignmentTarget);
  4420. }
  4421. LPCOLESTR pNameGetOrSet = nullptr;
  4422. OpCode op = pidHint == wellKnownPropertyPids.get ? knopGetMember : knopSetMember;
  4423. pnodeArg = ParseMemberGetSet<buildAST>(op, &pNameGetOrSet, iecpMin, ichMin);
  4424. if (CONFIG_FLAG(UseFullName) && buildAST && pnodeArg->pnode2->nop == knopFncDecl)
  4425. {
  4426. // displays as "get object.funcname" or "set object.funcname"
  4427. uint32 getOrSetOffset = 0;
  4428. LPCOLESTR intermediateHint = AppendNameHints(pNameHint, pNameGetOrSet, &fullNameHintLength, &shortNameOffset);
  4429. pFullNameHint = AppendNameHints(pidHint, intermediateHint, &fullNameHintLength, &getOrSetOffset, true);
  4430. shortNameOffset += getOrSetOffset;
  4431. }
  4432. }
  4433. else if ((m_token.tk == tkRCurly || m_token.tk == tkComma || m_token.tk == tkAsg) && m_scriptContext->GetConfig()->IsES6ObjectLiteralsEnabled())
  4434. {
  4435. // Shorthand {foo} -> {foo:foo} syntax.
  4436. // {foo = <initializer>} supported only when on object pattern rules are being applied
  4437. if (tkHint.tk != tkID)
  4438. {
  4439. Assert(tkHint.IsReservedWord()
  4440. || tkHint.tk == tkIntCon || tkHint.tk == tkFltCon || tkHint.tk == tkStrCon);
  4441. // All keywords are banned in non-strict mode.
  4442. // Future reserved words are banned in strict mode.
  4443. if (IsStrictMode() || !tkHint.IsFutureReservedWord(true))
  4444. {
  4445. IdentifierExpectedError(tkHint);
  4446. }
  4447. }
  4448. CheckArgumentsUse(pidHint, GetCurrentFunctionNode());
  4449. bool couldBeObjectPattern = !isObjectPattern && m_token.tk == tkAsg;
  4450. // Saving the current state as we may change the isObjectPattern down below.
  4451. bool oldState = isObjectPattern;
  4452. if (couldBeObjectPattern)
  4453. {
  4454. declarationType = tkLCurly;
  4455. isObjectPattern = true;
  4456. // This may be an error but we are deferring for favouring destructuring.
  4457. hasDeferredInitError = true;
  4458. }
  4459. ParseNodePtr pnodeIdent = nullptr;
  4460. if (isObjectPattern)
  4461. {
  4462. this->GetScanner()->SeekTo(atPid);
  4463. pnodeIdent = ParseDestructuredVarDecl<buildAST>(declarationType, declarationType != tkLCurly, &seenRest/* *hasSeenRest*/, false /*topLevel*/, false /*allowEmptyExpression*/, true /*isObjectPattern*/);
  4464. if (m_token.tk != tkComma && m_token.tk != tkRCurly)
  4465. {
  4466. if (m_token.IsOperator())
  4467. {
  4468. Error(ERRDestructNoOper);
  4469. }
  4470. Error(ERRsyntax);
  4471. }
  4472. }
  4473. else
  4474. {
  4475. // Add a reference to the hinted name so we can bind it properly.
  4476. PidRefStack *ref = PushPidRef(pidHint);
  4477. if (buildAST)
  4478. {
  4479. pnodeIdent = CreateNameNode(pidHint, ref, idHintIchMin, idHintIchLim);
  4480. }
  4481. }
  4482. if (buildAST)
  4483. {
  4484. pnodeArg = CreateBinNode(isObjectPattern && !couldBeObjectPattern ? knopObjectPatternMember : knopMemberShort, pnodeName, pnodeIdent);
  4485. }
  4486. isObjectPattern = oldState;
  4487. }
  4488. else
  4489. {
  4490. Error(ERRnoColon);
  4491. }
  4492. }
  4493. else
  4494. {
  4495. Error(ERRnoColon);
  4496. }
  4497. if (buildAST)
  4498. {
  4499. if (seenEllipsis)
  4500. {
  4501. Assert(pnodeEllipsis != nullptr);
  4502. AddToNodeListEscapedUse(&pnodeList, &lastNodeRef, pnodeEllipsis);
  4503. }
  4504. else
  4505. {
  4506. Assert(pnodeArg->pnode2 != nullptr);
  4507. if (pnodeArg->pnode2->nop == knopFncDecl)
  4508. {
  4509. Assert(fullNameHintLength >= shortNameOffset);
  4510. ParseNodeFnc * pnodeFunc = pnodeArg->pnode2->AsParseNodeFnc();
  4511. pnodeFunc->hint = pFullNameHint;
  4512. pnodeFunc->hintLength = fullNameHintLength;
  4513. pnodeFunc->hintOffset = shortNameOffset;
  4514. }
  4515. AddToNodeListEscapedUse(&pnodeList, &lastNodeRef, pnodeArg);
  4516. }
  4517. }
  4518. pidHint = nullptr;
  4519. pFullNameHint = nullptr;
  4520. if (tkComma != m_token.tk)
  4521. {
  4522. break;
  4523. }
  4524. this->GetScanner()->ScanForcingPid();
  4525. if (tkRCurly == m_token.tk)
  4526. {
  4527. break;
  4528. }
  4529. if (seenRest) // Rest must be in the last position.
  4530. {
  4531. Error(ERRDestructRestLast);
  4532. }
  4533. }
  4534. m_hasDeferredShorthandInitError = m_hasDeferredShorthandInitError || hasDeferredInitError;
  4535. if (buildAST)
  4536. {
  4537. Assert(lastNodeRef);
  4538. Assert(*lastNodeRef);
  4539. pnodeList->ichLim = (*lastNodeRef)->ichLim;
  4540. }
  4541. return pnodeList;
  4542. }
  4543. BOOL Parser::WillDeferParse(Js::LocalFunctionId functionId)
  4544. {
  4545. if ((m_grfscr & fscrWillDeferFncParse) != 0)
  4546. {
  4547. if (m_stoppedDeferredParse)
  4548. {
  4549. return false;
  4550. }
  4551. if (!PHASE_ENABLED_RAW(DeferParsePhase, m_sourceContextInfo->sourceContextId, functionId))
  4552. {
  4553. return false;
  4554. }
  4555. if (PHASE_FORCE_RAW(Js::DeferParsePhase, m_sourceContextInfo->sourceContextId, functionId)
  4556. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  4557. || Js::Configuration::Global.flags.IsEnabled(Js::ForceUndoDeferFlag)
  4558. #endif
  4559. )
  4560. {
  4561. return true;
  4562. }
  4563. #if ENABLE_PROFILE_INFO
  4564. #ifndef DISABLE_DYNAMIC_PROFILE_DEFER_PARSE
  4565. if (m_sourceContextInfo->sourceDynamicProfileManager != nullptr)
  4566. {
  4567. Js::ExecutionFlags flags = m_sourceContextInfo->sourceDynamicProfileManager->IsFunctionExecuted(functionId);
  4568. return flags != Js::ExecutionFlags_Executed;
  4569. }
  4570. #endif
  4571. #endif
  4572. return true;
  4573. }
  4574. return false;
  4575. }
  4576. //
  4577. // Call this in ParseFncDecl only to check (and reset) if ParseFncDecl is re-parsing a deferred
  4578. // function body. If a deferred function is called and being re-parsed, it shouldn't be deferred again.
  4579. //
  4580. BOOL Parser::IsDeferredFnc()
  4581. {
  4582. if (m_grfscr & fscrDeferredFnc)
  4583. {
  4584. m_grfscr &= ~fscrDeferredFnc;
  4585. return true;
  4586. }
  4587. return false;
  4588. }
  4589. template<bool buildAST>
  4590. ParseNode * Parser::ParseFncDeclCheckScope(ushort flags, bool fAllowIn)
  4591. {
  4592. ParseNodeBlock * pnodeFncBlockScope = nullptr;
  4593. ParseNodePtr *ppnodeScopeSave = nullptr;
  4594. ParseNodePtr *ppnodeExprScopeSave = nullptr;
  4595. bool fDeclaration = flags & fFncDeclaration;
  4596. bool noStmtContext = false;
  4597. if (fDeclaration)
  4598. {
  4599. noStmtContext = m_pstmtCur->GetNop() != knopBlock;
  4600. if (noStmtContext)
  4601. {
  4602. // We have a function declaration like "if (a) function f() {}". We didn't see
  4603. // a block scope on the way in, so we need to pretend we did. Note that this is a syntax error
  4604. // in strict mode.
  4605. if (!this->FncDeclAllowedWithoutContext(flags))
  4606. {
  4607. Error(ERRsyntax);
  4608. }
  4609. pnodeFncBlockScope = StartParseBlock<buildAST>(PnodeBlockType::Regular, ScopeType_Block);
  4610. if (buildAST)
  4611. {
  4612. PushFuncBlockScope(pnodeFncBlockScope, &ppnodeScopeSave, &ppnodeExprScopeSave);
  4613. }
  4614. }
  4615. }
  4616. ParseNodeFnc * pnodeFnc = ParseFncDeclInternal<buildAST>(flags, nullptr, /* needsPIDOnRCurlyScan */ false, /* fUnaryOrParen */ false, noStmtContext, SuperRestrictionState::Disallowed, fAllowIn);
  4617. if (pnodeFncBlockScope)
  4618. {
  4619. Assert(pnodeFncBlockScope->pnodeStmt == nullptr);
  4620. pnodeFncBlockScope->pnodeStmt = pnodeFnc;
  4621. if (buildAST)
  4622. {
  4623. PopFuncBlockScope(ppnodeScopeSave, ppnodeExprScopeSave);
  4624. }
  4625. FinishParseBlock(pnodeFncBlockScope);
  4626. return pnodeFncBlockScope;
  4627. }
  4628. return pnodeFnc;
  4629. }
  4630. template<bool buildAST>
  4631. ParseNodeFnc * Parser::ParseFncDeclNoCheckScope(ushort flags, SuperRestrictionState::State superRestrictionState, LPCOLESTR pNameHint, const bool needsPIDOnRCurlyScan, bool fUnaryOrParen, bool fAllowIn)
  4632. {
  4633. Assert((flags & fFncDeclaration) == 0);
  4634. return ParseFncDeclInternal<buildAST>(flags, pNameHint, needsPIDOnRCurlyScan, fUnaryOrParen, /* noStmtContext */ false, superRestrictionState, fAllowIn);
  4635. }
  4636. template<bool buildAST>
  4637. ParseNodeFnc * Parser::ParseFncDeclInternal(ushort flags, LPCOLESTR pNameHint, const bool needsPIDOnRCurlyScan, bool fUnaryOrParen, bool noStmtContext, SuperRestrictionState::State superRestrictionState, bool fAllowIn)
  4638. {
  4639. ParseNodeFnc * pnodeFnc = nullptr;
  4640. ParseNodePtr *ppnodeVarSave = nullptr;
  4641. bool fDeclaration = flags & fFncDeclaration;
  4642. bool fModule = (flags & fFncModule) != 0;
  4643. bool fLambda = (flags & fFncLambda) != 0;
  4644. charcount_t ichMin = this->GetScanner()->IchMinTok();
  4645. bool wasInDeferredNestedFunc = false;
  4646. uint tryCatchOrFinallyDepthSave = this->m_tryCatchOrFinallyDepth;
  4647. this->m_tryCatchOrFinallyDepth = 0;
  4648. if (this->m_arrayDepth)
  4649. {
  4650. this->m_funcInArrayDepth++; // Count function depth within array literal
  4651. }
  4652. // Update the count of functions nested in the current parent.
  4653. Assert(m_pnestedCount || !buildAST);
  4654. uint *pnestedCountSave = m_pnestedCount;
  4655. if (buildAST || m_pnestedCount)
  4656. {
  4657. (*m_pnestedCount)++;
  4658. }
  4659. uint scopeCountNoAstSave = m_scopeCountNoAst;
  4660. m_scopeCountNoAst = 0;
  4661. // Create the node.
  4662. pnodeFnc = CreateAllowDeferNodeForOpT<knopFncDecl>();
  4663. pnodeFnc->SetDeclaration(fDeclaration);
  4664. pnodeFnc->nestedFuncEscapes = false;
  4665. pnodeFnc->cbMin = this->GetScanner()->IecpMinTok();
  4666. pnodeFnc->cbStringMin = pnodeFnc->cbMin;
  4667. pnodeFnc->cbStringLim = pnodeFnc->cbLim;
  4668. pnodeFnc->functionId = (*m_nextFunctionId)++;
  4669. pnodeFnc->superRestrictionState = superRestrictionState;
  4670. // Push new parser state with this new function node
  4671. AppendFunctionToScopeList(fDeclaration, pnodeFnc);
  4672. // Start the argument list.
  4673. ppnodeVarSave = m_ppnodeVar;
  4674. if (buildAST)
  4675. {
  4676. pnodeFnc->lineNumber = this->GetScanner()->LineCur();
  4677. pnodeFnc->columnNumber = CalculateFunctionColumnNumber();
  4678. pnodeFnc->SetNested(m_currentNodeFunc != nullptr); // If there is a current function, then we're a nested function.
  4679. pnodeFnc->SetStrictMode(IsStrictMode()); // Inherit current strict mode -- may be overridden by the function itself if it contains a strict mode directive.
  4680. m_pCurrentAstSize = &pnodeFnc->astSize;
  4681. }
  4682. else // if !buildAST
  4683. {
  4684. wasInDeferredNestedFunc = m_inDeferredNestedFunc;
  4685. m_inDeferredNestedFunc = true;
  4686. }
  4687. m_pnestedCount = &pnodeFnc->nestedCount;
  4688. AnalysisAssert(pnodeFnc);
  4689. pnodeFnc->SetIsAsync((flags & fFncAsync) != 0);
  4690. pnodeFnc->SetIsLambda(fLambda);
  4691. pnodeFnc->SetIsMethod((flags & fFncMethod) != 0);
  4692. pnodeFnc->SetIsClassMember((flags & fFncClassMember) != 0);
  4693. pnodeFnc->SetIsModule(fModule);
  4694. pnodeFnc->SetIsClassConstructor((flags & fFncClassConstructor) != 0);
  4695. pnodeFnc->SetIsBaseClassConstructor((flags & fFncBaseClassConstructor) != 0);
  4696. pnodeFnc->SetHomeObjLocation(Js::Constants::NoRegister);
  4697. pnodeFnc->SetHasNonThisStmt(pnodeFnc->IsClassConstructor());
  4698. if (this->m_currentScope && this->m_currentScope->GetScopeType() == ScopeType_Parameter)
  4699. {
  4700. pnodeFnc->SetIsDeclaredInParamScope();
  4701. this->m_currentScope->SetHasNestedParamFunc();
  4702. }
  4703. IdentPtr pFncNamePid = nullptr;
  4704. bool needScanRCurly = true;
  4705. ParseFncDeclHelper<buildAST>(pnodeFnc, pNameHint, flags, fUnaryOrParen, noStmtContext, &needScanRCurly, fModule, &pFncNamePid, fAllowIn);
  4706. AddNestedCapturedNames(pnodeFnc);
  4707. AnalysisAssert(pnodeFnc);
  4708. *m_ppnodeVar = nullptr;
  4709. m_ppnodeVar = ppnodeVarSave;
  4710. if (m_currentNodeFunc && (pnodeFnc->CallsEval() || pnodeFnc->ChildCallsEval()))
  4711. {
  4712. GetCurrentFunctionNode()->SetChildCallsEval(true);
  4713. }
  4714. // Lambdas do not have "arguments" and instead capture their parent's
  4715. // binding of "arguments. To ensure the arguments object of the enclosing
  4716. // non-lambda function is loaded propagate the UsesArguments flag up to
  4717. // the parent function
  4718. if (fLambda && (pnodeFnc->UsesArguments() || pnodeFnc->CallsEval()))
  4719. {
  4720. ParseNodeFnc * pnodeFncParent = GetCurrentFunctionNode();
  4721. if (pnodeFncParent != nullptr)
  4722. {
  4723. pnodeFncParent->SetUsesArguments();
  4724. }
  4725. else
  4726. {
  4727. m_UsesArgumentsAtGlobal = true;
  4728. }
  4729. }
  4730. if (needScanRCurly && !fModule)
  4731. {
  4732. // Consume the next token now that we're back in the enclosing function (whose strictness may be
  4733. // different from the function we just finished).
  4734. #if DBG
  4735. bool expectedTokenValid = m_token.tk == tkRCurly;
  4736. AssertMsg(expectedTokenValid, "Invalid token expected for RCurly match");
  4737. #endif
  4738. // The next token may need to have a PID created in !buildAST mode, as we may be parsing a method with a string name.
  4739. if (needsPIDOnRCurlyScan)
  4740. {
  4741. this->GetScanner()->ScanForcingPid();
  4742. }
  4743. else
  4744. {
  4745. this->GetScanner()->Scan();
  4746. }
  4747. }
  4748. m_pnestedCount = pnestedCountSave;
  4749. Assert(!buildAST || !wasInDeferredNestedFunc);
  4750. m_inDeferredNestedFunc = wasInDeferredNestedFunc;
  4751. if (this->m_arrayDepth)
  4752. {
  4753. this->m_funcInArrayDepth--;
  4754. if (this->m_funcInArrayDepth == 0)
  4755. {
  4756. // We disable deferred parsing if array literals dominate.
  4757. // But don't do this if the array literal is dominated by function bodies.
  4758. if (flags & (fFncMethod | fFncClassMember) && m_token.tk != tkSColon)
  4759. {
  4760. // Class member methods have optional separators. We need to check whether we are
  4761. // getting the IchLim of the correct token.
  4762. Assert(this->GetScanner()->m_tkPrevious == tkRCurly && needScanRCurly);
  4763. this->m_funcInArray += this->GetScanner()->IchMinTok() - /*tkRCurly*/ 1 - ichMin;
  4764. }
  4765. else
  4766. {
  4767. this->m_funcInArray += this->GetScanner()->IchLimTok() - ichMin;
  4768. }
  4769. }
  4770. }
  4771. m_scopeCountNoAst = scopeCountNoAstSave;
  4772. if (fDeclaration && !IsStrictMode())
  4773. {
  4774. if (pFncNamePid != nullptr &&
  4775. GetCurrentBlock() &&
  4776. GetCurrentBlock()->blockType == PnodeBlockType::Regular)
  4777. {
  4778. // Add a function-scoped VarDecl with the same name as the function for
  4779. // back compat with pre-ES6 code that declares functions in blocks. The
  4780. // idea is that the last executed declaration wins at the function scope
  4781. // level and we accomplish this by having each block scoped function
  4782. // declaration assign to both the block scoped "let" binding, as well
  4783. // as the function scoped "var" binding.
  4784. ParseNodeVar * vardecl = CreateVarDeclNode(pFncNamePid, STVariable, false, nullptr, false);
  4785. vardecl->isBlockScopeFncDeclVar = true;
  4786. if (GetCurrentFunctionNode() && vardecl->sym->GetIsFormal())
  4787. {
  4788. GetCurrentFunctionNode()->SetHasAnyWriteToFormals(true);
  4789. }
  4790. }
  4791. }
  4792. if (buildAST && fDeclaration)
  4793. {
  4794. Symbol* funcSym = pnodeFnc->GetFuncSymbol();
  4795. if (funcSym->GetIsFormal())
  4796. {
  4797. GetCurrentFunctionNode()->SetHasAnyWriteToFormals(true);
  4798. }
  4799. } this->m_tryCatchOrFinallyDepth = tryCatchOrFinallyDepthSave;
  4800. return pnodeFnc;
  4801. }
  4802. bool Parser::FncDeclAllowedWithoutContext(ushort flags)
  4803. {
  4804. // Statement context required for strict mode, async functions, and generators.
  4805. // Note that generators aren't detected yet when this method is called; they're checked elsewhere.
  4806. return !IsStrictMode() && !(flags & fFncAsync);
  4807. }
  4808. uint Parser::CalculateFunctionColumnNumber()
  4809. {
  4810. uint columnNumber;
  4811. charcount_t ichMinTok = this->GetScanner()->IchMinTok();
  4812. charcount_t ichMinLine = this->GetScanner()->IchMinLine();
  4813. if (ichMinTok >= ichMinLine)
  4814. {
  4815. // In scenarios involving defer parse IchMinLine() can be incorrect for the first line after defer parse
  4816. columnNumber = ichMinTok - ichMinLine;
  4817. if (m_functionBody != nullptr && m_functionBody->GetRelativeLineNumber() == this->GetScanner()->LineCur())
  4818. {
  4819. // Adjust the column if it falls on the first line, where the re-parse is happening.
  4820. columnNumber += m_functionBody->GetRelativeColumnNumber();
  4821. }
  4822. }
  4823. else if (m_currentNodeFunc)
  4824. {
  4825. // For the first line after defer parse, compute the column relative to the column number
  4826. // of the lexically parent function.
  4827. ULONG offsetFromCurrentFunction = ichMinTok - m_currentNodeFunc->ichMin;
  4828. columnNumber = m_currentNodeFunc->columnNumber + offsetFromCurrentFunction;
  4829. }
  4830. else
  4831. {
  4832. // if there is no current function, lets give a default of 0.
  4833. columnNumber = 0;
  4834. }
  4835. return columnNumber;
  4836. }
  4837. void Parser::AppendFunctionToScopeList(bool fDeclaration, ParseNodeFnc * pnodeFnc)
  4838. {
  4839. if (!fDeclaration && m_ppnodeExprScope)
  4840. {
  4841. // We're tracking function expressions separately from declarations in this scope
  4842. // (e.g., inside a catch scope in standards mode).
  4843. Assert(*m_ppnodeExprScope == nullptr);
  4844. *m_ppnodeExprScope = pnodeFnc;
  4845. m_ppnodeExprScope = &pnodeFnc->pnodeNext;
  4846. }
  4847. else
  4848. {
  4849. Assert(*m_ppnodeScope == nullptr);
  4850. *m_ppnodeScope = pnodeFnc;
  4851. m_ppnodeScope = &pnodeFnc->pnodeNext;
  4852. }
  4853. }
  4854. /***************************************************************************
  4855. Parse a function definition.
  4856. ***************************************************************************/
  4857. template<bool buildAST>
  4858. void Parser::ParseFncDeclHelper(ParseNodeFnc * pnodeFnc, LPCOLESTR pNameHint, ushort flags, bool fUnaryOrParen, bool noStmtContext, bool *pNeedScanRCurly, bool skipFormals, IdentPtr* pFncNamePid, bool fAllowIn)
  4859. {
  4860. Assert(pnodeFnc);
  4861. ParseNodeFnc * pnodeFncParent = GetCurrentFunctionNode();
  4862. // is the following correct? When buildAST is false, m_currentNodeDeferredFunc can be nullptr on transition to deferred parse from non-deferred
  4863. ParseNodeFnc * pnodeFncSave = buildAST ? m_currentNodeFunc : m_currentNodeDeferredFunc;
  4864. ParseNodeFnc * pnodeFncSaveNonLambda = buildAST ? m_currentNodeNonLambdaFunc : m_currentNodeNonLambdaDeferredFunc;
  4865. int32* pAstSizeSave = m_pCurrentAstSize;
  4866. bool fDeclaration = (flags & fFncDeclaration) != 0;
  4867. bool fLambda = (flags & fFncLambda) != 0;
  4868. bool fAsync = (flags & fFncAsync) != 0;
  4869. bool fModule = (flags & fFncModule) != 0;
  4870. bool fDeferred = false;
  4871. StmtNest *pstmtSave;
  4872. bool fFunctionInBlock = false;
  4873. if (buildAST)
  4874. {
  4875. fFunctionInBlock = GetCurrentBlockInfo() != GetCurrentFunctionBlockInfo() &&
  4876. (GetCurrentBlockInfo()->pnodeBlock->scope == nullptr ||
  4877. GetCurrentBlockInfo()->pnodeBlock->scope->GetScopeType() != ScopeType_GlobalEvalBlock);
  4878. }
  4879. // Save the position of the scanner in case we need to inspect the name hint later
  4880. RestorePoint beginNameHint;
  4881. this->GetScanner()->Capture(&beginNameHint);
  4882. ParseNodeBlock * pnodeFncExprScope = nullptr;
  4883. Scope *fncExprScope = nullptr;
  4884. if (!fDeclaration)
  4885. {
  4886. if (!fLambda)
  4887. {
  4888. pnodeFncExprScope = StartParseBlock<buildAST>(PnodeBlockType::Function, ScopeType_FuncExpr);
  4889. fncExprScope = pnodeFncExprScope->scope;
  4890. }
  4891. // Function expression: push the new function onto the stack now so that the name (if any) will be
  4892. // local to the new function.
  4893. this->UpdateCurrentNodeFunc<buildAST>(pnodeFnc, fLambda);
  4894. }
  4895. if (!fLambda && !fModule)
  4896. {
  4897. this->ParseFncName<buildAST>(pnodeFnc, flags, pFncNamePid);
  4898. }
  4899. if (fDeclaration)
  4900. {
  4901. // Declaration statement: push the new function now, after parsing the name, so the name is local to the
  4902. // enclosing function.
  4903. this->UpdateCurrentNodeFunc<buildAST>(pnodeFnc, fLambda);
  4904. }
  4905. if (noStmtContext && pnodeFnc->IsGenerator())
  4906. {
  4907. // Generator decl not allowed outside stmt context. (We have to wait until we've parsed the '*' to
  4908. // detect generator.)
  4909. Error(ERRsyntax, pnodeFnc);
  4910. }
  4911. // switch scanner to treat 'yield' as keyword in generator functions
  4912. // or as an identifier in non-generator functions
  4913. bool fPreviousYieldIsKeyword = this->GetScanner()->SetYieldIsKeywordRegion(pnodeFnc->IsGenerator());
  4914. bool fPreviousAwaitIsKeyword = this->GetScanner()->SetAwaitIsKeywordRegion(fAsync);
  4915. if (pnodeFnc->IsGenerator())
  4916. {
  4917. CHAKRATEL_LANGSTATS_INC_LANGFEATURECOUNT(ES6, Generator, m_scriptContext);
  4918. }
  4919. if (fncExprScope && pnodeFnc->pnodeName == nullptr)
  4920. {
  4921. FinishParseBlock(pnodeFncExprScope);
  4922. m_nextBlockId--;
  4923. Adelete(&m_nodeAllocator, fncExprScope);
  4924. fncExprScope = nullptr;
  4925. pnodeFncExprScope = nullptr;
  4926. }
  4927. pnodeFnc->scope = fncExprScope;
  4928. // Start a new statement stack.
  4929. bool topLevelStmt =
  4930. buildAST &&
  4931. !fFunctionInBlock &&
  4932. (this->m_pstmtCur == nullptr || this->m_pstmtCur->pnodeStmt->nop == knopBlock);
  4933. pstmtSave = m_pstmtCur;
  4934. SetCurrentStatement(nullptr);
  4935. RestorePoint beginFormals;
  4936. this->GetScanner()->Capture(&beginFormals);
  4937. BOOL fWasAlreadyStrictMode = IsStrictMode();
  4938. BOOL oldStrictMode = this->m_fUseStrictMode;
  4939. if (fLambda)
  4940. {
  4941. CHAKRATEL_LANGSTATS_INC_LANGFEATURECOUNT(ES6, Lambda, m_scriptContext);
  4942. }
  4943. uint uCanDeferSave = m_grfscr & fscrCanDeferFncParse;
  4944. uint uDeferSave = m_grfscr & fscrWillDeferFncParse;
  4945. bool isTopLevelDeferredFunc = false;
  4946. #if ENABLE_BACKGROUND_PARSING
  4947. struct AutoFastScanFlag {
  4948. bool savedDoingFastScan;
  4949. AutoFastScanFlag(Parser *parser) : m_parser(parser) { savedDoingFastScan = m_parser->m_doingFastScan; }
  4950. ~AutoFastScanFlag() { m_parser->m_doingFastScan = savedDoingFastScan; }
  4951. Parser *m_parser;
  4952. } flag(this);
  4953. #endif
  4954. bool doParallel = false;
  4955. #if ENABLE_BACKGROUND_PARSING
  4956. bool parallelJobStarted = false;
  4957. #endif
  4958. if (buildAST)
  4959. {
  4960. bool isLikelyIIFE = !fDeclaration && fUnaryOrParen;
  4961. BOOL isDeferredFnc = IsDeferredFnc();
  4962. // These are the conditions that prohibit upfront deferral *and* redeferral.
  4963. isTopLevelDeferredFunc =
  4964. (m_grfscr & fscrCanDeferFncParse)
  4965. && !m_InAsmMode
  4966. // Don't defer a module function wrapper because we need to do export resolution at parse time
  4967. && !fModule;
  4968. pnodeFnc->SetCanBeDeferred(isTopLevelDeferredFunc && ParseNodeFnc::CanBeRedeferred(pnodeFnc->fncFlags));
  4969. // These are heuristic conditions that prohibit upfront deferral but not redeferral.
  4970. isTopLevelDeferredFunc = isTopLevelDeferredFunc && !isDeferredFnc && WillDeferParse(pnodeFnc->functionId) &&
  4971. (!isLikelyIIFE || !topLevelStmt || PHASE_FORCE_RAW(Js::DeferParsePhase, m_sourceContextInfo->sourceContextId, pnodeFnc->functionId));
  4972. #if ENABLE_BACKGROUND_PARSING
  4973. if (!fLambda &&
  4974. !isDeferredFnc &&
  4975. !isLikelyIIFE &&
  4976. !this->IsBackgroundParser() &&
  4977. !this->m_doingFastScan &&
  4978. !(pnodeFncSave && m_currDeferredStub) &&
  4979. !(this->m_parseType == ParseType_Deferred && this->m_functionBody && this->m_functionBody->GetScopeInfo() && !isTopLevelDeferredFunc))
  4980. {
  4981. doParallel = DoParallelParse(pnodeFnc);
  4982. if (doParallel)
  4983. {
  4984. BackgroundParser *bgp = m_scriptContext->GetBackgroundParser();
  4985. Assert(bgp);
  4986. if (bgp->HasFailedBackgroundParseItem())
  4987. {
  4988. Error(ERRsyntax);
  4989. }
  4990. doParallel = bgp->ParseBackgroundItem(this, pnodeFnc, isTopLevelDeferredFunc);
  4991. if (doParallel)
  4992. {
  4993. parallelJobStarted = true;
  4994. this->m_hasParallelJob = true;
  4995. this->m_doingFastScan = true;
  4996. doParallel = FastScanFormalsAndBody();
  4997. if (doParallel)
  4998. {
  4999. // Let the foreground thread take care of marking the limit on the function node,
  5000. // because in some cases this function's caller will want to change that limit,
  5001. // so we don't want the background thread to try and touch it.
  5002. pnodeFnc->ichLim = this->GetScanner()->IchLimTok();
  5003. pnodeFnc->cbLim = this->GetScanner()->IecpLimTok();
  5004. }
  5005. }
  5006. }
  5007. }
  5008. #endif
  5009. }
  5010. if (!doParallel)
  5011. {
  5012. #if ENABLE_BACKGROUND_PARSING
  5013. // We don't want to, or couldn't, let the main thread scan past this function body, so parse
  5014. // it for real.
  5015. ParseNodeFnc * pnodeRealFnc = pnodeFnc;
  5016. if (parallelJobStarted)
  5017. {
  5018. // We have to deal with a failure to fast-scan the function (due to syntax error? "/"?) when
  5019. // a background thread may already have begun to work on the job. Both threads can't be allowed to
  5020. // operate on the same node.
  5021. pnodeFnc = CreateDummyFuncNode(fDeclaration);
  5022. }
  5023. #endif
  5024. AnalysisAssert(pnodeFnc);
  5025. ParseNodeBlock * pnodeBlock = StartParseBlock<buildAST>(PnodeBlockType::Parameter, ScopeType_Parameter);
  5026. AnalysisAssert(pnodeBlock != nullptr);
  5027. pnodeFnc->pnodeScopes = pnodeBlock;
  5028. m_ppnodeVar = &pnodeFnc->pnodeParams;
  5029. pnodeFnc->pnodeVars = nullptr;
  5030. ParseNodePtr* varNodesList = &pnodeFnc->pnodeVars;
  5031. ParseNodeVar * argNode = nullptr;
  5032. if (!fModule && !fLambda)
  5033. {
  5034. ParseNodePtr *const ppnodeVarSave = m_ppnodeVar;
  5035. m_ppnodeVar = &pnodeFnc->pnodeVars;
  5036. // Create the built-in arguments symbol
  5037. argNode = this->AddArgumentsNodeToVars(pnodeFnc);
  5038. // Save the updated var list
  5039. varNodesList = m_ppnodeVar;
  5040. m_ppnodeVar = ppnodeVarSave;
  5041. }
  5042. ParseNodePtr *ppnodeScopeSave = nullptr;
  5043. ParseNodePtr *ppnodeExprScopeSave = nullptr;
  5044. ppnodeScopeSave = m_ppnodeScope;
  5045. if (pnodeBlock)
  5046. {
  5047. // This synthetic block scope will contain all the nested scopes.
  5048. m_ppnodeScope = &pnodeBlock->pnodeScopes;
  5049. pnodeBlock->pnodeStmt = pnodeFnc;
  5050. }
  5051. // Keep nested function declarations and expressions in the same list at function scope.
  5052. // (Indicate this by nulling out the current function expressions list.)
  5053. ppnodeExprScopeSave = m_ppnodeExprScope;
  5054. m_ppnodeExprScope = nullptr;
  5055. uint parenExprDepthSave = m_funcParenExprDepth;
  5056. m_funcParenExprDepth = 0;
  5057. if (!skipFormals)
  5058. {
  5059. bool fLambdaParamsSave = m_reparsingLambdaParams;
  5060. if (fLambda)
  5061. {
  5062. m_reparsingLambdaParams = true;
  5063. }
  5064. uint savedStubCount = m_currDeferredStubCount;
  5065. DeferredFunctionStub* savedStub = m_currDeferredStub;
  5066. ShiftCurrDeferredStubToChildFunction(pnodeFnc, pnodeFncParent);
  5067. this->ParseFncFormals<buildAST>(pnodeFnc, pnodeFncParent, flags, isTopLevelDeferredFunc);
  5068. m_currDeferredStub = savedStub;
  5069. m_currDeferredStubCount = savedStubCount;
  5070. m_reparsingLambdaParams = fLambdaParamsSave;
  5071. }
  5072. // Create function body scope
  5073. ParseNodeBlock * pnodeInnerBlock = StartParseBlock<buildAST>(PnodeBlockType::Function, ScopeType_FunctionBody);
  5074. // Set the parameter block's child to the function body block.
  5075. // The pnodeFnc->pnodeScopes list is constructed in such a way that it includes all the scopes in this list.
  5076. // For example if the param scope has one function and body scope has one function then the list will look like below,
  5077. // param scope block -> function decl from param scope -> body socpe block -> function decl from body scope.
  5078. *m_ppnodeScope = pnodeInnerBlock;
  5079. pnodeFnc->pnodeBodyScope = pnodeInnerBlock;
  5080. // This synthetic block scope will contain all the nested scopes.
  5081. m_ppnodeScope = &pnodeInnerBlock->pnodeScopes;
  5082. pnodeInnerBlock->pnodeStmt = pnodeFnc;
  5083. // DEFER: Begin deferral here (after names are parsed and name nodes created).
  5084. // Create no more AST nodes until we're done.
  5085. // Try to defer this func if all these are true:
  5086. // 0. We are not already in deferred parsing (i.e. buildAST is true)
  5087. // 1. We are not re-parsing a deferred func which is being invoked.
  5088. // 2. Dynamic profile suggests this func can be deferred (and deferred parse is on).
  5089. // 3. This func is top level or defer nested func is on.
  5090. // 4. Optionally, the function is non-nested and not in eval, or the deferral decision was based on cached profile info,
  5091. // or the function is sufficiently long. (I.e., don't defer little nested functions unless we're
  5092. // confident they'll never be executed, because un-deferring nested functions is more expensive.)
  5093. // NOTE: I'm disabling #4 by default, because we've found other ways to reduce the cost of un-deferral,
  5094. // and we don't want to create function bodies aggressively for little functions.
  5095. // We will also temporarily defer all asm.js functions, except for the asm.js
  5096. // module itself, which we will never defer
  5097. bool strictModeTurnedOn = false;
  5098. if (isTopLevelDeferredFunc &&
  5099. !(this->m_grfscr & fscrEvalCode) &&
  5100. pnodeFnc->IsNested() &&
  5101. #ifndef DISABLE_DYNAMIC_PROFILE_DEFER_PARSE
  5102. m_sourceContextInfo->sourceDynamicProfileManager == nullptr &&
  5103. #endif
  5104. PHASE_ON_RAW(Js::ScanAheadPhase, m_sourceContextInfo->sourceContextId, pnodeFnc->functionId) &&
  5105. (
  5106. !PHASE_FORCE_RAW(Js::DeferParsePhase, m_sourceContextInfo->sourceContextId, pnodeFnc->functionId) ||
  5107. PHASE_FORCE_RAW(Js::ScanAheadPhase, m_sourceContextInfo->sourceContextId, pnodeFnc->functionId)
  5108. ))
  5109. {
  5110. // Try to scan ahead to the end of the function. If we get there before we've scanned a minimum
  5111. // number of tokens, don't bother deferring, because it's too small.
  5112. if (this->ScanAheadToFunctionEnd(CONFIG_FLAG(MinDeferredFuncTokenCount)))
  5113. {
  5114. isTopLevelDeferredFunc = false;
  5115. }
  5116. }
  5117. Scope* paramScope = pnodeFnc->pnodeScopes ? pnodeFnc->pnodeScopes->scope : nullptr;
  5118. if (paramScope != nullptr)
  5119. {
  5120. if (CONFIG_FLAG(ForceSplitScope))
  5121. {
  5122. pnodeFnc->ResetBodyAndParamScopeMerged();
  5123. }
  5124. else if (pnodeFnc->HasNonSimpleParameterList() && pnodeFnc->IsBodyAndParamScopeMerged())
  5125. {
  5126. paramScope->ForEachSymbolUntil([this, paramScope, pnodeFnc](Symbol* sym) {
  5127. if (sym->GetPid()->GetTopRef()->GetFuncScopeId() > pnodeFnc->functionId)
  5128. {
  5129. // One of the symbol has non local reference. Mark the param scope as we can't merge it with body scope.
  5130. pnodeFnc->ResetBodyAndParamScopeMerged();
  5131. return true;
  5132. }
  5133. return false;
  5134. });
  5135. }
  5136. }
  5137. // If the param scope is merged with the body scope we want to use the param scope symbols in the body scope.
  5138. // So add a pid ref for the body using the param scope symbol. Note that in this case the same symbol will occur twice
  5139. // in the same pid ref stack.
  5140. if (paramScope != nullptr && pnodeFnc->IsBodyAndParamScopeMerged())
  5141. {
  5142. paramScope->ForEachSymbol([this](Symbol* paramSym)
  5143. {
  5144. PidRefStack* ref = PushPidRef(paramSym->GetPid());
  5145. ref->SetSym(paramSym);
  5146. });
  5147. }
  5148. AssertMsg(m_funcParenExprDepth == 0, "Paren exprs should have been resolved by the time we finish function formals");
  5149. if (fLambda)
  5150. {
  5151. #ifdef ASMJS_PLAT
  5152. if (m_InAsmMode && (isTopLevelDeferredFunc && m_deferAsmJs))
  5153. {
  5154. // asm.js doesn't support lambda functions
  5155. Js::AsmJSCompiler::OutputError(m_scriptContext, _u("Lambda functions are not supported."));
  5156. Js::AsmJSCompiler::OutputError(m_scriptContext, _u("Asm.js compilation failed."));
  5157. throw Js::AsmJsParseException();
  5158. }
  5159. #endif
  5160. }
  5161. if (m_token.tk == tkRParen)
  5162. {
  5163. this->GetScanner()->Scan();
  5164. }
  5165. if (fLambda)
  5166. {
  5167. BOOL hadNewLine = this->GetScanner()->FHadNewLine();
  5168. // it can be the case we do not have a fat arrow here if there is a valid expression on the left hand side
  5169. // of the fat arrow, but that expression does not parse as a parameter list. E.g.
  5170. // a.x => { }
  5171. // Therefore check for it and error if not found.
  5172. ChkCurTok(tkDArrow, ERRnoDArrow);
  5173. // Newline character between arrow parameters and fat arrow is a syntax error but we want to check for
  5174. // this after verifying there was a => token. Otherwise we would throw the wrong error.
  5175. if (hadNewLine)
  5176. {
  5177. Error(ERRValidIfFollowedBy, _u("Lambda parameter list"), _u("'=>' on the same line"));
  5178. }
  5179. }
  5180. if (isTopLevelDeferredFunc || (m_InAsmMode && m_deferAsmJs))
  5181. {
  5182. fDeferred = true;
  5183. this->ParseTopLevelDeferredFunc(pnodeFnc, pnodeFncSave, pNameHint, fLambda, pNeedScanRCurly, fAllowIn);
  5184. }
  5185. else
  5186. {
  5187. AnalysisAssert(pnodeFnc);
  5188. // Shouldn't be any temps in the arg list.
  5189. Assert(*m_ppnodeVar == nullptr);
  5190. // Start the var list.
  5191. m_ppnodeVar = varNodesList;
  5192. if (!pnodeFnc->IsBodyAndParamScopeMerged())
  5193. {
  5194. 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"));
  5195. }
  5196. // Keep nested function declarations and expressions in the same list at function scope.
  5197. // (Indicate this by nulling out the current function expressions list.)
  5198. m_ppnodeExprScope = nullptr;
  5199. if (buildAST)
  5200. {
  5201. if (m_token.tk != tkLCurly && fLambda)
  5202. {
  5203. *pNeedScanRCurly = false;
  5204. }
  5205. uint savedStubCount = m_currDeferredStubCount;
  5206. DeferredFunctionStub* savedStub = m_currDeferredStub;
  5207. ShiftCurrDeferredStubToChildFunction(pnodeFnc, pnodeFncSave);
  5208. this->FinishFncDecl(pnodeFnc, pNameHint, fLambda, skipFormals, fAllowIn);
  5209. m_currDeferredStub = savedStub;
  5210. m_currDeferredStubCount = savedStubCount;
  5211. }
  5212. else
  5213. {
  5214. this->ParseNestedDeferredFunc(pnodeFnc, fLambda, pNeedScanRCurly, &strictModeTurnedOn, fAllowIn);
  5215. }
  5216. }
  5217. // Restore the paren count for any outer spread/rest error checking.
  5218. m_funcParenExprDepth = parenExprDepthSave;
  5219. if (pnodeInnerBlock)
  5220. {
  5221. FinishParseBlock(pnodeInnerBlock, *pNeedScanRCurly);
  5222. }
  5223. if (!fModule && (m_token.tk == tkLCurly || !fLambda))
  5224. {
  5225. UpdateArgumentsNode(pnodeFnc, argNode);
  5226. }
  5227. CreateSpecialSymbolDeclarations(pnodeFnc);
  5228. // Restore the lists of scopes that contain function expressions.
  5229. Assert(m_ppnodeExprScope == nullptr || *m_ppnodeExprScope == nullptr);
  5230. m_ppnodeExprScope = ppnodeExprScopeSave;
  5231. Assert(m_ppnodeScope);
  5232. Assert(nullptr == *m_ppnodeScope);
  5233. m_ppnodeScope = ppnodeScopeSave;
  5234. if (pnodeBlock)
  5235. {
  5236. FinishParseBlock(pnodeBlock, *pNeedScanRCurly);
  5237. }
  5238. if (IsStrictMode() || strictModeTurnedOn)
  5239. {
  5240. this->m_fUseStrictMode = TRUE; // Now we know this function is in strict mode
  5241. if (!fWasAlreadyStrictMode)
  5242. {
  5243. // If this function turned on strict mode then we didn't check the formal
  5244. // parameters or function name hint for future reserved word usage. So do that now.
  5245. RestorePoint afterFnc;
  5246. this->GetScanner()->Capture(&afterFnc);
  5247. if (pnodeFnc->pnodeName != nullptr)
  5248. {
  5249. // Rewind to the function name hint and check if the token is a reserved word.
  5250. this->GetScanner()->SeekTo(beginNameHint);
  5251. this->GetScanner()->Scan();
  5252. if (pnodeFnc->IsGenerator())
  5253. {
  5254. Assert(m_token.tk == tkStar);
  5255. Assert(m_scriptContext->GetConfig()->IsES6GeneratorsEnabled());
  5256. Assert(!(flags & fFncClassMember));
  5257. this->GetScanner()->Scan();
  5258. }
  5259. if (m_token.IsReservedWord())
  5260. {
  5261. IdentifierExpectedError(m_token);
  5262. }
  5263. CheckStrictModeEvalArgumentsUsage(m_token.GetIdentifier(this->GetHashTbl()));
  5264. }
  5265. // Fast forward to formal parameter list, check for future reserved words,
  5266. // then restore scanner as it was.
  5267. this->GetScanner()->SeekToForcingPid(beginFormals);
  5268. CheckStrictFormalParameters();
  5269. this->GetScanner()->SeekTo(afterFnc);
  5270. }
  5271. if (buildAST)
  5272. {
  5273. if (pnodeFnc->pnodeName != nullptr)
  5274. {
  5275. Assert(pnodeFnc->pnodeName->nop == knopVarDecl);
  5276. CheckStrictModeEvalArgumentsUsage(pnodeFnc->pnodeName->pid, pnodeFnc->pnodeName);
  5277. }
  5278. }
  5279. this->m_fUseStrictMode = oldStrictMode;
  5280. CHAKRATEL_LANGSTATS_INC_LANGFEATURECOUNT(ES6, StrictModeFunction, m_scriptContext);
  5281. }
  5282. ProcessCapturedNames(pnodeFnc);
  5283. if (fDeferred)
  5284. {
  5285. AnalysisAssert(pnodeFnc);
  5286. pnodeFnc->pnodeVars = nullptr;
  5287. }
  5288. #if ENABLE_BACKGROUND_PARSING
  5289. if (parallelJobStarted)
  5290. {
  5291. pnodeFnc = pnodeRealFnc;
  5292. m_currentNodeFunc = pnodeRealFnc;
  5293. // Let the foreground thread take care of marking the limit on the function node,
  5294. // because in some cases this function's caller will want to change that limit,
  5295. // so we don't want the background thread to try and touch it.
  5296. pnodeFnc->ichLim = this->GetScanner()->IchLimTok();
  5297. pnodeFnc->cbLim = this->GetScanner()->IecpLimTok();
  5298. }
  5299. #endif
  5300. }
  5301. // after parsing asm.js module, we want to reset asm.js state before continuing
  5302. AnalysisAssert(pnodeFnc);
  5303. if (pnodeFnc->GetAsmjsMode())
  5304. {
  5305. m_InAsmMode = false;
  5306. }
  5307. // Restore the statement stack.
  5308. Assert(nullptr == m_pstmtCur);
  5309. SetCurrentStatement(pstmtSave);
  5310. if (pnodeFncExprScope)
  5311. {
  5312. FinishParseFncExprScope(pnodeFnc, pnodeFncExprScope);
  5313. }
  5314. m_grfscr |= uCanDeferSave;
  5315. if (!m_stoppedDeferredParse)
  5316. {
  5317. m_grfscr |= uDeferSave;
  5318. }
  5319. this->GetScanner()->SetYieldIsKeywordRegion(fPreviousYieldIsKeyword);
  5320. this->GetScanner()->SetAwaitIsKeywordRegion(fPreviousAwaitIsKeyword);
  5321. // Restore the current function.
  5322. if (buildAST)
  5323. {
  5324. Assert(pnodeFnc == m_currentNodeFunc);
  5325. m_currentNodeFunc = pnodeFncSave;
  5326. m_pCurrentAstSize = pAstSizeSave;
  5327. if (!fLambda)
  5328. {
  5329. Assert(pnodeFnc == m_currentNodeNonLambdaFunc);
  5330. m_currentNodeNonLambdaFunc = pnodeFncSaveNonLambda;
  5331. }
  5332. }
  5333. else
  5334. {
  5335. Assert(pnodeFnc == m_currentNodeDeferredFunc);
  5336. if (!fLambda)
  5337. {
  5338. Assert(pnodeFnc == m_currentNodeNonLambdaDeferredFunc);
  5339. m_currentNodeNonLambdaDeferredFunc = pnodeFncSaveNonLambda;
  5340. }
  5341. m_currentNodeDeferredFunc = pnodeFncSave;
  5342. }
  5343. if (m_currentNodeFunc && pnodeFnc->HasWithStmt())
  5344. {
  5345. GetCurrentFunctionNode()->SetHasWithStmt(true);
  5346. }
  5347. }
  5348. template<bool buildAST>
  5349. void Parser::UpdateCurrentNodeFunc(ParseNodeFnc * pnodeFnc, bool fLambda)
  5350. {
  5351. if (buildAST)
  5352. {
  5353. // Make this the current function and start its sub-function list.
  5354. m_currentNodeFunc = pnodeFnc;
  5355. Assert(m_currentNodeDeferredFunc == nullptr);
  5356. if (!fLambda)
  5357. {
  5358. m_currentNodeNonLambdaFunc = pnodeFnc;
  5359. }
  5360. }
  5361. else // if !buildAST
  5362. {
  5363. AnalysisAssert(pnodeFnc);
  5364. if (!fLambda)
  5365. {
  5366. m_currentNodeNonLambdaDeferredFunc = pnodeFnc;
  5367. }
  5368. m_currentNodeDeferredFunc = pnodeFnc;
  5369. }
  5370. }
  5371. void Parser::ParseTopLevelDeferredFunc(ParseNodeFnc * pnodeFnc, ParseNodeFnc * pnodeFncParent, LPCOLESTR pNameHint, bool fLambda, bool *pNeedScanRCurly, bool fAllowIn)
  5372. {
  5373. // Parse a function body that is a transition point from building AST to doing fast syntax check.
  5374. pnodeFnc->pnodeVars = nullptr;
  5375. pnodeFnc->pnodeBody = nullptr;
  5376. this->m_deferringAST = TRUE;
  5377. // Put the scanner into "no hashing" mode.
  5378. BYTE deferFlags = this->GetScanner()->SetDeferredParse(TRUE);
  5379. if (!fLambda)
  5380. {
  5381. ChkCurTok(tkLCurly, ERRnoLcurly);
  5382. }
  5383. else
  5384. {
  5385. // Lambda may consist of a single expression instead of a block
  5386. if (this->GetScanner()->m_ptoken->tk == tkLCurly)
  5387. {
  5388. this->GetScanner()->Scan();
  5389. }
  5390. else
  5391. {
  5392. *pNeedScanRCurly = false;
  5393. }
  5394. }
  5395. ParseNodePtr *ppnodeVarSave = m_ppnodeVar;
  5396. m_ppnodeVar = &pnodeFnc->pnodeVars;
  5397. // Don't try and skip scanning nested deferred lambdas which have only a single expression in the body.
  5398. // Their more-complicated text extents won't match the deferred-stub and the single expression should be fast to scan, anyway.
  5399. if (fLambda && !*pNeedScanRCurly)
  5400. {
  5401. ParseExpressionLambdaBody<false>(pnodeFnc, fAllowIn);
  5402. }
  5403. else if (pnodeFncParent != nullptr && m_currDeferredStub != nullptr)
  5404. {
  5405. // We've already parsed this function body for syntax errors on the initial parse of the script.
  5406. // We have information that allows us to skip it, so do so.
  5407. Assert(pnodeFncParent->nestedCount != 0);
  5408. DeferredFunctionStub *stub = m_currDeferredStub + (pnodeFncParent->nestedCount - 1);
  5409. Assert(pnodeFnc->ichMin == stub->ichMin
  5410. || (stub->fncFlags & kFunctionIsAsync) == kFunctionIsAsync
  5411. || ((stub->fncFlags & kFunctionIsMethod) == kFunctionIsMethod && (
  5412. (stub->fncFlags & kFunctionIsAccessor) == kFunctionIsAccessor
  5413. || (stub->fncFlags & kFunctionIsGenerator) == kFunctionIsGenerator
  5414. || (stub->fncFlags & kFunctionHasComputedName) == kFunctionHasComputedName
  5415. )));
  5416. if (stub->fncFlags & kFunctionCallsEval)
  5417. {
  5418. this->MarkEvalCaller();
  5419. }
  5420. PHASE_PRINT_TRACE1(
  5421. Js::SkipNestedDeferredPhase,
  5422. _u("Skipping nested deferred function %d. %s: %d...%d\n"),
  5423. pnodeFnc->functionId, GetFunctionName(pnodeFnc, pNameHint), pnodeFnc->ichMin, stub->restorePoint.m_ichMinTok);
  5424. this->GetScanner()->SeekTo(stub->restorePoint, m_nextFunctionId);
  5425. // If we already incremented m_nextFunctionId when we saw some functions in the parameter scope
  5426. // (in default argument assignment, for example), we want to remove the count of those so the
  5427. // function ids following the one we are skipping right now are correct.
  5428. *m_nextFunctionId -= pnodeFnc->nestedCount;
  5429. for (uint i = 0; i < stub->capturedNameCount; i++)
  5430. {
  5431. int stringId = stub->capturedNameSerializedIds[i];
  5432. uint32 stringLength = 0;
  5433. LPCWSTR stringVal = Js::ByteCodeSerializer::DeserializeString(stub, stringId, stringLength);
  5434. OUTPUT_TRACE_DEBUGONLY(Js::SkipNestedDeferredPhase, _u("\tPushing a reference to '%s'\n"), stringVal);
  5435. IdentPtr pid = this->GetHashTbl()->PidHashNameLen(stringVal, stringLength);
  5436. PushPidRef(pid);
  5437. }
  5438. pnodeFnc->nestedCount = stub->nestedCount;
  5439. pnodeFnc->deferredStub = stub->deferredStubs;
  5440. pnodeFnc->fncFlags = (FncFlags)(pnodeFnc->fncFlags | stub->fncFlags);
  5441. }
  5442. else
  5443. {
  5444. ParseStmtList<false>(nullptr, nullptr, SM_DeferredParse, true /* isSourceElementList */);
  5445. }
  5446. if (!fLambda || *pNeedScanRCurly)
  5447. {
  5448. pnodeFnc->ichLim = this->GetScanner()->IchLimTok();
  5449. pnodeFnc->cbLim = this->GetScanner()->IecpLimTok();
  5450. }
  5451. m_ppnodeVar = ppnodeVarSave;
  5452. // Restore the scanner's default hashing mode.
  5453. // Do this before we consume the next token.
  5454. this->GetScanner()->SetDeferredParseFlags(deferFlags);
  5455. if (*pNeedScanRCurly)
  5456. {
  5457. ChkCurTokNoScan(tkRCurly, ERRnoRcurly);
  5458. }
  5459. #if DBG
  5460. pnodeFnc->deferredParseNextFunctionId = *this->m_nextFunctionId;
  5461. #endif
  5462. this->m_deferringAST = FALSE;
  5463. }
  5464. bool Parser::DoParallelParse(ParseNodeFnc * pnodeFnc) const
  5465. {
  5466. #if ENABLE_BACKGROUND_PARSING
  5467. if (!PHASE_ENABLED_RAW(ParallelParsePhase, m_sourceContextInfo->sourceContextId, pnodeFnc->functionId))
  5468. {
  5469. return false;
  5470. }
  5471. BackgroundParser *bgp = m_scriptContext->GetBackgroundParser();
  5472. return bgp != nullptr;
  5473. #else
  5474. return false;
  5475. #endif
  5476. }
  5477. bool Parser::ScanAheadToFunctionEnd(uint count)
  5478. {
  5479. bool found = false;
  5480. uint curlyDepth = 0;
  5481. RestorePoint funcStart;
  5482. this->GetScanner()->Capture(&funcStart);
  5483. for (uint i = 0; i < count; i++)
  5484. {
  5485. switch (m_token.tk)
  5486. {
  5487. case tkStrTmplBegin:
  5488. case tkStrTmplMid:
  5489. case tkStrTmplEnd:
  5490. case tkDiv:
  5491. case tkAsgDiv:
  5492. case tkScanError:
  5493. case tkEOF:
  5494. goto LEnd;
  5495. case tkLCurly:
  5496. UInt32Math::Inc(curlyDepth, Parser::OutOfMemory);
  5497. break;
  5498. case tkRCurly:
  5499. if (curlyDepth == 1)
  5500. {
  5501. found = true;
  5502. goto LEnd;
  5503. }
  5504. if (curlyDepth == 0)
  5505. {
  5506. goto LEnd;
  5507. }
  5508. curlyDepth--;
  5509. break;
  5510. }
  5511. this->GetScanner()->ScanAhead();
  5512. }
  5513. LEnd:
  5514. this->GetScanner()->SeekTo(funcStart);
  5515. return found;
  5516. }
  5517. #if ENABLE_BACKGROUND_PARSING
  5518. bool Parser::FastScanFormalsAndBody()
  5519. {
  5520. // The scanner is currently pointing just past the name of a function.
  5521. // The idea here is to find the end of the function body as quickly as possible,
  5522. // by tokenizing and tracking {}'s if possible.
  5523. // String templates require some extra logic but can be handled.
  5524. // The real wrinkle is "/" and "/=", which may indicate either a RegExp literal or a division, depending
  5525. // on the context.
  5526. // To handle this with minimal work, keep track of the last ";" seen at each {} depth. If we see one of the
  5527. // difficult tokens, rewind to the last ";" at the current {} depth and parse statements until we pass the
  5528. // point where we had to rewind. This will process the "/" as required.
  5529. RestorePoint funcStart;
  5530. this->GetScanner()->Capture(&funcStart);
  5531. const int maxRestorePointDepth = 16;
  5532. struct FastScanRestorePoint
  5533. {
  5534. RestorePoint restorePoint;
  5535. uint parenDepth;
  5536. Js::LocalFunctionId functionId;
  5537. int blockId;
  5538. FastScanRestorePoint() : restorePoint(), parenDepth(0) {};
  5539. };
  5540. FastScanRestorePoint lastSColonAtCurlyDepth[maxRestorePointDepth];
  5541. charcount_t ichStart = this->GetScanner()->IchMinTok();
  5542. uint blockIdSave = m_nextBlockId;
  5543. uint functionIdSave = *m_nextFunctionId;
  5544. uint curlyDepth = 0;
  5545. uint strTmplDepth = 0;
  5546. for (;;)
  5547. {
  5548. switch (m_token.tk)
  5549. {
  5550. case tkStrTmplBegin:
  5551. UInt32Math::Inc(strTmplDepth, Parser::OutOfMemory);
  5552. // Fall through
  5553. case tkStrTmplMid:
  5554. case tkLCurly:
  5555. UInt32Math::Inc(curlyDepth, Parser::OutOfMemory);
  5556. Int32Math::Inc(m_nextBlockId, &m_nextBlockId);
  5557. break;
  5558. case tkStrTmplEnd:
  5559. // We can assert here, because the scanner will only return this token if we've told it we're
  5560. // in a string template.
  5561. Assert(strTmplDepth > 0);
  5562. strTmplDepth--;
  5563. break;
  5564. case tkRCurly:
  5565. if (curlyDepth == 1)
  5566. {
  5567. Assert(strTmplDepth == 0);
  5568. if (PHASE_TRACE1(Js::ParallelParsePhase))
  5569. {
  5570. Output::Print(_u("Finished fast seek: %d. %s -- %d...%d\n"),
  5571. m_currentNodeFunc->functionId,
  5572. GetFunctionName(m_currentNodeFunc, m_currentNodeFunc->hint),
  5573. ichStart, this->GetScanner()->IchLimTok());
  5574. }
  5575. return true;
  5576. }
  5577. if (curlyDepth < maxRestorePointDepth)
  5578. {
  5579. lastSColonAtCurlyDepth[curlyDepth].restorePoint.m_ichMinTok = (uint)-1;
  5580. }
  5581. curlyDepth--;
  5582. if (strTmplDepth > 0)
  5583. {
  5584. this->GetScanner()->SetScanState(Scanner_t::ScanState::ScanStateStringTemplateMiddleOrEnd);
  5585. }
  5586. break;
  5587. case tkSColon:
  5588. // Track the location of the ";" (if it's outside parens, as we don't, for instance, want
  5589. // to track the ";"'s in a for-loop header. If we find it's important to rewind within a paren
  5590. // expression, we can do something more sophisticated.)
  5591. if (curlyDepth < maxRestorePointDepth && lastSColonAtCurlyDepth[curlyDepth].parenDepth == 0)
  5592. {
  5593. this->GetScanner()->Capture(&lastSColonAtCurlyDepth[curlyDepth].restorePoint);
  5594. lastSColonAtCurlyDepth[curlyDepth].functionId = *this->m_nextFunctionId;
  5595. lastSColonAtCurlyDepth[curlyDepth].blockId = m_nextBlockId;
  5596. }
  5597. break;
  5598. case tkLParen:
  5599. if (curlyDepth < maxRestorePointDepth)
  5600. {
  5601. UInt32Math::Inc(lastSColonAtCurlyDepth[curlyDepth].parenDepth);
  5602. }
  5603. break;
  5604. case tkRParen:
  5605. if (curlyDepth < maxRestorePointDepth)
  5606. {
  5607. Assert(lastSColonAtCurlyDepth[curlyDepth].parenDepth != 0);
  5608. lastSColonAtCurlyDepth[curlyDepth].parenDepth--;
  5609. }
  5610. break;
  5611. case tkID:
  5612. {
  5613. charcount_t tokLength = this->GetScanner()->IchLimTok() - this->GetScanner()->IchMinTok();
  5614. // Detect the function and class keywords so we can track function ID's.
  5615. // (In fast mode, the scanner doesn't distinguish keywords and doesn't point the token
  5616. // to a PID.)
  5617. // Detect try/catch/for to increment block count for them.
  5618. switch (tokLength)
  5619. {
  5620. case 3:
  5621. if (!memcmp(this->GetScanner()->PchMinTok(), "try", 3) || !memcmp(this->GetScanner()->PchMinTok(), "for", 3))
  5622. {
  5623. Int32Math::Inc(m_nextBlockId, &m_nextBlockId);
  5624. }
  5625. break;
  5626. case 5:
  5627. if (!memcmp(this->GetScanner()->PchMinTok(), "catch", 5))
  5628. {
  5629. Int32Math::Inc(m_nextBlockId, &m_nextBlockId);
  5630. }
  5631. else if (!memcmp(this->GetScanner()->PchMinTok(), "class", 5))
  5632. {
  5633. Int32Math::Inc(m_nextBlockId, &m_nextBlockId);
  5634. Int32Math::Inc(*this->m_nextFunctionId, (int*)this->m_nextFunctionId);
  5635. }
  5636. break;
  5637. case 8:
  5638. if (!memcmp(this->GetScanner()->PchMinTok(), "function", 8))
  5639. {
  5640. // Account for the possible func expr scope or dummy block for missing {}'s around a declaration
  5641. Int32Math::Inc(m_nextBlockId, &m_nextBlockId);
  5642. Int32Math::Inc(*this->m_nextFunctionId, (int*)this->m_nextFunctionId);
  5643. }
  5644. break;
  5645. }
  5646. break;
  5647. }
  5648. case tkDArrow:
  5649. Int32Math::Inc(m_nextBlockId, &m_nextBlockId);
  5650. Int32Math::Inc(*this->m_nextFunctionId, (int*)this->m_nextFunctionId);
  5651. break;
  5652. case tkDiv:
  5653. case tkAsgDiv:
  5654. {
  5655. int opl;
  5656. OpCode nop;
  5657. tokens tkPrev = this->GetScanner()->m_tkPrevious;
  5658. if ((this->GetHashTbl()->TokIsBinop(tkPrev, &opl, &nop) && nop != knopNone) ||
  5659. (this->GetHashTbl()->TokIsUnop(tkPrev, &opl, &nop) &&
  5660. nop != knopNone &&
  5661. tkPrev != tkInc &&
  5662. tkPrev != tkDec) ||
  5663. tkPrev == tkColon ||
  5664. tkPrev == tkLParen ||
  5665. tkPrev == tkLBrack ||
  5666. tkPrev == tkRETURN)
  5667. {
  5668. // Previous token indicates that we're starting an expression here and can't have a
  5669. // binary operator now.
  5670. // Assume this is a RegExp.
  5671. ParseRegExp<false>();
  5672. break;
  5673. }
  5674. uint tempCurlyDepth = curlyDepth < maxRestorePointDepth ? curlyDepth : maxRestorePointDepth - 1;
  5675. for (; tempCurlyDepth != (uint)-1; tempCurlyDepth--)
  5676. {
  5677. // We don't know whether we've got a RegExp or a divide. Rewind to the last safe ";"
  5678. // if we can and parse statements until we pass this point.
  5679. if (lastSColonAtCurlyDepth[tempCurlyDepth].restorePoint.m_ichMinTok != -1)
  5680. {
  5681. break;
  5682. }
  5683. }
  5684. if (tempCurlyDepth != (uint)-1)
  5685. {
  5686. ParseNodeFnc * pnodeFncSave = m_currentNodeFunc;
  5687. int32 *pastSizeSave = m_pCurrentAstSize;
  5688. uint *pnestedCountSave = m_pnestedCount;
  5689. ParseNodePtr *ppnodeScopeSave = m_ppnodeScope;
  5690. ParseNodePtr *ppnodeExprScopeSave = m_ppnodeExprScope;
  5691. ParseNodeFnc * pnodeFnc = CreateDummyFuncNode(true);
  5692. charcount_t ichStop = this->GetScanner()->IchLimTok();
  5693. curlyDepth = tempCurlyDepth;
  5694. this->GetScanner()->SeekTo(lastSColonAtCurlyDepth[tempCurlyDepth].restorePoint);
  5695. m_nextBlockId = lastSColonAtCurlyDepth[tempCurlyDepth].blockId;
  5696. *this->m_nextFunctionId = lastSColonAtCurlyDepth[tempCurlyDepth].functionId;
  5697. ParseNodeBlock * pnodeBlock = StartParseBlock<true>(PnodeBlockType::Function, ScopeType_FunctionBody);
  5698. pnodeFnc->pnodeScopes = pnodeBlock;
  5699. m_ppnodeScope = &pnodeBlock->pnodeScopes;
  5700. m_ppnodeExprScope = nullptr;
  5701. this->GetScanner()->Scan();
  5702. do
  5703. {
  5704. ParseStatement<false>();
  5705. } while (this->GetScanner()->IchMinTok() < ichStop);
  5706. FinishParseBlock(pnodeBlock);
  5707. m_currentNodeFunc = pnodeFncSave;
  5708. m_pCurrentAstSize = pastSizeSave;
  5709. m_pnestedCount = pnestedCountSave;
  5710. m_ppnodeScope = ppnodeScopeSave;
  5711. m_ppnodeExprScope = ppnodeExprScopeSave;
  5712. // We've already consumed the first token of the next statement, so just continue
  5713. // without a further scan.
  5714. continue;
  5715. }
  5716. }
  5717. // fall through to rewind to function start
  5718. case tkScanError:
  5719. case tkEOF:
  5720. // Unexpected token.
  5721. if (PHASE_TRACE1(Js::ParallelParsePhase))
  5722. {
  5723. Output::Print(_u("Failed fast seek: %d. %s -- %d...%d\n"),
  5724. m_currentNodeFunc->functionId,
  5725. GetFunctionName(m_currentNodeFunc, m_currentNodeFunc->hint),
  5726. ichStart, this->GetScanner()->IchLimTok());
  5727. }
  5728. m_nextBlockId = blockIdSave;
  5729. *m_nextFunctionId = functionIdSave;
  5730. this->GetScanner()->SeekTo(funcStart);
  5731. return false;
  5732. }
  5733. this->GetScanner()->ScanNoKeywords();
  5734. }
  5735. }
  5736. #endif
  5737. ParseNodeFnc * Parser::CreateDummyFuncNode(bool fDeclaration)
  5738. {
  5739. // Create a dummy node and make it look like the current function declaration.
  5740. // Do this in situations where we want to parse statements without impacting
  5741. // the state of the "real" AST.
  5742. ParseNodeFnc * pnodeFnc = CreateAllowDeferNodeForOpT<knopFncDecl>();
  5743. pnodeFnc->SetDeclaration(fDeclaration);
  5744. pnodeFnc->SetNested(m_currentNodeFunc != nullptr); // If there is a current function, then we're a nested function.
  5745. pnodeFnc->SetStrictMode(IsStrictMode()); // Inherit current strict mode -- may be overridden by the function itself if it contains a strict mode directive.
  5746. m_pCurrentAstSize = &pnodeFnc->astSize;
  5747. m_currentNodeFunc = pnodeFnc;
  5748. m_pnestedCount = &pnodeFnc->nestedCount;
  5749. return pnodeFnc;
  5750. }
  5751. void Parser::ParseNestedDeferredFunc(ParseNodeFnc * pnodeFnc, bool fLambda, bool *pNeedScanRCurly, bool *pStrictModeTurnedOn, bool fAllowIn)
  5752. {
  5753. // Parse a function nested inside another deferred function.
  5754. size_t lengthBeforeBody = this->GetSourceLength();
  5755. if (m_token.tk != tkLCurly && fLambda)
  5756. {
  5757. ParseExpressionLambdaBody<false>(pnodeFnc, fAllowIn);
  5758. *pNeedScanRCurly = false;
  5759. }
  5760. else
  5761. {
  5762. ChkCurTok(tkLCurly, ERRnoLcurly);
  5763. bool* detectStrictModeOn = IsStrictMode() ? nullptr : pStrictModeTurnedOn;
  5764. m_ppnodeVar = &m_currentNodeDeferredFunc->pnodeVars;
  5765. ParseStmtList<false>(nullptr, nullptr, SM_DeferredParse, true /* isSourceElementList */, detectStrictModeOn);
  5766. ChkCurTokNoScan(tkRCurly, ERRnoRcurly);
  5767. pnodeFnc->ichLim = this->GetScanner()->IchLimTok();
  5768. pnodeFnc->cbLim = this->GetScanner()->IecpLimTok();
  5769. }
  5770. if (*pStrictModeTurnedOn)
  5771. {
  5772. pnodeFnc->SetStrictMode(true);
  5773. }
  5774. if (!PHASE_OFF1(Js::SkipNestedDeferredPhase))
  5775. {
  5776. // Record the end of the function and the function ID increment that happens inside the function.
  5777. // Byte code gen will use this to build stub information to allow us to skip this function when the
  5778. // enclosing function is fully parsed.
  5779. RestorePoint *restorePoint = Anew(&m_nodeAllocator, RestorePoint);
  5780. this->GetScanner()->Capture(restorePoint,
  5781. *m_nextFunctionId - pnodeFnc->functionId - 1,
  5782. lengthBeforeBody - this->GetSourceLength());
  5783. pnodeFnc->pRestorePoint = restorePoint;
  5784. }
  5785. }
  5786. template<bool buildAST>
  5787. void Parser::ParseFncName(ParseNodeFnc * pnodeFnc, ushort flags, IdentPtr* pFncNamePid)
  5788. {
  5789. Assert(pnodeFnc);
  5790. BOOL fDeclaration = flags & fFncDeclaration;
  5791. BOOL fIsAsync = flags & fFncAsync;
  5792. this->GetScanner()->Scan();
  5793. // If generators are enabled then we are in a recent enough version
  5794. // that deferred parsing will create a parse node for pnodeFnc and
  5795. // it is safe to assume it is not null.
  5796. if (flags & fFncGenerator)
  5797. {
  5798. Assert(m_scriptContext->GetConfig()->IsES6GeneratorsEnabled());
  5799. pnodeFnc->SetIsGenerator();
  5800. }
  5801. else if (m_scriptContext->GetConfig()->IsES6GeneratorsEnabled() &&
  5802. m_token.tk == tkStar &&
  5803. !(flags & fFncClassMember))
  5804. {
  5805. if (!fDeclaration)
  5806. {
  5807. bool fPreviousYieldIsKeyword = this->GetScanner()->SetYieldIsKeywordRegion(!fDeclaration);
  5808. this->GetScanner()->Scan();
  5809. this->GetScanner()->SetYieldIsKeywordRegion(fPreviousYieldIsKeyword);
  5810. }
  5811. else
  5812. {
  5813. this->GetScanner()->Scan();
  5814. }
  5815. pnodeFnc->SetIsGenerator();
  5816. }
  5817. if (fIsAsync)
  5818. {
  5819. if (pnodeFnc->IsGenerator())
  5820. {
  5821. if (!m_scriptContext->GetConfig()->IsES2018AsyncIterationEnabled())
  5822. {
  5823. Error(ERRExperimental);
  5824. }
  5825. }
  5826. pnodeFnc->SetIsAsync();
  5827. }
  5828. pnodeFnc->pnodeName = nullptr;
  5829. if ((m_token.tk != tkID || flags & fFncNoName)
  5830. && (IsStrictMode() || fDeclaration
  5831. || pnodeFnc->IsGenerator() || pnodeFnc->IsAsync()
  5832. || (m_token.tk != tkYIELD && m_token.tk != tkAWAIT))) // Function expressions can have the name yield/await even inside generator/async functions
  5833. {
  5834. if (fDeclaration ||
  5835. m_token.IsReservedWord()) // For example: var x = (function break(){});
  5836. {
  5837. IdentifierExpectedError(m_token);
  5838. }
  5839. return;
  5840. }
  5841. Assert(m_token.tk == tkID || (m_token.tk == tkYIELD && !fDeclaration) || (m_token.tk == tkAWAIT && !fDeclaration));
  5842. if (IsStrictMode())
  5843. {
  5844. CheckStrictModeEvalArgumentsUsage(m_token.GetIdentifier(this->GetHashTbl()));
  5845. }
  5846. IdentPtr pidBase = m_token.GetIdentifier(this->GetHashTbl());
  5847. pnodeFnc->pnodeName = CreateDeclNode(knopVarDecl, pidBase, STFunction);
  5848. pnodeFnc->pid = pnodeFnc->pnodeName->pid;
  5849. if (pFncNamePid != nullptr)
  5850. {
  5851. *pFncNamePid = pidBase;
  5852. }
  5853. this->GetScanner()->Scan();
  5854. }
  5855. void Parser::ValidateFormals()
  5856. {
  5857. ParseFncFormals<false>(this->GetCurrentFunctionNode(), nullptr, fFncNoFlgs);
  5858. // Eat the tkRParen. The ParseFncDeclHelper caller expects to see it.
  5859. this->GetScanner()->Scan();
  5860. }
  5861. void Parser::ValidateSourceElementList()
  5862. {
  5863. ParseStmtList<false>(nullptr, nullptr, SM_NotUsed, true);
  5864. }
  5865. void Parser::UpdateOrCheckForDuplicateInFormals(IdentPtr pid, SList<IdentPtr> *formals)
  5866. {
  5867. bool isStrictMode = IsStrictMode();
  5868. if (isStrictMode)
  5869. {
  5870. CheckStrictModeEvalArgumentsUsage(pid);
  5871. }
  5872. if (formals->Has(pid))
  5873. {
  5874. if (isStrictMode)
  5875. {
  5876. Error(ERRES5ArgSame);
  5877. }
  5878. else
  5879. {
  5880. Error(ERRFormalSame);
  5881. }
  5882. }
  5883. else
  5884. {
  5885. formals->Prepend(pid);
  5886. }
  5887. }
  5888. template<bool buildAST>
  5889. void Parser::ParseFncFormals(ParseNodeFnc * pnodeFnc, ParseNodeFnc * pnodeParentFnc, ushort flags, bool isTopLevelDeferredFunc)
  5890. {
  5891. bool fLambda = (flags & fFncLambda) != 0;
  5892. bool fMethod = (flags & fFncMethod) != 0;
  5893. bool fNoArg = (flags & fFncNoArg) != 0;
  5894. bool fOneArg = (flags & fFncOneArg) != 0;
  5895. bool fAsync = (flags & fFncAsync) != 0;
  5896. bool fPreviousYieldIsKeyword = false;
  5897. bool fPreviousAwaitIsKeyword = false;
  5898. if (fLambda)
  5899. {
  5900. fPreviousYieldIsKeyword = this->GetScanner()->SetYieldIsKeywordRegion(pnodeParentFnc != nullptr && pnodeParentFnc->IsGenerator());
  5901. fPreviousAwaitIsKeyword = this->GetScanner()->SetAwaitIsKeywordRegion(fAsync || (pnodeParentFnc != nullptr && pnodeParentFnc->IsAsync()));
  5902. }
  5903. Assert(!fNoArg || !fOneArg); // fNoArg and fOneArg can never be true at the same time.
  5904. // strictFormals corresponds to the StrictFormalParameters grammar production
  5905. // in the ES spec which just means duplicate names are not allowed
  5906. bool fStrictFormals = IsStrictMode() || fLambda || fMethod;
  5907. // When detecting duplicated formals pids are needed so force PID creation (unless the function should take 0 or 1 arg).
  5908. bool forcePid = fStrictFormals && !fNoArg && !fOneArg;
  5909. AutoTempForcePid autoForcePid(this->GetScanner(), forcePid);
  5910. // Lambda's allow single formal specified by a single binding identifier without parentheses, special case it.
  5911. if (fLambda && m_token.tk == tkID)
  5912. {
  5913. IdentPtr pid = m_token.GetIdentifier(this->GetHashTbl());
  5914. CreateVarDeclNode(pid, STFormal, false, nullptr, false);
  5915. CheckPidIsValid(pid);
  5916. this->GetScanner()->Scan();
  5917. if (m_token.tk != tkDArrow)
  5918. {
  5919. Error(ERRsyntax, this->GetScanner()->IchMinTok(), this->GetScanner()->IchLimTok());
  5920. }
  5921. if (fLambda)
  5922. {
  5923. this->GetScanner()->SetYieldIsKeywordRegion(fPreviousYieldIsKeyword);
  5924. this->GetScanner()->SetAwaitIsKeywordRegion(fPreviousAwaitIsKeyword);
  5925. }
  5926. return;
  5927. }
  5928. else if (fLambda && m_token.tk == tkAWAIT)
  5929. {
  5930. // async await => {}
  5931. IdentifierExpectedError(m_token);
  5932. }
  5933. // Otherwise, must have a parameter list within parens.
  5934. ChkCurTok(tkLParen, ERRnoLparen);
  5935. // Now parse the list of arguments, if present
  5936. if (m_token.tk == tkRParen)
  5937. {
  5938. if (fOneArg)
  5939. {
  5940. Error(ERRSetterMustHaveOneParameter);
  5941. }
  5942. }
  5943. else
  5944. {
  5945. if (fNoArg)
  5946. {
  5947. Error(ERRGetterMustHaveNoParameters);
  5948. }
  5949. SList<IdentPtr> formals(&m_nodeAllocator);
  5950. ParseNodeVar * pnodeT = nullptr;
  5951. bool seenRestParameter = false;
  5952. bool isNonSimpleParameterList = false;
  5953. for (Js::ArgSlot argPos = 0; ; ++argPos)
  5954. {
  5955. bool isBindingPattern = false;
  5956. if (m_scriptContext->GetConfig()->IsES6RestEnabled() && m_token.tk == tkEllipsis)
  5957. {
  5958. if (flags & fFncOneArg)
  5959. {
  5960. // The parameter of a setter cannot be a rest parameter.
  5961. Error(ERRUnexpectedEllipsis);
  5962. }
  5963. // Possible rest parameter
  5964. this->GetScanner()->Scan();
  5965. seenRestParameter = true;
  5966. }
  5967. if (m_token.tk != tkID)
  5968. {
  5969. if (IsES6DestructuringEnabled() && IsPossiblePatternStart())
  5970. {
  5971. // Mark that the function has a non simple parameter list before parsing the pattern since the pattern can have function definitions.
  5972. this->GetCurrentFunctionNode()->SetHasNonSimpleParameterList();
  5973. this->GetCurrentFunctionNode()->SetHasDestructuredParams();
  5974. ParseNodePtr *const ppnodeVarSave = m_ppnodeVar;
  5975. m_ppnodeVar = &pnodeFnc->pnodeVars;
  5976. ParseNodePtr * ppNodeLex = m_currentBlockInfo->m_ppnodeLex;
  5977. Assert(ppNodeLex != nullptr);
  5978. ParseNodeParamPattern * paramPattern = nullptr;
  5979. ParseNode * pnodePattern = nullptr;
  5980. if (isTopLevelDeferredFunc)
  5981. {
  5982. pnodePattern = ParseDestructuredLiteral<false>(tkLET, true /*isDecl*/, false /*topLevel*/);
  5983. }
  5984. else
  5985. {
  5986. pnodePattern = ParseDestructuredLiteral<buildAST>(tkLET, true /*isDecl*/, false /*topLevel*/);
  5987. }
  5988. // Instead of passing the STFormal all the way on many methods, it seems it is better to change the symbol type afterward.
  5989. for (ParseNodePtr lexNode = *ppNodeLex; lexNode != nullptr; lexNode = lexNode->AsParseNodeVar()->pnodeNext)
  5990. {
  5991. Assert(lexNode->IsVarLetOrConst());
  5992. UpdateOrCheckForDuplicateInFormals(lexNode->AsParseNodeVar()->pid, &formals);
  5993. lexNode->AsParseNodeVar()->sym->SetSymbolType(STFormal);
  5994. if (lexNode->AsParseNodeVar()->pid == wellKnownPropertyPids.arguments)
  5995. {
  5996. GetCurrentFunctionNode()->grfpn |= PNodeFlags::fpnArguments_overriddenInParam;
  5997. }
  5998. }
  5999. m_ppnodeVar = ppnodeVarSave;
  6000. if (buildAST)
  6001. {
  6002. if (isTopLevelDeferredFunc)
  6003. {
  6004. Assert(pnodePattern == nullptr);
  6005. // Create a dummy pattern node as we need the node to be considered for the param count
  6006. paramPattern = CreateDummyParamPatternNode(this->GetScanner()->IchMinTok());
  6007. }
  6008. else
  6009. {
  6010. Assert(pnodePattern);
  6011. paramPattern = CreateParamPatternNode(pnodePattern);
  6012. }
  6013. if (seenRestParameter)
  6014. {
  6015. Assert(pnodeFnc->pnodeRest == nullptr);
  6016. pnodeFnc->pnodeRest = paramPattern;
  6017. }
  6018. else
  6019. {
  6020. // Linking the current formal parameter (which is pattern parameter)
  6021. // with other formals.
  6022. *m_ppnodeVar = paramPattern;
  6023. paramPattern->pnodeNext = nullptr;
  6024. m_ppnodeVar = &paramPattern->pnodeNext;
  6025. }
  6026. }
  6027. isBindingPattern = true;
  6028. isNonSimpleParameterList = true;
  6029. }
  6030. else
  6031. {
  6032. IdentifierExpectedError(m_token);
  6033. }
  6034. }
  6035. if (!isBindingPattern)
  6036. {
  6037. IdentPtr pid = m_token.GetIdentifier(this->GetHashTbl());
  6038. LPCOLESTR pNameHint = pid->Psz();
  6039. uint32 nameHintLength = pid->Cch();
  6040. uint32 nameHintOffset = 0;
  6041. if (seenRestParameter)
  6042. {
  6043. this->GetCurrentFunctionNode()->SetHasNonSimpleParameterList();
  6044. pnodeT = CreateDeclNode(knopVarDecl, pid, STFormal, false);
  6045. pnodeT->sym->SetIsNonSimpleParameter(true);
  6046. if (buildAST)
  6047. {
  6048. // When only validating formals, we won't have a function node.
  6049. Assert(pnodeFnc->pnodeRest == nullptr);
  6050. pnodeFnc->pnodeRest = pnodeT;
  6051. if (!isNonSimpleParameterList)
  6052. {
  6053. // This is the first non-simple parameter we've seen. We need to go back
  6054. // and set the Symbols of all previous parameters.
  6055. MapFormalsWithoutRest(m_currentNodeFunc, [](ParseNodePtr pnodeArg)
  6056. {
  6057. pnodeArg->AsParseNodeVar()->sym->SetIsNonSimpleParameter(true);
  6058. });
  6059. }
  6060. }
  6061. isNonSimpleParameterList = true;
  6062. }
  6063. else
  6064. {
  6065. pnodeT = CreateVarDeclNode(pid, STFormal, false, nullptr, false);
  6066. if (isNonSimpleParameterList)
  6067. {
  6068. pnodeT->sym->SetIsNonSimpleParameter(true);
  6069. }
  6070. }
  6071. if (buildAST && pid == wellKnownPropertyPids.arguments)
  6072. {
  6073. // This formal parameter overrides the built-in 'arguments' object
  6074. m_currentNodeFunc->grfpn |= PNodeFlags::fpnArguments_overriddenInParam;
  6075. }
  6076. if (fStrictFormals)
  6077. {
  6078. UpdateOrCheckForDuplicateInFormals(pid, &formals);
  6079. }
  6080. this->GetScanner()->Scan();
  6081. if (m_token.tk == tkAsg && m_scriptContext->GetConfig()->IsES6DefaultArgsEnabled())
  6082. {
  6083. if (seenRestParameter && m_scriptContext->GetConfig()->IsES6RestEnabled())
  6084. {
  6085. Error(ERRRestWithDefault);
  6086. }
  6087. // In defer parse mode we have to flag the function node to indicate that it has default arguments
  6088. // so that it will be considered for any syntax error scenario.
  6089. // Also mark it before parsing the expression as it may contain functions.
  6090. ParseNodeFnc * currentFncNode = GetCurrentFunctionNode();
  6091. if (!currentFncNode->HasDefaultArguments())
  6092. {
  6093. currentFncNode->SetHasDefaultArguments();
  6094. currentFncNode->SetHasNonSimpleParameterList();
  6095. currentFncNode->firstDefaultArg = argPos;
  6096. }
  6097. this->GetScanner()->Scan();
  6098. ParseNodePtr pnodeInit;
  6099. if (isTopLevelDeferredFunc)
  6100. {
  6101. // Defer default expressions if the function will be deferred, since we know they can't be evaluated
  6102. // until the function is fully compiled, and generating code for a function nested inside a deferred function
  6103. // creates inconsistencies.
  6104. pnodeInit = ParseExpr<false>(koplCma, nullptr, TRUE, FALSE, pNameHint, &nameHintLength, &nameHintOffset);
  6105. }
  6106. else
  6107. {
  6108. pnodeInit = ParseExpr<buildAST>(koplCma, nullptr, TRUE, FALSE, pNameHint, &nameHintLength, &nameHintOffset);
  6109. }
  6110. if (buildAST && pnodeInit && pnodeInit->nop == knopFncDecl)
  6111. {
  6112. Assert(nameHintLength >= nameHintOffset);
  6113. ParseNodeFnc * pnodeFncInit = pnodeInit->AsParseNodeFnc();
  6114. pnodeFncInit->hint = pNameHint;
  6115. pnodeFncInit->hintLength = nameHintLength;
  6116. pnodeFncInit->hintOffset = nameHintOffset;
  6117. }
  6118. AnalysisAssert(pnodeT);
  6119. pnodeT->sym->SetIsNonSimpleParameter(true);
  6120. if (!isNonSimpleParameterList)
  6121. {
  6122. if (buildAST)
  6123. {
  6124. // This is the first non-simple parameter we've seen. We need to go back
  6125. // and set the Symbols of all previous parameters.
  6126. MapFormalsWithoutRest(m_currentNodeFunc, [&](ParseNodePtr pnodeArg) { pnodeArg->AsParseNodeVar()->sym->SetIsNonSimpleParameter(true); });
  6127. }
  6128. // There may be previous parameters that need to be checked for duplicates.
  6129. isNonSimpleParameterList = true;
  6130. }
  6131. if (buildAST)
  6132. {
  6133. if (!m_currentNodeFunc->HasDefaultArguments())
  6134. {
  6135. CHAKRATEL_LANGSTATS_INC_LANGFEATURECOUNT(ES6, DefaultArgFunction, m_scriptContext);
  6136. }
  6137. pnodeT->pnodeInit = pnodeInit;
  6138. pnodeT->ichLim = this->GetScanner()->IchLimTok();
  6139. }
  6140. }
  6141. }
  6142. if (isNonSimpleParameterList && m_currentScope->GetHasDuplicateFormals())
  6143. {
  6144. Error(ERRFormalSame);
  6145. }
  6146. if (flags & fFncOneArg)
  6147. {
  6148. if (m_token.tk != tkRParen)
  6149. {
  6150. Error(ERRSetterMustHaveOneParameter);
  6151. }
  6152. break; //enforce only one arg
  6153. }
  6154. if (m_token.tk != tkComma)
  6155. {
  6156. break;
  6157. }
  6158. this->GetScanner()->Scan();
  6159. if (seenRestParameter)
  6160. {
  6161. Error(ERRRestLastArg);
  6162. }
  6163. if (m_token.tk == tkRParen && m_scriptContext->GetConfig()->IsES7TrailingCommaEnabled())
  6164. {
  6165. break;
  6166. }
  6167. }
  6168. if (seenRestParameter)
  6169. {
  6170. CHAKRATEL_LANGSTATS_INC_LANGFEATURECOUNT(ES6, Rest, m_scriptContext);
  6171. }
  6172. if (m_token.tk != tkRParen)
  6173. {
  6174. Error(ERRnoRparen);
  6175. }
  6176. if (this->GetCurrentFunctionNode()->CallsEval() || this->GetCurrentFunctionNode()->ChildCallsEval())
  6177. {
  6178. Assert(pnodeFnc->HasNonSimpleParameterList());
  6179. pnodeFnc->ResetBodyAndParamScopeMerged();
  6180. }
  6181. }
  6182. Assert(m_token.tk == tkRParen);
  6183. if (fLambda)
  6184. {
  6185. this->GetScanner()->SetYieldIsKeywordRegion(fPreviousYieldIsKeyword);
  6186. this->GetScanner()->SetAwaitIsKeywordRegion(fPreviousAwaitIsKeyword);
  6187. }
  6188. }
  6189. template<bool buildAST>
  6190. ParseNodePtr Parser::GenerateModuleFunctionWrapper()
  6191. {
  6192. ParseNodePtr pnodeFnc = ParseFncDeclNoCheckScope<buildAST>(fFncModule, SuperRestrictionState::Disallowed, nullptr, /* needsPIDOnRCurlyScan */ false, /* fUnaryOrParen */ true);
  6193. // mark modules as generators after parsing - this is to enable cross-module hoisting of exported functions
  6194. pnodeFnc->AsParseNodeFnc()->SetIsGenerator(true);
  6195. ParseNodePtr callNode = CreateCallNode(knopCall, pnodeFnc, nullptr);
  6196. return callNode;
  6197. }
  6198. template<bool buildAST>
  6199. ParseNodeFnc * Parser::GenerateEmptyConstructor(bool extends)
  6200. {
  6201. ParseNodeFnc * pnodeFnc;
  6202. // Create the node.
  6203. pnodeFnc = CreateAllowDeferNodeForOpT<knopFncDecl>();
  6204. pnodeFnc->SetNested(NULL != m_currentNodeFunc);
  6205. pnodeFnc->SetStrictMode();
  6206. pnodeFnc->SetIsMethod(TRUE);
  6207. pnodeFnc->SetIsClassMember(TRUE);
  6208. pnodeFnc->SetIsClassConstructor(TRUE);
  6209. pnodeFnc->SetIsBaseClassConstructor(!extends);
  6210. pnodeFnc->SetHasNonThisStmt();
  6211. pnodeFnc->SetIsGeneratedDefault(TRUE);
  6212. pnodeFnc->SetHasHomeObj();
  6213. pnodeFnc->SetHomeObjLocation(Js::Constants::NoRegister);
  6214. pnodeFnc->ichLim = this->GetScanner()->IchLimTok();
  6215. pnodeFnc->ichMin = this->GetScanner()->IchMinTok();
  6216. pnodeFnc->cbLim = this->GetScanner()->IecpLimTok();
  6217. pnodeFnc->cbMin = this->GetScanner()->IecpMinTok();
  6218. pnodeFnc->cbStringMin = pnodeFnc->cbMin;
  6219. pnodeFnc->cbStringLim = pnodeFnc->cbLim;
  6220. pnodeFnc->lineNumber = this->GetScanner()->LineCur();
  6221. pnodeFnc->functionId = (*m_nextFunctionId);
  6222. // In order to (re-)defer the default constructor, we need to, for instance, track
  6223. // deferred class expression the way we track function expression, since we lose the part of the source
  6224. // that tells us which we have.
  6225. Assert(!pnodeFnc->canBeDeferred);
  6226. #ifdef DBG
  6227. pnodeFnc->deferredParseNextFunctionId = *(this->m_nextFunctionId);
  6228. #endif
  6229. AppendFunctionToScopeList(true, pnodeFnc);
  6230. if (m_nextFunctionId)
  6231. {
  6232. (*m_nextFunctionId)++;
  6233. }
  6234. // Update the count of functions nested in the current parent.
  6235. if (m_pnestedCount)
  6236. {
  6237. (*m_pnestedCount)++;
  6238. }
  6239. if (this->GetScanner()->IchMinTok() >= this->GetScanner()->IchMinLine())
  6240. {
  6241. // In scenarios involving defer parse IchMinLine() can be incorrect for the first line after defer parse
  6242. pnodeFnc->columnNumber = this->GetScanner()->IchMinTok() - this->GetScanner()->IchMinLine();
  6243. }
  6244. else if (m_currentNodeFunc)
  6245. {
  6246. // For the first line after defer parse, compute the column relative to the column number
  6247. // of the lexically parent function.
  6248. ULONG offsetFromCurrentFunction = this->GetScanner()->IchMinTok() - m_currentNodeFunc->ichMin;
  6249. pnodeFnc->columnNumber = m_currentNodeFunc->columnNumber + offsetFromCurrentFunction;
  6250. }
  6251. else
  6252. {
  6253. // if there is no current function, lets give a default of 0.
  6254. pnodeFnc->columnNumber = 0;
  6255. }
  6256. int32 * pAstSizeSave = m_pCurrentAstSize;
  6257. m_pCurrentAstSize = &(pnodeFnc->astSize);
  6258. // Make this the current function.
  6259. ParseNodeFnc * pnodeFncSave = m_currentNodeFunc;
  6260. m_currentNodeFunc = pnodeFnc;
  6261. ParseNodeName * argsId = nullptr;
  6262. ParseNodePtr *lastNodeRef = nullptr;
  6263. ParseNodeBlock * pnodeBlock = StartParseBlock<buildAST>(PnodeBlockType::Parameter, ScopeType_Parameter);
  6264. if (buildAST && extends)
  6265. {
  6266. // constructor(...args) { super(...args); }
  6267. // ^^^^^^^
  6268. ParseNodePtr *const ppnodeVarSave = m_ppnodeVar;
  6269. m_ppnodeVar = &pnodeFnc->pnodeVars;
  6270. IdentPtr pidargs = this->GetHashTbl()->PidHashNameLen(_u("args"), sizeof("args") - 1);
  6271. ParseNodeVar * pnodeT = CreateVarDeclNode(pidargs, STFormal);
  6272. pnodeT->sym->SetIsNonSimpleParameter(true);
  6273. pnodeFnc->pnodeRest = pnodeT;
  6274. PidRefStack *ref = this->PushPidRef(pidargs);
  6275. argsId = CreateNameNode(pidargs, ref, pnodeFnc->ichMin, pnodeFnc->ichLim);
  6276. m_ppnodeVar = ppnodeVarSave;
  6277. }
  6278. ParseNodeBlock * pnodeInnerBlock = StartParseBlock<buildAST>(PnodeBlockType::Function, ScopeType_FunctionBody);
  6279. pnodeBlock->pnodeScopes = pnodeInnerBlock;
  6280. pnodeFnc->pnodeBodyScope = pnodeInnerBlock;
  6281. pnodeFnc->pnodeScopes = pnodeBlock;
  6282. if (buildAST)
  6283. {
  6284. if (extends)
  6285. {
  6286. // constructor(...args) { super(...args); }
  6287. // ^^^^^^^^^^^^^^^
  6288. Assert(argsId);
  6289. ParseNodeUni * spreadArg = CreateUniNode(knopEllipsis, argsId, pnodeFnc->ichMin, pnodeFnc->ichLim);
  6290. ParseNodeSpecialName * superRef = ReferenceSpecialName(wellKnownPropertyPids._superConstructor, pnodeFnc->ichMin, pnodeFnc->ichLim, true);
  6291. pnodeFnc->SetHasSuperReference(TRUE);
  6292. ParseNodeSuperCall * callNode = CreateSuperCallNode(superRef, spreadArg);
  6293. callNode->pnodeThis = ReferenceSpecialName(wellKnownPropertyPids._this, pnodeFnc->ichMin, pnodeFnc->ichLim, true);
  6294. callNode->pnodeNewTarget = ReferenceSpecialName(wellKnownPropertyPids._newTarget, pnodeFnc->ichMin, pnodeFnc->ichLim, true);
  6295. callNode->spreadArgCount = 1;
  6296. AddToNodeList(&pnodeFnc->pnodeBody, &lastNodeRef, callNode);
  6297. }
  6298. AddToNodeList(&pnodeFnc->pnodeBody, &lastNodeRef, CreateNodeForOpT<knopEndCode>());
  6299. }
  6300. FinishParseBlock(pnodeInnerBlock);
  6301. CreateSpecialSymbolDeclarations(pnodeFnc);
  6302. FinishParseBlock(pnodeBlock);
  6303. m_currentNodeFunc = pnodeFncSave;
  6304. m_pCurrentAstSize = pAstSizeSave;
  6305. return pnodeFnc;
  6306. }
  6307. template<bool buildAST>
  6308. void Parser::ParseExpressionLambdaBody(ParseNodeFnc * pnodeLambda, bool fAllowIn)
  6309. {
  6310. ParseNodePtr *lastNodeRef = nullptr;
  6311. // The lambda body is a single expression, the result of which is the return value.
  6312. ParseNodeReturn * pnodeRet = nullptr;
  6313. if (buildAST)
  6314. {
  6315. pnodeRet = CreateNodeForOpT<knopReturn>();
  6316. pnodeRet->grfpn |= PNodeFlags::fpnSyntheticNode;
  6317. pnodeLambda->pnodeScopes->pnodeStmt = pnodeRet;
  6318. }
  6319. IdentToken token;
  6320. charcount_t lastRParen = 0;
  6321. // We need to disable deferred parse mode in the scanner because the lambda body doesn't end with a right paren.
  6322. // The scanner needs to create a pid in the case of a string constant token immediately following the lambda body expression.
  6323. // Otherwise, we'll save null for the string constant pid which will AV during ByteCode generation.
  6324. BYTE fScanDeferredFlagsSave = this->GetScanner()->SetDeferredParse(FALSE);
  6325. ParseNodePtr result = ParseExpr<buildAST>(koplAsg, nullptr, fAllowIn, FALSE, nullptr, nullptr, nullptr, &token, false, nullptr, &lastRParen);
  6326. this->GetScanner()->SetDeferredParseFlags(fScanDeferredFlagsSave);
  6327. this->MarkEscapingRef(result, &token);
  6328. if (buildAST)
  6329. {
  6330. pnodeRet->pnodeExpr = result;
  6331. pnodeRet->ichMin = pnodeRet->pnodeExpr->ichMin;
  6332. pnodeRet->ichLim = pnodeRet->pnodeExpr->ichLim;
  6333. // Pushing a statement node with PushStmt<>() normally does this initialization
  6334. // but do it here manually since we know there is no outer statement node.
  6335. pnodeRet->grfnop = 0;
  6336. pnodeRet->pnodeOuter = nullptr;
  6337. pnodeLambda->ichLim = max(pnodeRet->ichLim, lastRParen);
  6338. pnodeLambda->cbLim = this->GetScanner()->IecpLimTokPrevious();
  6339. pnodeLambda->pnodeScopes->ichLim = pnodeRet->ichLim;
  6340. pnodeLambda->pnodeBody = nullptr;
  6341. AddToNodeList(&pnodeLambda->pnodeBody, &lastNodeRef, pnodeRet);
  6342. // Append an EndCode node.
  6343. ParseNodePtr end = CreateNodeForOpT<knopEndCode>(pnodeRet->ichLim);
  6344. end->ichLim = end->ichMin; // make end code zero width at the immediate end of lambda body
  6345. AddToNodeList(&pnodeLambda->pnodeBody, &lastNodeRef, end);
  6346. // Lambda's do not have arguments binding
  6347. pnodeLambda->SetHasReferenceableBuiltInArguments(false);
  6348. }
  6349. else
  6350. {
  6351. pnodeLambda->ichLim = max(this->GetScanner()->IchLimTokPrevious(), lastRParen);
  6352. pnodeLambda->cbLim = this->GetScanner()->IecpLimTokPrevious();
  6353. }
  6354. }
  6355. void Parser::CheckStrictFormalParameters()
  6356. {
  6357. if (m_token.tk == tkID)
  6358. {
  6359. // single parameter arrow function case
  6360. IdentPtr pid = m_token.GetIdentifier(this->GetHashTbl());
  6361. CheckStrictModeEvalArgumentsUsage(pid);
  6362. return;
  6363. }
  6364. Assert(m_token.tk == tkLParen);
  6365. this->GetScanner()->ScanForcingPid();
  6366. if (m_token.tk != tkRParen)
  6367. {
  6368. SList<IdentPtr> formals(&m_nodeAllocator);
  6369. for (;;)
  6370. {
  6371. if (m_token.tk != tkID)
  6372. {
  6373. IdentifierExpectedError(m_token);
  6374. }
  6375. IdentPtr pid = m_token.GetIdentifier(this->GetHashTbl());
  6376. CheckStrictModeEvalArgumentsUsage(pid);
  6377. if (formals.Has(pid))
  6378. {
  6379. Error(ERRES5ArgSame, this->GetScanner()->IchMinTok(), this->GetScanner()->IchLimTok());
  6380. }
  6381. else
  6382. {
  6383. formals.Prepend(pid);
  6384. }
  6385. this->GetScanner()->Scan();
  6386. if (m_token.tk == tkAsg && m_scriptContext->GetConfig()->IsES6DefaultArgsEnabled())
  6387. {
  6388. this->GetScanner()->Scan();
  6389. // We can avoid building the AST since we are just checking the default expression.
  6390. ParseNodePtr pnodeInit = ParseExpr<false>(koplCma);
  6391. Assert(pnodeInit == nullptr);
  6392. }
  6393. if (m_token.tk != tkComma)
  6394. {
  6395. break;
  6396. }
  6397. this->GetScanner()->ScanForcingPid();
  6398. if (m_token.tk == tkRParen && m_scriptContext->GetConfig()->IsES7TrailingCommaEnabled())
  6399. {
  6400. break;
  6401. }
  6402. }
  6403. }
  6404. Assert(m_token.tk == tkRParen);
  6405. }
  6406. void Parser::FinishFncNode(ParseNodeFnc * pnodeFnc, bool fAllowIn)
  6407. {
  6408. AnalysisAssert(pnodeFnc);
  6409. // Finish the AST for a function that was deferred earlier, but which we decided
  6410. // to finish after the fact.
  6411. // We assume that the name(s) and arg(s) have already got parse nodes, so
  6412. // we just have to do the function body.
  6413. // Save the current next function Id, and resume from the old one.
  6414. Js::LocalFunctionId * nextFunctionIdSave = m_nextFunctionId;
  6415. Js::LocalFunctionId tempNextFunctionId = pnodeFnc->functionId + 1;
  6416. this->m_nextFunctionId = &tempNextFunctionId;
  6417. ParseNodeFnc * pnodeFncSave = m_currentNodeFunc;
  6418. uint *pnestedCountSave = m_pnestedCount;
  6419. int32* pAstSizeSave = m_pCurrentAstSize;
  6420. m_currentNodeFunc = pnodeFnc;
  6421. m_pCurrentAstSize = &(pnodeFnc->astSize);
  6422. pnodeFnc->nestedCount = 0;
  6423. m_pnestedCount = &pnodeFnc->nestedCount;
  6424. bool fLambda = pnodeFnc->IsLambda();
  6425. bool fMethod = pnodeFnc->IsMethod();
  6426. // Cue up the parser to the start of the function body.
  6427. if (pnodeFnc->pnodeName)
  6428. {
  6429. // Skip the name(s).
  6430. this->GetScanner()->SetCurrentCharacter(pnodeFnc->pnodeName->ichLim, pnodeFnc->lineNumber);
  6431. }
  6432. else
  6433. {
  6434. this->GetScanner()->SetCurrentCharacter(pnodeFnc->ichMin, pnodeFnc->lineNumber);
  6435. if (fMethod)
  6436. {
  6437. // Method. Skip identifier name, computed property name, "async", "get", "set", and '*' or '(' characters.
  6438. for (;;)
  6439. {
  6440. this->GetScanner()->Scan();
  6441. // '[' character indicates a computed property name for this method. We should consume it.
  6442. if (m_token.tk == tkLBrack)
  6443. {
  6444. // We don't care what the name expr is.
  6445. this->GetScanner()->Scan();
  6446. ParseExpr<false>();
  6447. Assert(m_token.tk == tkRBrack);
  6448. continue;
  6449. }
  6450. // Quit scanning ahead when we reach a '(' character which opens the arg list.
  6451. if (m_token.tk == tkLParen)
  6452. {
  6453. break;
  6454. }
  6455. }
  6456. }
  6457. else if (pnodeFnc->IsAccessor())
  6458. {
  6459. // Getter/setter. The node text starts with the name, so eat that.
  6460. this->GetScanner()->ScanNoKeywords();
  6461. }
  6462. else if (!fLambda)
  6463. {
  6464. // Anonymous function. Skip "async", "function", and '(' or '*' characters.
  6465. for (;;)
  6466. {
  6467. this->GetScanner()->Scan();
  6468. if (CheckContextualKeyword(wellKnownPropertyPids.async))
  6469. {
  6470. Assert(pnodeFnc->IsAsync());
  6471. continue;
  6472. }
  6473. // Quit scanning ahead when we reach a 'function' keyword which precedes the arg list.
  6474. if (m_token.tk == tkFUNCTION)
  6475. {
  6476. break;
  6477. }
  6478. Assert(m_token.tk == tkLParen || m_token.tk == tkStar);
  6479. }
  6480. }
  6481. }
  6482. // switch scanner to treat 'yield' as keyword in generator functions
  6483. // or as an identifier in non-generator functions
  6484. bool fPreviousYieldIsKeyword = this->GetScanner()->SetYieldIsKeywordRegion(pnodeFnc && pnodeFnc->IsGenerator());
  6485. bool fPreviousAwaitIsKeyword = this->GetScanner()->SetAwaitIsKeywordRegion(pnodeFnc && pnodeFnc->IsAsync());
  6486. // Skip the arg list.
  6487. if (!fMethod)
  6488. {
  6489. // If this is a method, we've already advanced to the '(' token.
  6490. this->GetScanner()->Scan();
  6491. }
  6492. if (m_token.tk == tkStar)
  6493. {
  6494. Assert(pnodeFnc->IsGenerator());
  6495. this->GetScanner()->ScanNoKeywords();
  6496. }
  6497. if (fLambda && CheckContextualKeyword(wellKnownPropertyPids.async))
  6498. {
  6499. Assert(pnodeFnc->IsAsync());
  6500. this->GetScanner()->ScanNoKeywords();
  6501. }
  6502. Assert(m_token.tk == tkLParen || (fLambda && m_token.tk == tkID));
  6503. this->GetScanner()->ScanNoKeywords();
  6504. if (m_token.tk != tkRParen && m_token.tk != tkDArrow)
  6505. {
  6506. for (;;)
  6507. {
  6508. if (m_token.tk == tkEllipsis)
  6509. {
  6510. this->GetScanner()->ScanNoKeywords();
  6511. }
  6512. if (m_token.tk == tkID)
  6513. {
  6514. this->GetScanner()->ScanNoKeywords();
  6515. if (m_token.tk == tkAsg)
  6516. {
  6517. // Eat the default expression
  6518. this->GetScanner()->Scan();
  6519. ParseExpr<false>(koplCma);
  6520. }
  6521. }
  6522. else if (IsPossiblePatternStart())
  6523. {
  6524. ParseDestructuredLiteralWithScopeSave(tkLET, false/*isDecl*/, false /*topLevel*/);
  6525. }
  6526. else
  6527. {
  6528. AssertMsg(false, "Unexpected identifier prefix while fast-scanning formals");
  6529. }
  6530. if (m_token.tk != tkComma)
  6531. {
  6532. break;
  6533. }
  6534. this->GetScanner()->ScanNoKeywords();
  6535. if (m_token.tk == tkRParen && m_scriptContext->GetConfig()->IsES7TrailingCommaEnabled())
  6536. {
  6537. break;
  6538. }
  6539. }
  6540. }
  6541. if (m_token.tk == tkRParen)
  6542. {
  6543. this->GetScanner()->Scan();
  6544. }
  6545. if (fLambda && m_token.tk == tkDArrow)
  6546. {
  6547. this->GetScanner()->Scan();
  6548. }
  6549. // Finish the function body.
  6550. {
  6551. // Note that in IE8- modes, surrounding parentheses are considered part of function body. e.g. "( function x(){} )".
  6552. // We lose that context here since we start from middle of function body. So save and restore source range info.
  6553. const charcount_t ichLim = pnodeFnc->ichLim;
  6554. const size_t cbLim = pnodeFnc->cbLim;
  6555. this->FinishFncDecl(pnodeFnc, NULL, fLambda, /* skipCurlyBraces */ false, fAllowIn);
  6556. #if DBG
  6557. // The pnode extent may not match the original extent.
  6558. // We expect this to happen only when there are trailing ")"'s.
  6559. // Consume them and make sure that's all we've got.
  6560. if (pnodeFnc->ichLim != ichLim)
  6561. {
  6562. Assert(pnodeFnc->ichLim < ichLim);
  6563. this->GetScanner()->SetCurrentCharacter(pnodeFnc->ichLim);
  6564. while (this->GetScanner()->IchLimTok() != ichLim)
  6565. {
  6566. this->GetScanner()->ScanNoKeywords();
  6567. Assert(m_token.tk == tkRParen);
  6568. }
  6569. }
  6570. #endif
  6571. pnodeFnc->ichLim = ichLim;
  6572. pnodeFnc->cbLim = cbLim;
  6573. }
  6574. m_currentNodeFunc = pnodeFncSave;
  6575. m_pCurrentAstSize = pAstSizeSave;
  6576. m_pnestedCount = pnestedCountSave;
  6577. Assert(m_pnestedCount);
  6578. Assert(tempNextFunctionId == pnodeFnc->deferredParseNextFunctionId);
  6579. this->m_nextFunctionId = nextFunctionIdSave;
  6580. this->GetScanner()->SetYieldIsKeywordRegion(fPreviousYieldIsKeyword);
  6581. this->GetScanner()->SetAwaitIsKeywordRegion(fPreviousAwaitIsKeyword);
  6582. }
  6583. void Parser::FinishFncDecl(ParseNodeFnc * pnodeFnc, LPCOLESTR pNameHint, bool fLambda, bool skipCurlyBraces, bool fAllowIn)
  6584. {
  6585. LPCOLESTR name = NULL;
  6586. JS_ETW(int32 startAstSize = *m_pCurrentAstSize);
  6587. if (IS_JS_ETW(EventEnabledJSCRIPT_PARSE_METHOD_START()) || PHASE_TRACE1(Js::DeferParsePhase))
  6588. {
  6589. name = GetFunctionName(pnodeFnc, pNameHint);
  6590. m_functionBody = NULL; // for nested functions we do not want to get the name of the top deferred function return name;
  6591. JS_ETW(EventWriteJSCRIPT_PARSE_METHOD_START(m_sourceContextInfo->dwHostSourceContext, GetScriptContext(), pnodeFnc->functionId, 0, m_parseType, name));
  6592. OUTPUT_TRACE(Js::DeferParsePhase, _u("Parsing function (%s) : %s (%d)\n"), GetParseType(), name, pnodeFnc->functionId);
  6593. }
  6594. JS_ETW_INTERNAL(EventWriteJSCRIPT_PARSE_FUNC(GetScriptContext(), pnodeFnc->functionId, /*Undefer*/FALSE));
  6595. // Do the work of creating an AST for a function body.
  6596. // This is common to the un-deferred case and the case in which we un-defer late in the game.
  6597. Assert(pnodeFnc->nop == knopFncDecl);
  6598. if (fLambda && m_token.tk != tkLCurly)
  6599. {
  6600. ParseExpressionLambdaBody<true>(pnodeFnc, fAllowIn);
  6601. }
  6602. else
  6603. {
  6604. if (!skipCurlyBraces)
  6605. {
  6606. ChkCurTok(tkLCurly, ERRnoLcurly);
  6607. }
  6608. ParseNodePtr * lastNodeRef = nullptr;
  6609. ParseStmtList<true>(&pnodeFnc->pnodeBody, &lastNodeRef, SM_OnFunctionCode, true /* isSourceElementList */);
  6610. // Append an EndCode node.
  6611. AddToNodeList(&pnodeFnc->pnodeBody, &lastNodeRef, CreateNodeForOpT<knopEndCode>());
  6612. if (!skipCurlyBraces)
  6613. {
  6614. ChkCurTokNoScan(tkRCurly, ERRnoRcurly);
  6615. }
  6616. pnodeFnc->ichLim = this->GetScanner()->IchLimTok();
  6617. pnodeFnc->cbLim = this->GetScanner()->IecpLimTok();
  6618. }
  6619. #ifdef ENABLE_JS_ETW
  6620. int32 astSize = *m_pCurrentAstSize - startAstSize;
  6621. EventWriteJSCRIPT_PARSE_METHOD_STOP(m_sourceContextInfo->dwHostSourceContext, GetScriptContext(), pnodeFnc->functionId, astSize, m_parseType, name);
  6622. #endif
  6623. }
  6624. ParseNodeVar * Parser::CreateSpecialVarDeclNode(ParseNodeFnc * pnodeFnc, IdentPtr pid)
  6625. {
  6626. ParseNodeVar * pnode = InsertVarAtBeginning(pnodeFnc, pid);
  6627. pnode->grfpn |= fpnSpecialSymbol;
  6628. // special symbol must not be global
  6629. pnode->sym->SetIsGlobal(false);
  6630. return pnode;
  6631. }
  6632. ParseNodeVar * Parser::InsertVarAtBeginning(ParseNodeFnc * pnodeFnc, IdentPtr pid)
  6633. {
  6634. ParseNodeVar * pnode = nullptr;
  6635. if (m_ppnodeVar == &pnodeFnc->pnodeVars)
  6636. {
  6637. pnode = CreateVarDeclNode(pid, STVariable, true, pnodeFnc);
  6638. }
  6639. else
  6640. {
  6641. ParseNodePtr * const ppnodeVarSave = m_ppnodeVar;
  6642. m_ppnodeVar = &pnodeFnc->pnodeVars;
  6643. pnode = CreateVarDeclNode(pid, STVariable, true, pnodeFnc);
  6644. m_ppnodeVar = ppnodeVarSave;
  6645. }
  6646. Assert(pnode);
  6647. return pnode;
  6648. }
  6649. ParseNodeVar * Parser::AddArgumentsNodeToVars(ParseNodeFnc * pnodeFnc)
  6650. {
  6651. Assert(!GetCurrentFunctionNode()->IsLambda());
  6652. ParseNodeVar * argNode = InsertVarAtBeginning(pnodeFnc, wellKnownPropertyPids.arguments);
  6653. argNode->grfpn |= PNodeFlags::fpnArguments; // Flag this as the built-in arguments node
  6654. return argNode;
  6655. }
  6656. void Parser::UpdateArgumentsNode(ParseNodeFnc * pnodeFnc, ParseNodeVar * argNode)
  6657. {
  6658. if ((pnodeFnc->grfpn & PNodeFlags::fpnArguments_overriddenInParam) || pnodeFnc->IsLambda())
  6659. {
  6660. // There is a parameter named arguments. So we don't have to create the built-in arguments.
  6661. pnodeFnc->SetHasReferenceableBuiltInArguments(false);
  6662. }
  6663. else if ((pnodeFnc->grfpn & PNodeFlags::fpnArguments_overriddenByDecl) && pnodeFnc->IsBodyAndParamScopeMerged())
  6664. {
  6665. // In non-split scope case there is a var or function definition named arguments in the body
  6666. pnodeFnc->SetHasReferenceableBuiltInArguments(false);
  6667. }
  6668. else
  6669. {
  6670. pnodeFnc->SetHasReferenceableBuiltInArguments(true);
  6671. Assert(argNode);
  6672. }
  6673. if (argNode != nullptr && !argNode->sym->IsArguments())
  6674. {
  6675. // A duplicate definition has updated the declaration node. Need to reset it back.
  6676. argNode->grfpn |= PNodeFlags::fpnArguments;
  6677. argNode->sym->SetDecl(argNode);
  6678. }
  6679. }
  6680. LPCOLESTR Parser::GetFunctionName(ParseNodeFnc * pnodeFnc, LPCOLESTR pNameHint)
  6681. {
  6682. LPCOLESTR name = nullptr;
  6683. if (pnodeFnc->pnodeName != nullptr)
  6684. {
  6685. Assert(pnodeFnc->pnodeName->nop == knopVarDecl);
  6686. name = pnodeFnc->pnodeName->pid->Psz();
  6687. }
  6688. if (name == nullptr && pNameHint != nullptr)
  6689. {
  6690. name = pNameHint;
  6691. }
  6692. if (name == nullptr && (pnodeFnc->IsLambda() ||
  6693. (!pnodeFnc->IsDeclaration() && !pnodeFnc->IsMethod())))
  6694. {
  6695. name = Js::Constants::AnonymousFunction;
  6696. }
  6697. if (name == nullptr && m_functionBody != nullptr)
  6698. {
  6699. name = m_functionBody->GetExternalDisplayName();
  6700. }
  6701. else if (name == nullptr)
  6702. {
  6703. name = Js::Constants::AnonymousFunction;
  6704. }
  6705. return name;
  6706. }
  6707. IdentPtr Parser::ParseClassPropertyName(IdentPtr * pidHint)
  6708. {
  6709. if (m_token.tk == tkID || m_token.tk == tkStrCon || m_token.IsReservedWord())
  6710. {
  6711. IdentPtr pid;
  6712. if (m_token.tk == tkStrCon)
  6713. {
  6714. if (this->GetScanner()->IsOctOrLeadingZeroOnLastTKNumber())
  6715. {
  6716. Error(ERRES5NoOctal);
  6717. }
  6718. pid = m_token.GetStr();
  6719. }
  6720. else
  6721. {
  6722. pid = m_token.GetIdentifier(this->GetHashTbl());
  6723. }
  6724. *pidHint = pid;
  6725. return pid;
  6726. }
  6727. else if (m_token.tk == tkIntCon)
  6728. {
  6729. if (this->GetScanner()->IsOctOrLeadingZeroOnLastTKNumber())
  6730. {
  6731. Error(ERRES5NoOctal);
  6732. }
  6733. return this->GetScanner()->PidFromLong(m_token.GetLong());
  6734. }
  6735. else if (m_token.tk == tkFltCon)
  6736. {
  6737. if (this->GetScanner()->IsOctOrLeadingZeroOnLastTKNumber())
  6738. {
  6739. Error(ERRES5NoOctal);
  6740. }
  6741. return this->GetScanner()->PidFromDbl(m_token.GetDouble());
  6742. }
  6743. Error(ERRnoMemberIdent);
  6744. }
  6745. LPCOLESTR Parser::ConstructFinalHintNode(IdentPtr pClassName, IdentPtr pMemberName, IdentPtr pGetSet, bool isStatic, uint32* nameLength, uint32* pShortNameOffset, bool isComputedName, LPCOLESTR pMemberNameHint)
  6746. {
  6747. if ((pMemberName == nullptr && !isComputedName) ||
  6748. (pMemberNameHint == nullptr && isComputedName) ||
  6749. !CONFIG_FLAG(UseFullName))
  6750. {
  6751. return nullptr;
  6752. }
  6753. LPCOLESTR pFinalName = isComputedName ? pMemberNameHint : pMemberName->Psz();
  6754. uint32 fullNameHintLength = (uint32)wcslen(pFinalName);
  6755. uint32 shortNameOffset = 0;
  6756. if (!isStatic)
  6757. {
  6758. // Add prototype.
  6759. pFinalName = AppendNameHints(wellKnownPropertyPids.prototype, pFinalName, &fullNameHintLength, &shortNameOffset);
  6760. }
  6761. if (pClassName)
  6762. {
  6763. uint32 classNameOffset = 0;
  6764. pFinalName = AppendNameHints(pClassName, pFinalName, &fullNameHintLength, &classNameOffset);
  6765. shortNameOffset += classNameOffset;
  6766. }
  6767. if (pGetSet)
  6768. {
  6769. // displays as get/set prototype.funcname
  6770. uint32 getSetOffset = 0;
  6771. pFinalName = AppendNameHints(pGetSet, pFinalName, &fullNameHintLength, &getSetOffset, true);
  6772. shortNameOffset += getSetOffset;
  6773. }
  6774. *nameLength = fullNameHintLength;
  6775. *pShortNameOffset = shortNameOffset;
  6776. return pFinalName;
  6777. }
  6778. template<bool buildAST>
  6779. ParseNodeClass * Parser::ParseClassDecl(BOOL isDeclaration, LPCOLESTR pNameHint, uint32 *pHintLength, uint32 *pShortNameOffset)
  6780. {
  6781. bool hasConstructor = false;
  6782. bool hasExtends = false;
  6783. IdentPtr name = nullptr;
  6784. ParseNodeVar * pnodeName = nullptr;
  6785. ParseNodeFnc * pnodeConstructor = nullptr;
  6786. ParseNodePtr pnodeExtends = nullptr;
  6787. ParseNodePtr pnodeMembers = nullptr;
  6788. ParseNodePtr *lastMemberNodeRef = nullptr;
  6789. uint32 nameHintLength = pHintLength ? *pHintLength : 0;
  6790. uint32 nameHintOffset = pShortNameOffset ? *pShortNameOffset : 0;
  6791. ArenaAllocator tempAllocator(_u("ClassMemberNames"), m_nodeAllocator.GetPageAllocator(), Parser::OutOfMemory);
  6792. size_t cbMinConstructor = 0;
  6793. ParseNodeClass * pnodeClass = nullptr;
  6794. if (buildAST)
  6795. {
  6796. pnodeClass = CreateNodeForOpT<knopClassDecl>();
  6797. CHAKRATEL_LANGSTATS_INC_LANGFEATURECOUNT(ES6, Class, m_scriptContext);
  6798. cbMinConstructor = this->GetScanner()->IecpMinTok();
  6799. }
  6800. BOOL strictSave = m_fUseStrictMode;
  6801. m_fUseStrictMode = TRUE;
  6802. this->GetScanner()->Scan();
  6803. if (m_token.tk == tkID)
  6804. {
  6805. name = m_token.GetIdentifier(this->GetHashTbl());
  6806. this->GetScanner()->Scan();
  6807. }
  6808. else if (isDeclaration)
  6809. {
  6810. IdentifierExpectedError(m_token);
  6811. }
  6812. if (isDeclaration && name == wellKnownPropertyPids.arguments && GetCurrentBlockInfo()->pnodeBlock->blockType == Function)
  6813. {
  6814. GetCurrentFunctionNode()->grfpn |= PNodeFlags::fpnArguments_overriddenByDecl;
  6815. }
  6816. ParseNodeVar * pnodeDeclName = nullptr;
  6817. if (isDeclaration)
  6818. {
  6819. pnodeDeclName = CreateBlockScopedDeclNode(name, knopLetDecl);
  6820. }
  6821. ParseNodePtr *ppnodeScopeSave = nullptr;
  6822. ParseNodePtr *ppnodeExprScopeSave = nullptr;
  6823. ParseNodeBlock * pnodeBlock = StartParseBlock<buildAST>(PnodeBlockType::Regular, ScopeType_Block);
  6824. if (buildAST)
  6825. {
  6826. PushFuncBlockScope(pnodeBlock, &ppnodeScopeSave, &ppnodeExprScopeSave);
  6827. pnodeClass->pnodeBlock = pnodeBlock;
  6828. }
  6829. if (name)
  6830. {
  6831. pnodeName = CreateBlockScopedDeclNode(name, knopConstDecl);
  6832. }
  6833. if (m_token.tk == tkEXTENDS)
  6834. {
  6835. this->GetScanner()->Scan();
  6836. pnodeExtends = ParseTerm<buildAST>();
  6837. hasExtends = true;
  6838. }
  6839. if (m_token.tk != tkLCurly)
  6840. {
  6841. Error(ERRnoLcurly);
  6842. }
  6843. OUTPUT_TRACE_DEBUGONLY(Js::ES6VerboseFlag, _u("Parsing class (%s) : %s\n"), GetParseType(), name ? name->Psz() : _u("anonymous class"));
  6844. RestorePoint beginClass;
  6845. this->GetScanner()->Capture(&beginClass);
  6846. this->GetScanner()->ScanForcingPid();
  6847. IdentPtr pClassNamePid = pnodeName ? pnodeName->pid : nullptr;
  6848. for (;;)
  6849. {
  6850. if (m_token.tk == tkSColon)
  6851. {
  6852. this->GetScanner()->ScanForcingPid();
  6853. continue;
  6854. }
  6855. if (m_token.tk == tkRCurly)
  6856. {
  6857. break;
  6858. }
  6859. bool isStatic = false;
  6860. if (m_token.tk == tkSTATIC)
  6861. {
  6862. // 'static' can be used as an IdentifierName here, even in strict mode code. We need to see the next token before we know
  6863. // if this is being used as a keyword. This is similar to the way we treat 'let' in some cases.
  6864. // See https://tc39.github.io/ecma262/#sec-keywords for more info.
  6865. RestorePoint beginStatic;
  6866. this->GetScanner()->Capture(&beginStatic);
  6867. this->GetScanner()->ScanForcingPid();
  6868. if (m_token.tk == tkLParen)
  6869. {
  6870. this->GetScanner()->SeekTo(beginStatic);
  6871. }
  6872. else
  6873. {
  6874. isStatic = true;
  6875. }
  6876. }
  6877. ushort fncDeclFlags = fFncNoName | fFncMethod | fFncClassMember;
  6878. charcount_t ichMin = this->GetScanner()->IchMinTok();
  6879. size_t iecpMin = this->GetScanner()->IecpMinTok();
  6880. ParseNodePtr pnodeMemberName = nullptr;
  6881. IdentPtr pidHint = nullptr;
  6882. IdentPtr memberPid = nullptr;
  6883. bool maybeAccessor = false;
  6884. LPCOLESTR pMemberNameHint = nullptr;
  6885. uint32 memberNameHintLength = 0;
  6886. uint32 memberNameOffset = 0;
  6887. bool isComputedName = false;
  6888. bool isAsyncMethod = false;
  6889. if (CheckContextualKeyword(wellKnownPropertyPids.async) && m_scriptContext->GetConfig()->IsES7AsyncAndAwaitEnabled())
  6890. {
  6891. RestorePoint parsedAsync;
  6892. this->GetScanner()->Capture(&parsedAsync);
  6893. ichMin = this->GetScanner()->IchMinTok();
  6894. iecpMin = this->GetScanner()->IecpMinTok();
  6895. this->GetScanner()->Scan();
  6896. if (m_token.tk == tkLParen || this->GetScanner()->FHadNewLine())
  6897. {
  6898. this->GetScanner()->SeekTo(parsedAsync);
  6899. }
  6900. else
  6901. {
  6902. isAsyncMethod = true;
  6903. }
  6904. }
  6905. bool isGenerator = m_scriptContext->GetConfig()->IsES6GeneratorsEnabled() &&
  6906. m_token.tk == tkStar;
  6907. if (isGenerator)
  6908. {
  6909. fncDeclFlags |= fFncGenerator;
  6910. this->GetScanner()->ScanForcingPid();
  6911. }
  6912. if (m_token.tk == tkLBrack && m_scriptContext->GetConfig()->IsES6ObjectLiteralsEnabled())
  6913. {
  6914. // Computed member name: [expr] () { }
  6915. LPCOLESTR emptyHint = nullptr;
  6916. ParseComputedName<buildAST>(&pnodeMemberName, &emptyHint, &pMemberNameHint, &memberNameHintLength, &memberNameOffset);
  6917. isComputedName = true;
  6918. }
  6919. else // not computed name
  6920. {
  6921. maybeAccessor = !this->GetScanner()->LastIdentifierHasEscape();
  6922. memberPid = this->ParseClassPropertyName(&pidHint);
  6923. if (pidHint)
  6924. {
  6925. pMemberNameHint = pidHint->Psz();
  6926. memberNameHintLength = pidHint->Cch();
  6927. }
  6928. }
  6929. if (buildAST && memberPid)
  6930. {
  6931. pnodeMemberName = CreateStrNode(memberPid);
  6932. }
  6933. if (!isStatic && memberPid == wellKnownPropertyPids.constructor)
  6934. {
  6935. if (hasConstructor || isAsyncMethod)
  6936. {
  6937. Error(ERRsyntax);
  6938. }
  6939. hasConstructor = true;
  6940. LPCOLESTR pConstructorName = nullptr;
  6941. uint32 constructorNameLength = 0;
  6942. uint32 constructorShortNameHintOffset = 0;
  6943. if (pnodeName && pnodeName->pid)
  6944. {
  6945. pConstructorName = pnodeName->pid->Psz();
  6946. constructorNameLength = pnodeName->pid->Cch();
  6947. }
  6948. else
  6949. {
  6950. pConstructorName = pNameHint;
  6951. constructorNameLength = nameHintLength;
  6952. constructorShortNameHintOffset = nameHintOffset;
  6953. }
  6954. {
  6955. SuperRestrictionState::State state = hasExtends ? SuperRestrictionState::CallAndPropertyAllowed : SuperRestrictionState::PropertyAllowed;
  6956. // Add the class constructor flag and base class constructor flag if pnodeExtends is nullptr
  6957. fncDeclFlags |= fFncClassConstructor | (hasExtends ? kFunctionNone : fFncBaseClassConstructor);
  6958. pnodeConstructor = ParseFncDeclNoCheckScope<buildAST>(fncDeclFlags, state, pConstructorName, /* needsPIDOnRCurlyScan */ true);
  6959. }
  6960. if (pnodeConstructor->IsGenerator())
  6961. {
  6962. Error(ERRConstructorCannotBeGenerator);
  6963. }
  6964. Assert(constructorNameLength >= constructorShortNameHintOffset);
  6965. // The constructor function will get the same name as class.
  6966. pnodeConstructor->hint = pConstructorName;
  6967. pnodeConstructor->hintLength = constructorNameLength;
  6968. pnodeConstructor->hintOffset = constructorShortNameHintOffset;
  6969. pnodeConstructor->pid = pnodeName && pnodeName->pid ? pnodeName->pid : wellKnownPropertyPids.constructor;
  6970. pnodeConstructor->SetHasNonThisStmt();
  6971. pnodeConstructor->SetHasHomeObj();
  6972. }
  6973. else
  6974. {
  6975. ParseNodePtr pnodeMember = nullptr;
  6976. RestorePoint beginMethodName;
  6977. this->GetScanner()->Capture(&beginMethodName);
  6978. if (maybeAccessor && (memberPid == wellKnownPropertyPids.get || memberPid == wellKnownPropertyPids.set))
  6979. {
  6980. this->GetScanner()->ScanForcingPid();
  6981. }
  6982. if (m_token.tk == tkLParen)
  6983. {
  6984. this->GetScanner()->SeekTo(beginMethodName);
  6985. maybeAccessor = false;
  6986. }
  6987. if (maybeAccessor && (memberPid == wellKnownPropertyPids.get || memberPid == wellKnownPropertyPids.set))
  6988. {
  6989. bool isGetter = (memberPid == wellKnownPropertyPids.get);
  6990. if (m_token.tk == tkLBrack && m_scriptContext->GetConfig()->IsES6ObjectLiteralsEnabled())
  6991. {
  6992. // Computed get/set member name: get|set [expr] () { }
  6993. LPCOLESTR emptyHint = nullptr;
  6994. ParseComputedName<buildAST>(&pnodeMemberName, &emptyHint, &pMemberNameHint, &memberNameHintLength, &memberNameOffset);
  6995. isComputedName = true;
  6996. }
  6997. else // not computed name
  6998. {
  6999. memberPid = this->ParseClassPropertyName(&pidHint);
  7000. }
  7001. if ((isStatic ? (memberPid == wellKnownPropertyPids.prototype) : (memberPid == wellKnownPropertyPids.constructor)) || isAsyncMethod)
  7002. {
  7003. Error(ERRsyntax);
  7004. }
  7005. if (buildAST && memberPid && !isComputedName)
  7006. {
  7007. pnodeMemberName = CreateStrNode(memberPid);
  7008. }
  7009. ParseNodeFnc * pnodeFnc = nullptr;
  7010. {
  7011. pnodeFnc = ParseFncDeclNoCheckScope<buildAST>(fncDeclFlags | (isGetter ? fFncNoArg : fFncOneArg),
  7012. SuperRestrictionState::PropertyAllowed, pidHint ? pidHint->Psz() : nullptr, /* needsPIDOnRCurlyScan */ true);
  7013. }
  7014. pnodeFnc->SetIsStaticMember(isStatic);
  7015. if (isComputedName)
  7016. {
  7017. pnodeFnc->SetHasComputedName();
  7018. }
  7019. pnodeFnc->SetHasHomeObj();
  7020. if (buildAST)
  7021. {
  7022. pnodeFnc->SetIsAccessor();
  7023. pnodeMember = CreateBinNode(isGetter ? knopGetMember : knopSetMember, pnodeMemberName, pnodeFnc);
  7024. pMemberNameHint = ConstructFinalHintNode(pClassNamePid, pidHint,
  7025. isGetter ? wellKnownPropertyPids.get : wellKnownPropertyPids.set, isStatic,
  7026. &memberNameHintLength, &memberNameOffset, isComputedName, pMemberNameHint);
  7027. }
  7028. }
  7029. else
  7030. {
  7031. if (isStatic && (memberPid == wellKnownPropertyPids.prototype))
  7032. {
  7033. Error(ERRsyntax);
  7034. }
  7035. ParseNodeFnc * pnodeFnc = nullptr;
  7036. {
  7037. if (isAsyncMethod)
  7038. {
  7039. fncDeclFlags |= fFncAsync;
  7040. }
  7041. pnodeFnc = ParseFncDeclNoCheckScope<buildAST>(fncDeclFlags, SuperRestrictionState::PropertyAllowed, pidHint ? pidHint->Psz() : nullptr, /* needsPIDOnRCurlyScan */ true);
  7042. if (isAsyncMethod || isGenerator || isComputedName)
  7043. {
  7044. pnodeFnc->cbStringMin = iecpMin;
  7045. pnodeFnc->cbStringLim = pnodeFnc->cbLim;
  7046. }
  7047. }
  7048. pnodeFnc->SetIsStaticMember(isStatic);
  7049. if (isComputedName)
  7050. {
  7051. pnodeFnc->SetHasComputedName();
  7052. }
  7053. pnodeFnc->SetHasHomeObj();
  7054. if (buildAST)
  7055. {
  7056. pnodeMember = CreateBinNode(knopMember, pnodeMemberName, pnodeFnc);
  7057. pMemberNameHint = ConstructFinalHintNode(pClassNamePid, pidHint, nullptr /*pgetset*/, isStatic, &memberNameHintLength, &memberNameOffset, isComputedName, pMemberNameHint);
  7058. }
  7059. }
  7060. if (buildAST)
  7061. {
  7062. Assert(memberNameHintLength >= memberNameOffset);
  7063. pnodeMember->AsParseNodeBin()->pnode2->AsParseNodeFnc()->hint = pMemberNameHint; // Fully qualified name
  7064. pnodeMember->AsParseNodeBin()->pnode2->AsParseNodeFnc()->hintLength = memberNameHintLength;
  7065. pnodeMember->AsParseNodeBin()->pnode2->AsParseNodeFnc()->hintOffset = memberNameOffset;
  7066. pnodeMember->AsParseNodeBin()->pnode2->AsParseNodeFnc()->pid = memberPid; // Short name
  7067. AddToNodeList(&pnodeMembers, &lastMemberNodeRef, pnodeMember);
  7068. }
  7069. }
  7070. }
  7071. size_t cbLimConstructor = 0;
  7072. if (buildAST)
  7073. {
  7074. pnodeClass->ichLim = this->GetScanner()->IchLimTok();
  7075. cbLimConstructor = this->GetScanner()->IecpLimTok();
  7076. }
  7077. if (!hasConstructor)
  7078. {
  7079. OUTPUT_TRACE_DEBUGONLY(Js::ES6VerboseFlag, _u("Generating constructor (%s) : %s\n"), GetParseType(), name ? name->Psz() : _u("anonymous class"));
  7080. RestorePoint endClass;
  7081. this->GetScanner()->Capture(&endClass);
  7082. this->GetScanner()->SeekTo(beginClass);
  7083. pnodeConstructor = GenerateEmptyConstructor<buildAST>(pnodeExtends != nullptr);
  7084. if (buildAST)
  7085. {
  7086. if (pClassNamePid)
  7087. {
  7088. pnodeConstructor->hint = pClassNamePid->Psz();
  7089. pnodeConstructor->hintLength = pClassNamePid->Cch();
  7090. pnodeConstructor->hintOffset = 0;
  7091. }
  7092. else
  7093. {
  7094. Assert(nameHintLength >= nameHintOffset);
  7095. pnodeConstructor->hint = pNameHint;
  7096. pnodeConstructor->hintLength = nameHintLength;
  7097. pnodeConstructor->hintOffset = nameHintOffset;
  7098. }
  7099. pnodeConstructor->pid = pClassNamePid;
  7100. }
  7101. this->GetScanner()->SeekTo(endClass);
  7102. }
  7103. if (buildAST)
  7104. {
  7105. pnodeConstructor->cbStringMin = cbMinConstructor;
  7106. pnodeConstructor->cbStringLim = cbLimConstructor;
  7107. PopFuncBlockScope(ppnodeScopeSave, ppnodeExprScopeSave);
  7108. pnodeClass->pnodeDeclName = pnodeDeclName;
  7109. pnodeClass->pnodeName = pnodeName;
  7110. pnodeClass->pnodeConstructor = pnodeConstructor;
  7111. pnodeClass->pnodeExtends = pnodeExtends;
  7112. pnodeClass->pnodeMembers = pnodeMembers;
  7113. pnodeClass->isDefaultModuleExport = false;
  7114. }
  7115. FinishParseBlock(pnodeBlock);
  7116. m_fUseStrictMode = strictSave;
  7117. this->GetScanner()->Scan();
  7118. return pnodeClass;
  7119. }
  7120. template<bool buildAST>
  7121. ParseNodePtr Parser::ParseStringTemplateDecl(ParseNodePtr pnodeTagFnc)
  7122. {
  7123. ParseNodePtr pnodeStringLiterals = nullptr;
  7124. ParseNodePtr* lastStringLiteralNodeRef = nullptr;
  7125. ParseNodePtr pnodeRawStringLiterals = nullptr;
  7126. ParseNodePtr* lastRawStringLiteralNodeRef = nullptr;
  7127. ParseNodePtr pnodeSubstitutionExpressions = nullptr;
  7128. ParseNodePtr* lastSubstitutionExpressionNodeRef = nullptr;
  7129. ParseNodePtr pnodeTagFncArgs = nullptr;
  7130. ParseNodePtr* lastTagFncArgNodeRef = nullptr;
  7131. ParseNodeStr * stringLiteral = nullptr;
  7132. ParseNodeStr * stringLiteralRaw = nullptr;
  7133. ParseNodeStrTemplate * pnodeStringTemplate = nullptr;
  7134. ParseNode * pnodeReturn = nullptr;
  7135. bool templateClosed = false;
  7136. const bool isTagged = pnodeTagFnc != nullptr;
  7137. uint16 stringConstantCount = 0;
  7138. charcount_t ichMin = 0;
  7139. Assert(m_token.tk == tkStrTmplBasic || m_token.tk == tkStrTmplBegin);
  7140. if (buildAST)
  7141. {
  7142. pnodeReturn = pnodeStringTemplate = CreateNodeForOpT<knopStrTemplate>();
  7143. pnodeStringTemplate->countStringLiterals = 0;
  7144. pnodeStringTemplate->isTaggedTemplate = isTagged ? TRUE : FALSE;
  7145. // If this is a tagged string template, we need to start building the arg list for the call
  7146. if (isTagged)
  7147. {
  7148. ichMin = pnodeTagFnc->ichMin;
  7149. AddToNodeListEscapedUse(&pnodeTagFncArgs, &lastTagFncArgNodeRef, pnodeStringTemplate);
  7150. }
  7151. }
  7152. CHAKRATEL_LANGSTATS_INC_LANGFEATURECOUNT(ES6, StringTemplates, m_scriptContext);
  7153. OUTPUT_TRACE_DEBUGONLY(
  7154. Js::StringTemplateParsePhase,
  7155. _u("Starting to parse a string template (%s)...\n\tis tagged = %s\n"),
  7156. GetParseType(),
  7157. isTagged ? _u("true") : _u("false (Raw and cooked strings will not differ!)"));
  7158. // String template grammar
  7159. // `...` Simple string template
  7160. // `...${ String template beginning
  7161. // }...${ String template middle
  7162. // }...` String template end
  7163. while (!templateClosed)
  7164. {
  7165. // First, extract the string constant part - we always have one
  7166. if (IsStrictMode() && this->GetScanner()->IsOctOrLeadingZeroOnLastTKNumber())
  7167. {
  7168. Error(ERRES5NoOctal);
  7169. }
  7170. // We are not able to pass more than a ushort worth of arguments to the tag
  7171. // so use that as a logical limit on the number of string constant pieces.
  7172. if (stringConstantCount >= Js::Constants::MaxAllowedArgs)
  7173. {
  7174. Error(ERRTooManyArgs);
  7175. }
  7176. // Keep track of the string literal count (must be the same for raw strings)
  7177. // We use this in code gen so we don't need to count the string literals list
  7178. stringConstantCount++;
  7179. // If we are not creating parse nodes, there is no need to create strings
  7180. if (buildAST)
  7181. {
  7182. stringLiteral = CreateStrNode(m_token.GetStr());
  7183. AddToNodeList(&pnodeStringLiterals, &lastStringLiteralNodeRef, stringLiteral);
  7184. // We only need to collect a raw string when we are going to pass the string template to a tag
  7185. if (isTagged)
  7186. {
  7187. // Make the scanner create a PID for the raw string constant for the preceding scan
  7188. IdentPtr pid = this->GetScanner()->GetSecondaryBufferAsPid();
  7189. stringLiteralRaw = CreateStrNode(pid);
  7190. // Should have gotten a raw string literal above
  7191. AddToNodeList(&pnodeRawStringLiterals, &lastRawStringLiteralNodeRef, stringLiteralRaw);
  7192. }
  7193. else
  7194. {
  7195. #if DBG
  7196. // Assign the raw string for debug tracing below
  7197. stringLiteralRaw = stringLiteral;
  7198. #endif
  7199. }
  7200. OUTPUT_TRACE_DEBUGONLY(
  7201. Js::StringTemplateParsePhase,
  7202. _u("Parsed string constant: \n\tcooked = \"%s\" \n\traw = \"%s\" \n\tdiffer = %d\n"),
  7203. stringLiteral->pid->Psz(),
  7204. stringLiteralRaw->pid->Psz(),
  7205. stringLiteral->pid->Psz() == stringLiteralRaw->pid->Psz() ? 0 : 1);
  7206. }
  7207. switch (m_token.tk)
  7208. {
  7209. case tkStrTmplEnd:
  7210. case tkStrTmplBasic:
  7211. // We do not need to parse an expression for either the end or basic string template tokens
  7212. templateClosed = true;
  7213. break;
  7214. case tkStrTmplBegin:
  7215. case tkStrTmplMid:
  7216. {
  7217. // In the middle or begin string template token case, we need to parse an expression next
  7218. this->GetScanner()->Scan();
  7219. // Parse the contents of the curly braces as an expression
  7220. ParseNodePtr expression = ParseExpr<buildAST>(0);
  7221. // After parsing expression, scan should leave us with an RCurly token.
  7222. // Use the NoScan version so we do not automatically perform a scan - we need to
  7223. // set the scan state before next scan but we don't want to set that state if
  7224. // the token is not as expected since we'll error in that case.
  7225. ChkCurTokNoScan(tkRCurly, ERRnoRcurly);
  7226. // Notify the scanner that it should scan for a middle or end string template token
  7227. this->GetScanner()->SetScanState(Scanner_t::ScanState::ScanStateStringTemplateMiddleOrEnd);
  7228. this->GetScanner()->Scan();
  7229. if (buildAST)
  7230. {
  7231. // If we are going to call the tag function, add this expression into the list of args
  7232. if (isTagged)
  7233. {
  7234. AddToNodeListEscapedUse(&pnodeTagFncArgs, &lastTagFncArgNodeRef, expression);
  7235. }
  7236. else
  7237. {
  7238. // Otherwise add it to the substitution expression list
  7239. // TODO: Store the arguments and substitution expressions in a single list?
  7240. AddToNodeList(&pnodeSubstitutionExpressions, &lastSubstitutionExpressionNodeRef, expression);
  7241. }
  7242. }
  7243. if (!(m_token.tk == tkStrTmplMid || m_token.tk == tkStrTmplEnd))
  7244. {
  7245. // Scan with ScanState ScanStateStringTemplateMiddleOrEnd should only return
  7246. // tkStrTmpMid/End unless it is EOF or tkScanError
  7247. Assert(m_token.tk == tkEOF || m_token.tk == tkScanError);
  7248. Error(ERRsyntax);
  7249. }
  7250. OUTPUT_TRACE_DEBUGONLY(Js::StringTemplateParsePhase, _u("Parsed expression\n"));
  7251. }
  7252. break;
  7253. default:
  7254. Assert(false);
  7255. break;
  7256. }
  7257. }
  7258. if (buildAST)
  7259. {
  7260. pnodeStringTemplate->pnodeStringLiterals = pnodeStringLiterals;
  7261. pnodeStringTemplate->pnodeStringRawLiterals = pnodeRawStringLiterals;
  7262. pnodeStringTemplate->pnodeSubstitutionExpressions = pnodeSubstitutionExpressions;
  7263. pnodeStringTemplate->countStringLiterals = stringConstantCount;
  7264. // We should still have the last string literal.
  7265. // Use the char offset of the end of that constant as the end of the string template.
  7266. pnodeStringTemplate->ichLim = stringLiteral->ichLim;
  7267. // If this is a tagged template, we now have the argument list and can construct a call node
  7268. if (isTagged)
  7269. {
  7270. // Return the call node here and let the byte code generator Emit the string template automagically
  7271. ParseNodeCall * pnodeCall;
  7272. pnodeReturn = pnodeCall = CreateCallNode(knopCall, pnodeTagFnc, pnodeTagFncArgs, ichMin, pnodeStringTemplate->ichLim);
  7273. // We need to set the arg count explicitly
  7274. pnodeCall->argCount = stringConstantCount;
  7275. pnodeCall->hasDestructuring = m_hasDestructuringPattern;
  7276. }
  7277. }
  7278. this->GetScanner()->Scan();
  7279. return pnodeReturn;
  7280. }
  7281. LPCOLESTR Parser::FormatPropertyString(LPCOLESTR propertyString, ParseNodePtr pNode, uint32 *fullNameHintLength, uint32 *pShortNameOffset)
  7282. {
  7283. // propertyString could be null, such as 'this.foo' =
  7284. // propertyString could be empty, found in pattern as in (-1)[""][(x = z)]
  7285. OpCode op = pNode->nop;
  7286. LPCOLESTR rightNode = nullptr;
  7287. if (propertyString == nullptr)
  7288. {
  7289. propertyString = _u("");
  7290. }
  7291. if (op != knopInt && op != knopFlt && op != knopName && op != knopStr)
  7292. {
  7293. rightNode = _u("");
  7294. }
  7295. else if (op == knopStr)
  7296. {
  7297. return AppendNameHints(propertyString, pNode->AsParseNodeStr()->pid, fullNameHintLength, pShortNameOffset, false, true/*add brackets*/);
  7298. }
  7299. else if (op == knopFlt)
  7300. {
  7301. rightNode = this->GetScanner()->StringFromDbl(pNode->AsParseNodeFloat()->dbl);
  7302. }
  7303. else
  7304. {
  7305. rightNode = op == knopInt ? this->GetScanner()->StringFromLong(pNode->AsParseNodeInt()->lw)
  7306. : pNode->AsParseNodeName()->pid->Psz();
  7307. }
  7308. return AppendNameHints(propertyString, rightNode, fullNameHintLength, pShortNameOffset, false, true/*add brackets*/);
  7309. }
  7310. LPCOLESTR Parser::ConstructNameHint(ParseNodeBin * pNode, uint32* fullNameHintLength, uint32 *pShortNameOffset)
  7311. {
  7312. Assert(pNode != nullptr);
  7313. Assert(pNode->nop == knopDot || pNode->nop == knopIndex);
  7314. // This method recursively visits nodes in the AST and could cause an SOE crash for long knopDot chains.
  7315. // Although this method could be made non-recursive, Emit (ByteCodeEmitter.cpp) hits a stack probe
  7316. // for shorter chains than which cause SOE here, so add a stack probe to throw SOE rather than crash on SOE.
  7317. // Because of that correspondence, use Js::Constants::MinStackByteCodeVisitor (which is used in Emit)
  7318. // for the stack probe here. See OS#14711878.
  7319. PROBE_STACK_NO_DISPOSE(this->m_scriptContext, Js::Constants::MinStackByteCodeVisitor);
  7320. LPCOLESTR leftNode = nullptr;
  7321. if (pNode->pnode1->nop == knopDot || pNode->pnode1->nop == knopIndex)
  7322. {
  7323. leftNode = ConstructNameHint(pNode->pnode1->AsParseNodeBin(), fullNameHintLength, pShortNameOffset);
  7324. }
  7325. else if (pNode->pnode1->nop == knopName && !pNode->pnode1->AsParseNodeName()->IsSpecialName())
  7326. {
  7327. // We need to skip special names like 'this' because those shouldn't be appended to the
  7328. // name hint in the debugger stack trace.
  7329. // function ctor() {
  7330. // this.func = function() {
  7331. // // If we break here, the stack should say we are in 'func' and not 'this.func'
  7332. // }
  7333. // }
  7334. IdentPtr pid = pNode->pnode1->AsParseNodeName()->pid;
  7335. leftNode = pid->Psz();
  7336. *fullNameHintLength = pid->Cch();
  7337. *pShortNameOffset = 0;
  7338. }
  7339. if (pNode->nop == knopIndex)
  7340. {
  7341. return FormatPropertyString(
  7342. leftNode ? leftNode : Js::Constants::AnonymousFunction, // e.g. f()[0] = function () {}
  7343. pNode->pnode2, fullNameHintLength, pShortNameOffset);
  7344. }
  7345. Assert(pNode->pnode2->nop == knopDot || pNode->pnode2->nop == knopName);
  7346. LPCOLESTR rightNode = nullptr;
  7347. bool wrapWithBrackets = false;
  7348. if (pNode->pnode2->nop == knopDot)
  7349. {
  7350. rightNode = ConstructNameHint(pNode->pnode2->AsParseNodeBin(), fullNameHintLength, pShortNameOffset);
  7351. }
  7352. else
  7353. {
  7354. rightNode = pNode->pnode2->AsParseNodeName()->pid->Psz();
  7355. wrapWithBrackets = PNodeFlags::fpnIndexOperator == (pNode->grfpn & PNodeFlags::fpnIndexOperator);
  7356. }
  7357. Assert(rightNode != nullptr);
  7358. return AppendNameHints(leftNode, rightNode, fullNameHintLength, pShortNameOffset, false, wrapWithBrackets);
  7359. }
  7360. LPCOLESTR Parser::AppendNameHints(LPCOLESTR leftStr, uint32 leftLen, LPCOLESTR rightStr, uint32 rightLen, uint32 *pNameLength, uint32 *pShortNameOffset, bool ignoreAddDotWithSpace, bool wrapInBrackets)
  7361. {
  7362. Assert(rightStr != nullptr);
  7363. Assert(leftLen != 0 || wrapInBrackets);
  7364. Assert(rightLen != 0 || wrapInBrackets);
  7365. 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
  7366. uint32 totalLength = leftLen + rightLen + ((ignoreDot) ? 1 : 2); // 1 (for dot or [) + 1 (for null termination)
  7367. if (wrapInBrackets)
  7368. {
  7369. totalLength++; //1 for ']';
  7370. }
  7371. WCHAR * finalName = AllocateStringOfLength(totalLength);
  7372. if (leftStr != nullptr && leftLen != 0)
  7373. {
  7374. wcscpy_s(finalName, leftLen + 1, leftStr);
  7375. }
  7376. if (ignoreAddDotWithSpace)
  7377. {
  7378. finalName[leftLen++] = (OLECHAR)_u(' ');
  7379. }
  7380. // mutually exclusive from ignoreAddDotWithSpace which is used for getters/setters
  7381. else if (wrapInBrackets)
  7382. {
  7383. finalName[leftLen++] = (OLECHAR)_u('[');
  7384. finalName[totalLength - 2] = (OLECHAR)_u(']');
  7385. }
  7386. else if (!ignoreDot)
  7387. {
  7388. finalName[leftLen++] = (OLECHAR)_u('.');
  7389. }
  7390. //ignore case falls through
  7391. js_wmemcpy_s(finalName + leftLen, rightLen, rightStr, rightLen);
  7392. finalName[totalLength - 1] = (OLECHAR)_u('\0');
  7393. if (pNameLength != nullptr)
  7394. {
  7395. *pNameLength = totalLength - 1;
  7396. }
  7397. if (pShortNameOffset != nullptr)
  7398. {
  7399. *pShortNameOffset = leftLen;
  7400. }
  7401. return finalName;
  7402. }
  7403. WCHAR * Parser::AllocateStringOfLength(ULONG length)
  7404. {
  7405. Assert(length > 0);
  7406. ULONG totalBytes;
  7407. if (ULongMult(length, sizeof(OLECHAR), &totalBytes) != S_OK)
  7408. {
  7409. Error(ERRnoMemory);
  7410. }
  7411. WCHAR* finalName = (WCHAR*)this->GetHashTbl()->GetAllocator()->Alloc(totalBytes);
  7412. if (finalName == nullptr)
  7413. {
  7414. Error(ERRnoMemory);
  7415. }
  7416. return finalName;
  7417. }
  7418. LPCOLESTR Parser::AppendNameHints(IdentPtr left, IdentPtr right, uint32 *pNameLength, uint32 *pShortNameOffset, bool ignoreAddDotWithSpace, bool wrapInBrackets)
  7419. {
  7420. if (pShortNameOffset != nullptr)
  7421. {
  7422. *pShortNameOffset = 0;
  7423. }
  7424. if (left == nullptr && !wrapInBrackets)
  7425. {
  7426. if (right)
  7427. {
  7428. *pNameLength = right->Cch();
  7429. return right->Psz();
  7430. }
  7431. return nullptr;
  7432. }
  7433. uint32 leftLen = 0;
  7434. LPCOLESTR leftStr = _u("");
  7435. if (left != nullptr) // if wrapInBrackets is true
  7436. {
  7437. leftStr = left->Psz();
  7438. leftLen = left->Cch();
  7439. }
  7440. if (right == nullptr)
  7441. {
  7442. *pNameLength = leftLen;
  7443. return left->Psz();
  7444. }
  7445. uint32 rightLen = right->Cch();
  7446. return AppendNameHints(leftStr, leftLen, right->Psz(), rightLen, pNameLength, pShortNameOffset, ignoreAddDotWithSpace, wrapInBrackets);
  7447. }
  7448. LPCOLESTR Parser::AppendNameHints(IdentPtr left, LPCOLESTR right, uint32 *pNameLength, uint32 *pShortNameOffset, bool ignoreAddDotWithSpace, bool wrapInBrackets)
  7449. {
  7450. uint32 rightLen = (right == nullptr) ? 0 : (uint32)wcslen(right);
  7451. if (pShortNameOffset != nullptr)
  7452. {
  7453. *pShortNameOffset = 0;
  7454. }
  7455. Assert(rightLen <= ULONG_MAX); // name hints should not exceed ULONG_MAX characters
  7456. if (left == nullptr && !wrapInBrackets)
  7457. {
  7458. *pNameLength = rightLen;
  7459. return right;
  7460. }
  7461. LPCOLESTR leftStr = _u("");
  7462. uint32 leftLen = 0;
  7463. if (left != nullptr) // if wrapInBrackets is true
  7464. {
  7465. leftStr = left->Psz();
  7466. leftLen = left->Cch();
  7467. }
  7468. if (rightLen == 0 && !wrapInBrackets)
  7469. {
  7470. *pNameLength = leftLen;
  7471. return left->Psz();
  7472. }
  7473. return AppendNameHints(leftStr, leftLen, right, rightLen, pNameLength, pShortNameOffset, ignoreAddDotWithSpace, wrapInBrackets);
  7474. }
  7475. LPCOLESTR Parser::AppendNameHints(LPCOLESTR left, IdentPtr right, uint32 *pNameLength, uint32 *pShortNameOffset, bool ignoreAddDotWithSpace, bool wrapInBrackets)
  7476. {
  7477. uint32 leftLen = (left == nullptr) ? 0 : (uint32)wcslen(left);
  7478. if (pShortNameOffset != nullptr)
  7479. {
  7480. *pShortNameOffset = 0;
  7481. }
  7482. Assert(leftLen <= ULONG_MAX); // name hints should not exceed ULONG_MAX characters
  7483. if (left == nullptr || (leftLen == 0 && !wrapInBrackets))
  7484. {
  7485. if (right != nullptr)
  7486. {
  7487. *pNameLength = right->Cch();
  7488. return right->Psz();
  7489. }
  7490. return nullptr;
  7491. }
  7492. if (right == nullptr)
  7493. {
  7494. *pNameLength = leftLen;
  7495. return left;
  7496. }
  7497. uint32 rightLen = right->Cch();
  7498. return AppendNameHints(left, leftLen, right->Psz(), rightLen, pNameLength, pShortNameOffset, ignoreAddDotWithSpace, wrapInBrackets);
  7499. }
  7500. LPCOLESTR Parser::AppendNameHints(LPCOLESTR left, LPCOLESTR right, uint32 *pNameLength, uint32 *pShortNameOffset, bool ignoreAddDotWithSpace, bool wrapInBrackets)
  7501. {
  7502. uint32 leftLen = (left == nullptr) ? 0 : (uint32)wcslen(left);
  7503. uint32 rightLen = (right == nullptr) ? 0 : (uint32)wcslen(right);
  7504. if (pShortNameOffset != nullptr)
  7505. {
  7506. *pShortNameOffset = 0;
  7507. }
  7508. Assert(rightLen <= ULONG_MAX && leftLen <= ULONG_MAX); // name hints should not exceed ULONG_MAX characters
  7509. if (leftLen == 0 && !wrapInBrackets)
  7510. {
  7511. *pNameLength = right ? rightLen : 0;
  7512. return right;
  7513. }
  7514. if (rightLen == 0 && !wrapInBrackets)
  7515. {
  7516. *pNameLength = leftLen;
  7517. return left;
  7518. }
  7519. return AppendNameHints(left, leftLen, right, rightLen, pNameLength, pShortNameOffset, ignoreAddDotWithSpace, wrapInBrackets);
  7520. }
  7521. /**
  7522. * Emits a spread error if there is no ambiguity, or marks defers the error for
  7523. * when we can determine if it is a rest error or a spread error.
  7524. *
  7525. * The ambiguity arises when we are parsing a lambda parameter list but we have
  7526. * not seen the => token. At this point, we are either in a parenthesized
  7527. * expression or a parameter list, and cannot issue an error until the matching
  7528. * RParen has been scanned.
  7529. *
  7530. * The actual emission of the error happens in ParseExpr, when we first know if
  7531. * the expression is a lambda parameter list or not.
  7532. *
  7533. */
  7534. void Parser::DeferOrEmitPotentialSpreadError(ParseNodePtr pnodeT)
  7535. {
  7536. if (m_funcParenExprDepth > 0)
  7537. {
  7538. if (m_token.tk == tkRParen)
  7539. {
  7540. if (!m_deferEllipsisError)
  7541. {
  7542. // Capture only the first error instance. Because a lambda will cause a reparse in a formals context, we can assume
  7543. // that this will be a spread error. Nested paren exprs will have their own error instance.
  7544. this->GetScanner()->Capture(&m_deferEllipsisErrorLoc);
  7545. m_deferEllipsisError = true;
  7546. }
  7547. }
  7548. else
  7549. {
  7550. Error(ERRUnexpectedEllipsis);
  7551. }
  7552. }
  7553. else
  7554. {
  7555. Error(ERRInvalidSpreadUse);
  7556. }
  7557. }
  7558. bool Parser::IsTerminateToken(bool fAllowIn)
  7559. {
  7560. return (m_token.tk == tkRCurly ||
  7561. m_token.tk == tkRBrack ||
  7562. m_token.tk == tkRParen ||
  7563. m_token.tk == tkSColon ||
  7564. m_token.tk == tkColon ||
  7565. m_token.tk == tkComma ||
  7566. m_token.tk == tkLimKwd ||
  7567. (m_token.tk == tkIN && fAllowIn) ||
  7568. this->GetScanner()->FHadNewLine());
  7569. }
  7570. /***************************************************************************
  7571. Parse an optional sub expression returning null if there was no expression.
  7572. Checks for no expression by looking for a token that can follow an
  7573. Expression grammar production.
  7574. ***************************************************************************/
  7575. template<bool buildAST>
  7576. bool Parser::ParseOptionalExpr(ParseNodePtr* pnode, bool fUnaryOrParen, int oplMin, BOOL *pfCanAssign, BOOL fAllowIn, BOOL fAllowEllipsis, _Inout_opt_ IdentToken* pToken)
  7577. {
  7578. *pnode = nullptr;
  7579. if (IsTerminateToken(!fAllowIn))
  7580. {
  7581. return false;
  7582. }
  7583. IdentToken token;
  7584. ParseNodePtr pnodeT = ParseExpr<buildAST>(oplMin, pfCanAssign, fAllowIn, fAllowEllipsis, nullptr /*pNameHint*/, nullptr /*pHintLength*/, nullptr /*pShortNameOffset*/, &token, fUnaryOrParen);
  7585. // Detect nested function escapes of the pattern "return function(){...}" or "yield function(){...}".
  7586. // Doing so in the parser allows us to disable stack-nested-functions in common cases where an escape
  7587. // is not detected at byte code gen time because of deferred parsing.
  7588. this->MarkEscapingRef(pnodeT, &token);
  7589. if (pToken)
  7590. {
  7591. *pToken = token;
  7592. }
  7593. *pnode = pnodeT;
  7594. return true;
  7595. }
  7596. /***************************************************************************
  7597. Parse a sub expression.
  7598. 'fAllowIn' indicates if the 'in' operator should be allowed in the initializing
  7599. expression ( it is not allowed in the context of the first expression in a 'for' loop).
  7600. ***************************************************************************/
  7601. template<bool buildAST>
  7602. ParseNodePtr Parser::ParseExpr(int oplMin,
  7603. BOOL *pfCanAssign,
  7604. BOOL fAllowIn,
  7605. BOOL fAllowEllipsis,
  7606. LPCOLESTR pNameHint,
  7607. uint32 *pHintLength,
  7608. uint32 *pShortNameOffset,
  7609. _Inout_opt_ IdentToken* pToken,
  7610. bool fUnaryOrParen,
  7611. _Inout_opt_ bool* pfLikelyPattern,
  7612. _Inout_opt_ charcount_t *plastRParen)
  7613. {
  7614. Assert(pToken == nullptr || pToken->tk == tkNone); // Must be empty initially
  7615. int opl;
  7616. OpCode nop;
  7617. charcount_t ichMin;
  7618. ParseNodePtr pnode = nullptr;
  7619. ParseNodePtr pnodeT = nullptr;
  7620. BOOL fCanAssign = TRUE;
  7621. bool assignmentStmt = false;
  7622. bool fIsDotOrIndex = false;
  7623. IdentToken term;
  7624. RestorePoint termStart;
  7625. uint32 hintLength = 0;
  7626. uint32 hintOffset = 0;
  7627. BOOL fLikelyPattern = FALSE;
  7628. ParserState parserState;
  7629. if (pHintLength != nullptr)
  7630. {
  7631. hintLength = *pHintLength;
  7632. }
  7633. if (pShortNameOffset != nullptr)
  7634. {
  7635. hintOffset = *pShortNameOffset;
  7636. }
  7637. EnsureStackAvailable();
  7638. // Storing the state here as we need to restore this state back when we need to reparse the grammar under lambda syntax.
  7639. CaptureState(&parserState);
  7640. this->GetScanner()->Capture(&termStart);
  7641. bool savedDeferredInitError = m_hasDeferredShorthandInitError;
  7642. m_hasDeferredShorthandInitError = false;
  7643. // Is the current token a unary operator?
  7644. if (this->GetHashTbl()->TokIsUnop(m_token.tk, &opl, &nop) && nop != knopNone)
  7645. {
  7646. IdentToken operandToken;
  7647. ichMin = this->GetScanner()->IchMinTok();
  7648. if (nop == knopYield)
  7649. {
  7650. if (!this->GetScanner()->YieldIsKeywordRegion() || oplMin > opl)
  7651. {
  7652. // The case where 'yield' is scanned as a keyword (tkYIELD) but the scanner
  7653. // is not treating yield as a keyword (!this->GetScanner()->YieldIsKeywordRegion()) occurs
  7654. // in strict mode non-generator function contexts.
  7655. //
  7656. // That is, 'yield' is a keyword because of strict mode, but YieldExpression
  7657. // is not a grammar production outside of generator functions.
  7658. //
  7659. // Otherwise it is an error for a yield to appear in the context of a higher level
  7660. // binding operator, be it unary or binary.
  7661. Error(ERRsyntax);
  7662. }
  7663. if (m_currentScope->GetScopeType() == ScopeType_Parameter
  7664. || (m_currentScope->GetScopeType() == ScopeType_Block && m_currentScope->GetEnclosingScope()->GetScopeType() == ScopeType_Parameter)) // Check whether this is a class definition inside param scope
  7665. {
  7666. Error(ERRsyntax);
  7667. }
  7668. }
  7669. else if (nop == knopAwait)
  7670. {
  7671. if (!this->GetScanner()->AwaitIsKeywordRegion() ||
  7672. m_currentScope->GetScopeType() == ScopeType_Parameter ||
  7673. (m_currentScope->GetScopeType() == ScopeType_Block && m_currentScope->GetEnclosingScope()->GetScopeType() == ScopeType_Parameter)) // Check whether this is a class definition inside param scope
  7674. {
  7675. // As with the 'yield' keyword, the case where 'await' is scanned as a keyword (tkAWAIT)
  7676. // but the scanner is not treating await as a keyword (!this->GetScanner()->AwaitIsKeyword())
  7677. // occurs in strict mode non-async function contexts.
  7678. //
  7679. // That is, 'await' is a keyword because of strict mode, but AwaitExpression
  7680. // is not a grammar production outside of async functions.
  7681. //
  7682. // Further, await expressions are disallowed within parameter scopes.
  7683. Error(ERRBadAwait);
  7684. }
  7685. }
  7686. this->GetScanner()->Scan();
  7687. if (m_token.tk == tkEllipsis) {
  7688. // ... cannot have a unary prefix.
  7689. Error(ERRUnexpectedEllipsis);
  7690. }
  7691. if (nop == knopYield && !this->GetScanner()->FHadNewLine() && m_token.tk == tkStar)
  7692. {
  7693. this->GetScanner()->Scan();
  7694. nop = knopYieldStar;
  7695. }
  7696. if (nop == knopYield)
  7697. {
  7698. if (!ParseOptionalExpr<buildAST>(&pnodeT, false, opl, NULL, fAllowIn, fAllowEllipsis))
  7699. {
  7700. nop = knopYieldLeaf;
  7701. if (buildAST)
  7702. {
  7703. pnode = CreateNodeForOpT<knopYieldLeaf>(ichMin, this->GetScanner()->IchLimTok());
  7704. }
  7705. }
  7706. }
  7707. else if (nop == knopAwait && m_token.tk == tkColon)
  7708. {
  7709. Error(ERRAwaitAsLabelInAsync);
  7710. }
  7711. else
  7712. {
  7713. // Disallow spread after a unary operator.
  7714. pnodeT = ParseExpr<buildAST>(opl, &fCanAssign, TRUE, FALSE, nullptr /*hint*/, nullptr /*hintLength*/, nullptr /*hintOffset*/, &operandToken, true, nullptr, plastRParen);
  7715. }
  7716. if (nop != knopYieldLeaf)
  7717. {
  7718. if ((nop == knopIncPre || nop == knopDecPre) && (m_token.tk != tkDArrow))
  7719. {
  7720. if (!fCanAssign &&
  7721. (m_sourceContextInfo
  7722. ? !PHASE_OFF_RAW(Js::EarlyReferenceErrorsPhase, m_sourceContextInfo->sourceContextId, GetCurrentFunctionNode()->functionId)
  7723. : !PHASE_OFF1(Js::EarlyReferenceErrorsPhase)))
  7724. {
  7725. Error(ERRInvalidAsgTarget);
  7726. }
  7727. TrackAssignment<buildAST>(pnodeT, &operandToken);
  7728. if (buildAST)
  7729. {
  7730. if (IsStrictMode() && pnodeT->nop == knopName)
  7731. {
  7732. CheckStrictModeEvalArgumentsUsage(pnodeT->AsParseNodeName()->pid);
  7733. }
  7734. }
  7735. else
  7736. {
  7737. if (IsStrictMode() && operandToken.tk == tkID)
  7738. {
  7739. CheckStrictModeEvalArgumentsUsage(operandToken.pid);
  7740. }
  7741. }
  7742. }
  7743. else if (nop == knopEllipsis)
  7744. {
  7745. if (!fAllowEllipsis)
  7746. {
  7747. DeferOrEmitPotentialSpreadError(pnodeT);
  7748. }
  7749. }
  7750. else if (m_token.tk == tkExpo)
  7751. {
  7752. //Unary operator on the left hand-side of ** is unexpected, except ++, -- or ...
  7753. Error(ERRInvalidUseofExponentiationOperator);
  7754. }
  7755. if (buildAST)
  7756. {
  7757. //Do not do the folding for Asm in case of KnopPos as we need this to determine the type
  7758. if (nop == knopPos && (pnodeT->nop == knopInt || pnodeT->nop == knopFlt) && !this->m_InAsmMode)
  7759. {
  7760. // Fold away a unary '+' on a number.
  7761. pnode = pnodeT;
  7762. }
  7763. else if (nop == knopNeg &&
  7764. ((pnodeT->nop == knopInt && pnodeT->AsParseNodeInt()->lw != 0) ||
  7765. (pnodeT->nop == knopFlt && (pnodeT->AsParseNodeFloat()->dbl != 0 || this->m_InAsmMode)) ||
  7766. (pnodeT->nop == knopBigInt)))
  7767. {
  7768. // Fold a unary '-' on a number into the value of the number itself.
  7769. pnode = pnodeT;
  7770. if (pnode->nop == knopInt)
  7771. {
  7772. pnode->AsParseNodeInt()->lw = -pnode->AsParseNodeInt()->lw;
  7773. }
  7774. else if (pnode->nop == knopBigInt)
  7775. {
  7776. pnode->AsParseNodeBigInt()->isNegative = true;
  7777. }
  7778. else
  7779. {
  7780. pnode->AsParseNodeFloat()->dbl = -pnode->AsParseNodeFloat()->dbl;
  7781. }
  7782. }
  7783. else
  7784. {
  7785. pnode = CreateUniNode(nop, pnodeT);
  7786. this->CheckArguments(pnode->AsParseNodeUni()->pnode1);
  7787. }
  7788. pnode->ichMin = ichMin;
  7789. }
  7790. if (nop == knopDelete)
  7791. {
  7792. if (IsStrictMode())
  7793. {
  7794. if ((buildAST && pnode->AsParseNodeUni()->pnode1->IsUserIdentifier()) ||
  7795. (!buildAST && operandToken.tk == tkID && !this->IsSpecialName(operandToken.pid)))
  7796. {
  7797. Error(ERRInvalidDelete);
  7798. }
  7799. }
  7800. if (buildAST)
  7801. {
  7802. ParseNodePtr pnode1 = pnode->AsParseNodeUni()->pnode1;
  7803. if (m_currentNodeFunc)
  7804. {
  7805. if (pnode1->nop == knopDot || pnode1->nop == knopIndex)
  7806. {
  7807. // If we delete an arguments property, use the conservative,
  7808. // heap-allocated arguments object.
  7809. this->CheckArguments(pnode1->AsParseNodeBin()->pnode1);
  7810. }
  7811. }
  7812. }
  7813. }
  7814. }
  7815. fCanAssign = FALSE;
  7816. }
  7817. else
  7818. {
  7819. ichMin = this->GetScanner()->IchMinTok();
  7820. pnode = ParseTerm<buildAST>(TRUE, pNameHint, &hintLength, &hintOffset, &term, fUnaryOrParen, TRUE, &fCanAssign, IsES6DestructuringEnabled() ? &fLikelyPattern : nullptr, &fIsDotOrIndex, plastRParen);
  7821. if (pfLikelyPattern != nullptr)
  7822. {
  7823. *pfLikelyPattern = !!fLikelyPattern;
  7824. }
  7825. if (m_token.tk == tkDArrow
  7826. // If we have introduced shorthand error above in the ParseExpr, we need to reset if next token is the assignment.
  7827. || (m_token.tk == tkAsg && oplMin <= koplAsg))
  7828. {
  7829. m_hasDeferredShorthandInitError = false;
  7830. }
  7831. if (m_token.tk == tkAsg && oplMin <= koplAsg && fLikelyPattern)
  7832. {
  7833. this->GetScanner()->SeekTo(termStart);
  7834. // 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
  7835. // on the pidref stack match.
  7836. int saveNextBlockId = m_nextBlockId;
  7837. m_nextBlockId = parserState.m_nextBlockId;
  7838. ParseDestructuredLiteralWithScopeSave(tkLCurly, false/*isDecl*/, false /*topLevel*/, DIC_ShouldNotParseInitializer);
  7839. fCanAssign = TRUE;
  7840. // 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
  7841. // because we don't parse initializers during reparse and there may be additional blocks (e.g. a class declaration)
  7842. // in the initializers that will cause the next Block ID at the end of the reparsing to be different.
  7843. m_nextBlockId = saveNextBlockId;
  7844. if (buildAST)
  7845. {
  7846. this->SetHasDestructuringPattern(true);
  7847. pnode = ConvertToPattern(pnode);
  7848. }
  7849. }
  7850. if (buildAST)
  7851. {
  7852. pNameHint = NULL;
  7853. if (pnode->nop == knopName)
  7854. {
  7855. IdentPtr pid = pnode->AsParseNodeName()->pid;
  7856. pNameHint = pid->Psz();
  7857. hintLength = pid->Cch();
  7858. hintOffset = 0;
  7859. }
  7860. else if (pnode->nop == knopDot || pnode->nop == knopIndex)
  7861. {
  7862. if (CONFIG_FLAG(UseFullName))
  7863. {
  7864. pNameHint = ConstructNameHint(pnode->AsParseNodeBin(), &hintLength, &hintOffset);
  7865. }
  7866. else
  7867. {
  7868. ParseNodePtr pnodeName = pnode;
  7869. while (pnodeName->nop == knopDot)
  7870. {
  7871. pnodeName = pnodeName->AsParseNodeBin()->pnode2;
  7872. }
  7873. if (pnodeName->nop == knopName)
  7874. {
  7875. IdentPtr pid = pnode->AsParseNodeName()->pid;
  7876. pNameHint = pid->Psz();
  7877. hintLength = pid->Cch();
  7878. hintOffset = 0;
  7879. }
  7880. }
  7881. }
  7882. }
  7883. // Check for postfix unary operators.
  7884. if (!this->GetScanner()->FHadNewLine() &&
  7885. (tkInc == m_token.tk || tkDec == m_token.tk))
  7886. {
  7887. if (!fCanAssign &&
  7888. (m_sourceContextInfo
  7889. ? !PHASE_OFF_RAW(Js::EarlyReferenceErrorsPhase, m_sourceContextInfo->sourceContextId, GetCurrentFunctionNode()->functionId)
  7890. : !PHASE_OFF1(Js::EarlyReferenceErrorsPhase)))
  7891. {
  7892. Error(ERRInvalidAsgTarget);
  7893. }
  7894. TrackAssignment<buildAST>(pnode, &term);
  7895. fCanAssign = FALSE;
  7896. if (buildAST)
  7897. {
  7898. if (IsStrictMode() && pnode->nop == knopName)
  7899. {
  7900. CheckStrictModeEvalArgumentsUsage(pnode->AsParseNodeName()->pid);
  7901. }
  7902. this->CheckArguments(pnode);
  7903. pnode = CreateUniNode(tkInc == m_token.tk ? knopIncPost : knopDecPost, pnode);
  7904. pnode->ichLim = this->GetScanner()->IchLimTok();
  7905. }
  7906. else
  7907. {
  7908. if (IsStrictMode() && term.tk == tkID)
  7909. {
  7910. CheckStrictModeEvalArgumentsUsage(term.pid);
  7911. }
  7912. // This expression is not an identifier
  7913. term.tk = tkNone;
  7914. }
  7915. this->GetScanner()->Scan();
  7916. }
  7917. }
  7918. // Process a sequence of operators and operands.
  7919. for (;;)
  7920. {
  7921. if (!this->GetHashTbl()->TokIsBinop(m_token.tk, &opl, &nop) || nop == knopNone)
  7922. {
  7923. break;
  7924. }
  7925. if (!fAllowIn && nop == knopIn)
  7926. {
  7927. break;
  7928. }
  7929. Assert(opl != koplNo);
  7930. if (opl == koplAsg)
  7931. {
  7932. if (m_token.tk != tkDArrow)
  7933. {
  7934. // Assignment operator. These are the only right associative
  7935. // binary operators. We also need to special case the left
  7936. // operand - it should only be a LeftHandSideExpression.
  7937. Assert(ParseNode::Grfnop(nop) & fnopAsg || nop == knopFncDecl);
  7938. TrackAssignment<buildAST>(pnode, &term);
  7939. if (buildAST)
  7940. {
  7941. if (IsStrictMode() && pnode->nop == knopName)
  7942. {
  7943. CheckStrictModeEvalArgumentsUsage(pnode->AsParseNodeName()->pid);
  7944. }
  7945. // Assignment stmt of the form "this.<id> = <expr>"
  7946. if (nop == knopAsg
  7947. && pnode->nop == knopDot
  7948. && pnode->AsParseNodeBin()->pnode1->nop == knopName
  7949. && pnode->AsParseNodeBin()->pnode1->AsParseNodeName()->pid == wellKnownPropertyPids._this
  7950. && pnode->AsParseNodeBin()->pnode2->nop == knopName)
  7951. {
  7952. if (pnode->AsParseNodeBin()->pnode2->AsParseNodeName()->pid != wellKnownPropertyPids.__proto__)
  7953. {
  7954. assignmentStmt = true;
  7955. }
  7956. }
  7957. }
  7958. else
  7959. {
  7960. if (IsStrictMode() && term.tk == tkID)
  7961. {
  7962. CheckStrictModeEvalArgumentsUsage(term.pid);
  7963. }
  7964. }
  7965. }
  7966. if (opl < oplMin)
  7967. {
  7968. break;
  7969. }
  7970. if (m_token.tk != tkDArrow && !fCanAssign &&
  7971. (m_sourceContextInfo
  7972. ? !PHASE_OFF_RAW(Js::EarlyReferenceErrorsPhase, m_sourceContextInfo->sourceContextId, GetCurrentFunctionNode()->functionId)
  7973. : !PHASE_OFF1(Js::EarlyReferenceErrorsPhase)))
  7974. {
  7975. Error(ERRInvalidAsgTarget);
  7976. // No recovery necessary since this is a semantic, not structural, error.
  7977. }
  7978. }
  7979. else if (opl == koplExpo)
  7980. {
  7981. // ** operator is right associative
  7982. if (opl < oplMin)
  7983. {
  7984. break;
  7985. }
  7986. }
  7987. else if (opl <= oplMin)
  7988. {
  7989. break;
  7990. }
  7991. // This expression is not an identifier
  7992. term.tk = tkNone;
  7993. // Precedence is high enough. Consume the operator token.
  7994. this->GetScanner()->Scan();
  7995. fCanAssign = !!fLikelyPattern;
  7996. // Special case the "?:" operator
  7997. if (nop == knopQmark)
  7998. {
  7999. pnodeT = ParseExpr<buildAST>(koplAsg, NULL, TRUE);
  8000. ChkCurTok(tkColon, ERRnoColon);
  8001. ParseNodePtr pnodeT2 = ParseExpr<buildAST>(koplAsg, NULL, fAllowIn, 0, nullptr, nullptr, nullptr, nullptr, false, nullptr, plastRParen);
  8002. if (buildAST)
  8003. {
  8004. pnode = CreateTriNode(nop, pnode, pnodeT, pnodeT2);
  8005. this->CheckArguments(pnode->AsParseNodeTri()->pnode2);
  8006. this->CheckArguments(pnode->AsParseNodeTri()->pnode3);
  8007. }
  8008. }
  8009. else if (nop == knopFncDecl)
  8010. {
  8011. ushort flags = fFncLambda;
  8012. size_t iecpMin = 0;
  8013. bool isAsyncMethod = false;
  8014. RestoreStateFrom(&parserState);
  8015. this->GetScanner()->SeekTo(termStart);
  8016. if (CheckContextualKeyword(wellKnownPropertyPids.async) && m_scriptContext->GetConfig()->IsES7AsyncAndAwaitEnabled())
  8017. {
  8018. ichMin = this->GetScanner()->IchMinTok();
  8019. iecpMin = this->GetScanner()->IecpMinTok();
  8020. this->GetScanner()->Scan();
  8021. if ((m_token.tk == tkID || m_token.tk == tkLParen) && !this->GetScanner()->FHadNewLine())
  8022. {
  8023. flags |= fFncAsync;
  8024. isAsyncMethod = true;
  8025. }
  8026. else
  8027. {
  8028. this->GetScanner()->SeekTo(termStart);
  8029. }
  8030. }
  8031. pnode = ParseFncDeclNoCheckScope<buildAST>(flags, SuperRestrictionState::Disallowed, nullptr, /* needsPIDOnRCurlyScan = */false, /* fUnaryOrParen = */ false, fAllowIn);
  8032. if (isAsyncMethod)
  8033. {
  8034. pnode->AsParseNodeFnc()->cbStringMin = iecpMin;
  8035. pnode->AsParseNodeFnc()->cbStringLim = pnode->AsParseNodeFnc()->cbLim;
  8036. }
  8037. // ArrowFunction/AsyncArrowFunction is part of AssignmentExpression, which should terminate the expression unless followed by a comma
  8038. if (m_token.tk != tkComma && m_token.tk != tkIN)
  8039. {
  8040. if (!(IsTerminateToken(false)))
  8041. {
  8042. Error(ERRnoSemic);
  8043. }
  8044. break;
  8045. }
  8046. }
  8047. else // a binary operator
  8048. {
  8049. if (nop == knopComma && m_token.tk == tkRParen)
  8050. {
  8051. // Trailing comma
  8052. this->GetScanner()->Capture(&m_deferCommaErrorLoc);
  8053. m_deferCommaError = true;
  8054. break;
  8055. }
  8056. ParseNode* pnode1 = pnode;
  8057. // Parse the operand, make a new node, and look for more
  8058. IdentToken token;
  8059. ParseNode* pnode2 = ParseExpr<buildAST>(
  8060. opl, nullptr, fAllowIn, FALSE, pNameHint, &hintLength, &hintOffset, &token, false, nullptr, plastRParen);
  8061. // Detect nested function escapes of the pattern "o.f = function(){...}" or "o[s] = function(){...}".
  8062. // Doing so in the parser allows us to disable stack-nested-functions in common cases where an escape
  8063. // is not detected at byte code gen time because of deferred parsing.
  8064. if (fIsDotOrIndex && nop == knopAsg)
  8065. {
  8066. this->MarkEscapingRef(pnodeT, &token);
  8067. }
  8068. if (buildAST)
  8069. {
  8070. Assert(pnode2 != nullptr);
  8071. if (pnode2->nop == knopFncDecl)
  8072. {
  8073. Assert(hintLength >= hintOffset);
  8074. pnode2->AsParseNodeFnc()->hint = pNameHint;
  8075. pnode2->AsParseNodeFnc()->hintLength = hintLength;
  8076. pnode2->AsParseNodeFnc()->hintOffset = hintOffset;
  8077. if (pnode1->nop == knopDot)
  8078. {
  8079. pnode2->AsParseNodeFnc()->isNameIdentifierRef = false;
  8080. }
  8081. else if (pnode1->nop == knopName)
  8082. {
  8083. PidRefStack *pidRef = pnode1->AsParseNodeName()->pid->GetTopRef();
  8084. pidRef->isFuncAssignment = true;
  8085. }
  8086. }
  8087. else if (pnode2->nop == knopClassDecl && pnode1->nop == knopDot)
  8088. {
  8089. Assert(pnode2->AsParseNodeClass()->pnodeConstructor);
  8090. if (!pnode2->AsParseNodeClass()->pnodeConstructor->pid)
  8091. {
  8092. pnode2->AsParseNodeClass()->pnodeConstructor->isNameIdentifierRef = false;
  8093. }
  8094. }
  8095. else if (pnode1->nop == knopName && nop == knopIn)
  8096. {
  8097. PidRefStack* pidRef = pnode1->AsParseNodeName()->pid->GetTopRef();
  8098. pidRef->SetIsUsedInLdElem(true);
  8099. }
  8100. pnode = CreateBinNode(nop, pnode1, pnode2);
  8101. }
  8102. pNameHint = nullptr;
  8103. }
  8104. }
  8105. if (buildAST)
  8106. {
  8107. if (!assignmentStmt)
  8108. {
  8109. // Don't set the flag for following nodes
  8110. switch (pnode->nop)
  8111. {
  8112. case knopName:
  8113. case knopInt:
  8114. case knopBigInt:
  8115. case knopFlt:
  8116. case knopStr:
  8117. case knopRegExp:
  8118. case knopNull:
  8119. case knopFalse:
  8120. case knopTrue:
  8121. break;
  8122. default:
  8123. if (m_currentNodeFunc)
  8124. {
  8125. m_currentNodeFunc->SetHasNonThisStmt();
  8126. }
  8127. else if (m_currentNodeProg)
  8128. {
  8129. m_currentNodeProg->SetHasNonThisStmt();
  8130. }
  8131. }
  8132. }
  8133. }
  8134. m_hasDeferredShorthandInitError = m_hasDeferredShorthandInitError || savedDeferredInitError;
  8135. if (NULL != pfCanAssign)
  8136. {
  8137. *pfCanAssign = fCanAssign;
  8138. }
  8139. // Pass back identifier if requested
  8140. if (pToken && term.tk == tkID)
  8141. {
  8142. *pToken = term;
  8143. }
  8144. //Track "obj.a" assignment patterns here - Promote the Assignment state for the property's PID.
  8145. // This includes =, += etc.
  8146. if (pnode != NULL)
  8147. {
  8148. uint nodeType = ParseNode::Grfnop(pnode->nop);
  8149. if (nodeType & fnopAsg)
  8150. {
  8151. if (nodeType & fnopBin)
  8152. {
  8153. ParseNodePtr lhs = pnode->AsParseNodeBin()->pnode1;
  8154. Assert(lhs);
  8155. if (lhs->nop == knopDot)
  8156. {
  8157. ParseNodePtr propertyNode = lhs->AsParseNodeBin()->pnode2;
  8158. if (propertyNode->nop == knopName)
  8159. {
  8160. propertyNode->AsParseNodeName()->pid->PromoteAssignmentState();
  8161. }
  8162. }
  8163. }
  8164. else if (nodeType & fnopUni)
  8165. {
  8166. // cases like obj.a++, ++obj.a
  8167. ParseNodePtr lhs = pnode->AsParseNodeUni()->pnode1;
  8168. if (lhs->nop == knopDot)
  8169. {
  8170. ParseNodePtr propertyNode = lhs->AsParseNodeBin()->pnode2;
  8171. if (propertyNode->nop == knopName)
  8172. {
  8173. propertyNode->AsParseNodeName()->pid->PromoteAssignmentState();
  8174. }
  8175. }
  8176. }
  8177. }
  8178. }
  8179. return pnode;
  8180. }
  8181. template<bool buildAST>
  8182. void Parser::TrackAssignment(ParseNodePtr pnodeT, IdentToken* pToken)
  8183. {
  8184. if (buildAST)
  8185. {
  8186. Assert(pnodeT != nullptr);
  8187. if (pnodeT->nop == knopName)
  8188. {
  8189. PidRefStack *ref = pnodeT->AsParseNodeName()->pid->GetTopRef();
  8190. Assert(ref);
  8191. ref->isAsg = true;
  8192. }
  8193. }
  8194. else
  8195. {
  8196. Assert(pToken != nullptr);
  8197. if (pToken->tk == tkID)
  8198. {
  8199. PidRefStack *ref = pToken->pid->GetTopRef();
  8200. Assert(ref);
  8201. ref->isAsg = true;
  8202. }
  8203. }
  8204. }
  8205. PidRefStack* Parser::PushPidRef(IdentPtr pid)
  8206. {
  8207. ParseNodeFnc* currentFnc = GetCurrentFunctionNode();
  8208. if (this->IsCreatingStateCache())
  8209. {
  8210. IdentPtrSet* capturedNames = currentFnc->EnsureCapturedNames(&m_nodeAllocator);
  8211. capturedNames->AddNew(pid);
  8212. }
  8213. if (PHASE_ON1(Js::ParallelParsePhase))
  8214. {
  8215. // NOTE: the phase check is here to protect perf. See OSG 1020424.
  8216. // In some LS AST-rewrite cases we lose a lot of perf searching the PID ref stack rather
  8217. // than just pushing on the top. This hasn't shown up as a perf issue in non-LS benchmarks.
  8218. return pid->FindOrAddPidRef(&m_nodeAllocator, GetCurrentBlock()->blockId, currentFnc->functionId);
  8219. }
  8220. Assert(GetCurrentBlock() != nullptr);
  8221. AssertMsg(pid != nullptr, "PID should be created");
  8222. PidRefStack *ref = pid->GetTopRef(m_nextBlockId - 1);
  8223. int blockId = GetCurrentBlock()->blockId;
  8224. int funcId = currentFnc->functionId;
  8225. if (!ref || (ref->GetScopeId() < blockId))
  8226. {
  8227. ref = Anew(&m_nodeAllocator, PidRefStack);
  8228. if (ref == nullptr)
  8229. {
  8230. Error(ERRnoMemory);
  8231. }
  8232. pid->PushPidRef(blockId, funcId, ref);
  8233. }
  8234. else if (m_reparsingLambdaParams)
  8235. {
  8236. // If we're reparsing params, then we may have pid refs left behind from the first pass. Make sure we're
  8237. // working with the right ref at this point.
  8238. ref = this->FindOrAddPidRef(pid, blockId, funcId);
  8239. // Fix up the function ID if we're reparsing lambda parameters.
  8240. ref->funcId = funcId;
  8241. }
  8242. return ref;
  8243. }
  8244. PidRefStack* Parser::FindOrAddPidRef(IdentPtr pid, int scopeId, Js::LocalFunctionId funcId)
  8245. {
  8246. PidRefStack *ref = pid->FindOrAddPidRef(&m_nodeAllocator, scopeId, funcId);
  8247. if (ref == NULL)
  8248. {
  8249. Error(ERRnoMemory);
  8250. }
  8251. return ref;
  8252. }
  8253. void Parser::RemovePrevPidRef(IdentPtr pid, PidRefStack *ref)
  8254. {
  8255. PidRefStack *prevRef = pid->RemovePrevPidRef(ref);
  8256. Assert(prevRef);
  8257. if (prevRef->GetSym() == nullptr)
  8258. {
  8259. AllocatorDelete(ArenaAllocator, &m_nodeAllocator, prevRef);
  8260. }
  8261. }
  8262. void Parser::SetPidRefsInScopeDynamic(IdentPtr pid, int blockId)
  8263. {
  8264. PidRefStack *ref = pid->GetTopRef();
  8265. while (ref && ref->GetScopeId() >= blockId)
  8266. {
  8267. ref->SetDynamicBinding();
  8268. ref = ref->prev;
  8269. }
  8270. }
  8271. ParseNodeBlock* Parser::GetFunctionBlock()
  8272. {
  8273. Assert(m_currentBlockInfo != nullptr);
  8274. return m_currentBlockInfo->pBlockInfoFunction->pnodeBlock;
  8275. }
  8276. ParseNodeBlock* Parser::GetCurrentBlock()
  8277. {
  8278. return m_currentBlockInfo != nullptr ? m_currentBlockInfo->pnodeBlock : nullptr;
  8279. }
  8280. BlockInfoStack* Parser::GetCurrentBlockInfo()
  8281. {
  8282. return m_currentBlockInfo;
  8283. }
  8284. BlockInfoStack* Parser::GetCurrentFunctionBlockInfo()
  8285. {
  8286. return m_currentBlockInfo->pBlockInfoFunction;
  8287. }
  8288. /***************************************************************************
  8289. Parse a variable declaration.
  8290. 'fAllowIn' indicates if the 'in' operator should be allowed in the initializing
  8291. expression ( it is not allowed in the context of the first expression in a 'for' loop).
  8292. ***************************************************************************/
  8293. template<bool buildAST>
  8294. ParseNodePtr Parser::ParseVariableDeclaration(
  8295. tokens declarationType, charcount_t ichMin,
  8296. BOOL fAllowIn/* = TRUE*/,
  8297. BOOL* pfForInOk/* = nullptr*/,
  8298. BOOL singleDefOnly/* = FALSE*/,
  8299. BOOL allowInit/* = TRUE*/,
  8300. BOOL isTopVarParse/* = TRUE*/,
  8301. BOOL isFor/* = FALSE*/,
  8302. BOOL* nativeForOk /*= nullptr*/)
  8303. {
  8304. ParseNodePtr pnodeThis = nullptr;
  8305. ParseNodePtr pnodeInit;
  8306. ParseNodePtr pnodeList = nullptr;
  8307. ParseNodePtr *lastNodeRef = nullptr;
  8308. LPCOLESTR pNameHint = nullptr;
  8309. uint32 nameHintLength = 0;
  8310. uint32 nameHintOffset = 0;
  8311. Assert(declarationType == tkVAR || declarationType == tkCONST || declarationType == tkLET);
  8312. for (;;)
  8313. {
  8314. if (IsES6DestructuringEnabled() && IsPossiblePatternStart())
  8315. {
  8316. pnodeThis = ParseDestructuredLiteral<buildAST>(declarationType, true, !!isTopVarParse, DIC_None, !!fAllowIn, pfForInOk, nativeForOk);
  8317. if (pnodeThis != nullptr)
  8318. {
  8319. pnodeThis->ichMin = ichMin;
  8320. pnodeThis->SetIsPatternDeclaration();
  8321. }
  8322. }
  8323. else
  8324. {
  8325. if (m_token.tk != tkID)
  8326. {
  8327. IdentifierExpectedError(m_token);
  8328. }
  8329. IdentPtr pid = m_token.GetIdentifier(this->GetHashTbl());
  8330. Assert(pid);
  8331. pNameHint = pid->Psz();
  8332. nameHintLength = pid->Cch();
  8333. nameHintOffset = 0;
  8334. if (pid == wellKnownPropertyPids.let && (declarationType == tkCONST || declarationType == tkLET))
  8335. {
  8336. Error(ERRLetIDInLexicalDecl, pnodeThis);
  8337. }
  8338. if (declarationType == tkVAR)
  8339. {
  8340. pnodeThis = CreateVarDeclNode(pid, STVariable);
  8341. }
  8342. else if (declarationType == tkCONST)
  8343. {
  8344. pnodeThis = CreateBlockScopedDeclNode(pid, knopConstDecl);
  8345. CHAKRATEL_LANGSTATS_INC_LANGFEATURECOUNT(ES6, Const, m_scriptContext);
  8346. }
  8347. else
  8348. {
  8349. pnodeThis = CreateBlockScopedDeclNode(pid, knopLetDecl);
  8350. CHAKRATEL_LANGSTATS_INC_LANGFEATURECOUNT(ES6, Let, m_scriptContext);
  8351. }
  8352. if (pid == wellKnownPropertyPids.arguments)
  8353. {
  8354. // This var declaration may change the way an 'arguments' identifier in the function is resolved
  8355. if (declarationType == tkVAR)
  8356. {
  8357. GetCurrentFunctionNode()->grfpn |= PNodeFlags::fpnArguments_varDeclaration;
  8358. }
  8359. else
  8360. {
  8361. if (GetCurrentBlockInfo()->pnodeBlock->blockType == Function)
  8362. {
  8363. // Only override arguments if we are at the function block level.
  8364. GetCurrentFunctionNode()->grfpn |= PNodeFlags::fpnArguments_overriddenByDecl;
  8365. }
  8366. }
  8367. }
  8368. if (pnodeThis)
  8369. {
  8370. pnodeThis->ichMin = ichMin;
  8371. }
  8372. this->GetScanner()->Scan();
  8373. if (m_token.tk == tkAsg)
  8374. {
  8375. if (!allowInit)
  8376. {
  8377. Error(ERRUnexpectedDefault);
  8378. }
  8379. if (pfForInOk && (declarationType == tkLET || declarationType == tkCONST || IsStrictMode()))
  8380. {
  8381. *pfForInOk = FALSE;
  8382. }
  8383. this->GetScanner()->Scan();
  8384. pnodeInit = ParseExpr<buildAST>(koplCma, nullptr, fAllowIn, FALSE, pNameHint, &nameHintLength, &nameHintOffset);
  8385. if (buildAST)
  8386. {
  8387. AnalysisAssert(pnodeThis);
  8388. pnodeThis->AsParseNodeVar()->pnodeInit = pnodeInit;
  8389. pnodeThis->ichLim = pnodeInit->ichLim;
  8390. if (pnodeInit->nop == knopFncDecl)
  8391. {
  8392. Assert(nameHintLength >= nameHintOffset);
  8393. pnodeInit->AsParseNodeFnc()->hint = pNameHint;
  8394. pnodeInit->AsParseNodeFnc()->hintLength = nameHintLength;
  8395. pnodeInit->AsParseNodeFnc()->hintOffset = nameHintOffset;
  8396. pnodeThis->AsParseNodeVar()->pid->GetTopRef()->isFuncAssignment = true;
  8397. }
  8398. else
  8399. {
  8400. this->CheckArguments(pnodeInit);
  8401. }
  8402. pNameHint = nullptr;
  8403. }
  8404. //Track var a =, let a= , const a =
  8405. // This is for FixedFields Constant Heuristics
  8406. if (pnodeThis && pnodeThis->AsParseNodeVar()->pnodeInit != nullptr)
  8407. {
  8408. pnodeThis->AsParseNodeVar()->sym->PromoteAssignmentState();
  8409. }
  8410. }
  8411. else if (declarationType == tkCONST /*pnodeThis->nop == knopConstDecl*/
  8412. && !singleDefOnly
  8413. && !(isFor && TokIsForInOrForOf()))
  8414. {
  8415. Error(ERRUninitializedConst);
  8416. }
  8417. if (m_currentNodeFunc && pnodeThis && pnodeThis->AsParseNodeVar()->sym->GetIsFormal())
  8418. {
  8419. m_currentNodeFunc->SetHasAnyWriteToFormals(true);
  8420. }
  8421. }
  8422. if (singleDefOnly)
  8423. {
  8424. return pnodeThis;
  8425. }
  8426. if (buildAST)
  8427. {
  8428. AddToNodeListEscapedUse(&pnodeList, &lastNodeRef, pnodeThis);
  8429. }
  8430. if (m_token.tk != tkComma)
  8431. {
  8432. return pnodeList;
  8433. }
  8434. if (pfForInOk)
  8435. {
  8436. // don't allow "for (var a, b in c)"
  8437. *pfForInOk = FALSE;
  8438. }
  8439. this->GetScanner()->Scan();
  8440. ichMin = this->GetScanner()->IchMinTok();
  8441. }
  8442. }
  8443. /***************************************************************************
  8444. Parse try-catch-finally statement
  8445. ***************************************************************************/
  8446. // The try-catch-finally tree nests the try-catch within a try-finally.
  8447. // This matches the new runtime implementation.
  8448. template<bool buildAST>
  8449. ParseNodeStmt * Parser::ParseTryCatchFinally()
  8450. {
  8451. this->m_tryCatchOrFinallyDepth++;
  8452. ParseNodeTry * pnodeT = ParseTry<buildAST>();
  8453. ParseNodeTryCatch * pnodeTC = nullptr;
  8454. StmtNest stmt;
  8455. bool hasCatch = false;
  8456. if (tkCATCH == m_token.tk)
  8457. {
  8458. hasCatch = true;
  8459. if (buildAST)
  8460. {
  8461. pnodeTC = CreateNodeForOpT<knopTryCatch>();
  8462. pnodeT->pnodeOuter = pnodeTC;
  8463. pnodeTC->pnodeTry = pnodeT;
  8464. }
  8465. PushStmt<buildAST>(&stmt, pnodeTC, knopTryCatch, nullptr);
  8466. ParseNodeCatch * pnodeCatch = ParseCatch<buildAST>();
  8467. if (buildAST)
  8468. {
  8469. pnodeTC->pnodeCatch = pnodeCatch;
  8470. }
  8471. PopStmt(&stmt);
  8472. }
  8473. if (tkFINALLY != m_token.tk)
  8474. {
  8475. if (!hasCatch)
  8476. {
  8477. Error(ERRnoCatch);
  8478. }
  8479. Assert(!buildAST || pnodeTC);
  8480. this->m_tryCatchOrFinallyDepth--;
  8481. return pnodeTC;
  8482. }
  8483. ParseNodeTryFinally * pnodeTF = nullptr;
  8484. if (buildAST)
  8485. {
  8486. pnodeTF = CreateNodeForOpT<knopTryFinally>();
  8487. }
  8488. PushStmt<buildAST>(&stmt, pnodeTF, knopTryFinally, nullptr);
  8489. ParseNodeFinally * pnodeFinally = ParseFinally<buildAST>();
  8490. if (buildAST)
  8491. {
  8492. if (!hasCatch)
  8493. {
  8494. pnodeTF->pnodeTry = pnodeT;
  8495. pnodeT->pnodeOuter = pnodeTF;
  8496. }
  8497. else
  8498. {
  8499. pnodeTF->pnodeTry = CreateNodeForOpT<knopTry>();
  8500. pnodeTF->pnodeTry->pnodeOuter = pnodeTF;
  8501. pnodeTF->pnodeTry->pnodeBody = pnodeTC;
  8502. pnodeTC->pnodeOuter = pnodeTF->pnodeTry;
  8503. }
  8504. pnodeTF->pnodeFinally = pnodeFinally;
  8505. }
  8506. PopStmt(&stmt);
  8507. this->m_tryCatchOrFinallyDepth--;
  8508. return pnodeTF;
  8509. }
  8510. template<bool buildAST>
  8511. ParseNodeTry * Parser::ParseTry()
  8512. {
  8513. ParseNodeTry * pnode = nullptr;
  8514. StmtNest stmt;
  8515. Assert(tkTRY == m_token.tk);
  8516. if (buildAST)
  8517. {
  8518. pnode = CreateNodeForOpT<knopTry>();
  8519. }
  8520. this->GetScanner()->Scan();
  8521. if (tkLCurly != m_token.tk)
  8522. {
  8523. Error(ERRnoLcurly);
  8524. }
  8525. PushStmt<buildAST>(&stmt, pnode, knopTry, nullptr);
  8526. ParseNodePtr pnodeBody = ParseStatement<buildAST>();
  8527. if (buildAST)
  8528. {
  8529. pnode->pnodeBody = pnodeBody;
  8530. if (pnode->pnodeBody)
  8531. pnode->ichLim = pnode->pnodeBody->ichLim;
  8532. }
  8533. PopStmt(&stmt);
  8534. return pnode;
  8535. }
  8536. template<bool buildAST>
  8537. ParseNodeFinally * Parser::ParseFinally()
  8538. {
  8539. ParseNodeFinally * pnode = nullptr;
  8540. StmtNest stmt;
  8541. Assert(tkFINALLY == m_token.tk);
  8542. if (buildAST)
  8543. {
  8544. pnode = CreateNodeForOpT<knopFinally>();
  8545. }
  8546. this->GetScanner()->Scan();
  8547. if (tkLCurly != m_token.tk)
  8548. {
  8549. Error(ERRnoLcurly);
  8550. }
  8551. PushStmt<buildAST>(&stmt, pnode, knopFinally, nullptr);
  8552. ParseNodePtr pnodeBody = ParseStatement<buildAST>();
  8553. if (buildAST)
  8554. {
  8555. pnode->pnodeBody = pnodeBody;
  8556. if (!pnode->pnodeBody)
  8557. // Will only occur due to error correction.
  8558. pnode->pnodeBody = CreateNodeForOpT<knopEmpty>();
  8559. else
  8560. pnode->ichLim = pnode->pnodeBody->ichLim;
  8561. }
  8562. PopStmt(&stmt);
  8563. return pnode;
  8564. }
  8565. template<bool buildAST>
  8566. ParseNodeCatch * Parser::ParseCatch()
  8567. {
  8568. ParseNodePtr *ppnodeExprScopeSave = nullptr;
  8569. ParseNodeCatch * pnode = nullptr;
  8570. ParseNodeBlock * pnodeCatchScope = nullptr;
  8571. StmtNest stmt;
  8572. IdentPtr pidCatch = nullptr;
  8573. if (tkCATCH == m_token.tk)
  8574. {
  8575. charcount_t ichMin;
  8576. if (buildAST)
  8577. {
  8578. ichMin = this->GetScanner()->IchMinTok();
  8579. }
  8580. this->GetScanner()->Scan(); //catch
  8581. bool isPattern = false;
  8582. bool hasParam = false;
  8583. if (tkLParen == m_token.tk)
  8584. {
  8585. hasParam = true;
  8586. this->GetScanner()->Scan(); //catch(
  8587. if (tkID != m_token.tk)
  8588. {
  8589. isPattern = IsES6DestructuringEnabled() && IsPossiblePatternStart();
  8590. if (!isPattern)
  8591. {
  8592. IdentifierExpectedError(m_token);
  8593. }
  8594. }
  8595. }
  8596. if (buildAST)
  8597. {
  8598. pnode = CreateNodeForOpT<knopCatch>(ichMin);
  8599. pnode->pnodeNext = nullptr;
  8600. PushStmt<buildAST>(&stmt, pnode, knopCatch, nullptr);
  8601. }
  8602. pnodeCatchScope = StartParseBlock<buildAST>(PnodeBlockType::Regular, isPattern ? ScopeType_CatchParamPattern : ScopeType_Catch);
  8603. if (buildAST)
  8604. {
  8605. // Add this catch to the current scope list.
  8606. if (m_ppnodeExprScope)
  8607. {
  8608. Assert(*m_ppnodeExprScope == nullptr);
  8609. *m_ppnodeExprScope = pnode;
  8610. m_ppnodeExprScope = &pnode->pnodeNext;
  8611. }
  8612. else
  8613. {
  8614. Assert(m_ppnodeScope);
  8615. Assert(*m_ppnodeScope == nullptr);
  8616. *m_ppnodeScope = pnode;
  8617. m_ppnodeScope = &pnode->pnodeNext;
  8618. }
  8619. // Keep a list of function expressions (not declarations) at this scope.
  8620. ppnodeExprScopeSave = m_ppnodeExprScope;
  8621. m_ppnodeExprScope = &pnode->pnodeScopes;
  8622. pnode->pnodeScopes = nullptr;
  8623. }
  8624. if (isPattern)
  8625. {
  8626. ParseNodePtr pnodePattern = ParseDestructuredLiteral<buildAST>(tkLET, true /*isDecl*/, true /*topLevel*/, DIC_ForceErrorOnInitializer);
  8627. if (buildAST)
  8628. {
  8629. pnode->SetParam(CreateParamPatternNode(pnodePattern));
  8630. Scope *scope = pnodeCatchScope->scope;
  8631. pnode->scope = scope;
  8632. }
  8633. }
  8634. else if (hasParam)
  8635. {
  8636. if (IsStrictMode())
  8637. {
  8638. IdentPtr pid = m_token.GetIdentifier(this->GetHashTbl());
  8639. if (pid == wellKnownPropertyPids.eval)
  8640. {
  8641. Error(ERREvalUsage);
  8642. }
  8643. else if (pid == wellKnownPropertyPids.arguments)
  8644. {
  8645. Error(ERRArgsUsage);
  8646. }
  8647. }
  8648. pidCatch = m_token.GetIdentifier(this->GetHashTbl());
  8649. PidRefStack *ref = this->FindOrAddPidRef(pidCatch, GetCurrentBlock()->blockId, GetCurrentFunctionNode()->functionId);
  8650. ParseNodeName * pnodeParam = CreateNameNode(pidCatch);
  8651. pnodeParam->SetSymRef(ref);
  8652. const char16 *name = reinterpret_cast<const char16*>(pidCatch->Psz());
  8653. int nameLength = pidCatch->Cch();
  8654. SymbolName const symName(name, nameLength);
  8655. Symbol *sym = Anew(&m_nodeAllocator, Symbol, symName, pnodeParam, STVariable);
  8656. if (sym == nullptr)
  8657. {
  8658. Error(ERRnoMemory);
  8659. }
  8660. sym->SetPid(pidCatch);
  8661. Assert(ref->GetSym() == nullptr);
  8662. ref->SetSym(sym);
  8663. Scope *scope = pnodeCatchScope->scope;
  8664. scope->AddNewSymbol(sym);
  8665. if (buildAST)
  8666. {
  8667. pnode->SetParam(pnodeParam);
  8668. pnode->scope = scope;
  8669. }
  8670. this->GetScanner()->Scan();
  8671. }
  8672. else
  8673. {
  8674. if (buildAST)
  8675. {
  8676. pnode->scope = pnodeCatchScope->scope;
  8677. }
  8678. }
  8679. charcount_t ichLim;
  8680. if (buildAST)
  8681. {
  8682. ichLim = this->GetScanner()->IchLimTok();
  8683. }
  8684. if (hasParam)
  8685. {
  8686. ChkCurTok(tkRParen, ERRnoRparen); //catch(id[:expr])
  8687. }
  8688. if (tkLCurly != m_token.tk)
  8689. {
  8690. Error(ERRnoLcurly);
  8691. }
  8692. ParseNodePtr pnodeBody = ParseStatement<buildAST>(); //catch(id[:expr]) {block}
  8693. if (buildAST)
  8694. {
  8695. pnode->pnodeBody = pnodeBody;
  8696. pnode->ichLim = ichLim;
  8697. }
  8698. if (pnodeCatchScope != nullptr)
  8699. {
  8700. FinishParseBlock(pnodeCatchScope);
  8701. }
  8702. if (pnodeCatchScope->GetCallsEval() || pnodeCatchScope->GetChildCallsEval())
  8703. {
  8704. GetCurrentBlock()->SetChildCallsEval(true);
  8705. }
  8706. if (pnodeCatchScope->GetCallsEval())
  8707. {
  8708. pnodeBody->AsParseNodeBlock()->SetCallsEval(true);
  8709. }
  8710. if (pnodeCatchScope->GetChildCallsEval())
  8711. {
  8712. pnodeBody->AsParseNodeBlock()->SetChildCallsEval(true);
  8713. }
  8714. if (buildAST)
  8715. {
  8716. PopStmt(&stmt);
  8717. // Restore the lists of function expression scopes.
  8718. Assert(m_ppnodeExprScope);
  8719. Assert(*m_ppnodeExprScope == nullptr);
  8720. m_ppnodeExprScope = ppnodeExprScopeSave;
  8721. }
  8722. }
  8723. return pnode;
  8724. }
  8725. template<bool buildAST>
  8726. ParseNodeCase * Parser::ParseCase(ParseNodePtr *ppnodeBody)
  8727. {
  8728. ParseNodeCase * pnodeT = nullptr;
  8729. charcount_t ichMinT = this->GetScanner()->IchMinTok();
  8730. this->GetScanner()->Scan();
  8731. ParseNodePtr pnodeExpr = ParseExpr<buildAST>();
  8732. charcount_t ichLim = this->GetScanner()->IchLimTok();
  8733. ChkCurTok(tkColon, ERRnoColon);
  8734. if (buildAST)
  8735. {
  8736. pnodeT = CreateNodeForOpT<knopCase>(ichMinT);
  8737. pnodeT->pnodeExpr = pnodeExpr;
  8738. pnodeT->ichLim = ichLim;
  8739. }
  8740. ParseStmtList<buildAST>(ppnodeBody);
  8741. return pnodeT;
  8742. }
  8743. /***************************************************************************
  8744. Parse a single statement. Digest a trailing semicolon.
  8745. ***************************************************************************/
  8746. template<bool buildAST>
  8747. ParseNodePtr Parser::ParseStatement()
  8748. {
  8749. ParseNodePtr pnode = nullptr;
  8750. LabelId* pLabelIdList = nullptr;
  8751. charcount_t ichMin = 0;
  8752. size_t iecpMin = 0;
  8753. StmtNest stmt;
  8754. StmtNest *pstmt;
  8755. BOOL fForInOrOfOkay;
  8756. BOOL fCanAssign;
  8757. IdentPtr pid;
  8758. uint fnop;
  8759. bool expressionStmt = false;
  8760. bool isAsyncMethod = false;
  8761. bool labelledStatement = false;
  8762. tokens tok;
  8763. #if EXCEPTION_RECOVERY
  8764. ParseNodeTryCatch * pParentTryCatch = nullptr;
  8765. ParseNodeBlock * pTryBlock = nullptr;
  8766. ParseNodeTry * pTry = nullptr;
  8767. ParseNodeBlock * pParentTryCatchBlock = nullptr;
  8768. StmtNest stmtTryCatchBlock;
  8769. StmtNest stmtTryCatch;
  8770. StmtNest stmtTry;
  8771. StmtNest stmtTryBlock;
  8772. #endif
  8773. if (buildAST)
  8774. {
  8775. #if EXCEPTION_RECOVERY
  8776. if (Js::Configuration::Global.flags.SwallowExceptions)
  8777. {
  8778. // If we're swallowing exceptions, surround this statement with a try/catch block:
  8779. //
  8780. // Before: x.y = 3;
  8781. // After: try { x.y = 3; } catch(__ehobj) { }
  8782. //
  8783. // This is done to force the runtime to recover from exceptions at the most granular
  8784. // possible point. Recovering from EH dramatically improves coverage of testing via
  8785. // fault injection.
  8786. // create and push the try-catch node
  8787. pParentTryCatchBlock = CreateBlockNode();
  8788. PushStmt<buildAST>(&stmtTryCatchBlock, pParentTryCatchBlock, knopBlock, nullptr);
  8789. pParentTryCatch = CreateNodeForOpT<knopTryCatch>();
  8790. PushStmt<buildAST>(&stmtTryCatch, pParentTryCatch, knopTryCatch, nullptr);
  8791. // create and push a try node
  8792. pTry = CreateNodeForOpT<knopTry>();
  8793. PushStmt<buildAST>(&stmtTry, pTry, knopTry, nullptr);
  8794. pTryBlock = CreateBlockNode();
  8795. PushStmt<buildAST>(&stmtTryBlock, pTryBlock, knopBlock, nullptr);
  8796. // these nodes will be closed after the statement is parsed.
  8797. }
  8798. #endif // EXCEPTION_RECOVERY
  8799. }
  8800. EnsureStackAvailable();
  8801. LRestart:
  8802. tok = m_token.tk;
  8803. switch (tok)
  8804. {
  8805. case tkEOF:
  8806. if (labelledStatement)
  8807. {
  8808. Error(ERRLabelFollowedByEOF);
  8809. }
  8810. if (buildAST)
  8811. {
  8812. pnode = nullptr;
  8813. }
  8814. break;
  8815. case tkFUNCTION:
  8816. {
  8817. LFunctionStatement:
  8818. if (m_grfscr & fscrDeferredFncExpression)
  8819. {
  8820. // The top-level deferred function body was defined by a function expression whose parsing was deferred. We are now
  8821. // parsing it, so unset the flag so that any nested functions are parsed normally. This flag is only applicable the
  8822. // first time we see it.
  8823. m_grfscr &= ~fscrDeferredFncExpression;
  8824. pnode = ParseFncDeclNoCheckScope<buildAST>(isAsyncMethod ? fFncAsync : fFncNoFlgs);
  8825. }
  8826. else
  8827. {
  8828. pnode = ParseFncDeclCheckScope<buildAST>(fFncDeclaration | (isAsyncMethod ? fFncAsync : fFncNoFlgs));
  8829. }
  8830. Assert(pnode != nullptr);
  8831. if (labelledStatement)
  8832. {
  8833. if (IsStrictMode())
  8834. {
  8835. Error(ERRFunctionAfterLabelInStrict);
  8836. }
  8837. // #sec-with-statement-static-semantics-early-errors states that the Statement of
  8838. // a WithStatement throws a Syntax Error if the Statement is a LabelledFunction.
  8839. else if (m_pstmtCur && m_pstmtCur->pnodeStmt && m_pstmtCur->GetNop() == knopWith)
  8840. {
  8841. Error(ERRStmtOfWithIsLabelledFunc);
  8842. }
  8843. ParseNodeFnc* pNodeFnc = nullptr;
  8844. // pnode can be a knopBlock due to ParseFncDeclCheckScope, which
  8845. // can return a ParseNodeBlock that contains a ParseNodeFnc.
  8846. if (pnode->nop == knopBlock)
  8847. {
  8848. ParseNodeBlock* pNodeBlock = pnode->AsParseNodeBlock();
  8849. if (pNodeBlock->pnodeStmt && pNodeBlock->pnodeStmt->nop == knopFncDecl)
  8850. {
  8851. pNodeFnc = pNodeBlock->pnodeStmt->AsParseNodeFnc();
  8852. }
  8853. }
  8854. if (pNodeFnc == nullptr)
  8855. {
  8856. pNodeFnc = pnode->AsParseNodeFnc();
  8857. }
  8858. if (pNodeFnc->IsAsync())
  8859. {
  8860. Error(ERRLabelBeforeAsyncFncDeclaration);
  8861. }
  8862. else if (pNodeFnc->IsGenerator())
  8863. {
  8864. Error(ERRLabelBeforeGeneratorDeclaration);
  8865. }
  8866. }
  8867. if (isAsyncMethod)
  8868. {
  8869. pnode->AsParseNodeFnc()->cbStringMin = iecpMin;
  8870. pnode->AsParseNodeFnc()->cbStringLim = pnode->AsParseNodeFnc()->cbLim;
  8871. }
  8872. break;
  8873. }
  8874. case tkCLASS:
  8875. if (labelledStatement)
  8876. {
  8877. Error(ERRLabelBeforeClassDeclaration);
  8878. }
  8879. else if (m_scriptContext->GetConfig()->IsES6ClassAndExtendsEnabled())
  8880. {
  8881. pnode = ParseClassDecl<buildAST>(TRUE, nullptr, nullptr, nullptr);
  8882. }
  8883. else
  8884. {
  8885. goto LDefaultToken;
  8886. }
  8887. break;
  8888. case tkID:
  8889. case tkLET:
  8890. if (tok == tkLET || CheckContextualKeyword(wellKnownPropertyPids.let))
  8891. {
  8892. // We see "let" at the start of a statement. This could either be a declaration or an identifier
  8893. // reference. The next token determines which.
  8894. RestorePoint parsedLet;
  8895. this->GetScanner()->Capture(&parsedLet);
  8896. ichMin = this->GetScanner()->IchMinTok();
  8897. this->GetScanner()->Scan();
  8898. if (labelledStatement)
  8899. {
  8900. if (!this->GetScanner()->FHadNewLine() || m_token.tk == tkLBrack)
  8901. {
  8902. // In the case where a label is followed by a let, we want to fail when parsing if there is no new line after let,
  8903. // otherwise fail at runtime as let will be viewed as undefined. A left bracket after a let signifies a syntax error regardless.
  8904. Error(ERRLabelBeforeLexicalDeclaration);
  8905. }
  8906. }
  8907. else if (this->NextTokenConfirmsLetDecl())
  8908. {
  8909. pnode = ParseVariableDeclaration<buildAST>(tkLET, ichMin);
  8910. goto LNeedTerminator;
  8911. }
  8912. this->GetScanner()->SeekTo(parsedLet);
  8913. }
  8914. else if (CheckContextualKeyword(wellKnownPropertyPids.async) && m_scriptContext->GetConfig()->IsES7AsyncAndAwaitEnabled())
  8915. {
  8916. RestorePoint parsedAsync;
  8917. this->GetScanner()->Capture(&parsedAsync);
  8918. ichMin = this->GetScanner()->IchMinTok();
  8919. iecpMin = this->GetScanner()->IecpMinTok();
  8920. this->GetScanner()->Scan();
  8921. if (m_token.tk == tkFUNCTION && !this->GetScanner()->FHadNewLine())
  8922. {
  8923. isAsyncMethod = true;
  8924. goto LFunctionStatement;
  8925. }
  8926. this->GetScanner()->SeekTo(parsedAsync);
  8927. }
  8928. goto LDefaultToken;
  8929. case tkCONST:
  8930. if (labelledStatement)
  8931. {
  8932. Error(ERRLabelBeforeLexicalDeclaration);
  8933. }
  8934. ichMin = this->GetScanner()->IchMinTok();
  8935. this->GetScanner()->Scan();
  8936. pnode = ParseVariableDeclaration<buildAST>(tok, ichMin);
  8937. goto LNeedTerminator;
  8938. case tkVAR:
  8939. ichMin = this->GetScanner()->IchMinTok();
  8940. this->GetScanner()->Scan();
  8941. pnode = ParseVariableDeclaration<buildAST>(tok, ichMin);
  8942. goto LNeedTerminator;
  8943. case tkFOR:
  8944. {
  8945. ParseNodeBlock * pnodeBlock = nullptr;
  8946. ParseNodePtr *ppnodeScopeSave = nullptr;
  8947. ParseNodePtr *ppnodeExprScopeSave = nullptr;
  8948. bool isForAwait = false;
  8949. ichMin = this->GetScanner()->IchMinTok();
  8950. this->GetScanner()->Scan();
  8951. if (m_token.tk == tkAWAIT || CheckContextualKeyword(wellKnownPropertyPids.await))
  8952. {
  8953. if (!this->GetScanner()->AwaitIsKeywordRegion())
  8954. {
  8955. Error(ERRBadAwait); // for await () in a non-async function
  8956. }
  8957. if (!m_scriptContext->GetConfig()->IsES2018AsyncIterationEnabled())
  8958. {
  8959. Error(ERRExperimental);
  8960. }
  8961. isForAwait = true;
  8962. this->GetScanner()->Scan();
  8963. }
  8964. ChkCurTok(tkLParen, ERRnoLparen);
  8965. pnodeBlock = StartParseBlock<buildAST>(PnodeBlockType::Regular, ScopeType_Block);
  8966. if (buildAST)
  8967. {
  8968. PushFuncBlockScope(pnodeBlock, &ppnodeScopeSave, &ppnodeExprScopeSave);
  8969. }
  8970. RestorePoint startExprOrIdentifier;
  8971. fForInOrOfOkay = TRUE;
  8972. fCanAssign = TRUE;
  8973. tok = m_token.tk;
  8974. BOOL nativeForOkay = TRUE;
  8975. ParseNodePtr pnodeT;
  8976. switch (tok)
  8977. {
  8978. case tkID:
  8979. if (CheckContextualKeyword(wellKnownPropertyPids.let))
  8980. {
  8981. // We see "let" in the init part of a for loop. This could either be a declaration or an identifier
  8982. // reference. The next token determines which.
  8983. RestorePoint parsedLet;
  8984. this->GetScanner()->Capture(&parsedLet);
  8985. auto ichMinInner = this->GetScanner()->IchMinTok();
  8986. this->GetScanner()->Scan();
  8987. if (IsPossiblePatternStart())
  8988. {
  8989. this->GetScanner()->Capture(&startExprOrIdentifier);
  8990. }
  8991. if (this->NextTokenConfirmsLetDecl() && m_token.tk != tkIN)
  8992. {
  8993. pnodeT = ParseVariableDeclaration<buildAST>(tkLET, ichMinInner
  8994. , /*fAllowIn = */FALSE
  8995. , /*pfForInOk = */&fForInOrOfOkay
  8996. , /*singleDefOnly*/FALSE
  8997. , /*allowInit*/TRUE
  8998. , /*isTopVarParse*/TRUE
  8999. , /*isFor*/TRUE
  9000. , &nativeForOkay);
  9001. break;
  9002. }
  9003. this->GetScanner()->SeekTo(parsedLet);
  9004. }
  9005. goto LDefaultTokenFor;
  9006. case tkLET:
  9007. case tkCONST:
  9008. case tkVAR:
  9009. {
  9010. auto ichMinInner = this->GetScanner()->IchMinTok();
  9011. this->GetScanner()->Scan();
  9012. if (IsPossiblePatternStart())
  9013. {
  9014. this->GetScanner()->Capture(&startExprOrIdentifier);
  9015. }
  9016. pnodeT = ParseVariableDeclaration<buildAST>(tok, ichMinInner
  9017. , /*fAllowIn = */FALSE
  9018. , /*pfForInOk = */&fForInOrOfOkay
  9019. , /*singleDefOnly*/FALSE
  9020. , /*allowInit*/TRUE
  9021. , /*isTopVarParse*/TRUE
  9022. , /*isFor*/TRUE
  9023. , &nativeForOkay);
  9024. }
  9025. break;
  9026. case tkSColon:
  9027. pnodeT = nullptr;
  9028. fForInOrOfOkay = FALSE;
  9029. break;
  9030. default:
  9031. {
  9032. LDefaultTokenFor:
  9033. RestorePoint exprStart;
  9034. tokens beforeToken = tok;
  9035. this->GetScanner()->Capture(&exprStart);
  9036. if (IsPossiblePatternStart())
  9037. {
  9038. this->GetScanner()->Capture(&startExprOrIdentifier);
  9039. }
  9040. bool fLikelyPattern = false;
  9041. if (IsES6DestructuringEnabled() && (beforeToken == tkLBrack || beforeToken == tkLCurly))
  9042. {
  9043. pnodeT = ParseExpr<buildAST>(koplNo,
  9044. &fCanAssign,
  9045. /*fAllowIn = */FALSE,
  9046. /*fAllowEllipsis*/FALSE,
  9047. /*pHint*/nullptr,
  9048. /*pHintLength*/nullptr,
  9049. /*pShortNameOffset*/nullptr,
  9050. /*pToken*/nullptr,
  9051. /**fUnaryOrParen*/false,
  9052. &fLikelyPattern);
  9053. }
  9054. else
  9055. {
  9056. IdentToken token;
  9057. pnodeT = ParseExpr<buildAST>(koplNo, &fCanAssign, /*fAllowIn = */FALSE, FALSE, NULL, nullptr, nullptr, &token);
  9058. TrackAssignment<buildAST>(pnodeT, &token);
  9059. }
  9060. // 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
  9061. // has already converted them appropriately.
  9062. if (fLikelyPattern && TokIsForInOrForOf())
  9063. {
  9064. this->GetScanner()->SeekTo(exprStart);
  9065. ParseDestructuredLiteralWithScopeSave(tkNone, false/*isDecl*/, false /*topLevel*/, DIC_None, false /*allowIn*/);
  9066. fCanAssign = TRUE;
  9067. if (buildAST)
  9068. {
  9069. pnodeT = ConvertToPattern(pnodeT);
  9070. }
  9071. }
  9072. if (buildAST)
  9073. {
  9074. Assert(pnodeT);
  9075. pnodeT->isUsed = false;
  9076. }
  9077. }
  9078. break;
  9079. }
  9080. if (TokIsForInOrForOf())
  9081. {
  9082. bool isForOf = (m_token.tk != tkIN);
  9083. Assert(!isForOf || CheckContextualKeyword(wellKnownPropertyPids.of));
  9084. if (isForAwait && !isForOf)
  9085. {
  9086. Error(ERRTokenAfter, _u("in"), _u("for await"));
  9087. }
  9088. if ((buildAST && nullptr == pnodeT) || !fForInOrOfOkay)
  9089. {
  9090. if (isForOf)
  9091. {
  9092. Error(ERRForOfNoInitAllowed);
  9093. }
  9094. else
  9095. {
  9096. Error(ERRForInNoInitAllowed);
  9097. }
  9098. }
  9099. if (!fCanAssign &&
  9100. (m_sourceContextInfo
  9101. ? !PHASE_OFF_RAW(Js::EarlyReferenceErrorsPhase, m_sourceContextInfo->sourceContextId, GetCurrentFunctionNode()->functionId)
  9102. : !PHASE_OFF1(Js::EarlyReferenceErrorsPhase)))
  9103. {
  9104. Error(ERRInvalidLHSInFor);
  9105. }
  9106. this->GetScanner()->Scan();
  9107. ParseNodePtr pnodeObj = ParseExpr<buildAST>(isForOf ? koplCma : koplNo);
  9108. charcount_t ichLim = this->GetScanner()->IchLimTok();
  9109. ChkCurTok(tkRParen, ERRnoRparen);
  9110. ParseNodeForInOrForOf * pnodeForInOrForOf = nullptr;
  9111. if (buildAST)
  9112. {
  9113. if (isForAwait)
  9114. {
  9115. pnodeForInOrForOf = CreateNodeForOpT<knopForAwaitOf>(ichMin);
  9116. }
  9117. else if (isForOf)
  9118. {
  9119. pnodeForInOrForOf = CreateNodeForOpT<knopForOf>(ichMin);
  9120. }
  9121. else
  9122. {
  9123. pnodeForInOrForOf = CreateNodeForOpT<knopForIn>(ichMin);
  9124. }
  9125. pnodeForInOrForOf->pnodeBlock = pnodeBlock;
  9126. pnodeForInOrForOf->pnodeLval = pnodeT;
  9127. pnodeForInOrForOf->pnodeObj = pnodeObj;
  9128. pnodeForInOrForOf->ichLim = ichLim;
  9129. TrackAssignment<true>(pnodeT, nullptr);
  9130. }
  9131. PushStmt<buildAST>(&stmt, pnodeForInOrForOf, isForAwait ? knopForAwaitOf : (isForOf ? knopForOf : knopForIn), pLabelIdList);
  9132. ParseNodePtr pnodeBody = ParseStatement<buildAST>();
  9133. if (buildAST)
  9134. {
  9135. pnodeForInOrForOf->pnodeBody = pnodeBody;
  9136. pnode = pnodeForInOrForOf;
  9137. }
  9138. PopStmt(&stmt);
  9139. }
  9140. else
  9141. {
  9142. if (!nativeForOkay)
  9143. {
  9144. Error(ERRDestructInit);
  9145. }
  9146. if (isForAwait)
  9147. {
  9148. Error(ERRValidIfFollowedBy, _u("'for await'"), _u("'of'"));
  9149. }
  9150. ChkCurTok(tkSColon, ERRnoSemic);
  9151. ParseNodePtr pnodeCond = nullptr;
  9152. if (m_token.tk != tkSColon)
  9153. {
  9154. pnodeCond = ParseExpr<buildAST>();
  9155. if (m_token.tk != tkSColon)
  9156. {
  9157. Error(ERRnoSemic);
  9158. }
  9159. }
  9160. tokens tk;
  9161. tk = this->GetScanner()->Scan();
  9162. ParseNodePtr pnodeIncr = nullptr;
  9163. if (tk != tkRParen)
  9164. {
  9165. pnodeIncr = ParseExpr<buildAST>();
  9166. if (pnodeIncr)
  9167. {
  9168. pnodeIncr->isUsed = false;
  9169. }
  9170. }
  9171. charcount_t ichLim = this->GetScanner()->IchLimTok();
  9172. ChkCurTok(tkRParen, ERRnoRparen);
  9173. ParseNodeFor * pnodeFor = nullptr;
  9174. if (buildAST)
  9175. {
  9176. pnodeFor = CreateNodeForOpT<knopFor>(ichMin);
  9177. pnodeFor->pnodeBlock = pnodeBlock;
  9178. pnodeFor->pnodeInverted = nullptr;
  9179. pnodeFor->pnodeInit = pnodeT;
  9180. pnodeFor->pnodeCond = pnodeCond;
  9181. pnodeFor->pnodeIncr = pnodeIncr;
  9182. pnodeFor->ichLim = ichLim;
  9183. }
  9184. PushStmt<buildAST>(&stmt, pnodeFor, knopFor, pLabelIdList);
  9185. ParseNodePtr pnodeBody = ParseStatement<buildAST>();
  9186. if (buildAST)
  9187. {
  9188. pnodeFor->pnodeBody = pnodeBody;
  9189. pnode = pnodeFor;
  9190. }
  9191. PopStmt(&stmt);
  9192. }
  9193. if (buildAST)
  9194. {
  9195. PopFuncBlockScope(ppnodeScopeSave, ppnodeExprScopeSave);
  9196. }
  9197. FinishParseBlock(pnodeBlock);
  9198. break;
  9199. }
  9200. case tkSWITCH:
  9201. {
  9202. BOOL fSeenDefault = FALSE;
  9203. ParseNodeBlock * pnodeBlock = nullptr;
  9204. ParseNodePtr *ppnodeScopeSave = nullptr;
  9205. ParseNodePtr *ppnodeExprScopeSave = nullptr;
  9206. ichMin = this->GetScanner()->IchMinTok();
  9207. ChkNxtTok(tkLParen, ERRnoLparen);
  9208. ParseNodePtr pnodeVal = ParseExpr<buildAST>();
  9209. charcount_t ichLim = this->GetScanner()->IchLimTok();
  9210. ChkCurTok(tkRParen, ERRnoRparen);
  9211. ChkCurTok(tkLCurly, ERRnoLcurly);
  9212. ParseNodeSwitch * pnodeSwitch = nullptr;
  9213. if (buildAST)
  9214. {
  9215. pnodeSwitch = CreateNodeForOpT<knopSwitch>(ichMin);
  9216. }
  9217. PushStmt<buildAST>(&stmt, pnodeSwitch, knopSwitch, pLabelIdList);
  9218. pnodeBlock = StartParseBlock<buildAST>(PnodeBlockType::Regular, ScopeType_Block);
  9219. ParseNodeCase ** ppnodeCase = nullptr;
  9220. if (buildAST)
  9221. {
  9222. pnodeSwitch->pnodeVal = pnodeVal;
  9223. pnodeSwitch->pnodeBlock = pnodeBlock;
  9224. pnodeSwitch->ichLim = ichLim;
  9225. PushFuncBlockScope(pnodeSwitch->pnodeBlock, &ppnodeScopeSave, &ppnodeExprScopeSave);
  9226. pnodeSwitch->pnodeDefault = nullptr;
  9227. ppnodeCase = &pnodeSwitch->pnodeCases;
  9228. pnode = pnodeSwitch;
  9229. }
  9230. for (;;)
  9231. {
  9232. ParseNodeCase * pnodeCase;
  9233. ParseNodePtr pnodeBody = nullptr;
  9234. switch (m_token.tk)
  9235. {
  9236. default:
  9237. goto LEndSwitch;
  9238. case tkCASE:
  9239. {
  9240. pnodeCase = this->ParseCase<buildAST>(&pnodeBody);
  9241. break;
  9242. }
  9243. case tkDEFAULT:
  9244. if (fSeenDefault)
  9245. {
  9246. Error(ERRdupDefault);
  9247. // No recovery necessary since this is a semantic, not structural, error
  9248. }
  9249. fSeenDefault = TRUE;
  9250. charcount_t ichMinT = this->GetScanner()->IchMinTok();
  9251. this->GetScanner()->Scan();
  9252. charcount_t ichMinInner = this->GetScanner()->IchLimTok();
  9253. ChkCurTok(tkColon, ERRnoColon);
  9254. if (buildAST)
  9255. {
  9256. pnodeCase = CreateNodeForOpT<knopCase>(ichMinT);
  9257. pnodeSwitch->pnodeDefault = pnodeCase;
  9258. pnodeCase->ichLim = ichMinInner;
  9259. pnodeCase->pnodeExpr = nullptr;
  9260. }
  9261. ParseStmtList<buildAST>(&pnodeBody);
  9262. break;
  9263. }
  9264. // Create a block node to contain the statement list for this case.
  9265. // This helps us insert byte code to return the right value from
  9266. // global/eval code.
  9267. ParseNodeBlock * pnodeFakeBlock = CreateBlockNode();
  9268. if (buildAST)
  9269. {
  9270. if (pnodeBody)
  9271. {
  9272. pnodeFakeBlock->ichMin = pnodeCase->ichMin;
  9273. pnodeFakeBlock->ichLim = pnodeCase->ichLim;
  9274. pnodeCase->pnodeBody = pnodeFakeBlock;
  9275. pnodeCase->pnodeBody->grfpn |= PNodeFlags::fpnSyntheticNode; // block is not a user specifier block
  9276. pnodeCase->pnodeBody->pnodeStmt = pnodeBody;
  9277. }
  9278. else
  9279. {
  9280. pnodeCase->pnodeBody = nullptr;
  9281. }
  9282. *ppnodeCase = pnodeCase;
  9283. ppnodeCase = &pnodeCase->pnodeNext;
  9284. }
  9285. }
  9286. LEndSwitch:
  9287. ChkCurTok(tkRCurly, ERRnoRcurly);
  9288. if (buildAST)
  9289. {
  9290. *ppnodeCase = nullptr;
  9291. PopFuncBlockScope(ppnodeScopeSave, ppnodeExprScopeSave);
  9292. FinishParseBlock(pnode->AsParseNodeSwitch()->pnodeBlock);
  9293. }
  9294. else
  9295. {
  9296. FinishParseBlock(pnodeBlock);
  9297. }
  9298. PopStmt(&stmt);
  9299. break;
  9300. }
  9301. case tkWHILE:
  9302. {
  9303. ichMin = this->GetScanner()->IchMinTok();
  9304. ChkNxtTok(tkLParen, ERRnoLparen);
  9305. ParseNodePtr pnodeCond = ParseExpr<buildAST>();
  9306. charcount_t ichLim = this->GetScanner()->IchLimTok();
  9307. ChkCurTok(tkRParen, ERRnoRparen);
  9308. ParseNodeWhile * pnodeWhile = nullptr;
  9309. if (buildAST)
  9310. {
  9311. pnodeWhile = CreateNodeForOpT<knopWhile>(ichMin);
  9312. pnodeWhile->pnodeCond = pnodeCond;
  9313. pnodeWhile->ichLim = ichLim;
  9314. }
  9315. bool stashedDisallowImportExportStmt = m_disallowImportExportStmt;
  9316. m_disallowImportExportStmt = true;
  9317. PushStmt<buildAST>(&stmt, pnodeWhile, knopWhile, pLabelIdList);
  9318. ParseNodePtr pnodeBody = ParseStatement<buildAST>();
  9319. PopStmt(&stmt);
  9320. if (buildAST)
  9321. {
  9322. pnodeWhile->pnodeBody = pnodeBody;
  9323. pnode = pnodeWhile;
  9324. }
  9325. m_disallowImportExportStmt = stashedDisallowImportExportStmt;
  9326. break;
  9327. }
  9328. case tkDO:
  9329. {
  9330. ParseNodeWhile * pnodeWhile = nullptr;
  9331. if (buildAST)
  9332. {
  9333. pnodeWhile = CreateNodeForOpT<knopDoWhile>();
  9334. }
  9335. PushStmt<buildAST>(&stmt, pnodeWhile, knopDoWhile, pLabelIdList);
  9336. this->GetScanner()->Scan();
  9337. bool stashedDisallowImportExportStmt = m_disallowImportExportStmt;
  9338. m_disallowImportExportStmt = true;
  9339. ParseNodePtr pnodeBody = ParseStatement<buildAST>();
  9340. m_disallowImportExportStmt = stashedDisallowImportExportStmt;
  9341. PopStmt(&stmt);
  9342. charcount_t ichMinT = this->GetScanner()->IchMinTok();
  9343. ChkCurTok(tkWHILE, ERRnoWhile);
  9344. ChkCurTok(tkLParen, ERRnoLparen);
  9345. ParseNodePtr pnodeCond = ParseExpr<buildAST>();
  9346. charcount_t ichLim = this->GetScanner()->IchLimTok();
  9347. ChkCurTok(tkRParen, ERRnoRparen);
  9348. if (buildAST)
  9349. {
  9350. pnodeWhile->pnodeBody = pnodeBody;
  9351. pnodeWhile->pnodeCond = pnodeCond;
  9352. pnodeWhile->ichLim = ichLim;
  9353. pnodeWhile->ichMin = ichMinT;
  9354. pnode = pnodeWhile;
  9355. }
  9356. // REVIEW: Allow do...while statements to be embedded in other compound statements like if..else, or do..while?
  9357. // goto LNeedTerminator;
  9358. // For now just eat the trailing semicolon if present.
  9359. if (m_token.tk == tkSColon)
  9360. {
  9361. if (pnode)
  9362. {
  9363. pnode->grfpn |= PNodeFlags::fpnExplicitSemicolon;
  9364. }
  9365. this->GetScanner()->Scan();
  9366. }
  9367. else if (pnode)
  9368. {
  9369. pnode->grfpn |= PNodeFlags::fpnAutomaticSemicolon;
  9370. }
  9371. break;
  9372. }
  9373. case tkIF:
  9374. {
  9375. ichMin = this->GetScanner()->IchMinTok();
  9376. ChkNxtTok(tkLParen, ERRnoLparen);
  9377. ParseNodePtr pnodeCond = ParseExpr<buildAST>();
  9378. ParseNodeIf * pnodeIf = nullptr;
  9379. if (buildAST)
  9380. {
  9381. pnodeIf = CreateNodeForOpT<knopIf>(ichMin);
  9382. pnodeIf->ichLim = this->GetScanner()->IchLimTok();
  9383. pnodeIf->pnodeCond = pnodeCond;
  9384. }
  9385. ChkCurTok(tkRParen, ERRnoRparen);
  9386. bool stashedDisallowImportExportStmt = m_disallowImportExportStmt;
  9387. m_disallowImportExportStmt = true;
  9388. PushStmt<buildAST>(&stmt, pnodeIf, knopIf, pLabelIdList);
  9389. ParseNodePtr pnodeTrue = ParseStatement<buildAST>();
  9390. ParseNodePtr pnodeFalse = nullptr;
  9391. if (m_token.tk == tkELSE)
  9392. {
  9393. this->GetScanner()->Scan();
  9394. pnodeFalse = ParseStatement<buildAST>();
  9395. }
  9396. if (buildAST)
  9397. {
  9398. pnodeIf->pnodeTrue = pnodeTrue;
  9399. pnodeIf->pnodeFalse = pnodeFalse;
  9400. pnode = pnodeIf;
  9401. }
  9402. PopStmt(&stmt);
  9403. m_disallowImportExportStmt = stashedDisallowImportExportStmt;
  9404. break;
  9405. }
  9406. case tkTRY:
  9407. {
  9408. ParseNodeBlock * pnodeBlock = CreateBlockNode();
  9409. pnodeBlock->grfpn |= PNodeFlags::fpnSyntheticNode; // block is not a user specifier block
  9410. PushStmt<buildAST>(&stmt, pnodeBlock, knopBlock, pLabelIdList);
  9411. ParseNodePtr pnodeStmt = ParseTryCatchFinally<buildAST>();
  9412. if (buildAST)
  9413. {
  9414. pnodeBlock->pnodeStmt = pnodeStmt;
  9415. }
  9416. PopStmt(&stmt);
  9417. pnode = pnodeBlock;
  9418. break;
  9419. }
  9420. case tkWITH:
  9421. {
  9422. if (IsStrictMode())
  9423. {
  9424. Error(ERRES5NoWith);
  9425. }
  9426. if (m_currentNodeFunc)
  9427. {
  9428. GetCurrentFunctionNode()->SetHasWithStmt(); // Used by DeferNested
  9429. }
  9430. ichMin = this->GetScanner()->IchMinTok();
  9431. ChkNxtTok(tkLParen, ERRnoLparen);
  9432. ParseNodePtr pnodeObj = ParseExpr<buildAST>();
  9433. if (!buildAST)
  9434. {
  9435. m_scopeCountNoAst++;
  9436. }
  9437. charcount_t ichLim = this->GetScanner()->IchLimTok();
  9438. ChkCurTok(tkRParen, ERRnoRparen);
  9439. ParseNodeWith * pnodeWith = nullptr;
  9440. if (buildAST)
  9441. {
  9442. pnodeWith = CreateNodeForOpT<knopWith>(ichMin);
  9443. }
  9444. PushStmt<buildAST>(&stmt, pnodeWith, knopWith, pLabelIdList);
  9445. ParseNodePtr *ppnodeExprScopeSave = nullptr;
  9446. if (buildAST)
  9447. {
  9448. pnodeWith->pnodeObj = pnodeObj;
  9449. this->CheckArguments(pnodeWith->pnodeObj);
  9450. if (m_ppnodeExprScope)
  9451. {
  9452. Assert(*m_ppnodeExprScope == nullptr);
  9453. *m_ppnodeExprScope = pnodeWith;
  9454. m_ppnodeExprScope = &pnodeWith->pnodeNext;
  9455. }
  9456. else
  9457. {
  9458. Assert(m_ppnodeScope);
  9459. Assert(*m_ppnodeScope == nullptr);
  9460. *m_ppnodeScope = pnodeWith;
  9461. m_ppnodeScope = &pnodeWith->pnodeNext;
  9462. }
  9463. pnodeWith->pnodeNext = nullptr;
  9464. pnodeWith->scope = nullptr;
  9465. ppnodeExprScopeSave = m_ppnodeExprScope;
  9466. m_ppnodeExprScope = &pnodeWith->pnodeScopes;
  9467. pnodeWith->pnodeScopes = nullptr;
  9468. pnodeWith->ichLim = ichLim;
  9469. pnode = pnodeWith;
  9470. }
  9471. PushBlockInfo(CreateBlockNode());
  9472. PushDynamicBlock();
  9473. ParseNodePtr pnodeBody = ParseStatement<buildAST>();
  9474. if (buildAST)
  9475. {
  9476. pnode->AsParseNodeWith()->pnodeBody = pnodeBody;
  9477. m_ppnodeExprScope = ppnodeExprScopeSave;
  9478. }
  9479. else
  9480. {
  9481. m_scopeCountNoAst--;
  9482. }
  9483. // The dynamic block is not stored in the actual parse tree and so will not
  9484. // be visited by the byte code generator. Grab the callsEval flag off it and
  9485. // pass on to outer block in case of:
  9486. // with (...) eval(...); // i.e. blockless form of with
  9487. bool callsEval = GetCurrentBlock()->GetCallsEval();
  9488. PopBlockInfo();
  9489. if (callsEval)
  9490. {
  9491. // be careful not to overwrite an existing true with false
  9492. GetCurrentBlock()->SetCallsEval(true);
  9493. }
  9494. PopStmt(&stmt);
  9495. break;
  9496. }
  9497. case tkLCurly:
  9498. pnode = ParseBlock<buildAST>(pLabelIdList);
  9499. break;
  9500. case tkSColon:
  9501. pnode = nullptr;
  9502. this->GetScanner()->Scan();
  9503. break;
  9504. case tkBREAK:
  9505. if (buildAST)
  9506. {
  9507. pnode = CreateNodeForOpT<knopBreak>();
  9508. }
  9509. fnop = fnopBreak;
  9510. goto LGetJumpStatement;
  9511. case tkCONTINUE:
  9512. if (buildAST)
  9513. {
  9514. pnode = CreateNodeForOpT<knopContinue>();
  9515. }
  9516. fnop = fnopContinue;
  9517. LGetJumpStatement:
  9518. this->GetScanner()->ScanForcingPid();
  9519. if (tkID == m_token.tk && !this->GetScanner()->FHadNewLine())
  9520. {
  9521. // Labeled break or continue.
  9522. pid = m_token.GetIdentifier(this->GetHashTbl());
  9523. if (buildAST)
  9524. {
  9525. ParseNodeJump * pnodeJump = pnode->AsParseNodeJump();
  9526. pnodeJump->hasExplicitTarget = true;
  9527. pnodeJump->ichLim = this->GetScanner()->IchLimTok();
  9528. this->GetScanner()->Scan();
  9529. PushStmt<buildAST>(&stmt, pnodeJump, pnodeJump->nop, pLabelIdList);
  9530. Assert(pnodeJump->grfnop == 0);
  9531. for (pstmt = m_pstmtCur; nullptr != pstmt; pstmt = pstmt->pstmtOuter)
  9532. {
  9533. for (LabelId* label = pstmt->pLabelId; label != nullptr; label = label->next)
  9534. {
  9535. if (pid == label->pid)
  9536. {
  9537. // Found the label. Make sure we can use it. We can
  9538. // break out of any statement, but we can only
  9539. // continue loops.
  9540. if (fnop == fnopContinue &&
  9541. !(pstmt->pnodeStmt->Grfnop() & fnop))
  9542. {
  9543. Error(ERRbadContinue);
  9544. }
  9545. else
  9546. {
  9547. pstmt->pnodeStmt->grfnop |= fnop;
  9548. pnodeJump->pnodeTarget = pstmt->pnodeStmt;
  9549. }
  9550. PopStmt(&stmt);
  9551. goto LNeedTerminator;
  9552. }
  9553. }
  9554. pnodeJump->grfnop |=
  9555. (pstmt->pnodeStmt->Grfnop() & fnopCleanup);
  9556. }
  9557. }
  9558. else
  9559. {
  9560. this->GetScanner()->Scan();
  9561. // Check if label is found within the current label id list.
  9562. auto checkLabelList = [&](LabelId* list, StmtNest* checkStmtOp)
  9563. {
  9564. for (LabelId* pLabelId = list; pLabelId; pLabelId = pLabelId->next)
  9565. {
  9566. if (pid == pLabelId->pid)
  9567. {
  9568. // Found the label. Make sure we can use it. We can
  9569. // break out of any statement, but we can only
  9570. // continue loops.
  9571. if (fnop == fnopContinue &&
  9572. !(ParseNode::Grfnop(checkStmtOp->op) & fnop))
  9573. {
  9574. Error(ERRbadContinue);
  9575. }
  9576. return true;
  9577. }
  9578. }
  9579. return false;
  9580. };
  9581. if (checkLabelList(pLabelIdList, m_pstmtCur)) goto LNeedTerminator;
  9582. for (pstmt = m_pstmtCur; pstmt; pstmt = pstmt->pstmtOuter)
  9583. {
  9584. if (checkLabelList(pstmt->pLabelId, pstmt)) goto LNeedTerminator;
  9585. }
  9586. }
  9587. Error(ERRnoLabel);
  9588. }
  9589. else
  9590. {
  9591. // If we're doing a fast scan, we're not tracking labels, so we can't accurately do this analysis.
  9592. // Let the thread that's doing the full parse detect the error, if there is one.
  9593. if (!this->IsDoingFastScan())
  9594. {
  9595. // Unlabeled break or continue.
  9596. ParseNodeJump * pnodeJump = nullptr;
  9597. if (buildAST)
  9598. {
  9599. pnodeJump = pnode->AsParseNodeJump();
  9600. pnodeJump->hasExplicitTarget = false;
  9601. PushStmt<buildAST>(&stmt, pnodeJump, pnodeJump->nop, pLabelIdList);
  9602. Assert(pnodeJump->grfnop == 0);
  9603. }
  9604. for (pstmt = m_pstmtCur; nullptr != pstmt; pstmt = pstmt->pstmtOuter)
  9605. {
  9606. if (buildAST)
  9607. {
  9608. AnalysisAssert(pstmt->pnodeStmt);
  9609. if (pstmt->pnodeStmt->Grfnop() & fnop)
  9610. {
  9611. pstmt->pnodeStmt->grfnop |= fnop;
  9612. pnodeJump->pnodeTarget = pstmt->pnodeStmt;
  9613. PopStmt(&stmt);
  9614. goto LNeedTerminator;
  9615. }
  9616. pnodeJump->grfnop |=
  9617. (pstmt->pnodeStmt->Grfnop() & fnopCleanup);
  9618. }
  9619. else
  9620. {
  9621. if (ParseNode::Grfnop(pstmt->GetNop()) & fnop)
  9622. {
  9623. if (!pstmt->isDeferred)
  9624. {
  9625. AnalysisAssert(pstmt->pnodeStmt);
  9626. pstmt->pnodeStmt->grfnop |= fnop;
  9627. }
  9628. goto LNeedTerminator;
  9629. }
  9630. }
  9631. }
  9632. Error(fnop == fnopBreak ? ERRbadBreak : ERRbadContinue);
  9633. }
  9634. goto LNeedTerminator;
  9635. }
  9636. case tkRETURN:
  9637. {
  9638. ParseNodeReturn * pnodeReturn;
  9639. if (buildAST)
  9640. {
  9641. if (nullptr == m_currentNodeFunc || IsTopLevelModuleFunc())
  9642. {
  9643. Error(ERRbadReturn);
  9644. }
  9645. pnodeReturn = CreateNodeForOpT<knopReturn>();
  9646. }
  9647. this->GetScanner()->Scan();
  9648. ParseNodePtr pnodeExpr = nullptr;
  9649. ParseOptionalExpr<buildAST>(&pnodeExpr, true);
  9650. // Class constructors have special semantics regarding return statements.
  9651. // This might require a reference to 'this'
  9652. if (GetCurrentFunctionNode()->IsClassConstructor())
  9653. {
  9654. ReferenceSpecialName(wellKnownPropertyPids._this);
  9655. }
  9656. if (buildAST)
  9657. {
  9658. pnodeReturn->pnodeExpr = pnodeExpr;
  9659. if (pnodeExpr)
  9660. {
  9661. this->CheckArguments(pnodeReturn->pnodeExpr);
  9662. pnodeReturn->ichLim = pnodeReturn->pnodeExpr->ichLim;
  9663. }
  9664. // See if return should call finally
  9665. PushStmt<buildAST>(&stmt, pnodeReturn, knopReturn, pLabelIdList);
  9666. Assert(pnodeReturn->grfnop == 0);
  9667. for (pstmt = m_pstmtCur; nullptr != pstmt; pstmt = pstmt->pstmtOuter)
  9668. {
  9669. if (pstmt->pnodeStmt->Grfnop() & fnopCleanup)
  9670. {
  9671. pnodeReturn->grfnop |= fnopCleanup;
  9672. break;
  9673. }
  9674. }
  9675. PopStmt(&stmt);
  9676. pnode = pnodeReturn;
  9677. }
  9678. goto LNeedTerminator;
  9679. }
  9680. case tkTHROW:
  9681. {
  9682. if (buildAST)
  9683. {
  9684. pnode = CreateUniNode(knopThrow, nullptr);
  9685. }
  9686. this->GetScanner()->Scan();
  9687. ParseNodePtr pnode1 = nullptr;
  9688. if (m_token.tk != tkSColon &&
  9689. m_token.tk != tkRCurly &&
  9690. !this->GetScanner()->FHadNewLine())
  9691. {
  9692. pnode1 = ParseExpr<buildAST>();
  9693. }
  9694. else
  9695. {
  9696. Error(ERRdanglingThrow);
  9697. }
  9698. if (buildAST)
  9699. {
  9700. pnode->AsParseNodeUni()->pnode1 = pnode1;
  9701. if (pnode1)
  9702. {
  9703. this->CheckArguments(pnode->AsParseNodeUni()->pnode1);
  9704. pnode->ichLim = pnode->AsParseNodeUni()->pnode1->ichLim;
  9705. }
  9706. }
  9707. goto LNeedTerminator;
  9708. }
  9709. case tkDEBUGGER:
  9710. if (buildAST)
  9711. {
  9712. pnode = CreateNodeForOpT<knopDebugger>();
  9713. }
  9714. this->GetScanner()->Scan();
  9715. goto LNeedTerminator;
  9716. case tkIMPORT:
  9717. pnode = ParseImport<buildAST>();
  9718. goto LNeedTerminator;
  9719. case tkEXPORT:
  9720. {
  9721. if (!(m_grfscr & fscrIsModuleCode))
  9722. {
  9723. goto LDefaultToken;
  9724. }
  9725. bool needTerminator = false;
  9726. pnode = ParseExportDeclaration<buildAST>(&needTerminator);
  9727. if (needTerminator)
  9728. {
  9729. goto LNeedTerminator;
  9730. }
  9731. else
  9732. {
  9733. break;
  9734. }
  9735. }
  9736. LDefaultToken:
  9737. default:
  9738. {
  9739. // First check for a label via lookahead. If not found,
  9740. // rewind and reparse as expression statement.
  9741. if (m_token.tk == tkID)
  9742. {
  9743. RestorePoint idStart;
  9744. this->GetScanner()->Capture(&idStart);
  9745. IdentPtr pidInner = m_token.GetIdentifier(this->GetHashTbl());
  9746. this->GetScanner()->Scan();
  9747. if (m_token.tk == tkColon)
  9748. {
  9749. // We have a label.
  9750. if (LabelExists(pidInner, pLabelIdList))
  9751. {
  9752. Error(ERRbadLabel);
  9753. }
  9754. LabelId* pLabelId = CreateLabelId(pidInner);
  9755. pLabelId->next = pLabelIdList;
  9756. pLabelIdList = pLabelId;
  9757. this->GetScanner()->Scan();
  9758. labelledStatement = true;
  9759. goto LRestart;
  9760. }
  9761. // No label, rewind back to the tkID and parse an expression
  9762. this->GetScanner()->SeekTo(idStart);
  9763. }
  9764. // Must be an expression statement.
  9765. pnode = ParseExpr<buildAST>();
  9766. if (m_hasDeferredShorthandInitError)
  9767. {
  9768. Error(ERRnoColon);
  9769. }
  9770. if (buildAST)
  9771. {
  9772. expressionStmt = true;
  9773. AnalysisAssert(pnode);
  9774. pnode->isUsed = false;
  9775. }
  9776. }
  9777. LNeedTerminator:
  9778. // Need a semicolon, new-line, } or end-of-file.
  9779. // We digest a semicolon if it's there.
  9780. switch (m_token.tk)
  9781. {
  9782. case tkSColon:
  9783. this->GetScanner()->Scan();
  9784. if (pnode != nullptr) pnode->grfpn |= PNodeFlags::fpnExplicitSemicolon;
  9785. break;
  9786. case tkEOF:
  9787. case tkRCurly:
  9788. if (pnode != nullptr) pnode->grfpn |= PNodeFlags::fpnAutomaticSemicolon;
  9789. break;
  9790. default:
  9791. if (!this->GetScanner()->FHadNewLine())
  9792. {
  9793. Error(ERRnoSemic);
  9794. }
  9795. else
  9796. {
  9797. if (pnode != nullptr) pnode->grfpn |= PNodeFlags::fpnAutomaticSemicolon;
  9798. }
  9799. break;
  9800. }
  9801. break;
  9802. }
  9803. if (m_hasDeferredShorthandInitError)
  9804. {
  9805. Error(ERRnoColon);
  9806. }
  9807. if (buildAST)
  9808. {
  9809. // All non expression statements excluded from the "this.x" optimization
  9810. // Another check while parsing expressions
  9811. if (!expressionStmt)
  9812. {
  9813. if (m_currentNodeFunc)
  9814. {
  9815. m_currentNodeFunc->SetHasNonThisStmt();
  9816. }
  9817. else if (m_currentNodeProg)
  9818. {
  9819. m_currentNodeProg->SetHasNonThisStmt();
  9820. }
  9821. }
  9822. #if EXCEPTION_RECOVERY
  9823. // close the try/catch block
  9824. if (Js::Configuration::Global.flags.SwallowExceptions)
  9825. {
  9826. // pop the try block and fill in the body
  9827. PopStmt(&stmtTryBlock);
  9828. pTryBlock->pnodeStmt = pnode;
  9829. PopStmt(&stmtTry);
  9830. if (pnode != nullptr)
  9831. {
  9832. pTry->ichLim = pnode->ichLim;
  9833. }
  9834. pTry->pnodeBody = pTryBlock;
  9835. // create a catch block with an empty body
  9836. StmtNest stmtCatch;
  9837. ParseNodeCatch * pCatch;
  9838. pCatch = CreateNodeForOpT<knopCatch>();
  9839. PushStmt<buildAST>(&stmtCatch, pCatch, knopCatch, nullptr);
  9840. pCatch->pnodeBody = nullptr;
  9841. if (pnode != nullptr)
  9842. {
  9843. pCatch->ichLim = pnode->ichLim;
  9844. }
  9845. pCatch->grfnop = 0;
  9846. pCatch->pnodeNext = nullptr;
  9847. // create a fake name for the catch var.
  9848. const WCHAR *uniqueNameStr = _u("__ehobj");
  9849. IdentPtr uniqueName = this->GetHashTbl()->PidHashNameLen(uniqueNameStr, static_cast<int32>(wcslen(uniqueNameStr)));
  9850. pCatch->SetParam(CreateNameNode(uniqueName));
  9851. // Add this catch to the current list. We don't bother adjusting the catch and function expression
  9852. // lists here because the catch is just an empty statement.
  9853. if (m_ppnodeExprScope)
  9854. {
  9855. Assert(*m_ppnodeExprScope == nullptr);
  9856. *m_ppnodeExprScope = pCatch;
  9857. m_ppnodeExprScope = &pCatch->pnodeNext;
  9858. }
  9859. else
  9860. {
  9861. Assert(m_ppnodeScope);
  9862. Assert(*m_ppnodeScope == nullptr);
  9863. *m_ppnodeScope = pCatch;
  9864. m_ppnodeScope = &pCatch->pnodeNext;
  9865. }
  9866. pCatch->pnodeScopes = nullptr;
  9867. PopStmt(&stmtCatch);
  9868. // fill in and pop the try-catch
  9869. pParentTryCatch->pnodeTry = pTry;
  9870. pParentTryCatch->pnodeCatch = pCatch;
  9871. PopStmt(&stmtTryCatch);
  9872. PopStmt(&stmtTryCatchBlock);
  9873. // replace the node that's being returned
  9874. pParentTryCatchBlock->pnodeStmt = pParentTryCatch;
  9875. pnode = pParentTryCatchBlock;
  9876. }
  9877. #endif // EXCEPTION_RECOVERY
  9878. }
  9879. return pnode;
  9880. }
  9881. BOOL
  9882. Parser::TokIsForInOrForOf()
  9883. {
  9884. return m_token.tk == tkIN || CheckContextualKeyword(wellKnownPropertyPids.of);
  9885. }
  9886. /***************************************************************************
  9887. Parse a sequence of statements.
  9888. ***************************************************************************/
  9889. template<bool buildAST>
  9890. void Parser::ParseStmtList(ParseNodePtr *ppnodeList, ParseNodePtr **pppnodeLast, StrictModeEnvironment smEnvironment, const bool isSourceElementList, bool* strictModeOn)
  9891. {
  9892. BOOL doneDirectives = !isSourceElementList; // directives may only exist in a SourceElementList, not a StatementList
  9893. BOOL seenDirectiveContainingOctal = false; // Have we seen an octal directive before a use strict directive?
  9894. BOOL old_UseStrictMode = m_fUseStrictMode;
  9895. ParseNodePtr pnodeStmt;
  9896. ParseNodePtr *lastNodeRef = nullptr;
  9897. if (buildAST)
  9898. {
  9899. Assert(ppnodeList);
  9900. *ppnodeList = nullptr;
  9901. }
  9902. if (CONFIG_FLAG(ForceStrictMode))
  9903. {
  9904. m_fUseStrictMode = TRUE;
  9905. }
  9906. for (;;)
  9907. {
  9908. switch (m_token.tk)
  9909. {
  9910. case tkCASE:
  9911. case tkDEFAULT:
  9912. case tkRCurly:
  9913. case tkEOF:
  9914. if (buildAST && nullptr != pppnodeLast)
  9915. {
  9916. *pppnodeLast = lastNodeRef;
  9917. }
  9918. if (!buildAST)
  9919. {
  9920. m_fUseStrictMode = old_UseStrictMode;
  9921. }
  9922. return;
  9923. }
  9924. if (doneDirectives == FALSE)
  9925. {
  9926. bool isOctalInString = false;
  9927. bool isUseStrictDirective = false;
  9928. bool isUseAsmDirective = false;
  9929. if (smEnvironment != SM_NotUsed && CheckForDirective(&isUseStrictDirective, &isUseAsmDirective, &isOctalInString))
  9930. {
  9931. // Ignore "use asm" statement when not building the AST
  9932. isUseAsmDirective &= buildAST;
  9933. if (isUseStrictDirective)
  9934. {
  9935. // Functions with non-simple parameter list cannot be made strict mode
  9936. if (GetCurrentFunctionNode()->HasNonSimpleParameterList())
  9937. {
  9938. Error(ERRNonSimpleParamListInStrictMode);
  9939. }
  9940. if (seenDirectiveContainingOctal)
  9941. {
  9942. // Directives seen before a "use strict" cannot contain an octal.
  9943. Error(ERRES5NoOctal);
  9944. }
  9945. if (!buildAST)
  9946. {
  9947. // Turning on strict mode in deferred code.
  9948. m_fUseStrictMode = TRUE;
  9949. if (!m_inDeferredNestedFunc)
  9950. {
  9951. // Top-level deferred function, so there's a parse node
  9952. Assert(m_currentNodeFunc != nullptr);
  9953. m_currentNodeFunc->SetStrictMode();
  9954. }
  9955. else if (strictModeOn)
  9956. {
  9957. // This turns on strict mode in a deferred function, we need to go back
  9958. // and re-check duplicated formals.
  9959. *strictModeOn = true;
  9960. }
  9961. }
  9962. else
  9963. {
  9964. if (smEnvironment == SM_OnGlobalCode)
  9965. {
  9966. // Turning on strict mode at the top level
  9967. m_fUseStrictMode = TRUE;
  9968. }
  9969. else
  9970. {
  9971. // i.e. smEnvironment == SM_OnFunctionCode
  9972. Assert(m_currentNodeFunc != nullptr);
  9973. m_currentNodeFunc->SetStrictMode();
  9974. }
  9975. }
  9976. }
  9977. else if (isUseAsmDirective)
  9978. {
  9979. if (smEnvironment != SM_OnGlobalCode) //Top level use asm doesn't mean anything.
  9980. {
  9981. // i.e. smEnvironment == SM_OnFunctionCode
  9982. Assert(m_currentNodeFunc != nullptr);
  9983. m_currentNodeFunc->SetAsmjsMode();
  9984. m_currentNodeFunc->SetCanBeDeferred(false);
  9985. m_InAsmMode = true;
  9986. CHAKRATEL_LANGSTATS_INC_LANGFEATURECOUNT(ES6, AsmJSFunction, m_scriptContext);
  9987. }
  9988. }
  9989. else if (isOctalInString)
  9990. {
  9991. seenDirectiveContainingOctal = TRUE;
  9992. }
  9993. }
  9994. else
  9995. {
  9996. // The first time we see anything other than a directive we can have no more directives.
  9997. doneDirectives = TRUE;
  9998. }
  9999. }
  10000. if (nullptr != (pnodeStmt = ParseStatement<buildAST>()))
  10001. {
  10002. if (buildAST)
  10003. {
  10004. AddToNodeList(ppnodeList, &lastNodeRef, pnodeStmt);
  10005. }
  10006. }
  10007. }
  10008. }
  10009. template <class Fn>
  10010. void Parser::FinishFunctionsInScope(ParseNodePtr pnodeScopeList, Fn fn)
  10011. {
  10012. Scope * scope;
  10013. Scope * origCurrentScope = this->m_currentScope;
  10014. ParseNodePtr pnodeScope;
  10015. ParseNodeBlock * pnodeBlock;
  10016. for (pnodeScope = pnodeScopeList; pnodeScope;)
  10017. {
  10018. switch (pnodeScope->nop)
  10019. {
  10020. case knopBlock:
  10021. {
  10022. ParseNodeBlock * pnodeBlockScope = pnodeScope->AsParseNodeBlock();
  10023. m_nextBlockId = pnodeBlockScope->blockId + 1;
  10024. PushBlockInfo(pnodeBlockScope);
  10025. scope = pnodeBlockScope->scope;
  10026. if (scope && scope != origCurrentScope)
  10027. {
  10028. PushScope(scope);
  10029. }
  10030. FinishFunctionsInScope(pnodeBlockScope->pnodeScopes, fn);
  10031. if (scope && scope != origCurrentScope)
  10032. {
  10033. BindPidRefs<false>(GetCurrentBlockInfo(), m_nextBlockId - 1);
  10034. PopScope(scope);
  10035. }
  10036. PopBlockInfo();
  10037. pnodeScope = pnodeBlockScope->pnodeNext;
  10038. break;
  10039. }
  10040. case knopFncDecl:
  10041. fn(pnodeScope->AsParseNodeFnc());
  10042. pnodeScope = pnodeScope->AsParseNodeFnc()->pnodeNext;
  10043. break;
  10044. case knopCatch:
  10045. scope = pnodeScope->AsParseNodeCatch()->scope;
  10046. if (scope)
  10047. {
  10048. PushScope(scope);
  10049. }
  10050. pnodeBlock = CreateBlockNode(PnodeBlockType::Regular);
  10051. pnodeBlock->scope = scope;
  10052. PushBlockInfo(pnodeBlock);
  10053. FinishFunctionsInScope(pnodeScope->AsParseNodeCatch()->pnodeScopes, fn);
  10054. if (scope)
  10055. {
  10056. BindPidRefs<false>(GetCurrentBlockInfo(), m_nextBlockId - 1);
  10057. PopScope(scope);
  10058. }
  10059. PopBlockInfo();
  10060. pnodeScope = pnodeScope->AsParseNodeCatch()->pnodeNext;
  10061. break;
  10062. case knopWith:
  10063. PushBlockInfo(CreateBlockNode());
  10064. PushDynamicBlock();
  10065. FinishFunctionsInScope(pnodeScope->AsParseNodeWith()->pnodeScopes, fn);
  10066. PopBlockInfo();
  10067. pnodeScope = pnodeScope->AsParseNodeWith()->pnodeNext;
  10068. break;
  10069. default:
  10070. AssertMsg(false, "Unexpected node with scope list");
  10071. return;
  10072. }
  10073. }
  10074. }
  10075. // Scripts above this size (minus string literals and comments) will have parsing of
  10076. // function bodies deferred.
  10077. ULONG Parser::GetDeferralThreshold(bool isProfileLoaded)
  10078. {
  10079. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  10080. if (CONFIG_FLAG(ForceDeferParse) ||
  10081. PHASE_FORCE1(Js::DeferParsePhase) ||
  10082. Js::Configuration::Global.flags.IsEnabled(Js::ForceUndoDeferFlag))
  10083. {
  10084. return 0;
  10085. }
  10086. else if (Js::Configuration::Global.flags.IsEnabled(Js::DeferParseFlag))
  10087. {
  10088. return Js::Configuration::Global.flags.DeferParse;
  10089. }
  10090. else
  10091. #endif
  10092. {
  10093. if (isProfileLoaded)
  10094. {
  10095. return DEFAULT_CONFIG_ProfileBasedDeferParseThreshold;
  10096. }
  10097. return DEFAULT_CONFIG_DeferParseThreshold;
  10098. }
  10099. }
  10100. void Parser::FinishDeferredFunction(ParseNodeBlock * pnodeScopeList)
  10101. {
  10102. ParseContext parseContext;
  10103. this->CaptureContext(&parseContext);
  10104. m_nextBlockId = pnodeScopeList->blockId + 1;
  10105. FinishFunctionsInScope(pnodeScopeList,
  10106. [this, &parseContext](ParseNodeFnc * pnodeFnc)
  10107. {
  10108. Assert(pnodeFnc->nop == knopFncDecl);
  10109. // We need to scan this function based on the already known limits of the function declaration as some of
  10110. // the state such as fAllowIn may not be available at this point. Some of this state depends on the context
  10111. // of the function declaration. For example, a function declaration may be inside a for..in statement's var
  10112. // declaration. It may not be appropriate/possible to try and save all such context information. Functions
  10113. // that actually get deferred achieve this by going through the ParseSourceWithOffset code path.
  10114. this->GetScanner()->Clear();
  10115. this->GetScanner()->SetText(parseContext.pszSrc, pnodeFnc->cbMin /*+ this->m_scan.m_cMinTokMultiUnits*/, pnodeFnc->LengthInBytes(), pnodeFnc->ichMin, parseContext.isUtf8, parseContext.grfscr, pnodeFnc->lineNumber);
  10116. this->GetScanner()->Scan();
  10117. // Non-simple params (such as default) require a good amount of logic to put vars on appropriate scopes. ParseFncDecl handles it
  10118. // properly (both on defer and non-defer case). This is to avoid write duplicated logic here as well. Function with non-simple-param
  10119. // will remain deferred until they are called.
  10120. if (pnodeFnc->pnodeBody == nullptr && !pnodeFnc->HasNonSimpleParameterList())
  10121. {
  10122. // Go back and generate an AST for this function.
  10123. JS_ETW_INTERNAL(EventWriteJSCRIPT_PARSE_FUNC(this->GetScriptContext(), pnodeFnc->functionId, /*Undefer*/TRUE));
  10124. ParseNodeFnc * pnodeFncSave = this->m_currentNodeFunc;
  10125. this->m_currentNodeFunc = pnodeFnc;
  10126. ParseNodeBlock * pnodeFncExprBlock = nullptr;
  10127. ParseNodePtr pnodeName = pnodeFnc->pnodeName;
  10128. if (pnodeName)
  10129. {
  10130. Assert(pnodeName->nop == knopVarDecl);
  10131. ParseNodeVar * pnodeVarName = pnodeName->AsParseNodeVar();
  10132. Assert(pnodeVarName->pnodeNext == nullptr);
  10133. if (!pnodeFnc->IsDeclaration())
  10134. {
  10135. // Set up the named function expression symbol so references inside the function can be bound.
  10136. pnodeFncExprBlock = this->StartParseBlock<true>(PnodeBlockType::Function, ScopeType_FuncExpr);
  10137. PidRefStack *ref = this->PushPidRef(pnodeVarName->pid);
  10138. pnodeVarName->symRef = ref->GetSymRef();
  10139. ref->SetSym(pnodeVarName->sym);
  10140. Scope *fncExprScope = pnodeFncExprBlock->scope;
  10141. fncExprScope->AddNewSymbol(pnodeVarName->sym);
  10142. pnodeFnc->scope = fncExprScope;
  10143. }
  10144. }
  10145. ParseNodeBlock * pnodeBlock = this->StartParseBlock<true>(PnodeBlockType::Parameter, ScopeType_Parameter);
  10146. pnodeFnc->pnodeScopes = pnodeBlock;
  10147. m_ppnodeScope = &pnodeBlock->pnodeScopes;
  10148. pnodeBlock->pnodeStmt = pnodeFnc;
  10149. ParseNodePtr * varNodesList = &pnodeFnc->pnodeVars;
  10150. ParseNodeVar * argNode = nullptr;
  10151. if (!pnodeFnc->IsModule() && !pnodeFnc->IsLambda() && !(pnodeFnc->grfpn & PNodeFlags::fpnArguments_overriddenInParam))
  10152. {
  10153. ParseNodePtr *const ppnodeVarSave = m_ppnodeVar;
  10154. m_ppnodeVar = &pnodeFnc->pnodeVars;
  10155. argNode = this->AddArgumentsNodeToVars(pnodeFnc);
  10156. varNodesList = m_ppnodeVar;
  10157. m_ppnodeVar = ppnodeVarSave;
  10158. }
  10159. // Add the args to the scope, since we won't re-parse those.
  10160. Scope *scope = pnodeBlock->scope;
  10161. uint blockId = GetCurrentBlock()->blockId;
  10162. uint funcId = GetCurrentFunctionNode()->functionId;
  10163. auto addArgsToScope = [&](ParseNodePtr pnodeArg) {
  10164. if (pnodeArg->IsVarLetOrConst())
  10165. {
  10166. ParseNodeVar * pnodeVarArg = pnodeArg->AsParseNodeVar();
  10167. PidRefStack *ref = this->FindOrAddPidRef(pnodeVarArg->pid, blockId, funcId);
  10168. pnodeVarArg->symRef = ref->GetSymRef();
  10169. if (ref->GetSym() != nullptr)
  10170. {
  10171. // Duplicate parameter in a configuration that allows them.
  10172. // The symbol is already in the scope, just point it to the right declaration.
  10173. Assert(ref->GetSym() == pnodeVarArg->sym);
  10174. ref->GetSym()->SetDecl(pnodeVarArg);
  10175. }
  10176. else
  10177. {
  10178. ref->SetSym(pnodeArg->AsParseNodeVar()->sym);
  10179. scope->AddNewSymbol(pnodeVarArg->sym);
  10180. }
  10181. }
  10182. };
  10183. MapFormals(pnodeFnc, addArgsToScope);
  10184. MapFormalsFromPattern(pnodeFnc, addArgsToScope);
  10185. ParseNodeBlock * pnodeInnerBlock = this->StartParseBlock<true>(PnodeBlockType::Function, ScopeType_FunctionBody);
  10186. pnodeFnc->pnodeBodyScope = pnodeInnerBlock;
  10187. // Set the parameter block's child to the function body block.
  10188. *m_ppnodeScope = pnodeInnerBlock;
  10189. ParseNodePtr *ppnodeScopeSave = nullptr;
  10190. ParseNodePtr *ppnodeExprScopeSave = nullptr;
  10191. ppnodeScopeSave = m_ppnodeScope;
  10192. // This synthetic block scope will contain all the nested scopes.
  10193. m_ppnodeScope = &pnodeInnerBlock->pnodeScopes;
  10194. pnodeInnerBlock->pnodeStmt = pnodeFnc;
  10195. // Keep nested function declarations and expressions in the same list at function scope.
  10196. // (Indicate this by nulling out the current function expressions list.)
  10197. ppnodeExprScopeSave = m_ppnodeExprScope;
  10198. m_ppnodeExprScope = nullptr;
  10199. // Shouldn't be any temps in the arg list.
  10200. Assert(*m_ppnodeVar == nullptr);
  10201. // Start the var list.
  10202. m_ppnodeVar = varNodesList;
  10203. if (scope != nullptr)
  10204. {
  10205. Assert(pnodeFnc->IsBodyAndParamScopeMerged());
  10206. blockId = GetCurrentBlock()->blockId;
  10207. funcId = GetCurrentFunctionNode()->functionId;
  10208. scope->ForEachSymbol([this, blockId, funcId](Symbol* paramSym)
  10209. {
  10210. PidRefStack* ref = this->FindOrAddPidRef(paramSym->GetPid(), blockId, funcId);
  10211. ref->SetSym(paramSym);
  10212. });
  10213. }
  10214. Assert(m_currentNodeNonLambdaFunc == nullptr);
  10215. m_currentNodeNonLambdaFunc = pnodeFnc;
  10216. this->FinishFncNode(pnodeFnc);
  10217. Assert(pnodeFnc == m_currentNodeNonLambdaFunc);
  10218. m_currentNodeNonLambdaFunc = nullptr;
  10219. m_ppnodeExprScope = ppnodeExprScopeSave;
  10220. Assert(m_ppnodeScope);
  10221. Assert(nullptr == *m_ppnodeScope);
  10222. m_ppnodeScope = ppnodeScopeSave;
  10223. this->FinishParseBlock(pnodeInnerBlock);
  10224. if (!pnodeFnc->IsModule() && (m_token.tk == tkLCurly || !pnodeFnc->IsLambda()))
  10225. {
  10226. UpdateArgumentsNode(pnodeFnc, argNode);
  10227. }
  10228. CreateSpecialSymbolDeclarations(pnodeFnc);
  10229. this->FinishParseBlock(pnodeBlock);
  10230. if (pnodeFncExprBlock)
  10231. {
  10232. this->FinishParseBlock(pnodeFncExprBlock);
  10233. }
  10234. this->m_currentNodeFunc = pnodeFncSave;
  10235. }
  10236. });
  10237. this->RestoreContext(&parseContext);
  10238. }
  10239. void Parser::InitPids()
  10240. {
  10241. wellKnownPropertyPids.arguments = this->GetHashTbl()->PidHashNameLen(g_ssym_arguments.sz, g_ssym_arguments.cch);
  10242. wellKnownPropertyPids.async = this->GetHashTbl()->PidHashNameLen(g_ssym_async.sz, g_ssym_async.cch);
  10243. wellKnownPropertyPids.eval = this->GetHashTbl()->PidHashNameLen(g_ssym_eval.sz, g_ssym_eval.cch);
  10244. wellKnownPropertyPids.get = this->GetHashTbl()->PidHashNameLen(g_ssym_get.sz, g_ssym_get.cch);
  10245. wellKnownPropertyPids.set = this->GetHashTbl()->PidHashNameLen(g_ssym_set.sz, g_ssym_set.cch);
  10246. wellKnownPropertyPids.let = this->GetHashTbl()->PidHashNameLen(g_ssym_let.sz, g_ssym_let.cch);
  10247. wellKnownPropertyPids.await = this->GetHashTbl()->PidHashNameLen(g_ssym_await.sz, g_ssym_await.cch);
  10248. wellKnownPropertyPids.constructor = this->GetHashTbl()->PidHashNameLen(g_ssym_constructor.sz, g_ssym_constructor.cch);
  10249. wellKnownPropertyPids.prototype = this->GetHashTbl()->PidHashNameLen(g_ssym_prototype.sz, g_ssym_prototype.cch);
  10250. wellKnownPropertyPids.__proto__ = this->GetHashTbl()->PidHashNameLen(_u("__proto__"), sizeof("__proto__") - 1);
  10251. wellKnownPropertyPids.of = this->GetHashTbl()->PidHashNameLen(_u("of"), sizeof("of") - 1);
  10252. wellKnownPropertyPids.target = this->GetHashTbl()->PidHashNameLen(_u("target"), sizeof("target") - 1);
  10253. wellKnownPropertyPids.meta = this->GetHashTbl()->PidHashNameLen(_u("meta"), sizeof("meta") - 1);
  10254. wellKnownPropertyPids.as = this->GetHashTbl()->PidHashNameLen(_u("as"), sizeof("as") - 1);
  10255. wellKnownPropertyPids.from = this->GetHashTbl()->PidHashNameLen(_u("from"), sizeof("from") - 1);
  10256. wellKnownPropertyPids._default = this->GetHashTbl()->PidHashNameLen(_u("default"), sizeof("default") - 1);
  10257. wellKnownPropertyPids._star = this->GetHashTbl()->PidHashNameLen(_u("*"), sizeof("*") - 1);
  10258. wellKnownPropertyPids._this = this->GetHashTbl()->PidHashNameLen(_u("*this*"), sizeof("*this*") - 1);
  10259. wellKnownPropertyPids._newTarget = this->GetHashTbl()->PidHashNameLen(_u("*new.target*"), sizeof("*new.target*") - 1);
  10260. wellKnownPropertyPids._super = this->GetHashTbl()->PidHashNameLen(_u("*super*"), sizeof("*super*") - 1);
  10261. wellKnownPropertyPids._superConstructor = this->GetHashTbl()->PidHashNameLen(_u("*superconstructor*"), sizeof("*superconstructor*") - 1);
  10262. wellKnownPropertyPids._importMeta = this->GetHashTbl()->PidHashNameLen(_u("*import.meta*"), sizeof("*import.meta*") - 1);
  10263. }
  10264. void Parser::RestoreScopeInfo(Js::ScopeInfo * scopeInfo)
  10265. {
  10266. if (!scopeInfo)
  10267. {
  10268. return;
  10269. }
  10270. PROBE_STACK_NO_DISPOSE(m_scriptContext, Js::Constants::MinStackByteCodeVisitor);
  10271. RestoreScopeInfo(scopeInfo->GetParentScopeInfo()); // Recursively restore outer func scope info
  10272. scopeInfo->SetScopeId(m_nextBlockId);
  10273. ParseNodeBlock * pnodeScope = nullptr;
  10274. ScopeType scopeType = scopeInfo->GetScopeType();
  10275. PnodeBlockType blockType;
  10276. switch (scopeType)
  10277. {
  10278. case ScopeType_With:
  10279. PushDynamicBlock();
  10280. // fall through
  10281. case ScopeType_Block:
  10282. case ScopeType_Catch:
  10283. case ScopeType_CatchParamPattern:
  10284. case ScopeType_GlobalEvalBlock:
  10285. blockType = PnodeBlockType::Regular;
  10286. break;
  10287. case ScopeType_FunctionBody:
  10288. case ScopeType_FuncExpr:
  10289. blockType = PnodeBlockType::Function;
  10290. break;
  10291. case ScopeType_Parameter:
  10292. blockType = PnodeBlockType::Parameter;
  10293. break;
  10294. default:
  10295. Assert(0);
  10296. return;
  10297. }
  10298. pnodeScope = StartParseBlockWithCapacity<true>(blockType, scopeType, scopeInfo->GetSymbolCount());
  10299. Scope *scope = pnodeScope->scope;
  10300. scope->SetScopeInfo(scopeInfo);
  10301. scopeInfo->ExtractScopeInfo(this, /*nullptr, nullptr,*/ scope);
  10302. }
  10303. void Parser::FinishScopeInfo(Js::ScopeInfo * scopeInfo)
  10304. {
  10305. PROBE_STACK_NO_DISPOSE(m_scriptContext, Js::Constants::MinStackByteCodeVisitor);
  10306. for (; scopeInfo != nullptr; scopeInfo = scopeInfo->GetParentScopeInfo())
  10307. {
  10308. int scopeId = scopeInfo->GetScopeId();
  10309. scopeInfo->GetScope()->ForEachSymbol([this, scopeId](Symbol *sym)
  10310. {
  10311. this->BindPidRefsInScope(sym->GetPid(), sym, scopeId);
  10312. });
  10313. PopScope(scopeInfo->GetScope());
  10314. PopStmt(&m_currentBlockInfo->pstmt);
  10315. PopBlockInfo();
  10316. }
  10317. }
  10318. /***************************************************************************
  10319. Parse the code.
  10320. ***************************************************************************/
  10321. 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)
  10322. {
  10323. ParseNodeProg * pnodeProg;
  10324. ParseNodePtr *lastNodeRef = nullptr;
  10325. m_nextBlockId = 0;
  10326. bool isDeferred = (grfscr & fscrDeferredFnc) != 0;
  10327. bool isModuleSource = (grfscr & fscrIsModuleCode) != 0;
  10328. bool isGlobalCode = (grfscr & fscrGlobalCode) != 0;
  10329. if (this->m_scriptContext->IsScriptContextInDebugMode()
  10330. #ifdef ENABLE_PREJIT
  10331. || Js::Configuration::Global.flags.Prejit
  10332. #endif
  10333. || ((grfscr & fscrNoDeferParse) != 0)
  10334. )
  10335. {
  10336. // Don't do deferred parsing if debugger is attached or feature is disabled
  10337. // by command-line switch.
  10338. grfscr &= ~fscrWillDeferFncParse;
  10339. }
  10340. else if (!isGlobalCode &&
  10341. (
  10342. PHASE_OFF1(Js::Phase::DeferEventHandlersPhase) ||
  10343. this->m_scriptContext->IsScriptContextInSourceRundownOrDebugMode()
  10344. )
  10345. )
  10346. {
  10347. // Don't defer event handlers in debug/rundown mode, because we need to register the document,
  10348. // so we need to create a full FunctionBody for the script body.
  10349. grfscr &= ~fscrWillDeferFncParse;
  10350. }
  10351. m_grfscr = grfscr;
  10352. m_length = length;
  10353. m_originalLength = length;
  10354. m_nextFunctionId = nextFunctionId;
  10355. if (m_parseType != ParseType_Deferred)
  10356. {
  10357. JS_ETW(EventWriteJSCRIPT_PARSE_METHOD_START(m_sourceContextInfo->dwHostSourceContext, GetScriptContext(), *m_nextFunctionId, 0, m_parseType, Js::Constants::GlobalFunction));
  10358. OUTPUT_TRACE(Js::DeferParsePhase, _u("Parsing function (%s) : %s (%d)\n"), GetParseType(), Js::Constants::GlobalFunction, *m_nextFunctionId);
  10359. }
  10360. // Give the scanner the source and get the first token
  10361. this->GetScanner()->SetText(pszSrc, offset, length, charOffset, isUtf8, grfscr, lineNumber);
  10362. this->GetScanner()->Scan();
  10363. // Make the main 'knopProg' node
  10364. int32 initSize = 0;
  10365. m_pCurrentAstSize = &initSize;
  10366. pnodeProg = CreateProgNode(isModuleSource, lineNumber);
  10367. if (!isDeferred || (isDeferred && isGlobalCode))
  10368. {
  10369. // In the deferred case, if the global function is deferred parse (which is in no-refresh case),
  10370. // we will re-use the same function body, so start with the correct functionId.
  10371. pnodeProg->functionId = (*m_nextFunctionId)++;
  10372. }
  10373. if (isModuleSource)
  10374. {
  10375. Assert(m_scriptContext->GetConfig()->IsES6ModuleEnabled());
  10376. pnodeProg->AsParseNodeModule()->localExportEntries = nullptr;
  10377. pnodeProg->AsParseNodeModule()->indirectExportEntries = nullptr;
  10378. pnodeProg->AsParseNodeModule()->starExportEntries = nullptr;
  10379. pnodeProg->AsParseNodeModule()->importEntries = nullptr;
  10380. pnodeProg->AsParseNodeModule()->requestedModules = nullptr;
  10381. }
  10382. m_pCurrentAstSize = &(pnodeProg->astSize);
  10383. // initialize parsing variables
  10384. m_currentNodeFunc = nullptr;
  10385. m_currentNodeDeferredFunc = nullptr;
  10386. m_currentNodeProg = pnodeProg;
  10387. m_cactIdentToNodeLookup = 1;
  10388. m_pnestedCount = &pnodeProg->nestedCount;
  10389. m_inDeferredNestedFunc = false;
  10390. m_ppnodeVar = &pnodeProg->pnodeVars;
  10391. SetCurrentStatement(nullptr);
  10392. AssertMsg(m_pstmtCur == nullptr, "Statement stack should be empty when we start parse global code");
  10393. // Create block for const's and let's
  10394. ParseNodeBlock * pnodeGlobalBlock = StartParseBlock<true>(PnodeBlockType::Global, ScopeType_Global);
  10395. pnodeProg->scope = pnodeGlobalBlock->scope;
  10396. ParseNodeBlock * pnodeGlobalEvalBlock = nullptr;
  10397. // Don't track function expressions separately from declarations at global scope.
  10398. m_ppnodeExprScope = nullptr;
  10399. // This synthetic block scope will contain all the nested scopes.
  10400. pnodeProg->pnodeScopes = pnodeGlobalBlock;
  10401. m_ppnodeScope = &pnodeGlobalBlock->pnodeScopes;
  10402. if ((this->m_grfscr & fscrEvalCode) &&
  10403. !(this->m_functionBody && this->m_functionBody->GetScopeInfo()))
  10404. {
  10405. pnodeGlobalEvalBlock = StartParseBlock<true>(PnodeBlockType::Regular, ScopeType_GlobalEvalBlock);
  10406. pnodeProg->pnodeScopes = pnodeGlobalEvalBlock;
  10407. m_ppnodeScope = &pnodeGlobalEvalBlock->pnodeScopes;
  10408. }
  10409. Js::ScopeInfo *scopeInfo = nullptr;
  10410. if (m_parseType == ParseType_Deferred && m_functionBody)
  10411. {
  10412. // this->m_functionBody can be cleared during parsing, but we need access to the scope info later.
  10413. scopeInfo = m_functionBody->GetScopeInfo();
  10414. if (scopeInfo)
  10415. {
  10416. // Create an enclosing function context.
  10417. m_currentNodeFunc = CreateNodeForOpT<knopFncDecl>();
  10418. m_currentNodeFunc->functionId = m_functionBody->GetLocalFunctionId();
  10419. m_currentNodeFunc->nestedCount = m_functionBody->GetNestedCount();
  10420. m_currentNodeFunc->SetStrictMode(!!this->m_fUseStrictMode);
  10421. this->RestoreScopeInfo(scopeInfo);
  10422. m_currentNodeFunc->SetIsGenerator(scopeInfo->IsGeneratorFunctionBody());
  10423. m_currentNodeFunc->SetIsAsync(scopeInfo->IsAsyncFunctionBody());
  10424. m_currentNodeFunc->SetIsClassConstructor(scopeInfo->IsClassConstructor());
  10425. }
  10426. }
  10427. // It's possible for the module global to be defer-parsed in debug scenarios.
  10428. if (isModuleSource && (!isDeferred || (isDeferred && isGlobalCode)))
  10429. {
  10430. ParseNodePtr moduleFunction = GenerateModuleFunctionWrapper<true>();
  10431. pnodeProg->pnodeBody = nullptr;
  10432. AddToNodeList(&pnodeProg->pnodeBody, &lastNodeRef, moduleFunction);
  10433. }
  10434. else
  10435. {
  10436. if (isDeferred && !isGlobalCode)
  10437. {
  10438. // Defer parse for a single function should just parse that one function - there are no other statements.
  10439. ushort flags = fFncNoFlgs;
  10440. bool isAsync = false;
  10441. bool isGenerator = false;
  10442. bool isMethod = false;
  10443. // The top-level deferred function body was defined by a function expression whose parsing was deferred. We are now
  10444. // parsing it, so unset the flag so that any nested functions are parsed normally. This flag is only applicable the
  10445. // first time we see it.
  10446. //
  10447. // Normally, deferred functions will be parsed in ParseStatement upon encountering the 'function' token. The first
  10448. // token of the source code of the function may not be a 'function' token though, so we still need to reset this flag
  10449. // for the first function we parse. This can happen in compat modes, for instance, for a function expression enclosed
  10450. // in parentheses, where the legacy behavior was to include the parentheses in the function's source code.
  10451. if (m_grfscr & fscrDeferredFncExpression)
  10452. {
  10453. m_grfscr &= ~fscrDeferredFncExpression;
  10454. }
  10455. else
  10456. {
  10457. flags |= fFncDeclaration;
  10458. }
  10459. if (m_grfscr & fscrDeferredFncIsMethod)
  10460. {
  10461. m_grfscr &= ~fscrDeferredFncIsMethod;
  10462. isMethod = true;
  10463. flags |= fFncNoName | fFncMethod;
  10464. if (m_grfscr & fscrDeferredFncIsGenerator)
  10465. {
  10466. m_grfscr &= ~fscrDeferredFncIsGenerator;
  10467. isGenerator = true;
  10468. flags |= fFncGenerator;
  10469. }
  10470. if (m_token.tk == tkStar && m_scriptContext->GetConfig()->IsES6GeneratorsEnabled())
  10471. {
  10472. Assert(isGenerator && !isMethod);
  10473. this->GetScanner()->Scan();
  10474. }
  10475. }
  10476. if (m_grfscr & fscrDeferredFncIsAsync)
  10477. {
  10478. m_grfscr &= ~fscrDeferredFncIsAsync;
  10479. isAsync = true;
  10480. flags |= fFncAsync;
  10481. }
  10482. if (m_grfscr & fscrDeferredFncIsClassConstructor)
  10483. {
  10484. m_grfscr &= ~fscrDeferredFncIsClassConstructor;
  10485. flags |= fFncClassConstructor | fFncClassMember;
  10486. }
  10487. if (m_grfscr & fscrDeferredFncIsBaseClassConstructor)
  10488. {
  10489. m_grfscr &= ~fscrDeferredFncIsBaseClassConstructor;
  10490. flags |= fFncBaseClassConstructor;
  10491. }
  10492. if (m_grfscr & fscrDeferredFncIsClassMember)
  10493. {
  10494. m_grfscr &= ~fscrDeferredFncIsClassMember;
  10495. flags |= fFncClassMember;
  10496. }
  10497. #if DBG
  10498. if (isMethod && m_token.tk == tkID)
  10499. {
  10500. RestorePoint atPid;
  10501. IdentPtr pidHint = m_token.GetIdentifier(this->GetHashTbl());
  10502. this->GetScanner()->Capture(&atPid);
  10503. this->GetScanner()->Scan();
  10504. if ((pidHint == wellKnownPropertyPids.get || pidHint == wellKnownPropertyPids.set) && NextTokenIsPropertyNameStart())
  10505. {
  10506. // Getter/setter
  10507. // Skip the get/set keyword and continue normally
  10508. AssertMsg(false, "We should not be re-parsing the get/set part of member accessor functions");
  10509. }
  10510. else
  10511. {
  10512. // Not a getter/setter; rewind and treat the token as a name.
  10513. this->GetScanner()->SeekTo(atPid);
  10514. }
  10515. }
  10516. #endif
  10517. // Ensure this isn't a computed name
  10518. AssertMsg(!(m_token.tk == tkLBrack && isMethod), "Can't defer parse a computed name expression, we should have started after this");
  10519. if (!isMethod && (m_token.tk == tkID || m_token.tk == tkLParen))
  10520. {
  10521. // If first token of the function is tkID or tkLParen, this is a lambda.
  10522. flags |= fFncLambda;
  10523. }
  10524. ParseNode * pnodeFnc = ParseFncDeclCheckScope<true>(flags);
  10525. pnodeProg->pnodeBody = nullptr;
  10526. AddToNodeList(&pnodeProg->pnodeBody, &lastNodeRef, pnodeFnc);
  10527. // No need to update the cbStringMin property since no ParseableFunctionInfo will be created from this defer-parsed pnodeFnc
  10528. }
  10529. else
  10530. {
  10531. // Process a sequence of statements/declarations
  10532. ParseStmtList<true>(
  10533. &pnodeProg->pnodeBody,
  10534. &lastNodeRef,
  10535. SM_OnGlobalCode,
  10536. !(m_grfscr & fscrDeferredFncExpression) /* isSourceElementList */);
  10537. }
  10538. }
  10539. if (m_parseType == ParseType_Deferred)
  10540. {
  10541. if (scopeInfo)
  10542. {
  10543. this->FinishScopeInfo(scopeInfo);
  10544. }
  10545. }
  10546. pnodeProg->m_UsesArgumentsAtGlobal = m_UsesArgumentsAtGlobal;
  10547. if (IsStrictMode())
  10548. {
  10549. pnodeProg->SetStrictMode();
  10550. }
  10551. #if DEBUG
  10552. if (m_grfscr & fscrEnforceJSON && !IsJSONValid(pnodeProg->pnodeBody))
  10553. {
  10554. Error(ERRsyntax);
  10555. }
  10556. #endif
  10557. if (tkEOF != m_token.tk)
  10558. Error(ERRsyntax);
  10559. // Append an EndCode node.
  10560. AddToNodeList(&pnodeProg->pnodeBody, &lastNodeRef,
  10561. CreateNodeForOpT<knopEndCode>());
  10562. Assert(lastNodeRef);
  10563. Assert(*lastNodeRef);
  10564. Assert((*lastNodeRef)->nop == knopEndCode);
  10565. (*lastNodeRef)->ichMin = 0;
  10566. (*lastNodeRef)->ichLim = 0;
  10567. // Get the extent of the code.
  10568. pnodeProg->ichLim = this->GetScanner()->IchLimTok();
  10569. pnodeProg->cbLim = this->GetScanner()->IecpLimTok();
  10570. // Terminate the local list
  10571. *m_ppnodeVar = nullptr;
  10572. Assert(nullptr == *m_ppnodeScope);
  10573. Assert(nullptr == pnodeProg->pnodeNext);
  10574. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  10575. if (Js::Configuration::Global.flags.IsEnabled(Js::ForceUndoDeferFlag))
  10576. {
  10577. m_stoppedDeferredParse = true;
  10578. }
  10579. #endif
  10580. if (m_stoppedDeferredParse)
  10581. {
  10582. #if ENABLE_BACKGROUND_PARSING
  10583. if (this->m_hasParallelJob)
  10584. {
  10585. BackgroundParser *bgp = static_cast<BackgroundParser*>(m_scriptContext->GetBackgroundParser());
  10586. Assert(bgp);
  10587. this->WaitForBackgroundJobs(bgp, pse);
  10588. }
  10589. #endif
  10590. // Do any remaining bindings of globals referenced in non-deferred functions.
  10591. if (pnodeGlobalEvalBlock)
  10592. {
  10593. FinishParseBlock(pnodeGlobalEvalBlock);
  10594. }
  10595. FinishParseBlock(pnodeGlobalBlock);
  10596. // Clear out references to undeclared identifiers.
  10597. this->GetHashTbl()->VisitPids([&](IdentPtr pid) { pid->SetTopRef(nullptr); });
  10598. // Restore global scope and blockinfo stacks preparatory to reparsing deferred functions.
  10599. PushScope(pnodeGlobalBlock->scope);
  10600. BlockInfoStack *newBlockInfo = PushBlockInfo(pnodeGlobalBlock);
  10601. PushStmt<true>(&newBlockInfo->pstmt, pnodeGlobalBlock, knopBlock, nullptr);
  10602. if (pnodeGlobalEvalBlock)
  10603. {
  10604. PushScope(pnodeGlobalEvalBlock->scope);
  10605. newBlockInfo = PushBlockInfo(pnodeGlobalEvalBlock);
  10606. PushStmt<true>(&newBlockInfo->pstmt, pnodeGlobalEvalBlock, knopBlock, nullptr);
  10607. }
  10608. // Finally, see if there are any function bodies we now want to generate because we
  10609. // decided to stop deferring.
  10610. FinishDeferredFunction(pnodeProg->pnodeScopes);
  10611. }
  10612. if (pnodeGlobalEvalBlock)
  10613. {
  10614. FinishParseBlock(pnodeGlobalEvalBlock);
  10615. }
  10616. // Append block as body of pnodeProg
  10617. FinishParseBlock(pnodeGlobalBlock);
  10618. m_scriptContext->AddSourceSize(m_length);
  10619. if (m_parseType != ParseType_Deferred)
  10620. {
  10621. JS_ETW(EventWriteJSCRIPT_PARSE_METHOD_STOP(m_sourceContextInfo->dwHostSourceContext, GetScriptContext(), pnodeProg->functionId, *m_pCurrentAstSize, false, Js::Constants::GlobalFunction));
  10622. }
  10623. if (isModuleSource)
  10624. {
  10625. // verify that any local module exports are defined
  10626. VerifyModuleLocalExportEntries();
  10627. }
  10628. return pnodeProg;
  10629. }
  10630. bool Parser::CheckForDirective(bool* pIsUseStrict, bool *pIsUseAsm, bool* pIsOctalInString)
  10631. {
  10632. // A directive is a string constant followed by a statement terminating token
  10633. if (m_token.tk != tkStrCon)
  10634. return false;
  10635. // Careful, need to check for octal before calling this->GetScanner()->Scan()
  10636. // because Scan() clears the "had octal" flag on the scanner and
  10637. // this->GetScanner()->Restore() does not restore this flag.
  10638. if (pIsOctalInString != nullptr)
  10639. {
  10640. *pIsOctalInString = this->GetScanner()->IsOctOrLeadingZeroOnLastTKNumber();
  10641. }
  10642. Ident* pidDirective = m_token.GetStr();
  10643. RestorePoint start;
  10644. this->GetScanner()->Capture(&start);
  10645. this->GetScanner()->Scan();
  10646. bool isDirective = true;
  10647. switch (m_token.tk)
  10648. {
  10649. case tkSColon:
  10650. case tkEOF:
  10651. case tkLCurly:
  10652. case tkRCurly:
  10653. break;
  10654. default:
  10655. if (!this->GetScanner()->FHadNewLine())
  10656. {
  10657. isDirective = false;
  10658. }
  10659. break;
  10660. }
  10661. if (isDirective)
  10662. {
  10663. if (pIsUseStrict != nullptr)
  10664. {
  10665. *pIsUseStrict = CheckStrictModeStrPid(pidDirective);
  10666. }
  10667. if (pIsUseAsm != nullptr)
  10668. {
  10669. *pIsUseAsm = CheckAsmjsModeStrPid(pidDirective);
  10670. }
  10671. }
  10672. this->GetScanner()->SeekTo(start);
  10673. return isDirective;
  10674. }
  10675. bool Parser::CheckStrictModeStrPid(IdentPtr pid)
  10676. {
  10677. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  10678. if (Js::Configuration::Global.flags.NoStrictMode)
  10679. return false;
  10680. #endif
  10681. return pid != nullptr &&
  10682. pid->Cch() == 10 &&
  10683. !this->GetScanner()->IsEscapeOnLastTkStrCon() &&
  10684. wcsncmp(pid->Psz(), _u("use strict"), 10) == 0;
  10685. }
  10686. bool Parser::CheckAsmjsModeStrPid(IdentPtr pid)
  10687. {
  10688. #ifdef ASMJS_PLAT
  10689. if (!CONFIG_FLAG(AsmJs))
  10690. {
  10691. return false;
  10692. }
  10693. bool isAsmCandidate = (pid != nullptr &&
  10694. AutoSystemInfo::Data.SSE2Available() &&
  10695. pid->Cch() == 7 &&
  10696. !this->GetScanner()->IsEscapeOnLastTkStrCon() &&
  10697. wcsncmp(pid->Psz(), _u("use asm"), 10) == 0);
  10698. #ifdef ENABLE_SCRIPT_DEBUGGING
  10699. if (isAsmCandidate && m_scriptContext->IsScriptContextInDebugMode())
  10700. {
  10701. // We would like to report this to debugger - they may choose to disable debugging.
  10702. // TODO : localization of the string?
  10703. 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);
  10704. return false;
  10705. }
  10706. #endif
  10707. return isAsmCandidate && !(m_grfscr & fscrNoAsmJs);
  10708. #else
  10709. return false;
  10710. #endif
  10711. }
  10712. HRESULT Parser::ParseUtf8Source(__out ParseNodeProg ** parseTree, LPCUTF8 pSrc, size_t length, ULONG grfsrc, CompileScriptException *pse,
  10713. Js::LocalFunctionId * nextFunctionId, SourceContextInfo * sourceContextInfo)
  10714. {
  10715. m_functionBody = nullptr;
  10716. m_parseType = ParseType_Upfront;
  10717. return ParseSourceInternal(parseTree, pSrc, 0, length, 0, true, grfsrc, pse, nextFunctionId, 0, sourceContextInfo);
  10718. }
  10719. HRESULT Parser::ParseCesu8Source(__out ParseNodeProg ** parseTree, LPCUTF8 pSrc, size_t length, ULONG grfsrc, CompileScriptException *pse,
  10720. Js::LocalFunctionId * nextFunctionId, SourceContextInfo * sourceContextInfo)
  10721. {
  10722. m_functionBody = nullptr;
  10723. m_parseType = ParseType_Upfront;
  10724. return ParseSourceInternal(parseTree, pSrc, 0, length, 0, false, grfsrc, pse, nextFunctionId, 0, sourceContextInfo);
  10725. }
  10726. #if ENABLE_BACKGROUND_PARSING
  10727. void Parser::PrepareForBackgroundParse()
  10728. {
  10729. this->GetScanner()->PrepareForBackgroundParse(m_scriptContext);
  10730. }
  10731. void Parser::AddBackgroundParseItem(BackgroundParseItem *const item)
  10732. {
  10733. if (currBackgroundParseItem == nullptr)
  10734. {
  10735. backgroundParseItems = item;
  10736. }
  10737. else
  10738. {
  10739. currBackgroundParseItem->SetNext(item);
  10740. }
  10741. currBackgroundParseItem = item;
  10742. }
  10743. void Parser::AddFastScannedRegExpNode(ParseNodePtr const pnode)
  10744. {
  10745. Assert(!IsBackgroundParser());
  10746. Assert(m_doingFastScan);
  10747. if (fastScannedRegExpNodes == nullptr)
  10748. {
  10749. fastScannedRegExpNodes = Anew(&m_nodeAllocator, NodeDList, &m_nodeAllocator);
  10750. }
  10751. fastScannedRegExpNodes->Append(pnode);
  10752. }
  10753. void Parser::AddBackgroundRegExpNode(ParseNodePtr const pnode)
  10754. {
  10755. Assert(IsBackgroundParser());
  10756. Assert(currBackgroundParseItem != nullptr);
  10757. currBackgroundParseItem->AddRegExpNode(pnode, &m_nodeAllocator);
  10758. }
  10759. HRESULT Parser::ParseFunctionInBackground(ParseNodeFnc * pnodeFnc, ParseContext *parseContext, bool topLevelDeferred, CompileScriptException *pse)
  10760. {
  10761. m_functionBody = nullptr;
  10762. m_parseType = ParseType_Upfront;
  10763. HRESULT hr = S_OK;
  10764. SmartFPUControl smartFpuControl;
  10765. uint nextFunctionId = pnodeFnc->functionId + 1;
  10766. this->RestoreContext(parseContext);
  10767. m_nextFunctionId = &nextFunctionId;
  10768. m_deferringAST = topLevelDeferred;
  10769. m_inDeferredNestedFunc = false;
  10770. m_scopeCountNoAst = 0;
  10771. SetCurrentStatement(nullptr);
  10772. pnodeFnc->pnodeVars = nullptr;
  10773. pnodeFnc->pnodeParams = nullptr;
  10774. pnodeFnc->pnodeBody = nullptr;
  10775. pnodeFnc->nestedCount = 0;
  10776. ParseNodeFnc * pnodeParentFnc = GetCurrentFunctionNode();
  10777. m_currentNodeFunc = pnodeFnc;
  10778. m_currentNodeDeferredFunc = nullptr;
  10779. m_ppnodeScope = nullptr;
  10780. m_ppnodeExprScope = nullptr;
  10781. m_pnestedCount = &pnodeFnc->nestedCount;
  10782. m_pCurrentAstSize = &pnodeFnc->astSize;
  10783. ParseNodeBlock * pnodeBlock = StartParseBlock<true>(PnodeBlockType::Function, ScopeType_FunctionBody);
  10784. pnodeFnc->pnodeScopes = pnodeBlock;
  10785. m_ppnodeScope = &pnodeBlock->pnodeScopes;
  10786. bool handled = false;
  10787. uint uDeferSave = m_grfscr & (fscrCanDeferFncParse | fscrWillDeferFncParse);
  10788. try
  10789. {
  10790. this->GetScanner()->Scan();
  10791. m_ppnodeVar = &pnodeFnc->pnodeParams;
  10792. this->ParseFncFormals<true>(pnodeFnc, pnodeParentFnc, fFncNoFlgs);
  10793. if (m_token.tk == tkRParen)
  10794. {
  10795. this->GetScanner()->Scan();
  10796. }
  10797. ChkCurTok(tkLCurly, ERRnoLcurly);
  10798. m_ppnodeVar = &pnodeFnc->pnodeVars;
  10799. // Put the scanner into "no hashing" mode.
  10800. BYTE deferFlags = this->GetScanner()->SetDeferredParse(topLevelDeferred);
  10801. // Process a sequence of statements/declarations
  10802. if (topLevelDeferred)
  10803. {
  10804. ParseStmtList<false>(nullptr, nullptr, SM_DeferredParse, true);
  10805. }
  10806. else
  10807. {
  10808. ParseNodePtr *lastNodeRef = nullptr;
  10809. ParseStmtList<true>(&pnodeFnc->pnodeBody, &lastNodeRef, SM_OnFunctionCode, true);
  10810. AddArgumentsNodeToVars(pnodeFnc);
  10811. // Append an EndCode node.
  10812. AddToNodeList(&pnodeFnc->pnodeBody, &lastNodeRef, CreateNodeForOpT<knopEndCode>());
  10813. }
  10814. // Restore the scanner's default hashing mode.
  10815. this->GetScanner()->SetDeferredParseFlags(deferFlags);
  10816. #if DBG
  10817. pnodeFnc->deferredParseNextFunctionId = *this->m_nextFunctionId;
  10818. #endif
  10819. this->m_deferringAST = FALSE;
  10820. // Append block as body of pnodeProg
  10821. FinishParseBlock(pnodeBlock);
  10822. }
  10823. catch (ParseExceptionObject& e)
  10824. {
  10825. hr = e.GetError();
  10826. hr = pse->ProcessError(this->GetScanner(), hr, nullptr, e.GetStringOne(), e.GetStringTwo());
  10827. handled = true;
  10828. }
  10829. if (handled == false && FAILED(hr))
  10830. {
  10831. hr = pse->ProcessError(this->GetScanner(), hr, nullptr);
  10832. }
  10833. if (IsStrictMode())
  10834. {
  10835. pnodeFnc->SetStrictMode();
  10836. }
  10837. if (topLevelDeferred)
  10838. {
  10839. pnodeFnc->pnodeVars = nullptr;
  10840. }
  10841. m_grfscr |= uDeferSave;
  10842. Assert(nullptr == *m_ppnodeScope);
  10843. return hr;
  10844. }
  10845. #endif
  10846. HRESULT Parser::ParseSourceWithOffset(__out ParseNodeProg ** parseTree, LPCUTF8 pSrc, size_t offset, size_t cbLength, charcount_t cchOffset,
  10847. bool isCesu8, ULONG grfscr, CompileScriptException *pse, Js::LocalFunctionId * nextFunctionId, ULONG lineNumber, SourceContextInfo * sourceContextInfo,
  10848. Js::ParseableFunctionInfo* functionInfo)
  10849. {
  10850. m_functionBody = functionInfo;
  10851. if (m_functionBody)
  10852. {
  10853. m_currDeferredStub = m_functionBody->GetDeferredStubs();
  10854. m_currDeferredStubCount = m_currDeferredStub != nullptr ? m_functionBody->GetNestedCount() : 0;
  10855. m_InAsmMode = grfscr & fscrNoAsmJs ? false : m_functionBody->GetIsAsmjsMode();
  10856. }
  10857. m_deferAsmJs = !m_InAsmMode;
  10858. m_parseType = ParseType_Deferred;
  10859. return ParseSourceInternal(parseTree, pSrc, offset, cbLength, cchOffset, !isCesu8, grfscr, pse, nextFunctionId, lineNumber, sourceContextInfo);
  10860. }
  10861. bool Parser::IsStrictMode() const
  10862. {
  10863. return (m_fUseStrictMode ||
  10864. (m_currentNodeFunc != nullptr && m_currentNodeFunc->GetStrictMode()));
  10865. }
  10866. BOOL Parser::ExpectingExternalSource()
  10867. {
  10868. return m_fExpectExternalSource;
  10869. }
  10870. Symbol *ParseNodeFnc::GetFuncSymbol()
  10871. {
  10872. if (pnodeName)
  10873. {
  10874. Assert(pnodeName->nop == knopVarDecl);
  10875. return pnodeName->sym;
  10876. }
  10877. return nullptr;
  10878. }
  10879. void ParseNodeFnc::SetFuncSymbol(Symbol *sym)
  10880. {
  10881. Assert(pnodeName);
  10882. Assert(pnodeName->nop == knopVarDecl);
  10883. pnodeName->sym = sym;
  10884. }
  10885. ParseNodePtr ParseNodeFnc::GetParamScope() const
  10886. {
  10887. if (this->pnodeScopes == nullptr)
  10888. {
  10889. return nullptr;
  10890. }
  10891. Assert(this->pnodeScopes->nop == knopBlock &&
  10892. this->pnodeScopes->pnodeNext == nullptr);
  10893. return this->pnodeScopes->pnodeScopes;
  10894. }
  10895. ParseNodePtr ParseNodeFnc::GetBodyScope() const
  10896. {
  10897. if (this->pnodeBodyScope == nullptr)
  10898. {
  10899. return nullptr;
  10900. }
  10901. Assert(this->pnodeBodyScope->nop == knopBlock &&
  10902. this->pnodeBodyScope->pnodeNext == nullptr);
  10903. return this->pnodeBodyScope->pnodeScopes;
  10904. }
  10905. bool ParseNodeBlock::HasBlockScopedContent() const
  10906. {
  10907. // A block has its own content if a let, const, or function is declared there.
  10908. if (this->pnodeLexVars != nullptr || this->blockType == Parameter)
  10909. {
  10910. return true;
  10911. }
  10912. // The enclosing scopes can contain functions and other things, so walk the list
  10913. // looking specifically for functions.
  10914. for (ParseNodePtr pnode = this->pnodeScopes; pnode;)
  10915. {
  10916. switch (pnode->nop) {
  10917. case knopFncDecl:
  10918. return true;
  10919. case knopBlock:
  10920. pnode = pnode->AsParseNodeBlock()->pnodeNext;
  10921. break;
  10922. case knopCatch:
  10923. pnode = pnode->AsParseNodeCatch()->pnodeNext;
  10924. break;
  10925. case knopWith:
  10926. pnode = pnode->AsParseNodeWith()->pnodeNext;
  10927. break;
  10928. default:
  10929. Assert(UNREACHED);
  10930. return true;
  10931. }
  10932. }
  10933. return false;
  10934. }
  10935. class ByteCodeGenerator;
  10936. // Copy AST; this works mostly on expressions for now
  10937. ParseNode* Parser::CopyPnode(ParseNode *pnode) {
  10938. if (pnode == NULL)
  10939. return NULL;
  10940. switch (pnode->nop) {
  10941. //PTNODE(knopName , "name" ,None ,Pid ,fnopLeaf)
  10942. case knopName: {
  10943. ParseNodeName * nameNode = CreateNameNode(pnode->AsParseNodeName()->pid);
  10944. nameNode->ichMin = pnode->ichMin;
  10945. nameNode->ichLim = pnode->ichLim;
  10946. nameNode->sym = pnode->AsParseNodeName()->sym;
  10947. return nameNode;
  10948. }
  10949. //PTNODE(knopInt , "int const" ,None ,Int ,fnopLeaf|fnopConst)
  10950. case knopInt:
  10951. return pnode;
  10952. //PTNODE(knopBigInt , "bigint const" ,None ,BigInt ,fnopLeaf|fnopConst)
  10953. case knopBigInt:
  10954. return pnode;
  10955. //PTNODE(knopFlt , "flt const" ,None ,Flt ,fnopLeaf|fnopConst)
  10956. case knopFlt:
  10957. return pnode;
  10958. //PTNODE(knopStr , "str const" ,None ,Pid ,fnopLeaf|fnopConst)
  10959. case knopStr:
  10960. return pnode;
  10961. //PTNODE(knopRegExp , "reg expr" ,None ,Pid ,fnopLeaf|fnopConst)
  10962. case knopRegExp:
  10963. return pnode;
  10964. break;
  10965. //PTNODE(knopNull , "null" ,Null ,None ,fnopLeaf)
  10966. case knopNull:
  10967. return pnode;
  10968. //PTNODE(knopFalse , "false" ,False ,None ,fnopLeaf)
  10969. case knopFalse:
  10970. {
  10971. ParseNode* ret = CreateNodeForOpT<knopFalse>(pnode->ichMin, pnode->ichLim);
  10972. ret->location = pnode->location;
  10973. return ret;
  10974. }
  10975. //PTNODE(knopTrue , "true" ,True ,None ,fnopLeaf)
  10976. case knopTrue:
  10977. {
  10978. ParseNode* ret = CreateNodeForOpT<knopTrue>(pnode->ichMin, pnode->ichLim);
  10979. ret->location = pnode->location;
  10980. return ret;
  10981. }
  10982. //PTNODE(knopEmpty , "empty" ,Empty ,None ,fnopLeaf)
  10983. case knopEmpty:
  10984. return CreateNodeForOpT<knopEmpty>(pnode->ichMin, pnode->ichLim);
  10985. // Unary operators.
  10986. //PTNODE(knopNot , "~" ,BitNot ,Uni ,fnopUni)
  10987. //PTNODE(knopNeg , "unary -" ,Neg ,Uni ,fnopUni)
  10988. //PTNODE(knopPos , "unary +" ,Pos ,Uni ,fnopUni)
  10989. //PTNODE(knopLogNot , "!" ,LogNot ,Uni ,fnopUni)
  10990. //PTNODE(knopEllipsis , "..." ,Spread ,Uni , fnopUni)
  10991. //PTNODE(knopDecPost , "-- post" ,Dec ,Uni ,fnopUni|fnopAsg)
  10992. //PTNODE(knopIncPre , "++ pre" ,Inc ,Uni ,fnopUni|fnopAsg)
  10993. //PTNODE(knopDecPre , "-- pre" ,Dec ,Uni ,fnopUni|fnopAsg)
  10994. //PTNODE(knopTypeof , "typeof" ,None ,Uni ,fnopUni)
  10995. //PTNODE(knopVoid , "void" ,Void ,Uni ,fnopUni)
  10996. //PTNODE(knopDelete , "delete" ,None ,Uni ,fnopUni)
  10997. case knopNot:
  10998. case knopNeg:
  10999. case knopPos:
  11000. case knopLogNot:
  11001. case knopEllipsis:
  11002. case knopIncPost:
  11003. case knopDecPost:
  11004. case knopIncPre:
  11005. case knopDecPre:
  11006. case knopTypeof:
  11007. case knopVoid:
  11008. case knopDelete:
  11009. return CreateUniNode(pnode->nop, CopyPnode(pnode->AsParseNodeUni()->pnode1), pnode->ichMin, pnode->ichLim);
  11010. //PTNODE(knopArray , "arr cnst" ,None ,Uni ,fnopUni)
  11011. //PTNODE(knopObject , "obj cnst" ,None ,Uni ,fnopUni)
  11012. case knopArray:
  11013. case knopObject:
  11014. // TODO: need to copy arr
  11015. Assert(false);
  11016. break;
  11017. // Binary operators
  11018. //PTNODE(knopAdd , "+" ,Add ,Bin ,fnopBin)
  11019. //PTNODE(knopSub , "-" ,Sub ,Bin ,fnopBin)
  11020. //PTNODE(knopMul , "*" ,Mul ,Bin ,fnopBin)
  11021. //PTNODE(knopExpo , "**" ,Expo ,Bin ,fnopBin)
  11022. //PTNODE(knopDiv , "/" ,Div ,Bin ,fnopBin)
  11023. //PTNODE(knopMod , "%" ,Mod ,Bin ,fnopBin)
  11024. //PTNODE(knopOr , "|" ,BitOr ,Bin ,fnopBin)
  11025. //PTNODE(knopXor , "^" ,BitXor ,Bin ,fnopBin)
  11026. //PTNODE(knopAnd , "&" ,BitAnd ,Bin ,fnopBin)
  11027. //PTNODE(knopEq , "==" ,EQ ,Bin ,fnopBin|fnopRel)
  11028. //PTNODE(knopNe , "!=" ,NE ,Bin ,fnopBin|fnopRel)
  11029. //PTNODE(knopLt , "<" ,LT ,Bin ,fnopBin|fnopRel)
  11030. //PTNODE(knopLe , "<=" ,LE ,Bin ,fnopBin|fnopRel)
  11031. //PTNODE(knopGe , ">=" ,GE ,Bin ,fnopBin|fnopRel)
  11032. //PTNODE(knopGt , ">" ,GT ,Bin ,fnopBin|fnopRel)
  11033. //PTNODE(knopEqv , "===" ,Eqv ,Bin ,fnopBin|fnopRel)
  11034. //PTNODE(knopIn , "in" ,In ,Bin ,fnopBin|fnopRel)
  11035. //PTNODE(knopInstOf , "instanceof",InstOf ,Bin ,fnopBin|fnopRel)
  11036. //PTNODE(knopNEqv , "!==" ,NEqv ,Bin ,fnopBin|fnopRel)
  11037. //PTNODE(knopComma , "," ,None ,Bin ,fnopBin)
  11038. //PTNODE(knopLogOr , "||" ,None ,Bin ,fnopBin)
  11039. //PTNODE(knopLogAnd , "&&" ,None ,Bin ,fnopBin)
  11040. //PTNODE(knopLsh , "<<" ,Lsh ,Bin ,fnopBin)
  11041. //PTNODE(knopRsh , ">>" ,Rsh ,Bin ,fnopBin)
  11042. //PTNODE(knopRs2 , ">>>" ,Rs2 ,Bin ,fnopBin)
  11043. case knopAdd:
  11044. case knopSub:
  11045. case knopMul:
  11046. case knopExpo:
  11047. case knopDiv:
  11048. case knopMod:
  11049. case knopOr:
  11050. case knopXor:
  11051. case knopAnd:
  11052. case knopEq:
  11053. case knopNe:
  11054. case knopLt:
  11055. case knopLe:
  11056. case knopGe:
  11057. case knopGt:
  11058. case knopEqv:
  11059. case knopIn:
  11060. case knopInstOf:
  11061. case knopNEqv:
  11062. case knopComma:
  11063. case knopLogOr:
  11064. case knopLogAnd:
  11065. case knopLsh:
  11066. case knopRsh:
  11067. case knopRs2:
  11068. //PTNODE(knopAsg , "=" ,None ,Bin ,fnopBin|fnopAsg)
  11069. case knopAsg:
  11070. //PTNODE(knopDot , "." ,None ,Bin ,fnopBin)
  11071. case knopDot:
  11072. //PTNODE(knopAsgAdd , "+=" ,Add ,Bin ,fnopBin|fnopAsg)
  11073. case knopAsgAdd:
  11074. //PTNODE(knopAsgSub , "-=" ,Sub ,Bin ,fnopBin|fnopAsg)
  11075. case knopAsgSub:
  11076. //PTNODE(knopAsgMul , "*=" ,Mul ,Bin ,fnopBin|fnopAsg)
  11077. case knopAsgMul:
  11078. //PTNODE(knopAsgDiv , "/=" ,Div ,Bin ,fnopBin|fnopAsg)
  11079. case knopAsgExpo:
  11080. //PTNODE(knopAsgExpo , "**=" ,Expo ,Bin ,fnopBin|fnopAsg)
  11081. case knopAsgDiv:
  11082. //PTNODE(knopAsgMod , "%=" ,Mod ,Bin ,fnopBin|fnopAsg)
  11083. case knopAsgMod:
  11084. //PTNODE(knopAsgAnd , "&=" ,BitAnd ,Bin ,fnopBin|fnopAsg)
  11085. case knopAsgAnd:
  11086. //PTNODE(knopAsgXor , "^=" ,BitXor ,Bin ,fnopBin|fnopAsg)
  11087. case knopAsgXor:
  11088. //PTNODE(knopAsgOr , "|=" ,BitOr ,Bin ,fnopBin|fnopAsg)
  11089. case knopAsgOr:
  11090. //PTNODE(knopAsgLsh , "<<=" ,Lsh ,Bin ,fnopBin|fnopAsg)
  11091. case knopAsgLsh:
  11092. //PTNODE(knopAsgRsh , ">>=" ,Rsh ,Bin ,fnopBin|fnopAsg)
  11093. case knopAsgRsh:
  11094. //PTNODE(knopAsgRs2 , ">>>=" ,Rs2 ,Bin ,fnopBin|fnopAsg)
  11095. case knopAsgRs2:
  11096. //PTNODE(knopMember , ":" ,None ,Bin ,fnopBin)
  11097. case knopMember:
  11098. case knopMemberShort:
  11099. //PTNODE(knopIndex , "[]" ,None ,Bin ,fnopBin)
  11100. //PTNODE(knopList , "<list>" ,None ,Bin ,fnopNone)
  11101. case knopIndex:
  11102. case knopList:
  11103. return CreateBinNode(pnode->nop, CopyPnode(pnode->AsParseNodeBin()->pnode1),
  11104. CopyPnode(pnode->AsParseNodeBin()->pnode2), pnode->ichMin, pnode->ichLim);
  11105. //PTNODE(knopCall , "()" ,None ,Bin ,fnopBin)
  11106. //PTNODE(knopNew , "new" ,None ,Bin ,fnopBin)
  11107. case knopNew:
  11108. case knopCall:
  11109. return CreateCallNode(pnode->nop, CopyPnode(pnode->AsParseNodeCall()->pnodeTarget),
  11110. CopyPnode(pnode->AsParseNodeCall()->pnodeArgs), pnode->ichMin, pnode->ichLim);
  11111. //PTNODE(knopQmark , "?" ,None ,Tri ,fnopBin)
  11112. case knopQmark:
  11113. return CreateTriNode(pnode->nop, CopyPnode(pnode->AsParseNodeTri()->pnode1),
  11114. CopyPnode(pnode->AsParseNodeTri()->pnode2), CopyPnode(pnode->AsParseNodeTri()->pnode3),
  11115. pnode->ichMin, pnode->ichLim);
  11116. // General nodes.
  11117. //PTNODE(knopVarDecl , "varDcl" ,None ,Var ,fnopNone)
  11118. case knopVarDecl: {
  11119. ParseNodeVar* copyNode = Anew(&m_nodeAllocator, ParseNodeVar, knopVarDecl, pnode->ichMin, pnode->ichLim, nullptr);
  11120. copyNode->pnodeInit = CopyPnode(pnode->AsParseNodeVar()->pnodeInit);
  11121. copyNode->sym = pnode->AsParseNodeVar()->sym;
  11122. // TODO: mult-decl
  11123. Assert(pnode->AsParseNodeVar()->pnodeNext == NULL);
  11124. copyNode->pnodeNext = NULL;
  11125. return copyNode;
  11126. }
  11127. //PTNODE(knopFncDecl , "fncDcl" ,None ,Fnc ,fnopLeaf)
  11128. //PTNODE(knopProg , "program" ,None ,Fnc ,fnopNone)
  11129. case knopFncDecl:
  11130. case knopProg:
  11131. Assert(false);
  11132. break;
  11133. //PTNODE(knopEndCode , "<endcode>" ,None ,None ,fnopNone)
  11134. case knopEndCode:
  11135. break;
  11136. //PTNODE(knopDebugger , "debugger" ,None ,None ,fnopNone)
  11137. case knopDebugger:
  11138. break;
  11139. //PTNODE(knopFor , "for" ,None ,For ,fnopBreak|fnopContinue)
  11140. case knopFor: {
  11141. ParseNode* copyNode = CreateNodeForOpT<knopFor>(pnode->ichMin, pnode->ichLim);
  11142. copyNode->AsParseNodeFor()->pnodeInverted = NULL;
  11143. copyNode->AsParseNodeFor()->pnodeInit = CopyPnode(pnode->AsParseNodeFor()->pnodeInit);
  11144. copyNode->AsParseNodeFor()->pnodeCond = CopyPnode(pnode->AsParseNodeFor()->pnodeCond);
  11145. copyNode->AsParseNodeFor()->pnodeIncr = CopyPnode(pnode->AsParseNodeFor()->pnodeIncr);
  11146. copyNode->AsParseNodeFor()->pnodeBody = CopyPnode(pnode->AsParseNodeFor()->pnodeBody);
  11147. return copyNode;
  11148. }
  11149. //PTNODE(knopIf , "if" ,None ,If ,fnopNone)
  11150. case knopIf:
  11151. Assert(false);
  11152. break;
  11153. //PTNODE(knopWhile , "while" ,None ,While,fnopBreak|fnopContinue)
  11154. case knopWhile:
  11155. Assert(false);
  11156. break;
  11157. //PTNODE(knopDoWhile , "do-while" ,None ,While,fnopBreak|fnopContinue)
  11158. case knopDoWhile:
  11159. Assert(false);
  11160. break;
  11161. //PTNODE(knopForIn , "for in" ,None ,ForIn,fnopBreak|fnopContinue|fnopCleanup)
  11162. case knopForIn:
  11163. Assert(false);
  11164. break;
  11165. case knopForOf:
  11166. Assert(false);
  11167. break;
  11168. case knopForAwaitOf:
  11169. Assert(false);
  11170. break;
  11171. //PTNODE(knopReturn , "return" ,None ,Uni ,fnopNone)
  11172. case knopReturn: {
  11173. ParseNode* copyNode = CreateNodeForOpT<knopReturn>(pnode->ichMin, pnode->ichLim);
  11174. copyNode->AsParseNodeReturn()->pnodeExpr = CopyPnode(pnode->AsParseNodeReturn()->pnodeExpr);
  11175. return copyNode;
  11176. }
  11177. //PTNODE(knopBlock , "{}" ,None ,Block,fnopNone)
  11178. case knopBlock: {
  11179. ParseNodeBlock* copyNode = CreateBlockNode(pnode->ichMin, pnode->ichLim, pnode->AsParseNodeBlock()->blockType);
  11180. if (pnode->grfpn & PNodeFlags::fpnSyntheticNode) {
  11181. // fpnSyntheticNode is sometimes set on PnodeBlockType::Regular blocks which
  11182. // CreateBlockNode() will not automatically set for us, so set it here if it's
  11183. // specified on the source node.
  11184. copyNode->grfpn |= PNodeFlags::fpnSyntheticNode;
  11185. }
  11186. copyNode->pnodeStmt = CopyPnode(pnode->AsParseNodeBlock()->pnodeStmt);
  11187. return copyNode;
  11188. }
  11189. //PTNODE(knopWith , "with" ,None ,With ,fnopCleanup)
  11190. case knopWith:
  11191. Assert(false);
  11192. break;
  11193. //PTNODE(knopBreak , "break" ,None ,Jump ,fnopNone)
  11194. case knopBreak:
  11195. Assert(false);
  11196. break;
  11197. //PTNODE(knopContinue , "continue" ,None ,Jump ,fnopNone)
  11198. case knopContinue:
  11199. Assert(false);
  11200. break;
  11201. //PTNODE(knopSwitch , "switch" ,None ,Switch,fnopBreak)
  11202. case knopSwitch:
  11203. Assert(false);
  11204. break;
  11205. //PTNODE(knopCase , "case" ,None ,Case ,fnopNone)
  11206. case knopCase:
  11207. Assert(false);
  11208. break;
  11209. //PTNODE(knopTryFinally,"try-finally",None,TryFinally,fnopCleanup)
  11210. case knopTryFinally:
  11211. Assert(false);
  11212. break;
  11213. case knopFinally:
  11214. Assert(false);
  11215. break;
  11216. //PTNODE(knopCatch , "catch" ,None ,Catch,fnopNone)
  11217. case knopCatch:
  11218. Assert(false);
  11219. break;
  11220. //PTNODE(knopTryCatch , "try-catch" ,None ,TryCatch ,fnopCleanup)
  11221. case knopTryCatch:
  11222. Assert(false);
  11223. break;
  11224. //PTNODE(knopTry , "try" ,None ,Try ,fnopCleanup)
  11225. case knopTry:
  11226. Assert(false);
  11227. break;
  11228. //PTNODE(knopThrow , "throw" ,None ,Uni ,fnopNone)
  11229. case knopThrow:
  11230. Assert(false);
  11231. break;
  11232. default:
  11233. Assert(false);
  11234. break;
  11235. }
  11236. return NULL;
  11237. }
  11238. // Returns true when str is string for Nan, Infinity or -Infinity.
  11239. // Does not check for double number value being in NaN/Infinity range.
  11240. // static
  11241. template<bool CheckForNegativeInfinity>
  11242. inline bool Parser::IsNaNOrInfinityLiteral(LPCOLESTR str)
  11243. {
  11244. // Note: wcscmp crashes when one of the parameters is NULL.
  11245. return str &&
  11246. (wcscmp(_u("NaN"), str) == 0 ||
  11247. wcscmp(_u("Infinity"), str) == 0 ||
  11248. (CheckForNegativeInfinity && wcscmp(_u("-Infinity"), str) == 0));
  11249. }
  11250. template <bool buildAST>
  11251. IdentPtr Parser::ParseSuper(bool fAllowCall)
  11252. {
  11253. ParseNodeFnc * currentNodeFunc = GetCurrentFunctionNode();
  11254. ParseNodeFnc * currentNonLambdaFunc = GetCurrentNonLambdaFunctionNode();
  11255. IdentPtr superPid = nullptr;
  11256. switch (m_token.tk)
  11257. {
  11258. case tkDot: // super.prop
  11259. case tkLBrack: // super[foo]
  11260. superPid = wellKnownPropertyPids._super;
  11261. break;
  11262. case tkLParen: // super(args)
  11263. superPid = wellKnownPropertyPids._superConstructor;
  11264. break;
  11265. default:
  11266. Error(ERRInvalidSuper);
  11267. break;
  11268. }
  11269. currentNodeFunc->SetHasSuperReference(TRUE);
  11270. CHAKRATEL_LANGSTATS_INC_LANGFEATURECOUNT(ES6, Super, m_scriptContext);
  11271. // If we are defer parsing, we can skip verifying that the super reference is valid.
  11272. // If it wasn't the parser would have thrown during upfront parsing and we wouldn't be defer parsing the function.
  11273. if (m_parseType == ParseType_Deferred)
  11274. {
  11275. return superPid;
  11276. }
  11277. if (!fAllowCall && (m_token.tk == tkLParen))
  11278. {
  11279. Error(ERRInvalidSuper); // new super() is not allowed
  11280. }
  11281. else if ((currentNodeFunc->IsConstructor() && currentNodeFunc->superRestrictionState == SuperRestrictionState::CallAndPropertyAllowed)
  11282. || (currentNonLambdaFunc != nullptr && currentNonLambdaFunc->superRestrictionState == SuperRestrictionState::CallAndPropertyAllowed))
  11283. {
  11284. // Any super access is good within a class constructor
  11285. }
  11286. else if ((this->m_grfscr & fscrEval) == fscrEval || (currentNonLambdaFunc != nullptr && currentNonLambdaFunc->superRestrictionState == SuperRestrictionState::PropertyAllowed))
  11287. {
  11288. // Currently for eval cases during compile time we use propertyallowed and throw during runtime for error cases
  11289. if (m_token.tk == tkLParen)
  11290. {
  11291. if ((this->m_grfscr & fscrEval) == fscrNil)
  11292. {
  11293. // Cannot call super within a class member
  11294. Error(ERRInvalidSuper);
  11295. }
  11296. else
  11297. {
  11298. Js::JavascriptFunction * caller = nullptr;
  11299. if (Js::JavascriptStackWalker::GetCaller(&caller, m_scriptContext))
  11300. {
  11301. Js::FunctionBody * callerBody = caller->GetFunctionBody();
  11302. Assert(callerBody);
  11303. if (!callerBody->GetFunctionInfo()->GetAllowDirectSuper())
  11304. {
  11305. Error(ERRInvalidSuper);
  11306. }
  11307. }
  11308. }
  11309. }
  11310. }
  11311. else
  11312. {
  11313. // Anything else is an error
  11314. Error(ERRInvalidSuper);
  11315. }
  11316. return superPid;
  11317. }
  11318. void Parser::AppendToList(ParseNodePtr *node, ParseNodePtr nodeToAppend)
  11319. {
  11320. Assert(nodeToAppend);
  11321. ParseNodePtr* lastPtr = node;
  11322. while ((*lastPtr) && (*lastPtr)->nop == knopList)
  11323. {
  11324. lastPtr = &(*lastPtr)->AsParseNodeBin()->pnode2;
  11325. }
  11326. auto last = (*lastPtr);
  11327. if (last)
  11328. {
  11329. *lastPtr = CreateBinNode(knopList, last, nodeToAppend, last->ichMin, nodeToAppend->ichLim);
  11330. }
  11331. else
  11332. {
  11333. *lastPtr = nodeToAppend;
  11334. }
  11335. }
  11336. ParseNodePtr Parser::ConvertArrayToArrayPattern(ParseNodePtr pnode)
  11337. {
  11338. Assert(pnode->nop == knopArray);
  11339. pnode->nop = knopArrayPattern;
  11340. ForEachItemRefInList(&pnode->AsParseNodeArrLit()->pnode1, [&](ParseNodePtr *itemRef) {
  11341. ParseNodePtr item = *itemRef;
  11342. if (item->nop == knopEllipsis)
  11343. {
  11344. itemRef = &item->AsParseNodeUni()->pnode1;
  11345. item = *itemRef;
  11346. if (!(item->nop == knopName
  11347. || item->nop == knopDot
  11348. || item->nop == knopIndex
  11349. || item->nop == knopArray
  11350. || item->nop == knopObject))
  11351. {
  11352. Error(ERRInvalidAssignmentTarget);
  11353. }
  11354. }
  11355. else if (item->nop == knopAsg)
  11356. {
  11357. itemRef = &item->AsParseNodeBin()->pnode1;
  11358. item = *itemRef;
  11359. }
  11360. if (item->nop == knopArray)
  11361. {
  11362. ConvertArrayToArrayPattern(item);
  11363. }
  11364. else if (item->nop == knopObject)
  11365. {
  11366. *itemRef = ConvertObjectToObjectPattern(item);
  11367. }
  11368. });
  11369. return pnode;
  11370. }
  11371. ParseNodeUni * Parser::ConvertObjectToObjectPattern(ParseNodePtr pnodeMemberList)
  11372. {
  11373. charcount_t ichMin = this->GetScanner()->IchMinTok();
  11374. charcount_t ichLim = this->GetScanner()->IchLimTok();
  11375. if (pnodeMemberList != nullptr && pnodeMemberList->nop == knopObject)
  11376. {
  11377. ichMin = pnodeMemberList->ichMin;
  11378. ichLim = pnodeMemberList->ichLim;
  11379. pnodeMemberList = pnodeMemberList->AsParseNodeUni()->pnode1;
  11380. }
  11381. ParseNodeObjLit * objectPatternNode = CreateObjectPatternNode(pnodeMemberList, ichMin, ichLim, true/*convertToPattern*/);
  11382. return objectPatternNode;
  11383. }
  11384. ParseNodePtr Parser::GetRightSideNodeFromPattern(ParseNodePtr pnode)
  11385. {
  11386. Assert(pnode != nullptr);
  11387. ParseNodePtr rightNode = nullptr;
  11388. OpCode op = pnode->nop;
  11389. if (op == knopObject)
  11390. {
  11391. rightNode = ConvertObjectToObjectPattern(pnode);
  11392. }
  11393. else if (op == knopArray)
  11394. {
  11395. rightNode = ConvertArrayToArrayPattern(pnode);
  11396. }
  11397. else
  11398. {
  11399. rightNode = pnode;
  11400. if (op == knopAsg)
  11401. {
  11402. TrackAssignment<true>(pnode->AsParseNodeBin()->pnode1, nullptr);
  11403. }
  11404. }
  11405. return rightNode;
  11406. }
  11407. ParseNodePtr Parser::ConvertMemberToMemberPattern(ParseNodePtr pnodeMember)
  11408. {
  11409. if (pnodeMember->nop == knopObjectPatternMember || pnodeMember->nop == knopEllipsis)
  11410. {
  11411. return pnodeMember;
  11412. }
  11413. Assert(pnodeMember->nop == knopMember || pnodeMember->nop == knopMemberShort);
  11414. ParseNodePtr rightNode = GetRightSideNodeFromPattern(pnodeMember->AsParseNodeBin()->pnode2);
  11415. ParseNodePtr resultNode = CreateBinNode(knopObjectPatternMember, pnodeMember->AsParseNodeBin()->pnode1, rightNode);
  11416. resultNode->ichMin = pnodeMember->ichMin;
  11417. resultNode->ichLim = pnodeMember->ichLim;
  11418. return resultNode;
  11419. }
  11420. ParseNodePtr Parser::ConvertToPattern(ParseNodePtr pnode)
  11421. {
  11422. if (pnode != nullptr)
  11423. {
  11424. if (pnode->nop == knopArray)
  11425. {
  11426. ConvertArrayToArrayPattern(pnode);
  11427. }
  11428. else if (pnode->nop == knopObject)
  11429. {
  11430. pnode = ConvertObjectToObjectPattern(pnode);
  11431. }
  11432. }
  11433. return pnode;
  11434. }
  11435. // This essentially be called for verifying the structure of the current tree with satisfying the destructuring grammar.
  11436. void Parser::ParseDestructuredLiteralWithScopeSave(tokens declarationType,
  11437. bool isDecl,
  11438. bool topLevel,
  11439. DestructuringInitializerContext initializerContext/* = DIC_None*/,
  11440. bool allowIn /*= true*/)
  11441. {
  11442. // We are going to parse the text again to validate the current grammar as Destructuring. Saving some scopes and
  11443. // AST related information before the validation parsing and later they will be restored.
  11444. ParseNodeFnc * pnodeFncSave = m_currentNodeFunc;
  11445. ParseNodeFnc * pnodeDeferredFncSave = m_currentNodeDeferredFunc;
  11446. if (m_currentNodeDeferredFunc == nullptr)
  11447. {
  11448. m_currentNodeDeferredFunc = m_currentNodeFunc;
  11449. }
  11450. int32 *pAstSizeSave = m_pCurrentAstSize;
  11451. uint *pNestedCountSave = m_pnestedCount;
  11452. ParseNodePtr *ppnodeScopeSave = m_ppnodeScope;
  11453. ParseNodePtr *ppnodeExprScopeSave = m_ppnodeExprScope;
  11454. ParseNodePtr newTempScope = nullptr;
  11455. m_ppnodeScope = &newTempScope;
  11456. int32 newTempAstSize = 0;
  11457. m_pCurrentAstSize = &newTempAstSize;
  11458. uint newTempNestedCount = 0;
  11459. m_pnestedCount = &newTempNestedCount;
  11460. m_ppnodeExprScope = nullptr;
  11461. charcount_t funcInArraySave = m_funcInArray;
  11462. uint funcInArrayDepthSave = m_funcInArrayDepth;
  11463. // we need to reset this as we are going to parse the grammar again.
  11464. m_hasDeferredShorthandInitError = false;
  11465. ParseDestructuredLiteral<false>(declarationType, isDecl, topLevel, initializerContext, allowIn);
  11466. m_currentNodeFunc = pnodeFncSave;
  11467. m_currentNodeDeferredFunc = pnodeDeferredFncSave;
  11468. m_pCurrentAstSize = pAstSizeSave;
  11469. m_pnestedCount = pNestedCountSave;
  11470. m_ppnodeScope = ppnodeScopeSave;
  11471. m_ppnodeExprScope = ppnodeExprScopeSave;
  11472. m_funcInArray = funcInArraySave;
  11473. m_funcInArrayDepth = funcInArrayDepthSave;
  11474. }
  11475. template <bool buildAST>
  11476. ParseNodePtr Parser::ParseDestructuredLiteral(tokens declarationType,
  11477. bool isDecl,
  11478. bool topLevel/* = true*/,
  11479. DestructuringInitializerContext initializerContext/* = DIC_None*/,
  11480. bool allowIn/* = true*/,
  11481. BOOL *forInOfOkay/* = nullptr*/,
  11482. BOOL *nativeForOkay/* = nullptr*/)
  11483. {
  11484. ParseNodeUni * pnode = nullptr;
  11485. Assert(IsPossiblePatternStart());
  11486. PROBE_STACK_NO_DISPOSE(m_scriptContext, Js::Constants::MinStackDefault);
  11487. if (m_token.tk == tkLCurly)
  11488. {
  11489. pnode = ParseDestructuredObjectLiteral<buildAST>(declarationType, isDecl, topLevel);
  11490. }
  11491. else
  11492. {
  11493. pnode = ParseDestructuredArrayLiteral<buildAST>(declarationType, isDecl, topLevel);
  11494. }
  11495. return ParseDestructuredInitializer<buildAST>(pnode, isDecl, topLevel, initializerContext, allowIn, forInOfOkay, nativeForOkay);
  11496. }
  11497. template <bool buildAST>
  11498. ParseNodePtr Parser::ParseDestructuredInitializer(ParseNodeUni * lhsNode,
  11499. bool isDecl,
  11500. bool topLevel,
  11501. DestructuringInitializerContext initializerContext,
  11502. bool allowIn,
  11503. BOOL *forInOfOkay,
  11504. BOOL *nativeForOkay)
  11505. {
  11506. this->GetScanner()->Scan();
  11507. if (topLevel && nativeForOkay == nullptr)
  11508. {
  11509. if (initializerContext != DIC_ForceErrorOnInitializer && m_token.tk != tkAsg)
  11510. {
  11511. // e.g. var {x};
  11512. Error(ERRDestructInit);
  11513. }
  11514. else if (initializerContext == DIC_ForceErrorOnInitializer && m_token.tk == tkAsg)
  11515. {
  11516. // e.g. catch([x] = [0])
  11517. Error(ERRDestructNotInit);
  11518. }
  11519. }
  11520. if (m_token.tk != tkAsg || initializerContext == DIC_ShouldNotParseInitializer)
  11521. {
  11522. if (topLevel && nativeForOkay != nullptr)
  11523. {
  11524. // Native loop should have destructuring initializer
  11525. *nativeForOkay = FALSE;
  11526. }
  11527. return lhsNode;
  11528. }
  11529. if (forInOfOkay)
  11530. {
  11531. *forInOfOkay = FALSE;
  11532. }
  11533. this->GetScanner()->Scan();
  11534. bool alreadyHasInitError = m_hasDeferredShorthandInitError;
  11535. ParseNodePtr pnodeDefault = ParseExpr<buildAST>(koplCma, nullptr, allowIn);
  11536. if (m_hasDeferredShorthandInitError && !alreadyHasInitError)
  11537. {
  11538. Error(ERRnoColon);
  11539. }
  11540. ParseNodeBin * pnodeDestructAsg = nullptr;
  11541. if (buildAST)
  11542. {
  11543. Assert(lhsNode != nullptr);
  11544. pnodeDestructAsg = CreateBinNode(knopAsg, lhsNode, pnodeDefault, lhsNode->ichMin, pnodeDefault->ichLim);
  11545. }
  11546. return pnodeDestructAsg;
  11547. }
  11548. template <bool buildAST>
  11549. ParseNodeUni * Parser::ParseDestructuredObjectLiteral(tokens declarationType, bool isDecl, bool topLevel/* = true*/)
  11550. {
  11551. Assert(m_token.tk == tkLCurly);
  11552. charcount_t ichMin = this->GetScanner()->IchMinTok();
  11553. this->GetScanner()->Scan();
  11554. if (!isDecl)
  11555. {
  11556. declarationType = tkLCurly;
  11557. }
  11558. ParseNodePtr pnodeMemberList = ParseMemberList<buildAST>(nullptr/*pNameHint*/, nullptr/*pHintLength*/, declarationType);
  11559. charcount_t ichLim = this->GetScanner()->IchLimTok();
  11560. ParseNodeObjLit * objectPatternNode = buildAST ? CreateObjectPatternNode(pnodeMemberList, ichMin, ichLim) : nullptr;
  11561. Assert(m_token.tk == tkRCurly);
  11562. return objectPatternNode;
  11563. }
  11564. template <bool buildAST>
  11565. ParseNodePtr Parser::ParseDestructuredVarDecl(tokens declarationType, bool isDecl, bool *hasSeenRest, bool topLevel/* = true*/, bool allowEmptyExpression/* = true*/, bool isObjectPattern/* =false*/)
  11566. {
  11567. ParseNodePtr pnodeElem = nullptr;
  11568. int parenCount = 0;
  11569. bool seenRest = false;
  11570. IdentToken token;
  11571. // Save the Block ID prior to the increments, so we can restore it back.
  11572. int originalCurrentBlockId = GetCurrentBlock()->blockId;
  11573. // Eat the left parentheses only when its not a declaration. This will make sure we throw syntax errors early.
  11574. if (!isDecl)
  11575. {
  11576. while (m_token.tk == tkLParen)
  11577. {
  11578. this->GetScanner()->Scan();
  11579. ++parenCount;
  11580. // Match the block increment we do upon entering parenthetical expressions
  11581. // so that the block ID's will match on reparsing of parameters.
  11582. GetCurrentBlock()->blockId = m_nextBlockId++;
  11583. }
  11584. }
  11585. if (m_token.tk == tkEllipsis)
  11586. {
  11587. // As per ES 2015 : Rest can have left-hand-side-expression when on assignment expression, but under declaration only binding identifier is allowed
  11588. // But spec is going to change for this one to allow LHS-expression both on expression and declaration - so making that happen early.
  11589. seenRest = true;
  11590. this->GetScanner()->Scan();
  11591. // Eat the left parentheses only when its not a declaration. This will make sure we throw syntax errors early.
  11592. if (!isDecl)
  11593. {
  11594. while (m_token.tk == tkLParen)
  11595. {
  11596. this->GetScanner()->Scan();
  11597. ++parenCount;
  11598. // Match the block increment we do upon entering parenthetical expressions
  11599. // so that the block ID's will match on reparsing of parameters.
  11600. GetCurrentBlock()->blockId = m_nextBlockId++;
  11601. }
  11602. }
  11603. if (m_token.tk != tkID && m_token.tk != tkTHIS && m_token.tk != tkSUPER)
  11604. {
  11605. bool nestedDestructuring = m_token.tk == tkLCurly || m_token.tk == tkLBrack;
  11606. if ((isObjectPattern && nestedDestructuring) || (!isObjectPattern && !nestedDestructuring))
  11607. {
  11608. if (isDecl)
  11609. {
  11610. Error(ERRnoIdent);
  11611. }
  11612. else
  11613. {
  11614. Error(ERRInvalidAssignmentTarget);
  11615. }
  11616. }
  11617. }
  11618. }
  11619. if (IsPossiblePatternStart())
  11620. {
  11621. // For the possible pattern start we do not allow the parens before
  11622. if (parenCount != 0)
  11623. {
  11624. Error(ERRDestructIDRef);
  11625. }
  11626. // Go recursively
  11627. pnodeElem = ParseDestructuredLiteral<buildAST>(declarationType, isDecl, false /*topLevel*/, seenRest ? DIC_ShouldNotParseInitializer : DIC_None);
  11628. if (!isDecl)
  11629. {
  11630. BOOL fCanAssign;
  11631. // Look for postfix operator
  11632. pnodeElem = ParsePostfixOperators<buildAST>(pnodeElem, TRUE, FALSE, FALSE, TRUE, &fCanAssign, &token);
  11633. }
  11634. }
  11635. else if (m_token.tk == tkSUPER || m_token.tk == tkID || m_token.tk == tkTHIS)
  11636. {
  11637. if (isDecl)
  11638. {
  11639. charcount_t ichMin = this->GetScanner()->IchMinTok();
  11640. pnodeElem = ParseVariableDeclaration<buildAST>(declarationType, ichMin
  11641. ,/* fAllowIn */false, /* pfForInOk */nullptr, /* singleDefOnly */true, /* allowInit */!seenRest, false /*topLevelParse*/);
  11642. }
  11643. else
  11644. {
  11645. BOOL fCanAssign;
  11646. // We aren't declaring anything, so scan the ID reference manually.
  11647. pnodeElem = ParseTerm<buildAST>(/* fAllowCall */ m_token.tk != tkSUPER, nullptr /*pNameHint*/, nullptr /*pHintLength*/, nullptr /*pShortNameOffset*/, &token, false,
  11648. FALSE, &fCanAssign);
  11649. // In this destructuring case we can force error here as we cannot assign.
  11650. if (!fCanAssign)
  11651. {
  11652. Error(ERRInvalidAssignmentTarget);
  11653. }
  11654. if (buildAST)
  11655. {
  11656. TrackAssignment<buildAST>(pnodeElem, nullptr);
  11657. }
  11658. if (buildAST)
  11659. {
  11660. if (IsStrictMode() && pnodeElem != nullptr && pnodeElem->nop == knopName)
  11661. {
  11662. CheckStrictModeEvalArgumentsUsage(pnodeElem->AsParseNodeName()->pid);
  11663. }
  11664. }
  11665. else
  11666. {
  11667. if (IsStrictMode() && token.tk == tkID)
  11668. {
  11669. CheckStrictModeEvalArgumentsUsage(token.pid);
  11670. }
  11671. }
  11672. }
  11673. }
  11674. else if (!((m_token.tk == tkComma || m_token.tk == tkRBrack || m_token.tk == tkRCurly) && allowEmptyExpression))
  11675. {
  11676. if (m_token.IsOperator())
  11677. {
  11678. Error(ERRDestructNoOper);
  11679. }
  11680. Error(ERRDestructIDRef);
  11681. }
  11682. // Swallow RParens before a default expression, if any.
  11683. // 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.
  11684. if (!isDecl)
  11685. {
  11686. while (m_token.tk == tkRParen)
  11687. {
  11688. this->GetScanner()->Scan();
  11689. --parenCount;
  11690. }
  11691. // Restore the Block ID of the current block after the parsing of destructured variable declarations and initializers.
  11692. GetCurrentBlock()->blockId = originalCurrentBlockId;
  11693. }
  11694. if (parenCount != 0)
  11695. {
  11696. Error(ERRnoRparen);
  11697. }
  11698. if (hasSeenRest != nullptr)
  11699. {
  11700. *hasSeenRest = seenRest;
  11701. }
  11702. if (m_token.tk == tkAsg)
  11703. {
  11704. // Parse the initializer.
  11705. if (seenRest)
  11706. {
  11707. Error(ERRRestWithDefault);
  11708. }
  11709. this->GetScanner()->Scan();
  11710. bool alreadyHasInitError = m_hasDeferredShorthandInitError;
  11711. ParseNodePtr pnodeInit = ParseExpr<buildAST>(koplCma);
  11712. if (m_hasDeferredShorthandInitError && !alreadyHasInitError)
  11713. {
  11714. Error(ERRnoColon);
  11715. }
  11716. if (buildAST)
  11717. {
  11718. pnodeElem = CreateBinNode(knopAsg, pnodeElem, pnodeInit);
  11719. }
  11720. }
  11721. if (buildAST && seenRest)
  11722. {
  11723. ParseNodePtr pnodeRest = CreateUniNode(knopEllipsis, pnodeElem);
  11724. pnodeElem = pnodeRest;
  11725. }
  11726. if (!(m_token.tk == tkComma || m_token.tk == tkRBrack || m_token.tk == tkRCurly))
  11727. {
  11728. if (m_token.IsOperator())
  11729. {
  11730. Error(ERRDestructNoOper);
  11731. }
  11732. Error(ERRsyntax);
  11733. }
  11734. if (!buildAST && token.tk == tkID)
  11735. {
  11736. TrackAssignment<buildAST>(nullptr, &token);
  11737. }
  11738. return pnodeElem;
  11739. }
  11740. template <bool buildAST>
  11741. ParseNodeUni * Parser::ParseDestructuredArrayLiteral(tokens declarationType, bool isDecl, bool topLevel)
  11742. {
  11743. Assert(m_token.tk == tkLBrack);
  11744. charcount_t ichMin = this->GetScanner()->IchMinTok();
  11745. this->GetScanner()->Scan();
  11746. ParseNodeArrLit * pnodeDestructArr = nullptr;
  11747. ParseNodePtr pnodeList = nullptr;
  11748. ParseNodePtr *lastNodeRef = nullptr;
  11749. uint count = 0;
  11750. bool hasMissingValues = false;
  11751. bool seenRest = false;
  11752. if (m_token.tk != tkRBrack)
  11753. {
  11754. while (true)
  11755. {
  11756. ParseNodePtr pnodeElem = ParseDestructuredVarDecl<buildAST>(declarationType, isDecl, &seenRest, topLevel);
  11757. if (buildAST)
  11758. {
  11759. if (pnodeElem == nullptr && buildAST)
  11760. {
  11761. pnodeElem = CreateNodeForOpT<knopEmpty>();
  11762. hasMissingValues = true;
  11763. }
  11764. AddToNodeListEscapedUse(&pnodeList, &lastNodeRef, pnodeElem);
  11765. }
  11766. count++;
  11767. if (m_token.tk == tkRBrack)
  11768. {
  11769. break;
  11770. }
  11771. if (m_token.tk != tkComma)
  11772. {
  11773. Error(ERRDestructNoOper);
  11774. }
  11775. if (seenRest) // Rest must be in the last position.
  11776. {
  11777. Error(ERRDestructRestLast);
  11778. }
  11779. this->GetScanner()->Scan();
  11780. // break if we have the trailing comma as well, eg. [a,]
  11781. if (m_token.tk == tkRBrack)
  11782. {
  11783. break;
  11784. }
  11785. }
  11786. }
  11787. if (buildAST)
  11788. {
  11789. pnodeDestructArr = CreateNodeForOpT<knopArrayPattern>(ichMin);
  11790. pnodeDestructArr->pnode1 = pnodeList;
  11791. pnodeDestructArr->arrayOfTaggedInts = false;
  11792. pnodeDestructArr->arrayOfInts = false;
  11793. pnodeDestructArr->arrayOfNumbers = false;
  11794. pnodeDestructArr->hasMissingValues = hasMissingValues;
  11795. pnodeDestructArr->count = count;
  11796. pnodeDestructArr->spreadCount = seenRest ? 1 : 0;
  11797. if (pnodeDestructArr->pnode1)
  11798. {
  11799. this->CheckArguments(pnodeDestructArr->pnode1);
  11800. }
  11801. }
  11802. return pnodeDestructArr;
  11803. }
  11804. void Parser::CaptureContext(ParseContext *parseContext) const
  11805. {
  11806. parseContext->pszSrc = this->GetScanner()->PchBase();
  11807. parseContext->length = this->m_originalLength;
  11808. parseContext->characterOffset = this->GetScanner()->IchMinTok();
  11809. parseContext->offset = parseContext->characterOffset + this->GetScanner()->m_cMultiUnits;
  11810. parseContext->grfscr = this->m_grfscr;
  11811. parseContext->lineNumber = this->GetScanner()->LineCur();
  11812. parseContext->pnodeProg = this->m_currentNodeProg;
  11813. parseContext->isUtf8 = this->GetScanner()->IsUtf8();
  11814. parseContext->strictMode = this->IsStrictMode();
  11815. parseContext->sourceContextInfo = this->m_sourceContextInfo;
  11816. parseContext->currentBlockInfo = this->m_currentBlockInfo;
  11817. parseContext->nextBlockId = this->m_nextBlockId;
  11818. }
  11819. void Parser::RestoreContext(ParseContext *const parseContext)
  11820. {
  11821. m_sourceContextInfo = parseContext->sourceContextInfo;
  11822. m_currentBlockInfo = parseContext->currentBlockInfo;
  11823. m_nextBlockId = parseContext->nextBlockId;
  11824. m_grfscr = parseContext->grfscr;
  11825. m_length = parseContext->length;
  11826. this->GetScanner()->SetText(parseContext->pszSrc, parseContext->offset, parseContext->length, parseContext->characterOffset, parseContext->isUtf8, parseContext->grfscr, parseContext->lineNumber);
  11827. m_currentNodeProg = parseContext->pnodeProg;
  11828. m_fUseStrictMode = parseContext->strictMode;
  11829. }
  11830. class ByteCodeGenerator;
  11831. #if DBG_DUMP
  11832. #define INDENT_SIZE 2
  11833. void PrintPnodeListWIndent(ParseNode *pnode, int indentAmt);
  11834. void PrintFormalsWIndent(ParseNode *pnode, int indentAmt);
  11835. void Indent(int indentAmt) {
  11836. for (int i = 0; i < indentAmt; i++) {
  11837. Output::Print(_u(" "));
  11838. }
  11839. }
  11840. void PrintBlockType(PnodeBlockType type)
  11841. {
  11842. switch (type)
  11843. {
  11844. case Global:
  11845. Output::Print(_u("(Global)"));
  11846. break;
  11847. case Function:
  11848. Output::Print(_u("(Function)"));
  11849. break;
  11850. case Regular:
  11851. Output::Print(_u("(Regular)"));
  11852. break;
  11853. case Parameter:
  11854. Output::Print(_u("(Parameter)"));
  11855. break;
  11856. default:
  11857. Output::Print(_u("(unknown blocktype)"));
  11858. break;
  11859. }
  11860. }
  11861. void PrintScopesWIndent(ParseNode *pnode, int indentAmt) {
  11862. ParseNode *scope = nullptr;
  11863. bool firstOnly = false;
  11864. switch (pnode->nop)
  11865. {
  11866. case knopProg:
  11867. case knopFncDecl: scope = pnode->AsParseNodeFnc()->pnodeScopes; break;
  11868. case knopBlock: scope = pnode->AsParseNodeBlock()->pnodeScopes; break;
  11869. case knopCatch: scope = pnode->AsParseNodeCatch()->pnodeScopes; break;
  11870. case knopWith: scope = pnode->AsParseNodeWith()->pnodeScopes; break;
  11871. case knopSwitch: scope = pnode->AsParseNodeSwitch()->pnodeBlock; firstOnly = true; break;
  11872. case knopFor: scope = pnode->AsParseNodeFor()->pnodeBlock; firstOnly = true; break;
  11873. case knopForIn: scope = pnode->AsParseNodeForInOrForOf()->pnodeBlock; firstOnly = true; break;
  11874. case knopForOf: scope = pnode->AsParseNodeForInOrForOf()->pnodeBlock; firstOnly = true; break;
  11875. case knopForAwaitOf: scope = pnode->AsParseNodeForInOrForOf()->pnodeBlock; firstOnly = true; break;
  11876. }
  11877. if (scope) {
  11878. Output::Print(_u("[%4d, %4d): "), scope->ichMin, scope->ichLim);
  11879. Indent(indentAmt);
  11880. Output::Print(_u("Scopes: "));
  11881. ParseNode *next = nullptr;
  11882. ParseNode *syntheticBlock = nullptr;
  11883. while (scope) {
  11884. switch (scope->nop) {
  11885. case knopFncDecl: Output::Print(_u("knopFncDecl")); next = scope->AsParseNodeFnc()->pnodeNext; break;
  11886. case knopBlock: Output::Print(_u("knopBlock")); PrintBlockType(scope->AsParseNodeBlock()->blockType); next = scope->AsParseNodeBlock()->pnodeNext; break;
  11887. case knopCatch: Output::Print(_u("knopCatch")); next = scope->AsParseNodeCatch()->pnodeNext; break;
  11888. case knopWith: Output::Print(_u("knopWith")); next = scope->AsParseNodeWith()->pnodeNext; break;
  11889. default: Output::Print(_u("unknown")); break;
  11890. }
  11891. if (firstOnly) {
  11892. next = nullptr;
  11893. syntheticBlock = scope;
  11894. }
  11895. if (scope->grfpn & fpnSyntheticNode) {
  11896. Output::Print(_u(" synthetic"));
  11897. if (scope->nop == knopBlock)
  11898. syntheticBlock = scope;
  11899. }
  11900. Output::Print(_u(" (%d-%d)"), scope->ichMin, scope->ichLim);
  11901. if (next) Output::Print(_u(", "));
  11902. scope = next;
  11903. }
  11904. Output::Print(_u("\n"));
  11905. if (syntheticBlock || firstOnly) {
  11906. PrintScopesWIndent(syntheticBlock, indentAmt + INDENT_SIZE);
  11907. }
  11908. }
  11909. }
  11910. void PrintPnodeWIndent(ParseNode *pnode, int indentAmt) {
  11911. if (pnode == NULL)
  11912. return;
  11913. Output::Print(_u("[%4d, %4d): "), pnode->ichMin, pnode->ichLim);
  11914. switch (pnode->nop) {
  11915. //PTNODE(knopName , "name" ,None ,Pid ,fnopLeaf)
  11916. case knopName:
  11917. Indent(indentAmt);
  11918. if (pnode->AsParseNodeName()->pid != NULL) {
  11919. Output::Print(_u("id: %s\n"), pnode->AsParseNodeName()->pid->Psz());
  11920. }
  11921. else {
  11922. Output::Print(_u("name node\n"));
  11923. }
  11924. break;
  11925. //PTNODE(knopInt , "int const" ,None ,Int ,fnopLeaf|fnopConst)
  11926. case knopInt:
  11927. Indent(indentAmt);
  11928. Output::Print(_u("%d\n"), pnode->AsParseNodeInt()->lw);
  11929. break;
  11930. //PTNODE(knopInt , "int const" ,None ,Int ,fnopLeaf|fnopConst)
  11931. case knopBigInt:
  11932. Indent(indentAmt);
  11933. Output::Print(_u("%s%s\n"), pnode->AsParseNodeBigInt()->isNegative? "-" : "", pnode->AsParseNodeBigInt()->pid->Psz());
  11934. break;
  11935. //PTNODE(knopFlt , "flt const" ,None ,Flt ,fnopLeaf|fnopConst)
  11936. case knopFlt:
  11937. Indent(indentAmt);
  11938. Output::Print(_u("%lf\n"), pnode->AsParseNodeFloat()->dbl);
  11939. break;
  11940. //PTNODE(knopStr , "str const" ,None ,Pid ,fnopLeaf|fnopConst)
  11941. case knopStr:
  11942. Indent(indentAmt);
  11943. Output::Print(_u("\"%s\"\n"), pnode->AsParseNodeStr()->pid->Psz());
  11944. break;
  11945. //PTNODE(knopRegExp , "reg expr" ,None ,Pid ,fnopLeaf|fnopConst)
  11946. case knopRegExp:
  11947. Indent(indentAmt);
  11948. Output::Print(_u("/%x/\n"), pnode->AsParseNodeRegExp()->regexPattern);
  11949. break;
  11950. //PTNODE(knopNull , "null" ,Null ,None ,fnopLeaf)
  11951. case knopNull:
  11952. Indent(indentAmt);
  11953. Output::Print(_u("null\n"));
  11954. break;
  11955. //PTNODE(knopFalse , "false" ,False ,None ,fnopLeaf)
  11956. case knopFalse:
  11957. Indent(indentAmt);
  11958. Output::Print(_u("false\n"));
  11959. break;
  11960. //PTNODE(knopTrue , "true" ,True ,None ,fnopLeaf)
  11961. case knopTrue:
  11962. Indent(indentAmt);
  11963. Output::Print(_u("true\n"));
  11964. break;
  11965. //PTNODE(knopEmpty , "empty" ,Empty ,None ,fnopLeaf)
  11966. case knopEmpty:
  11967. Indent(indentAmt);
  11968. Output::Print(_u("empty\n"));
  11969. break;
  11970. // Unary operators.
  11971. //PTNODE(knopNot , "~" ,BitNot ,Uni ,fnopUni)
  11972. case knopNot:
  11973. Indent(indentAmt);
  11974. Output::Print(_u("~\n"));
  11975. PrintPnodeWIndent(pnode->AsParseNodeUni()->pnode1, indentAmt + INDENT_SIZE);
  11976. break;
  11977. //PTNODE(knopNeg , "unary -" ,Neg ,Uni ,fnopUni)
  11978. case knopNeg:
  11979. Indent(indentAmt);
  11980. Output::Print(_u("U-\n"));
  11981. PrintPnodeWIndent(pnode->AsParseNodeUni()->pnode1, indentAmt + INDENT_SIZE);
  11982. break;
  11983. //PTNODE(knopPos , "unary +" ,Pos ,Uni ,fnopUni)
  11984. case knopPos:
  11985. Indent(indentAmt);
  11986. Output::Print(_u("U+\n"));
  11987. PrintPnodeWIndent(pnode->AsParseNodeUni()->pnode1, indentAmt + INDENT_SIZE);
  11988. break;
  11989. //PTNODE(knopLogNot , "!" ,LogNot ,Uni ,fnopUni)
  11990. case knopLogNot:
  11991. Indent(indentAmt);
  11992. Output::Print(_u("!\n"));
  11993. PrintPnodeWIndent(pnode->AsParseNodeUni()->pnode1, indentAmt + INDENT_SIZE);
  11994. break;
  11995. //PTNODE(knopEllipsis , "..." ,Spread ,Uni , fnopUni)
  11996. case knopEllipsis:
  11997. Indent(indentAmt);
  11998. Output::Print(_u("...<expr>\n"));
  11999. PrintPnodeWIndent(pnode->AsParseNodeUni()->pnode1, indentAmt + INDENT_SIZE);
  12000. break;
  12001. //PTNODE(knopIncPost , "++ post" ,Inc ,Uni ,fnopUni|fnopAsg)
  12002. case knopIncPost:
  12003. Indent(indentAmt);
  12004. Output::Print(_u("<expr>++\n"));
  12005. PrintPnodeWIndent(pnode->AsParseNodeUni()->pnode1, indentAmt + INDENT_SIZE);
  12006. break;
  12007. //PTNODE(knopDecPost , "-- post" ,Dec ,Uni ,fnopUni|fnopAsg)
  12008. case knopDecPost:
  12009. Indent(indentAmt);
  12010. Output::Print(_u("<expr>--\n"));
  12011. PrintPnodeWIndent(pnode->AsParseNodeUni()->pnode1, indentAmt + INDENT_SIZE);
  12012. break;
  12013. //PTNODE(knopIncPre , "++ pre" ,Inc ,Uni ,fnopUni|fnopAsg)
  12014. case knopIncPre:
  12015. Indent(indentAmt);
  12016. Output::Print(_u("++<expr>\n"));
  12017. PrintPnodeWIndent(pnode->AsParseNodeUni()->pnode1, indentAmt + INDENT_SIZE);
  12018. break;
  12019. //PTNODE(knopDecPre , "-- pre" ,Dec ,Uni ,fnopUni|fnopAsg)
  12020. case knopDecPre:
  12021. Indent(indentAmt);
  12022. Output::Print(_u("--<expr>\n"));
  12023. PrintPnodeWIndent(pnode->AsParseNodeUni()->pnode1, indentAmt + INDENT_SIZE);
  12024. break;
  12025. //PTNODE(knopTypeof , "typeof" ,None ,Uni ,fnopUni)
  12026. case knopTypeof:
  12027. Indent(indentAmt);
  12028. Output::Print(_u("typeof\n"));
  12029. PrintPnodeWIndent(pnode->AsParseNodeUni()->pnode1, indentAmt + INDENT_SIZE);
  12030. break;
  12031. //PTNODE(knopVoid , "void" ,Void ,Uni ,fnopUni)
  12032. case knopVoid:
  12033. Indent(indentAmt);
  12034. Output::Print(_u("void\n"));
  12035. PrintPnodeWIndent(pnode->AsParseNodeUni()->pnode1, indentAmt + INDENT_SIZE);
  12036. break;
  12037. //PTNODE(knopDelete , "delete" ,None ,Uni ,fnopUni)
  12038. case knopDelete:
  12039. Indent(indentAmt);
  12040. Output::Print(_u("delete\n"));
  12041. PrintPnodeWIndent(pnode->AsParseNodeUni()->pnode1, indentAmt + INDENT_SIZE);
  12042. break;
  12043. //PTNODE(knopArray , "arr cnst" ,None ,Uni ,fnopUni)
  12044. case knopArrayPattern:
  12045. Indent(indentAmt);
  12046. Output::Print(_u("Array Pattern\n"));
  12047. PrintPnodeListWIndent(pnode->AsParseNodeUni()->pnode1, indentAmt + INDENT_SIZE);
  12048. break;
  12049. case knopObjectPattern:
  12050. Indent(indentAmt);
  12051. Output::Print(_u("Object Pattern\n"));
  12052. PrintPnodeListWIndent(pnode->AsParseNodeUni()->pnode1, indentAmt + INDENT_SIZE);
  12053. break;
  12054. case knopArray:
  12055. Indent(indentAmt);
  12056. Output::Print(_u("Array Literal\n"));
  12057. PrintPnodeListWIndent(pnode->AsParseNodeUni()->pnode1, indentAmt + INDENT_SIZE);
  12058. break;
  12059. //PTNODE(knopObject , "obj cnst" ,None ,Uni ,fnopUni)
  12060. case knopObject:
  12061. Indent(indentAmt);
  12062. Output::Print(_u("Object Literal\n"));
  12063. PrintPnodeListWIndent(pnode->AsParseNodeUni()->pnode1, indentAmt + INDENT_SIZE);
  12064. break;
  12065. // Binary and Ternary Operators
  12066. //PTNODE(knopAdd , "+" ,Add ,Bin ,fnopBin)
  12067. case knopAdd:
  12068. Indent(indentAmt);
  12069. Output::Print(_u("+\n"));
  12070. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  12071. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  12072. break;
  12073. //PTNODE(knopSub , "-" ,Sub ,Bin ,fnopBin)
  12074. case knopSub:
  12075. Indent(indentAmt);
  12076. Output::Print(_u("-\n"));
  12077. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  12078. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  12079. break;
  12080. //PTNODE(knopMul , "*" ,Mul ,Bin ,fnopBin)
  12081. case knopMul:
  12082. Indent(indentAmt);
  12083. Output::Print(_u("*\n"));
  12084. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  12085. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  12086. break;
  12087. //PTNODE(knopDiv , "/" ,Div ,Bin ,fnopBin)
  12088. case knopExpo:
  12089. Indent(indentAmt);
  12090. Output::Print(_u("**\n"));
  12091. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  12092. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  12093. break;
  12094. //PTNODE(knopExpo , "**" ,Expo ,Bin ,fnopBin)
  12095. case knopDiv:
  12096. Indent(indentAmt);
  12097. Output::Print(_u("/\n"));
  12098. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  12099. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  12100. break;
  12101. //PTNODE(knopMod , "%" ,Mod ,Bin ,fnopBin)
  12102. case knopMod:
  12103. Indent(indentAmt);
  12104. Output::Print(_u("%%\n"));
  12105. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  12106. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  12107. break;
  12108. //PTNODE(knopOr , "|" ,BitOr ,Bin ,fnopBin)
  12109. case knopOr:
  12110. Indent(indentAmt);
  12111. Output::Print(_u("|\n"));
  12112. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  12113. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  12114. break;
  12115. //PTNODE(knopXor , "^" ,BitXor ,Bin ,fnopBin)
  12116. case knopXor:
  12117. Indent(indentAmt);
  12118. Output::Print(_u("^\n"));
  12119. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  12120. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  12121. break;
  12122. //PTNODE(knopAnd , "&" ,BitAnd ,Bin ,fnopBin)
  12123. case knopAnd:
  12124. Indent(indentAmt);
  12125. Output::Print(_u("&\n"));
  12126. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  12127. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  12128. break;
  12129. //PTNODE(knopEq , "==" ,EQ ,Bin ,fnopBin|fnopRel)
  12130. case knopEq:
  12131. Indent(indentAmt);
  12132. Output::Print(_u("==\n"));
  12133. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  12134. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  12135. break;
  12136. //PTNODE(knopNe , "!=" ,NE ,Bin ,fnopBin|fnopRel)
  12137. case knopNe:
  12138. Indent(indentAmt);
  12139. Output::Print(_u("!=\n"));
  12140. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  12141. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  12142. break;
  12143. //PTNODE(knopLt , "<" ,LT ,Bin ,fnopBin|fnopRel)
  12144. case knopLt:
  12145. Indent(indentAmt);
  12146. Output::Print(_u("<\n"));
  12147. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  12148. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  12149. break;
  12150. //PTNODE(knopLe , "<=" ,LE ,Bin ,fnopBin|fnopRel)
  12151. case knopLe:
  12152. Indent(indentAmt);
  12153. Output::Print(_u("<=\n"));
  12154. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  12155. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  12156. break;
  12157. //PTNODE(knopGe , ">=" ,GE ,Bin ,fnopBin|fnopRel)
  12158. case knopGe:
  12159. Indent(indentAmt);
  12160. Output::Print(_u(">=\n"));
  12161. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  12162. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  12163. break;
  12164. //PTNODE(knopGt , ">" ,GT ,Bin ,fnopBin|fnopRel)
  12165. case knopGt:
  12166. Indent(indentAmt);
  12167. Output::Print(_u(">\n"));
  12168. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  12169. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  12170. break;
  12171. //PTNODE(knopCall , "()" ,None ,Bin ,fnopBin)
  12172. case knopCall:
  12173. Indent(indentAmt);
  12174. Output::Print(_u("Call\n"));
  12175. PrintPnodeWIndent(pnode->AsParseNodeCall()->pnodeTarget, indentAmt + INDENT_SIZE);
  12176. PrintPnodeListWIndent(pnode->AsParseNodeCall()->pnodeArgs, indentAmt + INDENT_SIZE);
  12177. break;
  12178. //PTNODE(knopDot , "." ,None ,Bin ,fnopBin)
  12179. case knopDot:
  12180. Indent(indentAmt);
  12181. Output::Print(_u(".\n"));
  12182. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  12183. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  12184. break;
  12185. //PTNODE(knopAsg , "=" ,None ,Bin ,fnopBin|fnopAsg)
  12186. case knopAsg:
  12187. Indent(indentAmt);
  12188. Output::Print(_u("=\n"));
  12189. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  12190. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  12191. break;
  12192. //PTNODE(knopInstOf , "instanceof",InstOf ,Bin ,fnopBin|fnopRel)
  12193. case knopInstOf:
  12194. Indent(indentAmt);
  12195. Output::Print(_u("instanceof\n"));
  12196. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  12197. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  12198. break;
  12199. //PTNODE(knopIn , "in" ,In ,Bin ,fnopBin|fnopRel)
  12200. case knopIn:
  12201. Indent(indentAmt);
  12202. Output::Print(_u("in\n"));
  12203. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  12204. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  12205. break;
  12206. //PTNODE(knopEqv , "===" ,Eqv ,Bin ,fnopBin|fnopRel)
  12207. case knopEqv:
  12208. Indent(indentAmt);
  12209. Output::Print(_u("===\n"));
  12210. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  12211. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  12212. break;
  12213. //PTNODE(knopNEqv , "!==" ,NEqv ,Bin ,fnopBin|fnopRel)
  12214. case knopNEqv:
  12215. Indent(indentAmt);
  12216. Output::Print(_u("!==\n"));
  12217. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  12218. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  12219. break;
  12220. //PTNODE(knopComma , "," ,None ,Bin ,fnopBin)
  12221. case knopComma:
  12222. Indent(indentAmt);
  12223. Output::Print(_u(",\n"));
  12224. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  12225. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  12226. break;
  12227. //PTNODE(knopLogOr , "||" ,None ,Bin ,fnopBin)
  12228. case knopLogOr:
  12229. Indent(indentAmt);
  12230. Output::Print(_u("||\n"));
  12231. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  12232. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  12233. break;
  12234. //PTNODE(knopLogAnd , "&&" ,None ,Bin ,fnopBin)
  12235. case knopLogAnd:
  12236. Indent(indentAmt);
  12237. Output::Print(_u("&&\n"));
  12238. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  12239. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  12240. break;
  12241. //PTNODE(knopLsh , "<<" ,Lsh ,Bin ,fnopBin)
  12242. case knopLsh:
  12243. Indent(indentAmt);
  12244. Output::Print(_u("<<\n"));
  12245. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  12246. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  12247. break;
  12248. //PTNODE(knopRsh , ">>" ,Rsh ,Bin ,fnopBin)
  12249. case knopRsh:
  12250. Indent(indentAmt);
  12251. Output::Print(_u(">>\n"));
  12252. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  12253. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  12254. break;
  12255. //PTNODE(knopRs2 , ">>>" ,Rs2 ,Bin ,fnopBin)
  12256. case knopRs2:
  12257. Indent(indentAmt);
  12258. Output::Print(_u(">>>\n"));
  12259. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  12260. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  12261. break;
  12262. //PTNODE(knopNew , "new" ,None ,Bin ,fnopBin)
  12263. case knopNew:
  12264. Indent(indentAmt);
  12265. Output::Print(_u("new\n"));
  12266. PrintPnodeWIndent(pnode->AsParseNodeCall()->pnodeTarget, indentAmt + INDENT_SIZE);
  12267. PrintPnodeListWIndent(pnode->AsParseNodeCall()->pnodeArgs, indentAmt + INDENT_SIZE);
  12268. break;
  12269. //PTNODE(knopIndex , "[]" ,None ,Bin ,fnopBin)
  12270. case knopIndex:
  12271. Indent(indentAmt);
  12272. Output::Print(_u("[]\n"));
  12273. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  12274. PrintPnodeListWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  12275. break;
  12276. //PTNODE(knopQmark , "?" ,None ,Tri ,fnopBin)
  12277. case knopQmark:
  12278. Indent(indentAmt);
  12279. Output::Print(_u("?:\n"));
  12280. PrintPnodeWIndent(pnode->AsParseNodeTri()->pnode1, indentAmt + INDENT_SIZE);
  12281. PrintPnodeWIndent(pnode->AsParseNodeTri()->pnode2, indentAmt + INDENT_SIZE);
  12282. PrintPnodeWIndent(pnode->AsParseNodeTri()->pnode3, indentAmt + INDENT_SIZE);
  12283. break;
  12284. //PTNODE(knopAsgAdd , "+=" ,Add ,Bin ,fnopBin|fnopAsg)
  12285. case knopAsgAdd:
  12286. Indent(indentAmt);
  12287. Output::Print(_u("+=\n"));
  12288. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  12289. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  12290. break;
  12291. //PTNODE(knopAsgSub , "-=" ,Sub ,Bin ,fnopBin|fnopAsg)
  12292. case knopAsgSub:
  12293. Indent(indentAmt);
  12294. Output::Print(_u("-=\n"));
  12295. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  12296. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  12297. break;
  12298. //PTNODE(knopAsgMul , "*=" ,Mul ,Bin ,fnopBin|fnopAsg)
  12299. case knopAsgMul:
  12300. Indent(indentAmt);
  12301. Output::Print(_u("*=\n"));
  12302. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  12303. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  12304. break;
  12305. //PTNODE(knopAsgDiv , "/=" ,Div ,Bin ,fnopBin|fnopAsg)
  12306. case knopAsgExpo:
  12307. Indent(indentAmt);
  12308. Output::Print(_u("**=\n"));
  12309. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  12310. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  12311. break;
  12312. //PTNODE(knopAsgExpo , "**=" ,Expo ,Bin ,fnopBin|fnopAsg)
  12313. case knopAsgDiv:
  12314. Indent(indentAmt);
  12315. Output::Print(_u("/=\n"));
  12316. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  12317. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  12318. break;
  12319. //PTNODE(knopAsgMod , "%=" ,Mod ,Bin ,fnopBin|fnopAsg)
  12320. case knopAsgMod:
  12321. Indent(indentAmt);
  12322. Output::Print(_u("%=\n"));
  12323. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  12324. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  12325. break;
  12326. //PTNODE(knopAsgAnd , "&=" ,BitAnd ,Bin ,fnopBin|fnopAsg)
  12327. case knopAsgAnd:
  12328. Indent(indentAmt);
  12329. Output::Print(_u("&=\n"));
  12330. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  12331. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  12332. break;
  12333. //PTNODE(knopAsgXor , "^=" ,BitXor ,Bin ,fnopBin|fnopAsg)
  12334. case knopAsgXor:
  12335. Indent(indentAmt);
  12336. Output::Print(_u("^=\n"));
  12337. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  12338. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  12339. break;
  12340. //PTNODE(knopAsgOr , "|=" ,BitOr ,Bin ,fnopBin|fnopAsg)
  12341. case knopAsgOr:
  12342. Indent(indentAmt);
  12343. Output::Print(_u("|=\n"));
  12344. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  12345. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  12346. break;
  12347. //PTNODE(knopAsgLsh , "<<=" ,Lsh ,Bin ,fnopBin|fnopAsg)
  12348. case knopAsgLsh:
  12349. Indent(indentAmt);
  12350. Output::Print(_u("<<=\n"));
  12351. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  12352. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  12353. break;
  12354. //PTNODE(knopAsgRsh , ">>=" ,Rsh ,Bin ,fnopBin|fnopAsg)
  12355. case knopAsgRsh:
  12356. Indent(indentAmt);
  12357. Output::Print(_u(">>=\n"));
  12358. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  12359. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  12360. break;
  12361. //PTNODE(knopAsgRs2 , ">>>=" ,Rs2 ,Bin ,fnopBin|fnopAsg)
  12362. case knopAsgRs2:
  12363. Indent(indentAmt);
  12364. Output::Print(_u(">>>=\n"));
  12365. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  12366. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  12367. break;
  12368. case knopComputedName:
  12369. Indent(indentAmt);
  12370. Output::Print(_u("ComputedProperty\n"));
  12371. PrintPnodeWIndent(pnode->AsParseNodeUni()->pnode1, indentAmt + INDENT_SIZE);
  12372. break;
  12373. case knopParamPattern:
  12374. PrintPnodeWIndent(pnode->AsParseNodeParamPattern()->pnode1, indentAmt);
  12375. break;
  12376. //PTNODE(knopMember , ":" ,None ,Bin ,fnopBin)
  12377. case knopMember:
  12378. case knopMemberShort:
  12379. case knopObjectPatternMember:
  12380. Indent(indentAmt);
  12381. Output::Print(_u(":\n"));
  12382. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  12383. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  12384. break;
  12385. // General nodes.
  12386. //PTNODE(knopList , "<list>" ,None ,Bin ,fnopNone)
  12387. case knopList:
  12388. Indent(indentAmt);
  12389. Output::Print(_u("List\n"));
  12390. PrintPnodeListWIndent(pnode, indentAmt + INDENT_SIZE);
  12391. break;
  12392. //PTNODE(knopVarDecl , "varDcl" ,None ,Var ,fnopNone)
  12393. case knopVarDecl:
  12394. Indent(indentAmt);
  12395. Output::Print(_u("var %s\n"), pnode->AsParseNodeVar()->pid->Psz());
  12396. if (pnode->AsParseNodeVar()->pnodeInit != NULL)
  12397. PrintPnodeWIndent(pnode->AsParseNodeVar()->pnodeInit, indentAmt + INDENT_SIZE);
  12398. break;
  12399. case knopConstDecl:
  12400. Indent(indentAmt);
  12401. Output::Print(_u("const %s\n"), pnode->AsParseNodeVar()->pid->Psz());
  12402. if (pnode->AsParseNodeVar()->pnodeInit != NULL)
  12403. PrintPnodeWIndent(pnode->AsParseNodeVar()->pnodeInit, indentAmt + INDENT_SIZE);
  12404. break;
  12405. case knopLetDecl:
  12406. Indent(indentAmt);
  12407. Output::Print(_u("let %s\n"), pnode->AsParseNodeVar()->pid->Psz());
  12408. if (pnode->AsParseNodeVar()->pnodeInit != NULL)
  12409. PrintPnodeWIndent(pnode->AsParseNodeVar()->pnodeInit, indentAmt + INDENT_SIZE);
  12410. break;
  12411. //PTNODE(knopFncDecl , "fncDcl" ,None ,Fnc ,fnopLeaf)
  12412. case knopFncDecl:
  12413. Indent(indentAmt);
  12414. if (pnode->AsParseNodeFnc()->pid != NULL)
  12415. {
  12416. Output::Print(_u("fn decl %d nested %d name %s (%d-%d)\n"), pnode->AsParseNodeFnc()->IsDeclaration(), pnode->AsParseNodeFnc()->IsNested(),
  12417. pnode->AsParseNodeFnc()->pid->Psz(), pnode->ichMin, pnode->ichLim);
  12418. }
  12419. else
  12420. {
  12421. Output::Print(_u("fn decl %d nested %d anonymous (%d-%d)\n"), pnode->AsParseNodeFnc()->IsDeclaration(), pnode->AsParseNodeFnc()->IsNested(), pnode->ichMin, pnode->ichLim);
  12422. }
  12423. PrintScopesWIndent(pnode, indentAmt + INDENT_SIZE);
  12424. PrintFormalsWIndent(pnode->AsParseNodeFnc()->pnodeParams, indentAmt + INDENT_SIZE);
  12425. PrintPnodeWIndent(pnode->AsParseNodeFnc()->pnodeRest, indentAmt + INDENT_SIZE);
  12426. PrintPnodeWIndent(pnode->AsParseNodeFnc()->pnodeBody, indentAmt + INDENT_SIZE);
  12427. if (pnode->AsParseNodeFnc()->pnodeBody == nullptr)
  12428. {
  12429. Output::Print(_u("[%4d, %4d): "), pnode->ichMin, pnode->ichLim);
  12430. Indent(indentAmt + INDENT_SIZE);
  12431. Output::Print(_u("<parse deferred body>\n"));
  12432. }
  12433. break;
  12434. //PTNODE(knopProg , "program" ,None ,Fnc ,fnopNone)
  12435. case knopProg:
  12436. Indent(indentAmt);
  12437. Output::Print(_u("program\n"));
  12438. PrintScopesWIndent(pnode, indentAmt + INDENT_SIZE);
  12439. PrintPnodeListWIndent(pnode->AsParseNodeFnc()->pnodeBody, indentAmt + INDENT_SIZE);
  12440. break;
  12441. //PTNODE(knopEndCode , "<endcode>" ,None ,None ,fnopNone)
  12442. case knopEndCode:
  12443. Indent(indentAmt);
  12444. Output::Print(_u("<endcode>\n"));
  12445. break;
  12446. //PTNODE(knopDebugger , "debugger" ,None ,None ,fnopNone)
  12447. case knopDebugger:
  12448. Indent(indentAmt);
  12449. Output::Print(_u("<debugger>\n"));
  12450. break;
  12451. //PTNODE(knopFor , "for" ,None ,For ,fnopBreak|fnopContinue)
  12452. case knopFor:
  12453. Indent(indentAmt);
  12454. Output::Print(_u("for\n"));
  12455. PrintScopesWIndent(pnode, indentAmt + INDENT_SIZE);
  12456. PrintPnodeWIndent(pnode->AsParseNodeFor()->pnodeInit, indentAmt + INDENT_SIZE);
  12457. PrintPnodeWIndent(pnode->AsParseNodeFor()->pnodeCond, indentAmt + INDENT_SIZE);
  12458. PrintPnodeWIndent(pnode->AsParseNodeFor()->pnodeIncr, indentAmt + INDENT_SIZE);
  12459. PrintPnodeWIndent(pnode->AsParseNodeFor()->pnodeBody, indentAmt + INDENT_SIZE);
  12460. break;
  12461. //PTNODE(knopIf , "if" ,None ,If ,fnopNone)
  12462. case knopIf:
  12463. Indent(indentAmt);
  12464. Output::Print(_u("if\n"));
  12465. PrintPnodeWIndent(pnode->AsParseNodeIf()->pnodeCond, indentAmt + INDENT_SIZE);
  12466. PrintPnodeWIndent(pnode->AsParseNodeIf()->pnodeTrue, indentAmt + INDENT_SIZE);
  12467. if (pnode->AsParseNodeIf()->pnodeFalse != NULL)
  12468. PrintPnodeWIndent(pnode->AsParseNodeIf()->pnodeFalse, indentAmt + INDENT_SIZE);
  12469. break;
  12470. //PTNODE(knopWhile , "while" ,None ,While,fnopBreak|fnopContinue)
  12471. case knopWhile:
  12472. Indent(indentAmt);
  12473. Output::Print(_u("while\n"));
  12474. PrintPnodeWIndent(pnode->AsParseNodeWhile()->pnodeCond, indentAmt + INDENT_SIZE);
  12475. PrintPnodeWIndent(pnode->AsParseNodeWhile()->pnodeBody, indentAmt + INDENT_SIZE);
  12476. break;
  12477. //PTNODE(knopDoWhile , "do-while" ,None ,While,fnopBreak|fnopContinue)
  12478. case knopDoWhile:
  12479. Indent(indentAmt);
  12480. Output::Print(_u("do\n"));
  12481. PrintPnodeWIndent(pnode->AsParseNodeWhile()->pnodeCond, indentAmt + INDENT_SIZE);
  12482. PrintPnodeWIndent(pnode->AsParseNodeWhile()->pnodeBody, indentAmt + INDENT_SIZE);
  12483. break;
  12484. //PTNODE(knopForIn , "for in" ,None ,ForIn,fnopBreak|fnopContinue|fnopCleanup)
  12485. case knopForIn:
  12486. Indent(indentAmt);
  12487. Output::Print(_u("forIn\n"));
  12488. PrintScopesWIndent(pnode, indentAmt + INDENT_SIZE);
  12489. PrintPnodeWIndent(pnode->AsParseNodeForInOrForOf()->pnodeLval, indentAmt + INDENT_SIZE);
  12490. PrintPnodeWIndent(pnode->AsParseNodeForInOrForOf()->pnodeObj, indentAmt + INDENT_SIZE);
  12491. PrintPnodeWIndent(pnode->AsParseNodeForInOrForOf()->pnodeBody, indentAmt + INDENT_SIZE);
  12492. break;
  12493. case knopForOf:
  12494. Indent(indentAmt);
  12495. Output::Print(_u("forOf\n"));
  12496. PrintScopesWIndent(pnode, indentAmt + INDENT_SIZE);
  12497. PrintPnodeWIndent(pnode->AsParseNodeForInOrForOf()->pnodeLval, indentAmt + INDENT_SIZE);
  12498. PrintPnodeWIndent(pnode->AsParseNodeForInOrForOf()->pnodeObj, indentAmt + INDENT_SIZE);
  12499. PrintPnodeWIndent(pnode->AsParseNodeForInOrForOf()->pnodeBody, indentAmt + INDENT_SIZE);
  12500. break;
  12501. case knopForAwaitOf:
  12502. Indent(indentAmt);
  12503. Output::Print(_u("forAwaitOf\n"));
  12504. PrintScopesWIndent(pnode, indentAmt + INDENT_SIZE);
  12505. PrintPnodeWIndent(pnode->AsParseNodeForInOrForOf()->pnodeLval, indentAmt + INDENT_SIZE);
  12506. PrintPnodeWIndent(pnode->AsParseNodeForInOrForOf()->pnodeObj, indentAmt + INDENT_SIZE);
  12507. PrintPnodeWIndent(pnode->AsParseNodeForInOrForOf()->pnodeBody, indentAmt + INDENT_SIZE);
  12508. break;
  12509. //PTNODE(knopReturn , "return" ,None ,Uni ,fnopNone)
  12510. case knopReturn:
  12511. Indent(indentAmt);
  12512. Output::Print(_u("return\n"));
  12513. if (pnode->AsParseNodeReturn()->pnodeExpr != NULL)
  12514. PrintPnodeWIndent(pnode->AsParseNodeReturn()->pnodeExpr, indentAmt + INDENT_SIZE);
  12515. break;
  12516. //PTNODE(knopBlock , "{}" ,None ,Block,fnopNone)
  12517. case knopBlock:
  12518. Indent(indentAmt);
  12519. Output::Print(_u("block "));
  12520. if (pnode->grfpn & fpnSyntheticNode)
  12521. Output::Print(_u("synthetic "));
  12522. PrintBlockType(pnode->AsParseNodeBlock()->blockType);
  12523. Output::Print(_u("(%d-%d)\n"), pnode->ichMin, pnode->ichLim);
  12524. PrintScopesWIndent(pnode, indentAmt + INDENT_SIZE);
  12525. if (pnode->AsParseNodeBlock()->pnodeStmt != NULL)
  12526. PrintPnodeWIndent(pnode->AsParseNodeBlock()->pnodeStmt, indentAmt + INDENT_SIZE);
  12527. break;
  12528. //PTNODE(knopWith , "with" ,None ,With ,fnopCleanup)
  12529. case knopWith:
  12530. Indent(indentAmt);
  12531. Output::Print(_u("with (%d-%d)\n"), pnode->ichMin, pnode->ichLim);
  12532. PrintScopesWIndent(pnode, indentAmt + INDENT_SIZE);
  12533. PrintPnodeWIndent(pnode->AsParseNodeWith()->pnodeObj, indentAmt + INDENT_SIZE);
  12534. PrintPnodeWIndent(pnode->AsParseNodeWith()->pnodeBody, indentAmt + INDENT_SIZE);
  12535. break;
  12536. //PTNODE(knopBreak , "break" ,None ,Jump ,fnopNone)
  12537. case knopBreak:
  12538. Indent(indentAmt);
  12539. Output::Print(_u("break\n"));
  12540. // TODO: some representation of target
  12541. break;
  12542. //PTNODE(knopContinue , "continue" ,None ,Jump ,fnopNone)
  12543. case knopContinue:
  12544. Indent(indentAmt);
  12545. Output::Print(_u("continue\n"));
  12546. // TODO: some representation of target
  12547. break;
  12548. //PTNODE(knopSwitch , "switch" ,None ,Switch,fnopBreak)
  12549. case knopSwitch:
  12550. Indent(indentAmt);
  12551. Output::Print(_u("switch\n"));
  12552. PrintScopesWIndent(pnode, indentAmt + INDENT_SIZE);
  12553. for (ParseNodeCase *pnodeT = pnode->AsParseNodeSwitch()->pnodeCases; NULL != pnodeT; pnodeT = pnodeT->pnodeNext) {
  12554. PrintPnodeWIndent(pnodeT, indentAmt + 2);
  12555. }
  12556. break;
  12557. //PTNODE(knopCase , "case" ,None ,Case ,fnopNone)
  12558. case knopCase:
  12559. Indent(indentAmt);
  12560. Output::Print(_u("case\n"));
  12561. PrintPnodeWIndent(pnode->AsParseNodeCase()->pnodeExpr, indentAmt + INDENT_SIZE);
  12562. PrintPnodeWIndent(pnode->AsParseNodeCase()->pnodeBody, indentAmt + INDENT_SIZE);
  12563. break;
  12564. //PTNODE(knopTryFinally,"try-finally",None,TryFinally,fnopCleanup)
  12565. case knopTryFinally:
  12566. PrintPnodeWIndent(pnode->AsParseNodeTryFinally()->pnodeTry, indentAmt);
  12567. PrintPnodeWIndent(pnode->AsParseNodeTryFinally()->pnodeFinally, indentAmt);
  12568. break;
  12569. case knopFinally:
  12570. Indent(indentAmt);
  12571. Output::Print(_u("finally\n"));
  12572. PrintPnodeWIndent(pnode->AsParseNodeFinally()->pnodeBody, indentAmt + INDENT_SIZE);
  12573. break;
  12574. //PTNODE(knopCatch , "catch" ,None ,Catch,fnopNone)
  12575. case knopCatch:
  12576. Indent(indentAmt);
  12577. Output::Print(_u("catch (%d-%d)\n"), pnode->ichMin, pnode->ichLim);
  12578. PrintScopesWIndent(pnode, indentAmt + INDENT_SIZE);
  12579. PrintPnodeWIndent(pnode->AsParseNodeCatch()->GetParam(), indentAmt + INDENT_SIZE);
  12580. // if (pnode->AsParseNodeCatch()->pnodeGuard!=NULL)
  12581. // PrintPnodeWIndent(pnode->AsParseNodeCatch()->pnodeGuard,indentAmt+INDENT_SIZE);
  12582. PrintPnodeWIndent(pnode->AsParseNodeCatch()->pnodeBody, indentAmt + INDENT_SIZE);
  12583. break;
  12584. //PTNODE(knopTryCatch , "try-catch" ,None ,TryCatch ,fnopCleanup)
  12585. case knopTryCatch:
  12586. PrintPnodeWIndent(pnode->AsParseNodeTryCatch()->pnodeTry, indentAmt);
  12587. PrintPnodeWIndent(pnode->AsParseNodeTryCatch()->pnodeCatch, indentAmt);
  12588. break;
  12589. //PTNODE(knopTry , "try" ,None ,Try ,fnopCleanup)
  12590. case knopTry:
  12591. Indent(indentAmt);
  12592. Output::Print(_u("try\n"));
  12593. PrintPnodeWIndent(pnode->AsParseNodeTry()->pnodeBody, indentAmt + INDENT_SIZE);
  12594. break;
  12595. //PTNODE(knopThrow , "throw" ,None ,Uni ,fnopNone)
  12596. case knopThrow:
  12597. Indent(indentAmt);
  12598. Output::Print(_u("throw\n"));
  12599. PrintPnodeWIndent(pnode->AsParseNodeUni()->pnode1, indentAmt + INDENT_SIZE);
  12600. break;
  12601. //PTNODE(knopClassDecl, "classDecl", None , Class, fnopLeaf)
  12602. case knopClassDecl:
  12603. Indent(indentAmt);
  12604. Output::Print(_u("class %s"), pnode->AsParseNodeClass()->pnodeName->pid->Psz());
  12605. if (pnode->AsParseNodeClass()->pnodeExtends != nullptr)
  12606. {
  12607. Output::Print(_u(" extends "));
  12608. PrintPnodeWIndent(pnode->AsParseNodeClass()->pnodeExtends, 0);
  12609. }
  12610. else {
  12611. Output::Print(_u("\n"));
  12612. }
  12613. PrintPnodeWIndent(pnode->AsParseNodeClass()->pnodeConstructor, indentAmt + INDENT_SIZE);
  12614. PrintPnodeWIndent(pnode->AsParseNodeClass()->pnodeMembers, indentAmt + INDENT_SIZE);
  12615. break;
  12616. case knopStrTemplate:
  12617. Indent(indentAmt);
  12618. Output::Print(_u("string template\n"));
  12619. PrintPnodeListWIndent(pnode->AsParseNodeStrTemplate()->pnodeSubstitutionExpressions, indentAmt + INDENT_SIZE);
  12620. break;
  12621. case knopYieldStar:
  12622. Indent(indentAmt);
  12623. Output::Print(_u("yield*\n"));
  12624. PrintPnodeListWIndent(pnode->AsParseNodeUni()->pnode1, indentAmt + INDENT_SIZE);
  12625. break;
  12626. case knopYield:
  12627. case knopYieldLeaf:
  12628. Indent(indentAmt);
  12629. Output::Print(_u("yield\n"));
  12630. PrintPnodeListWIndent(pnode->AsParseNodeUni()->pnode1, indentAmt + INDENT_SIZE);
  12631. break;
  12632. case knopAwait:
  12633. Indent(indentAmt);
  12634. Output::Print(_u("await\n"));
  12635. PrintPnodeListWIndent(pnode->AsParseNodeUni()->pnode1, indentAmt + INDENT_SIZE);
  12636. break;
  12637. case knopExportDefault:
  12638. Indent(indentAmt);
  12639. Output::Print(_u("export default\n"));
  12640. PrintPnodeListWIndent(pnode->AsParseNodeExportDefault()->pnodeExpr, indentAmt + INDENT_SIZE);
  12641. break;
  12642. default:
  12643. Output::Print(_u("unhandled pnode op %d\n"), pnode->nop);
  12644. break;
  12645. }
  12646. }
  12647. void PrintPnodeListWIndent(ParseNode *pnode, int indentAmt) {
  12648. if (pnode != NULL) {
  12649. while (pnode->nop == knopList) {
  12650. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt);
  12651. pnode = pnode->AsParseNodeBin()->pnode2;
  12652. }
  12653. PrintPnodeWIndent(pnode, indentAmt);
  12654. }
  12655. }
  12656. void PrintFormalsWIndent(ParseNode *pnodeArgs, int indentAmt)
  12657. {
  12658. for (ParseNode *pnode = pnodeArgs; pnode != nullptr; pnode = pnode->GetFormalNext())
  12659. {
  12660. PrintPnodeWIndent(pnode, indentAmt);
  12661. }
  12662. }
  12663. void PrintPnode(ParseNode *pnode) {
  12664. PrintPnodeWIndent(pnode, 0);
  12665. }
  12666. void ParseNode::Dump()
  12667. {
  12668. switch (nop)
  12669. {
  12670. case knopFncDecl:
  12671. case knopProg:
  12672. LPCOLESTR name = Js::Constants::AnonymousFunction;
  12673. if (this->AsParseNodeFnc()->pnodeName)
  12674. {
  12675. Assert(this->AsParseNodeFnc()->pnodeName->nop == knopVarDecl);
  12676. name = this->AsParseNodeFnc()->pnodeName->pid->Psz();
  12677. }
  12678. Output::Print(_u("%s (%d) [%d, %d]:\n"), name, this->AsParseNodeFnc()->functionId, this->AsParseNodeFnc()->lineNumber, this->AsParseNodeFnc()->columnNumber);
  12679. Output::Print(_u("hasArguments: %s callsEval:%s childCallsEval:%s HasReferenceableBuiltInArguments:%s ArgumentsObjectEscapes:%s HasWith:%s HasOnlyThis:%s \n"),
  12680. IsTrueOrFalse(this->AsParseNodeFnc()->HasHeapArguments()),
  12681. IsTrueOrFalse(this->AsParseNodeFnc()->CallsEval()),
  12682. IsTrueOrFalse(this->AsParseNodeFnc()->ChildCallsEval()),
  12683. IsTrueOrFalse(this->AsParseNodeFnc()->HasReferenceableBuiltInArguments()),
  12684. IsTrueOrFalse(this->AsParseNodeFnc()->GetArgumentsObjectEscapes()),
  12685. IsTrueOrFalse(this->AsParseNodeFnc()->HasWithStmt()),
  12686. IsTrueOrFalse(this->AsParseNodeFnc()->HasOnlyThisStmts()));
  12687. if (this->AsParseNodeFnc()->funcInfo)
  12688. {
  12689. this->AsParseNodeFnc()->funcInfo->Dump();
  12690. }
  12691. break;
  12692. }
  12693. }
  12694. void DumpCapturedNames(ParseNodeFnc* pnodeFnc, IdentPtrSet* capturedNames, ArenaAllocator* alloc)
  12695. {
  12696. auto sortedNames = JsUtil::List<IdentPtr, ArenaAllocator>::New(alloc);
  12697. capturedNames->Map([=](const IdentPtr& pid) -> void {
  12698. sortedNames->Add(pid);
  12699. });
  12700. sortedNames->Sort([](void* context, const void* left, const void* right) -> int {
  12701. const IdentPtr leftIdentPtr = *(const IdentPtr*)(left);
  12702. const IdentPtr rightIdentPtr = *(const IdentPtr*)(right);
  12703. return ::wcscmp(leftIdentPtr->Psz(), rightIdentPtr->Psz());
  12704. }, nullptr);
  12705. sortedNames->Map([=](int index, const IdentPtr pid) -> void {
  12706. OUTPUT_TRACE_DEBUGONLY(Js::CreateParserStatePhase, _u(" Function %u captured name \"%s\"\n"), pnodeFnc->functionId, pid->Psz());
  12707. });
  12708. }
  12709. #endif
  12710. void Parser::AddNestedCapturedNames(ParseNodeFnc* pnodeChildFnc)
  12711. {
  12712. if (m_currentNodeFunc && this->IsCreatingStateCache() && pnodeChildFnc->HasAnyCapturedNames())
  12713. {
  12714. IdentPtrSet* parentCapturedNames = GetCurrentFunctionNode()->EnsureCapturedNames(&m_nodeAllocator);
  12715. IdentPtrSet* childCaptureNames = pnodeChildFnc->GetCapturedNames();
  12716. auto iter = childCaptureNames->GetIterator();
  12717. while (iter.IsValid())
  12718. {
  12719. parentCapturedNames->AddNew(iter.CurrentValue());
  12720. iter.MoveNext();
  12721. }
  12722. }
  12723. }
  12724. void Parser::ProcessCapturedNames(ParseNodeFnc* pnodeFnc)
  12725. {
  12726. if (this->IsCreatingStateCache() && pnodeFnc->HasAnyCapturedNames())
  12727. {
  12728. IdentPtrSet* capturedNames = pnodeFnc->GetCapturedNames();
  12729. auto iter = capturedNames->GetIteratorWithRemovalSupport();
  12730. while (iter.IsValid())
  12731. {
  12732. const IdentPtr& pid = iter.CurrentValueReference();
  12733. PidRefStack* ref = pid->GetTopRef();
  12734. // If the pid has no refs left in our function's scope after binding, we didn't capture it.
  12735. if (!ref || ref->GetFuncScopeId() < pnodeFnc->functionId)
  12736. {
  12737. iter.RemoveCurrent();
  12738. }
  12739. iter.MoveNext();
  12740. }
  12741. #if DBG_DUMP
  12742. if (Js::Configuration::Global.flags.Trace.IsEnabled(Js::CreateParserStatePhase))
  12743. {
  12744. DumpCapturedNames(pnodeFnc, capturedNames, &this->m_nodeAllocator);
  12745. fflush(stdout);
  12746. }
  12747. #endif
  12748. }
  12749. }
  12750. void Parser::ReleaseTemporaryGuestArena()
  12751. {
  12752. // In case of modules the Parser lives longer than the temporary Guest Arena. We may have already released the arena explicitly.
  12753. if (!m_tempGuestArenaReleased)
  12754. {
  12755. // The regex patterns list has references to the temporary Guest Arena. Reset it first.
  12756. m_registeredRegexPatterns.Reset();
  12757. if (this->m_scriptContext != nullptr)
  12758. {
  12759. this->m_scriptContext->ReleaseTemporaryGuestAllocator(m_tempGuestArena);
  12760. m_tempGuestArena.Unroot();
  12761. }
  12762. m_tempGuestArenaReleased = true;
  12763. }
  12764. }
  12765. bool Parser::IsCreatingStateCache()
  12766. {
  12767. return (((this->m_grfscr & fscrCreateParserState) == fscrCreateParserState)
  12768. && this->m_functionBody == nullptr
  12769. && CONFIG_FLAG(ParserStateCache));
  12770. }
  12771. void Parser::ShiftCurrDeferredStubToChildFunction(ParseNodeFnc* pnodeFnc, ParseNodeFnc* pnodeFncParent)
  12772. {
  12773. // Goal here is to shift the current deferred stub to point to the stubs for pnodeFnc
  12774. // so we may continue parsing pnodeFnc using the correct set of stubs instead of the
  12775. // stubs for pnodeFncParent.
  12776. // This function assumes we are in the middle of parsing pnodeFnc which is a child
  12777. // nested in pnodeFncParent.
  12778. if (pnodeFnc->IsNested() && pnodeFncParent != nullptr && m_currDeferredStub != nullptr && pnodeFncParent->ichMin != pnodeFnc->ichMin)
  12779. {
  12780. AssertOrFailFast(pnodeFncParent->nestedCount > 0);
  12781. DeferredFunctionStub* childStub = m_currDeferredStub + (pnodeFncParent->nestedCount - 1);
  12782. m_currDeferredStubCount = childStub->nestedCount;
  12783. m_currDeferredStub = childStub->deferredStubs;
  12784. }
  12785. }
  12786. uint Parser::BuildDeferredStubTreeHelper(ParseNodeBlock* pnodeBlock, DeferredFunctionStub* deferredStubs, uint currentStubIndex, uint deferredStubCount, Recycler *recycler)
  12787. {
  12788. Assert(pnodeBlock != nullptr
  12789. && (pnodeBlock->blockType == PnodeBlockType::Function
  12790. || pnodeBlock->blockType == PnodeBlockType::Parameter));
  12791. ParseNodePtr pnodeChild = pnodeBlock->pnodeScopes;
  12792. while (pnodeChild != nullptr)
  12793. {
  12794. if (pnodeChild->nop != knopFncDecl)
  12795. {
  12796. // We only expect to find a function body block in a parameter scope block.
  12797. Assert(pnodeChild->nop == knopBlock
  12798. && (pnodeBlock->blockType == PnodeBlockType::Parameter
  12799. || pnodeChild->AsParseNodeBlock()->blockType == PnodeBlockType::Function));
  12800. pnodeChild = pnodeChild->AsParseNodeBlock()->pnodeNext;
  12801. continue;
  12802. }
  12803. ParseNodeFnc* pnodeFncChild = pnodeChild->AsParseNodeFnc();
  12804. AnalysisAssertOrFailFast(currentStubIndex < deferredStubCount);
  12805. Assert(pnodeFncChild->pnodeBody == nullptr);
  12806. if (pnodeFncChild->IsGeneratedDefault())
  12807. {
  12808. ++currentStubIndex;
  12809. pnodeChild = pnodeFncChild->pnodeNext;
  12810. continue;
  12811. }
  12812. deferredStubs[currentStubIndex].fncFlags = pnodeFncChild->fncFlags;
  12813. deferredStubs[currentStubIndex].nestedCount = pnodeFncChild->nestedCount;
  12814. deferredStubs[currentStubIndex].restorePoint = *pnodeFncChild->pRestorePoint;
  12815. deferredStubs[currentStubIndex].deferredStubs = BuildDeferredStubTree(pnodeFncChild, recycler);
  12816. deferredStubs[currentStubIndex].ichMin = pnodeChild->ichMin;
  12817. // Save the set of captured names onto the deferred stub.
  12818. // Since this set is allocated in the Parser arena, we'll have to convert these
  12819. // into indices in a string table which will survive when the parser goes away.
  12820. deferredStubs[currentStubIndex].capturedNamePointers = pnodeFncChild->GetCapturedNames();
  12821. ++currentStubIndex;
  12822. pnodeChild = pnodeFncChild->pnodeNext;
  12823. }
  12824. return currentStubIndex;
  12825. }
  12826. DeferredFunctionStub * Parser::BuildDeferredStubTree(ParseNodeFnc *pnodeFnc, Recycler *recycler)
  12827. {
  12828. Assert(CONFIG_FLAG(ParserStateCache));
  12829. uint nestedCount = pnodeFnc->nestedCount;
  12830. if (nestedCount == 0)
  12831. {
  12832. return nullptr;
  12833. }
  12834. if (pnodeFnc->deferredStub)
  12835. {
  12836. return pnodeFnc->deferredStub;
  12837. }
  12838. DeferredFunctionStub* deferredStubs = RecyclerNewArray(recycler, DeferredFunctionStub, nestedCount);
  12839. uint currentStubIndex = BuildDeferredStubTreeHelper(pnodeFnc->pnodeScopes, deferredStubs, 0, nestedCount, recycler);
  12840. currentStubIndex = BuildDeferredStubTreeHelper(pnodeFnc->pnodeBodyScope, deferredStubs, currentStubIndex, nestedCount, recycler);
  12841. Assert(currentStubIndex == nestedCount);
  12842. pnodeFnc->deferredStub = deferredStubs;
  12843. return deferredStubs;
  12844. }