Parse.cpp 492 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161
  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. #if DBG_DUMP
  9. void PrintPnodeWIndent(ParseNode *pnode,int indentAmt);
  10. #endif
  11. const char* const nopNames[knopLim]= {
  12. #define PTNODE(nop,sn,pc,nk,grfnop,json) sn,
  13. #include "ptlist.h"
  14. };
  15. void printNop(int nop) {
  16. Output::Print(_u("%S\n"), nopNames[nop]);
  17. }
  18. const uint ParseNode::mpnopgrfnop[knopLim] =
  19. {
  20. #define PTNODE(nop,sn,pc,nk,grfnop,json) grfnop,
  21. #include "ptlist.h"
  22. };
  23. bool Parser::IsES6DestructuringEnabled() const
  24. {
  25. return m_scriptContext->GetConfig()->IsES6DestructuringEnabled();
  26. }
  27. struct DeferredFunctionStub
  28. {
  29. Field(RestorePoint) restorePoint;
  30. Field(FncFlags) fncFlags;
  31. Field(uint) nestedCount;
  32. Field(DeferredFunctionStub *) deferredStubs;
  33. Field(charcount_t) ichMin;
  34. };
  35. struct StmtNest
  36. {
  37. union
  38. {
  39. struct
  40. {
  41. ParseNodePtr pnodeStmt; // This statement node.
  42. };
  43. struct
  44. {
  45. bool isDeferred : 1;
  46. OpCode op; // This statement operation.
  47. };
  48. };
  49. LabelId* pLabelId; // Labels for this statement.
  50. StmtNest *pstmtOuter; // Enclosing statement.
  51. OpCode GetNop() const
  52. {
  53. AnalysisAssert(isDeferred || pnodeStmt != nullptr);
  54. return isDeferred ? op : pnodeStmt->nop;
  55. }
  56. };
  57. struct BlockInfoStack
  58. {
  59. StmtNest pstmt;
  60. ParseNode *pnodeBlock;
  61. ParseNodePtr *m_ppnodeLex; // lexical variable list tail
  62. BlockInfoStack *pBlockInfoOuter; // containing block's BlockInfoStack
  63. BlockInfoStack *pBlockInfoFunction; // nearest function's BlockInfoStack (if pnodeBlock is a function, this points to itself)
  64. };
  65. #if DEBUG
  66. Parser::Parser(Js::ScriptContext* scriptContext, BOOL strictMode, PageAllocator *alloc, bool isBackground, size_t size)
  67. #else
  68. Parser::Parser(Js::ScriptContext* scriptContext, BOOL strictMode, PageAllocator *alloc, bool isBackground)
  69. #endif
  70. : m_nodeAllocator(_u("Parser"), alloc ? alloc : scriptContext->GetThreadContext()->GetPageAllocator(), Parser::OutOfMemory),
  71. m_cactIdentToNodeLookup(0),
  72. m_grfscr(fscrNil),
  73. m_length(0),
  74. m_originalLength(0),
  75. m_nextFunctionId(nullptr),
  76. m_sourceContextInfo(nullptr),
  77. #if ENABLE_BACKGROUND_PARSING
  78. m_isInBackground(isBackground),
  79. m_hasParallelJob(false),
  80. m_doingFastScan(false),
  81. #endif
  82. m_nextBlockId(0),
  83. // use the GuestArena directly for keeping the RegexPattern* alive during byte code generation
  84. m_registeredRegexPatterns(scriptContext->GetGuestArena()),
  85. m_scriptContext(scriptContext),
  86. m_phtbl(nullptr),
  87. m_token(), // should initialize to 0/nullptrs
  88. m_pscan(nullptr),
  89. m_currentNodeNonLambdaFunc(nullptr),
  90. m_currentNodeNonLambdaDeferredFunc(nullptr),
  91. m_currentNodeFunc(nullptr),
  92. m_currentNodeDeferredFunc(nullptr),
  93. m_currentNodeProg(nullptr),
  94. m_currDeferredStub(nullptr),
  95. m_prevSiblingDeferredStub(nullptr),
  96. m_pCurrentAstSize(nullptr),
  97. m_ppnodeScope(nullptr),
  98. m_ppnodeExprScope(nullptr),
  99. m_ppnodeVar(nullptr),
  100. m_inDeferredNestedFunc(false),
  101. m_reparsingLambdaParams(false),
  102. m_disallowImportExportStmt(false),
  103. m_isInParsingArgList(false),
  104. m_hasDestructuringPattern(false),
  105. m_hasDeferredShorthandInitError(false),
  106. m_pnestedCount(nullptr),
  107. wellKnownPropertyPids(), // should initialize to nullptrs
  108. m_sourceLim(0),
  109. m_functionBody(nullptr),
  110. m_parseType(ParseType_Upfront),
  111. m_arrayDepth(0),
  112. m_funcInArrayDepth(0),
  113. m_funcInArray(0),
  114. m_scopeCountNoAst(0),
  115. m_parsingSuperRestrictionState(ParsingSuperRestrictionState_SuperDisallowed),
  116. m_funcParenExprDepth(0),
  117. m_deferEllipsisError(false),
  118. m_deferEllipsisErrorLoc(), // calls default initializer
  119. m_tryCatchOrFinallyDepth(0),
  120. m_pstmtCur(nullptr),
  121. m_currentBlockInfo(nullptr),
  122. m_currentScope(nullptr),
  123. currBackgroundParseItem(nullptr),
  124. backgroundParseItems(nullptr),
  125. fastScannedRegExpNodes(nullptr),
  126. m_currentDynamicBlock(nullptr),
  127. m_UsesArgumentsAtGlobal(false),
  128. m_fUseStrictMode(strictMode),
  129. m_InAsmMode(false),
  130. m_deferAsmJs(true),
  131. m_fExpectExternalSource(FALSE),
  132. m_deferringAST(FALSE),
  133. m_stoppedDeferredParse(FALSE)
  134. {
  135. AssertMsg(size == sizeof(Parser), "verify conditionals affecting the size of Parser agree");
  136. Assert(scriptContext != nullptr);
  137. }
  138. Parser::~Parser(void)
  139. {
  140. if (m_scriptContext == nullptr || m_scriptContext->GetGuestArena() == nullptr)
  141. {
  142. // If the scriptContext or guestArena have gone away, there is no point clearing each item of this list.
  143. // Just reset it so that destructor of the SList will be no-op
  144. m_registeredRegexPatterns.Reset();
  145. }
  146. #if ENABLE_BACKGROUND_PARSING
  147. if (this->m_hasParallelJob)
  148. {
  149. // Let the background threads know that they can decommit their arena pages.
  150. BackgroundParser *bgp = m_scriptContext->GetBackgroundParser();
  151. Assert(bgp);
  152. if (bgp->Processor()->ProcessesInBackground())
  153. {
  154. JsUtil::BackgroundJobProcessor *processor = static_cast<JsUtil::BackgroundJobProcessor*>(bgp->Processor());
  155. bool result = processor->IterateBackgroundThreads([&](JsUtil::ParallelThreadData *threadData)->bool {
  156. threadData->canDecommit = true;
  157. return false;
  158. });
  159. Assert(result);
  160. }
  161. }
  162. #endif
  163. Release();
  164. }
  165. void Parser::OutOfMemory()
  166. {
  167. throw ParseExceptionObject(ERRnoMemory);
  168. }
  169. void Parser::Error(HRESULT hr)
  170. {
  171. throw ParseExceptionObject(hr);
  172. }
  173. void Parser::Error(HRESULT hr, ParseNodePtr pnode)
  174. {
  175. if (pnode && pnode->ichLim)
  176. {
  177. Error(hr, pnode->ichMin, pnode->ichLim);
  178. }
  179. else
  180. {
  181. Error(hr);
  182. }
  183. }
  184. void Parser::Error(HRESULT hr, charcount_t ichMin, charcount_t ichLim)
  185. {
  186. m_pscan->SetErrorPosition(ichMin, ichLim);
  187. Error(hr);
  188. }
  189. void Parser::IdentifierExpectedError(const Token& token)
  190. {
  191. Assert(token.tk != tkID);
  192. HRESULT hr;
  193. if (token.IsReservedWord())
  194. {
  195. if (token.IsKeyword())
  196. {
  197. hr = ERRKeywordNotId;
  198. }
  199. else
  200. {
  201. Assert(token.IsFutureReservedWord(true));
  202. if (token.IsFutureReservedWord(false))
  203. {
  204. // Future reserved word in strict and non-strict modes
  205. hr = ERRFutureReservedWordNotId;
  206. }
  207. else
  208. {
  209. // Future reserved word only in strict mode. The token would have been converted to tkID by the scanner if not
  210. // in strict mode.
  211. Assert(IsStrictMode());
  212. hr = ERRFutureReservedWordInStrictModeNotId;
  213. }
  214. }
  215. }
  216. else
  217. {
  218. hr = ERRnoIdent;
  219. }
  220. Error(hr);
  221. }
  222. HRESULT Parser::ValidateSyntax(LPCUTF8 pszSrc, size_t encodedCharCount, bool isGenerator, bool isAsync, CompileScriptException *pse, void (Parser::*validateFunction)())
  223. {
  224. AssertPsz(pszSrc);
  225. AssertMemN(pse);
  226. PROBE_STACK_NO_DISPOSE(m_scriptContext, Js::Constants::MinStackDefault);
  227. HRESULT hr;
  228. SmartFPUControl smartFpuControl;
  229. BOOL fDeferSave = m_deferringAST;
  230. try
  231. {
  232. hr = NOERROR;
  233. this->PrepareScanner(false);
  234. m_length = encodedCharCount;
  235. m_originalLength = encodedCharCount;
  236. // make sure deferred parsing is turned off
  237. ULONG grfscr = fscrNil;
  238. // Give the scanner the source and get the first token
  239. m_pscan->SetText(pszSrc, 0, encodedCharCount, 0, grfscr);
  240. m_pscan->SetYieldIsKeywordRegion(isGenerator);
  241. m_pscan->SetAwaitIsKeywordRegion(isAsync);
  242. m_pscan->Scan();
  243. uint nestedCount = 0;
  244. m_pnestedCount = &nestedCount;
  245. ParseNodePtr pnodeScope = nullptr;
  246. m_ppnodeScope = &pnodeScope;
  247. m_ppnodeExprScope = nullptr;
  248. uint nextFunctionId = 0;
  249. m_nextFunctionId = &nextFunctionId;
  250. m_inDeferredNestedFunc = false;
  251. m_deferringAST = true;
  252. m_nextBlockId = 0;
  253. ParseNode *pnodeFnc = CreateNode(knopFncDecl);
  254. pnodeFnc->AsParseNodeFnc()->ClearFlags();
  255. pnodeFnc->AsParseNodeFnc()->SetDeclaration(false);
  256. pnodeFnc->AsParseNodeFnc()->functionId = 0;
  257. pnodeFnc->AsParseNodeFnc()->astSize = 0;
  258. pnodeFnc->AsParseNodeFnc()->pnodeVars = nullptr;
  259. pnodeFnc->AsParseNodeFnc()->pnodeParams = nullptr;
  260. pnodeFnc->AsParseNodeFnc()->pnodeBody = nullptr;
  261. pnodeFnc->AsParseNodeFnc()->pnodeName = nullptr;
  262. pnodeFnc->AsParseNodeFnc()->pnodeRest = nullptr;
  263. pnodeFnc->AsParseNodeFnc()->deferredStub = nullptr;
  264. pnodeFnc->AsParseNodeFnc()->SetIsGenerator(isGenerator);
  265. pnodeFnc->AsParseNodeFnc()->SetIsAsync(isAsync);
  266. m_ppnodeVar = &pnodeFnc->AsParseNodeFnc()->pnodeVars;
  267. m_currentNodeFunc = pnodeFnc;
  268. m_currentNodeDeferredFunc = NULL;
  269. m_sourceContextInfo = nullptr;
  270. AssertMsg(m_pstmtCur == NULL, "Statement stack should be empty when we start parse function body");
  271. ParseNodePtr block = StartParseBlock<false>(PnodeBlockType::Function, ScopeType_FunctionBody);
  272. (this->*validateFunction)();
  273. FinishParseBlock(block);
  274. pnodeFnc->ichLim = m_pscan->IchLimTok();
  275. pnodeFnc->AsParseNodeFnc()->cbLim = m_pscan->IecpLimTok();
  276. pnodeFnc->AsParseNodeFnc()->pnodeVars = nullptr;
  277. // there should be nothing after successful parsing for a given construct
  278. if (m_token.tk != tkEOF)
  279. Error(ERRsyntax);
  280. RELEASEPTR(m_pscan);
  281. m_deferringAST = fDeferSave;
  282. }
  283. catch(ParseExceptionObject& e)
  284. {
  285. m_deferringAST = fDeferSave;
  286. hr = e.GetError();
  287. }
  288. if (nullptr != pse && FAILED(hr))
  289. {
  290. hr = pse->ProcessError(m_pscan, hr, /* pnodeBase */ NULL);
  291. }
  292. return hr;
  293. }
  294. HRESULT Parser::ParseSourceInternal(
  295. __out ParseNodePtr* parseTree, LPCUTF8 pszSrc, size_t offsetInBytes, size_t encodedCharCount, charcount_t offsetInChars,
  296. bool fromExternal, ULONG grfscr, CompileScriptException *pse, Js::LocalFunctionId * nextFunctionId, ULONG lineNumber, SourceContextInfo * sourceContextInfo)
  297. {
  298. AssertMem(parseTree);
  299. AssertPsz(pszSrc);
  300. AssertMemN(pse);
  301. if (this->IsBackgroundParser())
  302. {
  303. PROBE_STACK_NO_DISPOSE(m_scriptContext, Js::Constants::MinStackDefault);
  304. }
  305. else
  306. {
  307. PROBE_STACK(m_scriptContext, Js::Constants::MinStackDefault);
  308. }
  309. #ifdef PROFILE_EXEC
  310. m_scriptContext->ProfileBegin(Js::ParsePhase);
  311. #endif
  312. JS_ETW_INTERNAL(EventWriteJSCRIPT_PARSE_START(m_scriptContext,0));
  313. *parseTree = NULL;
  314. m_sourceLim = 0;
  315. m_grfscr = grfscr;
  316. m_sourceContextInfo = sourceContextInfo;
  317. ParseNodePtr pnodeBase = NULL;
  318. HRESULT hr;
  319. SmartFPUControl smartFpuControl;
  320. try
  321. {
  322. this->PrepareScanner(fromExternal);
  323. if ((grfscr & fscrEvalCode) != 0)
  324. {
  325. this->m_parsingSuperRestrictionState = Parser::ParsingSuperRestrictionState_SuperPropertyAllowed;
  326. }
  327. if ((grfscr & fscrIsModuleCode) != 0)
  328. {
  329. // Module source flag should not be enabled unless module is enabled
  330. Assert(m_scriptContext->GetConfig()->IsES6ModuleEnabled());
  331. // Module code is always strict mode code.
  332. this->m_fUseStrictMode = TRUE;
  333. }
  334. // parse the source
  335. pnodeBase = Parse(pszSrc, offsetInBytes, encodedCharCount, offsetInChars, grfscr, lineNumber, nextFunctionId, pse);
  336. AssertNodeMem(pnodeBase);
  337. // Record the actual number of words parsed.
  338. m_sourceLim = pnodeBase->ichLim - offsetInChars;
  339. // TODO: The assert can be false positive in some scenarios and chuckj to fix it later
  340. // Assert(utf8::ByteIndexIntoCharacterIndex(pszSrc + offsetInBytes, encodedCharCount, fromExternal ? utf8::doDefault : utf8::doAllowThreeByteSurrogates) == m_sourceLim);
  341. #if DBG_DUMP
  342. if (Js::Configuration::Global.flags.Trace.IsEnabled(Js::ParsePhase))
  343. {
  344. PrintPnodeWIndent(pnodeBase,4);
  345. fflush(stdout);
  346. }
  347. #endif
  348. *parseTree = pnodeBase;
  349. hr = NOERROR;
  350. }
  351. catch(ParseExceptionObject& e)
  352. {
  353. hr = e.GetError();
  354. }
  355. catch (Js::AsmJsParseException&)
  356. {
  357. hr = JSERR_AsmJsCompileError;
  358. }
  359. if (FAILED(hr))
  360. {
  361. hr = pse->ProcessError(m_pscan, hr, pnodeBase);
  362. }
  363. #if ENABLE_BACKGROUND_PARSING
  364. if (this->m_hasParallelJob)
  365. {
  366. ///// Wait here for remaining jobs to finish. Then look for errors, do final const bindings.
  367. // pleath TODO: If there are remaining jobs, let the main thread help finish them.
  368. BackgroundParser *bgp = m_scriptContext->GetBackgroundParser();
  369. Assert(bgp);
  370. CompileScriptException se;
  371. this->WaitForBackgroundJobs(bgp, &se);
  372. BackgroundParseItem *failedItem = bgp->GetFailedBackgroundParseItem();
  373. if (failedItem)
  374. {
  375. CompileScriptException *bgPse = failedItem->GetPSE();
  376. Assert(bgPse);
  377. *pse = *bgPse;
  378. hr = failedItem->GetHR();
  379. bgp->SetFailedBackgroundParseItem(nullptr);
  380. }
  381. if (this->fastScannedRegExpNodes != nullptr)
  382. {
  383. this->FinishBackgroundRegExpNodes();
  384. }
  385. for (BackgroundParseItem *item = this->backgroundParseItems; item; item = item->GetNext())
  386. {
  387. Parser *parser = item->GetParser();
  388. parser->FinishBackgroundPidRefs(item, this != parser);
  389. }
  390. }
  391. #endif
  392. // done with the scanner
  393. RELEASEPTR(m_pscan);
  394. #ifdef PROFILE_EXEC
  395. m_scriptContext->ProfileEnd(Js::ParsePhase);
  396. #endif
  397. JS_ETW_INTERNAL(EventWriteJSCRIPT_PARSE_STOP(m_scriptContext, 0));
  398. return hr;
  399. }
  400. #if ENABLE_BACKGROUND_PARSING
  401. void Parser::WaitForBackgroundJobs(BackgroundParser *bgp, CompileScriptException *pse)
  402. {
  403. // The scan of the script is done, but there may be unfinished background jobs in the queue.
  404. // Enlist the main thread to help with those.
  405. BackgroundParseItem *item;
  406. if (!*bgp->GetPendingBackgroundItemsPtr())
  407. {
  408. // We're done.
  409. return;
  410. }
  411. // Save parser state, since we'll need to restore it in order to bind references correctly later.
  412. this->m_isInBackground = true;
  413. this->SetCurrBackgroundParseItem(nullptr);
  414. uint blockIdSave = this->m_nextBlockId;
  415. uint functionIdSave = *this->m_nextFunctionId;
  416. StmtNest *pstmtSave = this->m_pstmtCur;
  417. if (!bgp->Processor()->ProcessesInBackground())
  418. {
  419. // No background thread. Just walk the jobs with no locking and process them.
  420. for (item = bgp->GetNextUnprocessedItem(); item; item = bgp->GetNextUnprocessedItem())
  421. {
  422. bgp->Processor()->RemoveJob(item);
  423. bool succeeded = bgp->Process(item, this, pse);
  424. bgp->JobProcessed(item, succeeded);
  425. }
  426. Assert(!*bgp->GetPendingBackgroundItemsPtr());
  427. }
  428. else
  429. {
  430. // Background threads. We need to have the critical section in order to:
  431. // - Check for unprocessed jobs;
  432. // - Remove jobs from the processor queue;
  433. // - Do JobsProcessed work (such as removing jobs from the BackgroundParser's unprocessed list).
  434. CriticalSection *pcs = static_cast<JsUtil::BackgroundJobProcessor*>(bgp->Processor())->GetCriticalSection();
  435. pcs->Enter();
  436. for (;;)
  437. {
  438. // Grab a job (in lock)
  439. item = bgp->GetNextUnprocessedItem();
  440. if (item == nullptr)
  441. {
  442. break;
  443. }
  444. bgp->Processor()->RemoveJob(item);
  445. pcs->Leave();
  446. // Process job (if there is one) (outside lock)
  447. bool succeeded = bgp->Process(item, this, pse);
  448. pcs->Enter();
  449. bgp->JobProcessed(item, succeeded);
  450. }
  451. pcs->Leave();
  452. // Wait for the background threads to finish jobs they're already processing (if any).
  453. // TODO: Replace with a proper semaphore.
  454. while(*bgp->GetPendingBackgroundItemsPtr());
  455. }
  456. Assert(!*bgp->GetPendingBackgroundItemsPtr());
  457. // Restore parser state.
  458. this->m_pstmtCur = pstmtSave;
  459. this->m_isInBackground = false;
  460. this->m_nextBlockId = blockIdSave;
  461. *this->m_nextFunctionId = functionIdSave;
  462. }
  463. void Parser::FinishBackgroundPidRefs(BackgroundParseItem *item, bool isOtherParser)
  464. {
  465. for (BlockInfoStack *blockInfo = item->GetParseContext()->currentBlockInfo; blockInfo; blockInfo = blockInfo->pBlockInfoOuter)
  466. {
  467. if (isOtherParser)
  468. {
  469. this->BindPidRefs<true>(blockInfo, item->GetMaxBlockId());
  470. }
  471. else
  472. {
  473. this->BindPidRefs<false>(blockInfo, item->GetMaxBlockId());
  474. }
  475. }
  476. }
  477. void Parser::FinishBackgroundRegExpNodes()
  478. {
  479. // We have a list of RegExp nodes that we saw on the UI thread in functions we're parallel parsing,
  480. // and for each background job we have a list of RegExp nodes for which we couldn't allocate patterns.
  481. // We need to copy the pattern pointers from the UI thread nodes to the corresponding nodes on the
  482. // background nodes.
  483. // There may be UI thread nodes for which there are no background thread equivalents, because the UI thread
  484. // has to assume that the background thread won't defer anything.
  485. // Note that because these lists (and the list of background jobs) are SList's built by prepending, they are
  486. // all in reverse lexical order.
  487. Assert(!this->IsBackgroundParser());
  488. Assert(this->fastScannedRegExpNodes);
  489. Assert(this->backgroundParseItems != nullptr);
  490. BackgroundParseItem *currBackgroundItem;
  491. #if DBG
  492. for (currBackgroundItem = this->backgroundParseItems;
  493. currBackgroundItem;
  494. currBackgroundItem = currBackgroundItem->GetNext())
  495. {
  496. if (currBackgroundItem->RegExpNodeList())
  497. {
  498. FOREACH_DLIST_ENTRY(ParseNodePtr, ArenaAllocator, pnode, currBackgroundItem->RegExpNodeList())
  499. {
  500. Assert(pnode->AsParseNodePid()->regexPattern == nullptr);
  501. }
  502. NEXT_DLIST_ENTRY;
  503. }
  504. }
  505. #endif
  506. // Hook up the patterns allocated on the main thread to the nodes created on the background thread.
  507. // Walk the list of foreground nodes, advancing through the work items and looking up each item.
  508. // Note that the background thread may have chosen to defer a given RegEx literal, so not every foreground
  509. // node will have a matching background node. Doesn't matter for correctness.
  510. // (It's inefficient, of course, to have to restart the inner loop from the beginning of the work item's
  511. // list, but it should be unusual to have many RegExes in a single work item's chunk of code. Figure out how
  512. // to start the inner loop from a known internal node within the list if that turns out to be important.)
  513. currBackgroundItem = this->backgroundParseItems;
  514. FOREACH_DLIST_ENTRY(ParseNodePtr, ArenaAllocator, pnodeFgnd, this->fastScannedRegExpNodes)
  515. {
  516. Assert(pnodeFgnd->nop == knopRegExp);
  517. Assert(pnodeFgnd->AsParseNodePid()->regexPattern != nullptr);
  518. bool quit = false;
  519. while (!quit)
  520. {
  521. // Find the next work item with a RegEx in it.
  522. while (currBackgroundItem && currBackgroundItem->RegExpNodeList() == nullptr)
  523. {
  524. currBackgroundItem = currBackgroundItem->GetNext();
  525. }
  526. if (!currBackgroundItem)
  527. {
  528. break;
  529. }
  530. // Walk the RegExps in the work item.
  531. FOREACH_DLIST_ENTRY(ParseNodePtr, ArenaAllocator, pnodeBgnd, currBackgroundItem->RegExpNodeList())
  532. {
  533. Assert(pnodeBgnd->nop == knopRegExp);
  534. if (pnodeFgnd->ichMin <= pnodeBgnd->ichMin)
  535. {
  536. // Either we found a match, or the next background node is past the foreground node.
  537. // In any case, we can stop searching.
  538. if (pnodeFgnd->ichMin == pnodeBgnd->ichMin)
  539. {
  540. Assert(pnodeFgnd->ichLim == pnodeBgnd->ichLim);
  541. pnodeBgnd->AsParseNodePid()->regexPattern = pnodeFgnd->AsParseNodePid()->regexPattern;
  542. }
  543. quit = true;
  544. break;
  545. }
  546. }
  547. NEXT_DLIST_ENTRY;
  548. if (!quit)
  549. {
  550. // Need to advance to the next work item.
  551. currBackgroundItem = currBackgroundItem->GetNext();
  552. }
  553. }
  554. }
  555. NEXT_DLIST_ENTRY;
  556. #if DBG
  557. for (currBackgroundItem = this->backgroundParseItems;
  558. currBackgroundItem;
  559. currBackgroundItem = currBackgroundItem->GetNext())
  560. {
  561. if (currBackgroundItem->RegExpNodeList())
  562. {
  563. FOREACH_DLIST_ENTRY(ParseNodePtr, ArenaAllocator, pnode, currBackgroundItem->RegExpNodeList())
  564. {
  565. Assert(pnode->AsParseNodePid()->regexPattern != nullptr);
  566. }
  567. NEXT_DLIST_ENTRY;
  568. }
  569. }
  570. #endif
  571. }
  572. #endif
  573. LabelId* Parser::CreateLabelId(IdentPtr pid)
  574. {
  575. LabelId* pLabelId;
  576. pLabelId = (LabelId*)m_nodeAllocator.Alloc(sizeof(LabelId));
  577. if (NULL == pLabelId)
  578. Error(ERRnoMemory);
  579. pLabelId->pid = pid;
  580. pLabelId->next = NULL;
  581. return pLabelId;
  582. }
  583. /*****************************************************************************
  584. The following set of routines allocate parse tree nodes of various kinds.
  585. They catch an exception on out of memory.
  586. *****************************************************************************/
  587. static const int g_mpnopcbNode[] =
  588. {
  589. #define PTNODE(nop,sn,pc,nk,ok,json) kcbPn##nk,
  590. #include "ptlist.h"
  591. };
  592. // Create nodes using Arena
  593. ParseNodePtr
  594. Parser::StaticCreateBlockNode(ArenaAllocator* alloc, charcount_t ichMin , charcount_t ichLim, int blockId, PnodeBlockType blockType)
  595. {
  596. ParseNodeBlock* pnode = reinterpret_cast<ParseNodeBlock*>(StaticAllocNode<knopBlock>(alloc));
  597. pnode->Init(blockId, blockType, ichMin, ichLim);
  598. return pnode;
  599. }
  600. // Create Node with limit
  601. template <OpCode nop>
  602. ParseNodePtr Parser::CreateNodeT(charcount_t ichMin,charcount_t ichLim)
  603. {
  604. Assert(!this->m_deferringAST);
  605. ParseNodePtr pnode = StaticCreateNodeT<nop>(&m_nodeAllocator, ichMin, ichLim);
  606. Assert(m_pCurrentAstSize != NULL);
  607. *m_pCurrentAstSize += GetNodeSize<nop>();
  608. return pnode;
  609. }
  610. ParseNodePtr Parser::CreateDeclNode(OpCode nop, IdentPtr pid, SymbolType symbolType, bool errorOnRedecl)
  611. {
  612. ParseNodePtr pnode = CreateNode(nop);
  613. pnode->AsParseNodeVar()->InitDeclNode(pid, NULL);
  614. if (symbolType != STUnknown)
  615. {
  616. pnode->AsParseNodeVar()->sym = AddDeclForPid(pnode, pid, symbolType, errorOnRedecl);
  617. }
  618. return pnode;
  619. }
  620. Symbol* Parser::AddDeclForPid(ParseNodePtr pnode, IdentPtr pid, SymbolType symbolType, bool errorOnRedecl)
  621. {
  622. Assert(pnode->IsVarLetOrConst());
  623. PidRefStack *refForUse = nullptr, *refForDecl = nullptr;
  624. BlockInfoStack *blockInfo;
  625. bool fBlockScope = false;
  626. if (pnode->nop != knopVarDecl || symbolType == STFunction)
  627. {
  628. Assert(m_pstmtCur);
  629. if (m_pstmtCur->GetNop() != knopBlock)
  630. {
  631. // Let/const declared in a bare statement context.
  632. Error(ERRDeclOutOfStmt);
  633. }
  634. if (m_pstmtCur->pstmtOuter && m_pstmtCur->pstmtOuter->GetNop() == knopSwitch)
  635. {
  636. // Let/const declared inside a switch block (requiring conservative use-before-decl check).
  637. pnode->AsParseNodeVar()->isSwitchStmtDecl = true;
  638. }
  639. fBlockScope = pnode->nop != knopVarDecl ||
  640. (
  641. !GetCurrentBlockInfo()->pnodeBlock->AsParseNodeBlock()->scope ||
  642. GetCurrentBlockInfo()->pnodeBlock->AsParseNodeBlock()->scope->GetScopeType() != ScopeType_GlobalEvalBlock
  643. );
  644. }
  645. if (fBlockScope)
  646. {
  647. blockInfo = GetCurrentBlockInfo();
  648. }
  649. else
  650. {
  651. blockInfo = GetCurrentFunctionBlockInfo();
  652. }
  653. refForDecl = this->FindOrAddPidRef(pid, blockInfo->pnodeBlock->AsParseNodeBlock()->blockId, GetCurrentFunctionNode()->AsParseNodeFnc()->functionId);
  654. if (refForDecl == nullptr)
  655. {
  656. Error(ERRnoMemory);
  657. }
  658. if (refForDecl->funcId != GetCurrentFunctionNode()->AsParseNodeFnc()->functionId)
  659. {
  660. // Fix up the function id, which is incorrect if we're reparsing lambda parameters
  661. Assert(this->m_reparsingLambdaParams);
  662. refForDecl->funcId = GetCurrentFunctionNode()->AsParseNodeFnc()->functionId;
  663. }
  664. if (blockInfo == GetCurrentBlockInfo())
  665. {
  666. refForUse = refForDecl;
  667. }
  668. else
  669. {
  670. refForUse = this->PushPidRef(pid);
  671. }
  672. pnode->AsParseNodeVar()->symRef = refForUse->GetSymRef();
  673. Symbol *sym = refForDecl->GetSym();
  674. if (sym != nullptr)
  675. {
  676. // Multiple declarations in the same scope. 3 possibilities: error, existing one wins, new one wins.
  677. switch (pnode->nop)
  678. {
  679. case knopLetDecl:
  680. case knopConstDecl:
  681. if (!sym->GetDecl()->AsParseNodeVar()->isBlockScopeFncDeclVar && !sym->IsArguments())
  682. {
  683. // If the built-in arguments is shadowed then don't throw
  684. Assert(errorOnRedecl);
  685. // Redeclaration error.
  686. Error(ERRRedeclaration);
  687. }
  688. else
  689. {
  690. // (New) let/const hides the (old) var
  691. sym->SetSymbolType(symbolType);
  692. sym->SetDecl(pnode);
  693. }
  694. break;
  695. case knopVarDecl:
  696. if (m_currentScope->GetScopeType() == ScopeType_Parameter && !sym->IsArguments())
  697. {
  698. // If this is a parameter list, mark the scope to indicate that it has duplicate definition unless it is shadowing the default arguments symbol.
  699. // 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.
  700. m_currentScope->SetHasDuplicateFormals();
  701. }
  702. if (sym->GetDecl() == nullptr)
  703. {
  704. sym->SetDecl(pnode);
  705. break;
  706. }
  707. switch (sym->GetDecl()->nop)
  708. {
  709. case knopLetDecl:
  710. case knopConstDecl:
  711. // Destructuring made possible to have the formals to be the let bind. But that shouldn't throw the error.
  712. if (errorOnRedecl && (!IsES6DestructuringEnabled() || sym->GetSymbolType() != STFormal))
  713. {
  714. Error(ERRRedeclaration);
  715. }
  716. // If !errorOnRedecl, (old) let/const hides the (new) var, so do nothing.
  717. break;
  718. case knopVarDecl:
  719. // Legal redeclaration. Who wins?
  720. if (errorOnRedecl || sym->GetDecl()->AsParseNodeVar()->isBlockScopeFncDeclVar || sym->IsArguments())
  721. {
  722. if (symbolType == STFormal ||
  723. (symbolType == STFunction && sym->GetSymbolType() != STFormal) ||
  724. sym->GetSymbolType() == STVariable)
  725. {
  726. // New decl wins.
  727. sym->SetSymbolType(symbolType);
  728. sym->SetDecl(pnode);
  729. }
  730. }
  731. break;
  732. }
  733. break;
  734. }
  735. }
  736. else
  737. {
  738. Scope *scope = blockInfo->pnodeBlock->AsParseNodeBlock()->scope;
  739. if (scope == nullptr)
  740. {
  741. Assert(blockInfo->pnodeBlock->AsParseNodeBlock()->blockType == PnodeBlockType::Regular);
  742. scope = Anew(&m_nodeAllocator, Scope, &m_nodeAllocator, ScopeType_Block);
  743. if (this->IsCurBlockInLoop())
  744. {
  745. scope->SetIsBlockInLoop();
  746. }
  747. blockInfo->pnodeBlock->AsParseNodeBlock()->scope = scope;
  748. PushScope(scope);
  749. }
  750. ParseNodePtr pnodeFnc = GetCurrentFunctionNode();
  751. if (scope->GetScopeType() == ScopeType_GlobalEvalBlock)
  752. {
  753. Assert(fBlockScope);
  754. Assert(scope->GetEnclosingScope() == m_currentNodeProg->AsParseNodeProg()->scope);
  755. // Check for same-named decl in Global scope.
  756. CheckRedeclarationErrorForBlockId(pid, 0);
  757. }
  758. else if (scope->GetScopeType() == ScopeType_Global && (this->m_grfscr & fscrEvalCode) &&
  759. !(m_functionBody && m_functionBody->GetScopeInfo()))
  760. {
  761. // Check for same-named decl in GlobalEvalBlock scope. Note that this is not necessary
  762. // if we're compiling a deferred nested function and the global scope was restored from cached info,
  763. // because in that case we don't need a GlobalEvalScope.
  764. Assert(!fBlockScope || (this->m_grfscr & fscrConsoleScopeEval) == fscrConsoleScopeEval);
  765. CheckRedeclarationErrorForBlockId(pid, 1);
  766. }
  767. else if (!pnodeFnc->AsParseNodeFnc()->IsBodyAndParamScopeMerged()
  768. && scope->GetScopeType() == ScopeType_FunctionBody
  769. && (pnode->nop == knopLetDecl || pnode->nop == knopConstDecl))
  770. {
  771. // In case of split scope function when we add a new let or const declaration to the body
  772. // we have to check whether the param scope already has the same symbol defined.
  773. CheckRedeclarationErrorForBlockId(pid, pnodeFnc->AsParseNodeFnc()->pnodeScopes->AsParseNodeBlock()->blockId);
  774. }
  775. if (!sym)
  776. {
  777. const char16 *name = reinterpret_cast<const char16*>(pid->Psz());
  778. int nameLength = pid->Cch();
  779. SymbolName const symName(name, nameLength);
  780. Assert(!scope->FindLocalSymbol(symName));
  781. sym = Anew(&m_nodeAllocator, Symbol, symName, pnode, symbolType);
  782. scope->AddNewSymbol(sym);
  783. sym->SetPid(pid);
  784. }
  785. refForDecl->SetSym(sym);
  786. }
  787. return sym;
  788. }
  789. void Parser::CheckRedeclarationErrorForBlockId(IdentPtr pid, int blockId)
  790. {
  791. // If the ref stack entry for the blockId contains a sym then throw redeclaration error
  792. PidRefStack *pidRefOld = pid->GetPidRefForScopeId(blockId);
  793. if (pidRefOld && pidRefOld->GetSym() && !pidRefOld->GetSym()->IsArguments())
  794. {
  795. Error(ERRRedeclaration);
  796. }
  797. }
  798. bool Parser::IsCurBlockInLoop() const
  799. {
  800. for (StmtNest *stmt = this->m_pstmtCur; stmt != nullptr; stmt = stmt->pstmtOuter)
  801. {
  802. OpCode nop = stmt->GetNop();
  803. if (ParseNode::Grfnop(nop) & fnopContinue)
  804. {
  805. return true;
  806. }
  807. if (nop == knopFncDecl)
  808. {
  809. return false;
  810. }
  811. }
  812. return false;
  813. }
  814. void Parser::RestorePidRefForSym(Symbol *sym)
  815. {
  816. IdentPtr pid = m_pscan->m_phtbl->PidHashNameLen(sym->GetName().GetBuffer(), sym->GetName().GetLength());
  817. Assert(pid);
  818. sym->SetPid(pid);
  819. PidRefStack *ref = this->PushPidRef(pid);
  820. ref->SetSym(sym);
  821. }
  822. IdentPtr Parser::PidFromNode(ParseNodePtr pnode)
  823. {
  824. for (;;)
  825. {
  826. switch (pnode->nop)
  827. {
  828. case knopName:
  829. return pnode->AsParseNodePid()->pid;
  830. case knopVarDecl:
  831. return pnode->AsParseNodeVar()->pid;
  832. case knopDot:
  833. Assert(pnode->AsParseNodeBin()->pnode2->nop == knopName);
  834. return pnode->AsParseNodeBin()->pnode2->AsParseNodePid()->pid;
  835. case knopComma:
  836. // Advance to the RHS and iterate.
  837. pnode = pnode->AsParseNodeBin()->pnode2;
  838. break;
  839. default:
  840. return nullptr;
  841. }
  842. }
  843. }
  844. #if DBG
  845. void VerifyNodeSize(OpCode nop, int size)
  846. {
  847. Assert(nop >= 0 && nop < knopLim);
  848. __analysis_assume(nop < knopLim);
  849. Assert(g_mpnopcbNode[nop] == size);
  850. }
  851. #endif
  852. ParseNodePtr Parser::StaticCreateSuperReferenceNode(OpCode nop,
  853. ParseNodePtr pnode1,
  854. ParseNodePtr pnode2,
  855. ArenaAllocator* alloc)
  856. {
  857. return StaticCreateBinNode(nop, pnode1, pnode2, alloc, kcbPnSuperReference, knopSuperReference);
  858. }
  859. ParseNodePtr Parser::StaticCreateBinNode(OpCode nop,
  860. ParseNodePtr pnode1,
  861. ParseNodePtr pnode2,
  862. ArenaAllocator* alloc)
  863. {
  864. return StaticCreateBinNode(nop, pnode1, pnode2, alloc, kcbPnBin, nop);
  865. }
  866. ParseNodePtr Parser::StaticCreateBinNode(OpCode nop,
  867. ParseNodePtr pnode1,
  868. ParseNodePtr pnode2,
  869. ArenaAllocator* alloc,
  870. int allocSize,
  871. OpCode nopForSize)
  872. {
  873. DebugOnly(VerifyNodeSize(nopForSize, allocSize));
  874. ParseNodePtr pnode = (ParseNodePtr)alloc->Alloc(allocSize);
  875. pnode->Init(nop, 0 /*ichMin*/, 0 /*ichLim*/);
  876. pnode->AsParseNodeBin()->pnodeNext = nullptr;
  877. pnode->AsParseNodeBin()->pnode1 = pnode1;
  878. pnode->AsParseNodeBin()->pnode2 = pnode2;
  879. // Statically detect if the add is a concat
  880. if (!PHASE_OFF1(Js::ByteCodeConcatExprOptPhase))
  881. {
  882. // We can't flatten the concat expression if the LHS is not a flatten concat already
  883. // e.g. a + (<str> + b)
  884. // Side effect of ToStr(b) need to happen first before ToStr(a)
  885. // If we flatten the concat expression, we will do ToStr(a) before ToStr(b)
  886. if ((nop == knopAdd) && (pnode1->CanFlattenConcatExpr() || pnode2->nop == knopStr))
  887. {
  888. pnode->grfpn |= fpnCanFlattenConcatExpr;
  889. }
  890. }
  891. return pnode;
  892. }
  893. // Create nodes using parser allocator
  894. ParseNodePtr Parser::CreateBlockNode(PnodeBlockType blockType)
  895. {
  896. ParseNodePtr pnode = CreateNode(knopBlock);
  897. pnode->AsParseNodeBlock()->Init(m_nextBlockId++, blockType, pnode->ichMin, pnode->ichLim);
  898. return pnode;
  899. }
  900. ParseNodePtr Parser::CreateNode(OpCode nop, charcount_t ichMin)
  901. {
  902. bool nodeAllowed = IsNodeAllowedInCurrentDeferralState(nop);
  903. Assert(nodeAllowed);
  904. Assert(nop >= 0 && nop < knopLim);
  905. ParseNodePtr pnode;
  906. int cb = (nop >= knopNone && nop < knopLim) ? g_mpnopcbNode[nop] : g_mpnopcbNode[knopEmpty];
  907. pnode = (ParseNodePtr)m_nodeAllocator.Alloc(cb);
  908. Assert(pnode != nullptr);
  909. if (!m_deferringAST)
  910. {
  911. Assert(m_pCurrentAstSize != nullptr);
  912. *m_pCurrentAstSize += cb;
  913. }
  914. pnode->Init(nop, ichMin, (m_pscan != nullptr) ? m_pscan->IchLimTok() : 0 /*ichLim*/);
  915. return pnode;
  916. }
  917. ParseNodePtr Parser::CreateUniNode(OpCode nop, ParseNodePtr pnode1)
  918. {
  919. Assert(!this->m_deferringAST);
  920. DebugOnly(VerifyNodeSize(nop, kcbPnUni));
  921. ParseNodePtr pnode = (ParseNodePtr)m_nodeAllocator.Alloc(kcbPnUni);
  922. Assert(m_pCurrentAstSize != nullptr);
  923. *m_pCurrentAstSize += kcbPnUni;
  924. pnode->Init(nop, 0 /*ichMin*/, 0 /*ichLim*/);
  925. pnode->AsParseNodeUni()->pnode1 = pnode1;
  926. if (nullptr == pnode1)
  927. {
  928. // no ops
  929. pnode->ichMin = m_pscan->IchMinTok();
  930. pnode->ichLim = m_pscan->IchLimTok();
  931. }
  932. else
  933. {
  934. // 1 op
  935. pnode->ichMin = pnode1->ichMin;
  936. pnode->ichLim = pnode1->ichLim;
  937. this->CheckArguments(pnode);
  938. }
  939. return pnode;
  940. }
  941. ParseNodePtr Parser::CreateBinNode(OpCode nop, ParseNodePtr pnode1, ParseNodePtr pnode2)
  942. {
  943. Assert(!this->m_deferringAST);
  944. charcount_t ichMin;
  945. charcount_t ichLim;
  946. if (nullptr == pnode1)
  947. {
  948. // no ops
  949. Assert(nullptr == pnode2);
  950. ichMin = m_pscan->IchMinTok();
  951. ichLim = m_pscan->IchLimTok();
  952. }
  953. else
  954. {
  955. if (nullptr == pnode2)
  956. {
  957. // 1 op
  958. ichMin = pnode1->ichMin;
  959. ichLim = pnode1->ichLim;
  960. }
  961. else
  962. {
  963. // 2 ops
  964. ichMin = pnode1->ichMin;
  965. ichLim = pnode2->ichLim;
  966. if (nop != knopDot && nop != knopIndex)
  967. {
  968. this->CheckArguments(pnode2);
  969. }
  970. }
  971. if (nop != knopDot && nop != knopIndex)
  972. {
  973. this->CheckArguments(pnode1);
  974. }
  975. }
  976. return CreateBinNode(nop, pnode1, pnode2, ichMin, ichLim);
  977. }
  978. ParseNodePtr Parser::CreateSuperReferenceNode(OpCode nop, ParseNodePtr pnode1, ParseNodePtr pnode2)
  979. {
  980. Assert(!this->m_deferringAST);
  981. Assert(pnode1 && pnode1->isSpecialName && pnode1->AsParseNodeSpecialName()->isSuper);
  982. Assert(pnode2 != nullptr);
  983. Assert(nop == knopDot || nop == knopIndex);
  984. ParseNodePtr pnode = StaticCreateSuperReferenceNode(nop, pnode1, pnode2, &m_nodeAllocator);
  985. Assert(m_pCurrentAstSize != NULL);
  986. *m_pCurrentAstSize += kcbPnSuperReference;
  987. pnode->ichMin = pnode1->ichMin;
  988. pnode->ichLim = pnode2->ichLim;
  989. pnode->AsParseNodeSuperReference()->pnodeThis = nullptr;
  990. return pnode;
  991. }
  992. ParseNodePtr Parser::CreateTriNode(OpCode nop, ParseNodePtr pnode1,
  993. ParseNodePtr pnode2, ParseNodePtr pnode3)
  994. {
  995. charcount_t ichMin;
  996. charcount_t ichLim;
  997. if (nullptr == pnode1)
  998. {
  999. // no ops
  1000. Assert(nullptr == pnode2);
  1001. Assert(nullptr == pnode3);
  1002. ichMin = m_pscan->IchMinTok();
  1003. ichLim = m_pscan->IchLimTok();
  1004. }
  1005. else if (nullptr == pnode2)
  1006. {
  1007. // 1 op
  1008. Assert(nullptr == pnode3);
  1009. ichMin = pnode1->ichMin;
  1010. ichLim = pnode1->ichLim;
  1011. }
  1012. else if (nullptr == pnode3)
  1013. {
  1014. // 2 op
  1015. ichMin = pnode1->ichMin;
  1016. ichLim = pnode2->ichLim;
  1017. }
  1018. else
  1019. {
  1020. // 3 ops
  1021. ichMin = pnode1->ichMin;
  1022. ichLim = pnode3->ichLim;
  1023. }
  1024. return CreateTriNode(nop, pnode1, pnode2, pnode3, ichMin, ichLim);
  1025. }
  1026. ParseNodePtr Parser::CreateBlockNode(charcount_t ichMin,charcount_t ichLim, PnodeBlockType blockType)
  1027. {
  1028. return StaticCreateBlockNode(&m_nodeAllocator, ichMin, ichLim, this->m_nextBlockId++, blockType);
  1029. }
  1030. ParseNodePtr Parser::CreateStrNode(IdentPtr pid)
  1031. {
  1032. Assert(!this->m_deferringAST);
  1033. ParseNodePtr pnode = CreateNode(knopStr);
  1034. pnode->AsParseNodePid()->pid=pid;
  1035. pnode->grfpn |= PNodeFlags::fpnCanFlattenConcatExpr;
  1036. return pnode;
  1037. }
  1038. ParseNodePtr Parser::CreateIntNode(int32 lw)
  1039. {
  1040. ParseNodePtr pnode = CreateNode(knopInt);
  1041. pnode->AsParseNodeInt()->lw = lw;
  1042. return pnode;
  1043. }
  1044. // Create Node with scanner limit
  1045. template <OpCode nop>
  1046. ParseNodePtr Parser::CreateNodeWithScanner()
  1047. {
  1048. Assert(m_pscan != nullptr);
  1049. return CreateNodeWithScanner<nop>(m_pscan->IchMinTok());
  1050. }
  1051. template <OpCode nop>
  1052. ParseNodePtr Parser::CreateNodeWithScanner(charcount_t ichMin)
  1053. {
  1054. Assert(m_pscan != nullptr);
  1055. return CreateNodeT<nop>(ichMin, m_pscan->IchLimTok());
  1056. }
  1057. ParseNodePtr Parser::CreateProgNodeWithScanner(bool isModuleSource)
  1058. {
  1059. ParseNodePtr pnodeProg;
  1060. if (isModuleSource)
  1061. {
  1062. pnodeProg = CreateNodeWithScanner<knopModule>();
  1063. // knopModule is not actually handled anywhere since we would need to handle it everywhere we could
  1064. // have knopProg and it would be treated exactly the same except for import/export statements.
  1065. // We are only using it as a way to get the correct size for PnModule.
  1066. // Consider: Should we add a flag to PnProg which is false but set to true in PnModule?
  1067. // If we do, it can't be a virtual method since the parse nodes are all in a union.
  1068. pnodeProg->nop = knopProg;
  1069. }
  1070. else
  1071. {
  1072. pnodeProg = CreateNodeWithScanner<knopProg>();
  1073. }
  1074. return pnodeProg;
  1075. }
  1076. ParseNodePtr Parser::CreateCallNode(OpCode nop, ParseNodePtr pnode1, ParseNodePtr pnode2)
  1077. {
  1078. charcount_t ichMin;
  1079. charcount_t ichLim;
  1080. if (nullptr == pnode1)
  1081. {
  1082. Assert(nullptr == pnode2);
  1083. ichMin = m_pscan->IchMinTok();
  1084. ichLim = m_pscan->IchLimTok();
  1085. }
  1086. else
  1087. {
  1088. ichMin = pnode1->ichMin;
  1089. ichLim = pnode2 == nullptr ? pnode1->ichLim : pnode2->ichLim;
  1090. if (pnode1->nop == knopDot || pnode1->nop == knopIndex)
  1091. {
  1092. this->CheckArguments(pnode1->AsParseNodeBin()->pnode1);
  1093. }
  1094. }
  1095. return CreateCallNode(nop, pnode1, pnode2, ichMin, ichLim);
  1096. }
  1097. ParseNodePtr Parser::CreateCallNode(OpCode nop, ParseNodePtr pnode1, ParseNodePtr pnode2, charcount_t ichMin, charcount_t ichLim)
  1098. {
  1099. Assert(!this->m_deferringAST);
  1100. // Classes, derived from ParseNodeCall, can be created here as well,
  1101. // as long as their size matches kcbPnCall (that is, they don't add
  1102. // any data members of their own).
  1103. DebugOnly(VerifyNodeSize(nop, kcbPnCall));
  1104. CompileAssert(kcbPnCall == sizeof(ParseNodeCall));
  1105. ParseNodeCall* pnode = reinterpret_cast<ParseNodeCall*>(m_nodeAllocator.Alloc(kcbPnCall));
  1106. pnode->Init(nop, pnode1, pnode2, ichMin, ichLim);
  1107. Assert(m_pCurrentAstSize != nullptr);
  1108. *m_pCurrentAstSize += kcbPnCall;
  1109. return pnode;
  1110. }
  1111. ParseNodePtr Parser::CreateSuperCallNode(ParseNodePtr pnode1, ParseNodePtr pnode2)
  1112. {
  1113. Assert(!this->m_deferringAST);
  1114. Assert(pnode1 && pnode1->isSpecialName && pnode1->AsParseNodeSpecialName()->isSuper);
  1115. DebugOnly(VerifyNodeSize(knopSuperCall, kcbPnSuperCall));
  1116. CompileAssert(kcbPnSuperCall == sizeof(ParseNodeSuperCall));
  1117. ParseNodeSuperCall* pnode = reinterpret_cast<ParseNodeSuperCall*>(m_nodeAllocator.Alloc(kcbPnSuperCall));
  1118. pnode->Init(knopCall, pnode1, pnode2, pnode1->ichMin, pnode2 == nullptr ? pnode1->ichLim : pnode2->ichLim);
  1119. Assert(m_pCurrentAstSize != nullptr);
  1120. *m_pCurrentAstSize += kcbPnSuperCall;
  1121. return pnode;
  1122. }
  1123. ParseNodePtr Parser::CreateStrNodeWithScanner(IdentPtr pid)
  1124. {
  1125. Assert(!this->m_deferringAST);
  1126. ParseNodePtr pnode = CreateNodeWithScanner<knopStr>();
  1127. pnode->AsParseNodePid()->pid=pid;
  1128. pnode->grfpn |= PNodeFlags::fpnCanFlattenConcatExpr;
  1129. return pnode;
  1130. }
  1131. ParseNodePtr Parser::CreateIntNodeWithScanner(int32 lw)
  1132. {
  1133. Assert(!this->m_deferringAST);
  1134. ParseNodePtr pnode = CreateNodeWithScanner<knopInt>();
  1135. pnode->AsParseNodeInt()->lw = lw;
  1136. return pnode;
  1137. }
  1138. ParseNodePtr Parser::CreateTempNode(ParseNode* initExpr)
  1139. {
  1140. ParseNodePtr pnode = CreateNode(knopTemp, (charcount_t)0);
  1141. pnode->AsParseNodeVar()->pnodeInit =initExpr;
  1142. pnode->AsParseNodeVar()->pnodeNext = nullptr;
  1143. return pnode;
  1144. }
  1145. ParseNodePtr Parser::CreateTempRef(ParseNode* tempNode)
  1146. {
  1147. ParseNodePtr pnode = CreateUniNode(knopTempRef, tempNode);
  1148. return pnode;
  1149. }
  1150. void Parser::CheckPidIsValid(IdentPtr pid, bool autoArgumentsObject)
  1151. {
  1152. if (IsStrictMode())
  1153. {
  1154. // in strict mode, variable named 'eval' cannot be created
  1155. if (pid == wellKnownPropertyPids.eval)
  1156. {
  1157. Error(ERREvalUsage);
  1158. }
  1159. else if (pid == wellKnownPropertyPids.arguments && !autoArgumentsObject)
  1160. {
  1161. Error(ERRArgsUsage);
  1162. }
  1163. }
  1164. }
  1165. // CreateVarDecl needs m_ppnodeVar to be pointing to the right function.
  1166. // Post-parsing rewriting during bytecode gen may have m_ppnodeVar pointing to the last parsed function.
  1167. // This function sets up m_ppnodeVar to point to the given pnodeFnc and creates the new var declaration.
  1168. // This prevents accidentally adding var declarations to the last parsed function.
  1169. ParseNodePtr Parser::AddVarDeclNode(IdentPtr pid, ParseNodePtr pnodeFnc)
  1170. {
  1171. AnalysisAssert(pnodeFnc);
  1172. ParseNodePtr *const ppnodeVarSave = m_ppnodeVar;
  1173. m_ppnodeVar = &pnodeFnc->AsParseNodeFnc()->pnodeVars;
  1174. while (*m_ppnodeVar != nullptr)
  1175. {
  1176. m_ppnodeVar = &(*m_ppnodeVar)->AsParseNodeVar()->pnodeNext;
  1177. }
  1178. ParseNodePtr pnode = CreateVarDeclNode(pid, STUnknown, false, 0, /* checkReDecl = */ false);
  1179. m_ppnodeVar = ppnodeVarSave;
  1180. return pnode;
  1181. }
  1182. ParseNodePtr Parser::CreateModuleImportDeclNode(IdentPtr localName)
  1183. {
  1184. ParseNodePtr declNode = CreateBlockScopedDeclNode(localName, knopConstDecl);
  1185. Symbol* sym = declNode->AsParseNodeVar()->sym;
  1186. sym->SetIsModuleExportStorage(true);
  1187. sym->SetIsModuleImport(true);
  1188. return declNode;
  1189. }
  1190. ParseNodePtr Parser::CreateVarDeclNode(IdentPtr pid, SymbolType symbolType, bool autoArgumentsObject, ParseNodePtr pnodeFnc, bool errorOnRedecl)
  1191. {
  1192. ParseNodePtr pnode = CreateDeclNode(knopVarDecl, pid, symbolType, errorOnRedecl);
  1193. // Append the variable to the end of the current variable list.
  1194. AssertMem(m_ppnodeVar);
  1195. pnode->AsParseNodeVar()->pnodeNext = *m_ppnodeVar;
  1196. *m_ppnodeVar = pnode;
  1197. if (nullptr != pid)
  1198. {
  1199. // this is not a temp - make sure temps go after this node
  1200. AssertMem(pid);
  1201. m_ppnodeVar = &pnode->AsParseNodeVar()->pnodeNext;
  1202. CheckPidIsValid(pid, autoArgumentsObject);
  1203. }
  1204. return pnode;
  1205. }
  1206. ParseNodePtr Parser::CreateBlockScopedDeclNode(IdentPtr pid, OpCode nodeType)
  1207. {
  1208. Assert(nodeType == knopConstDecl || nodeType == knopLetDecl);
  1209. ParseNodePtr pnode = CreateDeclNode(nodeType, pid, STVariable, true);
  1210. if (nullptr != pid)
  1211. {
  1212. AssertMem(pid);
  1213. AddVarDeclToBlock(pnode);
  1214. CheckPidIsValid(pid);
  1215. }
  1216. return pnode;
  1217. }
  1218. void Parser::AddVarDeclToBlock(ParseNode *pnode)
  1219. {
  1220. Assert(pnode->nop == knopConstDecl || pnode->nop == knopLetDecl);
  1221. // Maintain a combined list of let and const declarations to keep
  1222. // track of declaration order.
  1223. AssertMem(m_currentBlockInfo->m_ppnodeLex);
  1224. *m_currentBlockInfo->m_ppnodeLex = pnode;
  1225. m_currentBlockInfo->m_ppnodeLex = &pnode->AsParseNodeVar()->pnodeNext;
  1226. pnode->AsParseNodeVar()->pnodeNext = nullptr;
  1227. }
  1228. void Parser::SetCurrentStatement(StmtNest *stmt)
  1229. {
  1230. m_pstmtCur = stmt;
  1231. }
  1232. template<bool buildAST>
  1233. ParseNodePtr Parser::StartParseBlockWithCapacity(PnodeBlockType blockType, ScopeType scopeType, int capacity)
  1234. {
  1235. Scope *scope = nullptr;
  1236. // Block scopes are not created lazily in the case where we're repopulating a persisted scope.
  1237. scope = Anew(&m_nodeAllocator, Scope, &m_nodeAllocator, scopeType, capacity);
  1238. PushScope(scope);
  1239. return StartParseBlockHelper<buildAST>(blockType, scope, nullptr);
  1240. }
  1241. template<bool buildAST>
  1242. ParseNodePtr Parser::StartParseBlock(PnodeBlockType blockType, ScopeType scopeType, LabelId* pLabelId)
  1243. {
  1244. Scope *scope = nullptr;
  1245. // Block scopes are created lazily when we discover block-scoped content.
  1246. if (scopeType != ScopeType_Unknown && scopeType != ScopeType_Block)
  1247. {
  1248. scope = Anew(&m_nodeAllocator, Scope, &m_nodeAllocator, scopeType);
  1249. PushScope(scope);
  1250. }
  1251. return StartParseBlockHelper<buildAST>(blockType, scope, pLabelId);
  1252. }
  1253. template<bool buildAST>
  1254. ParseNodePtr Parser::StartParseBlockHelper(PnodeBlockType blockType, Scope *scope, LabelId* pLabelId)
  1255. {
  1256. ParseNodePtr pnodeBlock = CreateBlockNode(blockType);
  1257. pnodeBlock->AsParseNodeBlock()->scope = scope;
  1258. BlockInfoStack *newBlockInfo = PushBlockInfo(pnodeBlock);
  1259. PushStmt<buildAST>(&newBlockInfo->pstmt, pnodeBlock, knopBlock, pLabelId);
  1260. return pnodeBlock;
  1261. }
  1262. void Parser::PushScope(Scope *scope)
  1263. {
  1264. Assert(scope);
  1265. scope->SetEnclosingScope(m_currentScope);
  1266. m_currentScope = scope;
  1267. }
  1268. void Parser::PopScope(Scope *scope)
  1269. {
  1270. Assert(scope == m_currentScope);
  1271. m_currentScope = scope->GetEnclosingScope();
  1272. scope->SetEnclosingScope(nullptr);
  1273. }
  1274. void Parser::PushFuncBlockScope(ParseNodePtr pnodeBlock, ParseNodePtr **ppnodeScopeSave, ParseNodePtr **ppnodeExprScopeSave)
  1275. {
  1276. // Maintain the scope tree.
  1277. pnodeBlock->AsParseNodeBlock()->pnodeScopes = nullptr;
  1278. pnodeBlock->AsParseNodeBlock()->pnodeNext = nullptr;
  1279. // Insert this block into the active list of scopes (m_ppnodeExprScope or m_ppnodeScope).
  1280. // Save the current block's "next" pointer as the new endpoint of that list.
  1281. if (m_ppnodeExprScope)
  1282. {
  1283. *ppnodeScopeSave = m_ppnodeScope;
  1284. Assert(*m_ppnodeExprScope == nullptr);
  1285. *m_ppnodeExprScope = pnodeBlock;
  1286. *ppnodeExprScopeSave = &pnodeBlock->AsParseNodeBlock()->pnodeNext;
  1287. }
  1288. else
  1289. {
  1290. Assert(m_ppnodeScope);
  1291. Assert(*m_ppnodeScope == nullptr);
  1292. *m_ppnodeScope = pnodeBlock;
  1293. *ppnodeScopeSave = &pnodeBlock->AsParseNodeBlock()->pnodeNext;
  1294. *ppnodeExprScopeSave = m_ppnodeExprScope;
  1295. }
  1296. // Advance the global scope list pointer to the new block's child list.
  1297. m_ppnodeScope = &pnodeBlock->AsParseNodeBlock()->pnodeScopes;
  1298. // Set m_ppnodeExprScope to NULL to make that list inactive.
  1299. m_ppnodeExprScope = nullptr;
  1300. }
  1301. void Parser::PopFuncBlockScope(ParseNodePtr *ppnodeScopeSave, ParseNodePtr *ppnodeExprScopeSave)
  1302. {
  1303. Assert(m_ppnodeExprScope == nullptr || *m_ppnodeExprScope == nullptr);
  1304. m_ppnodeExprScope = ppnodeExprScopeSave;
  1305. AssertMem(m_ppnodeScope);
  1306. Assert(nullptr == *m_ppnodeScope);
  1307. m_ppnodeScope = ppnodeScopeSave;
  1308. }
  1309. template<bool buildAST>
  1310. ParseNodePtr Parser::ParseBlock(LabelId* pLabelId)
  1311. {
  1312. ParseNodePtr pnodeBlock = nullptr;
  1313. ParseNodePtr *ppnodeScopeSave = nullptr;
  1314. ParseNodePtr *ppnodeExprScopeSave = nullptr;
  1315. pnodeBlock = StartParseBlock<buildAST>(PnodeBlockType::Regular, ScopeType_Block, pLabelId);
  1316. BlockInfoStack* outerBlockInfo = m_currentBlockInfo->pBlockInfoOuter;
  1317. if (outerBlockInfo != nullptr && outerBlockInfo->pnodeBlock != nullptr
  1318. && outerBlockInfo->pnodeBlock->AsParseNodeBlock()->scope != nullptr
  1319. && outerBlockInfo->pnodeBlock->AsParseNodeBlock()->scope->GetScopeType() == ScopeType_CatchParamPattern)
  1320. {
  1321. // If we are parsing the catch block then destructured params can have let declarations. Let's add them to the new block.
  1322. for (ParseNodePtr pnode = m_currentBlockInfo->pBlockInfoOuter->pnodeBlock->AsParseNodeBlock()->pnodeLexVars; pnode; pnode = pnode->AsParseNodeVar()->pnodeNext)
  1323. {
  1324. PidRefStack* ref = PushPidRef(pnode->AsParseNodeVar()->sym->GetPid());
  1325. ref->SetSym(pnode->AsParseNodeVar()->sym);
  1326. }
  1327. }
  1328. ChkCurTok(tkLCurly, ERRnoLcurly);
  1329. ParseNodePtr * ppnodeList = nullptr;
  1330. if (buildAST)
  1331. {
  1332. PushFuncBlockScope(pnodeBlock, &ppnodeScopeSave, &ppnodeExprScopeSave);
  1333. ppnodeList = &pnodeBlock->AsParseNodeBlock()->pnodeStmt;
  1334. }
  1335. ParseStmtList<buildAST>(ppnodeList);
  1336. if (buildAST)
  1337. {
  1338. PopFuncBlockScope(ppnodeScopeSave, ppnodeExprScopeSave);
  1339. }
  1340. FinishParseBlock(pnodeBlock);
  1341. ChkCurTok(tkRCurly, ERRnoRcurly);
  1342. return pnodeBlock;
  1343. }
  1344. bool Parser::IsSpecialName(IdentPtr pid)
  1345. {
  1346. return pid == wellKnownPropertyPids._this ||
  1347. pid == wellKnownPropertyPids._super ||
  1348. pid == wellKnownPropertyPids._superConstructor ||
  1349. pid == wellKnownPropertyPids._newTarget;
  1350. }
  1351. ParseNodePtr Parser::ReferenceSpecialName(IdentPtr pid, charcount_t ichMin, charcount_t ichLim, bool createNode)
  1352. {
  1353. PidRefStack* ref = this->PushPidRef(pid);
  1354. if (!createNode)
  1355. {
  1356. return nullptr;
  1357. }
  1358. ParseNode* pnode = CreateSpecialNameNode(pid);
  1359. pnode->ichMin = ichMin;
  1360. pnode->ichLim = ichLim;
  1361. pnode->AsParseNodePid()->SetSymRef(ref);
  1362. if (pid == wellKnownPropertyPids._this)
  1363. {
  1364. pnode->AsParseNodeSpecialName()->isThis = true;
  1365. }
  1366. else if (pid == wellKnownPropertyPids._super || pid == wellKnownPropertyPids._superConstructor)
  1367. {
  1368. pnode->AsParseNodeSpecialName()->isSuper = true;
  1369. }
  1370. return pnode;
  1371. }
  1372. ParseNodePtr Parser::CreateSpecialVarDeclIfNeeded(ParseNodePtr pnodeFnc, IdentPtr pid, bool forceCreate)
  1373. {
  1374. Assert(pid != nullptr);
  1375. PidRefStack* ref = pid->GetTopRef();
  1376. // If the function has a reference to pid or we set forceCreate, make a special var decl
  1377. if (forceCreate || (ref && ref->GetScopeId() >= m_currentBlockInfo->pnodeBlock->AsParseNodeBlock()->blockId))
  1378. {
  1379. return this->CreateSpecialVarDeclNode(pnodeFnc, pid);
  1380. }
  1381. return nullptr;
  1382. }
  1383. void Parser::CreateSpecialSymbolDeclarations(ParseNodePtr pnodeFnc)
  1384. {
  1385. // Lambda function cannot have any special bindings.
  1386. if (pnodeFnc->AsParseNodeFnc()->IsLambda())
  1387. {
  1388. return;
  1389. }
  1390. bool isTopLevelEventHandler = (this->m_grfscr & fscrImplicitThis || this->m_grfscr & fscrImplicitParents) && !pnodeFnc->AsParseNodeFnc()->IsNested();
  1391. // Create a 'this' symbol for non-lambda functions with references to 'this', and all class constructors and top level event hanlders.
  1392. ParseNodePtr varDeclNode = CreateSpecialVarDeclIfNeeded(pnodeFnc, wellKnownPropertyPids._this, pnodeFnc->AsParseNodeFnc()->IsClassConstructor() || isTopLevelEventHandler);
  1393. if (varDeclNode)
  1394. {
  1395. varDeclNode->AsParseNodeVar()->sym->SetIsThis(true);
  1396. if (pnodeFnc->AsParseNodeFnc()->IsDerivedClassConstructor())
  1397. {
  1398. varDeclNode->AsParseNodeVar()->sym->SetNeedDeclaration(true);
  1399. }
  1400. }
  1401. // Create a 'new.target' symbol for any ordinary function with a reference and all class constructors.
  1402. varDeclNode = CreateSpecialVarDeclIfNeeded(pnodeFnc, wellKnownPropertyPids._newTarget, pnodeFnc->AsParseNodeFnc()->IsClassConstructor());
  1403. if (varDeclNode)
  1404. {
  1405. varDeclNode->AsParseNodeVar()->sym->SetIsNewTarget(true);
  1406. }
  1407. // Create a 'super' (as a reference) symbol.
  1408. varDeclNode = CreateSpecialVarDeclIfNeeded(pnodeFnc, wellKnownPropertyPids._super);
  1409. if (varDeclNode)
  1410. {
  1411. varDeclNode->AsParseNodeVar()->sym->SetIsSuper(true);
  1412. }
  1413. // Create a 'super' (as the call target for super()) symbol only for derived class constructors.
  1414. if (pnodeFnc->AsParseNodeFnc()->IsDerivedClassConstructor())
  1415. {
  1416. varDeclNode = CreateSpecialVarDeclIfNeeded(pnodeFnc, wellKnownPropertyPids._superConstructor);
  1417. if (varDeclNode)
  1418. {
  1419. varDeclNode->AsParseNodeVar()->sym->SetIsSuperConstructor(true);
  1420. }
  1421. }
  1422. }
  1423. void Parser::FinishParseBlock(ParseNode *pnodeBlock, bool needScanRCurly)
  1424. {
  1425. Assert(m_currentBlockInfo != nullptr && pnodeBlock == m_currentBlockInfo->pnodeBlock);
  1426. if (needScanRCurly)
  1427. {
  1428. // Only update the ichLim if we were expecting an RCurly. If there is an
  1429. // expression body without a necessary RCurly, the correct ichLim will
  1430. // have been set already.
  1431. pnodeBlock->ichLim = m_pscan->IchLimTok();
  1432. }
  1433. BindPidRefs<false>(GetCurrentBlockInfo(), m_nextBlockId - 1);
  1434. PopStmt(&m_currentBlockInfo->pstmt);
  1435. PopBlockInfo();
  1436. Scope *scope = pnodeBlock->AsParseNodeBlock()->scope;
  1437. if (scope)
  1438. {
  1439. PopScope(scope);
  1440. }
  1441. }
  1442. void Parser::FinishParseFncExprScope(ParseNodePtr pnodeFnc, ParseNodePtr pnodeFncExprScope)
  1443. {
  1444. int fncExprScopeId = pnodeFncExprScope->AsParseNodeBlock()->blockId;
  1445. ParseNodePtr pnodeName = pnodeFnc->AsParseNodeFnc()->pnodeName;
  1446. if (pnodeName)
  1447. {
  1448. Assert(pnodeName->nop == knopVarDecl);
  1449. BindPidRefsInScope(pnodeName->AsParseNodeVar()->pid, pnodeName->AsParseNodeVar()->sym, fncExprScopeId, m_nextBlockId - 1);
  1450. }
  1451. FinishParseBlock(pnodeFncExprScope);
  1452. }
  1453. template <const bool backgroundPidRef>
  1454. void Parser::BindPidRefs(BlockInfoStack *blockInfo, uint maxBlockId)
  1455. {
  1456. // We need to bind all assignments in order to emit assignment to 'const' error
  1457. int blockId = blockInfo->pnodeBlock->AsParseNodeBlock()->blockId;
  1458. Scope *scope = blockInfo->pnodeBlock->AsParseNodeBlock()->scope;
  1459. if (scope)
  1460. {
  1461. auto bindPidRefs = [blockId, maxBlockId, this](Symbol *sym)
  1462. {
  1463. ParseNodePtr pnode = sym->GetDecl();
  1464. IdentPtr pid;
  1465. #if PROFILE_DICTIONARY
  1466. int depth = 0;
  1467. #endif
  1468. Assert(pnode);
  1469. switch (pnode->nop)
  1470. {
  1471. case knopVarDecl:
  1472. case knopLetDecl:
  1473. case knopConstDecl:
  1474. pid = pnode->AsParseNodeVar()->pid;
  1475. if (backgroundPidRef)
  1476. {
  1477. pid = this->m_pscan->m_phtbl->FindExistingPid(pid->Psz(), pid->Psz() + pid->Cch(), pid->Cch(), pid->Hash(), nullptr, nullptr
  1478. #if PROFILE_DICTIONARY
  1479. , depth
  1480. #endif
  1481. );
  1482. if (pid == nullptr)
  1483. {
  1484. break;
  1485. }
  1486. }
  1487. this->BindPidRefsInScope(pid, sym, blockId, maxBlockId);
  1488. break;
  1489. case knopName:
  1490. pid = pnode->AsParseNodePid()->pid;
  1491. if (backgroundPidRef)
  1492. {
  1493. pid = this->m_pscan->m_phtbl->FindExistingPid(pid->Psz(), pid->Psz() + pid->Cch(), pid->Cch(), pid->Hash(), nullptr, nullptr
  1494. #if PROFILE_DICTIONARY
  1495. , depth
  1496. #endif
  1497. );
  1498. if (pid == nullptr)
  1499. {
  1500. break;
  1501. }
  1502. }
  1503. this->BindPidRefsInScope(pid, sym, blockId, maxBlockId);
  1504. break;
  1505. default:
  1506. Assert(0);
  1507. break;
  1508. }
  1509. };
  1510. scope->ForEachSymbol(bindPidRefs);
  1511. }
  1512. }
  1513. void Parser::BindPidRefsInScope(IdentPtr pid, Symbol *sym, int blockId, uint maxBlockId)
  1514. {
  1515. PidRefStack *ref, *nextRef, *lastRef = nullptr;
  1516. Js::LocalFunctionId funcId = GetCurrentFunctionNode()->AsParseNodeFnc()->functionId;
  1517. Assert(sym);
  1518. if (pid->GetIsModuleExport() && IsTopLevelModuleFunc())
  1519. {
  1520. sym->SetIsModuleExportStorage(true);
  1521. }
  1522. bool hasFuncAssignment = sym->GetHasFuncAssignment();
  1523. bool doesEscape = false;
  1524. for (ref = pid->GetTopRef(); ref && ref->GetScopeId() >= blockId; ref = nextRef)
  1525. {
  1526. // Fix up sym* on PID ref.
  1527. Assert(!ref->GetSym() || ref->GetSym() == sym);
  1528. nextRef = ref->prev;
  1529. Assert(ref->GetScopeId() >= 0);
  1530. if ((uint)ref->GetScopeId() > maxBlockId)
  1531. {
  1532. lastRef = ref;
  1533. continue;
  1534. }
  1535. ref->SetSym(sym);
  1536. this->RemovePrevPidRef(pid, lastRef);
  1537. if (ref->IsUsedInLdElem())
  1538. {
  1539. sym->SetIsUsedInLdElem(true);
  1540. }
  1541. if (ref->IsAssignment())
  1542. {
  1543. sym->PromoteAssignmentState();
  1544. if (sym->GetIsFormal())
  1545. {
  1546. GetCurrentFunctionNode()->AsParseNodeFnc()->SetHasAnyWriteToFormals(true);
  1547. }
  1548. }
  1549. if (ref->GetFuncScopeId() != funcId && !sym->GetIsGlobal() && !sym->GetIsModuleExportStorage())
  1550. {
  1551. Assert(ref->GetFuncScopeId() > funcId);
  1552. sym->SetHasNonLocalReference();
  1553. if (ref->IsDynamicBinding())
  1554. {
  1555. sym->SetNeedsScopeObject();
  1556. }
  1557. }
  1558. if (ref->IsFuncAssignment())
  1559. {
  1560. hasFuncAssignment = true;
  1561. }
  1562. if (ref->IsEscape())
  1563. {
  1564. doesEscape = true;
  1565. }
  1566. if (m_currentNodeFunc && doesEscape && hasFuncAssignment)
  1567. {
  1568. if (m_sourceContextInfo ?
  1569. !PHASE_OFF_RAW(Js::DisableStackFuncOnDeferredEscapePhase, m_sourceContextInfo->sourceContextId, m_currentNodeFunc->AsParseNodeFnc()->functionId) :
  1570. !PHASE_OFF1(Js::DisableStackFuncOnDeferredEscapePhase))
  1571. {
  1572. m_currentNodeFunc->AsParseNodeFnc()->SetNestedFuncEscapes();
  1573. }
  1574. }
  1575. if (ref->GetScopeId() == blockId)
  1576. {
  1577. break;
  1578. }
  1579. }
  1580. }
  1581. void Parser::MarkEscapingRef(ParseNodePtr pnode, IdentToken *pToken)
  1582. {
  1583. if (m_currentNodeFunc == nullptr)
  1584. {
  1585. return;
  1586. }
  1587. if (pnode && pnode->nop == knopFncDecl)
  1588. {
  1589. this->SetNestedFuncEscapes();
  1590. }
  1591. else if (pToken->pid)
  1592. {
  1593. PidRefStack *pidRef = pToken->pid->GetTopRef();
  1594. if (pidRef->sym)
  1595. {
  1596. if (pidRef->sym->GetSymbolType() == STFunction)
  1597. {
  1598. this->SetNestedFuncEscapes();
  1599. }
  1600. }
  1601. else
  1602. {
  1603. pidRef->isEscape = true;
  1604. }
  1605. }
  1606. }
  1607. void Parser::SetNestedFuncEscapes() const
  1608. {
  1609. if (m_sourceContextInfo ?
  1610. !PHASE_OFF_RAW(Js::DisableStackFuncOnDeferredEscapePhase, m_sourceContextInfo->sourceContextId, m_currentNodeFunc->AsParseNodeFnc()->functionId) :
  1611. !PHASE_OFF1(Js::DisableStackFuncOnDeferredEscapePhase))
  1612. {
  1613. m_currentNodeFunc->AsParseNodeFnc()->SetNestedFuncEscapes();
  1614. }
  1615. }
  1616. void Parser::PopStmt(StmtNest *pStmt)
  1617. {
  1618. Assert(pStmt == m_pstmtCur);
  1619. SetCurrentStatement(m_pstmtCur->pstmtOuter);
  1620. }
  1621. BlockInfoStack *Parser::PushBlockInfo(ParseNodePtr pnodeBlock)
  1622. {
  1623. BlockInfoStack *newBlockInfo = (BlockInfoStack *)m_nodeAllocator.Alloc(sizeof(BlockInfoStack));
  1624. Assert(nullptr != newBlockInfo);
  1625. newBlockInfo->pnodeBlock = pnodeBlock;
  1626. newBlockInfo->pBlockInfoOuter = m_currentBlockInfo;
  1627. newBlockInfo->m_ppnodeLex = &pnodeBlock->AsParseNodeBlock()->pnodeLexVars;
  1628. if (pnodeBlock->AsParseNodeBlock()->blockType != PnodeBlockType::Regular)
  1629. {
  1630. newBlockInfo->pBlockInfoFunction = newBlockInfo;
  1631. }
  1632. else
  1633. {
  1634. Assert(m_currentBlockInfo);
  1635. newBlockInfo->pBlockInfoFunction = m_currentBlockInfo->pBlockInfoFunction;
  1636. }
  1637. m_currentBlockInfo = newBlockInfo;
  1638. return newBlockInfo;
  1639. }
  1640. void Parser::PopBlockInfo()
  1641. {
  1642. Assert(m_currentBlockInfo);
  1643. PopDynamicBlock();
  1644. m_currentBlockInfo = m_currentBlockInfo->pBlockInfoOuter;
  1645. }
  1646. void Parser::PushDynamicBlock()
  1647. {
  1648. Assert(GetCurrentBlock());
  1649. int blockId = GetCurrentBlock()->AsParseNodeBlock()->blockId;
  1650. if (m_currentDynamicBlock && m_currentDynamicBlock->id == blockId)
  1651. {
  1652. return;
  1653. }
  1654. BlockIdsStack *info = (BlockIdsStack *)m_nodeAllocator.Alloc(sizeof(BlockIdsStack));
  1655. if (nullptr == info)
  1656. {
  1657. Error(ERRnoMemory);
  1658. }
  1659. info->id = blockId;
  1660. info->prev = m_currentDynamicBlock;
  1661. m_currentDynamicBlock = info;
  1662. }
  1663. void Parser::PopDynamicBlock()
  1664. {
  1665. int blockId = GetCurrentDynamicBlockId();
  1666. if (GetCurrentBlock()->AsParseNodeBlock()->blockId != blockId || blockId == -1)
  1667. {
  1668. return;
  1669. }
  1670. Assert(m_currentDynamicBlock);
  1671. m_phtbl->VisitPids([&](IdentPtr pid) {
  1672. for (PidRefStack *ref = pid->GetTopRef(); ref && ref->GetScopeId() >= blockId; ref = ref->prev)
  1673. {
  1674. ref->SetDynamicBinding();
  1675. }
  1676. });
  1677. m_currentDynamicBlock = m_currentDynamicBlock->prev;
  1678. }
  1679. int Parser::GetCurrentDynamicBlockId() const
  1680. {
  1681. return m_currentDynamicBlock ? m_currentDynamicBlock->id : -1;
  1682. }
  1683. ParseNode *Parser::GetCurrentFunctionNode()
  1684. {
  1685. if (m_currentNodeDeferredFunc != nullptr)
  1686. {
  1687. return m_currentNodeDeferredFunc;
  1688. }
  1689. else if (m_currentNodeFunc != nullptr)
  1690. {
  1691. return m_currentNodeFunc;
  1692. }
  1693. else
  1694. {
  1695. AssertMsg(GetFunctionBlock()->AsParseNodeBlock()->blockType == PnodeBlockType::Global,
  1696. "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'");
  1697. return m_currentNodeProg;
  1698. }
  1699. }
  1700. ParseNode *Parser::GetCurrentNonLambdaFunctionNode()
  1701. {
  1702. if (m_currentNodeNonLambdaDeferredFunc != nullptr)
  1703. {
  1704. return m_currentNodeNonLambdaDeferredFunc;
  1705. }
  1706. return m_currentNodeNonLambdaFunc;
  1707. }
  1708. void Parser::RegisterRegexPattern(UnifiedRegex::RegexPattern *const regexPattern)
  1709. {
  1710. Assert(regexPattern);
  1711. // ensure a no-throw add behavior here, to catch out of memory exceptions, using the guest arena allocator
  1712. if (!m_registeredRegexPatterns.PrependNoThrow(m_scriptContext->GetGuestArena(), regexPattern))
  1713. {
  1714. Parser::Error(ERRnoMemory);
  1715. }
  1716. }
  1717. void Parser::CaptureState(ParserState *state)
  1718. {
  1719. Assert(state != nullptr);
  1720. state->m_funcInArraySave = m_funcInArray;
  1721. state->m_funcInArrayDepthSave = m_funcInArrayDepth;
  1722. state->m_nestedCountSave = *m_pnestedCount;
  1723. state->m_ppnodeScopeSave = m_ppnodeScope;
  1724. state->m_ppnodeExprScopeSave = m_ppnodeExprScope;
  1725. state->m_pCurrentAstSizeSave = m_pCurrentAstSize;
  1726. state->m_nextBlockId = m_nextBlockId;
  1727. Assert(state->m_ppnodeScopeSave == nullptr || *state->m_ppnodeScopeSave == nullptr);
  1728. Assert(state->m_ppnodeExprScopeSave == nullptr || *state->m_ppnodeExprScopeSave == nullptr);
  1729. #if DEBUG
  1730. state->m_currentBlockInfo = m_currentBlockInfo;
  1731. #endif
  1732. }
  1733. void Parser::RestoreStateFrom(ParserState *state)
  1734. {
  1735. Assert(state != nullptr);
  1736. Assert(state->m_currentBlockInfo == m_currentBlockInfo);
  1737. m_funcInArray = state->m_funcInArraySave;
  1738. m_funcInArrayDepth = state->m_funcInArrayDepthSave;
  1739. *m_pnestedCount = state->m_nestedCountSave;
  1740. m_pCurrentAstSize = state->m_pCurrentAstSizeSave;
  1741. m_nextBlockId = state->m_nextBlockId;
  1742. if (state->m_ppnodeScopeSave != nullptr)
  1743. {
  1744. *state->m_ppnodeScopeSave = nullptr;
  1745. }
  1746. if (state->m_ppnodeExprScopeSave != nullptr)
  1747. {
  1748. *state->m_ppnodeExprScopeSave = nullptr;
  1749. }
  1750. m_ppnodeScope = state->m_ppnodeScopeSave;
  1751. m_ppnodeExprScope = state->m_ppnodeExprScopeSave;
  1752. }
  1753. void Parser::AddToNodeListEscapedUse(ParseNode ** ppnodeList, ParseNode *** pppnodeLast,
  1754. ParseNode * pnodeAdd)
  1755. {
  1756. AddToNodeList(ppnodeList, pppnodeLast, pnodeAdd);
  1757. pnodeAdd->SetIsInList();
  1758. }
  1759. void Parser::AddToNodeList(ParseNode ** ppnodeList, ParseNode *** pppnodeLast,
  1760. ParseNode * pnodeAdd)
  1761. {
  1762. Assert(!this->m_deferringAST);
  1763. if (nullptr == *pppnodeLast)
  1764. {
  1765. // should be an empty list
  1766. Assert(nullptr == *ppnodeList);
  1767. *ppnodeList = pnodeAdd;
  1768. *pppnodeLast = ppnodeList;
  1769. }
  1770. else
  1771. {
  1772. //
  1773. AssertNodeMem(*ppnodeList);
  1774. AssertNodeMem(**pppnodeLast);
  1775. ParseNode *pnodeT = CreateBinNode(knopList, **pppnodeLast, pnodeAdd);
  1776. **pppnodeLast = pnodeT;
  1777. *pppnodeLast = &pnodeT->AsParseNodeBin()->pnode2;
  1778. }
  1779. }
  1780. // Check reference to "arguments" that indicates the object may escape.
  1781. void Parser::CheckArguments(ParseNodePtr pnode)
  1782. {
  1783. if (m_currentNodeFunc && this->NodeIsIdent(pnode, wellKnownPropertyPids.arguments))
  1784. {
  1785. m_currentNodeFunc->AsParseNodeFnc()->SetHasHeapArguments();
  1786. }
  1787. }
  1788. // Check use of "arguments" that requires instantiation of the object.
  1789. void Parser::CheckArgumentsUse(IdentPtr pid, ParseNodePtr pnodeFnc)
  1790. {
  1791. if (pid == wellKnownPropertyPids.arguments)
  1792. {
  1793. if (pnodeFnc != nullptr && pnodeFnc != m_currentNodeProg)
  1794. {
  1795. pnodeFnc->AsParseNodeFnc()->SetUsesArguments(TRUE);
  1796. }
  1797. else
  1798. {
  1799. m_UsesArgumentsAtGlobal = true;
  1800. }
  1801. }
  1802. }
  1803. void Parser::CheckStrictModeEvalArgumentsUsage(IdentPtr pid, ParseNodePtr pnode)
  1804. {
  1805. if (pid != nullptr)
  1806. {
  1807. // In strict mode, 'eval' / 'arguments' cannot be assigned to.
  1808. if ( pid == wellKnownPropertyPids.eval)
  1809. {
  1810. Error(ERREvalUsage, pnode);
  1811. }
  1812. if (pid == wellKnownPropertyPids.arguments)
  1813. {
  1814. Error(ERRArgsUsage, pnode);
  1815. }
  1816. }
  1817. }
  1818. void Parser::ReduceDeferredScriptLength(size_t chars)
  1819. {
  1820. // If we're in deferred mode, subtract the given char count from the total length,
  1821. // and see if this puts us under the deferral threshold.
  1822. if ((m_grfscr & fscrDeferFncParse) &&
  1823. (
  1824. PHASE_OFF1(Js::DeferEventHandlersPhase) ||
  1825. (m_grfscr & fscrGlobalCode)
  1826. )
  1827. )
  1828. {
  1829. if (m_length > chars)
  1830. {
  1831. m_length -= chars;
  1832. }
  1833. else
  1834. {
  1835. m_length = 0;
  1836. }
  1837. if (m_length < Parser::GetDeferralThreshold(this->m_sourceContextInfo->IsSourceProfileLoaded()))
  1838. {
  1839. // Stop deferring.
  1840. m_grfscr &= ~fscrDeferFncParse;
  1841. m_stoppedDeferredParse = TRUE;
  1842. }
  1843. }
  1844. }
  1845. void Parser::EnsureStackAvailable()
  1846. {
  1847. bool isInterrupt = false;
  1848. if (!m_scriptContext->GetThreadContext()->IsStackAvailable(Js::Constants::MinStackCompile, &isInterrupt))
  1849. {
  1850. Error(isInterrupt ? E_ABORT : VBSERR_OutOfStack);
  1851. }
  1852. }
  1853. void Parser::ThrowNewTargetSyntaxErrForGlobalScope()
  1854. {
  1855. // If we are parsing a previously deferred function, we can skip throwing the SyntaxError for `new.target` at global scope.
  1856. // If we are at global scope, we would have thrown a SyntaxError when we did the Upfront parse pass and we would not have
  1857. // deferred the function in order to come back now and reparse it.
  1858. if (m_parseType == ParseType_Deferred)
  1859. {
  1860. return;
  1861. }
  1862. if (GetCurrentNonLambdaFunctionNode() != nullptr)
  1863. {
  1864. return;
  1865. }
  1866. if ((this->m_grfscr & fscrEval) != 0)
  1867. {
  1868. Js::JavascriptFunction * caller = nullptr;
  1869. if (Js::JavascriptStackWalker::GetCaller(&caller, m_scriptContext))
  1870. {
  1871. Js::FunctionBody * callerBody = caller->GetFunctionBody();
  1872. Assert(callerBody);
  1873. if (!callerBody->GetIsGlobalFunc() && !(callerBody->IsLambda() && callerBody->GetEnclosedByGlobalFunc()))
  1874. {
  1875. return;
  1876. }
  1877. }
  1878. }
  1879. Error(ERRInvalidNewTarget);
  1880. }
  1881. template<bool buildAST>
  1882. IdentPtr Parser::ParseMetaProperty(tokens metaParentKeyword, charcount_t ichMin, _Out_opt_ BOOL* pfCanAssign)
  1883. {
  1884. AssertMsg(metaParentKeyword == tkNEW, "Only supported for tkNEW parent keywords");
  1885. AssertMsg(this->m_token.tk == tkDot, "We must be currently sitting on the dot after the parent keyword");
  1886. m_pscan->Scan();
  1887. if (this->m_token.tk == tkID && this->m_token.GetIdentifier(m_phtbl) == this->GetTargetPid())
  1888. {
  1889. ThrowNewTargetSyntaxErrForGlobalScope();
  1890. if (pfCanAssign)
  1891. {
  1892. *pfCanAssign = FALSE;
  1893. }
  1894. return wellKnownPropertyPids._newTarget;
  1895. }
  1896. else
  1897. {
  1898. Error(ERRsyntax);
  1899. }
  1900. }
  1901. template<bool buildAST>
  1902. void Parser::ParseNamedImportOrExportClause(ModuleImportOrExportEntryList* importOrExportEntryList, bool isExportClause)
  1903. {
  1904. Assert(m_token.tk == tkLCurly);
  1905. Assert(importOrExportEntryList != nullptr);
  1906. m_pscan->Scan();
  1907. while (m_token.tk != tkRCurly && m_token.tk != tkEOF)
  1908. {
  1909. tokens firstToken = m_token.tk;
  1910. if (!(m_token.IsIdentifier() || m_token.IsReservedWord()))
  1911. {
  1912. Error(ERRsyntax);
  1913. }
  1914. IdentPtr identifierName = m_token.GetIdentifier(m_phtbl);
  1915. IdentPtr identifierAs = identifierName;
  1916. m_pscan->Scan();
  1917. if (m_token.tk == tkID)
  1918. {
  1919. // We have the pattern "IdentifierName as"
  1920. if (wellKnownPropertyPids.as != m_token.GetIdentifier(m_phtbl))
  1921. {
  1922. Error(ERRsyntax);
  1923. }
  1924. m_pscan->Scan();
  1925. // If we are parsing an import statement, the token after 'as' must be a BindingIdentifier.
  1926. if (!isExportClause)
  1927. {
  1928. ChkCurTokNoScan(tkID, ERRsyntax);
  1929. }
  1930. if (!(m_token.IsIdentifier() || m_token.IsReservedWord()))
  1931. {
  1932. Error(ERRsyntax);
  1933. }
  1934. identifierAs = m_token.GetIdentifier(m_phtbl);
  1935. // Scan to the next token.
  1936. m_pscan->Scan();
  1937. }
  1938. else if (!isExportClause && firstToken != tkID)
  1939. {
  1940. // If we are parsing an import statement and this ImportSpecifier clause did not have
  1941. // 'as ImportedBinding' at the end of it, identifierName must be a BindingIdentifier.
  1942. Error(ERRsyntax);
  1943. }
  1944. if (m_token.tk == tkComma)
  1945. {
  1946. // Consume a trailing comma
  1947. m_pscan->Scan();
  1948. }
  1949. if (buildAST)
  1950. {
  1951. // The name we will use 'as' this import/export is a binding identifier in import statements.
  1952. if (!isExportClause)
  1953. {
  1954. CreateModuleImportDeclNode(identifierAs);
  1955. AddModuleImportOrExportEntry(importOrExportEntryList, identifierName, identifierAs, nullptr, nullptr);
  1956. }
  1957. else
  1958. {
  1959. identifierName->SetIsModuleExport();
  1960. AddModuleImportOrExportEntry(importOrExportEntryList, nullptr, identifierName, identifierAs, nullptr);
  1961. }
  1962. }
  1963. }
  1964. // Final token in a named import or export clause must be a '}'
  1965. ChkCurTokNoScan(tkRCurly, ERRsyntax);
  1966. }
  1967. IdentPtrList* Parser::GetRequestedModulesList()
  1968. {
  1969. return m_currentNodeProg->AsParseNodeModule()->requestedModules;
  1970. }
  1971. ModuleImportOrExportEntryList* Parser::GetModuleImportEntryList()
  1972. {
  1973. return m_currentNodeProg->AsParseNodeModule()->importEntries;
  1974. }
  1975. ModuleImportOrExportEntryList* Parser::GetModuleLocalExportEntryList()
  1976. {
  1977. return m_currentNodeProg->AsParseNodeModule()->localExportEntries;
  1978. }
  1979. ModuleImportOrExportEntryList* Parser::GetModuleIndirectExportEntryList()
  1980. {
  1981. return m_currentNodeProg->AsParseNodeModule()->indirectExportEntries;
  1982. }
  1983. ModuleImportOrExportEntryList* Parser::GetModuleStarExportEntryList()
  1984. {
  1985. return m_currentNodeProg->AsParseNodeModule()->starExportEntries;
  1986. }
  1987. IdentPtrList* Parser::EnsureRequestedModulesList()
  1988. {
  1989. if (m_currentNodeProg->AsParseNodeModule()->requestedModules == nullptr)
  1990. {
  1991. m_currentNodeProg->AsParseNodeModule()->requestedModules = Anew(&m_nodeAllocator, IdentPtrList, &m_nodeAllocator);
  1992. }
  1993. return m_currentNodeProg->AsParseNodeModule()->requestedModules;
  1994. }
  1995. ModuleImportOrExportEntryList* Parser::EnsureModuleImportEntryList()
  1996. {
  1997. if (m_currentNodeProg->AsParseNodeModule()->importEntries == nullptr)
  1998. {
  1999. m_currentNodeProg->AsParseNodeModule()->importEntries = Anew(&m_nodeAllocator, ModuleImportOrExportEntryList, &m_nodeAllocator);
  2000. }
  2001. return m_currentNodeProg->AsParseNodeModule()->importEntries;
  2002. }
  2003. ModuleImportOrExportEntryList* Parser::EnsureModuleLocalExportEntryList()
  2004. {
  2005. if (m_currentNodeProg->AsParseNodeModule()->localExportEntries == nullptr)
  2006. {
  2007. m_currentNodeProg->AsParseNodeModule()->localExportEntries = Anew(&m_nodeAllocator, ModuleImportOrExportEntryList, &m_nodeAllocator);
  2008. }
  2009. return m_currentNodeProg->AsParseNodeModule()->localExportEntries;
  2010. }
  2011. ModuleImportOrExportEntryList* Parser::EnsureModuleIndirectExportEntryList()
  2012. {
  2013. if (m_currentNodeProg->AsParseNodeModule()->indirectExportEntries == nullptr)
  2014. {
  2015. m_currentNodeProg->AsParseNodeModule()->indirectExportEntries = Anew(&m_nodeAllocator, ModuleImportOrExportEntryList, &m_nodeAllocator);
  2016. }
  2017. return m_currentNodeProg->AsParseNodeModule()->indirectExportEntries;
  2018. }
  2019. ModuleImportOrExportEntryList* Parser::EnsureModuleStarExportEntryList()
  2020. {
  2021. if (m_currentNodeProg->AsParseNodeModule()->starExportEntries == nullptr)
  2022. {
  2023. m_currentNodeProg->AsParseNodeModule()->starExportEntries = Anew(&m_nodeAllocator, ModuleImportOrExportEntryList, &m_nodeAllocator);
  2024. }
  2025. return m_currentNodeProg->AsParseNodeModule()->starExportEntries;
  2026. }
  2027. void Parser::AddModuleSpecifier(IdentPtr moduleRequest)
  2028. {
  2029. IdentPtrList* requestedModulesList = EnsureRequestedModulesList();
  2030. if (!requestedModulesList->Has(moduleRequest))
  2031. {
  2032. requestedModulesList->Prepend(moduleRequest);
  2033. }
  2034. }
  2035. ModuleImportOrExportEntry* Parser::AddModuleImportOrExportEntry(ModuleImportOrExportEntryList* importOrExportEntryList, ModuleImportOrExportEntry* importOrExportEntry)
  2036. {
  2037. if (importOrExportEntry->exportName != nullptr)
  2038. {
  2039. CheckForDuplicateExportEntry(importOrExportEntryList, importOrExportEntry->exportName);
  2040. }
  2041. importOrExportEntryList->Prepend(*importOrExportEntry);
  2042. return importOrExportEntry;
  2043. }
  2044. ModuleImportOrExportEntry* Parser::AddModuleImportOrExportEntry(ModuleImportOrExportEntryList* importOrExportEntryList, IdentPtr importName, IdentPtr localName, IdentPtr exportName, IdentPtr moduleRequest)
  2045. {
  2046. ModuleImportOrExportEntry* importOrExportEntry = Anew(&m_nodeAllocator, ModuleImportOrExportEntry);
  2047. importOrExportEntry->importName = importName;
  2048. importOrExportEntry->localName = localName;
  2049. importOrExportEntry->exportName = exportName;
  2050. importOrExportEntry->moduleRequest = moduleRequest;
  2051. return AddModuleImportOrExportEntry(importOrExportEntryList, importOrExportEntry);
  2052. }
  2053. void Parser::AddModuleLocalExportEntry(ParseNodePtr varDeclNode)
  2054. {
  2055. AssertOrFailFast(varDeclNode->nop == knopVarDecl || varDeclNode->nop == knopLetDecl || varDeclNode->nop == knopConstDecl);
  2056. IdentPtr localName = varDeclNode->AsParseNodeVar()->pid;
  2057. varDeclNode->AsParseNodeVar()->sym->SetIsModuleExportStorage(true);
  2058. AddModuleImportOrExportEntry(EnsureModuleLocalExportEntryList(), nullptr, localName, localName, nullptr);
  2059. }
  2060. void Parser::CheckForDuplicateExportEntry(ModuleImportOrExportEntryList* exportEntryList, IdentPtr exportName)
  2061. {
  2062. ModuleImportOrExportEntry* findResult = exportEntryList->Find([&](ModuleImportOrExportEntry exportEntry)
  2063. {
  2064. if (exportName == exportEntry.exportName)
  2065. {
  2066. return true;
  2067. }
  2068. return false;
  2069. });
  2070. if (findResult != nullptr)
  2071. {
  2072. Error(ERRsyntax);
  2073. }
  2074. }
  2075. template<bool buildAST>
  2076. void Parser::ParseImportClause(ModuleImportOrExportEntryList* importEntryList, bool parsingAfterComma)
  2077. {
  2078. bool parsedNamespaceOrNamedImport = false;
  2079. switch (m_token.tk)
  2080. {
  2081. case tkID:
  2082. // This is the default binding identifier.
  2083. // If we already saw a comma in the import clause, this is a syntax error.
  2084. if (parsingAfterComma)
  2085. {
  2086. Error(ERRsyntax);
  2087. }
  2088. if (buildAST)
  2089. {
  2090. IdentPtr localName = m_token.GetIdentifier(m_phtbl);
  2091. IdentPtr importName = wellKnownPropertyPids._default;
  2092. CreateModuleImportDeclNode(localName);
  2093. AddModuleImportOrExportEntry(importEntryList, importName, localName, nullptr, nullptr);
  2094. }
  2095. break;
  2096. case tkLCurly:
  2097. // This begins a list of named imports.
  2098. ParseNamedImportOrExportClause<buildAST>(importEntryList, false);
  2099. parsedNamespaceOrNamedImport = true;
  2100. break;
  2101. case tkStar:
  2102. // This begins a namespace import clause.
  2103. // "* as ImportedBinding"
  2104. // Token following * must be the identifier 'as'
  2105. m_pscan->Scan();
  2106. if (m_token.tk != tkID || wellKnownPropertyPids.as != m_token.GetIdentifier(m_phtbl))
  2107. {
  2108. Error(ERRsyntax);
  2109. }
  2110. // Token following 'as' must be a binding identifier.
  2111. m_pscan->Scan();
  2112. ChkCurTokNoScan(tkID, ERRsyntax);
  2113. if (buildAST)
  2114. {
  2115. IdentPtr localName = m_token.GetIdentifier(m_phtbl);
  2116. IdentPtr importName = wellKnownPropertyPids._star;
  2117. CreateModuleImportDeclNode(localName);
  2118. AddModuleImportOrExportEntry(importEntryList, importName, localName, nullptr, nullptr);
  2119. }
  2120. parsedNamespaceOrNamedImport = true;
  2121. break;
  2122. default:
  2123. Error(ERRsyntax);
  2124. }
  2125. m_pscan->Scan();
  2126. if (m_token.tk == tkComma)
  2127. {
  2128. // There cannot be more than one comma in a module import clause.
  2129. // There cannot be a namespace import or named imports list on the left of the comma in a module import clause.
  2130. if (parsingAfterComma || parsedNamespaceOrNamedImport)
  2131. {
  2132. Error(ERRsyntax);
  2133. }
  2134. m_pscan->Scan();
  2135. ParseImportClause<buildAST>(importEntryList, true);
  2136. }
  2137. }
  2138. bool Parser::IsImportOrExportStatementValidHere()
  2139. {
  2140. ParseNodePtr curFunc = GetCurrentFunctionNode();
  2141. // Import must be located in the top scope of the module body.
  2142. return curFunc->nop == knopFncDecl
  2143. && curFunc->AsParseNodeFnc()->IsModule()
  2144. && this->m_currentBlockInfo->pnodeBlock == curFunc->AsParseNodeFnc()->pnodeBodyScope
  2145. && (this->m_grfscr & fscrEvalCode) != fscrEvalCode
  2146. && this->m_tryCatchOrFinallyDepth == 0
  2147. && !this->m_disallowImportExportStmt;
  2148. }
  2149. bool Parser::IsTopLevelModuleFunc()
  2150. {
  2151. ParseNodePtr curFunc = GetCurrentFunctionNode();
  2152. return curFunc->nop == knopFncDecl && curFunc->AsParseNodeFnc()->IsModule();
  2153. }
  2154. template<bool buildAST> ParseNodePtr Parser::ParseImportCall()
  2155. {
  2156. m_pscan->Scan();
  2157. ParseNodePtr specifier = ParseExpr<buildAST>(koplCma, nullptr, /* fAllowIn */FALSE, /* fAllowEllipsis */FALSE);
  2158. if (m_token.tk != tkRParen)
  2159. {
  2160. Error(ERRnoRparen);
  2161. }
  2162. m_pscan->Scan();
  2163. return buildAST ? CreateCallNode(knopCall, CreateNodeWithScanner<knopImport>(), specifier) : nullptr;
  2164. }
  2165. template<bool buildAST>
  2166. ParseNodePtr Parser::ParseImport()
  2167. {
  2168. Assert(m_scriptContext->GetConfig()->IsES6ModuleEnabled());
  2169. Assert(m_token.tk == tkIMPORT);
  2170. RestorePoint parsedImport;
  2171. m_pscan->Capture(&parsedImport);
  2172. m_pscan->Scan();
  2173. // import()
  2174. if (m_token.tk == tkLParen)
  2175. {
  2176. if (!m_scriptContext->GetConfig()->IsESDynamicImportEnabled())
  2177. {
  2178. Error(ERRsyntax);
  2179. }
  2180. ParseNodePtr pnode = ParseImportCall<buildAST>();
  2181. BOOL fCanAssign;
  2182. IdentToken token;
  2183. return ParsePostfixOperators<buildAST>(pnode, TRUE, FALSE, FALSE, &fCanAssign, &token);
  2184. }
  2185. m_pscan->SeekTo(parsedImport);
  2186. if (!IsImportOrExportStatementValidHere())
  2187. {
  2188. Error(ERRInvalidModuleImportOrExport);
  2189. }
  2190. // We just parsed an import token. Next valid token is *, {, string constant, or binding identifier.
  2191. m_pscan->Scan();
  2192. if (m_token.tk == tkStrCon)
  2193. {
  2194. // This import declaration has no import clause.
  2195. // "import ModuleSpecifier;"
  2196. if (buildAST)
  2197. {
  2198. AddModuleSpecifier(m_token.GetStr());
  2199. }
  2200. // Scan past the module identifier.
  2201. m_pscan->Scan();
  2202. }
  2203. else
  2204. {
  2205. ModuleImportOrExportEntryList importEntryList(&m_nodeAllocator);
  2206. // Parse the import clause (default binding can only exist before the comma).
  2207. ParseImportClause<buildAST>(&importEntryList);
  2208. // Token following import clause must be the identifier 'from'
  2209. IdentPtr moduleSpecifier = ParseImportOrExportFromClause<buildAST>(true);
  2210. if (buildAST)
  2211. {
  2212. Assert(moduleSpecifier != nullptr);
  2213. AddModuleSpecifier(moduleSpecifier);
  2214. importEntryList.Map([this, moduleSpecifier](ModuleImportOrExportEntry& importEntry) {
  2215. importEntry.moduleRequest = moduleSpecifier;
  2216. AddModuleImportOrExportEntry(EnsureModuleImportEntryList(), &importEntry);
  2217. });
  2218. }
  2219. importEntryList.Clear();
  2220. }
  2221. // Import statement is actually a nop, we hoist all the imported bindings to the top of the module.
  2222. return nullptr;
  2223. }
  2224. template<bool buildAST>
  2225. IdentPtr Parser::ParseImportOrExportFromClause(bool throwIfNotFound)
  2226. {
  2227. IdentPtr moduleSpecifier = nullptr;
  2228. if (m_token.tk == tkID && wellKnownPropertyPids.from == m_token.GetIdentifier(m_phtbl))
  2229. {
  2230. m_pscan->Scan();
  2231. // Token following the 'from' token must be a string constant - the module specifier.
  2232. ChkCurTokNoScan(tkStrCon, ERRsyntax);
  2233. if (buildAST)
  2234. {
  2235. moduleSpecifier = m_token.GetStr();
  2236. }
  2237. m_pscan->Scan();
  2238. }
  2239. else if (throwIfNotFound)
  2240. {
  2241. Error(ERRsyntax);
  2242. }
  2243. return moduleSpecifier;
  2244. }
  2245. template<bool buildAST>
  2246. ParseNodePtr Parser::ParseDefaultExportClause()
  2247. {
  2248. Assert(m_token.tk == tkDEFAULT);
  2249. m_pscan->Scan();
  2250. ParseNodePtr pnode = nullptr;
  2251. ushort flags = fFncNoFlgs;
  2252. switch (m_token.tk)
  2253. {
  2254. case tkCLASS:
  2255. {
  2256. if (!m_scriptContext->GetConfig()->IsES6ClassAndExtendsEnabled())
  2257. {
  2258. goto LDefault;
  2259. }
  2260. // Before we parse the class itself we need to know if the class has an identifier name.
  2261. // If it does, we'll treat this class as an ordinary class declaration which will bind
  2262. // it to that name. Otherwise the class should parse as a nameless class expression and
  2263. // bind only to the export binding.
  2264. BOOL classHasName = false;
  2265. RestorePoint parsedClass;
  2266. m_pscan->Capture(&parsedClass);
  2267. m_pscan->Scan();
  2268. if (m_token.tk == tkID)
  2269. {
  2270. classHasName = true;
  2271. }
  2272. m_pscan->SeekTo(parsedClass);
  2273. pnode = ParseClassDecl<buildAST>(classHasName, nullptr, nullptr, nullptr);
  2274. if (buildAST)
  2275. {
  2276. AnalysisAssert(pnode != nullptr);
  2277. Assert(pnode->nop == knopClassDecl);
  2278. pnode->AsParseNodeClass()->SetIsDefaultModuleExport(true);
  2279. }
  2280. break;
  2281. }
  2282. case tkID:
  2283. // If we parsed an async token, it could either modify the next token (if it is a
  2284. // function token) or it could be an identifier (let async = 0; export default async;).
  2285. // To handle both cases, when we parse an async token we need to keep the parser state
  2286. // and rewind if the next token is not function.
  2287. if (wellKnownPropertyPids.async == m_token.GetIdentifier(m_phtbl))
  2288. {
  2289. RestorePoint parsedAsync;
  2290. m_pscan->Capture(&parsedAsync);
  2291. m_pscan->Scan();
  2292. if (m_token.tk == tkFUNCTION)
  2293. {
  2294. // Token after async is function, consume the async token and continue to parse the
  2295. // function as an async function.
  2296. flags |= fFncAsync;
  2297. goto LFunction;
  2298. }
  2299. // Token after async is not function, no idea what the async token is supposed to mean
  2300. // so rewind and let the default case handle it.
  2301. m_pscan->SeekTo(parsedAsync);
  2302. }
  2303. goto LDefault;
  2304. break;
  2305. case tkFUNCTION:
  2306. {
  2307. LFunction:
  2308. // We just parsed a function token but we need to figure out if the function
  2309. // has an identifier name or not before we call the helper.
  2310. RestorePoint parsedFunction;
  2311. m_pscan->Capture(&parsedFunction);
  2312. m_pscan->Scan();
  2313. if (m_token.tk == tkStar)
  2314. {
  2315. // If we saw 'function*' that indicates we are going to parse a generator,
  2316. // but doesn't tell us if the generator has an identifier or not.
  2317. // Skip the '*' token for now as it doesn't matter yet.
  2318. m_pscan->Scan();
  2319. }
  2320. // We say that if the function has an identifier name, it is a 'normal' declaration
  2321. // and should create a binding to that identifier as well as one for our default export.
  2322. if (m_token.tk == tkID)
  2323. {
  2324. flags |= fFncDeclaration;
  2325. }
  2326. else
  2327. {
  2328. flags |= fFncNoName;
  2329. }
  2330. // Rewind back to the function token and let the helper handle the parsing.
  2331. m_pscan->SeekTo(parsedFunction);
  2332. pnode = ParseFncDecl<buildAST>(flags);
  2333. if (buildAST)
  2334. {
  2335. AnalysisAssert(pnode != nullptr);
  2336. Assert(pnode->nop == knopFncDecl);
  2337. pnode->AsParseNodeFnc()->SetIsDefaultModuleExport(true);
  2338. }
  2339. break;
  2340. }
  2341. default:
  2342. LDefault:
  2343. {
  2344. ParseNodePtr pnodeExpression = ParseExpr<buildAST>();
  2345. // Consider: Can we detect this syntax error earlier?
  2346. if (pnodeExpression && pnodeExpression->nop == knopComma)
  2347. {
  2348. Error(ERRsyntax);
  2349. }
  2350. if (buildAST)
  2351. {
  2352. AnalysisAssert(pnodeExpression != nullptr);
  2353. // Mark this node as the default module export. We need to make sure it is put into the correct
  2354. // module export slot when we emit the node.
  2355. pnode = CreateNode(knopExportDefault);
  2356. pnode->AsParseNodeExportDefault()->pnodeExpr = pnodeExpression;
  2357. }
  2358. break;
  2359. }
  2360. }
  2361. IdentPtr exportName = wellKnownPropertyPids._default;
  2362. IdentPtr localName = wellKnownPropertyPids._starDefaultStar;
  2363. AddModuleImportOrExportEntry(EnsureModuleLocalExportEntryList(), nullptr, localName, exportName, nullptr);
  2364. return pnode;
  2365. }
  2366. template<bool buildAST>
  2367. ParseNodePtr Parser::ParseExportDeclaration(bool *needTerminator)
  2368. {
  2369. Assert(m_scriptContext->GetConfig()->IsES6ModuleEnabled());
  2370. Assert(m_token.tk == tkEXPORT);
  2371. if (!IsImportOrExportStatementValidHere())
  2372. {
  2373. Error(ERRInvalidModuleImportOrExport);
  2374. }
  2375. ParseNodePtr pnode = nullptr;
  2376. IdentPtr moduleIdentifier = nullptr;
  2377. tokens declarationType;
  2378. if (needTerminator != nullptr)
  2379. {
  2380. *needTerminator = false;
  2381. }
  2382. // We just parsed an export token. Next valid tokens are *, {, var, let, const, async, function, class, default.
  2383. m_pscan->Scan();
  2384. switch (m_token.tk)
  2385. {
  2386. case tkStar:
  2387. m_pscan->Scan();
  2388. // A star token in an export declaration must be followed by a from clause which begins with a token 'from'.
  2389. moduleIdentifier = ParseImportOrExportFromClause<buildAST>(true);
  2390. if (buildAST)
  2391. {
  2392. Assert(moduleIdentifier != nullptr);
  2393. AddModuleSpecifier(moduleIdentifier);
  2394. IdentPtr importName = wellKnownPropertyPids._star;
  2395. AddModuleImportOrExportEntry(EnsureModuleStarExportEntryList(), importName, nullptr, nullptr, moduleIdentifier);
  2396. }
  2397. if (needTerminator != nullptr)
  2398. {
  2399. *needTerminator = true;
  2400. }
  2401. break;
  2402. case tkLCurly:
  2403. {
  2404. ModuleImportOrExportEntryList exportEntryList(&m_nodeAllocator);
  2405. ParseNamedImportOrExportClause<buildAST>(&exportEntryList, true);
  2406. m_pscan->Scan();
  2407. // Export clause may be followed by a from clause.
  2408. moduleIdentifier = ParseImportOrExportFromClause<buildAST>(false);
  2409. if (buildAST)
  2410. {
  2411. if (moduleIdentifier != nullptr)
  2412. {
  2413. AddModuleSpecifier(moduleIdentifier);
  2414. }
  2415. exportEntryList.Map([this, moduleIdentifier](ModuleImportOrExportEntry& exportEntry) {
  2416. if (moduleIdentifier != nullptr)
  2417. {
  2418. exportEntry.moduleRequest = moduleIdentifier;
  2419. // We need to swap localname and importname when this is a re-export.
  2420. exportEntry.importName = exportEntry.localName;
  2421. exportEntry.localName = nullptr;
  2422. AddModuleImportOrExportEntry(EnsureModuleIndirectExportEntryList(), &exportEntry);
  2423. }
  2424. else
  2425. {
  2426. AddModuleImportOrExportEntry(EnsureModuleLocalExportEntryList(), &exportEntry);
  2427. }
  2428. });
  2429. exportEntryList.Clear();
  2430. }
  2431. }
  2432. if (needTerminator != nullptr)
  2433. {
  2434. *needTerminator = true;
  2435. }
  2436. break;
  2437. case tkID:
  2438. {
  2439. IdentPtr pid = m_token.GetIdentifier(m_phtbl);
  2440. if (wellKnownPropertyPids.let == pid)
  2441. {
  2442. declarationType = tkLET;
  2443. goto ParseVarDecl;
  2444. }
  2445. if (wellKnownPropertyPids.async == pid && m_scriptContext->GetConfig()->IsES7AsyncAndAwaitEnabled())
  2446. {
  2447. // In module export statements, async token is only valid if it's followed by function.
  2448. // We need to check here because ParseStatement would think 'async = 20' is a var decl.
  2449. RestorePoint parsedAsync;
  2450. m_pscan->Capture(&parsedAsync);
  2451. m_pscan->Scan();
  2452. if (m_token.tk == tkFUNCTION)
  2453. {
  2454. // Token after async is function, rewind to the async token and let ParseStatement handle it.
  2455. m_pscan->SeekTo(parsedAsync);
  2456. goto ParseFunctionDecl;
  2457. }
  2458. // Token after async is not function, it's a syntax error.
  2459. }
  2460. goto ErrorToken;
  2461. }
  2462. case tkVAR:
  2463. case tkLET:
  2464. case tkCONST:
  2465. {
  2466. declarationType = m_token.tk;
  2467. ParseVarDecl:
  2468. m_pscan->Scan();
  2469. pnode = ParseVariableDeclaration<buildAST>(declarationType, m_pscan->IchMinTok());
  2470. if (buildAST)
  2471. {
  2472. ForEachItemInList(pnode, [&](ParseNodePtr item) {
  2473. if (item->nop == knopAsg)
  2474. {
  2475. Parser::MapBindIdentifier(item, [&](ParseNodePtr subItem)
  2476. {
  2477. AddModuleLocalExportEntry(subItem);
  2478. });
  2479. }
  2480. else
  2481. {
  2482. AddModuleLocalExportEntry(item);
  2483. }
  2484. });
  2485. }
  2486. }
  2487. break;
  2488. case tkFUNCTION:
  2489. case tkCLASS:
  2490. {
  2491. ParseFunctionDecl:
  2492. pnode = ParseStatement<buildAST>();
  2493. if (buildAST)
  2494. {
  2495. IdentPtr localName;
  2496. if (pnode->nop == knopClassDecl)
  2497. {
  2498. pnode->AsParseNodeClass()->pnodeDeclName->AsParseNodeVar()->sym->SetIsModuleExportStorage(true);
  2499. localName = pnode->AsParseNodeClass()->pnodeName->AsParseNodeVar()->pid;
  2500. }
  2501. else
  2502. {
  2503. Assert(pnode->nop == knopFncDecl);
  2504. pnode->AsParseNodeFnc()->GetFuncSymbol()->SetIsModuleExportStorage(true);
  2505. localName = pnode->AsParseNodeFnc()->pid;
  2506. }
  2507. Assert(localName != nullptr);
  2508. AddModuleImportOrExportEntry(EnsureModuleLocalExportEntryList(), nullptr, localName, localName, nullptr);
  2509. }
  2510. }
  2511. break;
  2512. case tkDEFAULT:
  2513. {
  2514. pnode = ParseDefaultExportClause<buildAST>();
  2515. }
  2516. break;
  2517. default:
  2518. {
  2519. ErrorToken:
  2520. Error(ERRsyntax);
  2521. }
  2522. }
  2523. return pnode;
  2524. }
  2525. /***************************************************************************
  2526. Parse an expression term.
  2527. ***************************************************************************/
  2528. template<bool buildAST>
  2529. ParseNodePtr Parser::ParseTerm(BOOL fAllowCall,
  2530. LPCOLESTR pNameHint,
  2531. uint32 *pHintLength,
  2532. uint32 *pShortNameOffset,
  2533. _Inout_opt_ IdentToken* pToken /*= nullptr*/,
  2534. bool fUnaryOrParen /*= false*/,
  2535. _Out_opt_ BOOL* pfCanAssign /*= nullptr*/,
  2536. _Inout_opt_ BOOL* pfLikelyPattern /*= nullptr*/,
  2537. _Out_opt_ bool* pfIsDotOrIndex /*= nullptr*/,
  2538. _Inout_opt_ charcount_t *plastRParen /*= nullptr*/)
  2539. {
  2540. ParseNodePtr pnode = nullptr;
  2541. PidRefStack *savedTopAsyncRef = nullptr;
  2542. charcount_t ichMin = 0;
  2543. charcount_t ichLim = 0;
  2544. size_t iecpMin = 0;
  2545. size_t iecpLim = 0;
  2546. size_t iuMin;
  2547. IdentToken term;
  2548. BOOL fInNew = FALSE;
  2549. BOOL fCanAssign = TRUE;
  2550. bool isAsyncExpr = false;
  2551. bool isLambdaExpr = false;
  2552. bool isSpecialName = false;
  2553. IdentPtr pid = nullptr;
  2554. Assert(pToken == nullptr || pToken->tk == tkNone); // Must be empty initially
  2555. PROBE_STACK_NO_DISPOSE(m_scriptContext, Js::Constants::MinStackParseOneTerm);
  2556. switch (m_token.tk)
  2557. {
  2558. case tkID:
  2559. {
  2560. pid = m_token.GetIdentifier(m_phtbl);
  2561. ichMin = m_pscan->IchMinTok();
  2562. iecpMin = m_pscan->IecpMinTok();
  2563. ichLim = m_pscan->IchLimTok();
  2564. iecpLim = m_pscan->IecpLimTok();
  2565. if (pid == wellKnownPropertyPids.async &&
  2566. m_scriptContext->GetConfig()->IsES7AsyncAndAwaitEnabled())
  2567. {
  2568. isAsyncExpr = true;
  2569. }
  2570. // Put this into a block to avoid previousAwaitIsKeyword being not initialized after jump to LIdentifier
  2571. {
  2572. bool previousAwaitIsKeyword = m_pscan->SetAwaitIsKeywordRegion(isAsyncExpr);
  2573. m_pscan->Scan();
  2574. m_pscan->SetAwaitIsKeywordRegion(previousAwaitIsKeyword);
  2575. }
  2576. // We search for an Async expression (a function declaration or an async lambda expression)
  2577. if (isAsyncExpr && !m_pscan->FHadNewLine())
  2578. {
  2579. if (m_token.tk == tkFUNCTION)
  2580. {
  2581. goto LFunction;
  2582. }
  2583. else if (m_token.tk == tkID || m_token.tk == tkAWAIT)
  2584. {
  2585. isLambdaExpr = true;
  2586. goto LFunction;
  2587. }
  2588. else if (m_token.tk == tkLParen)
  2589. {
  2590. // This is potentially an async arrow function. Save the state of the async references
  2591. // in case it needs to be restored. (Note that the case of a single parameter with no ()'s
  2592. // is detected upstream and need not be handled here.)
  2593. savedTopAsyncRef = pid->GetTopRef();
  2594. }
  2595. }
  2596. CheckArgumentsUse(pid, GetCurrentFunctionNode());
  2597. // Assume this pid is not special - overwrite when we parse a special name
  2598. isSpecialName = false;
  2599. LIdentifier:
  2600. PidRefStack *ref = nullptr;
  2601. // Don't push a reference if this is a single lambda parameter, because we'll reparse with
  2602. // a correct function ID.
  2603. if (m_token.tk != tkDArrow)
  2604. {
  2605. ref = this->PushPidRef(pid);
  2606. }
  2607. if (buildAST)
  2608. {
  2609. if (isSpecialName)
  2610. {
  2611. pnode = CreateSpecialNameNode(pid);
  2612. if (pid == wellKnownPropertyPids._super ||
  2613. pid == wellKnownPropertyPids._superConstructor)
  2614. {
  2615. pnode->AsParseNodeSpecialName()->isSuper = true;
  2616. }
  2617. else if (pid == wellKnownPropertyPids._this)
  2618. {
  2619. pnode->AsParseNodeSpecialName()->isThis = true;
  2620. }
  2621. }
  2622. else
  2623. {
  2624. pnode = CreateNameNode(pid);
  2625. }
  2626. pnode->ichMin = ichMin;
  2627. pnode->ichLim = ichLim;
  2628. pnode->AsParseNodePid()->SetSymRef(ref);
  2629. }
  2630. else
  2631. {
  2632. // Remember the identifier start and end in case it turns out to be a statement label.
  2633. term.tk = tkID;
  2634. term.pid = pid; // Record the identifier for detection of eval
  2635. term.ichMin = static_cast<charcount_t>(iecpMin);
  2636. term.ichLim = static_cast<charcount_t>(iecpLim);
  2637. }
  2638. break;
  2639. }
  2640. case tkSUPER:
  2641. ichMin = m_pscan->IchMinTok();
  2642. iecpMin = m_pscan->IecpMinTok();
  2643. ichLim = m_pscan->IchLimTok();
  2644. iecpLim = m_pscan->IecpLimTok();
  2645. if (!m_scriptContext->GetConfig()->IsES6ClassAndExtendsEnabled())
  2646. {
  2647. goto LUnknown;
  2648. }
  2649. m_pscan->Scan();
  2650. pid = ParseSuper<buildAST>(!!fAllowCall);
  2651. isSpecialName = true;
  2652. // Super reference and super call need to push a pid ref to 'this' even when not building an AST
  2653. ReferenceSpecialName(wellKnownPropertyPids._this, ichMin, ichLim);
  2654. // Super call needs to reference 'new.target'
  2655. if (pid == wellKnownPropertyPids._superConstructor)
  2656. {
  2657. ReferenceSpecialName(wellKnownPropertyPids._newTarget, ichMin, ichLim);
  2658. }
  2659. goto LIdentifier;
  2660. case tkTHIS:
  2661. ichMin = m_pscan->IchMinTok();
  2662. iecpMin = m_pscan->IecpMinTok();
  2663. ichLim = m_pscan->IchLimTok();
  2664. iecpLim = m_pscan->IecpLimTok();
  2665. pid = wellKnownPropertyPids._this;
  2666. m_pscan->Scan();
  2667. isSpecialName = true;
  2668. goto LIdentifier;
  2669. case tkLParen:
  2670. {
  2671. ichMin = m_pscan->IchMinTok();
  2672. iuMin = m_pscan->IecpMinTok();
  2673. m_pscan->Scan();
  2674. if (m_token.tk == tkRParen)
  2675. {
  2676. // Empty parens can only be legal as an empty parameter list to a lambda declaration.
  2677. // We're in a lambda if the next token is =>.
  2678. fAllowCall = FALSE;
  2679. m_pscan->Scan();
  2680. // If the token after the right paren is not => or if there was a newline between () and => this is a syntax error
  2681. if (!IsDoingFastScan() && (m_token.tk != tkDArrow || m_pscan->FHadNewLine()))
  2682. {
  2683. Error(ERRsyntax);
  2684. }
  2685. if (buildAST)
  2686. {
  2687. pnode = CreateNodeWithScanner<knopEmpty>();
  2688. }
  2689. break;
  2690. }
  2691. // Advance the block ID here in case this parenthetical expression turns out to be a lambda parameter list.
  2692. // That way the pid ref stacks will be created in their correct final form, and we can simply fix
  2693. // up function ID's.
  2694. uint saveNextBlockId = m_nextBlockId;
  2695. uint saveCurrBlockId = GetCurrentBlock()->AsParseNodeBlock()->blockId;
  2696. GetCurrentBlock()->AsParseNodeBlock()->blockId = m_nextBlockId++;
  2697. // Push the deferred error state for ellipsis errors. It is possible that another syntax error will occur before we undefer this one.
  2698. bool deferEllipsisErrorSave = m_deferEllipsisError;
  2699. RestorePoint ellipsisErrorLocSave = m_deferEllipsisErrorLoc;
  2700. this->m_funcParenExprDepth++;
  2701. pnode = ParseExpr<buildAST>(koplNo, &fCanAssign, TRUE, FALSE, nullptr, nullptr /*nameLength*/, nullptr /*pShortNameOffset*/, &term, true, nullptr, plastRParen);
  2702. this->m_funcParenExprDepth--;
  2703. if (buildAST && plastRParen)
  2704. {
  2705. *plastRParen = m_pscan->IchLimTok();
  2706. }
  2707. ChkCurTok(tkRParen, ERRnoRparen);
  2708. GetCurrentBlock()->AsParseNodeBlock()->blockId = saveCurrBlockId;
  2709. if (m_token.tk == tkDArrow)
  2710. {
  2711. // We're going to rewind and reinterpret the expression as a parameter list.
  2712. // Put back the original next-block-ID so the existing pid ref stacks will be correct.
  2713. m_nextBlockId = saveNextBlockId;
  2714. }
  2715. // Emit a deferred ... error if one was parsed.
  2716. if (m_deferEllipsisError && m_token.tk != tkDArrow)
  2717. {
  2718. m_pscan->SeekTo(m_deferEllipsisErrorLoc);
  2719. Error(ERRInvalidSpreadUse);
  2720. }
  2721. else
  2722. {
  2723. m_deferEllipsisError = false;
  2724. }
  2725. // We didn't error out, so restore the deferred error state.
  2726. m_deferEllipsisError = deferEllipsisErrorSave;
  2727. m_deferEllipsisErrorLoc = ellipsisErrorLocSave;
  2728. break;
  2729. }
  2730. case tkIntCon:
  2731. if (IsStrictMode() && m_pscan->IsOctOrLeadingZeroOnLastTKNumber())
  2732. {
  2733. Error(ERRES5NoOctal);
  2734. }
  2735. if (buildAST)
  2736. {
  2737. pnode = CreateIntNodeWithScanner(m_token.GetLong());
  2738. }
  2739. fCanAssign = FALSE;
  2740. m_pscan->Scan();
  2741. break;
  2742. case tkFltCon:
  2743. if (IsStrictMode() && m_pscan->IsOctOrLeadingZeroOnLastTKNumber())
  2744. {
  2745. Error(ERRES5NoOctal);
  2746. }
  2747. if (buildAST)
  2748. {
  2749. pnode = CreateNodeWithScanner<knopFlt>();
  2750. pnode->AsParseNodeFloat()->dbl = m_token.GetDouble();
  2751. pnode->AsParseNodeFloat()->maybeInt = m_token.GetDoubleMayBeInt();
  2752. }
  2753. fCanAssign = FALSE;
  2754. m_pscan->Scan();
  2755. break;
  2756. case tkStrCon:
  2757. if (IsStrictMode() && m_pscan->IsOctOrLeadingZeroOnLastTKNumber())
  2758. {
  2759. Error(ERRES5NoOctal);
  2760. }
  2761. if (buildAST)
  2762. {
  2763. pnode = CreateStrNodeWithScanner(m_token.GetStr());
  2764. }
  2765. else
  2766. {
  2767. // Subtract the string literal length from the total char count for the purpose
  2768. // of deciding whether to defer parsing and byte code generation.
  2769. this->ReduceDeferredScriptLength(m_pscan->IchLimTok() - m_pscan->IchMinTok());
  2770. }
  2771. fCanAssign = FALSE;
  2772. m_pscan->Scan();
  2773. break;
  2774. case tkTRUE:
  2775. if (buildAST)
  2776. {
  2777. pnode = CreateNodeWithScanner<knopTrue>();
  2778. }
  2779. fCanAssign = FALSE;
  2780. m_pscan->Scan();
  2781. break;
  2782. case tkFALSE:
  2783. if (buildAST)
  2784. {
  2785. pnode = CreateNodeWithScanner<knopFalse>();
  2786. }
  2787. fCanAssign = FALSE;
  2788. m_pscan->Scan();
  2789. break;
  2790. case tkNULL:
  2791. if (buildAST)
  2792. {
  2793. pnode = CreateNodeWithScanner<knopNull>();
  2794. }
  2795. fCanAssign = FALSE;
  2796. m_pscan->Scan();
  2797. break;
  2798. case tkDiv:
  2799. case tkAsgDiv:
  2800. pnode = ParseRegExp<buildAST>();
  2801. fCanAssign = FALSE;
  2802. m_pscan->Scan();
  2803. break;
  2804. case tkNEW:
  2805. {
  2806. ichMin = m_pscan->IchMinTok();
  2807. iecpMin = m_pscan->IecpMinTok();
  2808. m_pscan->Scan();
  2809. if (m_token.tk == tkDot && m_scriptContext->GetConfig()->IsES6ClassAndExtendsEnabled())
  2810. {
  2811. pid = ParseMetaProperty<buildAST>(tkNEW, ichMin, &fCanAssign);
  2812. ichLim = m_pscan->IchLimTok();
  2813. iecpLim = m_pscan->IecpLimTok();
  2814. m_pscan->Scan();
  2815. isSpecialName = true;
  2816. goto LIdentifier;
  2817. }
  2818. else
  2819. {
  2820. ParseNodePtr pnodeExpr = ParseTerm<buildAST>(FALSE, pNameHint, pHintLength, pShortNameOffset, nullptr, false, nullptr, nullptr, nullptr, plastRParen);
  2821. if (buildAST)
  2822. {
  2823. pnode = CreateCallNode(knopNew, pnodeExpr, nullptr);
  2824. pnode->ichMin = ichMin;
  2825. }
  2826. fInNew = TRUE;
  2827. fCanAssign = FALSE;
  2828. }
  2829. break;
  2830. }
  2831. case tkLBrack:
  2832. {
  2833. ichMin = m_pscan->IchMinTok();
  2834. m_pscan->Scan();
  2835. pnode = ParseArrayLiteral<buildAST>();
  2836. if (buildAST)
  2837. {
  2838. pnode->ichMin = ichMin;
  2839. pnode->ichLim = m_pscan->IchLimTok();
  2840. }
  2841. if (this->m_arrayDepth == 0)
  2842. {
  2843. Assert(m_pscan->IchLimTok() - ichMin > m_funcInArray);
  2844. this->ReduceDeferredScriptLength(m_pscan->IchLimTok() - ichMin - this->m_funcInArray);
  2845. this->m_funcInArray = 0;
  2846. this->m_funcInArrayDepth = 0;
  2847. }
  2848. ChkCurTok(tkRBrack, ERRnoRbrack);
  2849. if (!IsES6DestructuringEnabled())
  2850. {
  2851. fCanAssign = FALSE;
  2852. }
  2853. else if (pfLikelyPattern != nullptr && !IsPostFixOperators())
  2854. {
  2855. *pfLikelyPattern = TRUE;
  2856. }
  2857. break;
  2858. }
  2859. case tkLCurly:
  2860. {
  2861. ichMin = m_pscan->IchMinTok();
  2862. m_pscan->ScanForcingPid();
  2863. ParseNodePtr pnodeMemberList = ParseMemberList<buildAST>(pNameHint, pHintLength);
  2864. if (buildAST)
  2865. {
  2866. pnode = CreateUniNode(knopObject, pnodeMemberList);
  2867. pnode->ichMin = ichMin;
  2868. pnode->ichLim = m_pscan->IchLimTok();
  2869. }
  2870. ChkCurTok(tkRCurly, ERRnoRcurly);
  2871. if (!IsES6DestructuringEnabled())
  2872. {
  2873. fCanAssign = FALSE;
  2874. }
  2875. else if (pfLikelyPattern != nullptr && !IsPostFixOperators())
  2876. {
  2877. *pfLikelyPattern = TRUE;
  2878. }
  2879. break;
  2880. }
  2881. case tkFUNCTION:
  2882. {
  2883. LFunction :
  2884. if (m_grfscr & fscrDeferredFncExpression)
  2885. {
  2886. // The top-level deferred function body was defined by a function expression whose parsing was deferred. We are now
  2887. // parsing it, so unset the flag so that any nested functions are parsed normally. This flag is only applicable the
  2888. // first time we see it.
  2889. //
  2890. // Normally, deferred functions will be parsed in ParseStatement upon encountering the 'function' token. The first
  2891. // token of the source code of the function may not a 'function' token though, so we still need to reset this flag
  2892. // for the first function we parse. This can happen in compat modes, for instance, for a function expression enclosed
  2893. // in parentheses, where the legacy behavior was to include the parentheses in the function's source code.
  2894. m_grfscr &= ~fscrDeferredFncExpression;
  2895. }
  2896. ushort flags = fFncNoFlgs;
  2897. if (isLambdaExpr)
  2898. {
  2899. flags |= fFncLambda;
  2900. }
  2901. if (isAsyncExpr)
  2902. {
  2903. flags |= fFncAsync;
  2904. }
  2905. pnode = ParseFncDecl<buildAST>(flags, pNameHint, false, true, fUnaryOrParen);
  2906. if (isAsyncExpr)
  2907. {
  2908. pnode->AsParseNodeFnc()->cbMin = iecpMin;
  2909. pnode->ichMin = ichMin;
  2910. }
  2911. fCanAssign = FALSE;
  2912. break;
  2913. }
  2914. case tkCLASS:
  2915. if (m_scriptContext->GetConfig()->IsES6ClassAndExtendsEnabled())
  2916. {
  2917. pnode = ParseClassDecl<buildAST>(FALSE, pNameHint, pHintLength, pShortNameOffset);
  2918. }
  2919. else
  2920. {
  2921. goto LUnknown;
  2922. }
  2923. fCanAssign = FALSE;
  2924. break;
  2925. case tkStrTmplBasic:
  2926. case tkStrTmplBegin:
  2927. pnode = ParseStringTemplateDecl<buildAST>(nullptr);
  2928. fCanAssign = FALSE;
  2929. break;
  2930. case tkIMPORT:
  2931. if (m_scriptContext->GetConfig()->IsES6ModuleEnabled() && m_scriptContext->GetConfig()->IsESDynamicImportEnabled())
  2932. {
  2933. m_pscan->Scan();
  2934. ChkCurTokNoScan(tkLParen, ERRnoLparen);
  2935. pnode = ParseImportCall<buildAST>();
  2936. }
  2937. else
  2938. {
  2939. goto LUnknown;
  2940. }
  2941. break;
  2942. #if ENABLE_BACKGROUND_PARSING
  2943. case tkCASE:
  2944. {
  2945. if (!m_doingFastScan)
  2946. {
  2947. goto LUnknown;
  2948. }
  2949. ParseNodePtr pnodeUnused;
  2950. pnode = ParseCase<buildAST>(&pnodeUnused);
  2951. break;
  2952. }
  2953. case tkELSE:
  2954. if (!m_doingFastScan)
  2955. {
  2956. goto LUnknown;
  2957. }
  2958. m_pscan->Scan();
  2959. ParseStatement<buildAST>();
  2960. break;
  2961. #endif
  2962. default:
  2963. LUnknown :
  2964. Error(ERRsyntax);
  2965. break;
  2966. }
  2967. pnode = ParsePostfixOperators<buildAST>(pnode, fAllowCall, fInNew, isAsyncExpr, &fCanAssign, &term, pfIsDotOrIndex);
  2968. if (savedTopAsyncRef != nullptr &&
  2969. this->m_token.tk == tkDArrow)
  2970. {
  2971. // This is an async arrow function; we're going to back up and reparse it.
  2972. // Make sure we don't leave behind a bogus reference to the 'async' identifier.
  2973. for (pid = wellKnownPropertyPids.async; pid->GetTopRef() != savedTopAsyncRef;)
  2974. {
  2975. Assert(pid->GetTopRef() != nullptr);
  2976. pid->RemovePrevPidRef(nullptr);
  2977. }
  2978. }
  2979. // Pass back identifier if requested
  2980. if (pToken && term.tk == tkID)
  2981. {
  2982. *pToken = term;
  2983. }
  2984. if (pfCanAssign)
  2985. {
  2986. *pfCanAssign = fCanAssign;
  2987. }
  2988. return pnode;
  2989. }
  2990. template <bool buildAST>
  2991. ParseNodePtr Parser::ParseRegExp()
  2992. {
  2993. ParseNodePtr pnode = nullptr;
  2994. if (buildAST || IsDoingFastScan())
  2995. {
  2996. m_pscan->RescanRegExp();
  2997. #if ENABLE_BACKGROUND_PARSING
  2998. BOOL saveDeferringAST = this->m_deferringAST;
  2999. if (m_doingFastScan)
  3000. {
  3001. this->m_deferringAST = false;
  3002. }
  3003. #endif
  3004. pnode = CreateNodeWithScanner<knopRegExp>();
  3005. pnode->AsParseNodePid()->regexPattern = m_token.GetRegex();
  3006. #if ENABLE_BACKGROUND_PARSING
  3007. if (m_doingFastScan)
  3008. {
  3009. this->m_deferringAST = saveDeferringAST;
  3010. this->AddFastScannedRegExpNode(pnode);
  3011. if (!buildAST)
  3012. {
  3013. pnode = nullptr;
  3014. }
  3015. }
  3016. else if (this->IsBackgroundParser())
  3017. {
  3018. Assert(pnode->AsParseNodePid()->regexPattern == nullptr);
  3019. this->AddBackgroundRegExpNode(pnode);
  3020. }
  3021. #endif
  3022. }
  3023. else
  3024. {
  3025. m_pscan->RescanRegExpNoAST();
  3026. }
  3027. Assert(m_token.tk == tkRegExp);
  3028. return pnode;
  3029. }
  3030. BOOL Parser::NodeIsEvalName(ParseNodePtr pnode)
  3031. {
  3032. //WOOB 1107758 Special case of indirect eval binds to local scope in standards mode
  3033. return pnode->nop == knopName && (pnode->AsParseNodePid()->pid == wellKnownPropertyPids.eval);
  3034. }
  3035. BOOL Parser::NodeIsSuperName(ParseNodePtr pnode)
  3036. {
  3037. return pnode->nop == knopName && (pnode->AsParseNodePid()->pid == wellKnownPropertyPids._superConstructor);
  3038. }
  3039. BOOL Parser::NodeEqualsName(ParseNodePtr pnode, LPCOLESTR sz, uint32 cch)
  3040. {
  3041. return pnode->nop == knopName &&
  3042. pnode->AsParseNodePid()->pid->Cch() == cch &&
  3043. !wmemcmp(pnode->AsParseNodePid()->pid->Psz(), sz, cch);
  3044. }
  3045. BOOL Parser::NodeIsIdent(ParseNodePtr pnode, IdentPtr pid)
  3046. {
  3047. for (;;)
  3048. {
  3049. switch (pnode->nop)
  3050. {
  3051. case knopName:
  3052. return (pnode->AsParseNodePid()->pid == pid);
  3053. case knopComma:
  3054. pnode = pnode->AsParseNodeBin()->pnode2;
  3055. break;
  3056. default:
  3057. return FALSE;
  3058. }
  3059. }
  3060. }
  3061. template<bool buildAST>
  3062. ParseNodePtr Parser::ParsePostfixOperators(
  3063. ParseNodePtr pnode,
  3064. BOOL fAllowCall,
  3065. BOOL fInNew,
  3066. BOOL isAsyncExpr,
  3067. BOOL *pfCanAssign,
  3068. _Inout_ IdentToken* pToken,
  3069. _Out_opt_ bool* pfIsDotOrIndex /*= nullptr */)
  3070. {
  3071. uint16 count = 0;
  3072. bool callOfConstants = false;
  3073. if (pfIsDotOrIndex)
  3074. {
  3075. *pfIsDotOrIndex = false;
  3076. }
  3077. for (;;)
  3078. {
  3079. uint16 spreadArgCount = 0;
  3080. switch (m_token.tk)
  3081. {
  3082. case tkLParen:
  3083. {
  3084. AutoMarkInParsingArgs autoMarkInParsingArgs(this);
  3085. if (fInNew)
  3086. {
  3087. ParseNodePtr pnodeArgs = ParseArgList<buildAST>(&callOfConstants, &spreadArgCount, &count);
  3088. if (buildAST)
  3089. {
  3090. Assert(pnode->nop == knopNew);
  3091. Assert(pnode->AsParseNodeCall()->pnodeArgs == nullptr);
  3092. pnode->AsParseNodeCall()->pnodeArgs = pnodeArgs;
  3093. pnode->AsParseNodeCall()->callOfConstants = callOfConstants;
  3094. pnode->AsParseNodeCall()->isApplyCall = false;
  3095. pnode->AsParseNodeCall()->isEvalCall = false;
  3096. pnode->AsParseNodeCall()->isSuperCall = false;
  3097. pnode->AsParseNodeCall()->hasDestructuring = m_hasDestructuringPattern;
  3098. Assert(!m_hasDestructuringPattern || count > 0);
  3099. pnode->AsParseNodeCall()->argCount = count;
  3100. pnode->AsParseNodeCall()->spreadArgCount = spreadArgCount;
  3101. pnode->ichLim = m_pscan->IchLimTok();
  3102. }
  3103. else
  3104. {
  3105. pnode = nullptr;
  3106. pToken->tk = tkNone; // This is no longer an identifier
  3107. }
  3108. fInNew = FALSE;
  3109. ChkCurTok(tkRParen, ERRnoRparen);
  3110. }
  3111. else
  3112. {
  3113. if (!fAllowCall)
  3114. {
  3115. return pnode;
  3116. }
  3117. uint saveNextBlockId = m_nextBlockId;
  3118. uint saveCurrBlockId = GetCurrentBlock()->AsParseNodeBlock()->blockId;
  3119. if (isAsyncExpr)
  3120. {
  3121. // Advance the block ID here in case this parenthetical expression turns out to be a lambda parameter list.
  3122. // That way the pid ref stacks will be created in their correct final form, and we can simply fix
  3123. // up function ID's.
  3124. GetCurrentBlock()->AsParseNodeBlock()->blockId = m_nextBlockId++;
  3125. }
  3126. ParseNodePtr pnodeArgs = ParseArgList<buildAST>(&callOfConstants, &spreadArgCount, &count);
  3127. // We used to un-defer a deferred function body here if it was called as part of the expression that declared it.
  3128. // We now detect this case up front in ParseFncDecl, which is cheaper and simpler.
  3129. if (buildAST)
  3130. {
  3131. bool fCallIsEval = false;
  3132. // Detect super()
  3133. if (this->NodeIsSuperName(pnode))
  3134. {
  3135. pnode = CreateSuperCallNode(pnode, pnodeArgs);
  3136. Assert(pnode);
  3137. pnode->AsParseNodeSuperCall()->pnodeThis = ReferenceSpecialName(wellKnownPropertyPids._this, pnode->ichMin, m_pscan->IchLimTok(), true);
  3138. pnode->AsParseNodeSuperCall()->pnodeNewTarget = ReferenceSpecialName(wellKnownPropertyPids._newTarget, pnode->ichMin, m_pscan->IchLimTok(), true);
  3139. }
  3140. else
  3141. {
  3142. pnode = CreateCallNode(knopCall, pnode, pnodeArgs);
  3143. Assert(pnode);
  3144. }
  3145. // Detect call to "eval" and record it on the function.
  3146. // Note: we used to leave it up to the byte code generator to detect eval calls
  3147. // at global scope, but now it relies on the flag the parser sets, so set it here.
  3148. if (count > 0 && this->NodeIsEvalName(pnode->AsParseNodeCall()->pnodeTarget))
  3149. {
  3150. this->MarkEvalCaller();
  3151. fCallIsEval = true;
  3152. // Eval may reference any of the special symbols so we need to push refs to them here.
  3153. ReferenceSpecialName(wellKnownPropertyPids._this);
  3154. ReferenceSpecialName(wellKnownPropertyPids._newTarget);
  3155. ReferenceSpecialName(wellKnownPropertyPids._super);
  3156. ReferenceSpecialName(wellKnownPropertyPids._superConstructor);
  3157. ReferenceSpecialName(wellKnownPropertyPids.arguments);
  3158. }
  3159. pnode->AsParseNodeCall()->callOfConstants = callOfConstants;
  3160. pnode->AsParseNodeCall()->spreadArgCount = spreadArgCount;
  3161. pnode->AsParseNodeCall()->isApplyCall = false;
  3162. pnode->AsParseNodeCall()->isEvalCall = fCallIsEval;
  3163. pnode->AsParseNodeCall()->hasDestructuring = m_hasDestructuringPattern;
  3164. Assert(!m_hasDestructuringPattern || count > 0);
  3165. pnode->AsParseNodeCall()->argCount = count;
  3166. pnode->ichLim = m_pscan->IchLimTok();
  3167. }
  3168. else
  3169. {
  3170. pnode = nullptr;
  3171. if (pToken->tk == tkID && pToken->pid == wellKnownPropertyPids.eval && count > 0) // Detect eval
  3172. {
  3173. this->MarkEvalCaller();
  3174. ReferenceSpecialName(wellKnownPropertyPids._this);
  3175. ReferenceSpecialName(wellKnownPropertyPids._newTarget);
  3176. ReferenceSpecialName(wellKnownPropertyPids._super);
  3177. ReferenceSpecialName(wellKnownPropertyPids._superConstructor);
  3178. ReferenceSpecialName(wellKnownPropertyPids.arguments);
  3179. }
  3180. pToken->tk = tkNone; // This is no longer an identifier
  3181. }
  3182. ChkCurTok(tkRParen, ERRnoRparen);
  3183. if (isAsyncExpr)
  3184. {
  3185. GetCurrentBlock()->AsParseNodeBlock()->blockId = saveCurrBlockId;
  3186. if (m_token.tk == tkDArrow)
  3187. {
  3188. // We're going to rewind and reinterpret the expression as a parameter list.
  3189. // Put back the original next-block-ID so the existing pid ref stacks will be correct.
  3190. m_nextBlockId = saveNextBlockId;
  3191. }
  3192. }
  3193. }
  3194. if (pfCanAssign)
  3195. {
  3196. *pfCanAssign = FALSE;
  3197. }
  3198. if (pfIsDotOrIndex)
  3199. {
  3200. *pfIsDotOrIndex = false;
  3201. }
  3202. break;
  3203. }
  3204. case tkLBrack:
  3205. {
  3206. m_pscan->Scan();
  3207. IdentToken tok;
  3208. ParseNodePtr pnodeExpr = ParseExpr<buildAST>(0, FALSE, TRUE, FALSE, nullptr, nullptr, nullptr, &tok);
  3209. if (buildAST)
  3210. {
  3211. if (pnode && pnode->isSpecialName && pnode->AsParseNodeSpecialName()->isSuper)
  3212. {
  3213. pnode = CreateSuperReferenceNode(knopIndex, pnode, pnodeExpr);
  3214. pnode->AsParseNodeSuperReference()->pnodeThis = ReferenceSpecialName(wellKnownPropertyPids._this, pnode->ichMin, pnode->ichLim, true);
  3215. }
  3216. else
  3217. {
  3218. pnode = CreateBinNode(knopIndex, pnode, pnodeExpr);
  3219. }
  3220. AnalysisAssert(pnode);
  3221. pnode->ichLim = m_pscan->IchLimTok();
  3222. }
  3223. else
  3224. {
  3225. pnode = nullptr;
  3226. pToken->tk = tkNone; // This is no longer an identifier
  3227. }
  3228. ChkCurTok(tkRBrack, ERRnoRbrack);
  3229. if (pfCanAssign)
  3230. {
  3231. *pfCanAssign = TRUE;
  3232. }
  3233. if (pfIsDotOrIndex)
  3234. {
  3235. *pfIsDotOrIndex = true;
  3236. }
  3237. PidRefStack * topPidRef = nullptr;
  3238. if (buildAST)
  3239. {
  3240. if (pnodeExpr && pnodeExpr->nop == knopName)
  3241. {
  3242. topPidRef = pnodeExpr->AsParseNodePid()->pid->GetTopRef();
  3243. }
  3244. }
  3245. else if (tok.tk == tkID)
  3246. {
  3247. topPidRef = tok.pid->GetTopRef();
  3248. }
  3249. if (topPidRef)
  3250. {
  3251. topPidRef->SetIsUsedInLdElem(true);
  3252. }
  3253. if (!buildAST)
  3254. {
  3255. break;
  3256. }
  3257. bool shouldConvertToDot = false;
  3258. if (pnode->AsParseNodeBin()->pnode2->nop == knopStr)
  3259. {
  3260. // if the string is empty or contains escape character, we will not convert them to dot node
  3261. shouldConvertToDot = pnode->AsParseNodeBin()->pnode2->AsParseNodePid()->pid->Cch() > 0 && !m_pscan->IsEscapeOnLastTkStrCon();
  3262. }
  3263. if (shouldConvertToDot)
  3264. {
  3265. LPCOLESTR str = pnode->AsParseNodeBin()->pnode2->AsParseNodePid()->pid->Psz();
  3266. // See if we can convert o["p"] into o.p and o["0"] into o[0] since they're equivalent and the latter forms
  3267. // are faster
  3268. uint32 uintValue;
  3269. if(Js::JavascriptOperators::TryConvertToUInt32(
  3270. str,
  3271. pnode->AsParseNodeBin()->pnode2->AsParseNodePid()->pid->Cch(),
  3272. &uintValue) &&
  3273. !Js::TaggedInt::IsOverflow(uintValue)) // the optimization is not very useful if the number can't be represented as a TaggedInt
  3274. {
  3275. // No need to verify that uintValue != JavascriptArray::InvalidIndex since all nonnegative TaggedInts are valid indexes
  3276. auto intNode = CreateIntNodeWithScanner(uintValue); // implicit conversion from uint32 to int32
  3277. pnode->AsParseNodeBin()->pnode2 = intNode;
  3278. }
  3279. // Field optimization (see GlobOpt::KillLiveElems) checks for value being a Number,
  3280. // and since NaN/Infinity is a number it won't kill o.NaN/o.Infinity which would cause a problem
  3281. // if we decide to hoist o.NaN/o.Infinity.
  3282. // We need to keep o["NaN"] and o["+/-Infinity"] as array element access (we don't hoist that but we may hoist field access),
  3283. // so no matter if it's killed by o[x] inside a loop, we make sure that we never hoist these.
  3284. // We need to follow same logic for strings that convert to a floating point number.
  3285. else
  3286. {
  3287. bool doConvertToProperty = false; // Convert a["x"] -> a.x.
  3288. if (!Parser::IsNaNOrInfinityLiteral<true>(str))
  3289. {
  3290. const OLECHAR* terminalChar;
  3291. double dbl = Js::NumberUtilities::StrToDbl(str, &terminalChar, m_scriptContext);
  3292. bool convertsToFloat = !Js::NumberUtilities::IsNan(dbl);
  3293. doConvertToProperty = !convertsToFloat;
  3294. }
  3295. if (doConvertToProperty)
  3296. {
  3297. pnode->AsParseNodeBin()->pnode2->nop = knopName;
  3298. pnode->nop = knopDot;
  3299. pnode->grfpn |= PNodeFlags::fpnIndexOperator;
  3300. }
  3301. }
  3302. }
  3303. }
  3304. break;
  3305. case tkDot:
  3306. {
  3307. ParseNodePtr name = nullptr;
  3308. OpCode opCode = knopDot;
  3309. m_pscan->Scan();
  3310. if (!m_token.IsIdentifier())
  3311. {
  3312. //allow reserved words in ES5 mode
  3313. if (!(m_token.IsReservedWord()))
  3314. {
  3315. IdentifierExpectedError(m_token);
  3316. }
  3317. }
  3318. // Note: see comment above about field optimization WRT NaN/Infinity/-Infinity.
  3319. // Convert a.Nan, a.Infinity into a["NaN"], a["Infinity"].
  3320. // We don't care about -Infinity case here because x.-Infinity is invalid in JavaScript.
  3321. // Both NaN and Infinity are identifiers.
  3322. else if (buildAST && Parser::IsNaNOrInfinityLiteral<false>(m_token.GetIdentifier(m_phtbl)->Psz()))
  3323. {
  3324. opCode = knopIndex;
  3325. }
  3326. if (buildAST)
  3327. {
  3328. if (opCode == knopDot)
  3329. {
  3330. name = CreateNameNode(m_token.GetIdentifier(m_phtbl));
  3331. }
  3332. else
  3333. {
  3334. Assert(opCode == knopIndex);
  3335. name = CreateStrNodeWithScanner(m_token.GetIdentifier(m_phtbl));
  3336. }
  3337. if (pnode && pnode->isSpecialName && pnode->AsParseNodeSpecialName()->isSuper)
  3338. {
  3339. pnode = CreateSuperReferenceNode(opCode, pnode, name);
  3340. pnode->AsParseNodeSuperReference()->pnodeThis = ReferenceSpecialName(wellKnownPropertyPids._this, pnode->ichMin, pnode->ichLim, true);
  3341. }
  3342. else
  3343. {
  3344. pnode = CreateBinNode(opCode, pnode, name);
  3345. }
  3346. }
  3347. else
  3348. {
  3349. pnode = nullptr;
  3350. pToken->tk = tkNone;
  3351. }
  3352. if (pfCanAssign)
  3353. {
  3354. *pfCanAssign = TRUE;
  3355. }
  3356. if (pfIsDotOrIndex)
  3357. {
  3358. *pfIsDotOrIndex = true;
  3359. }
  3360. m_pscan->Scan();
  3361. break;
  3362. }
  3363. case tkStrTmplBasic:
  3364. case tkStrTmplBegin:
  3365. {
  3366. ParseNode* templateNode = nullptr;
  3367. if (pnode != nullptr)
  3368. {
  3369. AutoMarkInParsingArgs autoMarkInParsingArgs(this);
  3370. templateNode = ParseStringTemplateDecl<buildAST>(pnode);
  3371. }
  3372. else
  3373. {
  3374. templateNode = ParseStringTemplateDecl<buildAST>(pnode);
  3375. }
  3376. if (!buildAST)
  3377. {
  3378. pToken->tk = tkNone; // This is no longer an identifier
  3379. }
  3380. pnode = templateNode;
  3381. if (pfCanAssign)
  3382. {
  3383. *pfCanAssign = FALSE;
  3384. }
  3385. if (pfIsDotOrIndex)
  3386. {
  3387. *pfIsDotOrIndex = false;
  3388. }
  3389. break;
  3390. }
  3391. default:
  3392. return pnode;
  3393. }
  3394. }
  3395. }
  3396. /***************************************************************************
  3397. Look for an existing label with the given name.
  3398. ***************************************************************************/
  3399. bool Parser::LabelExists(IdentPtr pid, LabelId* pLabelIdList)
  3400. {
  3401. StmtNest dummy;
  3402. dummy.pLabelId = pLabelIdList;
  3403. dummy.pstmtOuter = m_pstmtCur;
  3404. // Look through each label list for the current stack of statements
  3405. for (StmtNest* pStmt = &dummy; pStmt != nullptr; pStmt = pStmt->pstmtOuter)
  3406. {
  3407. for (LabelId* pLabelId = pStmt->pLabelId; pLabelId != nullptr; pLabelId = pLabelId->next)
  3408. {
  3409. if (pLabelId->pid == pid)
  3410. return true;
  3411. }
  3412. }
  3413. return false;
  3414. }
  3415. // Currently only ints and floats are treated as constants in function call
  3416. // TODO: Check if we need for other constants as well
  3417. BOOL Parser::IsConstantInFunctionCall(ParseNodePtr pnode)
  3418. {
  3419. if (pnode->nop == knopInt && !Js::TaggedInt::IsOverflow(pnode->AsParseNodeInt()->lw))
  3420. {
  3421. return TRUE;
  3422. }
  3423. if (pnode->nop == knopFlt)
  3424. {
  3425. return TRUE;
  3426. }
  3427. return FALSE;
  3428. }
  3429. /***************************************************************************
  3430. Parse a list of arguments.
  3431. ***************************************************************************/
  3432. template<bool buildAST>
  3433. ParseNodePtr Parser::ParseArgList( bool *pCallOfConstants, uint16 *pSpreadArgCount, uint16 * pCount)
  3434. {
  3435. ParseNodePtr pnodeArg;
  3436. ParseNodePtr pnodeList = nullptr;
  3437. ParseNodePtr *lastNodeRef = nullptr;
  3438. // Check for an empty list
  3439. Assert(m_token.tk == tkLParen);
  3440. if (m_pscan->Scan() == tkRParen)
  3441. {
  3442. return nullptr;
  3443. }
  3444. *pCallOfConstants = true;
  3445. *pSpreadArgCount = 0;
  3446. int count=0;
  3447. while (true)
  3448. {
  3449. if (count >= Js::Constants::MaxAllowedArgs)
  3450. {
  3451. Error(ERRTooManyArgs);
  3452. }
  3453. // Allow spread in argument lists.
  3454. IdentToken token;
  3455. pnodeArg = ParseExpr<buildAST>(koplCma, nullptr, TRUE, /* fAllowEllipsis */TRUE, NULL, nullptr, nullptr, &token);
  3456. ++count;
  3457. this->MarkEscapingRef(pnodeArg, &token);
  3458. if (buildAST)
  3459. {
  3460. this->CheckArguments(pnodeArg);
  3461. if (*pCallOfConstants && !IsConstantInFunctionCall(pnodeArg))
  3462. {
  3463. *pCallOfConstants = false;
  3464. }
  3465. if (pnodeArg->nop == knopEllipsis)
  3466. {
  3467. (*pSpreadArgCount)++;
  3468. }
  3469. AddToNodeListEscapedUse(&pnodeList, &lastNodeRef, pnodeArg);
  3470. }
  3471. if (m_token.tk != tkComma)
  3472. {
  3473. break;
  3474. }
  3475. m_pscan->Scan();
  3476. if (m_token.tk == tkRParen && m_scriptContext->GetConfig()->IsES7TrailingCommaEnabled())
  3477. {
  3478. break;
  3479. }
  3480. }
  3481. if (pSpreadArgCount!=nullptr && (*pSpreadArgCount) > 0){
  3482. CHAKRATEL_LANGSTATS_INC_LANGFEATURECOUNT(ES6, SpreadFeature, m_scriptContext);
  3483. }
  3484. *pCount = static_cast<uint16>(count);
  3485. if (buildAST)
  3486. {
  3487. AssertMem(lastNodeRef);
  3488. AssertNodeMem(*lastNodeRef);
  3489. pnodeList->ichLim = (*lastNodeRef)->ichLim;
  3490. }
  3491. return pnodeList;
  3492. }
  3493. // Currently only ints are treated as constants in ArrayLiterals
  3494. BOOL Parser::IsConstantInArrayLiteral(ParseNodePtr pnode)
  3495. {
  3496. if (pnode->nop == knopInt && !Js::TaggedInt::IsOverflow(pnode->AsParseNodeInt()->lw))
  3497. {
  3498. return TRUE;
  3499. }
  3500. return FALSE;
  3501. }
  3502. template<bool buildAST>
  3503. ParseNodePtr Parser::ParseArrayLiteral()
  3504. {
  3505. ParseNodePtr pnode = nullptr;
  3506. bool arrayOfTaggedInts = false;
  3507. bool arrayOfInts = false;
  3508. bool arrayOfNumbers = false;
  3509. bool hasMissingValues = false;
  3510. uint count = 0;
  3511. uint spreadCount = 0;
  3512. ParseNodePtr pnode1 = ParseArrayList<buildAST>(&arrayOfTaggedInts, &arrayOfInts, &arrayOfNumbers, &hasMissingValues, &count, &spreadCount);
  3513. if (buildAST)
  3514. {
  3515. pnode = CreateNodeWithScanner<knopArray>();
  3516. pnode->AsParseNodeArrLit()->pnode1 = pnode1;
  3517. pnode->AsParseNodeArrLit()->arrayOfTaggedInts = arrayOfTaggedInts;
  3518. pnode->AsParseNodeArrLit()->arrayOfInts = arrayOfInts;
  3519. pnode->AsParseNodeArrLit()->arrayOfNumbers = arrayOfNumbers;
  3520. pnode->AsParseNodeArrLit()->hasMissingValues = hasMissingValues;
  3521. pnode->AsParseNodeArrLit()->count = count;
  3522. pnode->AsParseNodeArrLit()->spreadCount = spreadCount;
  3523. if (pnode->AsParseNodeArrLit()->pnode1)
  3524. {
  3525. this->CheckArguments(pnode->AsParseNodeArrLit()->pnode1);
  3526. }
  3527. }
  3528. return pnode;
  3529. }
  3530. /***************************************************************************
  3531. Create an ArrayLiteral node
  3532. Parse a list of array elements. [ a, b, , c, ]
  3533. ***************************************************************************/
  3534. template<bool buildAST>
  3535. ParseNodePtr Parser::ParseArrayList(bool *pArrayOfTaggedInts, bool *pArrayOfInts, bool *pArrayOfNumbers, bool *pHasMissingValues, uint *count, uint *spreadCount)
  3536. {
  3537. ParseNodePtr pnodeArg = nullptr;
  3538. ParseNodePtr pnodeList = nullptr;
  3539. ParseNodePtr *lastNodeRef = nullptr;
  3540. *count = 0;
  3541. // Check for an empty list
  3542. if (tkRBrack == m_token.tk)
  3543. {
  3544. return nullptr;
  3545. }
  3546. this->m_arrayDepth++;
  3547. bool arrayOfTaggedInts = buildAST;
  3548. bool arrayOfInts = buildAST;
  3549. bool arrayOfNumbers = buildAST;
  3550. bool arrayOfVarInts = false;
  3551. bool hasMissingValues = false;
  3552. for (;;)
  3553. {
  3554. (*count)++;
  3555. if (tkComma == m_token.tk || tkRBrack == m_token.tk)
  3556. {
  3557. hasMissingValues = true;
  3558. arrayOfTaggedInts = false;
  3559. arrayOfInts = false;
  3560. arrayOfNumbers = false;
  3561. if (buildAST)
  3562. {
  3563. pnodeArg = CreateNodeWithScanner<knopEmpty>();
  3564. }
  3565. }
  3566. else
  3567. {
  3568. // Allow Spread in array literals.
  3569. pnodeArg = ParseExpr<buildAST>(koplCma, nullptr, TRUE, /* fAllowEllipsis */ TRUE);
  3570. if (buildAST)
  3571. {
  3572. if (pnodeArg->nop == knopEllipsis)
  3573. {
  3574. (*spreadCount)++;
  3575. }
  3576. this->CheckArguments(pnodeArg);
  3577. }
  3578. }
  3579. #if DEBUG
  3580. if(m_grfscr & fscrEnforceJSON && !IsJSONValid(pnodeArg))
  3581. {
  3582. Error(ERRsyntax);
  3583. }
  3584. #endif
  3585. if (buildAST)
  3586. {
  3587. if (arrayOfNumbers)
  3588. {
  3589. if (pnodeArg->nop != knopInt)
  3590. {
  3591. arrayOfTaggedInts = false;
  3592. if (pnodeArg->nop != knopFlt)
  3593. {
  3594. // Not an array of constants.
  3595. arrayOfInts = false;
  3596. arrayOfNumbers = false;
  3597. }
  3598. else if (arrayOfInts && Js::JavascriptNumber::IsInt32OrUInt32(pnodeArg->AsParseNodeFloat()->dbl) && (!Js::JavascriptNumber::IsInt32(pnodeArg->AsParseNodeFloat()->dbl) || pnodeArg->AsParseNodeFloat()->dbl == -2147483648.0))
  3599. {
  3600. // We've seen nothing but ints, and this is a uint32 but not an int32.
  3601. // Unless we see an actual float at some point, we want an array of vars
  3602. // so we can work with tagged ints.
  3603. arrayOfVarInts = true;
  3604. }
  3605. else
  3606. {
  3607. // Not an int array, but it may still be a float array.
  3608. arrayOfInts = false;
  3609. }
  3610. }
  3611. else
  3612. {
  3613. if (Js::SparseArraySegment<int32>::IsMissingItem((int32*)&pnodeArg->AsParseNodeInt()->lw))
  3614. {
  3615. arrayOfInts = false;
  3616. }
  3617. if (Js::TaggedInt::IsOverflow(pnodeArg->AsParseNodeInt()->lw))
  3618. {
  3619. arrayOfTaggedInts = false;
  3620. }
  3621. }
  3622. }
  3623. AddToNodeListEscapedUse(&pnodeList, &lastNodeRef, pnodeArg);
  3624. }
  3625. if (tkComma != m_token.tk)
  3626. {
  3627. break;
  3628. }
  3629. m_pscan->Scan();
  3630. if (tkRBrack == m_token.tk)
  3631. {
  3632. break;
  3633. }
  3634. }
  3635. if (spreadCount != nullptr && *spreadCount > 0){
  3636. CHAKRATEL_LANGSTATS_INC_LANGFEATURECOUNT(ES6, SpreadFeature, m_scriptContext);
  3637. }
  3638. if (buildAST)
  3639. {
  3640. AssertMem(lastNodeRef);
  3641. AssertNodeMem(*lastNodeRef);
  3642. pnodeList->ichLim = (*lastNodeRef)->ichLim;
  3643. if (arrayOfVarInts && arrayOfInts)
  3644. {
  3645. arrayOfInts = false;
  3646. arrayOfNumbers = false;
  3647. }
  3648. *pArrayOfTaggedInts = arrayOfTaggedInts;
  3649. *pArrayOfInts = arrayOfInts;
  3650. *pArrayOfNumbers = arrayOfNumbers;
  3651. *pHasMissingValues = hasMissingValues;
  3652. }
  3653. this->m_arrayDepth--;
  3654. return pnodeList;
  3655. }
  3656. Parser::MemberNameToTypeMap* Parser::CreateMemberNameMap(ArenaAllocator* pAllocator)
  3657. {
  3658. Assert(pAllocator);
  3659. return Anew(pAllocator, MemberNameToTypeMap, pAllocator, 5);
  3660. }
  3661. template<bool buildAST> void Parser::ParseComputedName(ParseNodePtr* ppnodeName, LPCOLESTR* ppNameHint, LPCOLESTR* ppFullNameHint, uint32 *pNameLength, uint32 *pShortNameOffset)
  3662. {
  3663. m_pscan->Scan();
  3664. ParseNodePtr pnodeNameExpr = ParseExpr<buildAST>(koplCma, nullptr, TRUE, FALSE, *ppNameHint, pNameLength, pShortNameOffset);
  3665. if (buildAST)
  3666. {
  3667. *ppnodeName = CreateNodeT<knopComputedName>(pnodeNameExpr->ichMin, pnodeNameExpr->ichLim);
  3668. (*ppnodeName)->AsParseNodeUni()->pnode1 = pnodeNameExpr;
  3669. }
  3670. if (ppFullNameHint && buildAST && CONFIG_FLAG(UseFullName))
  3671. {
  3672. *ppFullNameHint = FormatPropertyString(*ppNameHint, pnodeNameExpr, pNameLength, pShortNameOffset);
  3673. }
  3674. ChkCurTokNoScan(tkRBrack, ERRnoRbrack);
  3675. }
  3676. /***************************************************************************
  3677. Parse a list of object set/get members, e.g.:
  3678. { get foo(){ ... }, set bar(arg) { ... } }
  3679. ***************************************************************************/
  3680. template<bool buildAST>
  3681. ParseNodePtr Parser::ParseMemberGetSet(OpCode nop, LPCOLESTR* ppNameHint)
  3682. {
  3683. ParseNodePtr pnodeName = nullptr;
  3684. Assert(nop == knopGetMember || nop == knopSetMember);
  3685. AssertMem(ppNameHint);
  3686. IdentPtr pid = nullptr;
  3687. bool isComputedName = false;
  3688. *ppNameHint=nullptr;
  3689. switch(m_token.tk)
  3690. {
  3691. default:
  3692. if (!m_token.IsReservedWord())
  3693. {
  3694. Error(ERRnoMemberIdent);
  3695. }
  3696. // fall through
  3697. case tkID:
  3698. pid = m_token.GetIdentifier(m_phtbl);
  3699. *ppNameHint = pid->Psz();
  3700. if (buildAST)
  3701. {
  3702. pnodeName = CreateStrNodeWithScanner(pid);
  3703. }
  3704. break;
  3705. case tkStrCon:
  3706. if (IsStrictMode() && m_pscan->IsOctOrLeadingZeroOnLastTKNumber())
  3707. {
  3708. Error(ERRES5NoOctal);
  3709. }
  3710. pid = m_token.GetStr();
  3711. *ppNameHint = pid->Psz();
  3712. if (buildAST)
  3713. {
  3714. pnodeName = CreateStrNodeWithScanner(pid);
  3715. }
  3716. break;
  3717. case tkIntCon:
  3718. if (IsStrictMode() && m_pscan->IsOctOrLeadingZeroOnLastTKNumber())
  3719. {
  3720. Error(ERRES5NoOctal);
  3721. }
  3722. pid = m_pscan->PidFromLong(m_token.GetLong());
  3723. if (buildAST)
  3724. {
  3725. pnodeName = CreateStrNodeWithScanner(pid);
  3726. }
  3727. break;
  3728. case tkFltCon:
  3729. if (IsStrictMode() && m_pscan->IsOctOrLeadingZeroOnLastTKNumber())
  3730. {
  3731. Error(ERRES5NoOctal);
  3732. }
  3733. pid = m_pscan->PidFromDbl(m_token.GetDouble());
  3734. if (buildAST)
  3735. {
  3736. pnodeName = CreateStrNodeWithScanner(pid);
  3737. }
  3738. break;
  3739. case tkLBrack:
  3740. // Computed property name: get|set [expr] () { }
  3741. if (!m_scriptContext->GetConfig()->IsES6ObjectLiteralsEnabled())
  3742. {
  3743. Error(ERRnoMemberIdent);
  3744. }
  3745. LPCOLESTR emptyHint = nullptr;
  3746. uint32 offset = 0;
  3747. ParseComputedName<buildAST>(&pnodeName, &emptyHint, ppNameHint, &offset);
  3748. isComputedName = true;
  3749. break;
  3750. }
  3751. MemberType memberType;
  3752. ushort flags = fFncMethod | fFncNoName;
  3753. if (nop == knopGetMember)
  3754. {
  3755. memberType = MemberTypeGetter;
  3756. flags |= fFncNoArg;
  3757. }
  3758. else
  3759. {
  3760. Assert(nop == knopSetMember);
  3761. memberType = MemberTypeSetter;
  3762. flags |= fFncOneArg;
  3763. }
  3764. this->m_parsingSuperRestrictionState = ParsingSuperRestrictionState_SuperPropertyAllowed;
  3765. ParseNodePtr pnodeFnc = ParseFncDecl<buildAST>(flags, *ppNameHint,
  3766. /*needsPIDOnRCurlyScan*/ false, /*resetParsingSuperRestrictionState*/ false);
  3767. if (buildAST)
  3768. {
  3769. pnodeFnc->AsParseNodeFnc()->SetIsAccessor();
  3770. return CreateBinNode(nop, pnodeName, pnodeFnc);
  3771. }
  3772. else
  3773. {
  3774. return nullptr;
  3775. }
  3776. }
  3777. /***************************************************************************
  3778. Parse a list of object members. e.g. { x:foo, 'y me':bar }
  3779. ***************************************************************************/
  3780. template<bool buildAST>
  3781. ParseNodePtr Parser::ParseMemberList(LPCOLESTR pNameHint, uint32* pNameHintLength, tokens declarationType)
  3782. {
  3783. ParseNodePtr pnodeArg = nullptr;
  3784. ParseNodePtr pnodeName = nullptr;
  3785. ParseNodePtr pnodeList = nullptr;
  3786. ParseNodePtr *lastNodeRef = nullptr;
  3787. LPCOLESTR pFullNameHint = nullptr; // A calculated full name
  3788. uint32 fullNameHintLength = pNameHintLength ? *pNameHintLength : 0;
  3789. uint32 shortNameOffset = 0;
  3790. bool isProtoDeclared = false;
  3791. // we get declaration tkLCurly - when the possible object pattern found under the expression.
  3792. bool isObjectPattern = (declarationType == tkVAR || declarationType == tkLET || declarationType == tkCONST || declarationType == tkLCurly) && IsES6DestructuringEnabled();
  3793. // Check for an empty list
  3794. if (tkRCurly == m_token.tk)
  3795. {
  3796. return nullptr;
  3797. }
  3798. ArenaAllocator tempAllocator(_u("MemberNames"), m_nodeAllocator.GetPageAllocator(), Parser::OutOfMemory);
  3799. bool hasDeferredInitError = false;
  3800. for (;;)
  3801. {
  3802. bool isComputedName = false;
  3803. #if DEBUG
  3804. if((m_grfscr & fscrEnforceJSON) && (tkStrCon != m_token.tk || !(m_pscan->IsDoubleQuoteOnLastTkStrCon())))
  3805. {
  3806. Error(ERRsyntax);
  3807. }
  3808. #endif
  3809. bool isAsyncMethod = false;
  3810. charcount_t ichMin = 0;
  3811. size_t iecpMin = 0;
  3812. if (m_token.tk == tkID && m_token.GetIdentifier(m_phtbl) == wellKnownPropertyPids.async && m_scriptContext->GetConfig()->IsES7AsyncAndAwaitEnabled())
  3813. {
  3814. RestorePoint parsedAsync;
  3815. m_pscan->Capture(&parsedAsync);
  3816. ichMin = m_pscan->IchMinTok();
  3817. iecpMin = m_pscan->IecpMinTok();
  3818. m_pscan->ScanForcingPid();
  3819. if (m_token.tk == tkLParen || m_token.tk == tkColon || m_token.tk == tkRCurly || m_pscan->FHadNewLine() || m_token.tk == tkComma)
  3820. {
  3821. m_pscan->SeekTo(parsedAsync);
  3822. }
  3823. else
  3824. {
  3825. isAsyncMethod = true;
  3826. }
  3827. }
  3828. bool isGenerator = m_scriptContext->GetConfig()->IsES6GeneratorsEnabled() &&
  3829. m_token.tk == tkStar;
  3830. ushort fncDeclFlags = fFncNoName | fFncMethod;
  3831. if (isGenerator)
  3832. {
  3833. if (isAsyncMethod)
  3834. {
  3835. Error(ERRsyntax);
  3836. }
  3837. // Include star character in the function extents
  3838. ichMin = m_pscan->IchMinTok();
  3839. iecpMin = m_pscan->IecpMinTok();
  3840. m_pscan->ScanForcingPid();
  3841. fncDeclFlags |= fFncGenerator;
  3842. }
  3843. IdentPtr pidHint = nullptr; // A name scoped to current expression
  3844. Token tkHint = m_token;
  3845. charcount_t idHintIchMin = static_cast<charcount_t>(m_pscan->IecpMinTok());
  3846. charcount_t idHintIchLim = static_cast< charcount_t >(m_pscan->IecpLimTok());
  3847. bool wrapInBrackets = false;
  3848. switch (m_token.tk)
  3849. {
  3850. default:
  3851. if (!m_token.IsReservedWord())
  3852. {
  3853. Error(ERRnoMemberIdent);
  3854. }
  3855. // allow reserved words
  3856. wrapInBrackets = true;
  3857. // fall-through
  3858. case tkID:
  3859. pidHint = m_token.GetIdentifier(m_phtbl);
  3860. if (buildAST)
  3861. {
  3862. pnodeName = CreateStrNodeWithScanner(pidHint);
  3863. }
  3864. break;
  3865. case tkStrCon:
  3866. if (IsStrictMode() && m_pscan->IsOctOrLeadingZeroOnLastTKNumber())
  3867. {
  3868. Error(ERRES5NoOctal);
  3869. }
  3870. wrapInBrackets = true;
  3871. pidHint = m_token.GetStr();
  3872. if (buildAST)
  3873. {
  3874. pnodeName = CreateStrNodeWithScanner(pidHint);
  3875. }
  3876. break;
  3877. case tkIntCon:
  3878. // Object initializers with numeric labels allowed in JS6
  3879. if (IsStrictMode() && m_pscan->IsOctOrLeadingZeroOnLastTKNumber())
  3880. {
  3881. Error(ERRES5NoOctal);
  3882. }
  3883. pidHint = m_pscan->PidFromLong(m_token.GetLong());
  3884. if (buildAST)
  3885. {
  3886. pnodeName = CreateStrNodeWithScanner(pidHint);
  3887. }
  3888. break;
  3889. case tkFltCon:
  3890. if (IsStrictMode() && m_pscan->IsOctOrLeadingZeroOnLastTKNumber())
  3891. {
  3892. Error(ERRES5NoOctal);
  3893. }
  3894. pidHint = m_pscan->PidFromDbl(m_token.GetDouble());
  3895. if (buildAST)
  3896. {
  3897. pnodeName = CreateStrNodeWithScanner(pidHint);
  3898. }
  3899. wrapInBrackets = true;
  3900. break;
  3901. case tkLBrack:
  3902. // Computed property name: [expr] : value
  3903. if (!m_scriptContext->GetConfig()->IsES6ObjectLiteralsEnabled())
  3904. {
  3905. Error(ERRnoMemberIdent);
  3906. }
  3907. ParseComputedName<buildAST>(&pnodeName, &pNameHint, &pFullNameHint, &fullNameHintLength, &shortNameOffset);
  3908. isComputedName = true;
  3909. break;
  3910. }
  3911. if (pFullNameHint == nullptr)
  3912. {
  3913. if (CONFIG_FLAG(UseFullName))
  3914. {
  3915. pFullNameHint = AppendNameHints(pNameHint, pidHint, &fullNameHintLength, &shortNameOffset, false, wrapInBrackets);
  3916. }
  3917. else
  3918. {
  3919. pFullNameHint = pidHint? pidHint->Psz() : nullptr;
  3920. fullNameHintLength = pidHint ? pidHint->Cch() : 0;
  3921. shortNameOffset = 0;
  3922. }
  3923. }
  3924. RestorePoint atPid;
  3925. m_pscan->Capture(&atPid);
  3926. m_pscan->ScanForcingPid();
  3927. if (isGenerator && m_token.tk != tkLParen)
  3928. {
  3929. Error(ERRnoLparen);
  3930. }
  3931. if (tkColon == m_token.tk)
  3932. {
  3933. // It is a syntax error is the production of the form __proto__ : <> occurs more than once. From B.3.1 in spec.
  3934. // Note that previous scan is important because only after that we can determine we have a variable.
  3935. if (!isComputedName && pidHint == wellKnownPropertyPids.__proto__)
  3936. {
  3937. if (isProtoDeclared)
  3938. {
  3939. Error(ERRsyntax);
  3940. }
  3941. else
  3942. {
  3943. isProtoDeclared = true;
  3944. }
  3945. }
  3946. m_pscan->Scan();
  3947. ParseNodePtr pnodeExpr = nullptr;
  3948. if (isObjectPattern)
  3949. {
  3950. if (m_token.tk == tkEllipsis)
  3951. {
  3952. Error(ERRUnexpectedEllipsis);
  3953. }
  3954. RestorePoint atExpression;
  3955. if (!buildAST && declarationType == tkLCurly && IsPossiblePatternStart())
  3956. {
  3957. m_pscan->Capture(&atExpression);
  3958. // It is possible that we might encounter the shorthand init error. Lets find that out.
  3959. bool savedDeferredInitError = m_hasDeferredShorthandInitError;
  3960. m_hasDeferredShorthandInitError = false;
  3961. IdentToken token;
  3962. BOOL fLikelyPattern = false;
  3963. // First identify that the current expression is indeed the object/array literal. Otherwise we will just use the ParsrExpr to parse that.
  3964. ParseTerm<buildAST>(/* fAllowCall */ m_token.tk != tkSUPER, nullptr /*pNameHint*/, nullptr /*pHintLength*/, nullptr /*pShortNameOffset*/, &token, false /*fUnaryOrParen*/,
  3965. nullptr /*pfCanAssign*/, &fLikelyPattern);
  3966. m_pscan->SeekTo(atExpression);
  3967. if (fLikelyPattern)
  3968. {
  3969. pnodeExpr = ParseDestructuredVarDecl<buildAST>(declarationType, declarationType != tkLCurly, nullptr/* *hasSeenRest*/, false /*topLevel*/, false /*allowEmptyExpression*/);
  3970. if (m_token.tk != tkComma && m_token.tk != tkRCurly)
  3971. {
  3972. if (m_token.IsOperator())
  3973. {
  3974. Error(ERRDestructNoOper);
  3975. }
  3976. Error(ERRsyntax);
  3977. }
  3978. }
  3979. else
  3980. {
  3981. if (m_hasDeferredShorthandInitError)
  3982. {
  3983. Error(ERRnoColon);
  3984. }
  3985. pnodeExpr = ParseExpr<buildAST>(koplCma, nullptr/*pfCantAssign*/, TRUE/*fAllowIn*/, FALSE/*fAllowEllipsis*/, pFullNameHint, &fullNameHintLength, &shortNameOffset);
  3986. }
  3987. m_hasDeferredShorthandInitError = savedDeferredInitError;
  3988. }
  3989. else
  3990. {
  3991. pnodeExpr = ParseDestructuredVarDecl<buildAST>(declarationType, declarationType != tkLCurly, nullptr/* *hasSeenRest*/, false /*topLevel*/, false /*allowEmptyExpression*/);
  3992. if (m_token.tk != tkComma && m_token.tk != tkRCurly)
  3993. {
  3994. if (m_token.IsOperator())
  3995. {
  3996. Error(ERRDestructNoOper);
  3997. }
  3998. Error(ERRsyntax);
  3999. }
  4000. }
  4001. }
  4002. else
  4003. {
  4004. pnodeExpr = ParseExpr<buildAST>(koplCma, nullptr/*pfCantAssign*/, TRUE/*fAllowIn*/, FALSE/*fAllowEllipsis*/, pFullNameHint, &fullNameHintLength, &shortNameOffset);
  4005. }
  4006. #if DEBUG
  4007. if((m_grfscr & fscrEnforceJSON) && !IsJSONValid(pnodeExpr))
  4008. {
  4009. Error(ERRsyntax);
  4010. }
  4011. #endif
  4012. if (buildAST)
  4013. {
  4014. pnodeArg = CreateBinNode(isObjectPattern ? knopObjectPatternMember : knopMember, pnodeName, pnodeExpr);
  4015. if (pnodeArg->AsParseNodeBin()->pnode1->nop == knopStr)
  4016. {
  4017. pnodeArg->AsParseNodeBin()->pnode1->AsParseNodePid()->pid->PromoteAssignmentState();
  4018. }
  4019. }
  4020. }
  4021. else if (m_token.tk == tkLParen && m_scriptContext->GetConfig()->IsES6ObjectLiteralsEnabled())
  4022. {
  4023. if (isObjectPattern)
  4024. {
  4025. Error(ERRInvalidAssignmentTarget);
  4026. }
  4027. // Shorthand syntax: foo() {} -> foo: function() {}
  4028. // Rewind to the PID and parse a function expression.
  4029. m_pscan->SeekTo(atPid);
  4030. this->m_parsingSuperRestrictionState = ParsingSuperRestrictionState_SuperPropertyAllowed;
  4031. ParseNodePtr pnodeFunc = ParseFncDecl<buildAST>(fncDeclFlags | (isAsyncMethod ? fFncAsync : fFncNoFlgs), pFullNameHint,
  4032. /*needsPIDOnRCurlyScan*/ false, /*resetParsingSuperRestrictionState*/ false);
  4033. if (isAsyncMethod || isGenerator)
  4034. {
  4035. pnodeFunc->AsParseNodeFnc()->cbMin = iecpMin;
  4036. pnodeFunc->ichMin = ichMin;
  4037. }
  4038. if (buildAST)
  4039. {
  4040. pnodeArg = CreateBinNode(knopMember, pnodeName, pnodeFunc);
  4041. }
  4042. }
  4043. else if (nullptr != pidHint) //Its either tkID/tkStrCon/tkFloatCon/tkIntCon
  4044. {
  4045. Assert(pidHint->Psz() != nullptr);
  4046. if ((pidHint == wellKnownPropertyPids.get || pidHint == wellKnownPropertyPids.set) &&
  4047. // get/set are only pseudo keywords when they are identifiers (i.e. not strings)
  4048. tkHint.tk == tkID && NextTokenIsPropertyNameStart())
  4049. {
  4050. if (isObjectPattern)
  4051. {
  4052. Error(ERRInvalidAssignmentTarget);
  4053. }
  4054. LPCOLESTR pNameGetOrSet = nullptr;
  4055. OpCode op = pidHint == wellKnownPropertyPids.get ? knopGetMember : knopSetMember;
  4056. pnodeArg = ParseMemberGetSet<buildAST>(op, &pNameGetOrSet);
  4057. if (CONFIG_FLAG(UseFullName) && buildAST && pnodeArg->AsParseNodeBin()->pnode2->nop == knopFncDecl)
  4058. {
  4059. // displays as "get object.funcname" or "set object.funcname"
  4060. uint32 getOrSetOffset = 0;
  4061. LPCOLESTR intermediateHint = AppendNameHints(pNameHint, pNameGetOrSet, &fullNameHintLength, &shortNameOffset);
  4062. pFullNameHint = AppendNameHints(pidHint, intermediateHint, &fullNameHintLength, &getOrSetOffset, true);
  4063. shortNameOffset += getOrSetOffset;
  4064. }
  4065. }
  4066. else if ((m_token.tk == tkRCurly || m_token.tk == tkComma || m_token.tk == tkAsg) && m_scriptContext->GetConfig()->IsES6ObjectLiteralsEnabled())
  4067. {
  4068. // Shorthand {foo} -> {foo:foo} syntax.
  4069. // {foo = <initializer>} supported only when on object pattern rules are being applied
  4070. if (tkHint.tk != tkID)
  4071. {
  4072. Assert(tkHint.IsReservedWord()
  4073. || tkHint.tk == tkIntCon || tkHint.tk == tkFltCon || tkHint.tk == tkStrCon);
  4074. // All keywords are banned in non-strict mode.
  4075. // Future reserved words are banned in strict mode.
  4076. if (IsStrictMode() || !tkHint.IsFutureReservedWord(true))
  4077. {
  4078. IdentifierExpectedError(tkHint);
  4079. }
  4080. }
  4081. if (buildAST)
  4082. {
  4083. CheckArgumentsUse(pidHint, GetCurrentFunctionNode());
  4084. }
  4085. bool couldBeObjectPattern = !isObjectPattern && m_token.tk == tkAsg;
  4086. // Saving the current state as we may change the isObjectPattern down below.
  4087. bool oldState = isObjectPattern;
  4088. if (couldBeObjectPattern)
  4089. {
  4090. declarationType = tkLCurly;
  4091. isObjectPattern = true;
  4092. // This may be an error but we are deferring for favouring destructuring.
  4093. hasDeferredInitError = true;
  4094. }
  4095. ParseNodePtr pnodeIdent = nullptr;
  4096. if (isObjectPattern)
  4097. {
  4098. m_pscan->SeekTo(atPid);
  4099. pnodeIdent = ParseDestructuredVarDecl<buildAST>(declarationType, declarationType != tkLCurly, nullptr/* *hasSeenRest*/, false /*topLevel*/, false /*allowEmptyExpression*/);
  4100. if (m_token.tk != tkComma && m_token.tk != tkRCurly)
  4101. {
  4102. if (m_token.IsOperator())
  4103. {
  4104. Error(ERRDestructNoOper);
  4105. }
  4106. Error(ERRsyntax);
  4107. }
  4108. }
  4109. else
  4110. {
  4111. // Add a reference to the hinted name so we can bind it properly.
  4112. PidRefStack *ref = PushPidRef(pidHint);
  4113. if (buildAST)
  4114. {
  4115. pnodeIdent = CreateNameNode(pidHint, idHintIchMin, idHintIchLim);
  4116. pnodeIdent->AsParseNodePid()->SetSymRef(ref);
  4117. }
  4118. }
  4119. if (buildAST)
  4120. {
  4121. pnodeArg = CreateBinNode(isObjectPattern && !couldBeObjectPattern ? knopObjectPatternMember : knopMemberShort, pnodeName, pnodeIdent);
  4122. }
  4123. isObjectPattern = oldState;
  4124. }
  4125. else
  4126. {
  4127. Error(ERRnoColon);
  4128. }
  4129. }
  4130. else
  4131. {
  4132. Error(ERRnoColon);
  4133. }
  4134. if (buildAST)
  4135. {
  4136. Assert(pnodeArg->AsParseNodeBin()->pnode2 != nullptr);
  4137. if (pnodeArg->AsParseNodeBin()->pnode2->nop == knopFncDecl)
  4138. {
  4139. Assert(fullNameHintLength >= shortNameOffset);
  4140. pnodeArg->AsParseNodeBin()->pnode2->AsParseNodeFnc()->hint = pFullNameHint;
  4141. pnodeArg->AsParseNodeBin()->pnode2->AsParseNodeFnc()->hintLength = fullNameHintLength;
  4142. pnodeArg->AsParseNodeBin()->pnode2->AsParseNodeFnc()->hintOffset = shortNameOffset;
  4143. }
  4144. AddToNodeListEscapedUse(&pnodeList, &lastNodeRef, pnodeArg);
  4145. }
  4146. pidHint = nullptr;
  4147. pFullNameHint = nullptr;
  4148. if (tkComma != m_token.tk)
  4149. {
  4150. break;
  4151. }
  4152. m_pscan->ScanForcingPid();
  4153. if (tkRCurly == m_token.tk)
  4154. {
  4155. break;
  4156. }
  4157. }
  4158. m_hasDeferredShorthandInitError = m_hasDeferredShorthandInitError || hasDeferredInitError;
  4159. if (buildAST)
  4160. {
  4161. AssertMem(lastNodeRef);
  4162. AssertNodeMem(*lastNodeRef);
  4163. pnodeList->ichLim = (*lastNodeRef)->ichLim;
  4164. }
  4165. return pnodeList;
  4166. }
  4167. BOOL Parser::DeferredParse(Js::LocalFunctionId functionId)
  4168. {
  4169. if ((m_grfscr & fscrDeferFncParse) != 0)
  4170. {
  4171. if (m_stoppedDeferredParse)
  4172. {
  4173. return false;
  4174. }
  4175. if (PHASE_OFF_RAW(Js::DeferParsePhase, m_sourceContextInfo->sourceContextId, functionId))
  4176. {
  4177. return false;
  4178. }
  4179. if (PHASE_FORCE_RAW(Js::DeferParsePhase, m_sourceContextInfo->sourceContextId, functionId)
  4180. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  4181. || Js::Configuration::Global.flags.IsEnabled(Js::ForceUndoDeferFlag)
  4182. #endif
  4183. )
  4184. {
  4185. return true;
  4186. }
  4187. #if ENABLE_PROFILE_INFO
  4188. #ifndef DISABLE_DYNAMIC_PROFILE_DEFER_PARSE
  4189. if (m_sourceContextInfo->sourceDynamicProfileManager != nullptr)
  4190. {
  4191. Js::ExecutionFlags flags = m_sourceContextInfo->sourceDynamicProfileManager->IsFunctionExecuted(functionId);
  4192. return flags != Js::ExecutionFlags_Executed;
  4193. }
  4194. #endif
  4195. #endif
  4196. return true;
  4197. }
  4198. return false;
  4199. }
  4200. //
  4201. // Call this in ParseFncDecl only to check (and reset) if ParseFncDecl is re-parsing a deferred
  4202. // function body. If a deferred function is called and being re-parsed, it shouldn't be deferred again.
  4203. //
  4204. BOOL Parser::IsDeferredFnc()
  4205. {
  4206. if (m_grfscr & fscrDeferredFnc)
  4207. {
  4208. m_grfscr &= ~fscrDeferredFnc;
  4209. return true;
  4210. }
  4211. return false;
  4212. }
  4213. template<bool buildAST>
  4214. ParseNodePtr Parser::ParseFncDecl(ushort flags, LPCOLESTR pNameHint, const bool needsPIDOnRCurlyScan, bool resetParsingSuperRestrictionState, bool fUnaryOrParen)
  4215. {
  4216. AutoParsingSuperRestrictionStateRestorer restorer(this);
  4217. if (resetParsingSuperRestrictionState)
  4218. {
  4219. // ParseFncDecl will always reset m_parsingSuperRestrictionState to super disallowed unless explicitly disabled
  4220. this->m_parsingSuperRestrictionState = ParsingSuperRestrictionState_SuperDisallowed;
  4221. }
  4222. ParseNodePtr pnodeFnc = nullptr;
  4223. ParseNodePtr *ppnodeVarSave = nullptr;
  4224. ParseNodePtr pnodeFncBlockScope = nullptr;
  4225. ParseNodePtr *ppnodeScopeSave = nullptr;
  4226. ParseNodePtr *ppnodeExprScopeSave = nullptr;
  4227. bool funcHasName = false;
  4228. bool fDeclaration = flags & fFncDeclaration;
  4229. bool fModule = (flags & fFncModule) != 0;
  4230. bool fLambda = (flags & fFncLambda) != 0;
  4231. charcount_t ichMin = this->m_pscan->IchMinTok();
  4232. bool wasInDeferredNestedFunc = false;
  4233. uint tryCatchOrFinallyDepthSave = this->m_tryCatchOrFinallyDepth;
  4234. this->m_tryCatchOrFinallyDepth = 0;
  4235. if (this->m_arrayDepth)
  4236. {
  4237. this->m_funcInArrayDepth++; // Count function depth within array literal
  4238. }
  4239. // Update the count of functions nested in the current parent.
  4240. Assert(m_pnestedCount || !buildAST);
  4241. uint *pnestedCountSave = m_pnestedCount;
  4242. if (buildAST || m_pnestedCount)
  4243. {
  4244. (*m_pnestedCount)++;
  4245. }
  4246. uint scopeCountNoAstSave = m_scopeCountNoAst;
  4247. m_scopeCountNoAst = 0;
  4248. bool noStmtContext = false;
  4249. if (fDeclaration)
  4250. {
  4251. noStmtContext = m_pstmtCur->GetNop() != knopBlock;
  4252. if (noStmtContext)
  4253. {
  4254. // We have a function declaration like "if (a) function f() {}". We didn't see
  4255. // a block scope on the way in, so we need to pretend we did. Note that this is a syntax error
  4256. // in strict mode.
  4257. if (!this->FncDeclAllowedWithoutContext(flags))
  4258. {
  4259. Error(ERRsyntax);
  4260. }
  4261. pnodeFncBlockScope = StartParseBlock<buildAST>(PnodeBlockType::Regular, ScopeType_Block);
  4262. if (buildAST)
  4263. {
  4264. PushFuncBlockScope(pnodeFncBlockScope, &ppnodeScopeSave, &ppnodeExprScopeSave);
  4265. }
  4266. }
  4267. }
  4268. // Create the node.
  4269. pnodeFnc = CreateNode(knopFncDecl);
  4270. pnodeFnc->AsParseNodeFnc()->ClearFlags();
  4271. pnodeFnc->AsParseNodeFnc()->SetDeclaration(fDeclaration);
  4272. pnodeFnc->AsParseNodeFnc()->astSize = 0;
  4273. pnodeFnc->AsParseNodeFnc()->pnodeName = nullptr;
  4274. pnodeFnc->AsParseNodeFnc()->pnodeScopes = nullptr;
  4275. pnodeFnc->AsParseNodeFnc()->pnodeRest = nullptr;
  4276. pnodeFnc->AsParseNodeFnc()->pid = nullptr;
  4277. pnodeFnc->AsParseNodeFnc()->hint = nullptr;
  4278. pnodeFnc->AsParseNodeFnc()->hintOffset = 0;
  4279. pnodeFnc->AsParseNodeFnc()->hintLength = 0;
  4280. pnodeFnc->AsParseNodeFnc()->isNameIdentifierRef = true;
  4281. pnodeFnc->AsParseNodeFnc()->nestedFuncEscapes = false;
  4282. pnodeFnc->AsParseNodeFnc()->pnodeNext = nullptr;
  4283. pnodeFnc->AsParseNodeFnc()->pnodeParams = nullptr;
  4284. pnodeFnc->AsParseNodeFnc()->pnodeVars = nullptr;
  4285. pnodeFnc->AsParseNodeFnc()->funcInfo = nullptr;
  4286. pnodeFnc->AsParseNodeFnc()->deferredStub = nullptr;
  4287. pnodeFnc->AsParseNodeFnc()->nestedCount = 0;
  4288. pnodeFnc->AsParseNodeFnc()->cbMin = m_pscan->IecpMinTok();
  4289. pnodeFnc->AsParseNodeFnc()->functionId = (*m_nextFunctionId)++;
  4290. pnodeFnc->AsParseNodeFnc()->isBodyAndParamScopeMerged = true;
  4291. // Push new parser state with this new function node
  4292. AppendFunctionToScopeList(fDeclaration, pnodeFnc);
  4293. // Start the argument list.
  4294. ppnodeVarSave = m_ppnodeVar;
  4295. if (buildAST)
  4296. {
  4297. pnodeFnc->AsParseNodeFnc()->lineNumber = m_pscan->LineCur();
  4298. pnodeFnc->AsParseNodeFnc()->columnNumber = CalculateFunctionColumnNumber();
  4299. pnodeFnc->AsParseNodeFnc()->SetNested(m_currentNodeFunc != nullptr); // If there is a current function, then we're a nested function.
  4300. pnodeFnc->AsParseNodeFnc()->SetStrictMode(IsStrictMode()); // Inherit current strict mode -- may be overridden by the function itself if it contains a strict mode directive.
  4301. pnodeFnc->AsParseNodeFnc()->firstDefaultArg = 0;
  4302. m_pCurrentAstSize = &pnodeFnc->AsParseNodeFnc()->astSize;
  4303. }
  4304. else // if !buildAST
  4305. {
  4306. wasInDeferredNestedFunc = m_inDeferredNestedFunc;
  4307. m_inDeferredNestedFunc = true;
  4308. }
  4309. m_pnestedCount = &pnodeFnc->AsParseNodeFnc()->nestedCount;
  4310. AnalysisAssert(pnodeFnc);
  4311. pnodeFnc->AsParseNodeFnc()->SetIsAsync((flags & fFncAsync) != 0);
  4312. pnodeFnc->AsParseNodeFnc()->SetIsLambda(fLambda);
  4313. pnodeFnc->AsParseNodeFnc()->SetIsMethod((flags & fFncMethod) != 0);
  4314. pnodeFnc->AsParseNodeFnc()->SetIsClassMember((flags & fFncClassMember) != 0);
  4315. pnodeFnc->AsParseNodeFnc()->SetIsModule(fModule);
  4316. pnodeFnc->AsParseNodeFnc()->SetIsClassConstructor((flags & fFncClassConstructor) != 0);
  4317. pnodeFnc->AsParseNodeFnc()->SetIsBaseClassConstructor((flags & fFncBaseClassConstructor) != 0);
  4318. IdentPtr pFncNamePid = nullptr;
  4319. bool needScanRCurly = true;
  4320. bool result = ParseFncDeclHelper<buildAST>(pnodeFnc, pNameHint, flags, &funcHasName, fUnaryOrParen, noStmtContext, &needScanRCurly, fModule, &pFncNamePid);
  4321. if (!result)
  4322. {
  4323. Assert(!pnodeFncBlockScope);
  4324. return pnodeFnc;
  4325. }
  4326. AnalysisAssert(pnodeFnc);
  4327. *m_ppnodeVar = nullptr;
  4328. m_ppnodeVar = ppnodeVarSave;
  4329. if (m_currentNodeFunc && (pnodeFnc->AsParseNodeFnc()->CallsEval() || pnodeFnc->AsParseNodeFnc()->ChildCallsEval()))
  4330. {
  4331. GetCurrentFunctionNode()->AsParseNodeFnc()->SetChildCallsEval(true);
  4332. }
  4333. // Lambdas do not have "arguments" and instead capture their parent's
  4334. // binding of "arguments. To ensure the arguments object of the enclosing
  4335. // non-lambda function is loaded propagate the UsesArguments flag up to
  4336. // the parent function
  4337. if (fLambda && (pnodeFnc->AsParseNodeFnc()->UsesArguments() || pnodeFnc->AsParseNodeFnc()->CallsEval()))
  4338. {
  4339. ParseNodePtr pnodeFncParent = GetCurrentFunctionNode();
  4340. if (pnodeFncParent != nullptr)
  4341. {
  4342. pnodeFncParent->AsParseNodeFnc()->SetUsesArguments();
  4343. }
  4344. else
  4345. {
  4346. m_UsesArgumentsAtGlobal = true;
  4347. }
  4348. }
  4349. if (needScanRCurly && !fModule)
  4350. {
  4351. // Consume the next token now that we're back in the enclosing function (whose strictness may be
  4352. // different from the function we just finished).
  4353. #if DBG
  4354. bool expectedTokenValid = m_token.tk == tkRCurly;
  4355. AssertMsg(expectedTokenValid, "Invalid token expected for RCurly match");
  4356. #endif
  4357. // The next token may need to have a PID created in !buildAST mode, as we may be parsing a method with a string name.
  4358. if (needsPIDOnRCurlyScan)
  4359. {
  4360. m_pscan->ScanForcingPid();
  4361. }
  4362. else
  4363. {
  4364. m_pscan->Scan();
  4365. }
  4366. }
  4367. m_pnestedCount = pnestedCountSave;
  4368. Assert(!buildAST || !wasInDeferredNestedFunc);
  4369. m_inDeferredNestedFunc = wasInDeferredNestedFunc;
  4370. if (this->m_arrayDepth)
  4371. {
  4372. this->m_funcInArrayDepth--;
  4373. if (this->m_funcInArrayDepth == 0)
  4374. {
  4375. // We disable deferred parsing if array literals dominate.
  4376. // But don't do this if the array literal is dominated by function bodies.
  4377. if (flags & (fFncMethod | fFncClassMember) && m_token.tk != tkSColon)
  4378. {
  4379. // Class member methods have optional separators. We need to check whether we are
  4380. // getting the IchLim of the correct token.
  4381. Assert(m_pscan->m_tkPrevious == tkRCurly && needScanRCurly);
  4382. this->m_funcInArray += m_pscan->IchMinTok() - /*tkRCurly*/ 1 - ichMin;
  4383. }
  4384. else
  4385. {
  4386. this->m_funcInArray += m_pscan->IchLimTok() - ichMin;
  4387. }
  4388. }
  4389. }
  4390. m_scopeCountNoAst = scopeCountNoAstSave;
  4391. if (fDeclaration && !IsStrictMode())
  4392. {
  4393. if (pFncNamePid != nullptr &&
  4394. GetCurrentBlock() &&
  4395. GetCurrentBlock()->AsParseNodeBlock()->blockType == PnodeBlockType::Regular)
  4396. {
  4397. // Add a function-scoped VarDecl with the same name as the function for
  4398. // back compat with pre-ES6 code that declares functions in blocks. The
  4399. // idea is that the last executed declaration wins at the function scope
  4400. // level and we accomplish this by having each block scoped function
  4401. // declaration assign to both the block scoped "let" binding, as well
  4402. // as the function scoped "var" binding.
  4403. ParseNodePtr vardecl = CreateVarDeclNode(pFncNamePid, STVariable, false, nullptr, false);
  4404. vardecl->AsParseNodeVar()->isBlockScopeFncDeclVar = true;
  4405. if (GetCurrentFunctionNode() && vardecl->AsParseNodeVar()->sym->GetIsFormal())
  4406. {
  4407. GetCurrentFunctionNode()->AsParseNodeFnc()->SetHasAnyWriteToFormals(true);
  4408. }
  4409. }
  4410. }
  4411. if (pnodeFncBlockScope)
  4412. {
  4413. Assert(pnodeFncBlockScope->AsParseNodeBlock()->pnodeStmt == nullptr);
  4414. pnodeFncBlockScope->AsParseNodeBlock()->pnodeStmt = pnodeFnc;
  4415. if (buildAST)
  4416. {
  4417. PopFuncBlockScope(ppnodeScopeSave, ppnodeExprScopeSave);
  4418. }
  4419. FinishParseBlock(pnodeFncBlockScope);
  4420. return pnodeFncBlockScope;
  4421. }
  4422. this->m_tryCatchOrFinallyDepth = tryCatchOrFinallyDepthSave;
  4423. return pnodeFnc;
  4424. }
  4425. bool Parser::FncDeclAllowedWithoutContext(ushort flags)
  4426. {
  4427. // Statement context required for strict mode, async functions, and generators.
  4428. // Note that generators aren't detected yet when this method is called; they're checked elsewhere.
  4429. return !IsStrictMode() && !(flags & fFncAsync);
  4430. }
  4431. uint Parser::CalculateFunctionColumnNumber()
  4432. {
  4433. uint columnNumber;
  4434. if (m_pscan->IchMinTok() >= m_pscan->IchMinLine())
  4435. {
  4436. // In scenarios involving defer parse IchMinLine() can be incorrect for the first line after defer parse
  4437. columnNumber = m_pscan->IchMinTok() - m_pscan->IchMinLine();
  4438. if (m_functionBody != nullptr && m_functionBody->GetRelativeLineNumber() == m_pscan->LineCur())
  4439. {
  4440. // Adjust the column if it falls on the first line, where the re-parse is happening.
  4441. columnNumber += m_functionBody->GetRelativeColumnNumber();
  4442. }
  4443. }
  4444. else if (m_currentNodeFunc)
  4445. {
  4446. // For the first line after defer parse, compute the column relative to the column number
  4447. // of the lexically parent function.
  4448. ULONG offsetFromCurrentFunction = m_pscan->IchMinTok() - m_currentNodeFunc->ichMin;
  4449. columnNumber = m_currentNodeFunc->AsParseNodeFnc()->columnNumber + offsetFromCurrentFunction ;
  4450. }
  4451. else
  4452. {
  4453. // if there is no current function, lets give a default of 0.
  4454. columnNumber = 0;
  4455. }
  4456. return columnNumber;
  4457. }
  4458. void Parser::AppendFunctionToScopeList(bool fDeclaration, ParseNodePtr pnodeFnc)
  4459. {
  4460. if (!fDeclaration && m_ppnodeExprScope)
  4461. {
  4462. // We're tracking function expressions separately from declarations in this scope
  4463. // (e.g., inside a catch scope in standards mode).
  4464. Assert(*m_ppnodeExprScope == nullptr);
  4465. *m_ppnodeExprScope = pnodeFnc;
  4466. m_ppnodeExprScope = &pnodeFnc->AsParseNodeFnc()->pnodeNext;
  4467. }
  4468. else
  4469. {
  4470. Assert(*m_ppnodeScope == nullptr);
  4471. *m_ppnodeScope = pnodeFnc;
  4472. m_ppnodeScope = &pnodeFnc->AsParseNodeFnc()->pnodeNext;
  4473. }
  4474. }
  4475. /***************************************************************************
  4476. Parse a function definition.
  4477. ***************************************************************************/
  4478. template<bool buildAST>
  4479. bool Parser::ParseFncDeclHelper(ParseNodePtr pnodeFnc, LPCOLESTR pNameHint, ushort flags, bool *pHasName, bool fUnaryOrParen, bool noStmtContext, bool *pNeedScanRCurly, bool skipFormals, IdentPtr* pFncNamePid)
  4480. {
  4481. ParseNodePtr pnodeFncParent = GetCurrentFunctionNode();
  4482. // is the following correct? When buildAST is false, m_currentNodeDeferredFunc can be nullptr on transition to deferred parse from non-deferred
  4483. ParseNodePtr pnodeFncSave = buildAST ? m_currentNodeFunc : m_currentNodeDeferredFunc;
  4484. ParseNodePtr pnodeFncSaveNonLambda = buildAST ? m_currentNodeNonLambdaFunc : m_currentNodeNonLambdaDeferredFunc;
  4485. int32* pAstSizeSave = m_pCurrentAstSize;
  4486. bool fDeclaration = (flags & fFncDeclaration) != 0;
  4487. bool fLambda = (flags & fFncLambda) != 0;
  4488. bool fAsync = (flags & fFncAsync) != 0;
  4489. bool fModule = (flags & fFncModule) != 0;
  4490. bool fDeferred = false;
  4491. StmtNest *pstmtSave;
  4492. ParseNodePtr *lastNodeRef = nullptr;
  4493. bool fFunctionInBlock = false;
  4494. if (buildAST)
  4495. {
  4496. fFunctionInBlock = GetCurrentBlockInfo() != GetCurrentFunctionBlockInfo() &&
  4497. (GetCurrentBlockInfo()->pnodeBlock->AsParseNodeBlock()->scope == nullptr ||
  4498. GetCurrentBlockInfo()->pnodeBlock->AsParseNodeBlock()->scope->GetScopeType() != ScopeType_GlobalEvalBlock);
  4499. }
  4500. // Save the position of the scanner in case we need to inspect the name hint later
  4501. RestorePoint beginNameHint;
  4502. m_pscan->Capture(&beginNameHint);
  4503. ParseNodePtr pnodeFncExprScope = nullptr;
  4504. Scope *fncExprScope = nullptr;
  4505. if (!fDeclaration)
  4506. {
  4507. if (!fLambda)
  4508. {
  4509. pnodeFncExprScope = StartParseBlock<buildAST>(PnodeBlockType::Function, ScopeType_FuncExpr);
  4510. fncExprScope = pnodeFncExprScope->AsParseNodeBlock()->scope;
  4511. }
  4512. // Function expression: push the new function onto the stack now so that the name (if any) will be
  4513. // local to the new function.
  4514. this->UpdateCurrentNodeFunc<buildAST>(pnodeFnc, fLambda);
  4515. }
  4516. *pHasName = !fLambda && !fModule && this->ParseFncNames<buildAST>(pnodeFnc, pnodeFncSave, flags, &lastNodeRef, pFncNamePid);
  4517. if (fDeclaration)
  4518. {
  4519. // Declaration statement: push the new function now, after parsing the name, so the name is local to the
  4520. // enclosing function.
  4521. this->UpdateCurrentNodeFunc<buildAST>(pnodeFnc, fLambda);
  4522. }
  4523. if (noStmtContext && pnodeFnc->AsParseNodeFnc()->IsGenerator())
  4524. {
  4525. // Generator decl not allowed outside stmt context. (We have to wait until we've parsed the '*' to
  4526. // detect generator.)
  4527. Error(ERRsyntax, pnodeFnc);
  4528. }
  4529. // switch scanner to treat 'yield' as keyword in generator functions
  4530. // or as an identifier in non-generator functions
  4531. bool fPreviousYieldIsKeyword = m_pscan->SetYieldIsKeywordRegion(pnodeFnc && pnodeFnc->AsParseNodeFnc()->IsGenerator());
  4532. bool fPreviousAwaitIsKeyword = m_pscan->SetAwaitIsKeywordRegion(fAsync);
  4533. if (pnodeFnc && pnodeFnc->AsParseNodeFnc()->IsGenerator())
  4534. {
  4535. CHAKRATEL_LANGSTATS_INC_LANGFEATURECOUNT(ES6, Generator, m_scriptContext);
  4536. }
  4537. if (fncExprScope && !*pHasName)
  4538. {
  4539. FinishParseBlock(pnodeFncExprScope);
  4540. m_nextBlockId--;
  4541. Adelete(&m_nodeAllocator, fncExprScope);
  4542. fncExprScope = nullptr;
  4543. pnodeFncExprScope = nullptr;
  4544. }
  4545. if (pnodeFnc)
  4546. {
  4547. pnodeFnc->AsParseNodeFnc()->scope = fncExprScope;
  4548. }
  4549. // Start a new statement stack.
  4550. bool topLevelStmt =
  4551. buildAST &&
  4552. !fFunctionInBlock &&
  4553. (this->m_pstmtCur == nullptr || this->m_pstmtCur->pnodeStmt->nop == knopBlock);
  4554. pstmtSave = m_pstmtCur;
  4555. SetCurrentStatement(nullptr);
  4556. RestorePoint beginFormals;
  4557. m_pscan->Capture(&beginFormals);
  4558. BOOL fWasAlreadyStrictMode = IsStrictMode();
  4559. BOOL oldStrictMode = this->m_fUseStrictMode;
  4560. if (fLambda)
  4561. {
  4562. CHAKRATEL_LANGSTATS_INC_LANGFEATURECOUNT(ES6, Lambda, m_scriptContext);
  4563. }
  4564. uint uDeferSave = m_grfscr & fscrDeferFncParse;
  4565. if (flags & fFncClassMember)
  4566. {
  4567. // Disable deferral on class members or other construct with unusual text bounds
  4568. // as these are usually trivial, and re-parsing is problematic.
  4569. // NOTE: It is probably worth supporting these cases for memory and load-time purposes,
  4570. // especially as they become more and more common.
  4571. m_grfscr &= ~fscrDeferFncParse;
  4572. }
  4573. bool isTopLevelDeferredFunc = false;
  4574. #if ENABLE_BACKGROUND_PARSING
  4575. struct AutoFastScanFlag {
  4576. bool savedDoingFastScan;
  4577. AutoFastScanFlag(Parser *parser) : m_parser(parser) { savedDoingFastScan = m_parser->m_doingFastScan; }
  4578. ~AutoFastScanFlag() { m_parser->m_doingFastScan = savedDoingFastScan; }
  4579. Parser *m_parser;
  4580. } flag(this);
  4581. #endif
  4582. bool doParallel = false;
  4583. bool parallelJobStarted = false;
  4584. if (buildAST)
  4585. {
  4586. bool isLikelyIIFE = !fDeclaration && pnodeFnc && fUnaryOrParen;
  4587. BOOL isDeferredFnc = IsDeferredFnc();
  4588. AnalysisAssert(isDeferredFnc || pnodeFnc);
  4589. // These are the conditions that prohibit upfront deferral *and* redeferral.
  4590. isTopLevelDeferredFunc =
  4591. (pnodeFnc
  4592. && DeferredParse(pnodeFnc->AsParseNodeFnc()->functionId)
  4593. && (!pnodeFnc->AsParseNodeFnc()->IsNested() || CONFIG_FLAG(DeferNested))
  4594. && !m_InAsmMode
  4595. // Don't defer a module function wrapper because we need to do export resolution at parse time
  4596. && !fModule
  4597. );
  4598. if (pnodeFnc)
  4599. {
  4600. pnodeFnc->AsParseNodeFnc()->SetCanBeDeferred(isTopLevelDeferredFunc && ParseNodeFnc::CanBeRedeferred(pnodeFnc->AsParseNodeFnc()->fncFlags));
  4601. }
  4602. // These are heuristic conditions that prohibit upfront deferral but not redeferral.
  4603. isTopLevelDeferredFunc = isTopLevelDeferredFunc && !isDeferredFnc &&
  4604. (!isLikelyIIFE || !topLevelStmt || PHASE_FORCE_RAW(Js::DeferParsePhase, m_sourceContextInfo->sourceContextId, pnodeFnc->AsParseNodeFnc()->functionId));
  4605. #if ENABLE_BACKGROUND_PARSING
  4606. if (!fLambda &&
  4607. !isDeferredFnc &&
  4608. !isLikelyIIFE &&
  4609. !this->IsBackgroundParser() &&
  4610. !this->m_doingFastScan &&
  4611. !(pnodeFncSave && m_currDeferredStub) &&
  4612. !(this->m_parseType == ParseType_Deferred && this->m_functionBody && this->m_functionBody->GetScopeInfo() && !isTopLevelDeferredFunc))
  4613. {
  4614. doParallel = DoParallelParse(pnodeFnc);
  4615. if (doParallel)
  4616. {
  4617. BackgroundParser *bgp = m_scriptContext->GetBackgroundParser();
  4618. Assert(bgp);
  4619. if (bgp->HasFailedBackgroundParseItem())
  4620. {
  4621. Error(ERRsyntax);
  4622. }
  4623. doParallel = bgp->ParseBackgroundItem(this, pnodeFnc, isTopLevelDeferredFunc);
  4624. if (doParallel)
  4625. {
  4626. parallelJobStarted = true;
  4627. this->m_hasParallelJob = true;
  4628. this->m_doingFastScan = true;
  4629. doParallel = FastScanFormalsAndBody();
  4630. if (doParallel)
  4631. {
  4632. // Let the foreground thread take care of marking the limit on the function node,
  4633. // because in some cases this function's caller will want to change that limit,
  4634. // so we don't want the background thread to try and touch it.
  4635. pnodeFnc->ichLim = m_pscan->IchLimTok();
  4636. pnodeFnc->AsParseNodeFnc()->cbLim = m_pscan->IecpLimTok();
  4637. }
  4638. }
  4639. }
  4640. }
  4641. #endif
  4642. }
  4643. if (!doParallel)
  4644. {
  4645. // We don't want to, or couldn't, let the main thread scan past this function body, so parse
  4646. // it for real.
  4647. ParseNodePtr pnodeRealFnc = pnodeFnc;
  4648. if (parallelJobStarted)
  4649. {
  4650. // We have to deal with a failure to fast-scan the function (due to syntax error? "/"?) when
  4651. // a background thread may already have begun to work on the job. Both threads can't be allowed to
  4652. // operate on the same node.
  4653. pnodeFnc = CreateDummyFuncNode(fDeclaration);
  4654. }
  4655. AnalysisAssert(pnodeFnc);
  4656. ParseNodePtr pnodeBlock = StartParseBlock<buildAST>(PnodeBlockType::Parameter, ScopeType_Parameter);
  4657. AnalysisAssert(pnodeBlock != nullptr);
  4658. pnodeFnc->AsParseNodeFnc()->pnodeScopes = pnodeBlock;
  4659. m_ppnodeVar = &pnodeFnc->AsParseNodeFnc()->pnodeParams;
  4660. pnodeFnc->AsParseNodeFnc()->pnodeVars = nullptr;
  4661. ParseNodePtr* varNodesList = &pnodeFnc->AsParseNodeFnc()->pnodeVars;
  4662. ParseNodePtr argNode = nullptr;
  4663. if (!fModule && !fLambda)
  4664. {
  4665. ParseNodePtr *const ppnodeVarSave = m_ppnodeVar;
  4666. m_ppnodeVar = &pnodeFnc->AsParseNodeFnc()->pnodeVars;
  4667. // Create the built-in arguments symbol
  4668. argNode = this->AddArgumentsNodeToVars(pnodeFnc);
  4669. // Save the updated var list
  4670. varNodesList = m_ppnodeVar;
  4671. m_ppnodeVar = ppnodeVarSave;
  4672. }
  4673. ParseNodePtr *ppnodeScopeSave = nullptr;
  4674. ParseNodePtr *ppnodeExprScopeSave = nullptr;
  4675. ppnodeScopeSave = m_ppnodeScope;
  4676. if (pnodeBlock)
  4677. {
  4678. // This synthetic block scope will contain all the nested scopes.
  4679. m_ppnodeScope = &pnodeBlock->AsParseNodeBlock()->pnodeScopes;
  4680. pnodeBlock->AsParseNodeBlock()->pnodeStmt = pnodeFnc;
  4681. }
  4682. // Keep nested function declarations and expressions in the same list at function scope.
  4683. // (Indicate this by nulling out the current function expressions list.)
  4684. ppnodeExprScopeSave = m_ppnodeExprScope;
  4685. m_ppnodeExprScope = nullptr;
  4686. uint parenExprDepthSave = m_funcParenExprDepth;
  4687. m_funcParenExprDepth = 0;
  4688. if (!skipFormals)
  4689. {
  4690. bool fLambdaParamsSave = m_reparsingLambdaParams;
  4691. if (fLambda)
  4692. {
  4693. m_reparsingLambdaParams = true;
  4694. }
  4695. DeferredFunctionStub *saveDeferredStub = nullptr;
  4696. if (buildAST)
  4697. {
  4698. // Don't try to make use of stubs while parsing formals. Issues with arrow functions, nested functions.
  4699. saveDeferredStub = m_currDeferredStub;
  4700. m_currDeferredStub = nullptr;
  4701. }
  4702. this->ParseFncFormals<buildAST>(pnodeFnc, pnodeFncParent, flags, isTopLevelDeferredFunc);
  4703. if (buildAST)
  4704. {
  4705. m_currDeferredStub = saveDeferredStub;
  4706. }
  4707. m_reparsingLambdaParams = fLambdaParamsSave;
  4708. }
  4709. // Create function body scope
  4710. ParseNodePtr pnodeInnerBlock = StartParseBlock<buildAST>(PnodeBlockType::Function, ScopeType_FunctionBody);
  4711. // Set the parameter block's child to the function body block.
  4712. // The pnodeFnc->AsParseNodeFnc()->pnodeScopes list is constructed in such a way that it includes all the scopes in this list.
  4713. // For example if the param scope has one function and body scope has one function then the list will look like below,
  4714. // param scope block -> function decl from param scope -> body socpe block -> function decl from body scope.
  4715. *m_ppnodeScope = pnodeInnerBlock;
  4716. pnodeFnc->AsParseNodeFnc()->pnodeBodyScope = pnodeInnerBlock;
  4717. // This synthetic block scope will contain all the nested scopes.
  4718. m_ppnodeScope = &pnodeInnerBlock->AsParseNodeBlock()->pnodeScopes;
  4719. pnodeInnerBlock->AsParseNodeBlock()->pnodeStmt = pnodeFnc;
  4720. // DEFER: Begin deferral here (after names are parsed and name nodes created).
  4721. // Create no more AST nodes until we're done.
  4722. // Try to defer this func if all these are true:
  4723. // 0. We are not already in deferred parsing (i.e. buildAST is true)
  4724. // 1. We are not re-parsing a deferred func which is being invoked.
  4725. // 2. Dynamic profile suggests this func can be deferred (and deferred parse is on).
  4726. // 3. This func is top level or defer nested func is on.
  4727. // 4. Optionally, the function is non-nested and not in eval, or the deferral decision was based on cached profile info,
  4728. // or the function is sufficiently long. (I.e., don't defer little nested functions unless we're
  4729. // confident they'll never be executed, because un-deferring nested functions is more expensive.)
  4730. // NOTE: I'm disabling #4 by default, because we've found other ways to reduce the cost of un-deferral,
  4731. // and we don't want to create function bodies aggressively for little functions.
  4732. // We will also temporarily defer all asm.js functions, except for the asm.js
  4733. // module itself, which we will never defer
  4734. bool strictModeTurnedOn = false;
  4735. if (isTopLevelDeferredFunc &&
  4736. !(this->m_grfscr & fscrEvalCode) &&
  4737. pnodeFnc->AsParseNodeFnc()->IsNested() &&
  4738. #ifndef DISABLE_DYNAMIC_PROFILE_DEFER_PARSE
  4739. m_sourceContextInfo->sourceDynamicProfileManager == nullptr &&
  4740. #endif
  4741. PHASE_ON_RAW(Js::ScanAheadPhase, m_sourceContextInfo->sourceContextId, pnodeFnc->AsParseNodeFnc()->functionId) &&
  4742. (
  4743. !PHASE_FORCE_RAW(Js::DeferParsePhase, m_sourceContextInfo->sourceContextId, pnodeFnc->AsParseNodeFnc()->functionId) ||
  4744. PHASE_FORCE_RAW(Js::ScanAheadPhase, m_sourceContextInfo->sourceContextId, pnodeFnc->AsParseNodeFnc()->functionId)
  4745. ))
  4746. {
  4747. // Try to scan ahead to the end of the function. If we get there before we've scanned a minimum
  4748. // number of tokens, don't bother deferring, because it's too small.
  4749. if (this->ScanAheadToFunctionEnd(CONFIG_FLAG(MinDeferredFuncTokenCount)))
  4750. {
  4751. isTopLevelDeferredFunc = false;
  4752. }
  4753. }
  4754. Scope* paramScope = pnodeFnc->AsParseNodeFnc()->pnodeScopes ? pnodeFnc->AsParseNodeFnc()->pnodeScopes->AsParseNodeBlock()->scope : nullptr;
  4755. if (paramScope != nullptr)
  4756. {
  4757. if (CONFIG_FLAG(ForceSplitScope))
  4758. {
  4759. pnodeFnc->AsParseNodeFnc()->ResetBodyAndParamScopeMerged();
  4760. }
  4761. else if (pnodeFnc->AsParseNodeFnc()->HasNonSimpleParameterList() && pnodeFnc->AsParseNodeFnc()->IsBodyAndParamScopeMerged())
  4762. {
  4763. paramScope->ForEachSymbolUntil([this, paramScope, pnodeFnc](Symbol* sym) {
  4764. if (sym->GetPid()->GetTopRef()->GetFuncScopeId() > pnodeFnc->AsParseNodeFnc()->functionId)
  4765. {
  4766. // One of the symbol has non local reference. Mark the param scope as we can't merge it with body scope.
  4767. pnodeFnc->AsParseNodeFnc()->ResetBodyAndParamScopeMerged();
  4768. return true;
  4769. }
  4770. return false;
  4771. });
  4772. if (pnodeFnc->AsParseNodeFnc()->IsBodyAndParamScopeMerged() && !fDeclaration && pnodeFnc->AsParseNodeFnc()->pnodeName != nullptr)
  4773. {
  4774. Symbol* funcSym = pnodeFnc->AsParseNodeFnc()->pnodeName->AsParseNodeVar()->sym;
  4775. if (funcSym->GetPid()->GetTopRef()->GetFuncScopeId() > pnodeFnc->AsParseNodeFnc()->functionId)
  4776. {
  4777. // This is a function expression with name captured in the param scope. In non-eval, non-split cases the function
  4778. // name symbol is added to the body scope to make it accessible in the body. But if there is a function or var
  4779. // declaration with the same name in the body then adding to the body will fail. So in this case we have to add
  4780. // the name symbol to the param scope by splitting it.
  4781. pnodeFnc->AsParseNodeFnc()->ResetBodyAndParamScopeMerged();
  4782. }
  4783. }
  4784. }
  4785. }
  4786. // If the param scope is merged with the body scope we want to use the param scope symbols in the body scope.
  4787. // So add a pid ref for the body using the param scope symbol. Note that in this case the same symbol will occur twice
  4788. // in the same pid ref stack.
  4789. if (paramScope != nullptr && pnodeFnc->AsParseNodeFnc()->IsBodyAndParamScopeMerged())
  4790. {
  4791. paramScope->ForEachSymbol([this](Symbol* paramSym)
  4792. {
  4793. PidRefStack* ref = PushPidRef(paramSym->GetPid());
  4794. ref->SetSym(paramSym);
  4795. });
  4796. }
  4797. AssertMsg(m_funcParenExprDepth == 0, "Paren exprs should have been resolved by the time we finish function formals");
  4798. if (fLambda)
  4799. {
  4800. #ifdef ASMJS_PLAT
  4801. if (m_InAsmMode && (isTopLevelDeferredFunc && m_deferAsmJs))
  4802. {
  4803. // asm.js doesn't support lambda functions
  4804. Js::AsmJSCompiler::OutputError(m_scriptContext, _u("Lambda functions are not supported."));
  4805. Js::AsmJSCompiler::OutputError(m_scriptContext, _u("Asm.js compilation failed."));
  4806. throw Js::AsmJsParseException();
  4807. }
  4808. #endif
  4809. }
  4810. if (m_token.tk == tkRParen)
  4811. {
  4812. m_pscan->Scan();
  4813. }
  4814. if (fLambda)
  4815. {
  4816. BOOL hadNewLine = m_pscan->FHadNewLine();
  4817. // it can be the case we do not have a fat arrow here if there is a valid expression on the left hand side
  4818. // of the fat arrow, but that expression does not parse as a parameter list. E.g.
  4819. // a.x => { }
  4820. // Therefore check for it and error if not found.
  4821. ChkCurTok(tkDArrow, ERRnoDArrow);
  4822. // Newline character between arrow parameters and fat arrow is a syntax error but we want to check for
  4823. // this after verifying there was a => token. Otherwise we would throw the wrong error.
  4824. if (hadNewLine)
  4825. {
  4826. Error(ERRsyntax);
  4827. }
  4828. }
  4829. if (isTopLevelDeferredFunc || (m_InAsmMode && m_deferAsmJs))
  4830. {
  4831. fDeferred = true;
  4832. this->ParseTopLevelDeferredFunc(pnodeFnc, pnodeFncSave, pNameHint, fLambda, pNeedScanRCurly);
  4833. }
  4834. else
  4835. {
  4836. AnalysisAssert(pnodeFnc);
  4837. // Shouldn't be any temps in the arg list.
  4838. Assert(*m_ppnodeVar == nullptr);
  4839. // Start the var list.
  4840. m_ppnodeVar = varNodesList;
  4841. if (!pnodeFnc->AsParseNodeFnc()->IsBodyAndParamScopeMerged())
  4842. {
  4843. OUTPUT_TRACE_DEBUGONLY(Js::ParsePhase, _u("The param and body scope of the function %s cannot be merged\n"), pnodeFnc->AsParseNodeFnc()->pnodeName ? pnodeFnc->AsParseNodeFnc()->pnodeName->AsParseNodeVar()->pid->Psz() : _u("Anonymous function"));
  4844. }
  4845. // Keep nested function declarations and expressions in the same list at function scope.
  4846. // (Indicate this by nulling out the current function expressions list.)
  4847. m_ppnodeExprScope = nullptr;
  4848. if (buildAST)
  4849. {
  4850. DeferredFunctionStub *saveCurrentStub = m_currDeferredStub;
  4851. if (pnodeFncSave && m_currDeferredStub)
  4852. {
  4853. // the Deferred stub will not match for the function which are defined on lambda formals.
  4854. // Since this is not determined upfront that the current function is a part of outer function or part of lambda formal until we have seen the Arrow token.
  4855. // Due to that the current function may be fetching stubs from the outer function (outer of the lambda) - rather then the lambda function. The way to fix is to match
  4856. // the function start with the stub. Because they should match. We need to have previous sibling concept as the lambda formals can have more than one
  4857. // functions and we want to avoid getting wrong stub.
  4858. if (pnodeFncSave->AsParseNodeFnc()->nestedCount == 1)
  4859. {
  4860. m_prevSiblingDeferredStub = nullptr;
  4861. }
  4862. if (m_prevSiblingDeferredStub == nullptr)
  4863. {
  4864. m_prevSiblingDeferredStub = (m_currDeferredStub + (pnodeFncSave->AsParseNodeFnc()->nestedCount - 1));
  4865. }
  4866. if (m_prevSiblingDeferredStub->ichMin == pnodeFnc->ichMin)
  4867. {
  4868. m_currDeferredStub = m_prevSiblingDeferredStub->deferredStubs;
  4869. m_prevSiblingDeferredStub = nullptr;
  4870. }
  4871. else
  4872. {
  4873. m_currDeferredStub = nullptr;
  4874. }
  4875. }
  4876. if (m_token.tk != tkLCurly && fLambda)
  4877. {
  4878. *pNeedScanRCurly = false;
  4879. }
  4880. this->FinishFncDecl(pnodeFnc, pNameHint, lastNodeRef, fLambda, skipFormals);
  4881. m_currDeferredStub = saveCurrentStub;
  4882. }
  4883. else
  4884. {
  4885. this->ParseNestedDeferredFunc(pnodeFnc, fLambda, pNeedScanRCurly, &strictModeTurnedOn);
  4886. }
  4887. }
  4888. // Restore the paren count for any outer spread/rest error checking.
  4889. m_funcParenExprDepth = parenExprDepthSave;
  4890. if (pnodeInnerBlock)
  4891. {
  4892. FinishParseBlock(pnodeInnerBlock, *pNeedScanRCurly);
  4893. }
  4894. if (!fModule && (m_token.tk == tkLCurly || !fLambda))
  4895. {
  4896. UpdateArgumentsNode(pnodeFnc, argNode);
  4897. }
  4898. CreateSpecialSymbolDeclarations(pnodeFnc);
  4899. // Restore the lists of scopes that contain function expressions.
  4900. Assert(m_ppnodeExprScope == nullptr || *m_ppnodeExprScope == nullptr);
  4901. m_ppnodeExprScope = ppnodeExprScopeSave;
  4902. AssertMem(m_ppnodeScope);
  4903. Assert(nullptr == *m_ppnodeScope);
  4904. m_ppnodeScope = ppnodeScopeSave;
  4905. if (pnodeBlock)
  4906. {
  4907. FinishParseBlock(pnodeBlock, *pNeedScanRCurly);
  4908. }
  4909. if (IsStrictMode() || strictModeTurnedOn)
  4910. {
  4911. this->m_fUseStrictMode = TRUE; // Now we know this function is in strict mode
  4912. if (!fWasAlreadyStrictMode)
  4913. {
  4914. // If this function turned on strict mode then we didn't check the formal
  4915. // parameters or function name hint for future reserved word usage. So do that now.
  4916. RestorePoint afterFnc;
  4917. m_pscan->Capture(&afterFnc);
  4918. if (*pHasName)
  4919. {
  4920. // Rewind to the function name hint and check if the token is a reserved word.
  4921. m_pscan->SeekTo(beginNameHint);
  4922. m_pscan->Scan();
  4923. if (pnodeFnc->AsParseNodeFnc()->IsGenerator())
  4924. {
  4925. Assert(m_token.tk == tkStar);
  4926. Assert(m_scriptContext->GetConfig()->IsES6GeneratorsEnabled());
  4927. Assert(!(flags & fFncClassMember));
  4928. m_pscan->Scan();
  4929. }
  4930. if (m_token.IsReservedWord())
  4931. {
  4932. IdentifierExpectedError(m_token);
  4933. }
  4934. CheckStrictModeEvalArgumentsUsage(m_token.GetIdentifier(m_phtbl));
  4935. }
  4936. // Fast forward to formal parameter list, check for future reserved words,
  4937. // then restore scanner as it was.
  4938. m_pscan->SeekToForcingPid(beginFormals);
  4939. CheckStrictFormalParameters();
  4940. m_pscan->SeekTo(afterFnc);
  4941. }
  4942. if (buildAST)
  4943. {
  4944. if (pnodeFnc->AsParseNodeFnc()->pnodeName != nullptr && knopVarDecl == pnodeFnc->AsParseNodeFnc()->pnodeName->nop)
  4945. {
  4946. CheckStrictModeEvalArgumentsUsage(pnodeFnc->AsParseNodeFnc()->pnodeName->AsParseNodeVar()->pid, pnodeFnc->AsParseNodeFnc()->pnodeName);
  4947. }
  4948. }
  4949. this->m_fUseStrictMode = oldStrictMode;
  4950. CHAKRATEL_LANGSTATS_INC_LANGFEATURECOUNT(ES6, StrictModeFunction, m_scriptContext);
  4951. }
  4952. if (fDeferred)
  4953. {
  4954. AnalysisAssert(pnodeFnc);
  4955. pnodeFnc->AsParseNodeFnc()->pnodeVars = nullptr;
  4956. }
  4957. if (parallelJobStarted)
  4958. {
  4959. pnodeFnc = pnodeRealFnc;
  4960. m_currentNodeFunc = pnodeRealFnc;
  4961. // Let the foreground thread take care of marking the limit on the function node,
  4962. // because in some cases this function's caller will want to change that limit,
  4963. // so we don't want the background thread to try and touch it.
  4964. pnodeFnc->ichLim = m_pscan->IchLimTok();
  4965. pnodeFnc->AsParseNodeFnc()->cbLim = m_pscan->IecpLimTok();
  4966. }
  4967. }
  4968. // after parsing asm.js module, we want to reset asm.js state before continuing
  4969. AnalysisAssert(pnodeFnc);
  4970. if (pnodeFnc->AsParseNodeFnc()->GetAsmjsMode())
  4971. {
  4972. m_InAsmMode = false;
  4973. }
  4974. // Restore the statement stack.
  4975. Assert(nullptr == m_pstmtCur);
  4976. SetCurrentStatement(pstmtSave);
  4977. if (pnodeFncExprScope)
  4978. {
  4979. FinishParseFncExprScope(pnodeFnc, pnodeFncExprScope);
  4980. }
  4981. if (!m_stoppedDeferredParse)
  4982. {
  4983. m_grfscr |= uDeferSave;
  4984. }
  4985. m_pscan->SetYieldIsKeywordRegion(fPreviousYieldIsKeyword);
  4986. m_pscan->SetAwaitIsKeywordRegion(fPreviousAwaitIsKeyword);
  4987. // Restore the current function.
  4988. if (buildAST)
  4989. {
  4990. Assert(pnodeFnc == m_currentNodeFunc);
  4991. m_currentNodeFunc = pnodeFncSave;
  4992. m_pCurrentAstSize = pAstSizeSave;
  4993. if (!fLambda)
  4994. {
  4995. Assert(pnodeFnc == m_currentNodeNonLambdaFunc);
  4996. m_currentNodeNonLambdaFunc = pnodeFncSaveNonLambda;
  4997. }
  4998. }
  4999. else
  5000. {
  5001. Assert(pnodeFnc == m_currentNodeDeferredFunc);
  5002. if (!fLambda)
  5003. {
  5004. Assert(pnodeFnc == m_currentNodeNonLambdaDeferredFunc);
  5005. m_currentNodeNonLambdaDeferredFunc = pnodeFncSaveNonLambda;
  5006. }
  5007. m_currentNodeDeferredFunc = pnodeFncSave;
  5008. }
  5009. if (m_currentNodeFunc && pnodeFnc->AsParseNodeFnc()->HasWithStmt())
  5010. {
  5011. GetCurrentFunctionNode()->AsParseNodeFnc()->SetHasWithStmt(true);
  5012. }
  5013. return true;
  5014. }
  5015. template<bool buildAST>
  5016. void Parser::UpdateCurrentNodeFunc(ParseNodePtr pnodeFnc, bool fLambda)
  5017. {
  5018. if (buildAST)
  5019. {
  5020. // Make this the current function and start its sub-function list.
  5021. m_currentNodeFunc = pnodeFnc;
  5022. Assert(m_currentNodeDeferredFunc == nullptr);
  5023. if (!fLambda)
  5024. {
  5025. m_currentNodeNonLambdaFunc = pnodeFnc;
  5026. }
  5027. }
  5028. else // if !buildAST
  5029. {
  5030. AnalysisAssert(pnodeFnc);
  5031. if (!fLambda)
  5032. {
  5033. m_currentNodeNonLambdaDeferredFunc = pnodeFnc;
  5034. }
  5035. m_currentNodeDeferredFunc = pnodeFnc;
  5036. }
  5037. }
  5038. void Parser::ParseTopLevelDeferredFunc(ParseNodePtr pnodeFnc, ParseNodePtr pnodeFncParent, LPCOLESTR pNameHint, bool fLambda, bool *pNeedScanRCurly)
  5039. {
  5040. // Parse a function body that is a transition point from building AST to doing fast syntax check.
  5041. pnodeFnc->AsParseNodeFnc()->pnodeVars = nullptr;
  5042. pnodeFnc->AsParseNodeFnc()->pnodeBody = nullptr;
  5043. this->m_deferringAST = TRUE;
  5044. // Put the scanner into "no hashing" mode.
  5045. BYTE deferFlags = m_pscan->SetDeferredParse(TRUE);
  5046. if (!fLambda)
  5047. {
  5048. ChkCurTok(tkLCurly, ERRnoLcurly);
  5049. }
  5050. else
  5051. {
  5052. // Lambda may consist of a single expression instead of a block
  5053. if (m_pscan->m_ptoken->tk == tkLCurly)
  5054. {
  5055. m_pscan->Scan();
  5056. }
  5057. else
  5058. {
  5059. *pNeedScanRCurly = false;
  5060. }
  5061. }
  5062. ParseNodePtr *ppnodeVarSave = m_ppnodeVar;
  5063. m_ppnodeVar = &pnodeFnc->AsParseNodeFnc()->pnodeVars;
  5064. if (pnodeFncParent != nullptr
  5065. && m_currDeferredStub != nullptr
  5066. // We don't create stubs for function bodies in parameter scope.
  5067. && pnodeFnc->AsParseNodeFnc()->pnodeScopes->AsParseNodeBlock()->blockType != PnodeBlockType::Parameter)
  5068. {
  5069. // We've already parsed this function body for syntax errors on the initial parse of the script.
  5070. // We have information that allows us to skip it, so do so.
  5071. DeferredFunctionStub *stub = m_currDeferredStub + (pnodeFncParent->AsParseNodeFnc()->nestedCount - 1);
  5072. Assert(pnodeFnc->ichMin == stub->ichMin);
  5073. if (stub->fncFlags & kFunctionCallsEval)
  5074. {
  5075. this->MarkEvalCaller();
  5076. }
  5077. if (stub->fncFlags & kFunctionChildCallsEval)
  5078. {
  5079. pnodeFnc->AsParseNodeFnc()->SetChildCallsEval(true);
  5080. }
  5081. if (stub->fncFlags & kFunctionHasWithStmt)
  5082. {
  5083. pnodeFnc->AsParseNodeFnc()->SetHasWithStmt(true);
  5084. }
  5085. PHASE_PRINT_TRACE1(
  5086. Js::SkipNestedDeferredPhase,
  5087. _u("Skipping nested deferred function %d. %s: %d...%d\n"),
  5088. pnodeFnc->AsParseNodeFnc()->functionId, GetFunctionName(pnodeFnc, pNameHint), pnodeFnc->ichMin, stub->restorePoint.m_ichMinTok);
  5089. m_pscan->SeekTo(stub->restorePoint, m_nextFunctionId);
  5090. pnodeFnc->AsParseNodeFnc()->nestedCount = stub->nestedCount;
  5091. pnodeFnc->AsParseNodeFnc()->deferredStub = stub->deferredStubs;
  5092. if (stub->fncFlags & kFunctionStrictMode)
  5093. {
  5094. pnodeFnc->AsParseNodeFnc()->SetStrictMode(true);
  5095. }
  5096. }
  5097. else
  5098. {
  5099. if (fLambda && !*pNeedScanRCurly)
  5100. {
  5101. ParseExpressionLambdaBody<false>(pnodeFnc);
  5102. }
  5103. else
  5104. {
  5105. ParseStmtList<false>(nullptr, nullptr, SM_DeferredParse, true /* isSourceElementList */);
  5106. }
  5107. }
  5108. if (!fLambda || *pNeedScanRCurly)
  5109. {
  5110. pnodeFnc->ichLim = m_pscan->IchLimTok();
  5111. pnodeFnc->AsParseNodeFnc()->cbLim = m_pscan->IecpLimTok();
  5112. }
  5113. m_ppnodeVar = ppnodeVarSave;
  5114. // Restore the scanner's default hashing mode.
  5115. // Do this before we consume the next token.
  5116. m_pscan->SetDeferredParseFlags(deferFlags);
  5117. if (*pNeedScanRCurly)
  5118. {
  5119. ChkCurTokNoScan(tkRCurly, ERRnoRcurly);
  5120. }
  5121. #if DBG
  5122. pnodeFnc->AsParseNodeFnc()->deferredParseNextFunctionId = *this->m_nextFunctionId;
  5123. #endif
  5124. this->m_deferringAST = FALSE;
  5125. }
  5126. bool Parser::DoParallelParse(ParseNodePtr pnodeFnc) const
  5127. {
  5128. #if ENABLE_BACKGROUND_PARSING
  5129. if (!PHASE_ON_RAW(Js::ParallelParsePhase, m_sourceContextInfo->sourceContextId, pnodeFnc->AsParseNodeFnc()->functionId))
  5130. {
  5131. return false;
  5132. }
  5133. BackgroundParser *bgp = m_scriptContext->GetBackgroundParser();
  5134. return bgp != nullptr;
  5135. #else
  5136. return false;
  5137. #endif
  5138. }
  5139. bool Parser::ScanAheadToFunctionEnd(uint count)
  5140. {
  5141. bool found = false;
  5142. uint curlyDepth = 0;
  5143. RestorePoint funcStart;
  5144. m_pscan->Capture(&funcStart);
  5145. for (uint i = 0; i < count; i++)
  5146. {
  5147. switch (m_token.tk)
  5148. {
  5149. case tkStrTmplBegin:
  5150. case tkStrTmplMid:
  5151. case tkStrTmplEnd:
  5152. case tkDiv:
  5153. case tkAsgDiv:
  5154. case tkScanError:
  5155. case tkEOF:
  5156. goto LEnd;
  5157. case tkLCurly:
  5158. UInt32Math::Inc(curlyDepth, Parser::OutOfMemory);
  5159. break;
  5160. case tkRCurly:
  5161. if (curlyDepth == 1)
  5162. {
  5163. found = true;
  5164. goto LEnd;
  5165. }
  5166. if (curlyDepth == 0)
  5167. {
  5168. goto LEnd;
  5169. }
  5170. curlyDepth--;
  5171. break;
  5172. }
  5173. m_pscan->ScanAhead();
  5174. }
  5175. LEnd:
  5176. m_pscan->SeekTo(funcStart);
  5177. return found;
  5178. }
  5179. bool Parser::FastScanFormalsAndBody()
  5180. {
  5181. // The scanner is currently pointing just past the name of a function.
  5182. // The idea here is to find the end of the function body as quickly as possible,
  5183. // by tokenizing and tracking {}'s if possible.
  5184. // String templates require some extra logic but can be handled.
  5185. // The real wrinkle is "/" and "/=", which may indicate either a RegExp literal or a division, depending
  5186. // on the context.
  5187. // To handle this with minimal work, keep track of the last ";" seen at each {} depth. If we see one of the
  5188. // difficult tokens, rewind to the last ";" at the current {} depth and parse statements until we pass the
  5189. // point where we had to rewind. This will process the "/" as required.
  5190. RestorePoint funcStart;
  5191. m_pscan->Capture(&funcStart);
  5192. const int maxRestorePointDepth = 16;
  5193. struct FastScanRestorePoint
  5194. {
  5195. RestorePoint restorePoint;
  5196. uint parenDepth;
  5197. Js::LocalFunctionId functionId;
  5198. int blockId;
  5199. FastScanRestorePoint() : restorePoint(), parenDepth(0) {};
  5200. };
  5201. FastScanRestorePoint lastSColonAtCurlyDepth[maxRestorePointDepth];
  5202. charcount_t ichStart = m_pscan->IchMinTok();
  5203. uint blockIdSave = m_nextBlockId;
  5204. uint functionIdSave = *m_nextFunctionId;
  5205. uint curlyDepth = 0;
  5206. uint strTmplDepth = 0;
  5207. for (;;)
  5208. {
  5209. switch (m_token.tk)
  5210. {
  5211. case tkStrTmplBegin:
  5212. UInt32Math::Inc(strTmplDepth, Parser::OutOfMemory);
  5213. // Fall through
  5214. case tkStrTmplMid:
  5215. case tkLCurly:
  5216. UInt32Math::Inc(curlyDepth, Parser::OutOfMemory);
  5217. Int32Math::Inc(m_nextBlockId, &m_nextBlockId);
  5218. break;
  5219. case tkStrTmplEnd:
  5220. // We can assert here, because the scanner will only return this token if we've told it we're
  5221. // in a string template.
  5222. Assert(strTmplDepth > 0);
  5223. strTmplDepth--;
  5224. break;
  5225. case tkRCurly:
  5226. if (curlyDepth == 1)
  5227. {
  5228. Assert(strTmplDepth == 0);
  5229. if (PHASE_TRACE1(Js::ParallelParsePhase))
  5230. {
  5231. Output::Print(_u("Finished fast seek: %d. %s -- %d...%d\n"),
  5232. m_currentNodeFunc->AsParseNodeFnc()->functionId,
  5233. GetFunctionName(m_currentNodeFunc, m_currentNodeFunc->AsParseNodeFnc()->hint),
  5234. ichStart, m_pscan->IchLimTok());
  5235. }
  5236. return true;
  5237. }
  5238. if (curlyDepth < maxRestorePointDepth)
  5239. {
  5240. lastSColonAtCurlyDepth[curlyDepth].restorePoint.m_ichMinTok = (uint)-1;
  5241. }
  5242. curlyDepth--;
  5243. if (strTmplDepth > 0)
  5244. {
  5245. m_pscan->SetScanState(Scanner_t::ScanState::ScanStateStringTemplateMiddleOrEnd);
  5246. }
  5247. break;
  5248. case tkSColon:
  5249. // Track the location of the ";" (if it's outside parens, as we don't, for instance, want
  5250. // to track the ";"'s in a for-loop header. If we find it's important to rewind within a paren
  5251. // expression, we can do something more sophisticated.)
  5252. if (curlyDepth < maxRestorePointDepth && lastSColonAtCurlyDepth[curlyDepth].parenDepth == 0)
  5253. {
  5254. m_pscan->Capture(&lastSColonAtCurlyDepth[curlyDepth].restorePoint);
  5255. lastSColonAtCurlyDepth[curlyDepth].functionId = *this->m_nextFunctionId;
  5256. lastSColonAtCurlyDepth[curlyDepth].blockId = m_nextBlockId;
  5257. }
  5258. break;
  5259. case tkLParen:
  5260. if (curlyDepth < maxRestorePointDepth)
  5261. {
  5262. UInt32Math::Inc(lastSColonAtCurlyDepth[curlyDepth].parenDepth);
  5263. }
  5264. break;
  5265. case tkRParen:
  5266. if (curlyDepth < maxRestorePointDepth)
  5267. {
  5268. Assert(lastSColonAtCurlyDepth[curlyDepth].parenDepth != 0);
  5269. lastSColonAtCurlyDepth[curlyDepth].parenDepth--;
  5270. }
  5271. break;
  5272. case tkID:
  5273. {
  5274. charcount_t tokLength = m_pscan->IchLimTok() - m_pscan->IchMinTok();
  5275. // Detect the function and class keywords so we can track function ID's.
  5276. // (In fast mode, the scanner doesn't distinguish keywords and doesn't point the token
  5277. // to a PID.)
  5278. // Detect try/catch/for to increment block count for them.
  5279. switch (tokLength)
  5280. {
  5281. case 3:
  5282. if (!memcmp(m_pscan->PchMinTok(), "try", 3) || !memcmp(m_pscan->PchMinTok(), "for", 3))
  5283. {
  5284. Int32Math::Inc(m_nextBlockId, &m_nextBlockId);
  5285. }
  5286. break;
  5287. case 5:
  5288. if (!memcmp(m_pscan->PchMinTok(), "catch", 5))
  5289. {
  5290. Int32Math::Inc(m_nextBlockId, &m_nextBlockId);
  5291. }
  5292. else if (!memcmp(m_pscan->PchMinTok(), "class", 5))
  5293. {
  5294. Int32Math::Inc(m_nextBlockId, &m_nextBlockId);
  5295. Int32Math::Inc(*this->m_nextFunctionId, (int*)this->m_nextFunctionId);
  5296. }
  5297. break;
  5298. case 8:
  5299. if (!memcmp(m_pscan->PchMinTok(), "function", 8))
  5300. {
  5301. // Account for the possible func expr scope or dummy block for missing {}'s around a declaration
  5302. Int32Math::Inc(m_nextBlockId, &m_nextBlockId);
  5303. Int32Math::Inc(*this->m_nextFunctionId, (int*)this->m_nextFunctionId);
  5304. }
  5305. break;
  5306. }
  5307. break;
  5308. }
  5309. case tkDArrow:
  5310. Int32Math::Inc(m_nextBlockId, &m_nextBlockId);
  5311. Int32Math::Inc(*this->m_nextFunctionId, (int*)this->m_nextFunctionId);
  5312. break;
  5313. case tkDiv:
  5314. case tkAsgDiv:
  5315. {
  5316. int opl;
  5317. OpCode nop;
  5318. tokens tkPrev = m_pscan->m_tkPrevious;
  5319. if ((m_pscan->m_phtbl->TokIsBinop(tkPrev, &opl, &nop) && nop != knopNone) ||
  5320. (m_pscan->m_phtbl->TokIsUnop(tkPrev, &opl, &nop) &&
  5321. nop != knopNone &&
  5322. tkPrev != tkInc &&
  5323. tkPrev != tkDec) ||
  5324. tkPrev == tkColon ||
  5325. tkPrev == tkLParen ||
  5326. tkPrev == tkLBrack ||
  5327. tkPrev == tkRETURN)
  5328. {
  5329. // Previous token indicates that we're starting an expression here and can't have a
  5330. // binary operator now.
  5331. // Assume this is a RegExp.
  5332. ParseRegExp<false>();
  5333. break;
  5334. }
  5335. uint tempCurlyDepth = curlyDepth < maxRestorePointDepth ? curlyDepth : maxRestorePointDepth - 1;
  5336. for (; tempCurlyDepth != (uint)-1; tempCurlyDepth--)
  5337. {
  5338. // We don't know whether we've got a RegExp or a divide. Rewind to the last safe ";"
  5339. // if we can and parse statements until we pass this point.
  5340. if (lastSColonAtCurlyDepth[tempCurlyDepth].restorePoint.m_ichMinTok != -1)
  5341. {
  5342. break;
  5343. }
  5344. }
  5345. if (tempCurlyDepth != (uint)-1)
  5346. {
  5347. ParseNodePtr pnodeFncSave = m_currentNodeFunc;
  5348. int32 *pastSizeSave = m_pCurrentAstSize;
  5349. uint *pnestedCountSave = m_pnestedCount;
  5350. ParseNodePtr *ppnodeScopeSave = m_ppnodeScope;
  5351. ParseNodePtr *ppnodeExprScopeSave = m_ppnodeExprScope;
  5352. ParseNodePtr pnodeFnc = CreateDummyFuncNode(true);
  5353. m_ppnodeScope = &pnodeFnc->AsParseNodeFnc()->pnodeScopes;
  5354. m_ppnodeExprScope = nullptr;
  5355. charcount_t ichStop = m_pscan->IchLimTok();
  5356. curlyDepth = tempCurlyDepth;
  5357. m_pscan->SeekTo(lastSColonAtCurlyDepth[tempCurlyDepth].restorePoint);
  5358. m_nextBlockId = lastSColonAtCurlyDepth[tempCurlyDepth].blockId;
  5359. *this->m_nextFunctionId = lastSColonAtCurlyDepth[tempCurlyDepth].functionId;
  5360. ParseNodePtr pnodeBlock = StartParseBlock<true>(PnodeBlockType::Function, ScopeType_FunctionBody);
  5361. m_pscan->Scan();
  5362. do
  5363. {
  5364. ParseStatement<false>();
  5365. }
  5366. while(m_pscan->IchMinTok() < ichStop);
  5367. FinishParseBlock(pnodeBlock);
  5368. m_currentNodeFunc = pnodeFncSave;
  5369. m_pCurrentAstSize = pastSizeSave;
  5370. m_pnestedCount = pnestedCountSave;
  5371. m_ppnodeScope = ppnodeScopeSave;
  5372. m_ppnodeExprScope = ppnodeExprScopeSave;
  5373. // We've already consumed the first token of the next statement, so just continue
  5374. // without a further scan.
  5375. continue;
  5376. }
  5377. }
  5378. // fall through to rewind to function start
  5379. case tkScanError:
  5380. case tkEOF:
  5381. // Unexpected token.
  5382. if (PHASE_TRACE1(Js::ParallelParsePhase))
  5383. {
  5384. Output::Print(_u("Failed fast seek: %d. %s -- %d...%d\n"),
  5385. m_currentNodeFunc->AsParseNodeFnc()->functionId,
  5386. GetFunctionName(m_currentNodeFunc, m_currentNodeFunc->AsParseNodeFnc()->hint),
  5387. ichStart, m_pscan->IchLimTok());
  5388. }
  5389. m_nextBlockId = blockIdSave;
  5390. *m_nextFunctionId = functionIdSave;
  5391. m_pscan->SeekTo(funcStart);
  5392. return false;
  5393. }
  5394. m_pscan->ScanNoKeywords();
  5395. }
  5396. }
  5397. ParseNodePtr Parser::CreateDummyFuncNode(bool fDeclaration)
  5398. {
  5399. // Create a dummy node and make it look like the current function declaration.
  5400. // Do this in situations where we want to parse statements without impacting
  5401. // the state of the "real" AST.
  5402. ParseNodePtr pnodeFnc = CreateNode(knopFncDecl);
  5403. pnodeFnc->AsParseNodeFnc()->ClearFlags();
  5404. pnodeFnc->AsParseNodeFnc()->SetDeclaration(fDeclaration);
  5405. pnodeFnc->AsParseNodeFnc()->astSize = 0;
  5406. pnodeFnc->AsParseNodeFnc()->pnodeName = nullptr;
  5407. pnodeFnc->AsParseNodeFnc()->pnodeScopes = nullptr;
  5408. pnodeFnc->AsParseNodeFnc()->pnodeRest = nullptr;
  5409. pnodeFnc->AsParseNodeFnc()->pid = nullptr;
  5410. pnodeFnc->AsParseNodeFnc()->hint = nullptr;
  5411. pnodeFnc->AsParseNodeFnc()->hintOffset = 0;
  5412. pnodeFnc->AsParseNodeFnc()->hintLength = 0;
  5413. pnodeFnc->AsParseNodeFnc()->isNameIdentifierRef = true;
  5414. pnodeFnc->AsParseNodeFnc()->nestedFuncEscapes = false;
  5415. pnodeFnc->AsParseNodeFnc()->pnodeNext = nullptr;
  5416. pnodeFnc->AsParseNodeFnc()->pnodeParams = nullptr;
  5417. pnodeFnc->AsParseNodeFnc()->pnodeVars = nullptr;
  5418. pnodeFnc->AsParseNodeFnc()->funcInfo = nullptr;
  5419. pnodeFnc->AsParseNodeFnc()->deferredStub = nullptr;
  5420. pnodeFnc->AsParseNodeFnc()->nestedCount = 0;
  5421. pnodeFnc->AsParseNodeFnc()->SetNested(m_currentNodeFunc != nullptr); // If there is a current function, then we're a nested function.
  5422. pnodeFnc->AsParseNodeFnc()->SetStrictMode(IsStrictMode()); // Inherit current strict mode -- may be overridden by the function itself if it contains a strict mode directive.
  5423. pnodeFnc->AsParseNodeFnc()->firstDefaultArg = 0;
  5424. pnodeFnc->AsParseNodeFnc()->isBodyAndParamScopeMerged = true;
  5425. m_pCurrentAstSize = &pnodeFnc->AsParseNodeFnc()->astSize;
  5426. m_currentNodeFunc = pnodeFnc;
  5427. m_pnestedCount = &pnodeFnc->AsParseNodeFnc()->nestedCount;
  5428. return pnodeFnc;
  5429. }
  5430. void Parser::ParseNestedDeferredFunc(ParseNodePtr pnodeFnc, bool fLambda, bool *pNeedScanRCurly, bool *pStrictModeTurnedOn)
  5431. {
  5432. // Parse a function nested inside another deferred function.
  5433. size_t lengthBeforeBody = this->GetSourceLength();
  5434. if (m_token.tk != tkLCurly && fLambda)
  5435. {
  5436. ParseExpressionLambdaBody<false>(pnodeFnc);
  5437. *pNeedScanRCurly = false;
  5438. }
  5439. else
  5440. {
  5441. ChkCurTok(tkLCurly, ERRnoLcurly);
  5442. bool* detectStrictModeOn = IsStrictMode() ? nullptr : pStrictModeTurnedOn;
  5443. m_ppnodeVar = &m_currentNodeDeferredFunc->AsParseNodeFnc()->pnodeVars;
  5444. ParseStmtList<false>(nullptr, nullptr, SM_DeferredParse, true /* isSourceElementList */, detectStrictModeOn);
  5445. ChkCurTokNoScan(tkRCurly, ERRnoRcurly);
  5446. pnodeFnc->ichLim = m_pscan->IchLimTok();
  5447. pnodeFnc->AsParseNodeFnc()->cbLim = m_pscan->IecpLimTok();
  5448. }
  5449. if (*pStrictModeTurnedOn)
  5450. {
  5451. pnodeFnc->AsParseNodeFnc()->SetStrictMode(true);
  5452. }
  5453. if (!PHASE_OFF1(Js::SkipNestedDeferredPhase))
  5454. {
  5455. // Record the end of the function and the function ID increment that happens inside the function.
  5456. // Byte code gen will use this to build stub information to allow us to skip this function when the
  5457. // enclosing function is fully parsed.
  5458. RestorePoint *restorePoint = Anew(&m_nodeAllocator, RestorePoint);
  5459. m_pscan->Capture(restorePoint,
  5460. *m_nextFunctionId - pnodeFnc->AsParseNodeFnc()->functionId - 1,
  5461. lengthBeforeBody - this->GetSourceLength());
  5462. pnodeFnc->AsParseNodeFnc()->pRestorePoint = restorePoint;
  5463. }
  5464. }
  5465. template<bool buildAST>
  5466. bool Parser::ParseFncNames(ParseNodePtr pnodeFnc, ParseNodePtr pnodeFncParent, ushort flags, ParseNodePtr **pLastNodeRef, IdentPtr* pFncNamePid)
  5467. {
  5468. BOOL fDeclaration = flags & fFncDeclaration;
  5469. BOOL fIsAsync = flags & fFncAsync;
  5470. ParseNodePtr pnodeT;
  5471. charcount_t ichMinNames, ichLimNames;
  5472. // Get the names to bind to.
  5473. /*
  5474. * KaushiS [5/15/08]:
  5475. * ECMAScript defines a FunctionExpression as follows:
  5476. *
  5477. * "function" [Identifier] ( [FormalParameterList] ) { FunctionBody }
  5478. *
  5479. * The function name being optional is omitted by most real world
  5480. * code that uses a FunctionExpression to define a function. This however
  5481. * is problematic for tools because there isn't a function name that
  5482. * the runtime can provide.
  5483. *
  5484. * To fix this (primarily for the profiler), I'm adding simple, static
  5485. * name inferencing logic to the parser. When it encounters the following
  5486. * productions
  5487. *
  5488. * "var" Identifier "=" FunctionExpression
  5489. * "var" IdentifierA.IdentifierB...Identifier "=" FunctionExpression
  5490. * Identifier = FunctionExpression
  5491. * "{" Identifier: FunctionExpression "}"
  5492. *
  5493. * it associates Identifier with the function created by the
  5494. * FunctionExpression. This identifier is *not* the function's name. It
  5495. * is ignored by the runtime and is only an additional piece of information
  5496. * about the function (function name hint) that tools could opt to
  5497. * surface.
  5498. */
  5499. m_pscan->Scan();
  5500. // If generators are enabled then we are in a recent enough version
  5501. // that deferred parsing will create a parse node for pnodeFnc and
  5502. // it is safe to assume it is not null.
  5503. if (flags & fFncGenerator)
  5504. {
  5505. Assert(m_scriptContext->GetConfig()->IsES6GeneratorsEnabled());
  5506. pnodeFnc->AsParseNodeFnc()->SetIsGenerator();
  5507. }
  5508. else if (m_scriptContext->GetConfig()->IsES6GeneratorsEnabled() &&
  5509. m_token.tk == tkStar &&
  5510. !(flags & fFncClassMember))
  5511. {
  5512. if (!fDeclaration)
  5513. {
  5514. bool fPreviousYieldIsKeyword = m_pscan->SetYieldIsKeywordRegion(!fDeclaration);
  5515. m_pscan->Scan();
  5516. m_pscan->SetYieldIsKeywordRegion(fPreviousYieldIsKeyword);
  5517. }
  5518. else
  5519. {
  5520. m_pscan->Scan();
  5521. }
  5522. pnodeFnc->AsParseNodeFnc()->SetIsGenerator();
  5523. }
  5524. if (fIsAsync)
  5525. {
  5526. if (pnodeFnc->AsParseNodeFnc()->IsGenerator())
  5527. {
  5528. Error(ERRsyntax);
  5529. }
  5530. pnodeFnc->AsParseNodeFnc()->SetIsAsync();
  5531. }
  5532. if (pnodeFnc)
  5533. {
  5534. pnodeFnc->AsParseNodeFnc()->pnodeName = nullptr;
  5535. }
  5536. if ((m_token.tk != tkID || flags & fFncNoName)
  5537. && (IsStrictMode() || (pnodeFnc && pnodeFnc->AsParseNodeFnc()->IsGenerator()) || m_token.tk != tkYIELD || fDeclaration)) // Function expressions can have the name yield even inside generator functions
  5538. {
  5539. if (fDeclaration ||
  5540. m_token.IsReservedWord()) // For example: var x = (function break(){});
  5541. {
  5542. IdentifierExpectedError(m_token);
  5543. }
  5544. return false;
  5545. }
  5546. ichMinNames = m_pscan->IchMinTok();
  5547. Assert(m_token.tk == tkID || (m_token.tk == tkYIELD && !fDeclaration));
  5548. if (IsStrictMode())
  5549. {
  5550. CheckStrictModeEvalArgumentsUsage(m_token.GetIdentifier(m_phtbl));
  5551. }
  5552. Token tokenBase = m_token;
  5553. charcount_t ichMinBase = m_pscan->IchMinTok();
  5554. charcount_t ichLimBase = m_pscan->IchLimTok();
  5555. m_pscan->Scan();
  5556. IdentPtr pidBase = tokenBase.GetIdentifier(m_phtbl);
  5557. pnodeT = CreateDeclNode(knopVarDecl, pidBase, STFunction);
  5558. pnodeT->ichMin = ichMinBase;
  5559. pnodeT->ichLim = ichLimBase;
  5560. if (pFncNamePid != nullptr)
  5561. {
  5562. *pFncNamePid = pidBase;
  5563. }
  5564. if (buildAST)
  5565. {
  5566. AnalysisAssert(pnodeFnc);
  5567. ichLimNames = pnodeT->ichLim;
  5568. AddToNodeList(&pnodeFnc->AsParseNodeFnc()->pnodeName, pLastNodeRef, pnodeT);
  5569. pnodeFnc->AsParseNodeFnc()->pnodeName->ichMin = ichMinNames;
  5570. pnodeFnc->AsParseNodeFnc()->pnodeName->ichLim = ichLimNames;
  5571. if (knopVarDecl == pnodeFnc->AsParseNodeFnc()->pnodeName->nop)
  5572. {
  5573. // Only one name (the common case).
  5574. pnodeFnc->AsParseNodeFnc()->pid = pnodeFnc->AsParseNodeFnc()->pnodeName->AsParseNodeVar()->pid;
  5575. }
  5576. else
  5577. {
  5578. // Multiple names. Turn the source into an IdentPtr.
  5579. pnodeFnc->AsParseNodeFnc()->pid = m_phtbl->PidHashNameLen(
  5580. m_pscan->PchBase() + ichMinNames,
  5581. m_pscan->AdjustedLast(),
  5582. ichLimNames - ichMinNames);
  5583. }
  5584. }
  5585. return true;
  5586. }
  5587. void Parser::ValidateFormals()
  5588. {
  5589. ParseFncFormals<false>(this->GetCurrentFunctionNode(), nullptr, fFncNoFlgs);
  5590. // Eat the tkRParen. The ParseFncDeclHelper caller expects to see it.
  5591. m_pscan->Scan();
  5592. }
  5593. void Parser::ValidateSourceElementList()
  5594. {
  5595. ParseStmtList<false>(nullptr, nullptr, SM_NotUsed, true);
  5596. }
  5597. void Parser::UpdateOrCheckForDuplicateInFormals(IdentPtr pid, SList<IdentPtr> *formals)
  5598. {
  5599. bool isStrictMode = IsStrictMode();
  5600. if (isStrictMode)
  5601. {
  5602. CheckStrictModeEvalArgumentsUsage(pid);
  5603. }
  5604. if (formals->Has(pid))
  5605. {
  5606. if (isStrictMode)
  5607. {
  5608. Error(ERRES5ArgSame);
  5609. }
  5610. else
  5611. {
  5612. Error(ERRFormalSame);
  5613. }
  5614. }
  5615. else
  5616. {
  5617. formals->Prepend(pid);
  5618. }
  5619. }
  5620. template<bool buildAST>
  5621. void Parser::ParseFncFormals(ParseNodePtr pnodeFnc, ParseNodePtr pnodeParentFnc, ushort flags, bool isTopLevelDeferredFunc)
  5622. {
  5623. bool fLambda = (flags & fFncLambda) != 0;
  5624. bool fMethod = (flags & fFncMethod) != 0;
  5625. bool fNoArg = (flags & fFncNoArg) != 0;
  5626. bool fOneArg = (flags & fFncOneArg) != 0;
  5627. bool fAsync = (flags & fFncAsync) != 0;
  5628. bool fPreviousYieldIsKeyword = false;
  5629. bool fPreviousAwaitIsKeyword = false;
  5630. if (fLambda)
  5631. {
  5632. fPreviousYieldIsKeyword = m_pscan->SetYieldIsKeywordRegion(pnodeParentFnc != nullptr && pnodeParentFnc->AsParseNodeFnc()->IsGenerator());
  5633. fPreviousAwaitIsKeyword = m_pscan->SetAwaitIsKeywordRegion(fAsync || (pnodeParentFnc != nullptr && pnodeParentFnc->AsParseNodeFnc()->IsAsync()));
  5634. }
  5635. Assert(!fNoArg || !fOneArg); // fNoArg and fOneArg can never be true at the same time.
  5636. // strictFormals corresponds to the StrictFormalParameters grammar production
  5637. // in the ES spec which just means duplicate names are not allowed
  5638. bool fStrictFormals = IsStrictMode() || fLambda || fMethod;
  5639. // When detecting duplicated formals pids are needed so force PID creation (unless the function should take 0 or 1 arg).
  5640. bool forcePid = fStrictFormals && !fNoArg && !fOneArg;
  5641. AutoTempForcePid autoForcePid(m_pscan, forcePid);
  5642. // Lambda's allow single formal specified by a single binding identifier without parentheses, special case it.
  5643. if (fLambda && m_token.tk == tkID)
  5644. {
  5645. IdentPtr pid = m_token.GetIdentifier(m_phtbl);
  5646. CreateVarDeclNode(pid, STFormal, false, nullptr, false);
  5647. CheckPidIsValid(pid);
  5648. m_pscan->Scan();
  5649. if (m_token.tk != tkDArrow)
  5650. {
  5651. Error(ERRsyntax, m_pscan->IchMinTok(), m_pscan->IchLimTok());
  5652. }
  5653. if (fLambda)
  5654. {
  5655. m_pscan->SetYieldIsKeywordRegion(fPreviousYieldIsKeyword);
  5656. m_pscan->SetAwaitIsKeywordRegion(fPreviousAwaitIsKeyword);
  5657. }
  5658. return;
  5659. }
  5660. else if (fLambda && m_token.tk == tkAWAIT)
  5661. {
  5662. // async await => {}
  5663. IdentifierExpectedError(m_token);
  5664. }
  5665. // Otherwise, must have a parameter list within parens.
  5666. ChkCurTok(tkLParen, ERRnoLparen);
  5667. // Now parse the list of arguments, if present
  5668. if (m_token.tk == tkRParen)
  5669. {
  5670. if (fOneArg)
  5671. {
  5672. Error(ERRSetterMustHaveOneParameter);
  5673. }
  5674. }
  5675. else
  5676. {
  5677. if (fNoArg)
  5678. {
  5679. Error(ERRGetterMustHaveNoParameters);
  5680. }
  5681. SList<IdentPtr> formals(&m_nodeAllocator);
  5682. ParseNodePtr pnodeT = nullptr;
  5683. bool seenRestParameter = false;
  5684. bool isNonSimpleParameterList = false;
  5685. for (Js::ArgSlot argPos = 0; ; ++argPos)
  5686. {
  5687. bool isBindingPattern = false;
  5688. if (m_scriptContext->GetConfig()->IsES6RestEnabled() && m_token.tk == tkEllipsis)
  5689. {
  5690. // Possible rest parameter
  5691. m_pscan->Scan();
  5692. seenRestParameter = true;
  5693. }
  5694. if (m_token.tk != tkID)
  5695. {
  5696. if (IsES6DestructuringEnabled() && IsPossiblePatternStart())
  5697. {
  5698. // Mark that the function has a non simple parameter list before parsing the pattern since the pattern can have function definitions.
  5699. this->GetCurrentFunctionNode()->AsParseNodeFnc()->SetHasNonSimpleParameterList();
  5700. this->GetCurrentFunctionNode()->AsParseNodeFnc()->SetHasDestructuredParams();
  5701. ParseNodePtr *const ppnodeVarSave = m_ppnodeVar;
  5702. m_ppnodeVar = &pnodeFnc->AsParseNodeFnc()->pnodeVars;
  5703. ParseNodePtr * ppNodeLex = m_currentBlockInfo->m_ppnodeLex;
  5704. Assert(ppNodeLex != nullptr);
  5705. ParseNodePtr paramPattern = nullptr;
  5706. ParseNodePtr pnodePattern = nullptr;
  5707. if (isTopLevelDeferredFunc)
  5708. {
  5709. pnodePattern = ParseDestructuredLiteral<false>(tkLET, true /*isDecl*/, false /*topLevel*/);
  5710. }
  5711. else
  5712. {
  5713. pnodePattern = ParseDestructuredLiteral<buildAST>(tkLET, true /*isDecl*/, false /*topLevel*/);
  5714. }
  5715. // Instead of passing the STFormal all the way on many methods, it seems it is better to change the symbol type afterward.
  5716. for (ParseNodePtr lexNode = *ppNodeLex; lexNode != nullptr; lexNode = lexNode->AsParseNodeVar()->pnodeNext)
  5717. {
  5718. Assert(lexNode->IsVarLetOrConst());
  5719. UpdateOrCheckForDuplicateInFormals(lexNode->AsParseNodeVar()->pid, &formals);
  5720. lexNode->AsParseNodeVar()->sym->SetSymbolType(STFormal);
  5721. if (lexNode->AsParseNodeVar()->pid == wellKnownPropertyPids.arguments)
  5722. {
  5723. GetCurrentFunctionNode()->grfpn |= PNodeFlags::fpnArguments_overriddenInParam;
  5724. }
  5725. }
  5726. m_ppnodeVar = ppnodeVarSave;
  5727. if (buildAST)
  5728. {
  5729. if (isTopLevelDeferredFunc)
  5730. {
  5731. Assert(pnodePattern == nullptr);
  5732. // Create a dummy pattern node as we need the node to be considered for the param count
  5733. paramPattern = CreateDummyParamPatternNode(m_pscan->IchMinTok());
  5734. }
  5735. else
  5736. {
  5737. Assert(pnodePattern);
  5738. paramPattern = CreateParamPatternNode(pnodePattern);
  5739. }
  5740. // Linking the current formal parameter (which is pattern parameter) with other formals.
  5741. *m_ppnodeVar = paramPattern;
  5742. paramPattern->AsParseNodeParamPattern()->pnodeNext = nullptr;
  5743. m_ppnodeVar = &paramPattern->AsParseNodeParamPattern()->pnodeNext;
  5744. }
  5745. isBindingPattern = true;
  5746. isNonSimpleParameterList = true;
  5747. }
  5748. else
  5749. {
  5750. IdentifierExpectedError(m_token);
  5751. }
  5752. }
  5753. if (!isBindingPattern)
  5754. {
  5755. IdentPtr pid = m_token.GetIdentifier(m_phtbl);
  5756. LPCOLESTR pNameHint = pid->Psz();
  5757. uint32 nameHintLength = pid->Cch();
  5758. uint32 nameHintOffset = 0;
  5759. if (seenRestParameter)
  5760. {
  5761. this->GetCurrentFunctionNode()->AsParseNodeFnc()->SetHasNonSimpleParameterList();
  5762. if (flags & fFncOneArg)
  5763. {
  5764. // The parameter of a setter cannot be a rest parameter.
  5765. Error(ERRUnexpectedEllipsis);
  5766. }
  5767. pnodeT = CreateDeclNode(knopVarDecl, pid, STFormal, false);
  5768. pnodeT->AsParseNodeVar()->sym->SetIsNonSimpleParameter(true);
  5769. if (buildAST)
  5770. {
  5771. // When only validating formals, we won't have a function node.
  5772. pnodeFnc->AsParseNodeFnc()->pnodeRest = pnodeT;
  5773. if (!isNonSimpleParameterList)
  5774. {
  5775. // This is the first non-simple parameter we've seen. We need to go back
  5776. // and set the Symbols of all previous parameters.
  5777. MapFormalsWithoutRest(m_currentNodeFunc, [&](ParseNodePtr pnodeArg) { pnodeArg->AsParseNodeVar()->sym->SetIsNonSimpleParameter(true); });
  5778. }
  5779. }
  5780. isNonSimpleParameterList = true;
  5781. }
  5782. else
  5783. {
  5784. pnodeT = CreateVarDeclNode(pid, STFormal, false, nullptr, false);
  5785. if (isNonSimpleParameterList)
  5786. {
  5787. pnodeT->AsParseNodeVar()->sym->SetIsNonSimpleParameter(true);
  5788. }
  5789. }
  5790. if (buildAST && pid == wellKnownPropertyPids.arguments)
  5791. {
  5792. // This formal parameter overrides the built-in 'arguments' object
  5793. m_currentNodeFunc->grfpn |= PNodeFlags::fpnArguments_overriddenInParam;
  5794. }
  5795. if (fStrictFormals)
  5796. {
  5797. UpdateOrCheckForDuplicateInFormals(pid, &formals);
  5798. }
  5799. m_pscan->Scan();
  5800. if (seenRestParameter && m_token.tk != tkRParen && m_token.tk != tkAsg)
  5801. {
  5802. Error(ERRRestLastArg);
  5803. }
  5804. if (m_token.tk == tkAsg && m_scriptContext->GetConfig()->IsES6DefaultArgsEnabled())
  5805. {
  5806. if (seenRestParameter && m_scriptContext->GetConfig()->IsES6RestEnabled())
  5807. {
  5808. Error(ERRRestWithDefault);
  5809. }
  5810. // In defer parse mode we have to flag the function node to indicate that it has default arguments
  5811. // so that it will be considered for any syntax error scenario.
  5812. // Also mark it before parsing the expression as it may contain functions.
  5813. ParseNode* currentFncNode = GetCurrentFunctionNode();
  5814. if (!currentFncNode->AsParseNodeFnc()->HasDefaultArguments())
  5815. {
  5816. currentFncNode->AsParseNodeFnc()->SetHasDefaultArguments();
  5817. currentFncNode->AsParseNodeFnc()->SetHasNonSimpleParameterList();
  5818. currentFncNode->AsParseNodeFnc()->firstDefaultArg = argPos;
  5819. }
  5820. m_pscan->Scan();
  5821. ParseNodePtr pnodeInit;
  5822. if (isTopLevelDeferredFunc)
  5823. {
  5824. // Defer default expressions if the function will be deferred, since we know they can't be evaluated
  5825. // until the function is fully compiled, and generating code for a function nested inside a deferred function
  5826. // creates inconsistencies.
  5827. pnodeInit = ParseExpr<false>(koplCma, nullptr, TRUE, FALSE, pNameHint, &nameHintLength, &nameHintOffset);
  5828. }
  5829. else
  5830. {
  5831. pnodeInit = ParseExpr<buildAST>(koplCma, nullptr, TRUE, FALSE, pNameHint, &nameHintLength, &nameHintOffset);
  5832. }
  5833. if (buildAST && pnodeInit && pnodeInit->nop == knopFncDecl)
  5834. {
  5835. Assert(nameHintLength >= nameHintOffset);
  5836. pnodeInit->AsParseNodeFnc()->hint = pNameHint;
  5837. pnodeInit->AsParseNodeFnc()->hintLength = nameHintLength;
  5838. pnodeInit->AsParseNodeFnc()->hintOffset = nameHintOffset;
  5839. }
  5840. AnalysisAssert(pnodeT);
  5841. pnodeT->AsParseNodeVar()->sym->SetIsNonSimpleParameter(true);
  5842. if (!isNonSimpleParameterList)
  5843. {
  5844. if (buildAST)
  5845. {
  5846. // This is the first non-simple parameter we've seen. We need to go back
  5847. // and set the Symbols of all previous parameters.
  5848. MapFormalsWithoutRest(m_currentNodeFunc, [&](ParseNodePtr pnodeArg) { pnodeArg->AsParseNodeVar()->sym->SetIsNonSimpleParameter(true); });
  5849. }
  5850. // There may be previous parameters that need to be checked for duplicates.
  5851. isNonSimpleParameterList = true;
  5852. }
  5853. if (buildAST)
  5854. {
  5855. if (!m_currentNodeFunc->AsParseNodeFnc()->HasDefaultArguments())
  5856. {
  5857. CHAKRATEL_LANGSTATS_INC_LANGFEATURECOUNT(ES6, DefaultArgFunction, m_scriptContext);
  5858. }
  5859. pnodeT->AsParseNodeVar()->pnodeInit = pnodeInit;
  5860. pnodeT->ichLim = m_pscan->IchLimTok();
  5861. }
  5862. }
  5863. }
  5864. if (isNonSimpleParameterList && m_currentScope->GetHasDuplicateFormals())
  5865. {
  5866. Error(ERRFormalSame);
  5867. }
  5868. if (flags & fFncOneArg)
  5869. {
  5870. if (m_token.tk != tkRParen)
  5871. {
  5872. Error(ERRSetterMustHaveOneParameter);
  5873. }
  5874. break; //enforce only one arg
  5875. }
  5876. if (m_token.tk != tkComma)
  5877. {
  5878. break;
  5879. }
  5880. m_pscan->Scan();
  5881. if (m_token.tk == tkRParen && m_scriptContext->GetConfig()->IsES7TrailingCommaEnabled())
  5882. {
  5883. break;
  5884. }
  5885. }
  5886. if (seenRestParameter)
  5887. {
  5888. CHAKRATEL_LANGSTATS_INC_LANGFEATURECOUNT(ES6, Rest, m_scriptContext);
  5889. }
  5890. if (m_token.tk != tkRParen)
  5891. {
  5892. Error(ERRnoRparen);
  5893. }
  5894. if (this->GetCurrentFunctionNode()->AsParseNodeFnc()->CallsEval() || this->GetCurrentFunctionNode()->AsParseNodeFnc()->ChildCallsEval())
  5895. {
  5896. Assert(pnodeFnc->AsParseNodeFnc()->HasNonSimpleParameterList());
  5897. pnodeFnc->AsParseNodeFnc()->ResetBodyAndParamScopeMerged();
  5898. }
  5899. }
  5900. Assert(m_token.tk == tkRParen);
  5901. if (fLambda)
  5902. {
  5903. m_pscan->SetYieldIsKeywordRegion(fPreviousYieldIsKeyword);
  5904. m_pscan->SetAwaitIsKeywordRegion(fPreviousAwaitIsKeyword);
  5905. }
  5906. }
  5907. template<bool buildAST>
  5908. ParseNodePtr Parser::GenerateModuleFunctionWrapper()
  5909. {
  5910. ParseNodePtr pnodeFnc = ParseFncDecl<buildAST>(fFncModule, nullptr, false, true, true);
  5911. ParseNodePtr callNode = CreateCallNode(knopCall, pnodeFnc, nullptr);
  5912. return callNode;
  5913. }
  5914. template<bool buildAST>
  5915. ParseNodePtr Parser::GenerateEmptyConstructor(bool extends)
  5916. {
  5917. ParseNodePtr pnodeFnc;
  5918. // Create the node.
  5919. pnodeFnc = CreateNode(knopFncDecl);
  5920. pnodeFnc->AsParseNodeFnc()->ClearFlags();
  5921. pnodeFnc->AsParseNodeFnc()->SetNested(NULL != m_currentNodeFunc);
  5922. pnodeFnc->AsParseNodeFnc()->SetStrictMode();
  5923. pnodeFnc->AsParseNodeFnc()->SetDeclaration(TRUE);
  5924. pnodeFnc->AsParseNodeFnc()->SetIsMethod(TRUE);
  5925. pnodeFnc->AsParseNodeFnc()->SetIsClassMember(TRUE);
  5926. pnodeFnc->AsParseNodeFnc()->SetIsClassConstructor(TRUE);
  5927. pnodeFnc->AsParseNodeFnc()->SetIsBaseClassConstructor(!extends);
  5928. pnodeFnc->AsParseNodeFnc()->SetHasNonThisStmt();
  5929. pnodeFnc->AsParseNodeFnc()->SetIsGeneratedDefault(TRUE);
  5930. pnodeFnc->ichLim = m_pscan->IchLimTok();
  5931. pnodeFnc->ichMin = m_pscan->IchMinTok();
  5932. pnodeFnc->AsParseNodeFnc()->cbLim = m_pscan->IecpLimTok();
  5933. pnodeFnc->AsParseNodeFnc()->cbMin = m_pscan->IecpMinTok();
  5934. pnodeFnc->AsParseNodeFnc()->astSize = 0;
  5935. pnodeFnc->AsParseNodeFnc()->lineNumber = m_pscan->LineCur();
  5936. pnodeFnc->AsParseNodeFnc()->functionId = (*m_nextFunctionId);
  5937. pnodeFnc->AsParseNodeFnc()->pid = nullptr;
  5938. pnodeFnc->AsParseNodeFnc()->hint = nullptr;
  5939. pnodeFnc->AsParseNodeFnc()->hintOffset = 0;
  5940. pnodeFnc->AsParseNodeFnc()->hintLength = 0;
  5941. pnodeFnc->AsParseNodeFnc()->isNameIdentifierRef = true;
  5942. pnodeFnc->AsParseNodeFnc()->nestedFuncEscapes = false;
  5943. pnodeFnc->AsParseNodeFnc()->pnodeName = nullptr;
  5944. pnodeFnc->AsParseNodeFnc()->pnodeScopes = nullptr;
  5945. pnodeFnc->AsParseNodeFnc()->pnodeParams = nullptr;
  5946. pnodeFnc->AsParseNodeFnc()->pnodeVars = nullptr;
  5947. pnodeFnc->AsParseNodeFnc()->pnodeBody = nullptr;
  5948. pnodeFnc->AsParseNodeFnc()->nestedCount = 0;
  5949. pnodeFnc->AsParseNodeFnc()->pnodeNext = nullptr;
  5950. pnodeFnc->AsParseNodeFnc()->pnodeRest = nullptr;
  5951. pnodeFnc->AsParseNodeFnc()->deferredStub = nullptr;
  5952. pnodeFnc->AsParseNodeFnc()->funcInfo = nullptr;
  5953. // In order to (re-)defer the default constructor, we need to, for instance, track
  5954. // deferred class expression the way we track function expression, since we lose the part of the source
  5955. // that tells us which we have.
  5956. pnodeFnc->AsParseNodeFnc()->canBeDeferred = false;
  5957. pnodeFnc->AsParseNodeFnc()->isBodyAndParamScopeMerged = true;
  5958. #ifdef DBG
  5959. pnodeFnc->AsParseNodeFnc()->deferredParseNextFunctionId = *(this->m_nextFunctionId);
  5960. #endif
  5961. AppendFunctionToScopeList(true, pnodeFnc);
  5962. if (m_nextFunctionId)
  5963. {
  5964. (*m_nextFunctionId)++;
  5965. }
  5966. // Update the count of functions nested in the current parent.
  5967. if (m_pnestedCount)
  5968. {
  5969. (*m_pnestedCount)++;
  5970. }
  5971. if (m_pscan->IchMinTok() >= m_pscan->IchMinLine())
  5972. {
  5973. // In scenarios involving defer parse IchMinLine() can be incorrect for the first line after defer parse
  5974. pnodeFnc->AsParseNodeFnc()->columnNumber = m_pscan->IchMinTok() - m_pscan->IchMinLine();
  5975. }
  5976. else if (m_currentNodeFunc)
  5977. {
  5978. // For the first line after defer parse, compute the column relative to the column number
  5979. // of the lexically parent function.
  5980. ULONG offsetFromCurrentFunction = m_pscan->IchMinTok() - m_currentNodeFunc->ichMin;
  5981. pnodeFnc->AsParseNodeFnc()->columnNumber = m_currentNodeFunc->AsParseNodeFnc()->columnNumber + offsetFromCurrentFunction;
  5982. }
  5983. else
  5984. {
  5985. // if there is no current function, lets give a default of 0.
  5986. pnodeFnc->AsParseNodeFnc()->columnNumber = 0;
  5987. }
  5988. int32 * pAstSizeSave = m_pCurrentAstSize;
  5989. m_pCurrentAstSize = &(pnodeFnc->AsParseNodeFnc()->astSize);
  5990. // Make this the current function.
  5991. ParseNodePtr pnodeFncSave = m_currentNodeFunc;
  5992. m_currentNodeFunc = pnodeFnc;
  5993. ParseNodePtr argsId = nullptr;
  5994. ParseNodePtr *lastNodeRef = nullptr;
  5995. ParseNodePtr pnodeBlock = StartParseBlock<buildAST>(PnodeBlockType::Parameter, ScopeType_Parameter);
  5996. if (buildAST && extends)
  5997. {
  5998. // constructor(...args) { super(...args); }
  5999. // ^^^^^^^
  6000. ParseNodePtr *const ppnodeVarSave = m_ppnodeVar;
  6001. m_ppnodeVar = &pnodeFnc->AsParseNodeFnc()->pnodeVars;
  6002. IdentPtr pidargs = m_phtbl->PidHashNameLen(_u("args"), sizeof("args") - 1);
  6003. ParseNodePtr pnodeT = CreateVarDeclNode(pidargs, STFormal);
  6004. pnodeT->AsParseNodeVar()->sym->SetIsNonSimpleParameter(true);
  6005. pnodeFnc->AsParseNodeFnc()->pnodeRest = pnodeT;
  6006. PidRefStack *ref = this->PushPidRef(pidargs);
  6007. argsId = CreateNameNode(pidargs, pnodeFnc->ichMin, pnodeFnc->ichLim);
  6008. argsId->AsParseNodePid()->symRef = ref->GetSymRef();
  6009. m_ppnodeVar = ppnodeVarSave;
  6010. }
  6011. ParseNodePtr pnodeInnerBlock = StartParseBlock<buildAST>(PnodeBlockType::Function, ScopeType_FunctionBody);
  6012. pnodeBlock->AsParseNodeBlock()->pnodeScopes = pnodeInnerBlock;
  6013. pnodeFnc->AsParseNodeFnc()->pnodeBodyScope = pnodeInnerBlock;
  6014. pnodeFnc->AsParseNodeFnc()->pnodeScopes = pnodeBlock;
  6015. if (buildAST)
  6016. {
  6017. if (extends)
  6018. {
  6019. // constructor(...args) { super(...args); }
  6020. // ^^^^^^^^^^^^^^^
  6021. Assert(argsId);
  6022. ParseNodePtr spreadArg = CreateUniNode(knopEllipsis, argsId, pnodeFnc->ichMin, pnodeFnc->ichLim);
  6023. ParseNodePtr superRef = ReferenceSpecialName(wellKnownPropertyPids._superConstructor, pnodeFnc->ichMin, pnodeFnc->ichLim, true);
  6024. pnodeFnc->AsParseNodeFnc()->SetHasSuperReference(TRUE);
  6025. ParseNodePtr callNode = CreateSuperCallNode(superRef, spreadArg);
  6026. callNode->AsParseNodeSuperCall()->pnodeThis = ReferenceSpecialName(wellKnownPropertyPids._this, pnodeFnc->ichMin, pnodeFnc->ichLim, true);
  6027. callNode->AsParseNodeSuperCall()->pnodeNewTarget = ReferenceSpecialName(wellKnownPropertyPids._newTarget, pnodeFnc->ichMin, pnodeFnc->ichLim, true);
  6028. callNode->AsParseNodeCall()->spreadArgCount = 1;
  6029. AddToNodeList(&pnodeFnc->AsParseNodeFnc()->pnodeBody, &lastNodeRef, callNode);
  6030. }
  6031. AddToNodeList(&pnodeFnc->AsParseNodeFnc()->pnodeBody, &lastNodeRef, CreateNodeWithScanner<knopEndCode>());
  6032. }
  6033. FinishParseBlock(pnodeInnerBlock);
  6034. CreateSpecialSymbolDeclarations(pnodeFnc);
  6035. FinishParseBlock(pnodeBlock);
  6036. m_currentNodeFunc = pnodeFncSave;
  6037. m_pCurrentAstSize = pAstSizeSave;
  6038. return pnodeFnc;
  6039. }
  6040. template<bool buildAST>
  6041. void Parser::ParseExpressionLambdaBody(ParseNodePtr pnodeLambda)
  6042. {
  6043. ParseNodePtr *lastNodeRef = nullptr;
  6044. // The lambda body is a single expression, the result of which is the return value.
  6045. ParseNodePtr pnodeRet = nullptr;
  6046. if (buildAST)
  6047. {
  6048. pnodeRet = CreateNodeWithScanner<knopReturn>();
  6049. pnodeRet->grfpn |= PNodeFlags::fpnSyntheticNode;
  6050. pnodeLambda->AsParseNodeFnc()->pnodeScopes->AsParseNodeBlock()->pnodeStmt = pnodeRet;
  6051. }
  6052. IdentToken token;
  6053. charcount_t lastRParen = 0;
  6054. // We need to disable deferred parse mode in the scanner because the lambda body doesn't end with a right paren.
  6055. // The scanner needs to create a pid in the case of a string constant token immediately following the lambda body expression.
  6056. // Otherwise, we'll save null for the string constant pid which will AV during ByteCode generation.
  6057. BYTE fScanDeferredFlagsSave = m_pscan->SetDeferredParse(FALSE);
  6058. ParseNodePtr result = ParseExpr<buildAST>(koplAsg, nullptr, TRUE, FALSE, nullptr, nullptr, nullptr, &token, false, nullptr, &lastRParen);
  6059. m_pscan->SetDeferredParseFlags(fScanDeferredFlagsSave);
  6060. this->MarkEscapingRef(result, &token);
  6061. if (buildAST)
  6062. {
  6063. pnodeRet->AsParseNodeReturn()->pnodeExpr = result;
  6064. pnodeRet->ichMin = pnodeRet->AsParseNodeReturn()->pnodeExpr->ichMin;
  6065. pnodeRet->ichLim = pnodeRet->AsParseNodeReturn()->pnodeExpr->ichLim;
  6066. // Pushing a statement node with PushStmt<>() normally does this initialization
  6067. // but do it here manually since we know there is no outer statement node.
  6068. pnodeRet->AsParseNodeStmt()->grfnop = 0;
  6069. pnodeRet->AsParseNodeStmt()->pnodeOuter = nullptr;
  6070. pnodeLambda->ichLim = max(pnodeRet->ichLim, lastRParen);
  6071. pnodeLambda->AsParseNodeFnc()->cbLim = m_pscan->IecpLimTokPrevious();
  6072. pnodeLambda->AsParseNodeFnc()->pnodeScopes->ichLim = pnodeRet->ichLim;
  6073. pnodeLambda->AsParseNodeFnc()->pnodeBody = nullptr;
  6074. AddToNodeList(&pnodeLambda->AsParseNodeFnc()->pnodeBody, &lastNodeRef, pnodeRet);
  6075. // Append an EndCode node.
  6076. ParseNodePtr end = CreateNodeWithScanner<knopEndCode>(pnodeRet->ichLim);
  6077. end->ichLim = end->ichMin; // make end code zero width at the immediate end of lambda body
  6078. AddToNodeList(&pnodeLambda->AsParseNodeFnc()->pnodeBody, &lastNodeRef, end);
  6079. // Lambda's do not have arguments binding
  6080. pnodeLambda->AsParseNodeFnc()->SetHasReferenceableBuiltInArguments(false);
  6081. }
  6082. else
  6083. {
  6084. pnodeLambda->ichLim = max(m_pscan->IchLimTokPrevious(), lastRParen);
  6085. pnodeLambda->AsParseNodeFnc()->cbLim = m_pscan->IecpLimTokPrevious();
  6086. }
  6087. }
  6088. void Parser::CheckStrictFormalParameters()
  6089. {
  6090. if (m_token.tk == tkID)
  6091. {
  6092. // single parameter arrow function case
  6093. IdentPtr pid = m_token.GetIdentifier(m_phtbl);
  6094. CheckStrictModeEvalArgumentsUsage(pid);
  6095. return;
  6096. }
  6097. Assert(m_token.tk == tkLParen);
  6098. m_pscan->ScanForcingPid();
  6099. if (m_token.tk != tkRParen)
  6100. {
  6101. SList<IdentPtr> formals(&m_nodeAllocator);
  6102. for (;;)
  6103. {
  6104. if (m_token.tk != tkID)
  6105. {
  6106. IdentifierExpectedError(m_token);
  6107. }
  6108. IdentPtr pid = m_token.GetIdentifier(m_phtbl);
  6109. CheckStrictModeEvalArgumentsUsage(pid);
  6110. if (formals.Has(pid))
  6111. {
  6112. Error(ERRES5ArgSame, m_pscan->IchMinTok(), m_pscan->IchLimTok());
  6113. }
  6114. else
  6115. {
  6116. formals.Prepend(pid);
  6117. }
  6118. m_pscan->Scan();
  6119. if (m_token.tk == tkAsg && m_scriptContext->GetConfig()->IsES6DefaultArgsEnabled())
  6120. {
  6121. m_pscan->Scan();
  6122. // We can avoid building the AST since we are just checking the default expression.
  6123. ParseNodePtr pnodeInit = ParseExpr<false>(koplCma);
  6124. Assert(pnodeInit == nullptr);
  6125. }
  6126. if (m_token.tk != tkComma)
  6127. {
  6128. break;
  6129. }
  6130. m_pscan->ScanForcingPid();
  6131. if (m_token.tk == tkRParen && m_scriptContext->GetConfig()->IsES7TrailingCommaEnabled())
  6132. {
  6133. break;
  6134. }
  6135. }
  6136. }
  6137. Assert(m_token.tk == tkRParen);
  6138. }
  6139. void Parser::FinishFncNode(ParseNodePtr pnodeFnc)
  6140. {
  6141. AnalysisAssert(pnodeFnc);
  6142. // Finish the AST for a function that was deferred earlier, but which we decided
  6143. // to finish after the fact.
  6144. // We assume that the name(s) and arg(s) have already got parse nodes, so
  6145. // we just have to do the function body.
  6146. // Save the current next function Id, and resume from the old one.
  6147. Js::LocalFunctionId * nextFunctionIdSave = m_nextFunctionId;
  6148. Js::LocalFunctionId tempNextFunctionId = pnodeFnc->AsParseNodeFnc()->functionId + 1;
  6149. this->m_nextFunctionId = &tempNextFunctionId;
  6150. ParseNodePtr pnodeFncSave = m_currentNodeFunc;
  6151. uint *pnestedCountSave = m_pnestedCount;
  6152. int32* pAstSizeSave = m_pCurrentAstSize;
  6153. m_currentNodeFunc = pnodeFnc;
  6154. m_pCurrentAstSize = & (pnodeFnc->AsParseNodeFnc()->astSize);
  6155. pnodeFnc->AsParseNodeFnc()->nestedCount = 0;
  6156. m_pnestedCount = &pnodeFnc->AsParseNodeFnc()->nestedCount;
  6157. bool fLambda = pnodeFnc->AsParseNodeFnc()->IsLambda();
  6158. bool fMethod = pnodeFnc->AsParseNodeFnc()->IsMethod();
  6159. // Cue up the parser to the start of the function body.
  6160. if (pnodeFnc->AsParseNodeFnc()->pnodeName)
  6161. {
  6162. // Skip the name(s).
  6163. m_pscan->SetCurrentCharacter(pnodeFnc->AsParseNodeFnc()->pnodeName->ichLim, pnodeFnc->AsParseNodeFnc()->lineNumber);
  6164. }
  6165. else
  6166. {
  6167. m_pscan->SetCurrentCharacter(pnodeFnc->ichMin, pnodeFnc->AsParseNodeFnc()->lineNumber);
  6168. if (fMethod)
  6169. {
  6170. // Method. Skip identifier name, computed property name, "async", "get", "set", and '*' or '(' characters.
  6171. for (;;)
  6172. {
  6173. m_pscan->Scan();
  6174. // '[' character indicates a computed property name for this method. We should consume it.
  6175. if (m_token.tk == tkLBrack)
  6176. {
  6177. // We don't care what the name expr is.
  6178. m_pscan->Scan();
  6179. ParseExpr<false>();
  6180. Assert(m_token.tk == tkRBrack);
  6181. continue;
  6182. }
  6183. // Quit scanning ahead when we reach a '(' character which opens the arg list.
  6184. if (m_token.tk == tkLParen)
  6185. {
  6186. break;
  6187. }
  6188. }
  6189. }
  6190. else if (pnodeFnc->AsParseNodeFnc()->IsAccessor())
  6191. {
  6192. // Getter/setter. The node text starts with the name, so eat that.
  6193. m_pscan->ScanNoKeywords();
  6194. }
  6195. else if (!fLambda)
  6196. {
  6197. // Anonymous function. Skip "async", "function", and '(' or '*' characters.
  6198. for (;;)
  6199. {
  6200. m_pscan->Scan();
  6201. if (m_token.GetIdentifier(m_phtbl) == wellKnownPropertyPids.async)
  6202. {
  6203. Assert(pnodeFnc->AsParseNodeFnc()->IsAsync());
  6204. continue;
  6205. }
  6206. // Quit scanning ahead when we reach a 'function' keyword which precedes the arg list.
  6207. if (m_token.tk == tkFUNCTION)
  6208. {
  6209. break;
  6210. }
  6211. Assert(m_token.tk == tkLParen || m_token.tk == tkStar);
  6212. }
  6213. }
  6214. }
  6215. // switch scanner to treat 'yield' as keyword in generator functions
  6216. // or as an identifier in non-generator functions
  6217. bool fPreviousYieldIsKeyword = m_pscan->SetYieldIsKeywordRegion(pnodeFnc && pnodeFnc->AsParseNodeFnc()->IsGenerator());
  6218. bool fPreviousAwaitIsKeyword = m_pscan->SetAwaitIsKeywordRegion(pnodeFnc && pnodeFnc->AsParseNodeFnc()->IsAsync());
  6219. // Skip the arg list.
  6220. if (!fMethod)
  6221. {
  6222. // If this is a method, we've already advanced to the '(' token.
  6223. m_pscan->Scan();
  6224. }
  6225. if (m_token.tk == tkStar)
  6226. {
  6227. Assert(pnodeFnc->AsParseNodeFnc()->IsGenerator());
  6228. m_pscan->ScanNoKeywords();
  6229. }
  6230. if (fLambda && m_token.tk == tkID && m_token.GetIdentifier(m_phtbl) == wellKnownPropertyPids.async)
  6231. {
  6232. Assert(pnodeFnc->AsParseNodeFnc()->IsAsync());
  6233. m_pscan->ScanNoKeywords();
  6234. }
  6235. Assert(m_token.tk == tkLParen || (fLambda && m_token.tk == tkID));
  6236. m_pscan->ScanNoKeywords();
  6237. if (m_token.tk != tkRParen && m_token.tk != tkDArrow)
  6238. {
  6239. for (;;)
  6240. {
  6241. if (m_token.tk == tkEllipsis)
  6242. {
  6243. m_pscan->ScanNoKeywords();
  6244. }
  6245. if (m_token.tk == tkID)
  6246. {
  6247. m_pscan->ScanNoKeywords();
  6248. if (m_token.tk == tkAsg)
  6249. {
  6250. // Eat the default expression
  6251. m_pscan->Scan();
  6252. ParseExpr<false>(koplCma);
  6253. }
  6254. }
  6255. else if (IsPossiblePatternStart())
  6256. {
  6257. ParseDestructuredLiteralWithScopeSave(tkLET, false/*isDecl*/, false /*topLevel*/);
  6258. }
  6259. else
  6260. {
  6261. AssertMsg(false, "Unexpected identifier prefix while fast-scanning formals");
  6262. }
  6263. if (m_token.tk != tkComma)
  6264. {
  6265. break;
  6266. }
  6267. m_pscan->ScanNoKeywords();
  6268. if (m_token.tk == tkRParen && m_scriptContext->GetConfig()->IsES7TrailingCommaEnabled())
  6269. {
  6270. break;
  6271. }
  6272. }
  6273. }
  6274. if (m_token.tk == tkRParen)
  6275. {
  6276. m_pscan->Scan();
  6277. }
  6278. if (fLambda && m_token.tk == tkDArrow)
  6279. {
  6280. m_pscan->Scan();
  6281. }
  6282. // Finish the function body.
  6283. {
  6284. // Note that in IE8- modes, surrounding parentheses are considered part of function body. e.g. "( function x(){} )".
  6285. // We lose that context here since we start from middle of function body. So save and restore source range info.
  6286. ParseNodePtr* lastNodeRef = NULL;
  6287. const charcount_t ichLim = pnodeFnc->ichLim;
  6288. const size_t cbLim = pnodeFnc->AsParseNodeFnc()->cbLim;
  6289. this->FinishFncDecl(pnodeFnc, NULL, lastNodeRef, fLambda);
  6290. #if DBG
  6291. // The pnode extent may not match the original extent.
  6292. // We expect this to happen only when there are trailing ")"'s.
  6293. // Consume them and make sure that's all we've got.
  6294. if (pnodeFnc->ichLim != ichLim)
  6295. {
  6296. Assert(pnodeFnc->ichLim < ichLim);
  6297. m_pscan->SetCurrentCharacter(pnodeFnc->ichLim);
  6298. while (m_pscan->IchLimTok() != ichLim)
  6299. {
  6300. m_pscan->ScanNoKeywords();
  6301. Assert(m_token.tk == tkRParen);
  6302. }
  6303. }
  6304. #endif
  6305. pnodeFnc->ichLim = ichLim;
  6306. pnodeFnc->AsParseNodeFnc()->cbLim = cbLim;
  6307. }
  6308. m_currentNodeFunc = pnodeFncSave;
  6309. m_pCurrentAstSize = pAstSizeSave;
  6310. m_pnestedCount = pnestedCountSave;
  6311. Assert(m_pnestedCount);
  6312. Assert(tempNextFunctionId == pnodeFnc->AsParseNodeFnc()->deferredParseNextFunctionId);
  6313. this->m_nextFunctionId = nextFunctionIdSave;
  6314. m_pscan->SetYieldIsKeywordRegion(fPreviousYieldIsKeyword);
  6315. m_pscan->SetAwaitIsKeywordRegion(fPreviousAwaitIsKeyword);
  6316. }
  6317. void Parser::FinishFncDecl(ParseNodePtr pnodeFnc, LPCOLESTR pNameHint, ParseNodePtr *lastNodeRef, bool fLambda, bool skipCurlyBraces)
  6318. {
  6319. LPCOLESTR name = NULL;
  6320. JS_ETW(int32 startAstSize = *m_pCurrentAstSize);
  6321. if (IS_JS_ETW(EventEnabledJSCRIPT_PARSE_METHOD_START()) || PHASE_TRACE1(Js::DeferParsePhase))
  6322. {
  6323. name = GetFunctionName(pnodeFnc, pNameHint);
  6324. m_functionBody = NULL; // for nested functions we do not want to get the name of the top deferred function return name;
  6325. JS_ETW(EventWriteJSCRIPT_PARSE_METHOD_START(m_sourceContextInfo->dwHostSourceContext, GetScriptContext(), pnodeFnc->AsParseNodeFnc()->functionId, 0, m_parseType, name));
  6326. OUTPUT_TRACE(Js::DeferParsePhase, _u("Parsing function (%s) : %s (%d)\n"), GetParseType(), name, pnodeFnc->AsParseNodeFnc()->functionId);
  6327. }
  6328. JS_ETW_INTERNAL(EventWriteJSCRIPT_PARSE_FUNC(GetScriptContext(), pnodeFnc->AsParseNodeFnc()->functionId, /*Undefer*/FALSE));
  6329. // Do the work of creating an AST for a function body.
  6330. // This is common to the un-deferred case and the case in which we un-defer late in the game.
  6331. Assert(pnodeFnc->nop == knopFncDecl);
  6332. if (fLambda && m_token.tk != tkLCurly)
  6333. {
  6334. ParseExpressionLambdaBody<true>(pnodeFnc);
  6335. }
  6336. else
  6337. {
  6338. if (!skipCurlyBraces)
  6339. {
  6340. ChkCurTok(tkLCurly, ERRnoLcurly);
  6341. }
  6342. ParseStmtList<true>(&pnodeFnc->AsParseNodeFnc()->pnodeBody, &lastNodeRef, SM_OnFunctionCode, true /* isSourceElementList */);
  6343. // Append an EndCode node.
  6344. AddToNodeList(&pnodeFnc->AsParseNodeFnc()->pnodeBody, &lastNodeRef, CreateNodeWithScanner<knopEndCode>());
  6345. if (!skipCurlyBraces)
  6346. {
  6347. ChkCurTokNoScan(tkRCurly, ERRnoRcurly);
  6348. }
  6349. pnodeFnc->ichLim = m_pscan->IchLimTok();
  6350. pnodeFnc->AsParseNodeFnc()->cbLim = m_pscan->IecpLimTok();
  6351. }
  6352. #ifdef ENABLE_JS_ETW
  6353. int32 astSize = *m_pCurrentAstSize - startAstSize;
  6354. EventWriteJSCRIPT_PARSE_METHOD_STOP(m_sourceContextInfo->dwHostSourceContext, GetScriptContext(), pnodeFnc->AsParseNodeFnc()->functionId, astSize, m_parseType, name);
  6355. #endif
  6356. }
  6357. ParseNodePtr Parser::CreateSpecialVarDeclNode(ParseNodePtr pnodeFnc, IdentPtr pid)
  6358. {
  6359. ParseNodePtr pnode = InsertVarAtBeginning(pnodeFnc, pid);
  6360. pnode->grfpn |= fpnSpecialSymbol;
  6361. // special symbol must not be global
  6362. pnode->AsParseNodeVar()->sym->SetIsGlobal(false);
  6363. return pnode;
  6364. }
  6365. ParseNodePtr Parser::InsertVarAtBeginning(ParseNodePtr pnodeFnc, IdentPtr pid)
  6366. {
  6367. ParseNodePtr pnode = nullptr;
  6368. if (m_ppnodeVar == &pnodeFnc->AsParseNodeFnc()->pnodeVars)
  6369. {
  6370. pnode = CreateVarDeclNode(pid, STVariable, true, pnodeFnc);
  6371. }
  6372. else
  6373. {
  6374. ParseNodePtr *const ppnodeVarSave = m_ppnodeVar;
  6375. m_ppnodeVar = &pnodeFnc->AsParseNodeFnc()->pnodeVars;
  6376. pnode = CreateVarDeclNode(pid, STVariable, true, pnodeFnc);
  6377. m_ppnodeVar = ppnodeVarSave;
  6378. }
  6379. Assert(pnode);
  6380. return pnode;
  6381. }
  6382. ParseNodePtr Parser::AddArgumentsNodeToVars(ParseNodePtr pnodeFnc)
  6383. {
  6384. Assert(!GetCurrentFunctionNode()->AsParseNodeFnc()->IsLambda());
  6385. ParseNodePtr argNode = InsertVarAtBeginning(pnodeFnc, wellKnownPropertyPids.arguments);
  6386. argNode->grfpn |= PNodeFlags::fpnArguments; // Flag this as the built-in arguments node
  6387. return argNode;
  6388. }
  6389. void Parser::UpdateArgumentsNode(ParseNodePtr pnodeFnc, ParseNodePtr argNode)
  6390. {
  6391. if ((pnodeFnc->grfpn & PNodeFlags::fpnArguments_overriddenInParam) || pnodeFnc->AsParseNodeFnc()->IsLambda())
  6392. {
  6393. // There is a parameter named arguments. So we don't have to create the built-in arguments.
  6394. pnodeFnc->AsParseNodeFnc()->SetHasReferenceableBuiltInArguments(false);
  6395. }
  6396. else if ((pnodeFnc->grfpn & PNodeFlags::fpnArguments_overriddenByDecl) && pnodeFnc->AsParseNodeFnc()->IsBodyAndParamScopeMerged())
  6397. {
  6398. // In non-split scope case there is a var or function definition named arguments in the body
  6399. pnodeFnc->AsParseNodeFnc()->SetHasReferenceableBuiltInArguments(false);
  6400. }
  6401. else
  6402. {
  6403. pnodeFnc->AsParseNodeFnc()->SetHasReferenceableBuiltInArguments(true);
  6404. Assert(argNode);
  6405. }
  6406. if (argNode != nullptr && !argNode->AsParseNodeVar()->sym->IsArguments())
  6407. {
  6408. // A duplicate definition has updated the declaration node. Need to reset it back.
  6409. argNode->grfpn |= PNodeFlags::fpnArguments;
  6410. argNode->AsParseNodeVar()->sym->SetDecl(argNode);
  6411. }
  6412. }
  6413. LPCOLESTR Parser::GetFunctionName(ParseNodePtr pnodeFnc, LPCOLESTR pNameHint)
  6414. {
  6415. LPCOLESTR name = nullptr;
  6416. if(pnodeFnc->AsParseNodeFnc()->pnodeName != nullptr && knopVarDecl == pnodeFnc->AsParseNodeFnc()->pnodeName->nop)
  6417. {
  6418. name = pnodeFnc->AsParseNodeFnc()->pnodeName->AsParseNodeVar()->pid->Psz();
  6419. }
  6420. if(name == nullptr && pNameHint != nullptr)
  6421. {
  6422. name = pNameHint;
  6423. }
  6424. if(name == nullptr && m_functionBody != nullptr)
  6425. {
  6426. name = m_functionBody->GetExternalDisplayName();
  6427. }
  6428. else if(name == nullptr)
  6429. {
  6430. name = Js::Constants::AnonymousFunction;
  6431. }
  6432. return name;
  6433. }
  6434. IdentPtr Parser::ParseClassPropertyName(IdentPtr * pidHint)
  6435. {
  6436. if (m_token.tk == tkID || m_token.tk == tkStrCon || m_token.IsReservedWord())
  6437. {
  6438. IdentPtr pid;
  6439. if (m_token.tk == tkStrCon)
  6440. {
  6441. if (m_pscan->IsOctOrLeadingZeroOnLastTKNumber())
  6442. {
  6443. Error(ERRES5NoOctal);
  6444. }
  6445. pid = m_token.GetStr();
  6446. }
  6447. else
  6448. {
  6449. pid = m_token.GetIdentifier(m_phtbl);
  6450. }
  6451. *pidHint = pid;
  6452. return pid;
  6453. }
  6454. else if (m_token.tk == tkIntCon)
  6455. {
  6456. if (m_pscan->IsOctOrLeadingZeroOnLastTKNumber())
  6457. {
  6458. Error(ERRES5NoOctal);
  6459. }
  6460. return m_pscan->PidFromLong(m_token.GetLong());
  6461. }
  6462. else if (m_token.tk == tkFltCon)
  6463. {
  6464. if (m_pscan->IsOctOrLeadingZeroOnLastTKNumber())
  6465. {
  6466. Error(ERRES5NoOctal);
  6467. }
  6468. return m_pscan->PidFromDbl(m_token.GetDouble());
  6469. }
  6470. Error(ERRnoMemberIdent);
  6471. }
  6472. LPCOLESTR Parser::ConstructFinalHintNode(IdentPtr pClassName, IdentPtr pMemberName, IdentPtr pGetSet, bool isStatic, uint32* nameLength, uint32* pShortNameOffset, bool isComputedName, LPCOLESTR pMemberNameHint)
  6473. {
  6474. if ((pMemberName == nullptr && !isComputedName) ||
  6475. (pMemberNameHint == nullptr && isComputedName) ||
  6476. !CONFIG_FLAG(UseFullName))
  6477. {
  6478. return nullptr;
  6479. }
  6480. LPCOLESTR pFinalName = isComputedName? pMemberNameHint : pMemberName->Psz();
  6481. uint32 fullNameHintLength = (uint32)wcslen(pFinalName);
  6482. uint32 shortNameOffset = 0;
  6483. if (!isStatic)
  6484. {
  6485. // Add prototype.
  6486. pFinalName = AppendNameHints(wellKnownPropertyPids.prototype, pFinalName, &fullNameHintLength, &shortNameOffset);
  6487. }
  6488. if (pClassName)
  6489. {
  6490. uint32 classNameOffset = 0;
  6491. pFinalName = AppendNameHints(pClassName, pFinalName, &fullNameHintLength, &classNameOffset);
  6492. shortNameOffset += classNameOffset;
  6493. }
  6494. if (pGetSet)
  6495. {
  6496. // displays as get/set prototype.funcname
  6497. uint32 getSetOffset = 0;
  6498. pFinalName = AppendNameHints(pGetSet, pFinalName, &fullNameHintLength, &getSetOffset, true);
  6499. shortNameOffset += getSetOffset;
  6500. }
  6501. *nameLength = fullNameHintLength;
  6502. *pShortNameOffset = shortNameOffset;
  6503. return pFinalName;
  6504. }
  6505. class AutoParsingSuperRestrictionStateRestorer
  6506. {
  6507. public:
  6508. AutoParsingSuperRestrictionStateRestorer(Parser* parser) : m_parser(parser)
  6509. {
  6510. AssertMsg(this->m_parser != nullptr, "This just should not happen");
  6511. this->m_originalParsingSuperRestrictionState = this->m_parser->m_parsingSuperRestrictionState;
  6512. }
  6513. ~AutoParsingSuperRestrictionStateRestorer()
  6514. {
  6515. AssertMsg(this->m_parser != nullptr, "This just should not happen");
  6516. this->m_parser->m_parsingSuperRestrictionState = m_originalParsingSuperRestrictionState;
  6517. }
  6518. private:
  6519. Parser* m_parser;
  6520. int m_originalParsingSuperRestrictionState;
  6521. };
  6522. template<bool buildAST>
  6523. ParseNodePtr Parser::ParseClassDecl(BOOL isDeclaration, LPCOLESTR pNameHint, uint32 *pHintLength, uint32 *pShortNameOffset)
  6524. {
  6525. bool hasConstructor = false;
  6526. bool hasExtends = false;
  6527. IdentPtr name = nullptr;
  6528. ParseNodePtr pnodeName = nullptr;
  6529. ParseNodePtr pnodeConstructor = nullptr;
  6530. ParseNodePtr pnodeExtends = nullptr;
  6531. ParseNodePtr pnodeMembers = nullptr;
  6532. ParseNodePtr *lastMemberNodeRef = nullptr;
  6533. ParseNodePtr pnodeStaticMembers = nullptr;
  6534. ParseNodePtr *lastStaticMemberNodeRef = nullptr;
  6535. uint32 nameHintLength = pHintLength ? *pHintLength : 0;
  6536. uint32 nameHintOffset = pShortNameOffset ? *pShortNameOffset : 0;
  6537. ArenaAllocator tempAllocator(_u("ClassMemberNames"), m_nodeAllocator.GetPageAllocator(), Parser::OutOfMemory);
  6538. size_t cbMinConstructor = 0;
  6539. ParseNodePtr pnodeClass = nullptr;
  6540. if (buildAST)
  6541. {
  6542. pnodeClass = CreateNode(knopClassDecl);
  6543. CHAKRATEL_LANGSTATS_INC_LANGFEATURECOUNT(ES6, Class, m_scriptContext);
  6544. cbMinConstructor = m_pscan->IecpMinTok();
  6545. }
  6546. m_pscan->Scan();
  6547. if (m_token.tk == tkID)
  6548. {
  6549. name = m_token.GetIdentifier(m_phtbl);
  6550. m_pscan->Scan();
  6551. }
  6552. else if (isDeclaration)
  6553. {
  6554. IdentifierExpectedError(m_token);
  6555. }
  6556. if (isDeclaration && name == wellKnownPropertyPids.arguments && GetCurrentBlockInfo()->pnodeBlock->AsParseNodeBlock()->blockType == Function)
  6557. {
  6558. GetCurrentFunctionNode()->grfpn |= PNodeFlags::fpnArguments_overriddenByDecl;
  6559. }
  6560. BOOL strictSave = m_fUseStrictMode;
  6561. m_fUseStrictMode = TRUE;
  6562. ParseNodePtr pnodeDeclName = nullptr;
  6563. if (isDeclaration)
  6564. {
  6565. pnodeDeclName = CreateBlockScopedDeclNode(name, knopLetDecl);
  6566. }
  6567. ParseNodePtr *ppnodeScopeSave = nullptr;
  6568. ParseNodePtr *ppnodeExprScopeSave = nullptr;
  6569. ParseNodePtr pnodeBlock = StartParseBlock<buildAST>(PnodeBlockType::Regular, ScopeType_Block);
  6570. if (buildAST)
  6571. {
  6572. PushFuncBlockScope(pnodeBlock, &ppnodeScopeSave, &ppnodeExprScopeSave);
  6573. pnodeClass->AsParseNodeClass()->pnodeBlock = pnodeBlock;
  6574. }
  6575. if (name)
  6576. {
  6577. pnodeName = CreateBlockScopedDeclNode(name, knopConstDecl);
  6578. }
  6579. if (m_token.tk == tkEXTENDS)
  6580. {
  6581. m_pscan->Scan();
  6582. pnodeExtends = ParseTerm<buildAST>();
  6583. hasExtends = true;
  6584. }
  6585. if (m_token.tk != tkLCurly)
  6586. {
  6587. Error(ERRnoLcurly);
  6588. }
  6589. OUTPUT_TRACE_DEBUGONLY(Js::ES6VerboseFlag, _u("Parsing class (%s) : %s\n"), GetParseType(), name ? name->Psz() : _u("anonymous class"));
  6590. RestorePoint beginClass;
  6591. m_pscan->Capture(&beginClass);
  6592. m_pscan->ScanForcingPid();
  6593. IdentPtr pClassNamePid = pnodeName ? pnodeName->AsParseNodeVar()->pid : nullptr;
  6594. for (;;)
  6595. {
  6596. if (m_token.tk == tkSColon)
  6597. {
  6598. m_pscan->ScanForcingPid();
  6599. continue;
  6600. }
  6601. if (m_token.tk == tkRCurly)
  6602. {
  6603. break;
  6604. }
  6605. bool isStatic = false;
  6606. if (m_token.tk == tkSTATIC)
  6607. {
  6608. // 'static' can be used as an IdentifierName here, even in strict mode code. We need to see the next token before we know
  6609. // if this is being used as a keyword. This is similar to the way we treat 'let' in some cases.
  6610. // See https://tc39.github.io/ecma262/#sec-keywords for more info.
  6611. RestorePoint beginStatic;
  6612. m_pscan->Capture(&beginStatic);
  6613. m_pscan->ScanForcingPid();
  6614. if (m_token.tk == tkLParen)
  6615. {
  6616. m_pscan->SeekTo(beginStatic);
  6617. }
  6618. else
  6619. {
  6620. isStatic = true;
  6621. }
  6622. }
  6623. ushort fncDeclFlags = fFncNoName | fFncMethod | fFncClassMember;
  6624. charcount_t ichMin = 0;
  6625. size_t iecpMin = 0;
  6626. ParseNodePtr pnodeMemberName = nullptr;
  6627. IdentPtr pidHint = nullptr;
  6628. IdentPtr memberPid = nullptr;
  6629. LPCOLESTR pMemberNameHint = nullptr;
  6630. uint32 memberNameHintLength = 0;
  6631. uint32 memberNameOffset = 0;
  6632. bool isComputedName = false;
  6633. bool isAsyncMethod = false;
  6634. if (m_token.tk == tkID && m_token.GetIdentifier(m_phtbl) == wellKnownPropertyPids.async && m_scriptContext->GetConfig()->IsES7AsyncAndAwaitEnabled())
  6635. {
  6636. RestorePoint parsedAsync;
  6637. m_pscan->Capture(&parsedAsync);
  6638. ichMin = m_pscan->IchMinTok();
  6639. iecpMin = m_pscan->IecpMinTok();
  6640. m_pscan->Scan();
  6641. if (m_token.tk == tkLParen || m_pscan->FHadNewLine())
  6642. {
  6643. m_pscan->SeekTo(parsedAsync);
  6644. }
  6645. else
  6646. {
  6647. isAsyncMethod = true;
  6648. }
  6649. }
  6650. bool isGenerator = m_scriptContext->GetConfig()->IsES6GeneratorsEnabled() &&
  6651. m_token.tk == tkStar;
  6652. if (isGenerator)
  6653. {
  6654. fncDeclFlags |= fFncGenerator;
  6655. m_pscan->ScanForcingPid();
  6656. }
  6657. if (m_token.tk == tkLBrack && m_scriptContext->GetConfig()->IsES6ObjectLiteralsEnabled())
  6658. {
  6659. // Computed member name: [expr] () { }
  6660. LPCOLESTR emptyHint = nullptr;
  6661. ParseComputedName<buildAST>(&pnodeMemberName, &emptyHint, &pMemberNameHint, &memberNameHintLength, &memberNameOffset);
  6662. isComputedName = true;
  6663. }
  6664. else // not computed name
  6665. {
  6666. memberPid = this->ParseClassPropertyName(&pidHint);
  6667. if (pidHint)
  6668. {
  6669. pMemberNameHint = pidHint->Psz();
  6670. memberNameHintLength = pidHint->Cch();
  6671. }
  6672. }
  6673. if (buildAST && memberPid)
  6674. {
  6675. pnodeMemberName = CreateStrNodeWithScanner(memberPid);
  6676. }
  6677. if (!isStatic && memberPid == wellKnownPropertyPids.constructor)
  6678. {
  6679. if (hasConstructor || isAsyncMethod)
  6680. {
  6681. Error(ERRsyntax);
  6682. }
  6683. hasConstructor = true;
  6684. LPCOLESTR pConstructorName = nullptr;
  6685. uint32 constructorNameLength = 0;
  6686. uint32 constructorShortNameHintOffset = 0;
  6687. if (pnodeName && pnodeName->AsParseNodeVar()->pid)
  6688. {
  6689. pConstructorName = pnodeName->AsParseNodeVar()->pid->Psz();
  6690. constructorNameLength = pnodeName->AsParseNodeVar()->pid->Cch();
  6691. }
  6692. else
  6693. {
  6694. pConstructorName = pNameHint;
  6695. constructorNameLength = nameHintLength;
  6696. constructorShortNameHintOffset = nameHintOffset;
  6697. }
  6698. {
  6699. AutoParsingSuperRestrictionStateRestorer restorer(this);
  6700. this->m_parsingSuperRestrictionState = hasExtends ? ParsingSuperRestrictionState_SuperCallAndPropertyAllowed : ParsingSuperRestrictionState_SuperPropertyAllowed;
  6701. // Add the class constructor flag and base class constructor flag if pnodeExtends is nullptr
  6702. fncDeclFlags |= fFncClassConstructor | (pnodeExtends == nullptr ? fFncBaseClassConstructor : kFunctionNone);
  6703. pnodeConstructor = ParseFncDecl<buildAST>(fncDeclFlags, pConstructorName, /* needsPIDOnRCurlyScan */ true, /* resetParsingSuperRestrictionState = */false);
  6704. }
  6705. if (pnodeConstructor->AsParseNodeFnc()->IsGenerator())
  6706. {
  6707. Error(ERRConstructorCannotBeGenerator);
  6708. }
  6709. Assert(constructorNameLength >= constructorShortNameHintOffset);
  6710. // The constructor function will get the same name as class.
  6711. pnodeConstructor->AsParseNodeFnc()->hint = pConstructorName;
  6712. pnodeConstructor->AsParseNodeFnc()->hintLength = constructorNameLength;
  6713. pnodeConstructor->AsParseNodeFnc()->hintOffset = constructorShortNameHintOffset;
  6714. pnodeConstructor->AsParseNodeFnc()->pid = pnodeName && pnodeName->AsParseNodeVar()->pid ? pnodeName->AsParseNodeVar()->pid : wellKnownPropertyPids.constructor;
  6715. pnodeConstructor->AsParseNodeFnc()->SetHasNonThisStmt();
  6716. }
  6717. else
  6718. {
  6719. ParseNodePtr pnodeMember = nullptr;
  6720. bool isMemberNamedGetOrSet = false;
  6721. RestorePoint beginMethodName;
  6722. m_pscan->Capture(&beginMethodName);
  6723. if (memberPid == wellKnownPropertyPids.get || memberPid == wellKnownPropertyPids.set)
  6724. {
  6725. m_pscan->ScanForcingPid();
  6726. }
  6727. if (m_token.tk == tkLParen)
  6728. {
  6729. m_pscan->SeekTo(beginMethodName);
  6730. isMemberNamedGetOrSet = true;
  6731. }
  6732. if ((memberPid == wellKnownPropertyPids.get || memberPid == wellKnownPropertyPids.set) && !isMemberNamedGetOrSet)
  6733. {
  6734. bool isGetter = (memberPid == wellKnownPropertyPids.get);
  6735. if (m_token.tk == tkLBrack && m_scriptContext->GetConfig()->IsES6ObjectLiteralsEnabled())
  6736. {
  6737. // Computed get/set member name: get|set [expr] () { }
  6738. LPCOLESTR emptyHint = nullptr;
  6739. ParseComputedName<buildAST>(&pnodeMemberName, &emptyHint, &pMemberNameHint, &memberNameHintLength, &memberNameOffset);
  6740. isComputedName = true;
  6741. }
  6742. else // not computed name
  6743. {
  6744. memberPid = this->ParseClassPropertyName(&pidHint);
  6745. }
  6746. if ((isStatic ? (memberPid == wellKnownPropertyPids.prototype) : (memberPid == wellKnownPropertyPids.constructor)) || isAsyncMethod)
  6747. {
  6748. Error(ERRsyntax);
  6749. }
  6750. if (buildAST && memberPid && !isComputedName)
  6751. {
  6752. pnodeMemberName = CreateStrNodeWithScanner(memberPid);
  6753. }
  6754. ParseNodePtr pnodeFnc = nullptr;
  6755. {
  6756. AutoParsingSuperRestrictionStateRestorer restorer(this);
  6757. this->m_parsingSuperRestrictionState = ParsingSuperRestrictionState_SuperPropertyAllowed;
  6758. pnodeFnc = ParseFncDecl<buildAST>(fncDeclFlags | (isGetter ? fFncNoArg : fFncOneArg),
  6759. pidHint ? pidHint->Psz() : nullptr, /* needsPIDOnRCurlyScan */ true,
  6760. /* resetParsingSuperRestrictionState */false);
  6761. }
  6762. pnodeFnc->AsParseNodeFnc()->SetIsStaticMember(isStatic);
  6763. if (buildAST)
  6764. {
  6765. pnodeFnc->AsParseNodeFnc()->SetIsAccessor();
  6766. pnodeMember = CreateBinNode(isGetter ? knopGetMember : knopSetMember, pnodeMemberName, pnodeFnc);
  6767. pMemberNameHint = ConstructFinalHintNode(pClassNamePid, pidHint,
  6768. isGetter ? wellKnownPropertyPids.get : wellKnownPropertyPids.set, isStatic,
  6769. &memberNameHintLength, &memberNameOffset, isComputedName, pMemberNameHint);
  6770. }
  6771. }
  6772. else
  6773. {
  6774. if (isStatic && (memberPid == wellKnownPropertyPids.prototype))
  6775. {
  6776. Error(ERRsyntax);
  6777. }
  6778. ParseNodePtr pnodeFnc = nullptr;
  6779. {
  6780. AutoParsingSuperRestrictionStateRestorer restorer(this);
  6781. this->m_parsingSuperRestrictionState = ParsingSuperRestrictionState_SuperPropertyAllowed;
  6782. if (isAsyncMethod)
  6783. {
  6784. fncDeclFlags |= fFncAsync;
  6785. }
  6786. pnodeFnc = ParseFncDecl<buildAST>(fncDeclFlags, pidHint ? pidHint->Psz() : nullptr, /* needsPIDOnRCurlyScan */ true, /* resetParsingSuperRestrictionState */false);
  6787. if (isAsyncMethod)
  6788. {
  6789. pnodeFnc->AsParseNodeFnc()->cbMin = iecpMin;
  6790. pnodeFnc->ichMin = ichMin;
  6791. }
  6792. }
  6793. pnodeFnc->AsParseNodeFnc()->SetIsStaticMember(isStatic);
  6794. if (buildAST)
  6795. {
  6796. pnodeMember = CreateBinNode(knopMember, pnodeMemberName, pnodeFnc);
  6797. pMemberNameHint = ConstructFinalHintNode(pClassNamePid, pidHint, nullptr /*pgetset*/, isStatic, &memberNameHintLength, &memberNameOffset, isComputedName, pMemberNameHint);
  6798. }
  6799. }
  6800. if (buildAST)
  6801. {
  6802. Assert(memberNameHintLength >= memberNameOffset);
  6803. pnodeMember->AsParseNodeBin()->pnode2->AsParseNodeFnc()->hint = pMemberNameHint; // Fully qualified name
  6804. pnodeMember->AsParseNodeBin()->pnode2->AsParseNodeFnc()->hintLength = memberNameHintLength;
  6805. pnodeMember->AsParseNodeBin()->pnode2->AsParseNodeFnc()->hintOffset = memberNameOffset;
  6806. pnodeMember->AsParseNodeBin()->pnode2->AsParseNodeFnc()->pid = memberPid; // Short name
  6807. AddToNodeList(isStatic ? &pnodeStaticMembers : &pnodeMembers, isStatic ? &lastStaticMemberNodeRef : &lastMemberNodeRef, pnodeMember);
  6808. }
  6809. }
  6810. }
  6811. size_t cbLimConstructor = 0;
  6812. if (buildAST)
  6813. {
  6814. pnodeClass->ichLim = m_pscan->IchLimTok();
  6815. cbLimConstructor = m_pscan->IecpLimTok();
  6816. }
  6817. if (!hasConstructor)
  6818. {
  6819. OUTPUT_TRACE_DEBUGONLY(Js::ES6VerboseFlag, _u("Generating constructor (%s) : %s\n"), GetParseType(), name ? name->Psz() : _u("anonymous class"));
  6820. RestorePoint endClass;
  6821. m_pscan->Capture(&endClass);
  6822. m_pscan->SeekTo(beginClass);
  6823. pnodeConstructor = GenerateEmptyConstructor<buildAST>(pnodeExtends != nullptr);
  6824. if (buildAST)
  6825. {
  6826. if (pClassNamePid)
  6827. {
  6828. pnodeConstructor->AsParseNodeFnc()->hint = pClassNamePid->Psz();
  6829. pnodeConstructor->AsParseNodeFnc()->hintLength = pClassNamePid->Cch();
  6830. pnodeConstructor->AsParseNodeFnc()->hintOffset = 0;
  6831. }
  6832. else
  6833. {
  6834. Assert(nameHintLength >= nameHintOffset);
  6835. pnodeConstructor->AsParseNodeFnc()->hint = pNameHint;
  6836. pnodeConstructor->AsParseNodeFnc()->hintLength = nameHintLength;
  6837. pnodeConstructor->AsParseNodeFnc()->hintOffset = nameHintOffset;
  6838. }
  6839. pnodeConstructor->AsParseNodeFnc()->pid = pClassNamePid;
  6840. }
  6841. m_pscan->SeekTo(endClass);
  6842. }
  6843. if (buildAST)
  6844. {
  6845. pnodeConstructor->AsParseNodeFnc()->cbMin = cbMinConstructor;
  6846. pnodeConstructor->AsParseNodeFnc()->cbLim = cbLimConstructor;
  6847. pnodeConstructor->ichMin = pnodeClass->ichMin;
  6848. pnodeConstructor->ichLim = pnodeClass->ichLim;
  6849. PopFuncBlockScope(ppnodeScopeSave, ppnodeExprScopeSave);
  6850. pnodeClass->AsParseNodeClass()->pnodeDeclName = pnodeDeclName;
  6851. pnodeClass->AsParseNodeClass()->pnodeName = pnodeName;
  6852. pnodeClass->AsParseNodeClass()->pnodeConstructor = pnodeConstructor;
  6853. pnodeClass->AsParseNodeClass()->pnodeExtends = pnodeExtends;
  6854. pnodeClass->AsParseNodeClass()->pnodeMembers = pnodeMembers;
  6855. pnodeClass->AsParseNodeClass()->pnodeStaticMembers = pnodeStaticMembers;
  6856. pnodeClass->AsParseNodeClass()->isDefaultModuleExport = false;
  6857. }
  6858. FinishParseBlock(pnodeBlock);
  6859. m_fUseStrictMode = strictSave;
  6860. m_pscan->Scan();
  6861. return pnodeClass;
  6862. }
  6863. template<bool buildAST>
  6864. ParseNodePtr Parser::ParseStringTemplateDecl(ParseNodePtr pnodeTagFnc)
  6865. {
  6866. ParseNodePtr pnodeStringLiterals = nullptr;
  6867. ParseNodePtr* lastStringLiteralNodeRef = nullptr;
  6868. ParseNodePtr pnodeRawStringLiterals = nullptr;
  6869. ParseNodePtr* lastRawStringLiteralNodeRef = nullptr;
  6870. ParseNodePtr pnodeSubstitutionExpressions = nullptr;
  6871. ParseNodePtr* lastSubstitutionExpressionNodeRef = nullptr;
  6872. ParseNodePtr pnodeTagFncArgs = nullptr;
  6873. ParseNodePtr* lastTagFncArgNodeRef = nullptr;
  6874. ParseNodePtr stringLiteral = nullptr;
  6875. ParseNodePtr stringLiteralRaw = nullptr;
  6876. ParseNodePtr pnodeStringTemplate = nullptr;
  6877. bool templateClosed = false;
  6878. const bool isTagged = pnodeTagFnc != nullptr;
  6879. uint16 stringConstantCount = 0;
  6880. charcount_t ichMin = 0;
  6881. Assert(m_token.tk == tkStrTmplBasic || m_token.tk == tkStrTmplBegin);
  6882. if (buildAST)
  6883. {
  6884. pnodeStringTemplate = CreateNode(knopStrTemplate);
  6885. pnodeStringTemplate->AsParseNodeStrTemplate()->countStringLiterals = 0;
  6886. pnodeStringTemplate->AsParseNodeStrTemplate()->isTaggedTemplate = isTagged ? TRUE : FALSE;
  6887. // If this is a tagged string template, we need to start building the arg list for the call
  6888. if (isTagged)
  6889. {
  6890. ichMin = pnodeTagFnc->ichMin;
  6891. AddToNodeListEscapedUse(&pnodeTagFncArgs, &lastTagFncArgNodeRef, pnodeStringTemplate);
  6892. }
  6893. }
  6894. CHAKRATEL_LANGSTATS_INC_LANGFEATURECOUNT(ES6, StringTemplates, m_scriptContext);
  6895. OUTPUT_TRACE_DEBUGONLY(
  6896. Js::StringTemplateParsePhase,
  6897. _u("Starting to parse a string template (%s)...\n\tis tagged = %s\n"),
  6898. GetParseType(),
  6899. isTagged ? _u("true") : _u("false (Raw and cooked strings will not differ!)"));
  6900. // String template grammar
  6901. // `...` Simple string template
  6902. // `...${ String template beginning
  6903. // }...${ String template middle
  6904. // }...` String template end
  6905. while (!templateClosed)
  6906. {
  6907. // First, extract the string constant part - we always have one
  6908. if (IsStrictMode() && m_pscan->IsOctOrLeadingZeroOnLastTKNumber())
  6909. {
  6910. Error(ERRES5NoOctal);
  6911. }
  6912. // We are not able to pass more than a ushort worth of arguments to the tag
  6913. // so use that as a logical limit on the number of string constant pieces.
  6914. if (stringConstantCount >= Js::Constants::MaxAllowedArgs)
  6915. {
  6916. Error(ERRTooManyArgs);
  6917. }
  6918. // Keep track of the string literal count (must be the same for raw strings)
  6919. // We use this in code gen so we don't need to count the string literals list
  6920. stringConstantCount++;
  6921. // If we are not creating parse nodes, there is no need to create strings
  6922. if (buildAST)
  6923. {
  6924. stringLiteral = CreateStrNodeWithScanner(m_token.GetStr());
  6925. AddToNodeList(&pnodeStringLiterals, &lastStringLiteralNodeRef, stringLiteral);
  6926. // We only need to collect a raw string when we are going to pass the string template to a tag
  6927. if (isTagged)
  6928. {
  6929. // Make the scanner create a PID for the raw string constant for the preceding scan
  6930. IdentPtr pid = m_pscan->GetSecondaryBufferAsPid();
  6931. stringLiteralRaw = CreateStrNodeWithScanner(pid);
  6932. // Should have gotten a raw string literal above
  6933. AddToNodeList(&pnodeRawStringLiterals, &lastRawStringLiteralNodeRef, stringLiteralRaw);
  6934. }
  6935. else
  6936. {
  6937. #if DBG
  6938. // Assign the raw string for debug tracing below
  6939. stringLiteralRaw = stringLiteral;
  6940. #endif
  6941. }
  6942. OUTPUT_TRACE_DEBUGONLY(
  6943. Js::StringTemplateParsePhase,
  6944. _u("Parsed string constant: \n\tcooked = \"%s\" \n\traw = \"%s\" \n\tdiffer = %d\n"),
  6945. stringLiteral->AsParseNodePid()->pid->Psz(),
  6946. stringLiteralRaw->AsParseNodePid()->pid->Psz(),
  6947. stringLiteral->AsParseNodePid()->pid->Psz() == stringLiteralRaw->AsParseNodePid()->pid->Psz() ? 0 : 1);
  6948. }
  6949. switch (m_token.tk)
  6950. {
  6951. case tkStrTmplEnd:
  6952. case tkStrTmplBasic:
  6953. // We do not need to parse an expression for either the end or basic string template tokens
  6954. templateClosed = true;
  6955. break;
  6956. case tkStrTmplBegin:
  6957. case tkStrTmplMid:
  6958. {
  6959. // In the middle or begin string template token case, we need to parse an expression next
  6960. m_pscan->Scan();
  6961. // Parse the contents of the curly braces as an expression
  6962. ParseNodePtr expression = ParseExpr<buildAST>(0);
  6963. // After parsing expression, scan should leave us with an RCurly token.
  6964. // Use the NoScan version so we do not automatically perform a scan - we need to
  6965. // set the scan state before next scan but we don't want to set that state if
  6966. // the token is not as expected since we'll error in that case.
  6967. ChkCurTokNoScan(tkRCurly, ERRnoRcurly);
  6968. // Notify the scanner that it should scan for a middle or end string template token
  6969. m_pscan->SetScanState(Scanner_t::ScanState::ScanStateStringTemplateMiddleOrEnd);
  6970. m_pscan->Scan();
  6971. if (buildAST)
  6972. {
  6973. // If we are going to call the tag function, add this expression into the list of args
  6974. if (isTagged)
  6975. {
  6976. AddToNodeListEscapedUse(&pnodeTagFncArgs, &lastTagFncArgNodeRef, expression);
  6977. }
  6978. else
  6979. {
  6980. // Otherwise add it to the substitution expression list
  6981. // TODO: Store the arguments and substitution expressions in a single list?
  6982. AddToNodeList(&pnodeSubstitutionExpressions, &lastSubstitutionExpressionNodeRef, expression);
  6983. }
  6984. }
  6985. if (!(m_token.tk == tkStrTmplMid || m_token.tk == tkStrTmplEnd))
  6986. {
  6987. // Scan with ScanState ScanStateStringTemplateMiddleOrEnd should only return
  6988. // tkStrTmpMid/End unless it is EOF or tkScanError
  6989. Assert(m_token.tk == tkEOF || m_token.tk == tkScanError);
  6990. Error(ERRsyntax);
  6991. }
  6992. OUTPUT_TRACE_DEBUGONLY(Js::StringTemplateParsePhase, _u("Parsed expression\n"));
  6993. }
  6994. break;
  6995. default:
  6996. Assert(false);
  6997. break;
  6998. }
  6999. }
  7000. if (buildAST)
  7001. {
  7002. pnodeStringTemplate->AsParseNodeStrTemplate()->pnodeStringLiterals = pnodeStringLiterals;
  7003. pnodeStringTemplate->AsParseNodeStrTemplate()->pnodeStringRawLiterals = pnodeRawStringLiterals;
  7004. pnodeStringTemplate->AsParseNodeStrTemplate()->pnodeSubstitutionExpressions = pnodeSubstitutionExpressions;
  7005. pnodeStringTemplate->AsParseNodeStrTemplate()->countStringLiterals = stringConstantCount;
  7006. // We should still have the last string literal.
  7007. // Use the char offset of the end of that constant as the end of the string template.
  7008. pnodeStringTemplate->ichLim = stringLiteral->ichLim;
  7009. // If this is a tagged template, we now have the argument list and can construct a call node
  7010. if (isTagged)
  7011. {
  7012. // Return the call node here and let the byte code generator Emit the string template automagically
  7013. pnodeStringTemplate = CreateCallNode(knopCall, pnodeTagFnc, pnodeTagFncArgs, ichMin, pnodeStringTemplate->ichLim);
  7014. // We need to set the arg count explicitly
  7015. pnodeStringTemplate->AsParseNodeCall()->argCount = stringConstantCount;
  7016. pnodeStringTemplate->AsParseNodeCall()->hasDestructuring = m_hasDestructuringPattern;
  7017. }
  7018. }
  7019. m_pscan->Scan();
  7020. return pnodeStringTemplate;
  7021. }
  7022. LPCOLESTR Parser::FormatPropertyString(LPCOLESTR propertyString, ParseNodePtr pNode, uint32 *fullNameHintLength, uint32 *pShortNameOffset)
  7023. {
  7024. // propertyString could be null, such as 'this.foo' =
  7025. // propertyString could be empty, found in pattern as in (-1)[""][(x = z)]
  7026. OpCode op = pNode->nop;
  7027. LPCOLESTR rightNode = nullptr;
  7028. if (propertyString == nullptr)
  7029. {
  7030. propertyString = _u("");
  7031. }
  7032. if (op != knopInt && op != knopFlt && op != knopName && op != knopStr)
  7033. {
  7034. rightNode = _u("");
  7035. }
  7036. else if (op == knopStr)
  7037. {
  7038. return AppendNameHints(propertyString, pNode->AsParseNodePid()->pid, fullNameHintLength, pShortNameOffset, false, true/*add brackets*/);
  7039. }
  7040. else if(op == knopFlt)
  7041. {
  7042. rightNode = m_pscan->StringFromDbl(pNode->AsParseNodeFloat()->dbl);
  7043. }
  7044. else
  7045. {
  7046. rightNode = op == knopInt ? m_pscan->StringFromLong(pNode->AsParseNodeInt()->lw)
  7047. : pNode->AsParseNodePid()->pid->Psz();
  7048. }
  7049. return AppendNameHints(propertyString, rightNode, fullNameHintLength, pShortNameOffset, false, true/*add brackets*/);
  7050. }
  7051. LPCOLESTR Parser::ConstructNameHint(ParseNodePtr pNode, uint32* fullNameHintLength, uint32 *pShortNameOffset)
  7052. {
  7053. Assert(pNode != nullptr);
  7054. Assert(pNode->nop == knopDot || pNode->nop == knopIndex);
  7055. // This method recursively visits nodes in the AST and could cause an SOE crash for long knopDot chains.
  7056. // Although this method could be made non-recursive, Emit (ByteCodeEmitter.cpp) hits a stack probe
  7057. // for shorter chains than which cause SOE here, so add a stack probe to throw SOE rather than crash on SOE.
  7058. // Because of that correspondence, use Js::Constants::MinStackByteCodeVisitor (which is used in Emit)
  7059. // for the stack probe here. See OS#14711878.
  7060. PROBE_STACK_NO_DISPOSE(this->m_scriptContext, Js::Constants::MinStackByteCodeVisitor);
  7061. LPCOLESTR leftNode = nullptr;
  7062. if (pNode->AsParseNodeBin()->pnode1->nop == knopDot || pNode->AsParseNodeBin()->pnode1->nop == knopIndex)
  7063. {
  7064. leftNode = ConstructNameHint(pNode->AsParseNodeBin()->pnode1, fullNameHintLength, pShortNameOffset);
  7065. }
  7066. else if (pNode->AsParseNodeBin()->pnode1->nop == knopName && !pNode->AsParseNodeBin()->pnode1->isSpecialName)
  7067. {
  7068. // We need to skip special names like 'this' because those shouldn't be appended to the
  7069. // name hint in the debugger stack trace.
  7070. // function ctor() {
  7071. // this.func = function() {
  7072. // // If we break here, the stack should say we are in 'func' and not 'this.func'
  7073. // }
  7074. // }
  7075. leftNode = pNode->AsParseNodeBin()->pnode1->AsParseNodePid()->pid->Psz();
  7076. *fullNameHintLength = pNode->AsParseNodeBin()->pnode1->AsParseNodePid()->pid->Cch();
  7077. *pShortNameOffset = 0;
  7078. }
  7079. if (pNode->nop == knopIndex)
  7080. {
  7081. return FormatPropertyString(
  7082. leftNode ? leftNode : Js::Constants::AnonymousFunction, // e.g. f()[0] = function () {}
  7083. pNode->AsParseNodeBin()->pnode2, fullNameHintLength, pShortNameOffset);
  7084. }
  7085. Assert(pNode->AsParseNodeBin()->pnode2->nop == knopDot || pNode->AsParseNodeBin()->pnode2->nop == knopName);
  7086. LPCOLESTR rightNode = nullptr;
  7087. bool wrapWithBrackets = false;
  7088. if (pNode->AsParseNodeBin()->pnode2->nop == knopDot)
  7089. {
  7090. rightNode = ConstructNameHint(pNode->AsParseNodeBin()->pnode2, fullNameHintLength, pShortNameOffset);
  7091. }
  7092. else
  7093. {
  7094. rightNode = pNode->AsParseNodeBin()->pnode2->AsParseNodePid()->pid->Psz();
  7095. wrapWithBrackets = PNodeFlags::fpnIndexOperator == (pNode->grfpn & PNodeFlags::fpnIndexOperator);
  7096. }
  7097. Assert(rightNode != nullptr);
  7098. return AppendNameHints(leftNode, rightNode, fullNameHintLength, pShortNameOffset, false, wrapWithBrackets);
  7099. }
  7100. LPCOLESTR Parser::AppendNameHints(LPCOLESTR leftStr, uint32 leftLen, LPCOLESTR rightStr, uint32 rightLen, uint32 *pNameLength, uint32 *pShortNameOffset, bool ignoreAddDotWithSpace, bool wrapInBrackets)
  7101. {
  7102. Assert(rightStr != nullptr);
  7103. Assert(leftLen != 0 || wrapInBrackets);
  7104. Assert(rightLen != 0 || wrapInBrackets);
  7105. 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
  7106. uint32 totalLength = leftLen + rightLen + ((ignoreDot) ? 1 : 2); // 1 (for dot or [) + 1 (for null termination)
  7107. if (wrapInBrackets)
  7108. {
  7109. totalLength++; //1 for ']';
  7110. }
  7111. WCHAR * finalName = AllocateStringOfLength(totalLength);
  7112. if (leftStr != nullptr && leftLen != 0)
  7113. {
  7114. wcscpy_s(finalName, leftLen + 1, leftStr);
  7115. }
  7116. if (ignoreAddDotWithSpace)
  7117. {
  7118. finalName[leftLen++] = (OLECHAR)_u(' ');
  7119. }
  7120. // mutually exclusive from ignoreAddDotWithSpace which is used for getters/setters
  7121. else if (wrapInBrackets)
  7122. {
  7123. finalName[leftLen++] = (OLECHAR)_u('[');
  7124. finalName[totalLength-2] = (OLECHAR)_u(']');
  7125. }
  7126. else if (!ignoreDot)
  7127. {
  7128. finalName[leftLen++] = (OLECHAR)_u('.');
  7129. }
  7130. //ignore case falls through
  7131. js_wmemcpy_s(finalName + leftLen, rightLen, rightStr, rightLen);
  7132. finalName[totalLength-1] = (OLECHAR)_u('\0');
  7133. if (pNameLength != nullptr)
  7134. {
  7135. *pNameLength = totalLength - 1;
  7136. }
  7137. if (pShortNameOffset != nullptr)
  7138. {
  7139. *pShortNameOffset = leftLen;
  7140. }
  7141. return finalName;
  7142. }
  7143. WCHAR * Parser::AllocateStringOfLength(ULONG length)
  7144. {
  7145. Assert(length > 0);
  7146. ULONG totalBytes;
  7147. if (ULongMult(length, sizeof(OLECHAR), &totalBytes) != S_OK)
  7148. {
  7149. Error(ERRnoMemory);
  7150. }
  7151. WCHAR* finalName = (WCHAR*)m_phtbl->GetAllocator()->Alloc(totalBytes);
  7152. if (finalName == nullptr)
  7153. {
  7154. Error(ERRnoMemory);
  7155. }
  7156. return finalName;
  7157. }
  7158. LPCOLESTR Parser::AppendNameHints(IdentPtr left, IdentPtr right, uint32 *pNameLength, uint32 *pShortNameOffset, bool ignoreAddDotWithSpace, bool wrapInBrackets)
  7159. {
  7160. if (pShortNameOffset != nullptr)
  7161. {
  7162. *pShortNameOffset = 0;
  7163. }
  7164. if (left == nullptr && !wrapInBrackets)
  7165. {
  7166. if (right)
  7167. {
  7168. *pNameLength = right->Cch();
  7169. return right->Psz();
  7170. }
  7171. return nullptr;
  7172. }
  7173. uint32 leftLen = 0;
  7174. LPCOLESTR leftStr = _u("");
  7175. if (left != nullptr) // if wrapInBrackets is true
  7176. {
  7177. leftStr = left->Psz();
  7178. leftLen = left->Cch();
  7179. }
  7180. if (right == nullptr)
  7181. {
  7182. *pNameLength = leftLen;
  7183. return left->Psz();
  7184. }
  7185. uint32 rightLen = right->Cch();
  7186. return AppendNameHints(leftStr, leftLen, right->Psz(), rightLen, pNameLength, pShortNameOffset, ignoreAddDotWithSpace, wrapInBrackets);
  7187. }
  7188. LPCOLESTR Parser::AppendNameHints(IdentPtr left, LPCOLESTR right, uint32 *pNameLength, uint32 *pShortNameOffset, bool ignoreAddDotWithSpace, bool wrapInBrackets)
  7189. {
  7190. uint32 rightLen = (right == nullptr) ? 0 : (uint32) wcslen(right);
  7191. if (pShortNameOffset != nullptr)
  7192. {
  7193. *pShortNameOffset = 0;
  7194. }
  7195. Assert(rightLen <= ULONG_MAX); // name hints should not exceed ULONG_MAX characters
  7196. if (left == nullptr && !wrapInBrackets)
  7197. {
  7198. *pNameLength = rightLen;
  7199. return right;
  7200. }
  7201. LPCOLESTR leftStr = _u("");
  7202. uint32 leftLen = 0;
  7203. if (left != nullptr) // if wrapInBrackets is true
  7204. {
  7205. leftStr = left->Psz();
  7206. leftLen = left->Cch();
  7207. }
  7208. if (rightLen == 0 && !wrapInBrackets)
  7209. {
  7210. *pNameLength = leftLen;
  7211. return left->Psz();
  7212. }
  7213. return AppendNameHints(leftStr, leftLen, right, rightLen, pNameLength, pShortNameOffset, ignoreAddDotWithSpace, wrapInBrackets);
  7214. }
  7215. LPCOLESTR Parser::AppendNameHints(LPCOLESTR left, IdentPtr right, uint32 *pNameLength, uint32 *pShortNameOffset, bool ignoreAddDotWithSpace, bool wrapInBrackets)
  7216. {
  7217. uint32 leftLen = (left == nullptr) ? 0 : (uint32) wcslen(left);
  7218. if (pShortNameOffset != nullptr)
  7219. {
  7220. *pShortNameOffset = 0;
  7221. }
  7222. Assert(leftLen <= ULONG_MAX); // name hints should not exceed ULONG_MAX characters
  7223. if (left == nullptr || (leftLen == 0 && !wrapInBrackets))
  7224. {
  7225. if (right != nullptr)
  7226. {
  7227. *pNameLength = right->Cch();
  7228. return right->Psz();
  7229. }
  7230. return nullptr;
  7231. }
  7232. if (right == nullptr)
  7233. {
  7234. *pNameLength = leftLen;
  7235. return left;
  7236. }
  7237. uint32 rightLen = right->Cch();
  7238. return AppendNameHints(left, leftLen, right->Psz(), rightLen, pNameLength, pShortNameOffset, ignoreAddDotWithSpace, wrapInBrackets);
  7239. }
  7240. LPCOLESTR Parser::AppendNameHints(LPCOLESTR left, LPCOLESTR right, uint32 *pNameLength, uint32 *pShortNameOffset, bool ignoreAddDotWithSpace, bool wrapInBrackets)
  7241. {
  7242. uint32 leftLen = (left == nullptr) ? 0 : (uint32) wcslen(left);
  7243. uint32 rightLen = (right == nullptr) ? 0 : (uint32) wcslen(right);
  7244. if (pShortNameOffset != nullptr)
  7245. {
  7246. *pShortNameOffset = 0;
  7247. }
  7248. Assert(rightLen <= ULONG_MAX && leftLen <= ULONG_MAX); // name hints should not exceed ULONG_MAX characters
  7249. if (leftLen == 0 && !wrapInBrackets)
  7250. {
  7251. *pNameLength = right ? rightLen : 0;
  7252. return right;
  7253. }
  7254. if (rightLen == 0 && !wrapInBrackets)
  7255. {
  7256. *pNameLength = leftLen;
  7257. return left;
  7258. }
  7259. return AppendNameHints(left, leftLen, right, rightLen, pNameLength, pShortNameOffset, ignoreAddDotWithSpace, wrapInBrackets);
  7260. }
  7261. /**
  7262. * Emits a spread error if there is no ambiguity, or marks defers the error for
  7263. * when we can determine if it is a rest error or a spread error.
  7264. *
  7265. * The ambiguity arises when we are parsing a lambda parameter list but we have
  7266. * not seen the => token. At this point, we are either in a parenthesized
  7267. * expression or a parameter list, and cannot issue an error until the matching
  7268. * RParen has been scanned.
  7269. *
  7270. * The actual emission of the error happens in ParseExpr, when we first know if
  7271. * the expression is a lambda parameter list or not.
  7272. *
  7273. */
  7274. void Parser::DeferOrEmitPotentialSpreadError(ParseNodePtr pnodeT)
  7275. {
  7276. if (m_funcParenExprDepth > 0)
  7277. {
  7278. if (m_token.tk == tkRParen)
  7279. {
  7280. if (!m_deferEllipsisError)
  7281. {
  7282. // Capture only the first error instance. Because a lambda will cause a reparse in a formals context, we can assume
  7283. // that this will be a spread error. Nested paren exprs will have their own error instance.
  7284. m_pscan->Capture(&m_deferEllipsisErrorLoc);
  7285. m_deferEllipsisError = true;
  7286. }
  7287. }
  7288. else
  7289. {
  7290. Error(ERRUnexpectedEllipsis);
  7291. }
  7292. }
  7293. else
  7294. {
  7295. Error(ERRInvalidSpreadUse);
  7296. }
  7297. }
  7298. bool Parser::IsTerminateToken()
  7299. {
  7300. return (m_token.tk == tkRCurly ||
  7301. m_token.tk == tkRBrack ||
  7302. m_token.tk == tkRParen ||
  7303. m_token.tk == tkSColon ||
  7304. m_token.tk == tkColon ||
  7305. m_token.tk == tkComma ||
  7306. m_token.tk == tkLimKwd ||
  7307. m_pscan->FHadNewLine());
  7308. }
  7309. /***************************************************************************
  7310. Parse an optional sub expression returning null if there was no expression.
  7311. Checks for no expression by looking for a token that can follow an
  7312. Expression grammar production.
  7313. ***************************************************************************/
  7314. template<bool buildAST>
  7315. bool Parser::ParseOptionalExpr(ParseNodePtr* pnode, bool fUnaryOrParen, int oplMin, BOOL *pfCanAssign, BOOL fAllowIn, BOOL fAllowEllipsis, _Inout_opt_ IdentToken* pToken)
  7316. {
  7317. *pnode = nullptr;
  7318. if (IsTerminateToken())
  7319. {
  7320. return false;
  7321. }
  7322. IdentToken token;
  7323. ParseNodePtr pnodeT = ParseExpr<buildAST>(oplMin, pfCanAssign, fAllowIn, fAllowEllipsis, nullptr /*pNameHint*/, nullptr /*pHintLength*/, nullptr /*pShortNameOffset*/, &token, fUnaryOrParen);
  7324. // Detect nested function escapes of the pattern "return function(){...}" or "yield function(){...}".
  7325. // Doing so in the parser allows us to disable stack-nested-functions in common cases where an escape
  7326. // is not detected at byte code gen time because of deferred parsing.
  7327. this->MarkEscapingRef(pnodeT, &token);
  7328. if (pToken)
  7329. {
  7330. *pToken = token;
  7331. }
  7332. *pnode = pnodeT;
  7333. return true;
  7334. }
  7335. /***************************************************************************
  7336. Parse a sub expression.
  7337. 'fAllowIn' indicates if the 'in' operator should be allowed in the initializing
  7338. expression ( it is not allowed in the context of the first expression in a 'for' loop).
  7339. ***************************************************************************/
  7340. template<bool buildAST>
  7341. ParseNodePtr Parser::ParseExpr(int oplMin,
  7342. BOOL *pfCanAssign,
  7343. BOOL fAllowIn,
  7344. BOOL fAllowEllipsis,
  7345. LPCOLESTR pNameHint,
  7346. uint32 *pHintLength,
  7347. uint32 *pShortNameOffset,
  7348. _Inout_opt_ IdentToken* pToken,
  7349. bool fUnaryOrParen,
  7350. _Inout_opt_ bool* pfLikelyPattern,
  7351. _Inout_opt_ charcount_t *plastRParen)
  7352. {
  7353. Assert(pToken == nullptr || pToken->tk == tkNone); // Must be empty initially
  7354. int opl;
  7355. OpCode nop;
  7356. charcount_t ichMin;
  7357. ParseNodePtr pnode = nullptr;
  7358. ParseNodePtr pnodeT = nullptr;
  7359. BOOL fCanAssign = TRUE;
  7360. bool assignmentStmt = false;
  7361. bool fIsDotOrIndex = false;
  7362. IdentToken term;
  7363. RestorePoint termStart;
  7364. uint32 hintLength = 0;
  7365. uint32 hintOffset = 0;
  7366. ParserState parserState;
  7367. if (pHintLength != nullptr)
  7368. {
  7369. hintLength = *pHintLength;
  7370. }
  7371. if (pShortNameOffset != nullptr)
  7372. {
  7373. hintOffset = *pShortNameOffset;
  7374. }
  7375. EnsureStackAvailable();
  7376. // Storing the state here as we need to restore this state back when we need to reparse the grammar under lambda syntax.
  7377. CaptureState(&parserState);
  7378. m_pscan->Capture(&termStart);
  7379. bool deferredErrorFoundOnLeftSide = false;
  7380. bool savedDeferredInitError = m_hasDeferredShorthandInitError;
  7381. m_hasDeferredShorthandInitError = false;
  7382. // Is the current token a unary operator?
  7383. if (m_phtbl->TokIsUnop(m_token.tk, &opl, &nop) && nop != knopNone)
  7384. {
  7385. IdentToken operandToken;
  7386. ichMin = m_pscan->IchMinTok();
  7387. if (nop == knopYield)
  7388. {
  7389. if (!m_pscan->YieldIsKeywordRegion() || oplMin > opl)
  7390. {
  7391. // The case where 'yield' is scanned as a keyword (tkYIELD) but the scanner
  7392. // is not treating yield as a keyword (!m_pscan->YieldIsKeywordRegion()) occurs
  7393. // in strict mode non-generator function contexts.
  7394. //
  7395. // That is, 'yield' is a keyword because of strict mode, but YieldExpression
  7396. // is not a grammar production outside of generator functions.
  7397. //
  7398. // Otherwise it is an error for a yield to appear in the context of a higher level
  7399. // binding operator, be it unary or binary.
  7400. Error(ERRsyntax);
  7401. }
  7402. if (m_currentScope->GetScopeType() == ScopeType_Parameter)
  7403. {
  7404. Error(ERRsyntax);
  7405. }
  7406. }
  7407. else if (nop == knopAwait)
  7408. {
  7409. if (!m_pscan->AwaitIsKeywordRegion() ||
  7410. m_currentScope->GetScopeType() == ScopeType_Parameter)
  7411. {
  7412. // As with the 'yield' keyword, the case where 'await' is scanned as a keyword (tkAWAIT)
  7413. // but the scanner is not treating await as a keyword (!m_pscan->AwaitIsKeyword())
  7414. // occurs in strict mode non-async function contexts.
  7415. //
  7416. // That is, 'await' is a keyword because of strict mode, but AwaitExpression
  7417. // is not a grammar production outside of async functions.
  7418. //
  7419. // Further, await expressions are disallowed within parameter scopes.
  7420. Error(ERRBadAwait);
  7421. }
  7422. }
  7423. m_pscan->Scan();
  7424. if (m_token.tk == tkEllipsis) {
  7425. // ... cannot have a unary prefix.
  7426. Error(ERRUnexpectedEllipsis);
  7427. }
  7428. if (nop == knopYield && !m_pscan->FHadNewLine() && m_token.tk == tkStar)
  7429. {
  7430. m_pscan->Scan();
  7431. nop = knopYieldStar;
  7432. }
  7433. if (nop == knopYield)
  7434. {
  7435. if (!ParseOptionalExpr<buildAST>(&pnodeT, false, opl, NULL, TRUE, fAllowEllipsis))
  7436. {
  7437. nop = knopYieldLeaf;
  7438. if (buildAST)
  7439. {
  7440. pnode = CreateNodeT<knopYieldLeaf>(ichMin, m_pscan->IchLimTok());
  7441. }
  7442. }
  7443. }
  7444. else
  7445. {
  7446. // Disallow spread after a unary operator.
  7447. pnodeT = ParseExpr<buildAST>(opl, &fCanAssign, TRUE, FALSE, nullptr /*hint*/, nullptr /*hintLength*/, nullptr /*hintOffset*/, &operandToken, true, nullptr, plastRParen);
  7448. }
  7449. if (nop != knopYieldLeaf)
  7450. {
  7451. if ((nop == knopIncPre || nop == knopDecPre) && (m_token.tk != tkDArrow))
  7452. {
  7453. if (!fCanAssign && PHASE_ON1(Js::EarlyReferenceErrorsPhase))
  7454. {
  7455. Error(JSERR_CantAssignTo);
  7456. }
  7457. TrackAssignment<buildAST>(pnodeT, &operandToken);
  7458. if (buildAST)
  7459. {
  7460. if (IsStrictMode() && pnodeT->nop == knopName)
  7461. {
  7462. CheckStrictModeEvalArgumentsUsage(pnodeT->AsParseNodePid()->pid);
  7463. }
  7464. }
  7465. else
  7466. {
  7467. if (IsStrictMode() && operandToken.tk == tkID)
  7468. {
  7469. CheckStrictModeEvalArgumentsUsage(operandToken.pid);
  7470. }
  7471. }
  7472. }
  7473. else if (nop == knopEllipsis)
  7474. {
  7475. if (!fAllowEllipsis)
  7476. {
  7477. DeferOrEmitPotentialSpreadError(pnodeT);
  7478. }
  7479. }
  7480. else if (m_token.tk == tkExpo)
  7481. {
  7482. //Unary operator on the left hand-side of ** is unexpected, except ++, -- or ...
  7483. Error(ERRInvalidUseofExponentiationOperator);
  7484. }
  7485. if (buildAST)
  7486. {
  7487. //Do not do the folding for Asm in case of KnopPos as we need this to determine the type
  7488. if (nop == knopPos && (pnodeT->nop == knopInt || pnodeT->nop == knopFlt) && !this->m_InAsmMode)
  7489. {
  7490. // Fold away a unary '+' on a number.
  7491. pnode = pnodeT;
  7492. }
  7493. else if (nop == knopNeg &&
  7494. ((pnodeT->nop == knopInt && pnodeT->AsParseNodeInt()->lw != 0) ||
  7495. (pnodeT->nop == knopFlt && (pnodeT->AsParseNodeFloat()->dbl != 0 || this->m_InAsmMode))))
  7496. {
  7497. // Fold a unary '-' on a number into the value of the number itself.
  7498. pnode = pnodeT;
  7499. if (pnode->nop == knopInt)
  7500. {
  7501. pnode->AsParseNodeInt()->lw = -pnode->AsParseNodeInt()->lw;
  7502. }
  7503. else
  7504. {
  7505. pnode->AsParseNodeFloat()->dbl = -pnode->AsParseNodeFloat()->dbl;
  7506. }
  7507. }
  7508. else
  7509. {
  7510. pnode = CreateUniNode(nop, pnodeT);
  7511. this->CheckArguments(pnode->AsParseNodeUni()->pnode1);
  7512. }
  7513. pnode->ichMin = ichMin;
  7514. }
  7515. if (nop == knopDelete)
  7516. {
  7517. if (IsStrictMode())
  7518. {
  7519. if ((buildAST && pnode->AsParseNodeUni()->pnode1->IsUserIdentifier()) ||
  7520. (!buildAST && operandToken.tk == tkID && !this->IsSpecialName(operandToken.pid)))
  7521. {
  7522. Error(ERRInvalidDelete);
  7523. }
  7524. }
  7525. if (buildAST)
  7526. {
  7527. ParseNodePtr pnode1 = pnode->AsParseNodeUni()->pnode1;
  7528. if (m_currentNodeFunc)
  7529. {
  7530. if (pnode1->nop == knopDot || pnode1->nop == knopIndex)
  7531. {
  7532. // If we delete an arguments property, use the conservative,
  7533. // heap-allocated arguments object.
  7534. this->CheckArguments(pnode1->AsParseNodeBin()->pnode1);
  7535. }
  7536. }
  7537. }
  7538. }
  7539. }
  7540. fCanAssign = FALSE;
  7541. }
  7542. else
  7543. {
  7544. ichMin = m_pscan->IchMinTok();
  7545. BOOL fLikelyPattern = FALSE;
  7546. pnode = ParseTerm<buildAST>(TRUE, pNameHint, &hintLength, &hintOffset, &term, fUnaryOrParen, &fCanAssign, IsES6DestructuringEnabled() ? &fLikelyPattern : nullptr, &fIsDotOrIndex, plastRParen);
  7547. if (pfLikelyPattern != nullptr)
  7548. {
  7549. *pfLikelyPattern = !!fLikelyPattern;
  7550. }
  7551. if (m_token.tk == tkDArrow)
  7552. {
  7553. m_hasDeferredShorthandInitError = false;
  7554. }
  7555. if (m_token.tk == tkAsg && oplMin <= koplAsg && fLikelyPattern)
  7556. {
  7557. m_pscan->SeekTo(termStart);
  7558. // 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
  7559. // on the pidref stack match.
  7560. int saveNextBlockId = m_nextBlockId;
  7561. m_nextBlockId = parserState.m_nextBlockId;
  7562. ParseDestructuredLiteralWithScopeSave(tkLCurly, false/*isDecl*/, false /*topLevel*/, DIC_ShouldNotParseInitializer);
  7563. // 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
  7564. // because we don't parse initializers during reparse and there may be additional blocks (e.g. a class declaration)
  7565. // in the initializers that will cause the next Block ID at the end of the reparsing to be different.
  7566. m_nextBlockId = saveNextBlockId;
  7567. if (buildAST)
  7568. {
  7569. this->SetHasDestructuringPattern(true);
  7570. pnode = ConvertToPattern(pnode);
  7571. }
  7572. }
  7573. if (buildAST)
  7574. {
  7575. pNameHint = NULL;
  7576. if (pnode->nop == knopName)
  7577. {
  7578. pNameHint = pnode->AsParseNodePid()->pid->Psz();
  7579. hintLength = pnode->AsParseNodePid()->pid->Cch();
  7580. hintOffset = 0;
  7581. }
  7582. else if (pnode->nop == knopDot || pnode->nop == knopIndex)
  7583. {
  7584. if (CONFIG_FLAG(UseFullName))
  7585. {
  7586. pNameHint = ConstructNameHint(pnode, &hintLength, &hintOffset);
  7587. }
  7588. else
  7589. {
  7590. ParseNodePtr pnodeName = pnode;
  7591. while (pnodeName->nop == knopDot)
  7592. {
  7593. pnodeName = pnodeName->AsParseNodeBin()->pnode2;
  7594. }
  7595. if (pnodeName->nop == knopName)
  7596. {
  7597. pNameHint = pnodeName->AsParseNodePid()->pid->Psz();
  7598. hintLength = pnodeName->AsParseNodePid()->pid->Cch();
  7599. hintOffset = 0;
  7600. }
  7601. }
  7602. }
  7603. }
  7604. // Check for postfix unary operators.
  7605. if (!m_pscan->FHadNewLine() &&
  7606. (tkInc == m_token.tk || tkDec == m_token.tk))
  7607. {
  7608. if (!fCanAssign && PHASE_ON1(Js::EarlyReferenceErrorsPhase))
  7609. {
  7610. Error(JSERR_CantAssignTo);
  7611. }
  7612. TrackAssignment<buildAST>(pnode, &term);
  7613. fCanAssign = FALSE;
  7614. if (buildAST)
  7615. {
  7616. if (IsStrictMode() && pnode->nop == knopName)
  7617. {
  7618. CheckStrictModeEvalArgumentsUsage(pnode->AsParseNodePid()->pid);
  7619. }
  7620. this->CheckArguments(pnode);
  7621. pnode = CreateUniNode(tkInc == m_token.tk ? knopIncPost : knopDecPost, pnode);
  7622. pnode->ichLim = m_pscan->IchLimTok();
  7623. }
  7624. else
  7625. {
  7626. if (IsStrictMode() && term.tk == tkID)
  7627. {
  7628. CheckStrictModeEvalArgumentsUsage(term.pid);
  7629. }
  7630. // This expression is not an identifier
  7631. term.tk = tkNone;
  7632. }
  7633. m_pscan->Scan();
  7634. }
  7635. }
  7636. deferredErrorFoundOnLeftSide = m_hasDeferredShorthandInitError;
  7637. // Process a sequence of operators and operands.
  7638. for (;;)
  7639. {
  7640. if (!m_phtbl->TokIsBinop(m_token.tk, &opl, &nop) || nop == knopNone)
  7641. {
  7642. break;
  7643. }
  7644. if ( ! fAllowIn && nop == knopIn )
  7645. {
  7646. break;
  7647. }
  7648. Assert(opl != koplNo);
  7649. if (opl == koplAsg)
  7650. {
  7651. if (m_token.tk != tkDArrow)
  7652. {
  7653. // Assignment operator. These are the only right associative
  7654. // binary operators. We also need to special case the left
  7655. // operand - it should only be a LeftHandSideExpression.
  7656. Assert(ParseNode::Grfnop(nop) & fnopAsg || nop == knopFncDecl);
  7657. TrackAssignment<buildAST>(pnode, &term);
  7658. if (buildAST)
  7659. {
  7660. if (IsStrictMode() && pnode->nop == knopName)
  7661. {
  7662. CheckStrictModeEvalArgumentsUsage(pnode->AsParseNodePid()->pid);
  7663. }
  7664. // Assignment stmt of the form "this.<id> = <expr>"
  7665. if (nop == knopAsg
  7666. && pnode->nop == knopDot
  7667. && pnode->AsParseNodeBin()->pnode1->nop == knopName
  7668. && pnode->AsParseNodeBin()->pnode1->AsParseNodePid()->pid == wellKnownPropertyPids._this
  7669. && pnode->AsParseNodeBin()->pnode2->nop == knopName)
  7670. {
  7671. if (pnode->AsParseNodeBin()->pnode2->AsParseNodePid()->pid != wellKnownPropertyPids.__proto__)
  7672. {
  7673. assignmentStmt = true;
  7674. }
  7675. }
  7676. }
  7677. else
  7678. {
  7679. if (IsStrictMode() && term.tk == tkID)
  7680. {
  7681. CheckStrictModeEvalArgumentsUsage(term.pid);
  7682. }
  7683. }
  7684. }
  7685. if (opl < oplMin)
  7686. {
  7687. break;
  7688. }
  7689. if (m_token.tk != tkDArrow && !fCanAssign && PHASE_ON1(Js::EarlyReferenceErrorsPhase))
  7690. {
  7691. Error(JSERR_CantAssignTo);
  7692. // No recovery necessary since this is a semantic, not structural, error.
  7693. }
  7694. }
  7695. else if (opl == koplExpo)
  7696. {
  7697. // ** operator is right associative
  7698. if (opl < oplMin)
  7699. {
  7700. break;
  7701. }
  7702. }
  7703. else if (opl <= oplMin)
  7704. {
  7705. break;
  7706. }
  7707. // This expression is not an identifier
  7708. term.tk = tkNone;
  7709. // Precedence is high enough. Consume the operator token.
  7710. m_pscan->Scan();
  7711. fCanAssign = FALSE;
  7712. // Special case the "?:" operator
  7713. if (nop == knopQmark)
  7714. {
  7715. pnodeT = ParseExpr<buildAST>(koplAsg, NULL, fAllowIn);
  7716. ChkCurTok(tkColon, ERRnoColon);
  7717. ParseNodePtr pnodeT2 = ParseExpr<buildAST>(koplAsg, NULL, fAllowIn, 0, nullptr, nullptr, nullptr, nullptr, false, nullptr, plastRParen);
  7718. if (buildAST)
  7719. {
  7720. pnode = CreateTriNode(nop, pnode, pnodeT, pnodeT2);
  7721. this->CheckArguments(pnode->AsParseNodeTri()->pnode2);
  7722. this->CheckArguments(pnode->AsParseNodeTri()->pnode3);
  7723. }
  7724. }
  7725. else if (nop == knopFncDecl)
  7726. {
  7727. ushort flags = fFncLambda;
  7728. size_t iecpMin = 0;
  7729. bool isAsyncMethod = false;
  7730. RestoreStateFrom(&parserState);
  7731. m_pscan->SeekTo(termStart);
  7732. if (m_token.tk == tkID && m_token.GetIdentifier(m_phtbl) == wellKnownPropertyPids.async && m_scriptContext->GetConfig()->IsES7AsyncAndAwaitEnabled())
  7733. {
  7734. ichMin = m_pscan->IchMinTok();
  7735. iecpMin = m_pscan->IecpMinTok();
  7736. m_pscan->Scan();
  7737. if ((m_token.tk == tkID || m_token.tk == tkLParen) && !m_pscan->FHadNewLine())
  7738. {
  7739. flags |= fFncAsync;
  7740. isAsyncMethod = true;
  7741. }
  7742. else
  7743. {
  7744. m_pscan->SeekTo(termStart);
  7745. }
  7746. }
  7747. pnode = ParseFncDecl<buildAST>(flags, nullptr, /* needsPIDOnRCurlyScan = */false, /* resetParsingSuperRestrictionState = */false);
  7748. if (isAsyncMethod)
  7749. {
  7750. pnode->AsParseNodeFnc()->cbMin = iecpMin;
  7751. pnode->ichMin = ichMin;
  7752. }
  7753. // ArrowFunction/AsyncArrowFunction is part of AssignmentExpression, which should terminate the expression unless followed by a comma
  7754. if (m_token.tk != tkComma)
  7755. {
  7756. if (!(IsTerminateToken()))
  7757. {
  7758. Error(ERRnoSemic);
  7759. }
  7760. break;
  7761. }
  7762. }
  7763. else
  7764. {
  7765. // Parse the operand, make a new node, and look for more
  7766. IdentToken token;
  7767. pnodeT = ParseExpr<buildAST>(opl, NULL, fAllowIn, FALSE, pNameHint, &hintLength, &hintOffset, &token, false, nullptr, plastRParen);
  7768. // Detect nested function escapes of the pattern "o.f = function(){...}" or "o[s] = function(){...}".
  7769. // Doing so in the parser allows us to disable stack-nested-functions in common cases where an escape
  7770. // is not detected at byte code gen time because of deferred parsing.
  7771. if (fIsDotOrIndex && nop == knopAsg)
  7772. {
  7773. this->MarkEscapingRef(pnodeT, &token);
  7774. }
  7775. if (buildAST)
  7776. {
  7777. pnode = CreateBinNode(nop, pnode, pnodeT);
  7778. Assert(pnode->AsParseNodeBin()->pnode2 != NULL);
  7779. if (pnode->AsParseNodeBin()->pnode2->nop == knopFncDecl)
  7780. {
  7781. Assert(hintLength >= hintOffset);
  7782. pnode->AsParseNodeBin()->pnode2->AsParseNodeFnc()->hint = pNameHint;
  7783. pnode->AsParseNodeBin()->pnode2->AsParseNodeFnc()->hintLength = hintLength;
  7784. pnode->AsParseNodeBin()->pnode2->AsParseNodeFnc()->hintOffset = hintOffset;
  7785. if (pnode->AsParseNodeBin()->pnode1->nop == knopDot)
  7786. {
  7787. pnode->AsParseNodeBin()->pnode2->AsParseNodeFnc()->isNameIdentifierRef = false;
  7788. }
  7789. else if (pnode->AsParseNodeBin()->pnode1->nop == knopName)
  7790. {
  7791. PidRefStack *pidRef = pnode->AsParseNodeBin()->pnode1->AsParseNodePid()->pid->GetTopRef();
  7792. pidRef->isFuncAssignment = true;
  7793. }
  7794. }
  7795. if (pnode->AsParseNodeBin()->pnode2->nop == knopClassDecl && pnode->AsParseNodeBin()->pnode1->nop == knopDot)
  7796. {
  7797. Assert(pnode->AsParseNodeBin()->pnode2->AsParseNodeClass()->pnodeConstructor);
  7798. if (!pnode->AsParseNodeBin()->pnode2->AsParseNodeClass()->pnodeConstructor->AsParseNodeFnc()->pid)
  7799. {
  7800. pnode->AsParseNodeBin()->pnode2->AsParseNodeClass()->pnodeConstructor->AsParseNodeFnc()->isNameIdentifierRef = false;
  7801. }
  7802. }
  7803. }
  7804. pNameHint = NULL;
  7805. }
  7806. }
  7807. if (buildAST)
  7808. {
  7809. if (!assignmentStmt)
  7810. {
  7811. // Don't set the flag for following nodes
  7812. switch (pnode->nop)
  7813. {
  7814. case knopName:
  7815. case knopInt:
  7816. case knopFlt:
  7817. case knopStr:
  7818. case knopRegExp:
  7819. case knopNull:
  7820. case knopFalse:
  7821. case knopTrue:
  7822. break;
  7823. default:
  7824. if (m_currentNodeFunc)
  7825. {
  7826. m_currentNodeFunc->AsParseNodeFnc()->SetHasNonThisStmt();
  7827. }
  7828. else if (m_currentNodeProg)
  7829. {
  7830. m_currentNodeProg->AsParseNodeFnc()->SetHasNonThisStmt();
  7831. }
  7832. }
  7833. }
  7834. }
  7835. if (m_hasDeferredShorthandInitError && !deferredErrorFoundOnLeftSide)
  7836. {
  7837. // Raise error only if it is found not on the right side of the expression.
  7838. // such as <expr> = {x = 1}
  7839. Error(ERRnoColon);
  7840. }
  7841. m_hasDeferredShorthandInitError = m_hasDeferredShorthandInitError || savedDeferredInitError;
  7842. if (NULL != pfCanAssign)
  7843. {
  7844. *pfCanAssign = fCanAssign;
  7845. }
  7846. // Pass back identifier if requested
  7847. if (pToken && term.tk == tkID)
  7848. {
  7849. *pToken = term;
  7850. }
  7851. //Track "obj.a" assignment patterns here - Promote the Assignment state for the property's PID.
  7852. // This includes =, += etc.
  7853. if (pnode != NULL)
  7854. {
  7855. uint nodeType = ParseNode::Grfnop(pnode->nop);
  7856. if (nodeType & fnopAsg)
  7857. {
  7858. if (nodeType & fnopBin)
  7859. {
  7860. ParseNodePtr lhs = pnode->AsParseNodeBin()->pnode1;
  7861. Assert(lhs);
  7862. if (lhs->nop == knopDot)
  7863. {
  7864. ParseNodePtr propertyNode = lhs->AsParseNodeBin()->pnode2;
  7865. if (propertyNode->nop == knopName)
  7866. {
  7867. propertyNode->AsParseNodePid()->pid->PromoteAssignmentState();
  7868. }
  7869. }
  7870. }
  7871. else if (nodeType & fnopUni)
  7872. {
  7873. // cases like obj.a++, ++obj.a
  7874. ParseNodePtr lhs = pnode->AsParseNodeUni()->pnode1;
  7875. if (lhs->nop == knopDot)
  7876. {
  7877. ParseNodePtr propertyNode = lhs->AsParseNodeBin()->pnode2;
  7878. if (propertyNode->nop == knopName)
  7879. {
  7880. propertyNode->AsParseNodePid()->pid->PromoteAssignmentState();
  7881. }
  7882. }
  7883. }
  7884. }
  7885. }
  7886. return pnode;
  7887. }
  7888. template<bool buildAST>
  7889. void Parser::TrackAssignment(ParseNodePtr pnodeT, IdentToken* pToken)
  7890. {
  7891. if (buildAST)
  7892. {
  7893. Assert(pnodeT != nullptr);
  7894. if (pnodeT->nop == knopName)
  7895. {
  7896. PidRefStack *ref = pnodeT->AsParseNodePid()->pid->GetTopRef();
  7897. Assert(ref);
  7898. ref->isAsg = true;
  7899. }
  7900. }
  7901. else
  7902. {
  7903. Assert(pToken != nullptr);
  7904. if (pToken->tk == tkID)
  7905. {
  7906. PidRefStack *ref = pToken->pid->GetTopRef();
  7907. Assert(ref);
  7908. ref->isAsg = true;
  7909. }
  7910. }
  7911. }
  7912. void ParseNodePid::SetSymRef(PidRefStack *ref)
  7913. {
  7914. Assert(symRef == nullptr);
  7915. this->symRef = ref->GetSymRef();
  7916. }
  7917. Js::PropertyId ParseNodePid::PropertyIdFromNameNode() const
  7918. {
  7919. Js::PropertyId propertyId;
  7920. Symbol *sym = this->sym;
  7921. if (sym)
  7922. {
  7923. propertyId = sym->GetPosition();
  7924. }
  7925. else
  7926. {
  7927. propertyId = this->pid->GetPropertyId();
  7928. }
  7929. return propertyId;
  7930. }
  7931. PidRefStack* Parser::PushPidRef(IdentPtr pid)
  7932. {
  7933. if (PHASE_ON1(Js::ParallelParsePhase))
  7934. {
  7935. // NOTE: the phase check is here to protect perf. See OSG 1020424.
  7936. // In some LS AST-rewrite cases we lose a lot of perf searching the PID ref stack rather
  7937. // than just pushing on the top. This hasn't shown up as a perf issue in non-LS benchmarks.
  7938. return pid->FindOrAddPidRef(&m_nodeAllocator, GetCurrentBlock()->AsParseNodeBlock()->blockId, GetCurrentFunctionNode()->AsParseNodeFnc()->functionId);
  7939. }
  7940. Assert(GetCurrentBlock() != nullptr);
  7941. AssertMsg(pid != nullptr, "PID should be created");
  7942. PidRefStack *ref = pid->GetTopRef(m_nextBlockId - 1);
  7943. int blockId = GetCurrentBlock()->AsParseNodeBlock()->blockId;
  7944. int funcId = GetCurrentFunctionNode()->AsParseNodeFnc()->functionId;
  7945. if (!ref || (ref->GetScopeId() < blockId))
  7946. {
  7947. ref = Anew(&m_nodeAllocator, PidRefStack);
  7948. if (ref == nullptr)
  7949. {
  7950. Error(ERRnoMemory);
  7951. }
  7952. pid->PushPidRef(blockId, funcId, ref);
  7953. }
  7954. else if (m_reparsingLambdaParams)
  7955. {
  7956. // If we're reparsing params, then we may have pid refs left behind from the first pass. Make sure we're
  7957. // working with the right ref at this point.
  7958. ref = this->FindOrAddPidRef(pid, blockId, funcId);
  7959. // Fix up the function ID if we're reparsing lambda parameters.
  7960. ref->funcId = funcId;
  7961. }
  7962. return ref;
  7963. }
  7964. PidRefStack* Parser::FindOrAddPidRef(IdentPtr pid, int scopeId, Js::LocalFunctionId funcId)
  7965. {
  7966. PidRefStack *ref = pid->FindOrAddPidRef(&m_nodeAllocator, scopeId, funcId);
  7967. if (ref == NULL)
  7968. {
  7969. Error(ERRnoMemory);
  7970. }
  7971. return ref;
  7972. }
  7973. void Parser::RemovePrevPidRef(IdentPtr pid, PidRefStack *ref)
  7974. {
  7975. PidRefStack *prevRef = pid->RemovePrevPidRef(ref);
  7976. Assert(prevRef);
  7977. if (prevRef->GetSym() == nullptr)
  7978. {
  7979. AllocatorDelete(ArenaAllocator, &m_nodeAllocator, prevRef);
  7980. }
  7981. }
  7982. void Parser::SetPidRefsInScopeDynamic(IdentPtr pid, int blockId)
  7983. {
  7984. PidRefStack *ref = pid->GetTopRef();
  7985. while (ref && ref->GetScopeId() >= blockId)
  7986. {
  7987. ref->SetDynamicBinding();
  7988. ref = ref->prev;
  7989. }
  7990. }
  7991. ParseNode* Parser::GetFunctionBlock()
  7992. {
  7993. Assert(m_currentBlockInfo != nullptr);
  7994. return m_currentBlockInfo->pBlockInfoFunction->pnodeBlock;
  7995. }
  7996. ParseNode* Parser::GetCurrentBlock()
  7997. {
  7998. return m_currentBlockInfo != nullptr ? m_currentBlockInfo->pnodeBlock : nullptr;
  7999. }
  8000. BlockInfoStack* Parser::GetCurrentBlockInfo()
  8001. {
  8002. return m_currentBlockInfo;
  8003. }
  8004. BlockInfoStack* Parser::GetCurrentFunctionBlockInfo()
  8005. {
  8006. return m_currentBlockInfo->pBlockInfoFunction;
  8007. }
  8008. /***************************************************************************
  8009. Parse a variable declaration.
  8010. 'fAllowIn' indicates if the 'in' operator should be allowed in the initializing
  8011. expression ( it is not allowed in the context of the first expression in a 'for' loop).
  8012. ***************************************************************************/
  8013. template<bool buildAST>
  8014. ParseNodePtr Parser::ParseVariableDeclaration(
  8015. tokens declarationType, charcount_t ichMin,
  8016. BOOL fAllowIn/* = TRUE*/,
  8017. BOOL* pfForInOk/* = nullptr*/,
  8018. BOOL singleDefOnly/* = FALSE*/,
  8019. BOOL allowInit/* = TRUE*/,
  8020. BOOL isTopVarParse/* = TRUE*/,
  8021. BOOL isFor/* = FALSE*/,
  8022. BOOL* nativeForOk /*= nullptr*/)
  8023. {
  8024. ParseNodePtr pnodeThis = nullptr;
  8025. ParseNodePtr pnodeInit;
  8026. ParseNodePtr pnodeList = nullptr;
  8027. ParseNodePtr *lastNodeRef = nullptr;
  8028. LPCOLESTR pNameHint = nullptr;
  8029. uint32 nameHintLength = 0;
  8030. uint32 nameHintOffset = 0;
  8031. Assert(declarationType == tkVAR || declarationType == tkCONST || declarationType == tkLET);
  8032. for (;;)
  8033. {
  8034. if (IsES6DestructuringEnabled() && IsPossiblePatternStart())
  8035. {
  8036. pnodeThis = ParseDestructuredLiteral<buildAST>(declarationType, true, !!isTopVarParse, DIC_None, !!fAllowIn, pfForInOk, nativeForOk);
  8037. if (pnodeThis != nullptr)
  8038. {
  8039. pnodeThis->ichMin = ichMin;
  8040. }
  8041. }
  8042. else
  8043. {
  8044. if (m_token.tk != tkID)
  8045. {
  8046. IdentifierExpectedError(m_token);
  8047. }
  8048. IdentPtr pid = m_token.GetIdentifier(m_phtbl);
  8049. Assert(pid);
  8050. pNameHint = pid->Psz();
  8051. nameHintLength = pid->Cch();
  8052. nameHintOffset = 0;
  8053. if (pid == wellKnownPropertyPids.let && (declarationType == tkCONST || declarationType == tkLET))
  8054. {
  8055. Error(ERRLetIDInLexicalDecl, pnodeThis);
  8056. }
  8057. if (declarationType == tkVAR)
  8058. {
  8059. pnodeThis = CreateVarDeclNode(pid, STVariable);
  8060. }
  8061. else if (declarationType == tkCONST)
  8062. {
  8063. pnodeThis = CreateBlockScopedDeclNode(pid, knopConstDecl);
  8064. CHAKRATEL_LANGSTATS_INC_LANGFEATURECOUNT(ES6, Const, m_scriptContext);
  8065. }
  8066. else
  8067. {
  8068. pnodeThis = CreateBlockScopedDeclNode(pid, knopLetDecl);
  8069. CHAKRATEL_LANGSTATS_INC_LANGFEATURECOUNT(ES6, Let, m_scriptContext);
  8070. }
  8071. if (pid == wellKnownPropertyPids.arguments)
  8072. {
  8073. // This var declaration may change the way an 'arguments' identifier in the function is resolved
  8074. if (declarationType == tkVAR)
  8075. {
  8076. GetCurrentFunctionNode()->grfpn |= PNodeFlags::fpnArguments_varDeclaration;
  8077. }
  8078. else
  8079. {
  8080. if (GetCurrentBlockInfo()->pnodeBlock->AsParseNodeBlock()->blockType == Function)
  8081. {
  8082. // Only override arguments if we are at the function block level.
  8083. GetCurrentFunctionNode()->grfpn |= PNodeFlags::fpnArguments_overriddenByDecl;
  8084. }
  8085. }
  8086. }
  8087. if (pnodeThis)
  8088. {
  8089. pnodeThis->ichMin = ichMin;
  8090. }
  8091. m_pscan->Scan();
  8092. if (m_token.tk == tkAsg)
  8093. {
  8094. if (!allowInit)
  8095. {
  8096. Error(ERRUnexpectedDefault);
  8097. }
  8098. if (pfForInOk && (declarationType == tkLET || declarationType == tkCONST || IsStrictMode()))
  8099. {
  8100. *pfForInOk = FALSE;
  8101. }
  8102. m_pscan->Scan();
  8103. pnodeInit = ParseExpr<buildAST>(koplCma, nullptr, fAllowIn, FALSE, pNameHint, &nameHintLength, &nameHintOffset);
  8104. if (buildAST)
  8105. {
  8106. AnalysisAssert(pnodeThis);
  8107. pnodeThis->AsParseNodeVar()->pnodeInit = pnodeInit;
  8108. pnodeThis->ichLim = pnodeInit->ichLim;
  8109. if (pnodeInit->nop == knopFncDecl)
  8110. {
  8111. Assert(nameHintLength >= nameHintOffset);
  8112. pnodeInit->AsParseNodeFnc()->hint = pNameHint;
  8113. pnodeInit->AsParseNodeFnc()->hintLength = nameHintLength;
  8114. pnodeInit->AsParseNodeFnc()->hintOffset = nameHintOffset;
  8115. pnodeThis->AsParseNodeVar()->pid->GetTopRef()->isFuncAssignment = true;
  8116. }
  8117. else
  8118. {
  8119. this->CheckArguments(pnodeInit);
  8120. }
  8121. pNameHint = nullptr;
  8122. }
  8123. //Track var a =, let a= , const a =
  8124. // This is for FixedFields Constant Heuristics
  8125. if (pnodeThis && pnodeThis->AsParseNodeVar()->pnodeInit != nullptr)
  8126. {
  8127. pnodeThis->AsParseNodeVar()->sym->PromoteAssignmentState();
  8128. }
  8129. }
  8130. else if (declarationType == tkCONST /*pnodeThis->nop == knopConstDecl*/
  8131. && !singleDefOnly
  8132. && !(isFor && TokIsForInOrForOf()))
  8133. {
  8134. Error(ERRUninitializedConst);
  8135. }
  8136. if (m_currentNodeFunc && pnodeThis && pnodeThis->AsParseNodeVar()->sym->GetIsFormal())
  8137. {
  8138. m_currentNodeFunc->AsParseNodeFnc()->SetHasAnyWriteToFormals(true);
  8139. }
  8140. }
  8141. if (singleDefOnly)
  8142. {
  8143. return pnodeThis;
  8144. }
  8145. if (buildAST)
  8146. {
  8147. AddToNodeListEscapedUse(&pnodeList, &lastNodeRef, pnodeThis);
  8148. }
  8149. if (m_token.tk != tkComma)
  8150. {
  8151. return pnodeList;
  8152. }
  8153. if (pfForInOk)
  8154. {
  8155. // don't allow "for (var a, b in c)"
  8156. *pfForInOk = FALSE;
  8157. }
  8158. m_pscan->Scan();
  8159. ichMin = m_pscan->IchMinTok();
  8160. }
  8161. }
  8162. /***************************************************************************
  8163. Parse try-catch-finally statement
  8164. ***************************************************************************/
  8165. // The try-catch-finally tree nests the try-catch within a try-finally.
  8166. // This matches the new runtime implementation.
  8167. template<bool buildAST>
  8168. ParseNodePtr Parser::ParseTryCatchFinally()
  8169. {
  8170. this->m_tryCatchOrFinallyDepth++;
  8171. ParseNodePtr pnodeT = ParseTry<buildAST>();
  8172. ParseNodePtr pnodeTC = nullptr;
  8173. StmtNest stmt;
  8174. bool hasCatch = false;
  8175. if (tkCATCH == m_token.tk)
  8176. {
  8177. hasCatch = true;
  8178. if (buildAST)
  8179. {
  8180. pnodeTC = CreateNodeWithScanner<knopTryCatch>();
  8181. pnodeT->AsParseNodeStmt()->pnodeOuter = pnodeTC;
  8182. pnodeTC->AsParseNodeTryCatch()->pnodeTry = pnodeT;
  8183. }
  8184. PushStmt<buildAST>(&stmt, pnodeTC, knopTryCatch, nullptr);
  8185. ParseNodePtr pnodeCatch = ParseCatch<buildAST>();
  8186. if (buildAST)
  8187. {
  8188. pnodeTC->AsParseNodeTryCatch()->pnodeCatch = pnodeCatch;
  8189. }
  8190. PopStmt(&stmt);
  8191. }
  8192. if (tkFINALLY != m_token.tk)
  8193. {
  8194. if (!hasCatch)
  8195. {
  8196. Error(ERRnoCatch);
  8197. }
  8198. Assert(!buildAST || pnodeTC);
  8199. this->m_tryCatchOrFinallyDepth--;
  8200. return pnodeTC;
  8201. }
  8202. ParseNodePtr pnodeTF = nullptr;
  8203. if (buildAST)
  8204. {
  8205. pnodeTF = CreateNode(knopTryFinally);
  8206. }
  8207. PushStmt<buildAST>(&stmt, pnodeTF, knopTryFinally, nullptr);
  8208. ParseNodePtr pnodeFinally = ParseFinally<buildAST>();
  8209. if (buildAST)
  8210. {
  8211. if (!hasCatch)
  8212. {
  8213. pnodeTF->AsParseNodeTryFinally()->pnodeTry = pnodeT;
  8214. pnodeT->AsParseNodeStmt()->pnodeOuter = pnodeTF;
  8215. }
  8216. else
  8217. {
  8218. pnodeTF->AsParseNodeTryFinally()->pnodeTry = CreateNode(knopTry);
  8219. pnodeTF->AsParseNodeTryFinally()->pnodeTry->AsParseNodeStmt()->pnodeOuter = pnodeTF;
  8220. pnodeTF->AsParseNodeTryFinally()->pnodeTry->AsParseNodeTry()->pnodeBody = pnodeTC;
  8221. pnodeTC->AsParseNodeStmt()->pnodeOuter = pnodeTF->AsParseNodeTryFinally()->pnodeTry;
  8222. }
  8223. pnodeTF->AsParseNodeTryFinally()->pnodeFinally = pnodeFinally;
  8224. }
  8225. PopStmt(&stmt);
  8226. this->m_tryCatchOrFinallyDepth--;
  8227. return pnodeTF;
  8228. }
  8229. template<bool buildAST>
  8230. ParseNodePtr Parser::ParseTry()
  8231. {
  8232. ParseNodePtr pnode = nullptr;
  8233. StmtNest stmt;
  8234. Assert(tkTRY == m_token.tk);
  8235. if (buildAST)
  8236. {
  8237. pnode = CreateNode(knopTry);
  8238. }
  8239. m_pscan->Scan();
  8240. if (tkLCurly != m_token.tk)
  8241. {
  8242. Error(ERRnoLcurly);
  8243. }
  8244. PushStmt<buildAST>(&stmt, pnode, knopTry, nullptr);
  8245. ParseNodePtr pnodeBody = ParseStatement<buildAST>();
  8246. if (buildAST)
  8247. {
  8248. pnode->AsParseNodeTry()->pnodeBody = pnodeBody;
  8249. if (pnode->AsParseNodeTry()->pnodeBody)
  8250. pnode->ichLim = pnode->AsParseNodeTry()->pnodeBody->ichLim;
  8251. }
  8252. PopStmt(&stmt);
  8253. return pnode;
  8254. }
  8255. template<bool buildAST>
  8256. ParseNodePtr Parser::ParseFinally()
  8257. {
  8258. ParseNodePtr pnode = nullptr;
  8259. StmtNest stmt;
  8260. Assert(tkFINALLY == m_token.tk);
  8261. if (buildAST)
  8262. {
  8263. pnode = CreateNode(knopFinally);
  8264. }
  8265. m_pscan->Scan();
  8266. if (tkLCurly != m_token.tk)
  8267. {
  8268. Error(ERRnoLcurly);
  8269. }
  8270. PushStmt<buildAST>(&stmt, pnode, knopFinally, nullptr);
  8271. ParseNodePtr pnodeBody = ParseStatement<buildAST>();
  8272. if (buildAST)
  8273. {
  8274. pnode->AsParseNodeFinally()->pnodeBody = pnodeBody;
  8275. if (!pnode->AsParseNodeFinally()->pnodeBody)
  8276. // Will only occur due to error correction.
  8277. pnode->AsParseNodeFinally()->pnodeBody = CreateNodeWithScanner<knopEmpty>();
  8278. else
  8279. pnode->ichLim = pnode->AsParseNodeFinally()->pnodeBody->ichLim;
  8280. }
  8281. PopStmt(&stmt);
  8282. return pnode;
  8283. }
  8284. template<bool buildAST>
  8285. ParseNodePtr Parser::ParseCatch()
  8286. {
  8287. ParseNodePtr rootNode = nullptr;
  8288. ParseNodePtr* ppnode = &rootNode;
  8289. ParseNodePtr *ppnodeExprScopeSave = nullptr;
  8290. ParseNodePtr pnode = nullptr;
  8291. ParseNodePtr pnodeCatchScope = nullptr;
  8292. StmtNest stmt;
  8293. IdentPtr pidCatch = nullptr;
  8294. //while (tkCATCH == m_token.tk)
  8295. if (tkCATCH == m_token.tk)
  8296. {
  8297. charcount_t ichMin;
  8298. if (buildAST)
  8299. {
  8300. ichMin = m_pscan->IchMinTok();
  8301. }
  8302. m_pscan->Scan(); //catch
  8303. ChkCurTok(tkLParen, ERRnoLparen); //catch(
  8304. bool isPattern = false;
  8305. if (tkID != m_token.tk)
  8306. {
  8307. isPattern = IsES6DestructuringEnabled() && IsPossiblePatternStart();
  8308. if (!isPattern)
  8309. {
  8310. IdentifierExpectedError(m_token);
  8311. }
  8312. }
  8313. if (buildAST)
  8314. {
  8315. pnode = CreateNodeWithScanner<knopCatch>(ichMin);
  8316. PushStmt<buildAST>(&stmt, pnode, knopCatch, nullptr);
  8317. *ppnode = pnode;
  8318. ppnode = &pnode->AsParseNodeCatch()->pnodeNext;
  8319. *ppnode = nullptr;
  8320. }
  8321. pnodeCatchScope = StartParseBlock<buildAST>(PnodeBlockType::Regular, isPattern ? ScopeType_CatchParamPattern : ScopeType_Catch);
  8322. if (buildAST)
  8323. {
  8324. // Add this catch to the current scope list.
  8325. if (m_ppnodeExprScope)
  8326. {
  8327. Assert(*m_ppnodeExprScope == nullptr);
  8328. *m_ppnodeExprScope = pnode;
  8329. m_ppnodeExprScope = &pnode->AsParseNodeCatch()->pnodeNext;
  8330. }
  8331. else
  8332. {
  8333. Assert(m_ppnodeScope);
  8334. Assert(*m_ppnodeScope == nullptr);
  8335. *m_ppnodeScope = pnode;
  8336. m_ppnodeScope = &pnode->AsParseNodeCatch()->pnodeNext;
  8337. }
  8338. // Keep a list of function expressions (not declarations) at this scope.
  8339. ppnodeExprScopeSave = m_ppnodeExprScope;
  8340. m_ppnodeExprScope = &pnode->AsParseNodeCatch()->pnodeScopes;
  8341. pnode->AsParseNodeCatch()->pnodeScopes = nullptr;
  8342. }
  8343. if (isPattern)
  8344. {
  8345. ParseNodePtr pnodePattern = ParseDestructuredLiteral<buildAST>(tkLET, true /*isDecl*/, true /*topLevel*/, DIC_ForceErrorOnInitializer);
  8346. if (buildAST)
  8347. {
  8348. pnode->AsParseNodeCatch()->pnodeParam = CreateParamPatternNode(pnodePattern);
  8349. Scope *scope = pnodeCatchScope->AsParseNodeBlock()->scope;
  8350. pnode->AsParseNodeCatch()->scope = scope;
  8351. }
  8352. }
  8353. else
  8354. {
  8355. if (IsStrictMode())
  8356. {
  8357. IdentPtr pid = m_token.GetIdentifier(m_phtbl);
  8358. if (pid == wellKnownPropertyPids.eval)
  8359. {
  8360. Error(ERREvalUsage);
  8361. }
  8362. else if (pid == wellKnownPropertyPids.arguments)
  8363. {
  8364. Error(ERRArgsUsage);
  8365. }
  8366. }
  8367. pidCatch = m_token.GetIdentifier(m_phtbl);
  8368. PidRefStack *ref = this->FindOrAddPidRef(pidCatch, GetCurrentBlock()->AsParseNodeBlock()->blockId, GetCurrentFunctionNode()->AsParseNodeFnc()->functionId);
  8369. ParseNodePtr pnodeParam = CreateNameNode(pidCatch);
  8370. pnodeParam->AsParseNodePid()->symRef = ref->GetSymRef();
  8371. const char16 *name = reinterpret_cast<const char16*>(pidCatch->Psz());
  8372. int nameLength = pidCatch->Cch();
  8373. SymbolName const symName(name, nameLength);
  8374. Symbol *sym = Anew(&m_nodeAllocator, Symbol, symName, pnodeParam, STVariable);
  8375. if (sym == nullptr)
  8376. {
  8377. Error(ERRnoMemory);
  8378. }
  8379. sym->SetPid(pidCatch);
  8380. Assert(ref->GetSym() == nullptr);
  8381. ref->SetSym(sym);
  8382. Scope *scope = pnodeCatchScope->AsParseNodeBlock()->scope;
  8383. scope->AddNewSymbol(sym);
  8384. if (buildAST)
  8385. {
  8386. pnode->AsParseNodeCatch()->pnodeParam = pnodeParam;
  8387. pnode->AsParseNodeCatch()->scope = scope;
  8388. }
  8389. m_pscan->Scan();
  8390. }
  8391. charcount_t ichLim;
  8392. if (buildAST)
  8393. {
  8394. ichLim = m_pscan->IchLimTok();
  8395. }
  8396. ChkCurTok(tkRParen, ERRnoRparen); //catch(id[:expr])
  8397. if (tkLCurly != m_token.tk)
  8398. {
  8399. Error(ERRnoLcurly);
  8400. }
  8401. ParseNodePtr pnodeBody = ParseStatement<buildAST>(); //catch(id[:expr]) {block}
  8402. if (buildAST)
  8403. {
  8404. pnode->AsParseNodeCatch()->pnodeBody = pnodeBody;
  8405. pnode->ichLim = ichLim;
  8406. }
  8407. if (pnodeCatchScope != nullptr)
  8408. {
  8409. FinishParseBlock(pnodeCatchScope);
  8410. }
  8411. if (pnodeCatchScope->AsParseNodeBlock()->GetCallsEval() || pnodeCatchScope->AsParseNodeBlock()->GetChildCallsEval())
  8412. {
  8413. GetCurrentBlock()->AsParseNodeBlock()->SetChildCallsEval(true);
  8414. }
  8415. if (buildAST)
  8416. {
  8417. PopStmt(&stmt);
  8418. // Restore the lists of function expression scopes.
  8419. AssertMem(m_ppnodeExprScope);
  8420. Assert(*m_ppnodeExprScope == nullptr);
  8421. m_ppnodeExprScope = ppnodeExprScopeSave;
  8422. }
  8423. }
  8424. return rootNode;
  8425. }
  8426. template<bool buildAST>
  8427. ParseNodePtr Parser::ParseCase(ParseNodePtr *ppnodeBody)
  8428. {
  8429. ParseNodePtr pnodeT = nullptr;
  8430. charcount_t ichMinT = m_pscan->IchMinTok();
  8431. m_pscan->Scan();
  8432. ParseNodePtr pnodeExpr = ParseExpr<buildAST>();
  8433. charcount_t ichLim = m_pscan->IchLimTok();
  8434. ChkCurTok(tkColon, ERRnoColon);
  8435. if (buildAST)
  8436. {
  8437. pnodeT = CreateNodeWithScanner<knopCase>(ichMinT);
  8438. pnodeT->AsParseNodeCase()->pnodeExpr = pnodeExpr;
  8439. pnodeT->ichLim = ichLim;
  8440. }
  8441. ParseStmtList<buildAST>(ppnodeBody);
  8442. return pnodeT;
  8443. }
  8444. /***************************************************************************
  8445. Parse a single statement. Digest a trailing semicolon.
  8446. ***************************************************************************/
  8447. template<bool buildAST>
  8448. ParseNodePtr Parser::ParseStatement()
  8449. {
  8450. ParseNodePtr *ppnodeT;
  8451. ParseNodePtr pnodeT;
  8452. ParseNodePtr pnode = nullptr;
  8453. LabelId* pLabelIdList = nullptr;
  8454. charcount_t ichMin = 0;
  8455. size_t iecpMin = 0;
  8456. StmtNest stmt;
  8457. StmtNest *pstmt;
  8458. BOOL fForInOrOfOkay;
  8459. BOOL fCanAssign;
  8460. IdentPtr pid;
  8461. uint fnop;
  8462. bool expressionStmt = false;
  8463. bool isAsyncMethod = false;
  8464. tokens tok;
  8465. #if EXCEPTION_RECOVERY
  8466. ParseNodePtr pParentTryCatch = nullptr;
  8467. ParseNodePtr pTryBlock = nullptr;
  8468. ParseNodePtr pTry = nullptr;
  8469. ParseNodePtr pParentTryCatchBlock = nullptr;
  8470. StmtNest stmtTryCatchBlock;
  8471. StmtNest stmtTryCatch;
  8472. StmtNest stmtTry;
  8473. StmtNest stmtTryBlock;
  8474. #endif
  8475. if (buildAST)
  8476. {
  8477. #if EXCEPTION_RECOVERY
  8478. if(Js::Configuration::Global.flags.SwallowExceptions)
  8479. {
  8480. // If we're swallowing exceptions, surround this statement with a try/catch block:
  8481. //
  8482. // Before: x.y = 3;
  8483. // After: try { x.y = 3; } catch(__ehobj) { }
  8484. //
  8485. // This is done to force the runtime to recover from exceptions at the most granular
  8486. // possible point. Recovering from EH dramatically improves coverage of testing via
  8487. // fault injection.
  8488. // create and push the try-catch node
  8489. pParentTryCatchBlock = CreateBlockNode();
  8490. PushStmt<buildAST>(&stmtTryCatchBlock, pParentTryCatchBlock, knopBlock, nullptr);
  8491. pParentTryCatch = CreateNodeWithScanner<knopTryCatch>();
  8492. PushStmt<buildAST>(&stmtTryCatch, pParentTryCatch, knopTryCatch, nullptr);
  8493. // create and push a try node
  8494. pTry = CreateNodeWithScanner<knopTry>();
  8495. PushStmt<buildAST>(&stmtTry, pTry, knopTry, nullptr);
  8496. pTryBlock = CreateBlockNode();
  8497. PushStmt<buildAST>(&stmtTryBlock, pTryBlock, knopBlock, nullptr);
  8498. // these nodes will be closed after the statement is parsed.
  8499. }
  8500. #endif // EXCEPTION_RECOVERY
  8501. }
  8502. EnsureStackAvailable();
  8503. LRestart:
  8504. tok = m_token.tk;
  8505. switch (tok)
  8506. {
  8507. case tkEOF:
  8508. if (buildAST)
  8509. {
  8510. pnode = nullptr;
  8511. }
  8512. break;
  8513. case tkFUNCTION:
  8514. {
  8515. LFunctionStatement:
  8516. if (m_grfscr & fscrDeferredFncExpression)
  8517. {
  8518. // The top-level deferred function body was defined by a function expression whose parsing was deferred. We are now
  8519. // parsing it, so unset the flag so that any nested functions are parsed normally. This flag is only applicable the
  8520. // first time we see it.
  8521. m_grfscr &= ~fscrDeferredFncExpression;
  8522. pnode = ParseFncDecl<buildAST>(isAsyncMethod ? fFncAsync : fFncNoFlgs, nullptr);
  8523. }
  8524. else
  8525. {
  8526. pnode = ParseFncDecl<buildAST>(fFncDeclaration | (isAsyncMethod ? fFncAsync : fFncNoFlgs), nullptr);
  8527. }
  8528. if (isAsyncMethod)
  8529. {
  8530. pnode->AsParseNodeFnc()->cbMin = iecpMin;
  8531. pnode->ichMin = ichMin;
  8532. }
  8533. break;
  8534. }
  8535. case tkCLASS:
  8536. if (m_scriptContext->GetConfig()->IsES6ClassAndExtendsEnabled())
  8537. {
  8538. pnode = ParseClassDecl<buildAST>(TRUE, nullptr, nullptr, nullptr);
  8539. }
  8540. else
  8541. {
  8542. goto LDefaultToken;
  8543. }
  8544. break;
  8545. case tkID:
  8546. if (m_token.GetIdentifier(m_phtbl) == wellKnownPropertyPids.let)
  8547. {
  8548. // We see "let" at the start of a statement. This could either be a declaration or an identifier
  8549. // reference. The next token determines which.
  8550. RestorePoint parsedLet;
  8551. m_pscan->Capture(&parsedLet);
  8552. ichMin = m_pscan->IchMinTok();
  8553. m_pscan->Scan();
  8554. if (this->NextTokenConfirmsLetDecl())
  8555. {
  8556. pnode = ParseVariableDeclaration<buildAST>(tkLET, ichMin);
  8557. goto LNeedTerminator;
  8558. }
  8559. m_pscan->SeekTo(parsedLet);
  8560. }
  8561. else if (m_token.GetIdentifier(m_phtbl) == wellKnownPropertyPids.async && m_scriptContext->GetConfig()->IsES7AsyncAndAwaitEnabled())
  8562. {
  8563. RestorePoint parsedAsync;
  8564. m_pscan->Capture(&parsedAsync);
  8565. ichMin = m_pscan->IchMinTok();
  8566. iecpMin = m_pscan->IecpMinTok();
  8567. m_pscan->Scan();
  8568. if (m_token.tk == tkFUNCTION && !m_pscan->FHadNewLine())
  8569. {
  8570. isAsyncMethod = true;
  8571. goto LFunctionStatement;
  8572. }
  8573. m_pscan->SeekTo(parsedAsync);
  8574. }
  8575. goto LDefaultToken;
  8576. case tkCONST:
  8577. case tkLET:
  8578. ichMin = m_pscan->IchMinTok();
  8579. m_pscan->Scan();
  8580. pnode = ParseVariableDeclaration<buildAST>(tok, ichMin);
  8581. goto LNeedTerminator;
  8582. case tkVAR:
  8583. ichMin = m_pscan->IchMinTok();
  8584. m_pscan->Scan();
  8585. pnode = ParseVariableDeclaration<buildAST>(tok, ichMin);
  8586. goto LNeedTerminator;
  8587. case tkFOR:
  8588. {
  8589. ParseNodePtr pnodeBlock = nullptr;
  8590. ParseNodePtr *ppnodeScopeSave = nullptr;
  8591. ParseNodePtr *ppnodeExprScopeSave = nullptr;
  8592. ichMin = m_pscan->IchMinTok();
  8593. ChkNxtTok(tkLParen, ERRnoLparen);
  8594. pnodeBlock = StartParseBlock<buildAST>(PnodeBlockType::Regular, ScopeType_Block);
  8595. if (buildAST)
  8596. {
  8597. PushFuncBlockScope(pnodeBlock, &ppnodeScopeSave, &ppnodeExprScopeSave);
  8598. }
  8599. RestorePoint startExprOrIdentifier;
  8600. fForInOrOfOkay = TRUE;
  8601. fCanAssign = TRUE;
  8602. tok = m_token.tk;
  8603. BOOL nativeForOkay = TRUE;
  8604. switch (tok)
  8605. {
  8606. case tkID:
  8607. if (m_token.GetIdentifier(m_phtbl) == wellKnownPropertyPids.let)
  8608. {
  8609. // We see "let" in the init part of a for loop. This could either be a declaration or an identifier
  8610. // reference. The next token determines which.
  8611. RestorePoint parsedLet;
  8612. m_pscan->Capture(&parsedLet);
  8613. auto ichMinInner = m_pscan->IchMinTok();
  8614. m_pscan->Scan();
  8615. if (IsPossiblePatternStart())
  8616. {
  8617. m_pscan->Capture(&startExprOrIdentifier);
  8618. }
  8619. if (this->NextTokenConfirmsLetDecl() && m_token.tk != tkIN)
  8620. {
  8621. pnodeT = ParseVariableDeclaration<buildAST>(tkLET, ichMinInner
  8622. , /*fAllowIn = */FALSE
  8623. , /*pfForInOk = */&fForInOrOfOkay
  8624. , /*singleDefOnly*/FALSE
  8625. , /*allowInit*/TRUE
  8626. , /*isTopVarParse*/TRUE
  8627. , /*isFor*/TRUE
  8628. , &nativeForOkay);
  8629. break;
  8630. }
  8631. m_pscan->SeekTo(parsedLet);
  8632. }
  8633. goto LDefaultTokenFor;
  8634. case tkLET:
  8635. case tkCONST:
  8636. case tkVAR:
  8637. {
  8638. auto ichMinInner = m_pscan->IchMinTok();
  8639. m_pscan->Scan();
  8640. if (IsPossiblePatternStart())
  8641. {
  8642. m_pscan->Capture(&startExprOrIdentifier);
  8643. }
  8644. pnodeT = ParseVariableDeclaration<buildAST>(tok, ichMinInner
  8645. , /*fAllowIn = */FALSE
  8646. , /*pfForInOk = */&fForInOrOfOkay
  8647. , /*singleDefOnly*/FALSE
  8648. , /*allowInit*/TRUE
  8649. , /*isTopVarParse*/TRUE
  8650. , /*isFor*/TRUE
  8651. , &nativeForOkay);
  8652. }
  8653. break;
  8654. case tkSColon:
  8655. pnodeT = nullptr;
  8656. fForInOrOfOkay = FALSE;
  8657. break;
  8658. default:
  8659. {
  8660. LDefaultTokenFor:
  8661. RestorePoint exprStart;
  8662. tokens beforeToken = tok;
  8663. m_pscan->Capture(&exprStart);
  8664. if (IsPossiblePatternStart())
  8665. {
  8666. m_pscan->Capture(&startExprOrIdentifier);
  8667. }
  8668. bool fLikelyPattern = false;
  8669. if (IsES6DestructuringEnabled() && (beforeToken == tkLBrack || beforeToken == tkLCurly))
  8670. {
  8671. pnodeT = ParseExpr<buildAST>(koplNo,
  8672. &fCanAssign,
  8673. /*fAllowIn = */FALSE,
  8674. /*fAllowEllipsis*/FALSE,
  8675. /*pHint*/nullptr,
  8676. /*pHintLength*/nullptr,
  8677. /*pShortNameOffset*/nullptr,
  8678. /*pToken*/nullptr,
  8679. /**fUnaryOrParen*/false,
  8680. &fLikelyPattern);
  8681. }
  8682. else
  8683. {
  8684. pnodeT = ParseExpr<buildAST>(koplNo, &fCanAssign, /*fAllowIn = */FALSE);
  8685. }
  8686. // 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
  8687. // has already converted them appropriately.
  8688. if (fLikelyPattern && TokIsForInOrForOf())
  8689. {
  8690. m_pscan->SeekTo(exprStart);
  8691. ParseDestructuredLiteralWithScopeSave(tkNone, false/*isDecl*/, false /*topLevel*/, DIC_None, false /*allowIn*/);
  8692. if (buildAST)
  8693. {
  8694. pnodeT = ConvertToPattern(pnodeT);
  8695. }
  8696. }
  8697. if (buildAST)
  8698. {
  8699. Assert(pnodeT);
  8700. pnodeT->isUsed = false;
  8701. }
  8702. }
  8703. break;
  8704. }
  8705. if (TokIsForInOrForOf())
  8706. {
  8707. bool isForOf = (m_token.tk != tkIN);
  8708. Assert(!isForOf || (m_token.tk == tkID && m_token.GetIdentifier(m_phtbl) == wellKnownPropertyPids.of));
  8709. if ((buildAST && nullptr == pnodeT) || !fForInOrOfOkay)
  8710. {
  8711. if (isForOf)
  8712. {
  8713. Error(ERRForOfNoInitAllowed);
  8714. }
  8715. else
  8716. {
  8717. Error(ERRForInNoInitAllowed);
  8718. }
  8719. }
  8720. if (!fCanAssign && PHASE_ON1(Js::EarlyReferenceErrorsPhase))
  8721. {
  8722. Error(JSERR_CantAssignTo);
  8723. }
  8724. m_pscan->Scan();
  8725. ParseNodePtr pnodeObj = ParseExpr<buildAST>(isForOf ? koplCma : koplNo);
  8726. charcount_t ichLim = m_pscan->IchLimTok();
  8727. ChkCurTok(tkRParen, ERRnoRparen);
  8728. if (buildAST)
  8729. {
  8730. if (isForOf)
  8731. {
  8732. pnode = CreateNodeWithScanner<knopForOf>(ichMin);
  8733. }
  8734. else
  8735. {
  8736. pnode = CreateNodeWithScanner<knopForIn>(ichMin);
  8737. }
  8738. pnode->AsParseNodeForInOrForOf()->pnodeBlock = pnodeBlock;
  8739. pnode->AsParseNodeForInOrForOf()->pnodeLval = pnodeT;
  8740. pnode->AsParseNodeForInOrForOf()->pnodeObj = pnodeObj;
  8741. pnode->ichLim = ichLim;
  8742. TrackAssignment<true>(pnodeT, nullptr);
  8743. }
  8744. PushStmt<buildAST>(&stmt, pnode, isForOf ? knopForOf : knopForIn, pLabelIdList);
  8745. ParseNodePtr pnodeBody = ParseStatement<buildAST>();
  8746. if (buildAST)
  8747. {
  8748. pnode->AsParseNodeForInOrForOf()->pnodeBody = pnodeBody;
  8749. }
  8750. PopStmt(&stmt);
  8751. }
  8752. else
  8753. {
  8754. if (!nativeForOkay)
  8755. {
  8756. Error(ERRDestructInit);
  8757. }
  8758. ChkCurTok(tkSColon, ERRnoSemic);
  8759. ParseNodePtr pnodeCond = nullptr;
  8760. if (m_token.tk != tkSColon)
  8761. {
  8762. pnodeCond = ParseExpr<buildAST>();
  8763. if (m_token.tk != tkSColon)
  8764. {
  8765. Error(ERRnoSemic);
  8766. }
  8767. }
  8768. tokens tk;
  8769. tk = m_pscan->Scan();
  8770. ParseNodePtr pnodeIncr = nullptr;
  8771. if (tk != tkRParen)
  8772. {
  8773. pnodeIncr = ParseExpr<buildAST>();
  8774. if(pnodeIncr)
  8775. {
  8776. pnodeIncr->isUsed = false;
  8777. }
  8778. }
  8779. charcount_t ichLim = m_pscan->IchLimTok();
  8780. ChkCurTok(tkRParen, ERRnoRparen);
  8781. if (buildAST)
  8782. {
  8783. pnode = CreateNodeWithScanner<knopFor>(ichMin);
  8784. pnode->AsParseNodeFor()->pnodeBlock = pnodeBlock;
  8785. pnode->AsParseNodeFor()->pnodeInverted= nullptr;
  8786. pnode->AsParseNodeFor()->pnodeInit = pnodeT;
  8787. pnode->AsParseNodeFor()->pnodeCond = pnodeCond;
  8788. pnode->AsParseNodeFor()->pnodeIncr = pnodeIncr;
  8789. pnode->ichLim = ichLim;
  8790. }
  8791. PushStmt<buildAST>(&stmt, pnode, knopFor, pLabelIdList);
  8792. ParseNodePtr pnodeBody = ParseStatement<buildAST>();
  8793. if (buildAST)
  8794. {
  8795. pnode->AsParseNodeFor()->pnodeBody = pnodeBody;
  8796. }
  8797. PopStmt(&stmt);
  8798. }
  8799. if (buildAST)
  8800. {
  8801. PopFuncBlockScope(ppnodeScopeSave, ppnodeExprScopeSave);
  8802. }
  8803. FinishParseBlock(pnodeBlock);
  8804. break;
  8805. }
  8806. case tkSWITCH:
  8807. {
  8808. BOOL fSeenDefault = FALSE;
  8809. ParseNodePtr pnodeBlock = nullptr;
  8810. ParseNodePtr *ppnodeScopeSave = nullptr;
  8811. ParseNodePtr *ppnodeExprScopeSave = nullptr;
  8812. ichMin = m_pscan->IchMinTok();
  8813. ChkNxtTok(tkLParen, ERRnoLparen);
  8814. ParseNodePtr pnodeVal = ParseExpr<buildAST>();
  8815. charcount_t ichLim = m_pscan->IchLimTok();
  8816. ChkCurTok(tkRParen, ERRnoRparen);
  8817. ChkCurTok(tkLCurly, ERRnoLcurly);
  8818. if (buildAST)
  8819. {
  8820. pnode = CreateNodeWithScanner<knopSwitch>(ichMin);
  8821. }
  8822. PushStmt<buildAST>(&stmt, pnode, knopSwitch, pLabelIdList);
  8823. pnodeBlock = StartParseBlock<buildAST>(PnodeBlockType::Regular, ScopeType_Block);
  8824. if (buildAST)
  8825. {
  8826. pnode->AsParseNodeSwitch()->pnodeVal = pnodeVal;
  8827. pnode->AsParseNodeSwitch()->pnodeBlock = pnodeBlock;
  8828. pnode->ichLim = ichLim;
  8829. PushFuncBlockScope(pnode->AsParseNodeSwitch()->pnodeBlock, &ppnodeScopeSave, &ppnodeExprScopeSave);
  8830. pnode->AsParseNodeSwitch()->pnodeDefault = nullptr;
  8831. ppnodeT = &pnode->AsParseNodeSwitch()->pnodeCases;
  8832. }
  8833. for (;;)
  8834. {
  8835. ParseNodePtr pnodeBody = nullptr;
  8836. switch (m_token.tk)
  8837. {
  8838. default:
  8839. goto LEndSwitch;
  8840. case tkCASE:
  8841. {
  8842. pnodeT = this->ParseCase<buildAST>(&pnodeBody);
  8843. break;
  8844. }
  8845. case tkDEFAULT:
  8846. if (fSeenDefault)
  8847. {
  8848. Error(ERRdupDefault);
  8849. // No recovery necessary since this is a semantic, not structural, error
  8850. }
  8851. fSeenDefault = TRUE;
  8852. charcount_t ichMinT = m_pscan->IchMinTok();
  8853. m_pscan->Scan();
  8854. charcount_t ichMinInner = m_pscan->IchLimTok();
  8855. ChkCurTok(tkColon, ERRnoColon);
  8856. if (buildAST)
  8857. {
  8858. pnodeT = CreateNodeWithScanner<knopCase>(ichMinT);
  8859. pnode->AsParseNodeSwitch()->pnodeDefault = pnodeT;
  8860. pnodeT->ichLim = ichMinInner;
  8861. pnodeT->AsParseNodeCase()->pnodeExpr = nullptr;
  8862. }
  8863. ParseStmtList<buildAST>(&pnodeBody);
  8864. break;
  8865. }
  8866. // Create a block node to contain the statement list for this case.
  8867. // This helps us insert byte code to return the right value from
  8868. // global/eval code.
  8869. ParseNodePtr pnodeFakeBlock = CreateBlockNode();
  8870. if (buildAST)
  8871. {
  8872. if (pnodeBody)
  8873. {
  8874. pnodeFakeBlock->ichMin = pnodeT->ichMin;
  8875. pnodeFakeBlock->ichLim = pnodeT->ichLim;
  8876. pnodeT->AsParseNodeCase()->pnodeBody = pnodeFakeBlock;
  8877. pnodeT->AsParseNodeCase()->pnodeBody->grfpn |= PNodeFlags::fpnSyntheticNode; // block is not a user specifier block
  8878. pnodeT->AsParseNodeCase()->pnodeBody->AsParseNodeBlock()->pnodeStmt = pnodeBody;
  8879. }
  8880. else
  8881. {
  8882. pnodeT->AsParseNodeCase()->pnodeBody = nullptr;
  8883. }
  8884. *ppnodeT = pnodeT;
  8885. ppnodeT = &pnodeT->AsParseNodeCase()->pnodeNext;
  8886. }
  8887. }
  8888. LEndSwitch:
  8889. ChkCurTok(tkRCurly, ERRnoRcurly);
  8890. if (buildAST)
  8891. {
  8892. *ppnodeT = nullptr;
  8893. PopFuncBlockScope(ppnodeScopeSave, ppnodeExprScopeSave);
  8894. FinishParseBlock(pnode->AsParseNodeSwitch()->pnodeBlock);
  8895. }
  8896. else
  8897. {
  8898. FinishParseBlock(pnodeBlock);
  8899. }
  8900. PopStmt(&stmt);
  8901. break;
  8902. }
  8903. case tkWHILE:
  8904. {
  8905. ichMin = m_pscan->IchMinTok();
  8906. ChkNxtTok(tkLParen, ERRnoLparen);
  8907. ParseNodePtr pnodeCond = ParseExpr<buildAST>();
  8908. charcount_t ichLim = m_pscan->IchLimTok();
  8909. ChkCurTok(tkRParen, ERRnoRparen);
  8910. if (buildAST)
  8911. {
  8912. pnode = CreateNodeWithScanner<knopWhile>(ichMin);
  8913. pnode->AsParseNodeWhile()->pnodeCond = pnodeCond;
  8914. pnode->ichLim = ichLim;
  8915. }
  8916. bool stashedDisallowImportExportStmt = m_disallowImportExportStmt;
  8917. m_disallowImportExportStmt = true;
  8918. PushStmt<buildAST>(&stmt, pnode, knopWhile, pLabelIdList);
  8919. ParseNodePtr pnodeBody = ParseStatement<buildAST>();
  8920. PopStmt(&stmt);
  8921. if (buildAST)
  8922. {
  8923. pnode->AsParseNodeWhile()->pnodeBody = pnodeBody;
  8924. }
  8925. m_disallowImportExportStmt = stashedDisallowImportExportStmt;
  8926. break;
  8927. }
  8928. case tkDO:
  8929. {
  8930. if (buildAST)
  8931. {
  8932. pnode = CreateNodeWithScanner<knopDoWhile>();
  8933. }
  8934. PushStmt<buildAST>(&stmt, pnode, knopDoWhile, pLabelIdList);
  8935. m_pscan->Scan();
  8936. bool stashedDisallowImportExportStmt = m_disallowImportExportStmt;
  8937. m_disallowImportExportStmt = true;
  8938. ParseNodePtr pnodeBody = ParseStatement<buildAST>();
  8939. m_disallowImportExportStmt = stashedDisallowImportExportStmt;
  8940. PopStmt(&stmt);
  8941. charcount_t ichMinT = m_pscan->IchMinTok();
  8942. ChkCurTok(tkWHILE, ERRnoWhile);
  8943. ChkCurTok(tkLParen, ERRnoLparen);
  8944. ParseNodePtr pnodeCond = ParseExpr<buildAST>();
  8945. charcount_t ichLim = m_pscan->IchLimTok();
  8946. ChkCurTok(tkRParen, ERRnoRparen);
  8947. if (buildAST)
  8948. {
  8949. pnode->AsParseNodeWhile()->pnodeBody = pnodeBody;
  8950. pnode->AsParseNodeWhile()->pnodeCond = pnodeCond;
  8951. pnode->ichLim = ichLim;
  8952. pnode->ichMin = ichMinT;
  8953. }
  8954. // REVIEW: Allow do...while statements to be embedded in other compound statements like if..else, or do..while?
  8955. // goto LNeedTerminator;
  8956. // For now just eat the trailing semicolon if present.
  8957. if (m_token.tk == tkSColon)
  8958. {
  8959. if (pnode)
  8960. {
  8961. pnode->grfpn |= PNodeFlags::fpnExplicitSemicolon;
  8962. }
  8963. m_pscan->Scan();
  8964. }
  8965. else if (pnode)
  8966. {
  8967. pnode->grfpn |= PNodeFlags::fpnAutomaticSemicolon;
  8968. }
  8969. break;
  8970. }
  8971. case tkIF:
  8972. {
  8973. ichMin = m_pscan->IchMinTok();
  8974. ChkNxtTok(tkLParen, ERRnoLparen);
  8975. ParseNodePtr pnodeCond = ParseExpr<buildAST>();
  8976. if (buildAST)
  8977. {
  8978. pnode = CreateNodeWithScanner<knopIf>(ichMin);
  8979. pnode->ichLim = m_pscan->IchLimTok();
  8980. pnode->AsParseNodeIf()->pnodeCond = pnodeCond;
  8981. }
  8982. ChkCurTok(tkRParen, ERRnoRparen);
  8983. bool stashedDisallowImportExportStmt = m_disallowImportExportStmt;
  8984. m_disallowImportExportStmt = true;
  8985. PushStmt<buildAST>(&stmt, pnode, knopIf, pLabelIdList);
  8986. ParseNodePtr pnodeTrue = ParseStatement<buildAST>();
  8987. ParseNodePtr pnodeFalse = nullptr;
  8988. if (m_token.tk == tkELSE)
  8989. {
  8990. m_pscan->Scan();
  8991. pnodeFalse = ParseStatement<buildAST>();
  8992. }
  8993. if (buildAST)
  8994. {
  8995. pnode->AsParseNodeIf()->pnodeTrue = pnodeTrue;
  8996. pnode->AsParseNodeIf()->pnodeFalse = pnodeFalse;
  8997. }
  8998. PopStmt(&stmt);
  8999. m_disallowImportExportStmt = stashedDisallowImportExportStmt;
  9000. break;
  9001. }
  9002. case tkTRY:
  9003. {
  9004. pnode = CreateBlockNode();
  9005. pnode->grfpn |= PNodeFlags::fpnSyntheticNode; // block is not a user specifier block
  9006. PushStmt<buildAST>(&stmt, pnode, knopBlock, pLabelIdList);
  9007. ParseNodePtr pnodeStmt = ParseTryCatchFinally<buildAST>();
  9008. if (buildAST)
  9009. {
  9010. pnode->AsParseNodeBlock()->pnodeStmt = pnodeStmt;
  9011. }
  9012. PopStmt(&stmt);
  9013. break;
  9014. }
  9015. case tkWITH:
  9016. {
  9017. if ( IsStrictMode() )
  9018. {
  9019. Error(ERRES5NoWith);
  9020. }
  9021. if (m_currentNodeFunc)
  9022. {
  9023. GetCurrentFunctionNode()->AsParseNodeFnc()->SetHasWithStmt(); // Used by DeferNested
  9024. }
  9025. ichMin = m_pscan->IchMinTok();
  9026. ChkNxtTok(tkLParen, ERRnoLparen);
  9027. ParseNodePtr pnodeObj = ParseExpr<buildAST>();
  9028. if (!buildAST)
  9029. {
  9030. m_scopeCountNoAst++;
  9031. }
  9032. charcount_t ichLim = m_pscan->IchLimTok();
  9033. ChkCurTok(tkRParen, ERRnoRparen);
  9034. if (buildAST)
  9035. {
  9036. pnode = CreateNodeWithScanner<knopWith>(ichMin);
  9037. }
  9038. PushStmt<buildAST>(&stmt, pnode, knopWith, pLabelIdList);
  9039. ParseNodePtr *ppnodeExprScopeSave = nullptr;
  9040. if (buildAST)
  9041. {
  9042. pnode->AsParseNodeWith()->pnodeObj = pnodeObj;
  9043. this->CheckArguments(pnode->AsParseNodeWith()->pnodeObj);
  9044. if (m_ppnodeExprScope)
  9045. {
  9046. Assert(*m_ppnodeExprScope == nullptr);
  9047. *m_ppnodeExprScope = pnode;
  9048. m_ppnodeExprScope = &pnode->AsParseNodeWith()->pnodeNext;
  9049. }
  9050. else
  9051. {
  9052. Assert(m_ppnodeScope);
  9053. Assert(*m_ppnodeScope == nullptr);
  9054. *m_ppnodeScope = pnode;
  9055. m_ppnodeScope = &pnode->AsParseNodeWith()->pnodeNext;
  9056. }
  9057. pnode->AsParseNodeWith()->pnodeNext = nullptr;
  9058. pnode->AsParseNodeWith()->scope = nullptr;
  9059. ppnodeExprScopeSave = m_ppnodeExprScope;
  9060. m_ppnodeExprScope = &pnode->AsParseNodeWith()->pnodeScopes;
  9061. pnode->AsParseNodeWith()->pnodeScopes = nullptr;
  9062. pnode->ichLim = ichLim;
  9063. }
  9064. PushBlockInfo(CreateBlockNode());
  9065. PushDynamicBlock();
  9066. ParseNodePtr pnodeBody = ParseStatement<buildAST>();
  9067. if (buildAST)
  9068. {
  9069. pnode->AsParseNodeWith()->pnodeBody = pnodeBody;
  9070. m_ppnodeExprScope = ppnodeExprScopeSave;
  9071. }
  9072. else
  9073. {
  9074. m_scopeCountNoAst--;
  9075. }
  9076. // The dynamic block is not stored in the actual parse tree and so will not
  9077. // be visited by the byte code generator. Grab the callsEval flag off it and
  9078. // pass on to outer block in case of:
  9079. // with (...) eval(...); // i.e. blockless form of with
  9080. bool callsEval = GetCurrentBlock()->AsParseNodeBlock()->GetCallsEval();
  9081. PopBlockInfo();
  9082. if (callsEval)
  9083. {
  9084. // be careful not to overwrite an existing true with false
  9085. GetCurrentBlock()->AsParseNodeBlock()->SetCallsEval(true);
  9086. }
  9087. PopStmt(&stmt);
  9088. break;
  9089. }
  9090. case tkLCurly:
  9091. pnode = ParseBlock<buildAST>(pLabelIdList);
  9092. break;
  9093. case tkSColon:
  9094. pnode = nullptr;
  9095. m_pscan->Scan();
  9096. break;
  9097. case tkBREAK:
  9098. if (buildAST)
  9099. {
  9100. pnode = CreateNodeWithScanner<knopBreak>();
  9101. }
  9102. fnop = fnopBreak;
  9103. goto LGetJumpStatement;
  9104. case tkCONTINUE:
  9105. if (buildAST)
  9106. {
  9107. pnode = CreateNode(knopContinue);
  9108. }
  9109. fnop = fnopContinue;
  9110. LGetJumpStatement:
  9111. m_pscan->ScanForcingPid();
  9112. if (tkID == m_token.tk && !m_pscan->FHadNewLine())
  9113. {
  9114. // Labeled break or continue.
  9115. pid = m_token.GetIdentifier(m_phtbl);
  9116. if (buildAST)
  9117. {
  9118. pnode->AsParseNodeJump()->hasExplicitTarget=true;
  9119. pnode->ichLim = m_pscan->IchLimTok();
  9120. m_pscan->Scan();
  9121. PushStmt<buildAST>(&stmt, pnode, pnode->nop, pLabelIdList);
  9122. Assert(pnode->AsParseNodeStmt()->grfnop == 0);
  9123. for (pstmt = m_pstmtCur; nullptr != pstmt; pstmt = pstmt->pstmtOuter)
  9124. {
  9125. for (LabelId* label = pstmt->pLabelId; label != nullptr; label = label->next)
  9126. {
  9127. if (pid == label->pid)
  9128. {
  9129. // Found the label. Make sure we can use it. We can
  9130. // break out of any statement, but we can only
  9131. // continue loops.
  9132. if (fnop == fnopContinue &&
  9133. !(pstmt->pnodeStmt->Grfnop() & fnop))
  9134. {
  9135. Error(ERRbadContinue);
  9136. }
  9137. else
  9138. {
  9139. pstmt->pnodeStmt->AsParseNodeStmt()->grfnop |= fnop;
  9140. pnode->AsParseNodeJump()->pnodeTarget = pstmt->pnodeStmt;
  9141. }
  9142. PopStmt(&stmt);
  9143. goto LNeedTerminator;
  9144. }
  9145. }
  9146. pnode->AsParseNodeStmt()->grfnop |=
  9147. (pstmt->pnodeStmt->Grfnop() & fnopCleanup);
  9148. }
  9149. }
  9150. else
  9151. {
  9152. m_pscan->Scan();
  9153. for (pstmt = m_pstmtCur; pstmt; pstmt = pstmt->pstmtOuter)
  9154. {
  9155. LabelId* pLabelId;
  9156. for (pLabelId = pstmt->pLabelId; pLabelId; pLabelId = pLabelId->next)
  9157. {
  9158. if (pid == pLabelId->pid)
  9159. {
  9160. // Found the label. Make sure we can use it. We can
  9161. // break out of any statement, but we can only
  9162. // continue loops.
  9163. if (fnop == fnopContinue &&
  9164. !(ParseNode::Grfnop(pstmt->op) & fnop))
  9165. {
  9166. Error(ERRbadContinue);
  9167. }
  9168. goto LNeedTerminator;
  9169. }
  9170. }
  9171. }
  9172. }
  9173. Error(ERRnoLabel);
  9174. }
  9175. else
  9176. {
  9177. // If we're doing a fast scan, we're not tracking labels, so we can't accurately do this analysis.
  9178. // Let the thread that's doing the full parse detect the error, if there is one.
  9179. if (!this->IsDoingFastScan())
  9180. {
  9181. // Unlabeled break or continue.
  9182. if (buildAST)
  9183. {
  9184. pnode->AsParseNodeJump()->hasExplicitTarget=false;
  9185. PushStmt<buildAST>(&stmt, pnode, pnode->nop, pLabelIdList);
  9186. Assert(pnode->AsParseNodeStmt()->grfnop == 0);
  9187. }
  9188. for (pstmt = m_pstmtCur; nullptr != pstmt; pstmt = pstmt->pstmtOuter)
  9189. {
  9190. if (buildAST)
  9191. {
  9192. AnalysisAssert(pstmt->pnodeStmt);
  9193. if (pstmt->pnodeStmt->Grfnop() & fnop)
  9194. {
  9195. pstmt->pnodeStmt->AsParseNodeStmt()->grfnop |= fnop;
  9196. pnode->AsParseNodeJump()->pnodeTarget = pstmt->pnodeStmt;
  9197. PopStmt(&stmt);
  9198. goto LNeedTerminator;
  9199. }
  9200. pnode->AsParseNodeStmt()->grfnop |=
  9201. (pstmt->pnodeStmt->Grfnop() & fnopCleanup);
  9202. }
  9203. else
  9204. {
  9205. if (ParseNode::Grfnop(pstmt->GetNop()) & fnop)
  9206. {
  9207. if (!pstmt->isDeferred)
  9208. {
  9209. AnalysisAssert(pstmt->pnodeStmt);
  9210. pstmt->pnodeStmt->AsParseNodeStmt()->grfnop |= fnop;
  9211. }
  9212. goto LNeedTerminator;
  9213. }
  9214. }
  9215. }
  9216. Error(fnop == fnopBreak ? ERRbadBreak : ERRbadContinue);
  9217. }
  9218. goto LNeedTerminator;
  9219. }
  9220. case tkRETURN:
  9221. {
  9222. if (buildAST)
  9223. {
  9224. if (nullptr == m_currentNodeFunc || IsTopLevelModuleFunc())
  9225. {
  9226. Error(ERRbadReturn);
  9227. }
  9228. pnode = CreateNodeWithScanner<knopReturn>();
  9229. }
  9230. m_pscan->Scan();
  9231. ParseNodePtr pnodeExpr = nullptr;
  9232. ParseOptionalExpr<buildAST>(&pnodeExpr, true);
  9233. // Class constructors have special semantics regarding return statements.
  9234. // This might require a reference to 'this'
  9235. if (GetCurrentFunctionNode()->AsParseNodeFnc()->IsClassConstructor())
  9236. {
  9237. ReferenceSpecialName(wellKnownPropertyPids._this);
  9238. }
  9239. if (buildAST)
  9240. {
  9241. pnode->AsParseNodeReturn()->pnodeExpr = pnodeExpr;
  9242. if (pnodeExpr)
  9243. {
  9244. this->CheckArguments(pnode->AsParseNodeReturn()->pnodeExpr);
  9245. pnode->ichLim = pnode->AsParseNodeReturn()->pnodeExpr->ichLim;
  9246. }
  9247. // See if return should call finally
  9248. PushStmt<buildAST>(&stmt, pnode, knopReturn, pLabelIdList);
  9249. Assert(pnode->AsParseNodeStmt()->grfnop == 0);
  9250. for (pstmt = m_pstmtCur; nullptr != pstmt; pstmt = pstmt->pstmtOuter)
  9251. {
  9252. if (pstmt->pnodeStmt->Grfnop() & fnopCleanup)
  9253. {
  9254. pnode->AsParseNodeStmt()->grfnop |= fnopCleanup;
  9255. break;
  9256. }
  9257. }
  9258. PopStmt(&stmt);
  9259. }
  9260. goto LNeedTerminator;
  9261. }
  9262. case tkTHROW:
  9263. {
  9264. if (buildAST)
  9265. {
  9266. pnode = CreateUniNode(knopThrow, nullptr);
  9267. }
  9268. m_pscan->Scan();
  9269. ParseNodePtr pnode1 = nullptr;
  9270. if (m_token.tk != tkSColon &&
  9271. m_token.tk != tkRCurly &&
  9272. !m_pscan->FHadNewLine())
  9273. {
  9274. pnode1 = ParseExpr<buildAST>();
  9275. }
  9276. else
  9277. {
  9278. Error(ERRdanglingThrow);
  9279. }
  9280. if (buildAST)
  9281. {
  9282. pnode->AsParseNodeUni()->pnode1 = pnode1;
  9283. if (pnode1)
  9284. {
  9285. this->CheckArguments(pnode->AsParseNodeUni()->pnode1);
  9286. pnode->ichLim = pnode->AsParseNodeUni()->pnode1->ichLim;
  9287. }
  9288. }
  9289. goto LNeedTerminator;
  9290. }
  9291. case tkDEBUGGER:
  9292. if (buildAST)
  9293. {
  9294. pnode = CreateNodeWithScanner<knopDebugger>();
  9295. }
  9296. m_pscan->Scan();
  9297. goto LNeedTerminator;
  9298. case tkIMPORT:
  9299. pnode = ParseImport<buildAST>();
  9300. goto LNeedTerminator;
  9301. case tkEXPORT:
  9302. {
  9303. if (!(m_grfscr & fscrIsModuleCode))
  9304. {
  9305. goto LDefaultToken;
  9306. }
  9307. bool needTerminator = false;
  9308. pnode = ParseExportDeclaration<buildAST>(&needTerminator);
  9309. if (needTerminator)
  9310. {
  9311. goto LNeedTerminator;
  9312. }
  9313. else
  9314. {
  9315. break;
  9316. }
  9317. }
  9318. LDefaultToken:
  9319. default:
  9320. {
  9321. // First check for a label via lookahead. If not found,
  9322. // rewind and reparse as expression statement.
  9323. if (m_token.tk == tkID)
  9324. {
  9325. RestorePoint idStart;
  9326. m_pscan->Capture(&idStart);
  9327. IdentPtr pidInner = m_token.GetIdentifier(m_phtbl);
  9328. m_pscan->Scan();
  9329. if (m_token.tk == tkColon)
  9330. {
  9331. // We have a label.
  9332. if (LabelExists(pidInner, pLabelIdList))
  9333. {
  9334. Error(ERRbadLabel);
  9335. }
  9336. LabelId* pLabelId = CreateLabelId(pidInner);
  9337. pLabelId->next = pLabelIdList;
  9338. pLabelIdList = pLabelId;
  9339. m_pscan->Scan();
  9340. goto LRestart;
  9341. }
  9342. // No label, rewind back to the tkID and parse an expression
  9343. m_pscan->SeekTo(idStart);
  9344. }
  9345. // Must be an expression statement.
  9346. pnode = ParseExpr<buildAST>();
  9347. if (m_hasDeferredShorthandInitError)
  9348. {
  9349. Error(ERRnoColon);
  9350. }
  9351. if (buildAST)
  9352. {
  9353. expressionStmt = true;
  9354. AnalysisAssert(pnode);
  9355. pnode->isUsed = false;
  9356. }
  9357. }
  9358. LNeedTerminator:
  9359. // Need a semicolon, new-line, } or end-of-file.
  9360. // We digest a semicolon if it's there.
  9361. switch (m_token.tk)
  9362. {
  9363. case tkSColon:
  9364. m_pscan->Scan();
  9365. if (pnode!= nullptr) pnode->grfpn |= PNodeFlags::fpnExplicitSemicolon;
  9366. break;
  9367. case tkEOF:
  9368. case tkRCurly:
  9369. if (pnode!= nullptr) pnode->grfpn |= PNodeFlags::fpnAutomaticSemicolon;
  9370. break;
  9371. default:
  9372. if (!m_pscan->FHadNewLine())
  9373. {
  9374. Error(ERRnoSemic);
  9375. }
  9376. else
  9377. {
  9378. if (pnode!= nullptr) pnode->grfpn |= PNodeFlags::fpnAutomaticSemicolon;
  9379. }
  9380. break;
  9381. }
  9382. break;
  9383. }
  9384. if (m_hasDeferredShorthandInitError)
  9385. {
  9386. Error(ERRnoColon);
  9387. }
  9388. if (buildAST)
  9389. {
  9390. // All non expression statements excluded from the "this.x" optimization
  9391. // Another check while parsing expressions
  9392. if (!expressionStmt)
  9393. {
  9394. if (m_currentNodeFunc)
  9395. {
  9396. m_currentNodeFunc->AsParseNodeFnc()->SetHasNonThisStmt();
  9397. }
  9398. else if (m_currentNodeProg)
  9399. {
  9400. m_currentNodeProg->AsParseNodeFnc()->SetHasNonThisStmt();
  9401. }
  9402. }
  9403. #if EXCEPTION_RECOVERY
  9404. // close the try/catch block
  9405. if(Js::Configuration::Global.flags.SwallowExceptions)
  9406. {
  9407. // pop the try block and fill in the body
  9408. PopStmt(&stmtTryBlock);
  9409. pTryBlock->AsParseNodeBlock()->pnodeStmt = pnode;
  9410. PopStmt(&stmtTry);
  9411. if(pnode != nullptr)
  9412. {
  9413. pTry->ichLim = pnode->ichLim;
  9414. }
  9415. pTry->AsParseNodeTry()->pnodeBody = pTryBlock;
  9416. // create a catch block with an empty body
  9417. StmtNest stmtCatch;
  9418. ParseNodePtr pCatch;
  9419. pCatch = CreateNodeWithScanner<knopCatch>();
  9420. PushStmt<buildAST>(&stmtCatch, pCatch, knopCatch, nullptr);
  9421. pCatch->AsParseNodeCatch()->pnodeBody = nullptr;
  9422. if(pnode != nullptr)
  9423. {
  9424. pCatch->ichLim = pnode->ichLim;
  9425. }
  9426. pCatch->AsParseNodeCatch()->grfnop = 0;
  9427. pCatch->AsParseNodeCatch()->pnodeNext = nullptr;
  9428. // create a fake name for the catch var.
  9429. const WCHAR *uniqueNameStr = _u("__ehobj");
  9430. IdentPtr uniqueName = m_phtbl->PidHashNameLen(uniqueNameStr, static_cast<int32>(wcslen(uniqueNameStr)));
  9431. pCatch->AsParseNodeCatch()->pnodeParam = CreateNameNode(uniqueName);
  9432. // Add this catch to the current list. We don't bother adjusting the catch and function expression
  9433. // lists here because the catch is just an empty statement.
  9434. if (m_ppnodeExprScope)
  9435. {
  9436. Assert(*m_ppnodeExprScope == nullptr);
  9437. *m_ppnodeExprScope = pCatch;
  9438. m_ppnodeExprScope = &pCatch->AsParseNodeCatch()->pnodeNext;
  9439. }
  9440. else
  9441. {
  9442. Assert(m_ppnodeScope);
  9443. Assert(*m_ppnodeScope == nullptr);
  9444. *m_ppnodeScope = pCatch;
  9445. m_ppnodeScope = &pCatch->AsParseNodeCatch()->pnodeNext;
  9446. }
  9447. pCatch->AsParseNodeCatch()->pnodeScopes = nullptr;
  9448. PopStmt(&stmtCatch);
  9449. // fill in and pop the try-catch
  9450. pParentTryCatch->AsParseNodeTryCatch()->pnodeTry = pTry;
  9451. pParentTryCatch->AsParseNodeTryCatch()->pnodeCatch = pCatch;
  9452. PopStmt(&stmtTryCatch);
  9453. PopStmt(&stmtTryCatchBlock);
  9454. // replace the node that's being returned
  9455. pParentTryCatchBlock->AsParseNodeBlock()->pnodeStmt = pParentTryCatch;
  9456. pnode = pParentTryCatchBlock;
  9457. }
  9458. #endif // EXCEPTION_RECOVERY
  9459. }
  9460. return pnode;
  9461. }
  9462. BOOL
  9463. Parser::TokIsForInOrForOf()
  9464. {
  9465. return m_token.tk == tkIN ||
  9466. (m_token.tk == tkID &&
  9467. m_token.GetIdentifier(m_phtbl) == wellKnownPropertyPids.of);
  9468. }
  9469. /***************************************************************************
  9470. Parse a sequence of statements.
  9471. ***************************************************************************/
  9472. template<bool buildAST>
  9473. void Parser::ParseStmtList(ParseNodePtr *ppnodeList, ParseNodePtr **pppnodeLast, StrictModeEnvironment smEnvironment, const bool isSourceElementList, bool* strictModeOn)
  9474. {
  9475. BOOL doneDirectives = !isSourceElementList; // directives may only exist in a SourceElementList, not a StatementList
  9476. BOOL seenDirectiveContainingOctal = false; // Have we seen an octal directive before a use strict directive?
  9477. BOOL old_UseStrictMode = m_fUseStrictMode;
  9478. ParseNodePtr pnodeStmt;
  9479. ParseNodePtr *lastNodeRef = nullptr;
  9480. if (buildAST)
  9481. {
  9482. AssertMem(ppnodeList);
  9483. AssertMemN(pppnodeLast);
  9484. *ppnodeList = nullptr;
  9485. }
  9486. if(CONFIG_FLAG(ForceStrictMode))
  9487. {
  9488. m_fUseStrictMode = TRUE;
  9489. }
  9490. for (;;)
  9491. {
  9492. switch (m_token.tk)
  9493. {
  9494. case tkCASE:
  9495. case tkDEFAULT:
  9496. case tkRCurly:
  9497. case tkEOF:
  9498. if (buildAST && nullptr != pppnodeLast)
  9499. {
  9500. *pppnodeLast = lastNodeRef;
  9501. }
  9502. if (!buildAST)
  9503. {
  9504. m_fUseStrictMode = old_UseStrictMode;
  9505. }
  9506. return;
  9507. }
  9508. if (doneDirectives == FALSE)
  9509. {
  9510. bool isOctalInString = false;
  9511. bool isUseStrictDirective = false;
  9512. bool isUseAsmDirective = false;
  9513. if (smEnvironment != SM_NotUsed && CheckForDirective(&isUseStrictDirective, &isUseAsmDirective, &isOctalInString))
  9514. {
  9515. // Ignore "use asm" statement when not building the AST
  9516. isUseAsmDirective &= buildAST;
  9517. if (isUseStrictDirective)
  9518. {
  9519. // Functions with non-simple parameter list cannot be made strict mode
  9520. if (GetCurrentFunctionNode()->AsParseNodeFnc()->HasNonSimpleParameterList())
  9521. {
  9522. Error(ERRNonSimpleParamListInStrictMode);
  9523. }
  9524. if (seenDirectiveContainingOctal)
  9525. {
  9526. // Directives seen before a "use strict" cannot contain an octal.
  9527. Error(ERRES5NoOctal);
  9528. }
  9529. if (!buildAST)
  9530. {
  9531. // Turning on strict mode in deferred code.
  9532. m_fUseStrictMode = TRUE;
  9533. if (!m_inDeferredNestedFunc)
  9534. {
  9535. // Top-level deferred function, so there's a parse node
  9536. Assert(m_currentNodeFunc != nullptr);
  9537. m_currentNodeFunc->AsParseNodeFnc()->SetStrictMode();
  9538. }
  9539. else if (strictModeOn)
  9540. {
  9541. // This turns on strict mode in a deferred function, we need to go back
  9542. // and re-check duplicated formals.
  9543. *strictModeOn = true;
  9544. }
  9545. }
  9546. else
  9547. {
  9548. if (smEnvironment == SM_OnGlobalCode)
  9549. {
  9550. // Turning on strict mode at the top level
  9551. m_fUseStrictMode = TRUE;
  9552. }
  9553. else
  9554. {
  9555. // i.e. smEnvironment == SM_OnFunctionCode
  9556. Assert(m_currentNodeFunc != nullptr);
  9557. m_currentNodeFunc->AsParseNodeFnc()->SetStrictMode();
  9558. }
  9559. }
  9560. }
  9561. else if (isUseAsmDirective)
  9562. {
  9563. if (smEnvironment != SM_OnGlobalCode) //Top level use asm doesn't mean anything.
  9564. {
  9565. // i.e. smEnvironment == SM_OnFunctionCode
  9566. Assert(m_currentNodeFunc != nullptr);
  9567. m_currentNodeFunc->AsParseNodeFnc()->SetAsmjsMode();
  9568. m_currentNodeFunc->AsParseNodeFnc()->SetCanBeDeferred(false);
  9569. m_InAsmMode = true;
  9570. CHAKRATEL_LANGSTATS_INC_LANGFEATURECOUNT(ES6, AsmJSFunction, m_scriptContext);
  9571. }
  9572. }
  9573. else if (isOctalInString)
  9574. {
  9575. seenDirectiveContainingOctal = TRUE;
  9576. }
  9577. }
  9578. else
  9579. {
  9580. // The first time we see anything other than a directive we can have no more directives.
  9581. doneDirectives = TRUE;
  9582. }
  9583. }
  9584. if (nullptr != (pnodeStmt = ParseStatement<buildAST>()))
  9585. {
  9586. if (buildAST)
  9587. {
  9588. AddToNodeList(ppnodeList, &lastNodeRef, pnodeStmt);
  9589. }
  9590. }
  9591. }
  9592. }
  9593. template <class Fn>
  9594. void Parser::FinishFunctionsInScope(ParseNodePtr pnodeScopeList, Fn fn)
  9595. {
  9596. Scope * scope;
  9597. Scope * origCurrentScope = this->m_currentScope;
  9598. ParseNodePtr pnodeScope;
  9599. ParseNodePtr pnodeBlock;
  9600. for (pnodeScope = pnodeScopeList; pnodeScope;)
  9601. {
  9602. switch (pnodeScope->nop)
  9603. {
  9604. case knopBlock:
  9605. m_nextBlockId = pnodeScope->AsParseNodeBlock()->blockId + 1;
  9606. PushBlockInfo(pnodeScope);
  9607. scope = pnodeScope->AsParseNodeBlock()->scope;
  9608. if (scope && scope != origCurrentScope)
  9609. {
  9610. PushScope(scope);
  9611. }
  9612. FinishFunctionsInScope(pnodeScope->AsParseNodeBlock()->pnodeScopes, fn);
  9613. if (scope && scope != origCurrentScope)
  9614. {
  9615. BindPidRefs<false>(GetCurrentBlockInfo(), m_nextBlockId - 1);
  9616. PopScope(scope);
  9617. }
  9618. PopBlockInfo();
  9619. pnodeScope = pnodeScope->AsParseNodeBlock()->pnodeNext;
  9620. break;
  9621. case knopFncDecl:
  9622. fn(pnodeScope);
  9623. pnodeScope = pnodeScope->AsParseNodeFnc()->pnodeNext;
  9624. break;
  9625. case knopCatch:
  9626. scope = pnodeScope->AsParseNodeCatch()->scope;
  9627. if (scope)
  9628. {
  9629. PushScope(scope);
  9630. }
  9631. pnodeBlock = CreateBlockNode(PnodeBlockType::Regular);
  9632. pnodeBlock->AsParseNodeBlock()->scope = scope;
  9633. PushBlockInfo(pnodeBlock);
  9634. FinishFunctionsInScope(pnodeScope->AsParseNodeCatch()->pnodeScopes, fn);
  9635. if (scope)
  9636. {
  9637. BindPidRefs<false>(GetCurrentBlockInfo(), m_nextBlockId - 1);
  9638. PopScope(scope);
  9639. }
  9640. PopBlockInfo();
  9641. pnodeScope = pnodeScope->AsParseNodeCatch()->pnodeNext;
  9642. break;
  9643. case knopWith:
  9644. PushBlockInfo(CreateBlockNode());
  9645. PushDynamicBlock();
  9646. FinishFunctionsInScope(pnodeScope->AsParseNodeWith()->pnodeScopes, fn);
  9647. PopBlockInfo();
  9648. pnodeScope = pnodeScope->AsParseNodeWith()->pnodeNext;
  9649. break;
  9650. default:
  9651. AssertMsg(false, "Unexpected node with scope list");
  9652. return;
  9653. }
  9654. }
  9655. }
  9656. // Scripts above this size (minus string literals and comments) will have parsing of
  9657. // function bodies deferred.
  9658. ULONG Parser::GetDeferralThreshold(bool isProfileLoaded)
  9659. {
  9660. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  9661. if (CONFIG_FLAG(ForceDeferParse) ||
  9662. PHASE_FORCE1(Js::DeferParsePhase) ||
  9663. Js::Configuration::Global.flags.IsEnabled(Js::ForceUndoDeferFlag))
  9664. {
  9665. return 0;
  9666. }
  9667. else if (Js::Configuration::Global.flags.IsEnabled(Js::DeferParseFlag))
  9668. {
  9669. return Js::Configuration::Global.flags.DeferParse;
  9670. }
  9671. else
  9672. #endif
  9673. {
  9674. if (isProfileLoaded)
  9675. {
  9676. return DEFAULT_CONFIG_ProfileBasedDeferParseThreshold;
  9677. }
  9678. return DEFAULT_CONFIG_DeferParseThreshold;
  9679. }
  9680. }
  9681. void Parser::FinishDeferredFunction(ParseNodePtr pnodeScopeList)
  9682. {
  9683. uint saveNextBlockId = m_nextBlockId;
  9684. m_nextBlockId = pnodeScopeList->AsParseNodeBlock()->blockId + 1;
  9685. FinishFunctionsInScope(pnodeScopeList,
  9686. [this](ParseNodePtr pnodeFnc)
  9687. {
  9688. Assert(pnodeFnc->nop == knopFncDecl);
  9689. // Non-simple params (such as default) require a good amount of logic to put vars on appropriate scopes. ParseFncDecl handles it
  9690. // properly (both on defer and non-defer case). This is to avoid write duplicated logic here as well. Function with non-simple-param
  9691. // will remain deferred until they are called.
  9692. if (pnodeFnc->AsParseNodeFnc()->pnodeBody == nullptr && !pnodeFnc->AsParseNodeFnc()->HasNonSimpleParameterList())
  9693. {
  9694. // Go back and generate an AST for this function.
  9695. JS_ETW_INTERNAL(EventWriteJSCRIPT_PARSE_FUNC(this->GetScriptContext(), pnodeFnc->AsParseNodeFnc()->functionId, /*Undefer*/TRUE));
  9696. ParseNodePtr pnodeFncSave = this->m_currentNodeFunc;
  9697. this->m_currentNodeFunc = pnodeFnc;
  9698. ParseNodePtr pnodeFncExprBlock = nullptr;
  9699. ParseNodePtr pnodeName = pnodeFnc->AsParseNodeFnc()->pnodeName;
  9700. if (pnodeName)
  9701. {
  9702. Assert(pnodeName->nop == knopVarDecl);
  9703. Assert(pnodeName->AsParseNodeVar()->pnodeNext == nullptr);
  9704. if (!pnodeFnc->AsParseNodeFnc()->IsDeclaration())
  9705. {
  9706. // Set up the named function expression symbol so references inside the function can be bound.
  9707. pnodeFncExprBlock = this->StartParseBlock<true>(PnodeBlockType::Function, ScopeType_FuncExpr);
  9708. PidRefStack *ref = this->PushPidRef(pnodeName->AsParseNodeVar()->pid);
  9709. pnodeName->AsParseNodeVar()->symRef = ref->GetSymRef();
  9710. ref->SetSym(pnodeName->AsParseNodeVar()->sym);
  9711. Scope *fncExprScope = pnodeFncExprBlock->AsParseNodeBlock()->scope;
  9712. fncExprScope->AddNewSymbol(pnodeName->AsParseNodeVar()->sym);
  9713. pnodeFnc->AsParseNodeFnc()->scope = fncExprScope;
  9714. }
  9715. }
  9716. ParseNodePtr pnodeBlock = this->StartParseBlock<true>(PnodeBlockType::Parameter, ScopeType_Parameter);
  9717. pnodeFnc->AsParseNodeFnc()->pnodeScopes = pnodeBlock;
  9718. m_ppnodeScope = &pnodeBlock->AsParseNodeBlock()->pnodeScopes;
  9719. pnodeBlock->AsParseNodeBlock()->pnodeStmt = pnodeFnc;
  9720. ParseNodePtr* varNodesList = &pnodeFnc->AsParseNodeFnc()->pnodeVars;
  9721. ParseNodePtr argNode = nullptr;
  9722. if (!pnodeFnc->AsParseNodeFnc()->IsModule() && !pnodeFnc->AsParseNodeFnc()->IsLambda() && !(pnodeFnc->grfpn & PNodeFlags::fpnArguments_overriddenInParam))
  9723. {
  9724. ParseNodePtr *const ppnodeVarSave = m_ppnodeVar;
  9725. m_ppnodeVar = &pnodeFnc->AsParseNodeFnc()->pnodeVars;
  9726. argNode = this->AddArgumentsNodeToVars(pnodeFnc);
  9727. varNodesList = m_ppnodeVar;
  9728. m_ppnodeVar = ppnodeVarSave;
  9729. }
  9730. // Add the args to the scope, since we won't re-parse those.
  9731. Scope *scope = pnodeBlock->AsParseNodeBlock()->scope;
  9732. uint blockId = GetCurrentBlock()->AsParseNodeBlock()->blockId;
  9733. uint funcId = GetCurrentFunctionNode()->AsParseNodeFnc()->functionId;
  9734. auto addArgsToScope = [&](ParseNodePtr pnodeArg) {
  9735. if (pnodeArg->IsVarLetOrConst())
  9736. {
  9737. PidRefStack *ref = this->FindOrAddPidRef(pnodeArg->AsParseNodeVar()->pid, blockId, funcId);
  9738. pnodeArg->AsParseNodeVar()->symRef = ref->GetSymRef();
  9739. if (ref->GetSym() != nullptr)
  9740. {
  9741. // Duplicate parameter in a configuration that allows them.
  9742. // The symbol is already in the scope, just point it to the right declaration.
  9743. Assert(ref->GetSym() == pnodeArg->AsParseNodeVar()->sym);
  9744. ref->GetSym()->SetDecl(pnodeArg);
  9745. }
  9746. else
  9747. {
  9748. ref->SetSym(pnodeArg->AsParseNodeVar()->sym);
  9749. scope->AddNewSymbol(pnodeArg->AsParseNodeVar()->sym);
  9750. }
  9751. }
  9752. };
  9753. MapFormals(pnodeFnc, addArgsToScope);
  9754. MapFormalsFromPattern(pnodeFnc, addArgsToScope);
  9755. ParseNodePtr pnodeInnerBlock = this->StartParseBlock<true>(PnodeBlockType::Function, ScopeType_FunctionBody);
  9756. pnodeFnc->AsParseNodeFnc()->pnodeBodyScope = pnodeInnerBlock;
  9757. // Set the parameter block's child to the function body block.
  9758. *m_ppnodeScope = pnodeInnerBlock;
  9759. ParseNodePtr *ppnodeScopeSave = nullptr;
  9760. ParseNodePtr *ppnodeExprScopeSave = nullptr;
  9761. ppnodeScopeSave = m_ppnodeScope;
  9762. // This synthetic block scope will contain all the nested scopes.
  9763. m_ppnodeScope = &pnodeInnerBlock->AsParseNodeBlock()->pnodeScopes;
  9764. pnodeInnerBlock->AsParseNodeBlock()->pnodeStmt = pnodeFnc;
  9765. // Keep nested function declarations and expressions in the same list at function scope.
  9766. // (Indicate this by nulling out the current function expressions list.)
  9767. ppnodeExprScopeSave = m_ppnodeExprScope;
  9768. m_ppnodeExprScope = nullptr;
  9769. // Shouldn't be any temps in the arg list.
  9770. Assert(*m_ppnodeVar == nullptr);
  9771. // Start the var list.
  9772. m_ppnodeVar = varNodesList;
  9773. if (scope != nullptr)
  9774. {
  9775. Assert(pnodeFnc->AsParseNodeFnc()->IsBodyAndParamScopeMerged());
  9776. blockId = GetCurrentBlock()->AsParseNodeBlock()->blockId;
  9777. funcId = GetCurrentFunctionNode()->AsParseNodeFnc()->functionId;
  9778. scope->ForEachSymbol([this, blockId, funcId](Symbol* paramSym)
  9779. {
  9780. PidRefStack* ref = this->FindOrAddPidRef(paramSym->GetPid(), blockId, funcId);
  9781. ref->SetSym(paramSym);
  9782. });
  9783. }
  9784. Assert(m_currentNodeNonLambdaFunc == nullptr);
  9785. m_currentNodeNonLambdaFunc = pnodeFnc;
  9786. this->FinishFncNode(pnodeFnc);
  9787. Assert(pnodeFnc == m_currentNodeNonLambdaFunc);
  9788. m_currentNodeNonLambdaFunc = nullptr;
  9789. m_ppnodeExprScope = ppnodeExprScopeSave;
  9790. AssertMem(m_ppnodeScope);
  9791. Assert(nullptr == *m_ppnodeScope);
  9792. m_ppnodeScope = ppnodeScopeSave;
  9793. this->FinishParseBlock(pnodeInnerBlock);
  9794. if (!pnodeFnc->AsParseNodeFnc()->IsModule() && (m_token.tk == tkLCurly || !pnodeFnc->AsParseNodeFnc()->IsLambda()))
  9795. {
  9796. UpdateArgumentsNode(pnodeFnc, argNode);
  9797. }
  9798. CreateSpecialSymbolDeclarations(pnodeFnc);
  9799. this->FinishParseBlock(pnodeBlock);
  9800. if (pnodeFncExprBlock)
  9801. {
  9802. this->FinishParseBlock(pnodeFncExprBlock);
  9803. }
  9804. this->m_currentNodeFunc = pnodeFncSave;
  9805. }
  9806. });
  9807. m_nextBlockId = saveNextBlockId;
  9808. }
  9809. void Parser::InitPids()
  9810. {
  9811. AssertMemN(m_phtbl);
  9812. wellKnownPropertyPids.arguments = m_phtbl->PidHashNameLen(g_ssym_arguments.sz, g_ssym_arguments.cch);
  9813. wellKnownPropertyPids.async = m_phtbl->PidHashNameLen(g_ssym_async.sz, g_ssym_async.cch);
  9814. wellKnownPropertyPids.eval = m_phtbl->PidHashNameLen(g_ssym_eval.sz, g_ssym_eval.cch);
  9815. wellKnownPropertyPids.get = m_phtbl->PidHashNameLen(g_ssym_get.sz, g_ssym_get.cch);
  9816. wellKnownPropertyPids.set = m_phtbl->PidHashNameLen(g_ssym_set.sz, g_ssym_set.cch);
  9817. wellKnownPropertyPids.let = m_phtbl->PidHashNameLen(g_ssym_let.sz, g_ssym_let.cch);
  9818. wellKnownPropertyPids.constructor = m_phtbl->PidHashNameLen(g_ssym_constructor.sz, g_ssym_constructor.cch);
  9819. wellKnownPropertyPids.prototype = m_phtbl->PidHashNameLen(g_ssym_prototype.sz, g_ssym_prototype.cch);
  9820. wellKnownPropertyPids.__proto__ = m_phtbl->PidHashNameLen(_u("__proto__"), sizeof("__proto__") - 1);
  9821. wellKnownPropertyPids.of = m_phtbl->PidHashNameLen(_u("of"), sizeof("of") - 1);
  9822. wellKnownPropertyPids.target = m_phtbl->PidHashNameLen(_u("target"), sizeof("target") - 1);
  9823. wellKnownPropertyPids.as = m_phtbl->PidHashNameLen(_u("as"), sizeof("as") - 1);
  9824. wellKnownPropertyPids.from = m_phtbl->PidHashNameLen(_u("from"), sizeof("from") - 1);
  9825. wellKnownPropertyPids._default = m_phtbl->PidHashNameLen(_u("default"), sizeof("default") - 1);
  9826. wellKnownPropertyPids._starDefaultStar = m_phtbl->PidHashNameLen(_u("*default*"), sizeof("*default*") - 1);
  9827. wellKnownPropertyPids._star = m_phtbl->PidHashNameLen(_u("*"), sizeof("*") - 1);
  9828. wellKnownPropertyPids._this = m_phtbl->PidHashNameLen(_u("*this*"), sizeof("*this*") - 1);
  9829. wellKnownPropertyPids._newTarget = m_phtbl->PidHashNameLen(_u("*new.target*"), sizeof("*new.target*") - 1);
  9830. wellKnownPropertyPids._super = m_phtbl->PidHashNameLen(_u("*super*"), sizeof("*super*") - 1);
  9831. wellKnownPropertyPids._superConstructor = m_phtbl->PidHashNameLen(_u("*superconstructor*"), sizeof("*superconstructor*") - 1);
  9832. }
  9833. void Parser::RestoreScopeInfo(Js::ScopeInfo * scopeInfo)
  9834. {
  9835. if (!scopeInfo)
  9836. {
  9837. return;
  9838. }
  9839. PROBE_STACK_NO_DISPOSE(m_scriptContext, Js::Constants::MinStackByteCodeVisitor);
  9840. RestoreScopeInfo(scopeInfo->GetParentScopeInfo()); // Recursively restore outer func scope info
  9841. scopeInfo->SetScopeId(m_nextBlockId);
  9842. ParseNodePtr pnodeScope = nullptr;
  9843. ScopeType scopeType = scopeInfo->GetScopeType();
  9844. PnodeBlockType blockType;
  9845. switch (scopeType)
  9846. {
  9847. case ScopeType_With:
  9848. PushDynamicBlock();
  9849. // fall through
  9850. case ScopeType_Block:
  9851. case ScopeType_Catch:
  9852. case ScopeType_CatchParamPattern:
  9853. case ScopeType_GlobalEvalBlock:
  9854. blockType = PnodeBlockType::Regular;
  9855. break;
  9856. case ScopeType_FunctionBody:
  9857. case ScopeType_FuncExpr:
  9858. blockType = PnodeBlockType::Function;
  9859. break;
  9860. case ScopeType_Parameter:
  9861. blockType = PnodeBlockType::Parameter;
  9862. break;
  9863. default:
  9864. Assert(0);
  9865. return;
  9866. }
  9867. pnodeScope = StartParseBlockWithCapacity<true>(blockType, scopeType, scopeInfo->GetSymbolCount());
  9868. Scope *scope = pnodeScope->AsParseNodeBlock()->scope;
  9869. scope->SetScopeInfo(scopeInfo);
  9870. scopeInfo->ExtractScopeInfo(this, /*nullptr, nullptr,*/ scope);
  9871. }
  9872. void Parser::FinishScopeInfo(Js::ScopeInfo * scopeInfo)
  9873. {
  9874. PROBE_STACK_NO_DISPOSE(m_scriptContext, Js::Constants::MinStackByteCodeVisitor);
  9875. for (;scopeInfo != nullptr; scopeInfo = scopeInfo->GetParentScopeInfo())
  9876. {
  9877. int scopeId = scopeInfo->GetScopeId();
  9878. scopeInfo->GetScope()->ForEachSymbol([this, scopeId](Symbol *sym)
  9879. {
  9880. this->BindPidRefsInScope(sym->GetPid(), sym, scopeId);
  9881. });
  9882. PopScope(scopeInfo->GetScope());
  9883. PopStmt(&m_currentBlockInfo->pstmt);
  9884. PopBlockInfo();
  9885. }
  9886. }
  9887. /***************************************************************************
  9888. Parse the code.
  9889. ***************************************************************************/
  9890. ParseNodePtr Parser::Parse(LPCUTF8 pszSrc, size_t offset, size_t length, charcount_t charOffset, ULONG grfscr, ULONG lineNumber, Js::LocalFunctionId * nextFunctionId, CompileScriptException *pse)
  9891. {
  9892. ParseNodePtr pnodeProg;
  9893. ParseNodePtr *lastNodeRef = nullptr;
  9894. m_nextBlockId = 0;
  9895. bool isDeferred = (grfscr & fscrDeferredFnc) != 0;
  9896. bool isModuleSource = (grfscr & fscrIsModuleCode) != 0;
  9897. bool isGlobalCode = (grfscr & fscrGlobalCode) != 0;
  9898. if (this->m_scriptContext->IsScriptContextInDebugMode()
  9899. #ifdef ENABLE_PREJIT
  9900. || Js::Configuration::Global.flags.Prejit
  9901. #endif
  9902. || ((grfscr & fscrNoDeferParse) != 0)
  9903. )
  9904. {
  9905. // Don't do deferred parsing if debugger is attached or feature is disabled
  9906. // by command-line switch.
  9907. grfscr &= ~fscrDeferFncParse;
  9908. }
  9909. else if (!isGlobalCode &&
  9910. (
  9911. PHASE_OFF1(Js::Phase::DeferEventHandlersPhase) ||
  9912. this->m_scriptContext->IsScriptContextInSourceRundownOrDebugMode()
  9913. )
  9914. )
  9915. {
  9916. // Don't defer event handlers in debug/rundown mode, because we need to register the document,
  9917. // so we need to create a full FunctionBody for the script body.
  9918. grfscr &= ~fscrDeferFncParse;
  9919. }
  9920. m_grfscr = grfscr;
  9921. m_length = length;
  9922. m_originalLength = length;
  9923. m_nextFunctionId = nextFunctionId;
  9924. if(m_parseType != ParseType_Deferred)
  9925. {
  9926. JS_ETW(EventWriteJSCRIPT_PARSE_METHOD_START(m_sourceContextInfo->dwHostSourceContext, GetScriptContext(), *m_nextFunctionId, 0, m_parseType, Js::Constants::GlobalFunction));
  9927. OUTPUT_TRACE(Js::DeferParsePhase, _u("Parsing function (%s) : %s (%d)\n"), GetParseType(), Js::Constants::GlobalFunction, *m_nextFunctionId);
  9928. }
  9929. // Give the scanner the source and get the first token
  9930. m_pscan->SetText(pszSrc, offset, length, charOffset, grfscr, lineNumber);
  9931. m_pscan->Scan();
  9932. // Make the main 'knopProg' node
  9933. int32 initSize = 0;
  9934. m_pCurrentAstSize = &initSize;
  9935. pnodeProg = CreateProgNodeWithScanner(isModuleSource);
  9936. pnodeProg->grfpn = PNodeFlags::fpnNone;
  9937. pnodeProg->AsParseNodeFnc()->pid = nullptr;
  9938. pnodeProg->AsParseNodeFnc()->pnodeName = nullptr;
  9939. pnodeProg->AsParseNodeFnc()->pnodeRest = nullptr;
  9940. pnodeProg->AsParseNodeFnc()->ClearFlags();
  9941. pnodeProg->AsParseNodeFnc()->SetNested(FALSE);
  9942. pnodeProg->AsParseNodeFnc()->astSize = 0;
  9943. pnodeProg->AsParseNodeFnc()->cbMin = m_pscan->IecpMinTok();
  9944. pnodeProg->AsParseNodeFnc()->lineNumber = lineNumber;
  9945. pnodeProg->AsParseNodeFnc()->columnNumber = 0;
  9946. pnodeProg->AsParseNodeFnc()->isBodyAndParamScopeMerged = true;
  9947. if (!isDeferred || (isDeferred && isGlobalCode))
  9948. {
  9949. // In the deferred case, if the global function is deferred parse (which is in no-refresh case),
  9950. // we will re-use the same function body, so start with the correct functionId.
  9951. pnodeProg->AsParseNodeFnc()->functionId = (*m_nextFunctionId)++;
  9952. }
  9953. else
  9954. {
  9955. pnodeProg->AsParseNodeFnc()->functionId = Js::Constants::NoFunctionId;
  9956. }
  9957. if (isModuleSource)
  9958. {
  9959. Assert(m_scriptContext->GetConfig()->IsES6ModuleEnabled());
  9960. pnodeProg->AsParseNodeModule()->localExportEntries = nullptr;
  9961. pnodeProg->AsParseNodeModule()->indirectExportEntries = nullptr;
  9962. pnodeProg->AsParseNodeModule()->starExportEntries = nullptr;
  9963. pnodeProg->AsParseNodeModule()->importEntries = nullptr;
  9964. pnodeProg->AsParseNodeModule()->requestedModules = nullptr;
  9965. }
  9966. m_pCurrentAstSize = & (pnodeProg->AsParseNodeFnc()->astSize);
  9967. pnodeProg->AsParseNodeFnc()->hint = nullptr;
  9968. pnodeProg->AsParseNodeFnc()->hintLength = 0;
  9969. pnodeProg->AsParseNodeFnc()->hintOffset = 0;
  9970. pnodeProg->AsParseNodeFnc()->isNameIdentifierRef = true;
  9971. pnodeProg->AsParseNodeFnc()->nestedFuncEscapes = false;
  9972. // initialize parsing variables
  9973. pnodeProg->AsParseNodeFnc()->pnodeNext = nullptr;
  9974. m_currentNodeFunc = nullptr;
  9975. m_currentNodeDeferredFunc = nullptr;
  9976. m_currentNodeProg = pnodeProg;
  9977. m_cactIdentToNodeLookup = 1;
  9978. pnodeProg->AsParseNodeFnc()->nestedCount = 0;
  9979. m_pnestedCount = &pnodeProg->AsParseNodeFnc()->nestedCount;
  9980. m_inDeferredNestedFunc = false;
  9981. pnodeProg->AsParseNodeFnc()->pnodeParams = nullptr;
  9982. pnodeProg->AsParseNodeFnc()->pnodeVars = nullptr;
  9983. pnodeProg->AsParseNodeFnc()->pnodeRest = nullptr;
  9984. m_ppnodeVar = &pnodeProg->AsParseNodeFnc()->pnodeVars;
  9985. SetCurrentStatement(nullptr);
  9986. AssertMsg(m_pstmtCur == nullptr, "Statement stack should be empty when we start parse global code");
  9987. // Create block for const's and let's
  9988. ParseNodePtr pnodeGlobalBlock = StartParseBlock<true>(PnodeBlockType::Global, ScopeType_Global);
  9989. pnodeProg->AsParseNodeProg()->scope = pnodeGlobalBlock->AsParseNodeBlock()->scope;
  9990. ParseNodePtr pnodeGlobalEvalBlock = nullptr;
  9991. // Don't track function expressions separately from declarations at global scope.
  9992. m_ppnodeExprScope = nullptr;
  9993. // This synthetic block scope will contain all the nested scopes.
  9994. pnodeProg->AsParseNodeFnc()->pnodeBodyScope = nullptr;
  9995. pnodeProg->AsParseNodeFnc()->pnodeScopes = pnodeGlobalBlock;
  9996. m_ppnodeScope = &pnodeGlobalBlock->AsParseNodeBlock()->pnodeScopes;
  9997. if ((this->m_grfscr & fscrEvalCode) &&
  9998. !(this->m_functionBody && this->m_functionBody->GetScopeInfo()))
  9999. {
  10000. pnodeGlobalEvalBlock = StartParseBlock<true>(PnodeBlockType::Regular, ScopeType_GlobalEvalBlock);
  10001. pnodeProg->AsParseNodeFnc()->pnodeScopes = pnodeGlobalEvalBlock;
  10002. m_ppnodeScope = &pnodeGlobalEvalBlock->AsParseNodeBlock()->pnodeScopes;
  10003. }
  10004. Js::ScopeInfo *scopeInfo = nullptr;
  10005. if (m_parseType == ParseType_Deferred && m_functionBody)
  10006. {
  10007. // this->m_functionBody can be cleared during parsing, but we need access to the scope info later.
  10008. scopeInfo = m_functionBody->GetScopeInfo();
  10009. if (scopeInfo)
  10010. {
  10011. // Create an enclosing function context.
  10012. m_currentNodeFunc = CreateNode(knopFncDecl);
  10013. m_currentNodeFunc->AsParseNodeFnc()->pnodeName = nullptr;
  10014. m_currentNodeFunc->AsParseNodeFnc()->functionId = m_functionBody->GetLocalFunctionId();
  10015. m_currentNodeFunc->AsParseNodeFnc()->nestedCount = m_functionBody->GetNestedCount();
  10016. m_currentNodeFunc->AsParseNodeFnc()->SetStrictMode(!!this->m_fUseStrictMode);
  10017. this->RestoreScopeInfo(scopeInfo);
  10018. m_currentNodeFunc->AsParseNodeFnc()->ClearFlags();
  10019. m_currentNodeFunc->AsParseNodeFnc()->SetIsGenerator(scopeInfo->IsGeneratorFunctionBody());
  10020. m_currentNodeFunc->AsParseNodeFnc()->SetIsAsync(scopeInfo->IsAsyncFunctionBody());
  10021. }
  10022. }
  10023. // It's possible for the module global to be defer-parsed in debug scenarios.
  10024. if (isModuleSource && (!isDeferred || (isDeferred && isGlobalCode)))
  10025. {
  10026. ParseNodePtr moduleFunction = GenerateModuleFunctionWrapper<true>();
  10027. pnodeProg->AsParseNodeFnc()->pnodeBody = nullptr;
  10028. AddToNodeList(&pnodeProg->AsParseNodeFnc()->pnodeBody, &lastNodeRef, moduleFunction);
  10029. }
  10030. else
  10031. {
  10032. if (isDeferred && !isGlobalCode)
  10033. {
  10034. // Defer parse for a single function should just parse that one function - there are no other statements.
  10035. ushort flags = fFncNoFlgs;
  10036. size_t iecpMin = 0;
  10037. charcount_t ichMin = 0;
  10038. bool isAsync = false;
  10039. bool isGenerator = false;
  10040. bool isMethod = false;
  10041. // The top-level deferred function body was defined by a function expression whose parsing was deferred. We are now
  10042. // parsing it, so unset the flag so that any nested functions are parsed normally. This flag is only applicable the
  10043. // first time we see it.
  10044. //
  10045. // Normally, deferred functions will be parsed in ParseStatement upon encountering the 'function' token. The first
  10046. // token of the source code of the function may not be a 'function' token though, so we still need to reset this flag
  10047. // for the first function we parse. This can happen in compat modes, for instance, for a function expression enclosed
  10048. // in parentheses, where the legacy behavior was to include the parentheses in the function's source code.
  10049. if (m_grfscr & fscrDeferredFncExpression)
  10050. {
  10051. m_grfscr &= ~fscrDeferredFncExpression;
  10052. }
  10053. else
  10054. {
  10055. flags |= fFncDeclaration;
  10056. }
  10057. if (m_grfscr & fscrDeferredFncIsMethod)
  10058. {
  10059. m_grfscr &= ~fscrDeferredFncIsMethod;
  10060. isMethod = true;
  10061. flags |= fFncNoName | fFncMethod;
  10062. }
  10063. // These are the cases which can confirm async function:
  10064. // async function() {} -> async function
  10065. // async () => {} -> async lambda with parens around the formal parameter
  10066. // async arg => {} -> async lambda with single identifier parameter
  10067. // async name() {} -> async method
  10068. // async [computed_name]() {} -> async method with a computed name
  10069. if (m_token.tk == tkID && m_token.GetIdentifier(m_phtbl) == wellKnownPropertyPids.async && m_scriptContext->GetConfig()->IsES7AsyncAndAwaitEnabled())
  10070. {
  10071. ichMin = m_pscan->IchMinTok();
  10072. iecpMin = m_pscan->IecpMinTok();
  10073. // Keep state so we can rewind if it turns out that this isn't an async function:
  10074. // async() {} -> method named async
  10075. // async => {} -> lambda with single parameter named async
  10076. RestorePoint termStart;
  10077. m_pscan->Capture(&termStart);
  10078. m_pscan->Scan();
  10079. if (m_token.tk == tkDArrow || (m_token.tk == tkLParen && isMethod) || m_pscan->FHadNewLine())
  10080. {
  10081. m_pscan->SeekTo(termStart);
  10082. }
  10083. else
  10084. {
  10085. flags |= fFncAsync;
  10086. isAsync = true;
  10087. }
  10088. }
  10089. if (m_token.tk == tkStar && m_scriptContext->GetConfig()->IsES6GeneratorsEnabled())
  10090. {
  10091. ichMin = m_pscan->IchMinTok();
  10092. iecpMin = m_pscan->IecpMinTok();
  10093. flags |= fFncGenerator;
  10094. isGenerator = true;
  10095. m_pscan->Scan();
  10096. }
  10097. // Eat the computed name expression
  10098. if (m_token.tk == tkLBrack && isMethod)
  10099. {
  10100. m_pscan->Scan();
  10101. ParseExpr<false>();
  10102. }
  10103. if (!isMethod && (m_token.tk == tkID || m_token.tk == tkLParen))
  10104. {
  10105. // If first token of the function is tkID or tkLParen, this is a lambda.
  10106. flags |= fFncLambda;
  10107. }
  10108. ParseNodePtr pnodeFnc = ParseFncDecl<true>(flags, nullptr, false, false);
  10109. pnodeProg->AsParseNodeFnc()->pnodeBody = nullptr;
  10110. AddToNodeList(&pnodeProg->AsParseNodeFnc()->pnodeBody, &lastNodeRef, pnodeFnc);
  10111. // Include the async keyword or star character in the function extents
  10112. if (isAsync || isGenerator)
  10113. {
  10114. pnodeFnc->AsParseNodeFnc()->cbMin = iecpMin;
  10115. pnodeFnc->ichMin = ichMin;
  10116. }
  10117. }
  10118. else
  10119. {
  10120. // Process a sequence of statements/declarations
  10121. ParseStmtList<true>(
  10122. &pnodeProg->AsParseNodeFnc()->pnodeBody,
  10123. &lastNodeRef,
  10124. SM_OnGlobalCode,
  10125. !(m_grfscr & fscrDeferredFncExpression) /* isSourceElementList */);
  10126. }
  10127. }
  10128. if (m_parseType == ParseType_Deferred)
  10129. {
  10130. if (scopeInfo)
  10131. {
  10132. this->FinishScopeInfo(scopeInfo);
  10133. }
  10134. }
  10135. pnodeProg->AsParseNodeProg()->m_UsesArgumentsAtGlobal = m_UsesArgumentsAtGlobal;
  10136. if (IsStrictMode())
  10137. {
  10138. pnodeProg->AsParseNodeFnc()->SetStrictMode();
  10139. }
  10140. #if DEBUG
  10141. if(m_grfscr & fscrEnforceJSON && !IsJSONValid(pnodeProg->AsParseNodeFnc()->pnodeBody))
  10142. {
  10143. Error(ERRsyntax);
  10144. }
  10145. #endif
  10146. if (tkEOF != m_token.tk)
  10147. Error(ERRsyntax);
  10148. // Append an EndCode node.
  10149. AddToNodeList(&pnodeProg->AsParseNodeFnc()->pnodeBody, &lastNodeRef,
  10150. CreateNodeWithScanner<knopEndCode>());
  10151. AssertMem(lastNodeRef);
  10152. AssertNodeMem(*lastNodeRef);
  10153. Assert((*lastNodeRef)->nop == knopEndCode);
  10154. (*lastNodeRef)->ichMin = 0;
  10155. (*lastNodeRef)->ichLim = 0;
  10156. // Get the extent of the code.
  10157. pnodeProg->ichLim = m_pscan->IchLimTok();
  10158. pnodeProg->AsParseNodeFnc()->cbLim = m_pscan->IecpLimTok();
  10159. // Terminate the local list
  10160. *m_ppnodeVar = nullptr;
  10161. Assert(nullptr == *m_ppnodeScope);
  10162. Assert(nullptr == pnodeProg->AsParseNodeFnc()->pnodeNext);
  10163. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  10164. if (Js::Configuration::Global.flags.IsEnabled(Js::ForceUndoDeferFlag))
  10165. {
  10166. m_stoppedDeferredParse = true;
  10167. }
  10168. #endif
  10169. if (m_stoppedDeferredParse)
  10170. {
  10171. #if ENABLE_BACKGROUND_PARSING
  10172. if (this->m_hasParallelJob)
  10173. {
  10174. BackgroundParser *bgp = static_cast<BackgroundParser*>(m_scriptContext->GetBackgroundParser());
  10175. Assert(bgp);
  10176. this->WaitForBackgroundJobs(bgp, pse);
  10177. }
  10178. #endif
  10179. // Do any remaining bindings of globals referenced in non-deferred functions.
  10180. if (pnodeGlobalEvalBlock)
  10181. {
  10182. FinishParseBlock(pnodeGlobalEvalBlock);
  10183. }
  10184. FinishParseBlock(pnodeGlobalBlock);
  10185. // Clear out references to undeclared identifiers.
  10186. m_phtbl->VisitPids([&](IdentPtr pid) { pid->SetTopRef(nullptr); });
  10187. // Restore global scope and blockinfo stacks preparatory to reparsing deferred functions.
  10188. PushScope(pnodeGlobalBlock->AsParseNodeBlock()->scope);
  10189. BlockInfoStack *newBlockInfo = PushBlockInfo(pnodeGlobalBlock);
  10190. PushStmt<true>(&newBlockInfo->pstmt, pnodeGlobalBlock, knopBlock, nullptr);
  10191. if (pnodeGlobalEvalBlock)
  10192. {
  10193. PushScope(pnodeGlobalEvalBlock->AsParseNodeBlock()->scope);
  10194. newBlockInfo = PushBlockInfo(pnodeGlobalEvalBlock);
  10195. PushStmt<true>(&newBlockInfo->pstmt, pnodeGlobalEvalBlock, knopBlock, nullptr);
  10196. }
  10197. // Finally, see if there are any function bodies we now want to generate because we
  10198. // decided to stop deferring.
  10199. FinishDeferredFunction(pnodeProg->AsParseNodeFnc()->pnodeScopes);
  10200. }
  10201. if (pnodeGlobalEvalBlock)
  10202. {
  10203. FinishParseBlock(pnodeGlobalEvalBlock);
  10204. }
  10205. // Append block as body of pnodeProg
  10206. FinishParseBlock(pnodeGlobalBlock);
  10207. m_scriptContext->AddSourceSize(m_length);
  10208. if (m_parseType != ParseType_Deferred)
  10209. {
  10210. JS_ETW(EventWriteJSCRIPT_PARSE_METHOD_STOP(m_sourceContextInfo->dwHostSourceContext, GetScriptContext(), pnodeProg->AsParseNodeFnc()->functionId, *m_pCurrentAstSize, false, Js::Constants::GlobalFunction));
  10211. }
  10212. return pnodeProg;
  10213. }
  10214. bool Parser::CheckForDirective(bool* pIsUseStrict, bool *pIsUseAsm, bool* pIsOctalInString)
  10215. {
  10216. // A directive is a string constant followed by a statement terminating token
  10217. if (m_token.tk != tkStrCon)
  10218. return false;
  10219. // Careful, need to check for octal before calling m_pscan->Scan()
  10220. // because Scan() clears the "had octal" flag on the scanner and
  10221. // m_pscan->Restore() does not restore this flag.
  10222. if (pIsOctalInString != nullptr)
  10223. {
  10224. *pIsOctalInString = m_pscan->IsOctOrLeadingZeroOnLastTKNumber();
  10225. }
  10226. Ident* pidDirective = m_token.GetStr();
  10227. RestorePoint start;
  10228. m_pscan->Capture(&start);
  10229. m_pscan->Scan();
  10230. bool isDirective = true;
  10231. switch (m_token.tk)
  10232. {
  10233. case tkSColon:
  10234. case tkEOF:
  10235. case tkLCurly:
  10236. case tkRCurly:
  10237. break;
  10238. default:
  10239. if (!m_pscan->FHadNewLine())
  10240. {
  10241. isDirective = false;
  10242. }
  10243. break;
  10244. }
  10245. if (isDirective)
  10246. {
  10247. if (pIsUseStrict != nullptr)
  10248. {
  10249. *pIsUseStrict = CheckStrictModeStrPid(pidDirective);
  10250. }
  10251. if (pIsUseAsm != nullptr)
  10252. {
  10253. *pIsUseAsm = CheckAsmjsModeStrPid(pidDirective);
  10254. }
  10255. }
  10256. m_pscan->SeekTo(start);
  10257. return isDirective;
  10258. }
  10259. bool Parser::CheckStrictModeStrPid(IdentPtr pid)
  10260. {
  10261. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  10262. if (Js::Configuration::Global.flags.NoStrictMode)
  10263. return false;
  10264. #endif
  10265. return pid != nullptr &&
  10266. pid->Cch() == 10 &&
  10267. !m_pscan->IsEscapeOnLastTkStrCon() &&
  10268. wcsncmp(pid->Psz(), _u("use strict"), 10) == 0;
  10269. }
  10270. bool Parser::CheckAsmjsModeStrPid(IdentPtr pid)
  10271. {
  10272. #ifdef ASMJS_PLAT
  10273. if (!CONFIG_FLAG_RELEASE(Asmjs))
  10274. {
  10275. return false;
  10276. }
  10277. bool isAsmCandidate = (pid != nullptr &&
  10278. AutoSystemInfo::Data.SSE2Available() &&
  10279. pid->Cch() == 7 &&
  10280. !m_pscan->IsEscapeOnLastTkStrCon() &&
  10281. wcsncmp(pid->Psz(), _u("use asm"), 10) == 0);
  10282. #ifdef ENABLE_SCRIPT_DEBUGGING
  10283. if (isAsmCandidate && m_scriptContext->IsScriptContextInDebugMode())
  10284. {
  10285. // We would like to report this to debugger - they may choose to disable debugging.
  10286. // TODO : localization of the string?
  10287. 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);
  10288. return false;
  10289. }
  10290. #endif
  10291. return isAsmCandidate && !(m_grfscr & fscrNoAsmJs);
  10292. #else
  10293. return false;
  10294. #endif
  10295. }
  10296. HRESULT Parser::ParseUtf8Source(__out ParseNodePtr* parseTree, LPCUTF8 pSrc, size_t length, ULONG grfsrc, CompileScriptException *pse,
  10297. Js::LocalFunctionId * nextFunctionId, SourceContextInfo * sourceContextInfo)
  10298. {
  10299. m_functionBody = nullptr;
  10300. m_parseType = ParseType_Upfront;
  10301. return ParseSourceInternal( parseTree, pSrc, 0, length, 0, true, grfsrc, pse, nextFunctionId, 0, sourceContextInfo);
  10302. }
  10303. HRESULT Parser::ParseCesu8Source(__out ParseNodePtr* parseTree, LPCUTF8 pSrc, size_t length, ULONG grfsrc, CompileScriptException *pse,
  10304. Js::LocalFunctionId * nextFunctionId, SourceContextInfo * sourceContextInfo)
  10305. {
  10306. m_functionBody = nullptr;
  10307. m_parseType = ParseType_Upfront;
  10308. return ParseSourceInternal( parseTree, pSrc, 0, length, 0, false, grfsrc, pse, nextFunctionId, 0, sourceContextInfo);
  10309. }
  10310. void Parser::PrepareScanner(bool fromExternal)
  10311. {
  10312. // NOTE: HashTbl and Scanner are currently allocated from the CRT heap. If we want to allocate them from the
  10313. // parser arena, then we also need to change the way the HashTbl allocates PID's from its underlying
  10314. // allocator (which also currently uses the CRT heap). This is not trivial, because we still need to support
  10315. // heap allocation for the colorizer interface.
  10316. // create the hash table and init PID members
  10317. if (nullptr == (m_phtbl = HashTbl::Create(HASH_TABLE_SIZE)))
  10318. Error(ERRnoMemory);
  10319. InitPids();
  10320. // create the scanner
  10321. if (nullptr == (m_pscan = Scanner_t::Create(this, m_phtbl, &m_token, m_scriptContext)))
  10322. Error(ERRnoMemory);
  10323. if (fromExternal)
  10324. m_pscan->FromExternalSource();
  10325. }
  10326. #if ENABLE_BACKGROUND_PARSING
  10327. void Parser::PrepareForBackgroundParse()
  10328. {
  10329. m_pscan->PrepareForBackgroundParse(m_scriptContext);
  10330. }
  10331. void Parser::AddBackgroundParseItem(BackgroundParseItem *const item)
  10332. {
  10333. if (currBackgroundParseItem == nullptr)
  10334. {
  10335. backgroundParseItems = item;
  10336. }
  10337. else
  10338. {
  10339. currBackgroundParseItem->SetNext(item);
  10340. }
  10341. currBackgroundParseItem = item;
  10342. }
  10343. void Parser::AddFastScannedRegExpNode(ParseNodePtr const pnode)
  10344. {
  10345. Assert(!IsBackgroundParser());
  10346. Assert(m_doingFastScan);
  10347. if (fastScannedRegExpNodes == nullptr)
  10348. {
  10349. fastScannedRegExpNodes = Anew(&m_nodeAllocator, NodeDList, &m_nodeAllocator);
  10350. }
  10351. fastScannedRegExpNodes->Append(pnode);
  10352. }
  10353. void Parser::AddBackgroundRegExpNode(ParseNodePtr const pnode)
  10354. {
  10355. Assert(IsBackgroundParser());
  10356. Assert(currBackgroundParseItem != nullptr);
  10357. currBackgroundParseItem->AddRegExpNode(pnode, &m_nodeAllocator);
  10358. }
  10359. HRESULT Parser::ParseFunctionInBackground(ParseNodePtr pnodeFnc, ParseContext *parseContext, bool topLevelDeferred, CompileScriptException *pse)
  10360. {
  10361. m_functionBody = nullptr;
  10362. m_parseType = ParseType_Upfront;
  10363. HRESULT hr = S_OK;
  10364. SmartFPUControl smartFpuControl;
  10365. uint nextFunctionId = pnodeFnc->AsParseNodeFnc()->functionId + 1;
  10366. this->RestoreContext(parseContext);
  10367. m_nextFunctionId = &nextFunctionId;
  10368. m_deferringAST = topLevelDeferred;
  10369. m_inDeferredNestedFunc = false;
  10370. m_scopeCountNoAst = 0;
  10371. SetCurrentStatement(nullptr);
  10372. pnodeFnc->AsParseNodeFnc()->pnodeVars = nullptr;
  10373. pnodeFnc->AsParseNodeFnc()->pnodeParams = nullptr;
  10374. pnodeFnc->AsParseNodeFnc()->pnodeBody = nullptr;
  10375. pnodeFnc->AsParseNodeFnc()->nestedCount = 0;
  10376. ParseNodePtr pnodeParentFnc = GetCurrentFunctionNode();
  10377. m_currentNodeFunc = pnodeFnc;
  10378. m_currentNodeDeferredFunc = nullptr;
  10379. m_ppnodeScope = nullptr;
  10380. m_ppnodeExprScope = nullptr;
  10381. m_pnestedCount = &pnodeFnc->AsParseNodeFnc()->nestedCount;
  10382. m_pCurrentAstSize = &pnodeFnc->AsParseNodeFnc()->astSize;
  10383. ParseNodePtr pnodeBlock = StartParseBlock<true>(PnodeBlockType::Function, ScopeType_FunctionBody);
  10384. pnodeFnc->AsParseNodeFnc()->pnodeScopes = pnodeBlock;
  10385. m_ppnodeScope = &pnodeBlock->AsParseNodeBlock()->pnodeScopes;
  10386. uint uDeferSave = m_grfscr & fscrDeferFncParse;
  10387. try
  10388. {
  10389. m_pscan->Scan();
  10390. m_ppnodeVar = &pnodeFnc->AsParseNodeFnc()->pnodeParams;
  10391. this->ParseFncFormals<true>(pnodeFnc, pnodeParentFnc, fFncNoFlgs);
  10392. if (m_token.tk == tkRParen)
  10393. {
  10394. m_pscan->Scan();
  10395. }
  10396. ChkCurTok(tkLCurly, ERRnoLcurly);
  10397. m_ppnodeVar = &pnodeFnc->AsParseNodeFnc()->pnodeVars;
  10398. // Put the scanner into "no hashing" mode.
  10399. BYTE deferFlags = m_pscan->SetDeferredParse(topLevelDeferred);
  10400. // Process a sequence of statements/declarations
  10401. if (topLevelDeferred)
  10402. {
  10403. ParseStmtList<false>(nullptr, nullptr, SM_DeferredParse, true);
  10404. }
  10405. else
  10406. {
  10407. ParseNodePtr *lastNodeRef = nullptr;
  10408. ParseStmtList<true>(&pnodeFnc->AsParseNodeFnc()->pnodeBody, &lastNodeRef, SM_OnFunctionCode, true);
  10409. AddArgumentsNodeToVars(pnodeFnc);
  10410. // Append an EndCode node.
  10411. AddToNodeList(&pnodeFnc->AsParseNodeFnc()->pnodeBody, &lastNodeRef, CreateNodeWithScanner<knopEndCode>());
  10412. }
  10413. // Restore the scanner's default hashing mode.
  10414. m_pscan->SetDeferredParseFlags(deferFlags);
  10415. #if DBG
  10416. pnodeFnc->AsParseNodeFnc()->deferredParseNextFunctionId = *this->m_nextFunctionId;
  10417. #endif
  10418. this->m_deferringAST = FALSE;
  10419. // Append block as body of pnodeProg
  10420. FinishParseBlock(pnodeBlock);
  10421. }
  10422. catch(ParseExceptionObject& e)
  10423. {
  10424. hr = e.GetError();
  10425. }
  10426. if (FAILED(hr))
  10427. {
  10428. hr = pse->ProcessError(m_pscan, hr, nullptr);
  10429. }
  10430. if (IsStrictMode())
  10431. {
  10432. pnodeFnc->AsParseNodeFnc()->SetStrictMode();
  10433. }
  10434. if (topLevelDeferred)
  10435. {
  10436. pnodeFnc->AsParseNodeFnc()->pnodeVars = nullptr;
  10437. }
  10438. m_grfscr |= uDeferSave;
  10439. Assert(nullptr == *m_ppnodeScope);
  10440. return hr;
  10441. }
  10442. #endif
  10443. HRESULT Parser::ParseSourceWithOffset(__out ParseNodePtr* parseTree, LPCUTF8 pSrc, size_t offset, size_t cbLength, charcount_t cchOffset,
  10444. bool isCesu8, ULONG grfscr, CompileScriptException *pse, Js::LocalFunctionId * nextFunctionId, ULONG lineNumber, SourceContextInfo * sourceContextInfo,
  10445. Js::ParseableFunctionInfo* functionInfo)
  10446. {
  10447. m_functionBody = functionInfo;
  10448. if (m_functionBody)
  10449. {
  10450. m_currDeferredStub = m_functionBody->GetDeferredStubs();
  10451. m_InAsmMode = grfscr & fscrNoAsmJs ? false : m_functionBody->GetIsAsmjsMode();
  10452. }
  10453. m_deferAsmJs = !m_InAsmMode;
  10454. m_parseType = ParseType_Deferred;
  10455. return ParseSourceInternal( parseTree, pSrc, offset, cbLength, cchOffset, !isCesu8, grfscr, pse, nextFunctionId, lineNumber, sourceContextInfo);
  10456. }
  10457. bool Parser::IsStrictMode() const
  10458. {
  10459. return (m_fUseStrictMode ||
  10460. (m_currentNodeFunc != nullptr && m_currentNodeFunc->AsParseNodeFnc()->GetStrictMode()));
  10461. }
  10462. BOOL Parser::ExpectingExternalSource()
  10463. {
  10464. return m_fExpectExternalSource;
  10465. }
  10466. Symbol *ParseNodeFnc::GetFuncSymbol()
  10467. {
  10468. if (pnodeName &&
  10469. pnodeName->nop == knopVarDecl)
  10470. {
  10471. return pnodeName->AsParseNodeVar()->sym;
  10472. }
  10473. return nullptr;
  10474. }
  10475. void ParseNodeFnc::SetFuncSymbol(Symbol *sym)
  10476. {
  10477. Assert(pnodeName &&
  10478. pnodeName->nop == knopVarDecl);
  10479. pnodeName->AsParseNodeVar()->sym = sym;
  10480. }
  10481. ParseNodePtr ParseNodeFnc::GetParamScope() const
  10482. {
  10483. if (this->pnodeScopes == nullptr)
  10484. {
  10485. return nullptr;
  10486. }
  10487. Assert(this->pnodeScopes->nop == knopBlock &&
  10488. this->pnodeScopes->AsParseNodeBlock()->pnodeNext == nullptr);
  10489. return this->pnodeScopes->AsParseNodeBlock()->pnodeScopes;
  10490. }
  10491. ParseNodePtr ParseNodeFnc::GetBodyScope() const
  10492. {
  10493. if (this->pnodeBodyScope == nullptr)
  10494. {
  10495. return nullptr;
  10496. }
  10497. Assert(this->pnodeBodyScope->nop == knopBlock &&
  10498. this->pnodeBodyScope->AsParseNodeBlock()->pnodeNext == nullptr);
  10499. return this->pnodeBodyScope->AsParseNodeBlock()->pnodeScopes;
  10500. }
  10501. // Create node versions with explicit token limits
  10502. ParseNodePtr Parser::CreateNode(OpCode nop, charcount_t ichMin, charcount_t ichLim)
  10503. {
  10504. Assert(!this->m_deferringAST);
  10505. Assert(nop >= 0 && nop < knopLim);
  10506. ParseNodePtr pnode;
  10507. __analysis_assume(nop < knopLim);
  10508. int cb = nop >= 0 && nop < knopLim ? g_mpnopcbNode[nop] : kcbPnNone;
  10509. pnode = (ParseNodePtr)m_nodeAllocator.Alloc(cb);
  10510. Assert(pnode);
  10511. Assert(m_pCurrentAstSize != NULL);
  10512. *m_pCurrentAstSize += cb;
  10513. pnode->Init(nop, ichMin, ichLim);
  10514. return pnode;
  10515. }
  10516. ParseNodePtr Parser::CreateNameNode(IdentPtr pid,charcount_t ichMin,charcount_t ichLim)
  10517. {
  10518. ParseNodePtr pnode = CreateNodeT<knopName>(ichMin,ichLim);
  10519. pnode->AsParseNodePid()->pid = pid;
  10520. pnode->AsParseNodePid()->sym=NULL;
  10521. pnode->AsParseNodePid()->symRef=NULL;
  10522. return pnode;
  10523. }
  10524. ParseNodePtr Parser::CreateUniNode(OpCode nop, ParseNodePtr pnode1, charcount_t ichMin,charcount_t ichLim)
  10525. {
  10526. Assert(!this->m_deferringAST);
  10527. DebugOnly(VerifyNodeSize(nop, kcbPnUni));
  10528. ParseNodePtr pnode = (ParseNodePtr)m_nodeAllocator.Alloc(kcbPnUni);
  10529. Assert(m_pCurrentAstSize != NULL);
  10530. *m_pCurrentAstSize += kcbPnUni;
  10531. pnode->Init(nop, ichMin, ichLim);
  10532. pnode->AsParseNodeUni()->pnode1 = pnode1;
  10533. return pnode;
  10534. }
  10535. ParseNodePtr Parser::CreateBinNode(OpCode nop, ParseNodePtr pnode1,
  10536. ParseNodePtr pnode2,charcount_t ichMin,charcount_t ichLim)
  10537. {
  10538. Assert(!this->m_deferringAST);
  10539. ParseNodePtr pnode = StaticCreateBinNode(nop, pnode1, pnode2, &m_nodeAllocator);
  10540. Assert(m_pCurrentAstSize != NULL);
  10541. *m_pCurrentAstSize += kcbPnBin;
  10542. pnode->ichMin = ichMin;
  10543. pnode->ichLim = ichLim;
  10544. return pnode;
  10545. }
  10546. ParseNodePtr Parser::CreateTriNode(OpCode nop, ParseNodePtr pnode1,
  10547. ParseNodePtr pnode2, ParseNodePtr pnode3,
  10548. charcount_t ichMin,charcount_t ichLim)
  10549. {
  10550. Assert(!this->m_deferringAST);
  10551. DebugOnly(VerifyNodeSize(nop, kcbPnTri));
  10552. ParseNodePtr pnode = (ParseNodePtr)m_nodeAllocator.Alloc(kcbPnTri);
  10553. Assert(m_pCurrentAstSize != NULL);
  10554. *m_pCurrentAstSize += kcbPnTri;
  10555. pnode->Init(nop, ichMin, ichLim);
  10556. pnode->AsParseNodeTri()->pnodeNext = NULL;
  10557. pnode->AsParseNodeTri()->pnode1 = pnode1;
  10558. pnode->AsParseNodeTri()->pnode2 = pnode2;
  10559. pnode->AsParseNodeTri()->pnode3 = pnode3;
  10560. return pnode;
  10561. }
  10562. bool ParseNodeBlock::HasBlockScopedContent() const
  10563. {
  10564. // A block has its own content if a let, const, or function is declared there.
  10565. if (this->pnodeLexVars != nullptr || this->blockType == Parameter)
  10566. {
  10567. return true;
  10568. }
  10569. // The enclosing scopes can contain functions and other things, so walk the list
  10570. // looking specifically for functions.
  10571. for (ParseNodePtr pnode = this->pnodeScopes; pnode;)
  10572. {
  10573. switch (pnode->nop) {
  10574. case knopFncDecl:
  10575. return true;
  10576. case knopBlock:
  10577. pnode = pnode->AsParseNodeBlock()->pnodeNext;
  10578. break;
  10579. case knopCatch:
  10580. pnode = pnode->AsParseNodeCatch()->pnodeNext;
  10581. break;
  10582. case knopWith:
  10583. pnode = pnode->AsParseNodeWith()->pnodeNext;
  10584. break;
  10585. default:
  10586. Assert(UNREACHED);
  10587. return true;
  10588. }
  10589. }
  10590. return false;
  10591. }
  10592. class ByteCodeGenerator;
  10593. // Copy AST; this works mostly on expressions for now
  10594. ParseNode* Parser::CopyPnode(ParseNode *pnode) {
  10595. if (pnode==NULL)
  10596. return NULL;
  10597. switch (pnode->nop) {
  10598. //PTNODE(knopName , "name" ,None ,Pid ,fnopLeaf)
  10599. case knopName: {
  10600. ParseNode* nameNode=CreateNameNode(pnode->AsParseNodePid()->pid,pnode->ichMin,pnode->ichLim);
  10601. nameNode->AsParseNodePid()->sym=pnode->AsParseNodePid()->sym;
  10602. return nameNode;
  10603. }
  10604. //PTNODE(knopInt , "int const" ,None ,Int ,fnopLeaf|fnopConst)
  10605. case knopInt:
  10606. return pnode;
  10607. //PTNODE(knopFlt , "flt const" ,None ,Flt ,fnopLeaf|fnopConst)
  10608. case knopFlt:
  10609. return pnode;
  10610. //PTNODE(knopStr , "str const" ,None ,Pid ,fnopLeaf|fnopConst)
  10611. case knopStr:
  10612. return pnode;
  10613. //PTNODE(knopRegExp , "reg expr" ,None ,Pid ,fnopLeaf|fnopConst)
  10614. case knopRegExp:
  10615. return pnode;
  10616. break;
  10617. //PTNODE(knopNull , "null" ,Null ,None ,fnopLeaf)
  10618. case knopNull:
  10619. return pnode;
  10620. //PTNODE(knopFalse , "false" ,False ,None ,fnopLeaf)
  10621. case knopFalse:
  10622. {
  10623. ParseNode* ret = CreateNodeT<knopFalse>(pnode->ichMin, pnode->ichLim);
  10624. ret->location = pnode->location;
  10625. return ret;
  10626. }
  10627. //PTNODE(knopTrue , "true" ,True ,None ,fnopLeaf)
  10628. case knopTrue:
  10629. {
  10630. ParseNode* ret = CreateNodeT<knopTrue>(pnode->ichMin, pnode->ichLim);
  10631. ret->location = pnode->location;
  10632. return ret;
  10633. }
  10634. //PTNODE(knopEmpty , "empty" ,Empty ,None ,fnopLeaf)
  10635. case knopEmpty:
  10636. return CreateNodeT<knopEmpty>(pnode->ichMin,pnode->ichLim);
  10637. // Unary operators.
  10638. //PTNODE(knopNot , "~" ,BitNot ,Uni ,fnopUni)
  10639. //PTNODE(knopNeg , "unary -" ,Neg ,Uni ,fnopUni)
  10640. //PTNODE(knopPos , "unary +" ,Pos ,Uni ,fnopUni)
  10641. //PTNODE(knopLogNot , "!" ,LogNot ,Uni ,fnopUni)
  10642. //PTNODE(knopEllipsis , "..." ,Spread ,Uni , fnopUni)
  10643. //PTNODE(knopDecPost , "-- post" ,Dec ,Uni ,fnopUni|fnopAsg)
  10644. //PTNODE(knopIncPre , "++ pre" ,Inc ,Uni ,fnopUni|fnopAsg)
  10645. //PTNODE(knopDecPre , "-- pre" ,Dec ,Uni ,fnopUni|fnopAsg)
  10646. //PTNODE(knopTypeof , "typeof" ,None ,Uni ,fnopUni)
  10647. //PTNODE(knopVoid , "void" ,Void ,Uni ,fnopUni)
  10648. //PTNODE(knopDelete , "delete" ,None ,Uni ,fnopUni)
  10649. case knopNot:
  10650. case knopNeg:
  10651. case knopPos:
  10652. case knopLogNot:
  10653. case knopEllipsis:
  10654. case knopIncPost:
  10655. case knopDecPost:
  10656. case knopIncPre:
  10657. case knopDecPre:
  10658. case knopTypeof:
  10659. case knopVoid:
  10660. case knopDelete:
  10661. return CreateUniNode(pnode->nop,CopyPnode(pnode->AsParseNodeUni()->pnode1),pnode->ichMin,pnode->ichLim);
  10662. //PTNODE(knopArray , "arr cnst" ,None ,Uni ,fnopUni)
  10663. //PTNODE(knopObject , "obj cnst" ,None ,Uni ,fnopUni)
  10664. case knopArray:
  10665. case knopObject:
  10666. // TODO: need to copy arr
  10667. Assert(false);
  10668. break;
  10669. // Binary operators
  10670. //PTNODE(knopAdd , "+" ,Add ,Bin ,fnopBin)
  10671. //PTNODE(knopSub , "-" ,Sub ,Bin ,fnopBin)
  10672. //PTNODE(knopMul , "*" ,Mul ,Bin ,fnopBin)
  10673. //PTNODE(knopExpo , "**" ,Expo ,Bin ,fnopBin)
  10674. //PTNODE(knopDiv , "/" ,Div ,Bin ,fnopBin)
  10675. //PTNODE(knopMod , "%" ,Mod ,Bin ,fnopBin)
  10676. //PTNODE(knopOr , "|" ,BitOr ,Bin ,fnopBin)
  10677. //PTNODE(knopXor , "^" ,BitXor ,Bin ,fnopBin)
  10678. //PTNODE(knopAnd , "&" ,BitAnd ,Bin ,fnopBin)
  10679. //PTNODE(knopEq , "==" ,EQ ,Bin ,fnopBin|fnopRel)
  10680. //PTNODE(knopNe , "!=" ,NE ,Bin ,fnopBin|fnopRel)
  10681. //PTNODE(knopLt , "<" ,LT ,Bin ,fnopBin|fnopRel)
  10682. //PTNODE(knopLe , "<=" ,LE ,Bin ,fnopBin|fnopRel)
  10683. //PTNODE(knopGe , ">=" ,GE ,Bin ,fnopBin|fnopRel)
  10684. //PTNODE(knopGt , ">" ,GT ,Bin ,fnopBin|fnopRel)
  10685. //PTNODE(knopEqv , "===" ,Eqv ,Bin ,fnopBin|fnopRel)
  10686. //PTNODE(knopIn , "in" ,In ,Bin ,fnopBin|fnopRel)
  10687. //PTNODE(knopInstOf , "instanceof",InstOf ,Bin ,fnopBin|fnopRel)
  10688. //PTNODE(knopNEqv , "!==" ,NEqv ,Bin ,fnopBin|fnopRel)
  10689. //PTNODE(knopComma , "," ,None ,Bin ,fnopBin)
  10690. //PTNODE(knopLogOr , "||" ,None ,Bin ,fnopBin)
  10691. //PTNODE(knopLogAnd , "&&" ,None ,Bin ,fnopBin)
  10692. //PTNODE(knopLsh , "<<" ,Lsh ,Bin ,fnopBin)
  10693. //PTNODE(knopRsh , ">>" ,Rsh ,Bin ,fnopBin)
  10694. //PTNODE(knopRs2 , ">>>" ,Rs2 ,Bin ,fnopBin)
  10695. case knopAdd:
  10696. case knopSub:
  10697. case knopMul:
  10698. case knopExpo:
  10699. case knopDiv:
  10700. case knopMod:
  10701. case knopOr:
  10702. case knopXor:
  10703. case knopAnd:
  10704. case knopEq:
  10705. case knopNe:
  10706. case knopLt:
  10707. case knopLe:
  10708. case knopGe:
  10709. case knopGt:
  10710. case knopEqv:
  10711. case knopIn:
  10712. case knopInstOf:
  10713. case knopNEqv:
  10714. case knopComma:
  10715. case knopLogOr:
  10716. case knopLogAnd:
  10717. case knopLsh:
  10718. case knopRsh:
  10719. case knopRs2:
  10720. //PTNODE(knopAsg , "=" ,None ,Bin ,fnopBin|fnopAsg)
  10721. case knopAsg:
  10722. //PTNODE(knopDot , "." ,None ,Bin ,fnopBin)
  10723. case knopDot:
  10724. //PTNODE(knopAsgAdd , "+=" ,Add ,Bin ,fnopBin|fnopAsg)
  10725. case knopAsgAdd:
  10726. //PTNODE(knopAsgSub , "-=" ,Sub ,Bin ,fnopBin|fnopAsg)
  10727. case knopAsgSub:
  10728. //PTNODE(knopAsgMul , "*=" ,Mul ,Bin ,fnopBin|fnopAsg)
  10729. case knopAsgMul:
  10730. //PTNODE(knopAsgDiv , "/=" ,Div ,Bin ,fnopBin|fnopAsg)
  10731. case knopAsgExpo:
  10732. //PTNODE(knopAsgExpo , "**=" ,Expo ,Bin ,fnopBin|fnopAsg)
  10733. case knopAsgDiv:
  10734. //PTNODE(knopAsgMod , "%=" ,Mod ,Bin ,fnopBin|fnopAsg)
  10735. case knopAsgMod:
  10736. //PTNODE(knopAsgAnd , "&=" ,BitAnd ,Bin ,fnopBin|fnopAsg)
  10737. case knopAsgAnd:
  10738. //PTNODE(knopAsgXor , "^=" ,BitXor ,Bin ,fnopBin|fnopAsg)
  10739. case knopAsgXor:
  10740. //PTNODE(knopAsgOr , "|=" ,BitOr ,Bin ,fnopBin|fnopAsg)
  10741. case knopAsgOr:
  10742. //PTNODE(knopAsgLsh , "<<=" ,Lsh ,Bin ,fnopBin|fnopAsg)
  10743. case knopAsgLsh:
  10744. //PTNODE(knopAsgRsh , ">>=" ,Rsh ,Bin ,fnopBin|fnopAsg)
  10745. case knopAsgRsh:
  10746. //PTNODE(knopAsgRs2 , ">>>=" ,Rs2 ,Bin ,fnopBin|fnopAsg)
  10747. case knopAsgRs2:
  10748. //PTNODE(knopMember , ":" ,None ,Bin ,fnopBin)
  10749. case knopMember:
  10750. case knopMemberShort:
  10751. //PTNODE(knopIndex , "[]" ,None ,Bin ,fnopBin)
  10752. //PTNODE(knopList , "<list>" ,None ,Bin ,fnopNone)
  10753. case knopIndex:
  10754. case knopList:
  10755. return CreateBinNode(pnode->nop,CopyPnode(pnode->AsParseNodeBin()->pnode1),
  10756. CopyPnode(pnode->AsParseNodeBin()->pnode2),pnode->ichMin,pnode->ichLim);
  10757. //PTNODE(knopCall , "()" ,None ,Bin ,fnopBin)
  10758. //PTNODE(knopNew , "new" ,None ,Bin ,fnopBin)
  10759. case knopNew:
  10760. case knopCall:
  10761. return CreateCallNode(pnode->nop,CopyPnode(pnode->AsParseNodeCall()->pnodeTarget),
  10762. CopyPnode(pnode->AsParseNodeCall()->pnodeArgs),pnode->ichMin,pnode->ichLim);
  10763. //PTNODE(knopQmark , "?" ,None ,Tri ,fnopBin)
  10764. case knopQmark:
  10765. return CreateTriNode(pnode->nop,CopyPnode(pnode->AsParseNodeTri()->pnode1),
  10766. CopyPnode(pnode->AsParseNodeTri()->pnode2),CopyPnode(pnode->AsParseNodeTri()->pnode3),
  10767. pnode->ichMin,pnode->ichLim);
  10768. // General nodes.
  10769. //PTNODE(knopVarDecl , "varDcl" ,None ,Var ,fnopNone)
  10770. case knopVarDecl: {
  10771. ParseNode* copyNode=CreateNodeT<knopVarDecl>(pnode->ichMin,pnode->ichLim);
  10772. copyNode->AsParseNodeVar()->pnodeInit=CopyPnode(pnode->AsParseNodeVar()->pnodeInit);
  10773. copyNode->AsParseNodeVar()->sym=pnode->AsParseNodeVar()->sym;
  10774. // TODO: mult-decl
  10775. Assert(pnode->AsParseNodeVar()->pnodeNext==NULL);
  10776. copyNode->AsParseNodeVar()->pnodeNext=NULL;
  10777. return copyNode;
  10778. }
  10779. //PTNODE(knopFncDecl , "fncDcl" ,None ,Fnc ,fnopLeaf)
  10780. //PTNODE(knopProg , "program" ,None ,Fnc ,fnopNone)
  10781. case knopFncDecl:
  10782. case knopProg:
  10783. Assert(false);
  10784. break;
  10785. //PTNODE(knopEndCode , "<endcode>" ,None ,None ,fnopNone)
  10786. case knopEndCode:
  10787. break;
  10788. //PTNODE(knopDebugger , "debugger" ,None ,None ,fnopNone)
  10789. case knopDebugger:
  10790. break;
  10791. //PTNODE(knopFor , "for" ,None ,For ,fnopBreak|fnopContinue)
  10792. case knopFor: {
  10793. ParseNode* copyNode=CreateNodeT<knopFor>(pnode->ichMin,pnode->ichLim);
  10794. copyNode->AsParseNodeFor()->pnodeInverted=NULL;
  10795. copyNode->AsParseNodeFor()->pnodeInit=CopyPnode(pnode->AsParseNodeFor()->pnodeInit);
  10796. copyNode->AsParseNodeFor()->pnodeCond=CopyPnode(pnode->AsParseNodeFor()->pnodeCond);
  10797. copyNode->AsParseNodeFor()->pnodeIncr=CopyPnode(pnode->AsParseNodeFor()->pnodeIncr);
  10798. copyNode->AsParseNodeFor()->pnodeBody=CopyPnode(pnode->AsParseNodeFor()->pnodeBody);
  10799. return copyNode;
  10800. }
  10801. //PTNODE(knopIf , "if" ,None ,If ,fnopNone)
  10802. case knopIf:
  10803. Assert(false);
  10804. break;
  10805. //PTNODE(knopWhile , "while" ,None ,While,fnopBreak|fnopContinue)
  10806. case knopWhile:
  10807. Assert(false);
  10808. break;
  10809. //PTNODE(knopDoWhile , "do-while" ,None ,While,fnopBreak|fnopContinue)
  10810. case knopDoWhile:
  10811. Assert(false);
  10812. break;
  10813. //PTNODE(knopForIn , "for in" ,None ,ForIn,fnopBreak|fnopContinue|fnopCleanup)
  10814. case knopForIn:
  10815. Assert(false);
  10816. break;
  10817. case knopForOf:
  10818. Assert(false);
  10819. break;
  10820. //PTNODE(knopReturn , "return" ,None ,Uni ,fnopNone)
  10821. case knopReturn: {
  10822. ParseNode* copyNode=CreateNodeT<knopReturn>(pnode->ichMin,pnode->ichLim);
  10823. copyNode->AsParseNodeReturn()->pnodeExpr=CopyPnode(pnode->AsParseNodeReturn()->pnodeExpr);
  10824. return copyNode;
  10825. }
  10826. //PTNODE(knopBlock , "{}" ,None ,Block,fnopNone)
  10827. case knopBlock: {
  10828. ParseNode* copyNode=CreateBlockNode(pnode->ichMin,pnode->ichLim,pnode->AsParseNodeBlock()->blockType);
  10829. if (pnode->grfpn & PNodeFlags::fpnSyntheticNode) {
  10830. // fpnSyntheticNode is sometimes set on PnodeBlockType::Regular blocks which
  10831. // CreateBlockNode() will not automatically set for us, so set it here if it's
  10832. // specified on the source node.
  10833. copyNode->grfpn |= PNodeFlags::fpnSyntheticNode;
  10834. }
  10835. copyNode->AsParseNodeBlock()->pnodeStmt=CopyPnode(pnode->AsParseNodeBlock()->pnodeStmt);
  10836. return copyNode;
  10837. }
  10838. //PTNODE(knopWith , "with" ,None ,With ,fnopCleanup)
  10839. case knopWith:
  10840. Assert(false);
  10841. break;
  10842. //PTNODE(knopBreak , "break" ,None ,Jump ,fnopNone)
  10843. case knopBreak:
  10844. Assert(false);
  10845. break;
  10846. //PTNODE(knopContinue , "continue" ,None ,Jump ,fnopNone)
  10847. case knopContinue:
  10848. Assert(false);
  10849. break;
  10850. //PTNODE(knopSwitch , "switch" ,None ,Switch,fnopBreak)
  10851. case knopSwitch:
  10852. Assert(false);
  10853. break;
  10854. //PTNODE(knopCase , "case" ,None ,Case ,fnopNone)
  10855. case knopCase:
  10856. Assert(false);
  10857. break;
  10858. //PTNODE(knopTryFinally,"try-finally",None,TryFinally,fnopCleanup)
  10859. case knopTryFinally:
  10860. Assert(false);
  10861. break;
  10862. case knopFinally:
  10863. Assert(false);
  10864. break;
  10865. //PTNODE(knopCatch , "catch" ,None ,Catch,fnopNone)
  10866. case knopCatch:
  10867. Assert(false);
  10868. break;
  10869. //PTNODE(knopTryCatch , "try-catch" ,None ,TryCatch ,fnopCleanup)
  10870. case knopTryCatch:
  10871. Assert(false);
  10872. break;
  10873. //PTNODE(knopTry , "try" ,None ,Try ,fnopCleanup)
  10874. case knopTry:
  10875. Assert(false);
  10876. break;
  10877. //PTNODE(knopThrow , "throw" ,None ,Uni ,fnopNone)
  10878. case knopThrow:
  10879. Assert(false);
  10880. break;
  10881. default:
  10882. Assert(false);
  10883. break;
  10884. }
  10885. return NULL;
  10886. }
  10887. // Returns true when str is string for Nan, Infinity or -Infinity.
  10888. // Does not check for double number value being in NaN/Infinity range.
  10889. // static
  10890. template<bool CheckForNegativeInfinity>
  10891. inline bool Parser::IsNaNOrInfinityLiteral(LPCOLESTR str)
  10892. {
  10893. // Note: wcscmp crashes when one of the parameters is NULL.
  10894. return str &&
  10895. (wcscmp(_u("NaN"), str) == 0 ||
  10896. wcscmp(_u("Infinity"), str) == 0 ||
  10897. (CheckForNegativeInfinity && wcscmp(_u("-Infinity"), str) == 0));
  10898. }
  10899. template <bool buildAST>
  10900. IdentPtr Parser::ParseSuper(bool fAllowCall)
  10901. {
  10902. ParseNodePtr currentNodeFunc = GetCurrentFunctionNode();
  10903. IdentPtr superPid = nullptr;
  10904. switch (m_token.tk)
  10905. {
  10906. case tkDot: // super.prop
  10907. case tkLBrack: // super[foo]
  10908. superPid = wellKnownPropertyPids._super;
  10909. break;
  10910. case tkLParen: // super(args)
  10911. superPid = wellKnownPropertyPids._superConstructor;
  10912. break;
  10913. default:
  10914. Error(ERRInvalidSuper);
  10915. break;
  10916. }
  10917. currentNodeFunc->AsParseNodeFnc()->SetHasSuperReference(TRUE);
  10918. CHAKRATEL_LANGSTATS_INC_LANGFEATURECOUNT(ES6, Super, m_scriptContext);
  10919. // If we are defer parsing, we can skip verifying that the super reference is valid.
  10920. // If it wasn't the parser would have thrown during upfront parsing and we wouldn't be defer parsing the function.
  10921. if (m_parseType == ParseType_Deferred)
  10922. {
  10923. return superPid;
  10924. }
  10925. if (!fAllowCall && (m_token.tk == tkLParen))
  10926. {
  10927. Error(ERRInvalidSuper); // new super() is not allowed
  10928. }
  10929. else if (this->m_parsingSuperRestrictionState == ParsingSuperRestrictionState_SuperCallAndPropertyAllowed)
  10930. {
  10931. // Any super access is good within a class constructor
  10932. }
  10933. else if (this->m_parsingSuperRestrictionState == ParsingSuperRestrictionState_SuperPropertyAllowed)
  10934. {
  10935. if (m_token.tk == tkLParen)
  10936. {
  10937. if ((this->m_grfscr & fscrEval) == fscrNil)
  10938. {
  10939. // Cannot call super within a class member
  10940. Error(ERRInvalidSuper);
  10941. }
  10942. else
  10943. {
  10944. Js::JavascriptFunction * caller = nullptr;
  10945. if (Js::JavascriptStackWalker::GetCaller(&caller, m_scriptContext))
  10946. {
  10947. Js::FunctionBody * callerBody = caller->GetFunctionBody();
  10948. Assert(callerBody);
  10949. if (!callerBody->GetFunctionInfo()->GetAllowDirectSuper())
  10950. {
  10951. Error(ERRInvalidSuper);
  10952. }
  10953. }
  10954. }
  10955. }
  10956. }
  10957. else
  10958. {
  10959. // Anything else is an error
  10960. Error(ERRInvalidSuper);
  10961. }
  10962. return superPid;
  10963. }
  10964. void Parser::AppendToList(ParseNodePtr *node, ParseNodePtr nodeToAppend)
  10965. {
  10966. Assert(nodeToAppend);
  10967. ParseNodePtr* lastPtr = node;
  10968. while ((*lastPtr) && (*lastPtr)->nop == knopList)
  10969. {
  10970. lastPtr = &(*lastPtr)->AsParseNodeBin()->pnode2;
  10971. }
  10972. auto last = (*lastPtr);
  10973. if (last)
  10974. {
  10975. *lastPtr = CreateBinNode(knopList, last, nodeToAppend, last->ichMin, nodeToAppend->ichLim);
  10976. }
  10977. else
  10978. {
  10979. *lastPtr = nodeToAppend;
  10980. }
  10981. }
  10982. ParseNodePtr Parser::ConvertArrayToArrayPattern(ParseNodePtr pnode)
  10983. {
  10984. Assert(pnode->nop == knopArray);
  10985. pnode->nop = knopArrayPattern;
  10986. ForEachItemRefInList(&pnode->AsParseNodeArrLit()->pnode1, [&](ParseNodePtr *itemRef) {
  10987. ParseNodePtr item = *itemRef;
  10988. if (item->nop == knopEllipsis)
  10989. {
  10990. itemRef = &item->AsParseNodeUni()->pnode1;
  10991. item = *itemRef;
  10992. if (!(item->nop == knopName
  10993. || item->nop == knopDot
  10994. || item->nop == knopIndex
  10995. || item->nop == knopArray
  10996. || item->nop == knopObject))
  10997. {
  10998. Error(ERRInvalidAssignmentTarget);
  10999. }
  11000. }
  11001. else if (item->nop == knopAsg)
  11002. {
  11003. itemRef = &item->AsParseNodeBin()->pnode1;
  11004. item = *itemRef;
  11005. }
  11006. if (item->nop == knopArray)
  11007. {
  11008. ConvertArrayToArrayPattern(item);
  11009. }
  11010. else if (item->nop == knopObject)
  11011. {
  11012. *itemRef = ConvertObjectToObjectPattern(item);
  11013. }
  11014. else if (item->nop == knopName)
  11015. {
  11016. TrackAssignment<true>(item, nullptr);
  11017. }
  11018. });
  11019. return pnode;
  11020. }
  11021. ParseNodePtr Parser::CreateParamPatternNode(ParseNodePtr pnode1)
  11022. {
  11023. ParseNodePtr paramPatternNode = CreateNode(knopParamPattern, pnode1->ichMin, pnode1->ichLim);
  11024. paramPatternNode->AsParseNodeParamPattern()->pnode1 = pnode1;
  11025. paramPatternNode->AsParseNodeParamPattern()->pnodeNext = nullptr;
  11026. paramPatternNode->AsParseNodeParamPattern()->location = Js::Constants::NoRegister;
  11027. return paramPatternNode;
  11028. }
  11029. ParseNodePtr Parser::CreateDummyParamPatternNode(charcount_t ichMin)
  11030. {
  11031. ParseNodePtr paramPatternNode = CreateNode(knopParamPattern, ichMin);
  11032. paramPatternNode->AsParseNodeParamPattern()->pnode1 = nullptr;
  11033. paramPatternNode->AsParseNodeParamPattern()->pnodeNext = nullptr;
  11034. paramPatternNode->AsParseNodeParamPattern()->location = Js::Constants::NoRegister;
  11035. return paramPatternNode;
  11036. }
  11037. ParseNodePtr Parser::ConvertObjectToObjectPattern(ParseNodePtr pnodeMemberList)
  11038. {
  11039. charcount_t ichMin = m_pscan->IchMinTok();
  11040. charcount_t ichLim = m_pscan->IchLimTok();
  11041. ParseNodePtr pnodeMemberNodeList = nullptr;
  11042. if (pnodeMemberList != nullptr && pnodeMemberList->nop == knopObject)
  11043. {
  11044. ichMin = pnodeMemberList->ichMin;
  11045. ichLim = pnodeMemberList->ichLim;
  11046. pnodeMemberList = pnodeMemberList->AsParseNodeUni()->pnode1;
  11047. }
  11048. ForEachItemInList(pnodeMemberList, [&](ParseNodePtr item) {
  11049. ParseNodePtr memberNode = ConvertMemberToMemberPattern(item);
  11050. AppendToList(&pnodeMemberNodeList, memberNode);
  11051. });
  11052. return CreateUniNode(knopObjectPattern, pnodeMemberNodeList, ichMin, ichLim);
  11053. }
  11054. ParseNodePtr Parser::GetRightSideNodeFromPattern(ParseNodePtr pnode)
  11055. {
  11056. Assert(pnode != nullptr);
  11057. ParseNodePtr rightNode = nullptr;
  11058. OpCode op = pnode->nop;
  11059. if (op == knopObject)
  11060. {
  11061. rightNode = ConvertObjectToObjectPattern(pnode);
  11062. }
  11063. else if (op == knopArray)
  11064. {
  11065. rightNode = ConvertArrayToArrayPattern(pnode);
  11066. }
  11067. else
  11068. {
  11069. rightNode = pnode;
  11070. if (op == knopName)
  11071. {
  11072. TrackAssignment<true>(pnode, nullptr);
  11073. }
  11074. else if (op == knopAsg)
  11075. {
  11076. TrackAssignment<true>(pnode->AsParseNodeBin()->pnode1, nullptr);
  11077. }
  11078. }
  11079. return rightNode;
  11080. }
  11081. ParseNodePtr Parser::ConvertMemberToMemberPattern(ParseNodePtr pnodeMember)
  11082. {
  11083. if (pnodeMember->nop == knopObjectPatternMember)
  11084. {
  11085. return pnodeMember;
  11086. }
  11087. Assert(pnodeMember->nop == knopMember || pnodeMember->nop == knopMemberShort);
  11088. ParseNodePtr rightNode = GetRightSideNodeFromPattern(pnodeMember->AsParseNodeBin()->pnode2);
  11089. ParseNodePtr resultNode = CreateBinNode(knopObjectPatternMember, pnodeMember->AsParseNodeBin()->pnode1, rightNode);
  11090. resultNode->ichMin = pnodeMember->ichMin;
  11091. resultNode->ichLim = pnodeMember->ichLim;
  11092. return resultNode;
  11093. }
  11094. ParseNodePtr Parser::ConvertToPattern(ParseNodePtr pnode)
  11095. {
  11096. if (pnode != nullptr)
  11097. {
  11098. if (pnode->nop == knopArray)
  11099. {
  11100. ConvertArrayToArrayPattern(pnode);
  11101. }
  11102. else if (pnode->nop == knopObject)
  11103. {
  11104. pnode = ConvertObjectToObjectPattern(pnode);
  11105. }
  11106. }
  11107. return pnode;
  11108. }
  11109. // This essentially be called for verifying the structure of the current tree with satisfying the destructuring grammar.
  11110. void Parser::ParseDestructuredLiteralWithScopeSave(tokens declarationType,
  11111. bool isDecl,
  11112. bool topLevel,
  11113. DestructuringInitializerContext initializerContext/* = DIC_None*/,
  11114. bool allowIn /*= true*/)
  11115. {
  11116. // We are going to parse the text again to validate the current grammar as Destructuring. Saving some scopes and
  11117. // AST related information before the validation parsing and later they will be restored.
  11118. ParseNodePtr pnodeFncSave = m_currentNodeFunc;
  11119. ParseNodePtr pnodeDeferredFncSave = m_currentNodeDeferredFunc;
  11120. if (m_currentNodeDeferredFunc == nullptr)
  11121. {
  11122. m_currentNodeDeferredFunc = m_currentNodeFunc;
  11123. }
  11124. int32 *pAstSizeSave = m_pCurrentAstSize;
  11125. uint *pNestedCountSave = m_pnestedCount;
  11126. ParseNodePtr *ppnodeScopeSave = m_ppnodeScope;
  11127. ParseNodePtr *ppnodeExprScopeSave = m_ppnodeExprScope;
  11128. ParseNodePtr newTempScope = nullptr;
  11129. m_ppnodeScope = &newTempScope;
  11130. int32 newTempAstSize = 0;
  11131. m_pCurrentAstSize = &newTempAstSize;
  11132. uint newTempNestedCount = 0;
  11133. m_pnestedCount = &newTempNestedCount;
  11134. m_ppnodeExprScope = nullptr;
  11135. charcount_t funcInArraySave = m_funcInArray;
  11136. uint funcInArrayDepthSave = m_funcInArrayDepth;
  11137. // we need to reset this as we are going to parse the grammar again.
  11138. m_hasDeferredShorthandInitError = false;
  11139. ParseDestructuredLiteral<false>(declarationType, isDecl, topLevel, initializerContext, allowIn);
  11140. m_currentNodeFunc = pnodeFncSave;
  11141. m_currentNodeDeferredFunc = pnodeDeferredFncSave;
  11142. m_pCurrentAstSize = pAstSizeSave;
  11143. m_pnestedCount = pNestedCountSave;
  11144. m_ppnodeScope = ppnodeScopeSave;
  11145. m_ppnodeExprScope = ppnodeExprScopeSave;
  11146. m_funcInArray = funcInArraySave;
  11147. m_funcInArrayDepth = funcInArrayDepthSave;
  11148. }
  11149. template <bool buildAST>
  11150. ParseNodePtr Parser::ParseDestructuredLiteral(tokens declarationType,
  11151. bool isDecl,
  11152. bool topLevel/* = true*/,
  11153. DestructuringInitializerContext initializerContext/* = DIC_None*/,
  11154. bool allowIn/* = true*/,
  11155. BOOL *forInOfOkay/* = nullptr*/,
  11156. BOOL *nativeForOkay/* = nullptr*/)
  11157. {
  11158. ParseNodePtr pnode = nullptr;
  11159. Assert(IsPossiblePatternStart());
  11160. if (m_token.tk == tkLCurly)
  11161. {
  11162. pnode = ParseDestructuredObjectLiteral<buildAST>(declarationType, isDecl, topLevel);
  11163. }
  11164. else
  11165. {
  11166. pnode = ParseDestructuredArrayLiteral<buildAST>(declarationType, isDecl, topLevel);
  11167. }
  11168. return ParseDestructuredInitializer<buildAST>(pnode, isDecl, topLevel, initializerContext, allowIn, forInOfOkay, nativeForOkay);
  11169. }
  11170. template <bool buildAST>
  11171. ParseNodePtr Parser::ParseDestructuredInitializer(ParseNodePtr lhsNode,
  11172. bool isDecl,
  11173. bool topLevel,
  11174. DestructuringInitializerContext initializerContext,
  11175. bool allowIn,
  11176. BOOL *forInOfOkay,
  11177. BOOL *nativeForOkay)
  11178. {
  11179. m_pscan->Scan();
  11180. if (topLevel && nativeForOkay == nullptr)
  11181. {
  11182. if (initializerContext != DIC_ForceErrorOnInitializer && m_token.tk != tkAsg)
  11183. {
  11184. // e.g. var {x};
  11185. Error(ERRDestructInit);
  11186. }
  11187. else if (initializerContext == DIC_ForceErrorOnInitializer && m_token.tk == tkAsg)
  11188. {
  11189. // e.g. catch([x] = [0])
  11190. Error(ERRDestructNotInit);
  11191. }
  11192. }
  11193. if (m_token.tk != tkAsg || initializerContext == DIC_ShouldNotParseInitializer)
  11194. {
  11195. if (topLevel && nativeForOkay != nullptr)
  11196. {
  11197. // Native loop should have destructuring initializer
  11198. *nativeForOkay = FALSE;
  11199. }
  11200. return lhsNode;
  11201. }
  11202. if (forInOfOkay)
  11203. {
  11204. *forInOfOkay = FALSE;
  11205. }
  11206. m_pscan->Scan();
  11207. bool alreadyHasInitError = m_hasDeferredShorthandInitError;
  11208. ParseNodePtr pnodeDefault = ParseExpr<buildAST>(koplCma, nullptr, allowIn);
  11209. if (m_hasDeferredShorthandInitError && !alreadyHasInitError)
  11210. {
  11211. Error(ERRnoColon);
  11212. }
  11213. ParseNodePtr pnodeDestructAsg = nullptr;
  11214. if (buildAST)
  11215. {
  11216. Assert(lhsNode != nullptr);
  11217. pnodeDestructAsg = CreateNodeWithScanner<knopAsg>();
  11218. pnodeDestructAsg->AsParseNodeBin()->pnode1 = lhsNode;
  11219. pnodeDestructAsg->AsParseNodeBin()->pnode2 = pnodeDefault;
  11220. pnodeDestructAsg->AsParseNodeBin()->pnodeNext = nullptr;
  11221. pnodeDestructAsg->ichMin = lhsNode->ichMin;
  11222. pnodeDestructAsg->ichLim = pnodeDefault->ichLim;
  11223. }
  11224. return pnodeDestructAsg;
  11225. }
  11226. template <bool buildAST>
  11227. ParseNodePtr Parser::ParseDestructuredObjectLiteral(tokens declarationType, bool isDecl, bool topLevel/* = true*/)
  11228. {
  11229. Assert(m_token.tk == tkLCurly);
  11230. charcount_t ichMin = m_pscan->IchMinTok();
  11231. m_pscan->Scan();
  11232. if (!isDecl)
  11233. {
  11234. declarationType = tkLCurly;
  11235. }
  11236. ParseNodePtr pnodeMemberList = ParseMemberList<buildAST>(nullptr/*pNameHint*/, nullptr/*pHintLength*/, declarationType);
  11237. Assert(m_token.tk == tkRCurly);
  11238. ParseNodePtr objectPatternNode = nullptr;
  11239. if (buildAST)
  11240. {
  11241. charcount_t ichLim = m_pscan->IchLimTok();
  11242. objectPatternNode = CreateUniNode(knopObjectPattern, pnodeMemberList, ichMin, ichLim);
  11243. }
  11244. return objectPatternNode;
  11245. }
  11246. template <bool buildAST>
  11247. ParseNodePtr Parser::ParseDestructuredVarDecl(tokens declarationType, bool isDecl, bool *hasSeenRest, bool topLevel/* = true*/, bool allowEmptyExpression/* = true*/)
  11248. {
  11249. ParseNodePtr pnodeElem = nullptr;
  11250. int parenCount = 0;
  11251. bool seenRest = false;
  11252. // Save the Block ID prior to the increments, so we can restore it back.
  11253. int originalCurrentBlockId = GetCurrentBlock()->AsParseNodeBlock()->blockId;
  11254. // Eat the left parentheses only when its not a declaration. This will make sure we throw syntax errors early.
  11255. if (!isDecl)
  11256. {
  11257. while (m_token.tk == tkLParen)
  11258. {
  11259. m_pscan->Scan();
  11260. ++parenCount;
  11261. // Match the block increment we do upon entering parenthetical expressions
  11262. // so that the block ID's will match on reparsing of parameters.
  11263. GetCurrentBlock()->AsParseNodeBlock()->blockId = m_nextBlockId++;
  11264. }
  11265. }
  11266. if (m_token.tk == tkEllipsis)
  11267. {
  11268. // As per ES 2015 : Rest can have left-hand-side-expression when on assignment expression, but under declaration only binding identifier is allowed
  11269. // But spec is going to change for this one to allow LHS-expression both on expression and declaration - so making that happen early.
  11270. seenRest = true;
  11271. m_pscan->Scan();
  11272. // Eat the left parentheses only when its not a declaration. This will make sure we throw syntax errors early.
  11273. if (!isDecl)
  11274. {
  11275. while (m_token.tk == tkLParen)
  11276. {
  11277. m_pscan->Scan();
  11278. ++parenCount;
  11279. // Match the block increment we do upon entering parenthetical expressions
  11280. // so that the block ID's will match on reparsing of parameters.
  11281. GetCurrentBlock()->AsParseNodeBlock()->blockId = m_nextBlockId++;
  11282. }
  11283. }
  11284. if (m_token.tk != tkID && m_token.tk != tkTHIS && m_token.tk != tkSUPER && m_token.tk != tkLCurly && m_token.tk != tkLBrack)
  11285. {
  11286. if (isDecl)
  11287. {
  11288. Error(ERRnoIdent);
  11289. }
  11290. else
  11291. {
  11292. Error(ERRInvalidAssignmentTarget);
  11293. }
  11294. }
  11295. }
  11296. if (IsPossiblePatternStart())
  11297. {
  11298. // For the possible pattern start we do not allow the parens before
  11299. if (parenCount != 0)
  11300. {
  11301. Error(ERRDestructIDRef);
  11302. }
  11303. // Go recursively
  11304. pnodeElem = ParseDestructuredLiteral<buildAST>(declarationType, isDecl, false /*topLevel*/, seenRest ? DIC_ShouldNotParseInitializer : DIC_None);
  11305. if (!isDecl)
  11306. {
  11307. BOOL fCanAssign;
  11308. IdentToken token;
  11309. // Look for postfix operator
  11310. pnodeElem = ParsePostfixOperators<buildAST>(pnodeElem, TRUE, FALSE, FALSE, &fCanAssign, &token);
  11311. }
  11312. }
  11313. else if (m_token.tk == tkSUPER || m_token.tk == tkID || m_token.tk == tkTHIS)
  11314. {
  11315. if (isDecl)
  11316. {
  11317. charcount_t ichMin = m_pscan->IchMinTok();
  11318. pnodeElem = ParseVariableDeclaration<buildAST>(declarationType, ichMin
  11319. ,/* fAllowIn */false, /* pfForInOk */nullptr, /* singleDefOnly */true, /* allowInit */!seenRest, false /*topLevelParse*/);
  11320. }
  11321. else
  11322. {
  11323. BOOL fCanAssign;
  11324. IdentToken token;
  11325. // We aren't declaring anything, so scan the ID reference manually.
  11326. pnodeElem = ParseTerm<buildAST>(/* fAllowCall */ m_token.tk != tkSUPER, nullptr /*pNameHint*/, nullptr /*pHintLength*/, nullptr /*pShortNameOffset*/, &token, false,
  11327. &fCanAssign);
  11328. // In this destructuring case we can force error here as we cannot assign.
  11329. if (!fCanAssign)
  11330. {
  11331. Error(ERRInvalidAssignmentTarget);
  11332. }
  11333. if (buildAST)
  11334. {
  11335. if (IsStrictMode() && pnodeElem != nullptr && pnodeElem->nop == knopName)
  11336. {
  11337. CheckStrictModeEvalArgumentsUsage(pnodeElem->AsParseNodePid()->pid);
  11338. }
  11339. }
  11340. else
  11341. {
  11342. if (IsStrictMode() && token.tk == tkID)
  11343. {
  11344. CheckStrictModeEvalArgumentsUsage(token.pid);
  11345. }
  11346. token.tk = tkNone;
  11347. }
  11348. }
  11349. }
  11350. else if (!((m_token.tk == tkComma || m_token.tk == tkRBrack || m_token.tk == tkRCurly) && allowEmptyExpression))
  11351. {
  11352. if (m_token.IsOperator())
  11353. {
  11354. Error(ERRDestructNoOper);
  11355. }
  11356. Error(ERRDestructIDRef);
  11357. }
  11358. // Swallow RParens before a default expression, if any.
  11359. // 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.
  11360. if (!isDecl)
  11361. {
  11362. while (m_token.tk == tkRParen)
  11363. {
  11364. m_pscan->Scan();
  11365. --parenCount;
  11366. }
  11367. // Restore the Block ID of the current block after the parsing of destructured variable declarations and initializers.
  11368. GetCurrentBlock()->AsParseNodeBlock()->blockId = originalCurrentBlockId;
  11369. }
  11370. if (parenCount != 0)
  11371. {
  11372. Error(ERRnoRparen);
  11373. }
  11374. if (hasSeenRest != nullptr)
  11375. {
  11376. *hasSeenRest = seenRest;
  11377. }
  11378. if (m_token.tk == tkAsg)
  11379. {
  11380. // Parse the initializer.
  11381. if (seenRest)
  11382. {
  11383. Error(ERRRestWithDefault);
  11384. }
  11385. m_pscan->Scan();
  11386. bool alreadyHasInitError = m_hasDeferredShorthandInitError;
  11387. ParseNodePtr pnodeInit = ParseExpr<buildAST>(koplCma);
  11388. if (m_hasDeferredShorthandInitError && !alreadyHasInitError)
  11389. {
  11390. Error(ERRnoColon);
  11391. }
  11392. if (buildAST)
  11393. {
  11394. pnodeElem = CreateBinNode(knopAsg, pnodeElem, pnodeInit);
  11395. }
  11396. }
  11397. if (buildAST && seenRest)
  11398. {
  11399. ParseNodePtr pnodeRest = CreateNodeWithScanner<knopEllipsis>();
  11400. pnodeRest->AsParseNodeUni()->pnode1 = pnodeElem;
  11401. pnodeElem = pnodeRest;
  11402. }
  11403. if (!(m_token.tk == tkComma || m_token.tk == tkRBrack || m_token.tk == tkRCurly))
  11404. {
  11405. if (m_token.IsOperator())
  11406. {
  11407. Error(ERRDestructNoOper);
  11408. }
  11409. Error(ERRsyntax);
  11410. }
  11411. return pnodeElem;
  11412. }
  11413. template <bool buildAST>
  11414. ParseNodePtr Parser::ParseDestructuredArrayLiteral(tokens declarationType, bool isDecl, bool topLevel)
  11415. {
  11416. Assert(m_token.tk == tkLBrack);
  11417. charcount_t ichMin = m_pscan->IchMinTok();
  11418. m_pscan->Scan();
  11419. ParseNodePtr pnodeDestructArr = nullptr;
  11420. ParseNodePtr pnodeList = nullptr;
  11421. ParseNodePtr *lastNodeRef = nullptr;
  11422. uint count = 0;
  11423. bool hasMissingValues = false;
  11424. bool seenRest = false;
  11425. if (m_token.tk != tkRBrack)
  11426. {
  11427. while (true)
  11428. {
  11429. ParseNodePtr pnodeElem = ParseDestructuredVarDecl<buildAST>(declarationType, isDecl, &seenRest, topLevel);
  11430. if (buildAST)
  11431. {
  11432. if (pnodeElem == nullptr && buildAST)
  11433. {
  11434. pnodeElem = CreateNodeWithScanner<knopEmpty>();
  11435. hasMissingValues = true;
  11436. }
  11437. AddToNodeListEscapedUse(&pnodeList, &lastNodeRef, pnodeElem);
  11438. }
  11439. count++;
  11440. if (m_token.tk == tkRBrack)
  11441. {
  11442. break;
  11443. }
  11444. if (m_token.tk != tkComma)
  11445. {
  11446. Error(ERRDestructNoOper);
  11447. }
  11448. if (seenRest) // Rest must be in the last position.
  11449. {
  11450. Error(ERRDestructRestLast);
  11451. }
  11452. m_pscan->Scan();
  11453. // break if we have the trailing comma as well, eg. [a,]
  11454. if (m_token.tk == tkRBrack)
  11455. {
  11456. break;
  11457. }
  11458. }
  11459. }
  11460. if (buildAST)
  11461. {
  11462. pnodeDestructArr = CreateNodeWithScanner<knopArrayPattern>();
  11463. pnodeDestructArr->AsParseNodeArrLit()->pnode1 = pnodeList;
  11464. pnodeDestructArr->AsParseNodeArrLit()->arrayOfTaggedInts = false;
  11465. pnodeDestructArr->AsParseNodeArrLit()->arrayOfInts = false;
  11466. pnodeDestructArr->AsParseNodeArrLit()->arrayOfNumbers = false;
  11467. pnodeDestructArr->AsParseNodeArrLit()->hasMissingValues = hasMissingValues;
  11468. pnodeDestructArr->AsParseNodeArrLit()->count = count;
  11469. pnodeDestructArr->AsParseNodeArrLit()->spreadCount = seenRest ? 1 : 0;
  11470. pnodeDestructArr->ichMin = ichMin;
  11471. pnodeDestructArr->ichLim = m_pscan->IchLimTok();
  11472. if (pnodeDestructArr->AsParseNodeArrLit()->pnode1)
  11473. {
  11474. this->CheckArguments(pnodeDestructArr->AsParseNodeArrLit()->pnode1);
  11475. }
  11476. }
  11477. return pnodeDestructArr;
  11478. }
  11479. void Parser::CaptureContext(ParseContext *parseContext) const
  11480. {
  11481. parseContext->pszSrc = m_pscan->PchBase();
  11482. parseContext->length = this->m_originalLength;
  11483. parseContext->characterOffset = m_pscan->IchMinTok();
  11484. parseContext->offset = parseContext->characterOffset + m_pscan->m_cMultiUnits;
  11485. parseContext->grfscr = this->m_grfscr;
  11486. parseContext->lineNumber = m_pscan->LineCur();
  11487. parseContext->pnodeProg = this->m_currentNodeProg;
  11488. parseContext->fromExternal = m_pscan->IsFromExternalSource();
  11489. parseContext->strictMode = this->IsStrictMode();
  11490. parseContext->sourceContextInfo = this->m_sourceContextInfo;
  11491. parseContext->currentBlockInfo = this->m_currentBlockInfo;
  11492. parseContext->nextBlockId = this->m_nextBlockId;
  11493. }
  11494. void Parser::RestoreContext(ParseContext *const parseContext)
  11495. {
  11496. m_sourceContextInfo = parseContext->sourceContextInfo;
  11497. m_currentBlockInfo = parseContext->currentBlockInfo;
  11498. m_nextBlockId = parseContext->nextBlockId;
  11499. m_grfscr = parseContext->grfscr;
  11500. m_length = parseContext->length;
  11501. m_pscan->SetText(parseContext->pszSrc, parseContext->offset, parseContext->length, parseContext->characterOffset, parseContext->grfscr, parseContext->lineNumber);
  11502. m_currentNodeProg = parseContext->pnodeProg;
  11503. m_fUseStrictMode = parseContext->strictMode;
  11504. }
  11505. class ByteCodeGenerator;
  11506. #if DBG_DUMP
  11507. #define INDENT_SIZE 2
  11508. void PrintPnodeListWIndent(ParseNode *pnode,int indentAmt);
  11509. void PrintFormalsWIndent(ParseNode *pnode, int indentAmt);
  11510. void Indent(int indentAmt) {
  11511. for (int i=0;i<indentAmt;i++) {
  11512. Output::Print(_u(" "));
  11513. }
  11514. }
  11515. void PrintBlockType(PnodeBlockType type)
  11516. {
  11517. switch (type)
  11518. {
  11519. case Global:
  11520. Output::Print(_u("(Global)"));
  11521. break;
  11522. case Function:
  11523. Output::Print(_u("(Function)"));
  11524. break;
  11525. case Regular:
  11526. Output::Print(_u("(Regular)"));
  11527. break;
  11528. case Parameter:
  11529. Output::Print(_u("(Parameter)"));
  11530. break;
  11531. default:
  11532. Output::Print(_u("(unknown blocktype)"));
  11533. break;
  11534. }
  11535. }
  11536. void PrintScopesWIndent(ParseNode *pnode,int indentAmt) {
  11537. ParseNode *scope = nullptr;
  11538. bool firstOnly = false;
  11539. switch(pnode->nop)
  11540. {
  11541. case knopProg:
  11542. case knopFncDecl: scope = pnode->AsParseNodeFnc()->pnodeScopes; break;
  11543. case knopBlock: scope = pnode->AsParseNodeBlock()->pnodeScopes; break;
  11544. case knopCatch: scope = pnode->AsParseNodeCatch()->pnodeScopes; break;
  11545. case knopWith: scope = pnode->AsParseNodeWith()->pnodeScopes; break;
  11546. case knopSwitch: scope = pnode->AsParseNodeSwitch()->pnodeBlock; firstOnly = true; break;
  11547. case knopFor: scope = pnode->AsParseNodeFor()->pnodeBlock; firstOnly = true; break;
  11548. case knopForIn: scope = pnode->AsParseNodeForInOrForOf()->pnodeBlock; firstOnly = true; break;
  11549. case knopForOf: scope = pnode->AsParseNodeForInOrForOf()->pnodeBlock; firstOnly = true; break;
  11550. }
  11551. if (scope) {
  11552. Output::Print(_u("[%4d, %4d): "), scope->ichMin, scope->ichLim);
  11553. Indent(indentAmt);
  11554. Output::Print(_u("Scopes: "));
  11555. ParseNode *next = nullptr;
  11556. ParseNode *syntheticBlock = nullptr;
  11557. while (scope) {
  11558. switch (scope->nop) {
  11559. case knopFncDecl: Output::Print(_u("knopFncDecl")); next = scope->AsParseNodeFnc()->pnodeNext; break;
  11560. case knopBlock: Output::Print(_u("knopBlock")); PrintBlockType(scope->AsParseNodeBlock()->blockType); next = scope->AsParseNodeBlock()->pnodeNext; break;
  11561. case knopCatch: Output::Print(_u("knopCatch")); next = scope->AsParseNodeCatch()->pnodeNext; break;
  11562. case knopWith: Output::Print(_u("knopWith")); next = scope->AsParseNodeWith()->pnodeNext; break;
  11563. default: Output::Print(_u("unknown")); break;
  11564. }
  11565. if (firstOnly) {
  11566. next = nullptr;
  11567. syntheticBlock = scope;
  11568. }
  11569. if (scope->grfpn & fpnSyntheticNode) {
  11570. Output::Print(_u(" synthetic"));
  11571. if (scope->nop == knopBlock)
  11572. syntheticBlock = scope;
  11573. }
  11574. Output::Print(_u(" (%d-%d)"), scope->ichMin, scope->ichLim);
  11575. if (next) Output::Print(_u(", "));
  11576. scope = next;
  11577. }
  11578. Output::Print(_u("\n"));
  11579. if (syntheticBlock || firstOnly) {
  11580. PrintScopesWIndent(syntheticBlock, indentAmt + INDENT_SIZE);
  11581. }
  11582. }
  11583. }
  11584. void PrintPnodeWIndent(ParseNode *pnode,int indentAmt) {
  11585. if (pnode==NULL)
  11586. return;
  11587. Output::Print(_u("[%4d, %4d): "), pnode->ichMin, pnode->ichLim);
  11588. switch (pnode->nop) {
  11589. //PTNODE(knopName , "name" ,None ,Pid ,fnopLeaf)
  11590. case knopName:
  11591. Indent(indentAmt);
  11592. if (pnode->AsParseNodePid()->pid!=NULL) {
  11593. Output::Print(_u("id: %s\n"),pnode->AsParseNodePid()->pid->Psz());
  11594. }
  11595. else {
  11596. Output::Print(_u("name node\n"));
  11597. }
  11598. break;
  11599. //PTNODE(knopInt , "int const" ,None ,Int ,fnopLeaf|fnopConst)
  11600. case knopInt:
  11601. Indent(indentAmt);
  11602. Output::Print(_u("%d\n"),pnode->AsParseNodeInt()->lw);
  11603. break;
  11604. //PTNODE(knopFlt , "flt const" ,None ,Flt ,fnopLeaf|fnopConst)
  11605. case knopFlt:
  11606. Indent(indentAmt);
  11607. Output::Print(_u("%lf\n"),pnode->AsParseNodeFloat()->dbl);
  11608. break;
  11609. //PTNODE(knopStr , "str const" ,None ,Pid ,fnopLeaf|fnopConst)
  11610. case knopStr:
  11611. Indent(indentAmt);
  11612. Output::Print(_u("\"%s\"\n"),pnode->AsParseNodePid()->pid->Psz());
  11613. break;
  11614. //PTNODE(knopRegExp , "reg expr" ,None ,Pid ,fnopLeaf|fnopConst)
  11615. case knopRegExp:
  11616. Indent(indentAmt);
  11617. Output::Print(_u("/%x/\n"),pnode->AsParseNodePid()->regexPattern);
  11618. break;
  11619. //PTNODE(knopNull , "null" ,Null ,None ,fnopLeaf)
  11620. case knopNull:
  11621. Indent(indentAmt);
  11622. Output::Print(_u("null\n"));
  11623. break;
  11624. //PTNODE(knopFalse , "false" ,False ,None ,fnopLeaf)
  11625. case knopFalse:
  11626. Indent(indentAmt);
  11627. Output::Print(_u("false\n"));
  11628. break;
  11629. //PTNODE(knopTrue , "true" ,True ,None ,fnopLeaf)
  11630. case knopTrue:
  11631. Indent(indentAmt);
  11632. Output::Print(_u("true\n"));
  11633. break;
  11634. //PTNODE(knopEmpty , "empty" ,Empty ,None ,fnopLeaf)
  11635. case knopEmpty:
  11636. Indent(indentAmt);
  11637. Output::Print(_u("empty\n"));
  11638. break;
  11639. // Unary operators.
  11640. //PTNODE(knopNot , "~" ,BitNot ,Uni ,fnopUni)
  11641. case knopNot:
  11642. Indent(indentAmt);
  11643. Output::Print(_u("~\n"));
  11644. PrintPnodeWIndent(pnode->AsParseNodeUni()->pnode1,indentAmt+INDENT_SIZE);
  11645. break;
  11646. //PTNODE(knopNeg , "unary -" ,Neg ,Uni ,fnopUni)
  11647. case knopNeg:
  11648. Indent(indentAmt);
  11649. Output::Print(_u("U-\n"));
  11650. PrintPnodeWIndent(pnode->AsParseNodeUni()->pnode1,indentAmt+INDENT_SIZE);
  11651. break;
  11652. //PTNODE(knopPos , "unary +" ,Pos ,Uni ,fnopUni)
  11653. case knopPos:
  11654. Indent(indentAmt);
  11655. Output::Print(_u("U+\n"));
  11656. PrintPnodeWIndent(pnode->AsParseNodeUni()->pnode1,indentAmt+INDENT_SIZE);
  11657. break;
  11658. //PTNODE(knopLogNot , "!" ,LogNot ,Uni ,fnopUni)
  11659. case knopLogNot:
  11660. Indent(indentAmt);
  11661. Output::Print(_u("!\n"));
  11662. PrintPnodeWIndent(pnode->AsParseNodeUni()->pnode1,indentAmt+INDENT_SIZE);
  11663. break;
  11664. //PTNODE(knopEllipsis , "..." ,Spread ,Uni , fnopUni)
  11665. case knopEllipsis:
  11666. Indent(indentAmt);
  11667. Output::Print(_u("...<expr>\n"));
  11668. PrintPnodeWIndent(pnode->AsParseNodeUni()->pnode1,indentAmt+INDENT_SIZE);
  11669. break;
  11670. //PTNODE(knopIncPost , "++ post" ,Inc ,Uni ,fnopUni|fnopAsg)
  11671. case knopIncPost:
  11672. Indent(indentAmt);
  11673. Output::Print(_u("<expr>++\n"));
  11674. PrintPnodeWIndent(pnode->AsParseNodeUni()->pnode1,indentAmt+INDENT_SIZE);
  11675. break;
  11676. //PTNODE(knopDecPost , "-- post" ,Dec ,Uni ,fnopUni|fnopAsg)
  11677. case knopDecPost:
  11678. Indent(indentAmt);
  11679. Output::Print(_u("<expr>--\n"));
  11680. PrintPnodeWIndent(pnode->AsParseNodeUni()->pnode1,indentAmt+INDENT_SIZE);
  11681. break;
  11682. //PTNODE(knopIncPre , "++ pre" ,Inc ,Uni ,fnopUni|fnopAsg)
  11683. case knopIncPre:
  11684. Indent(indentAmt);
  11685. Output::Print(_u("++<expr>\n"));
  11686. PrintPnodeWIndent(pnode->AsParseNodeUni()->pnode1,indentAmt+INDENT_SIZE);
  11687. break;
  11688. //PTNODE(knopDecPre , "-- pre" ,Dec ,Uni ,fnopUni|fnopAsg)
  11689. case knopDecPre:
  11690. Indent(indentAmt);
  11691. Output::Print(_u("--<expr>\n"));
  11692. PrintPnodeWIndent(pnode->AsParseNodeUni()->pnode1,indentAmt+INDENT_SIZE);
  11693. break;
  11694. //PTNODE(knopTypeof , "typeof" ,None ,Uni ,fnopUni)
  11695. case knopTypeof:
  11696. Indent(indentAmt);
  11697. Output::Print(_u("typeof\n"));
  11698. PrintPnodeWIndent(pnode->AsParseNodeUni()->pnode1,indentAmt+INDENT_SIZE);
  11699. break;
  11700. //PTNODE(knopVoid , "void" ,Void ,Uni ,fnopUni)
  11701. case knopVoid:
  11702. Indent(indentAmt);
  11703. Output::Print(_u("void\n"));
  11704. PrintPnodeWIndent(pnode->AsParseNodeUni()->pnode1,indentAmt+INDENT_SIZE);
  11705. break;
  11706. //PTNODE(knopDelete , "delete" ,None ,Uni ,fnopUni)
  11707. case knopDelete:
  11708. Indent(indentAmt);
  11709. Output::Print(_u("delete\n"));
  11710. PrintPnodeWIndent(pnode->AsParseNodeUni()->pnode1,indentAmt+INDENT_SIZE);
  11711. break;
  11712. //PTNODE(knopArray , "arr cnst" ,None ,Uni ,fnopUni)
  11713. case knopArrayPattern:
  11714. Indent(indentAmt);
  11715. Output::Print(_u("Array Pattern\n"));
  11716. PrintPnodeListWIndent(pnode->AsParseNodeUni()->pnode1, indentAmt + INDENT_SIZE);
  11717. break;
  11718. case knopObjectPattern:
  11719. Indent(indentAmt);
  11720. Output::Print(_u("Object Pattern\n"));
  11721. PrintPnodeListWIndent(pnode->AsParseNodeUni()->pnode1, indentAmt + INDENT_SIZE);
  11722. break;
  11723. case knopArray:
  11724. Indent(indentAmt);
  11725. Output::Print(_u("Array Literal\n"));
  11726. PrintPnodeListWIndent(pnode->AsParseNodeUni()->pnode1,indentAmt+INDENT_SIZE);
  11727. break;
  11728. //PTNODE(knopObject , "obj cnst" ,None ,Uni ,fnopUni)
  11729. case knopObject:
  11730. Indent(indentAmt);
  11731. Output::Print(_u("Object Literal\n"));
  11732. PrintPnodeListWIndent(pnode->AsParseNodeUni()->pnode1,indentAmt+INDENT_SIZE);
  11733. break;
  11734. // Binary and Ternary Operators
  11735. //PTNODE(knopAdd , "+" ,Add ,Bin ,fnopBin)
  11736. case knopAdd:
  11737. Indent(indentAmt);
  11738. Output::Print(_u("+\n"));
  11739. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1,indentAmt+INDENT_SIZE);
  11740. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2,indentAmt+INDENT_SIZE);
  11741. break;
  11742. //PTNODE(knopSub , "-" ,Sub ,Bin ,fnopBin)
  11743. case knopSub:
  11744. Indent(indentAmt);
  11745. Output::Print(_u("-\n"));
  11746. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1,indentAmt+INDENT_SIZE);
  11747. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2,indentAmt+INDENT_SIZE);
  11748. break;
  11749. //PTNODE(knopMul , "*" ,Mul ,Bin ,fnopBin)
  11750. case knopMul:
  11751. Indent(indentAmt);
  11752. Output::Print(_u("*\n"));
  11753. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1,indentAmt+INDENT_SIZE);
  11754. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2,indentAmt+INDENT_SIZE);
  11755. break;
  11756. //PTNODE(knopDiv , "/" ,Div ,Bin ,fnopBin)
  11757. case knopExpo:
  11758. Indent(indentAmt);
  11759. Output::Print(_u("**\n"));
  11760. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11761. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11762. break;
  11763. //PTNODE(knopExpo , "**" ,Expo ,Bin ,fnopBin)
  11764. case knopDiv:
  11765. Indent(indentAmt);
  11766. Output::Print(_u("/\n"));
  11767. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1,indentAmt+INDENT_SIZE);
  11768. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2,indentAmt+INDENT_SIZE);
  11769. break;
  11770. //PTNODE(knopMod , "%" ,Mod ,Bin ,fnopBin)
  11771. case knopMod:
  11772. Indent(indentAmt);
  11773. Output::Print(_u("%\n"));
  11774. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1,indentAmt+INDENT_SIZE);
  11775. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2,indentAmt+INDENT_SIZE);
  11776. break;
  11777. //PTNODE(knopOr , "|" ,BitOr ,Bin ,fnopBin)
  11778. case knopOr:
  11779. Indent(indentAmt);
  11780. Output::Print(_u("|\n"));
  11781. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1,indentAmt+INDENT_SIZE);
  11782. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2,indentAmt+INDENT_SIZE);
  11783. break;
  11784. //PTNODE(knopXor , "^" ,BitXor ,Bin ,fnopBin)
  11785. case knopXor:
  11786. Indent(indentAmt);
  11787. Output::Print(_u("^\n"));
  11788. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1,indentAmt+INDENT_SIZE);
  11789. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2,indentAmt+INDENT_SIZE);
  11790. break;
  11791. //PTNODE(knopAnd , "&" ,BitAnd ,Bin ,fnopBin)
  11792. case knopAnd:
  11793. Indent(indentAmt);
  11794. Output::Print(_u("&\n"));
  11795. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1,indentAmt+INDENT_SIZE);
  11796. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2,indentAmt+INDENT_SIZE);
  11797. break;
  11798. //PTNODE(knopEq , "==" ,EQ ,Bin ,fnopBin|fnopRel)
  11799. case knopEq:
  11800. Indent(indentAmt);
  11801. Output::Print(_u("==\n"));
  11802. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1,indentAmt+INDENT_SIZE);
  11803. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2,indentAmt+INDENT_SIZE);
  11804. break;
  11805. //PTNODE(knopNe , "!=" ,NE ,Bin ,fnopBin|fnopRel)
  11806. case knopNe:
  11807. Indent(indentAmt);
  11808. Output::Print(_u("!=\n"));
  11809. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1,indentAmt+INDENT_SIZE);
  11810. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2,indentAmt+INDENT_SIZE);
  11811. break;
  11812. //PTNODE(knopLt , "<" ,LT ,Bin ,fnopBin|fnopRel)
  11813. case knopLt:
  11814. Indent(indentAmt);
  11815. Output::Print(_u("<\n"));
  11816. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1,indentAmt+INDENT_SIZE);
  11817. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2,indentAmt+INDENT_SIZE);
  11818. break;
  11819. //PTNODE(knopLe , "<=" ,LE ,Bin ,fnopBin|fnopRel)
  11820. case knopLe:
  11821. Indent(indentAmt);
  11822. Output::Print(_u("<=\n"));
  11823. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1,indentAmt+INDENT_SIZE);
  11824. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2,indentAmt+INDENT_SIZE);
  11825. break;
  11826. //PTNODE(knopGe , ">=" ,GE ,Bin ,fnopBin|fnopRel)
  11827. case knopGe:
  11828. Indent(indentAmt);
  11829. Output::Print(_u(">=\n"));
  11830. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1,indentAmt+INDENT_SIZE);
  11831. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2,indentAmt+INDENT_SIZE);
  11832. break;
  11833. //PTNODE(knopGt , ">" ,GT ,Bin ,fnopBin|fnopRel)
  11834. case knopGt:
  11835. Indent(indentAmt);
  11836. Output::Print(_u(">\n"));
  11837. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1,indentAmt+INDENT_SIZE);
  11838. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2,indentAmt+INDENT_SIZE);
  11839. break;
  11840. //PTNODE(knopCall , "()" ,None ,Bin ,fnopBin)
  11841. case knopCall:
  11842. Indent(indentAmt);
  11843. Output::Print(_u("Call\n"));
  11844. PrintPnodeWIndent(pnode->AsParseNodeCall()->pnodeTarget,indentAmt+INDENT_SIZE);
  11845. PrintPnodeListWIndent(pnode->AsParseNodeCall()->pnodeArgs,indentAmt+INDENT_SIZE);
  11846. break;
  11847. //PTNODE(knopDot , "." ,None ,Bin ,fnopBin)
  11848. case knopDot:
  11849. Indent(indentAmt);
  11850. Output::Print(_u(".\n"));
  11851. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1,indentAmt+INDENT_SIZE);
  11852. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2,indentAmt+INDENT_SIZE);
  11853. break;
  11854. //PTNODE(knopAsg , "=" ,None ,Bin ,fnopBin|fnopAsg)
  11855. case knopAsg:
  11856. Indent(indentAmt);
  11857. Output::Print(_u("=\n"));
  11858. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1,indentAmt+INDENT_SIZE);
  11859. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2,indentAmt+INDENT_SIZE);
  11860. break;
  11861. //PTNODE(knopInstOf , "instanceof",InstOf ,Bin ,fnopBin|fnopRel)
  11862. case knopInstOf:
  11863. Indent(indentAmt);
  11864. Output::Print(_u("instanceof\n"));
  11865. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1,indentAmt+INDENT_SIZE);
  11866. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2,indentAmt+INDENT_SIZE);
  11867. break;
  11868. //PTNODE(knopIn , "in" ,In ,Bin ,fnopBin|fnopRel)
  11869. case knopIn:
  11870. Indent(indentAmt);
  11871. Output::Print(_u("in\n"));
  11872. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1,indentAmt+INDENT_SIZE);
  11873. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2,indentAmt+INDENT_SIZE);
  11874. break;
  11875. //PTNODE(knopEqv , "===" ,Eqv ,Bin ,fnopBin|fnopRel)
  11876. case knopEqv:
  11877. Indent(indentAmt);
  11878. Output::Print(_u("===\n"));
  11879. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1,indentAmt+INDENT_SIZE);
  11880. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2,indentAmt+INDENT_SIZE);
  11881. break;
  11882. //PTNODE(knopNEqv , "!==" ,NEqv ,Bin ,fnopBin|fnopRel)
  11883. case knopNEqv:
  11884. Indent(indentAmt);
  11885. Output::Print(_u("!==\n"));
  11886. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1,indentAmt+INDENT_SIZE);
  11887. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2,indentAmt+INDENT_SIZE);
  11888. break;
  11889. //PTNODE(knopComma , "," ,None ,Bin ,fnopBin)
  11890. case knopComma:
  11891. Indent(indentAmt);
  11892. Output::Print(_u(",\n"));
  11893. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1,indentAmt+INDENT_SIZE);
  11894. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2,indentAmt+INDENT_SIZE);
  11895. break;
  11896. //PTNODE(knopLogOr , "||" ,None ,Bin ,fnopBin)
  11897. case knopLogOr:
  11898. Indent(indentAmt);
  11899. Output::Print(_u("||\n"));
  11900. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1,indentAmt+INDENT_SIZE);
  11901. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2,indentAmt+INDENT_SIZE);
  11902. break;
  11903. //PTNODE(knopLogAnd , "&&" ,None ,Bin ,fnopBin)
  11904. case knopLogAnd:
  11905. Indent(indentAmt);
  11906. Output::Print(_u("&&\n"));
  11907. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1,indentAmt+INDENT_SIZE);
  11908. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2,indentAmt+INDENT_SIZE);
  11909. break;
  11910. //PTNODE(knopLsh , "<<" ,Lsh ,Bin ,fnopBin)
  11911. case knopLsh:
  11912. Indent(indentAmt);
  11913. Output::Print(_u("<<\n"));
  11914. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1,indentAmt+INDENT_SIZE);
  11915. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2,indentAmt+INDENT_SIZE);
  11916. break;
  11917. //PTNODE(knopRsh , ">>" ,Rsh ,Bin ,fnopBin)
  11918. case knopRsh:
  11919. Indent(indentAmt);
  11920. Output::Print(_u(">>\n"));
  11921. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1,indentAmt+INDENT_SIZE);
  11922. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2,indentAmt+INDENT_SIZE);
  11923. break;
  11924. //PTNODE(knopRs2 , ">>>" ,Rs2 ,Bin ,fnopBin)
  11925. case knopRs2:
  11926. Indent(indentAmt);
  11927. Output::Print(_u(">>>\n"));
  11928. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1,indentAmt+INDENT_SIZE);
  11929. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2,indentAmt+INDENT_SIZE);
  11930. break;
  11931. //PTNODE(knopNew , "new" ,None ,Bin ,fnopBin)
  11932. case knopNew:
  11933. Indent(indentAmt);
  11934. Output::Print(_u("new\n"));
  11935. PrintPnodeWIndent(pnode->AsParseNodeCall()->pnodeTarget, indentAmt + INDENT_SIZE);
  11936. PrintPnodeListWIndent(pnode->AsParseNodeCall()->pnodeArgs, indentAmt + INDENT_SIZE);
  11937. break;
  11938. //PTNODE(knopIndex , "[]" ,None ,Bin ,fnopBin)
  11939. case knopIndex:
  11940. Indent(indentAmt);
  11941. Output::Print(_u("[]\n"));
  11942. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1,indentAmt+INDENT_SIZE);
  11943. PrintPnodeListWIndent(pnode->AsParseNodeBin()->pnode2,indentAmt+INDENT_SIZE);
  11944. break;
  11945. //PTNODE(knopQmark , "?" ,None ,Tri ,fnopBin)
  11946. case knopQmark:
  11947. Indent(indentAmt);
  11948. Output::Print(_u("?:\n"));
  11949. PrintPnodeWIndent(pnode->AsParseNodeTri()->pnode1,indentAmt+INDENT_SIZE);
  11950. PrintPnodeWIndent(pnode->AsParseNodeTri()->pnode2,indentAmt+INDENT_SIZE);
  11951. PrintPnodeWIndent(pnode->AsParseNodeTri()->pnode3,indentAmt+INDENT_SIZE);
  11952. break;
  11953. //PTNODE(knopAsgAdd , "+=" ,Add ,Bin ,fnopBin|fnopAsg)
  11954. case knopAsgAdd:
  11955. Indent(indentAmt);
  11956. Output::Print(_u("+=\n"));
  11957. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1,indentAmt+INDENT_SIZE);
  11958. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2,indentAmt+INDENT_SIZE);
  11959. break;
  11960. //PTNODE(knopAsgSub , "-=" ,Sub ,Bin ,fnopBin|fnopAsg)
  11961. case knopAsgSub:
  11962. Indent(indentAmt);
  11963. Output::Print(_u("-=\n"));
  11964. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1,indentAmt+INDENT_SIZE);
  11965. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2,indentAmt+INDENT_SIZE);
  11966. break;
  11967. //PTNODE(knopAsgMul , "*=" ,Mul ,Bin ,fnopBin|fnopAsg)
  11968. case knopAsgMul:
  11969. Indent(indentAmt);
  11970. Output::Print(_u("*=\n"));
  11971. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1,indentAmt+INDENT_SIZE);
  11972. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2,indentAmt+INDENT_SIZE);
  11973. break;
  11974. //PTNODE(knopAsgDiv , "/=" ,Div ,Bin ,fnopBin|fnopAsg)
  11975. case knopAsgExpo:
  11976. Indent(indentAmt);
  11977. Output::Print(_u("**=\n"));
  11978. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1, indentAmt + INDENT_SIZE);
  11979. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2, indentAmt + INDENT_SIZE);
  11980. break;
  11981. //PTNODE(knopAsgExpo , "**=" ,Expo ,Bin ,fnopBin|fnopAsg)
  11982. case knopAsgDiv:
  11983. Indent(indentAmt);
  11984. Output::Print(_u("/=\n"));
  11985. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1,indentAmt+INDENT_SIZE);
  11986. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2,indentAmt+INDENT_SIZE);
  11987. break;
  11988. //PTNODE(knopAsgMod , "%=" ,Mod ,Bin ,fnopBin|fnopAsg)
  11989. case knopAsgMod:
  11990. Indent(indentAmt);
  11991. Output::Print(_u("%=\n"));
  11992. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1,indentAmt+INDENT_SIZE);
  11993. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2,indentAmt+INDENT_SIZE);
  11994. break;
  11995. //PTNODE(knopAsgAnd , "&=" ,BitAnd ,Bin ,fnopBin|fnopAsg)
  11996. case knopAsgAnd:
  11997. Indent(indentAmt);
  11998. Output::Print(_u("&=\n"));
  11999. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1,indentAmt+INDENT_SIZE);
  12000. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2,indentAmt+INDENT_SIZE);
  12001. break;
  12002. //PTNODE(knopAsgXor , "^=" ,BitXor ,Bin ,fnopBin|fnopAsg)
  12003. case knopAsgXor:
  12004. Indent(indentAmt);
  12005. Output::Print(_u("^=\n"));
  12006. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1,indentAmt+INDENT_SIZE);
  12007. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2,indentAmt+INDENT_SIZE);
  12008. break;
  12009. //PTNODE(knopAsgOr , "|=" ,BitOr ,Bin ,fnopBin|fnopAsg)
  12010. case knopAsgOr:
  12011. Indent(indentAmt);
  12012. Output::Print(_u("|=\n"));
  12013. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1,indentAmt+INDENT_SIZE);
  12014. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2,indentAmt+INDENT_SIZE);
  12015. break;
  12016. //PTNODE(knopAsgLsh , "<<=" ,Lsh ,Bin ,fnopBin|fnopAsg)
  12017. case knopAsgLsh:
  12018. Indent(indentAmt);
  12019. Output::Print(_u("<<=\n"));
  12020. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1,indentAmt+INDENT_SIZE);
  12021. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2,indentAmt+INDENT_SIZE);
  12022. break;
  12023. //PTNODE(knopAsgRsh , ">>=" ,Rsh ,Bin ,fnopBin|fnopAsg)
  12024. case knopAsgRsh:
  12025. Indent(indentAmt);
  12026. Output::Print(_u(">>=\n"));
  12027. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1,indentAmt+INDENT_SIZE);
  12028. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2,indentAmt+INDENT_SIZE);
  12029. break;
  12030. //PTNODE(knopAsgRs2 , ">>>=" ,Rs2 ,Bin ,fnopBin|fnopAsg)
  12031. case knopAsgRs2:
  12032. Indent(indentAmt);
  12033. Output::Print(_u(">>>=\n"));
  12034. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1,indentAmt+INDENT_SIZE);
  12035. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2,indentAmt+INDENT_SIZE);
  12036. break;
  12037. case knopComputedName:
  12038. Indent(indentAmt);
  12039. Output::Print(_u("ComputedProperty\n"));
  12040. PrintPnodeWIndent(pnode->AsParseNodeUni()->pnode1, indentAmt + INDENT_SIZE);
  12041. break;
  12042. //PTNODE(knopMember , ":" ,None ,Bin ,fnopBin)
  12043. case knopMember:
  12044. case knopMemberShort:
  12045. case knopObjectPatternMember:
  12046. Indent(indentAmt);
  12047. Output::Print(_u(":\n"));
  12048. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1,indentAmt+INDENT_SIZE);
  12049. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode2,indentAmt+INDENT_SIZE);
  12050. break;
  12051. // General nodes.
  12052. //PTNODE(knopList , "<list>" ,None ,Bin ,fnopNone)
  12053. case knopList:
  12054. Indent(indentAmt);
  12055. Output::Print(_u("List\n"));
  12056. PrintPnodeListWIndent(pnode,indentAmt+INDENT_SIZE);
  12057. break;
  12058. //PTNODE(knopVarDecl , "varDcl" ,None ,Var ,fnopNone)
  12059. case knopVarDecl:
  12060. Indent(indentAmt);
  12061. Output::Print(_u("var %s\n"),pnode->AsParseNodeVar()->pid->Psz());
  12062. if (pnode->AsParseNodeVar()->pnodeInit!=NULL)
  12063. PrintPnodeWIndent(pnode->AsParseNodeVar()->pnodeInit,indentAmt+INDENT_SIZE);
  12064. break;
  12065. case knopConstDecl:
  12066. Indent(indentAmt);
  12067. Output::Print(_u("const %s\n"),pnode->AsParseNodeVar()->pid->Psz());
  12068. if (pnode->AsParseNodeVar()->pnodeInit!=NULL)
  12069. PrintPnodeWIndent(pnode->AsParseNodeVar()->pnodeInit,indentAmt+INDENT_SIZE);
  12070. break;
  12071. case knopLetDecl:
  12072. Indent(indentAmt);
  12073. Output::Print(_u("let %s\n"),pnode->AsParseNodeVar()->pid->Psz());
  12074. if (pnode->AsParseNodeVar()->pnodeInit!=NULL)
  12075. PrintPnodeWIndent(pnode->AsParseNodeVar()->pnodeInit,indentAmt+INDENT_SIZE);
  12076. break;
  12077. //PTNODE(knopFncDecl , "fncDcl" ,None ,Fnc ,fnopLeaf)
  12078. case knopFncDecl:
  12079. Indent(indentAmt);
  12080. if (pnode->AsParseNodeFnc()->pid!=NULL)
  12081. {
  12082. Output::Print(_u("fn decl %d nested %d name %s (%d-%d)\n"),pnode->AsParseNodeFnc()->IsDeclaration(),pnode->AsParseNodeFnc()->IsNested(),
  12083. pnode->AsParseNodeFnc()->pid->Psz(), pnode->ichMin, pnode->ichLim);
  12084. }
  12085. else
  12086. {
  12087. Output::Print(_u("fn decl %d nested %d anonymous (%d-%d)\n"),pnode->AsParseNodeFnc()->IsDeclaration(),pnode->AsParseNodeFnc()->IsNested(),pnode->ichMin,pnode->ichLim);
  12088. }
  12089. PrintScopesWIndent(pnode, indentAmt+INDENT_SIZE);
  12090. PrintFormalsWIndent(pnode->AsParseNodeFnc()->pnodeParams, indentAmt + INDENT_SIZE);
  12091. PrintPnodeWIndent(pnode->AsParseNodeFnc()->pnodeRest, indentAmt + INDENT_SIZE);
  12092. PrintPnodeWIndent(pnode->AsParseNodeFnc()->pnodeBody, indentAmt + INDENT_SIZE);
  12093. if (pnode->AsParseNodeFnc()->pnodeBody == nullptr)
  12094. {
  12095. Output::Print(_u("[%4d, %4d): "), pnode->ichMin, pnode->ichLim);
  12096. Indent(indentAmt + INDENT_SIZE);
  12097. Output::Print(_u("<parse deferred body>\n"));
  12098. }
  12099. break;
  12100. //PTNODE(knopProg , "program" ,None ,Fnc ,fnopNone)
  12101. case knopProg:
  12102. Indent(indentAmt);
  12103. Output::Print(_u("program\n"));
  12104. PrintScopesWIndent(pnode, indentAmt+INDENT_SIZE);
  12105. PrintPnodeListWIndent(pnode->AsParseNodeFnc()->pnodeBody,indentAmt+INDENT_SIZE);
  12106. break;
  12107. //PTNODE(knopEndCode , "<endcode>" ,None ,None ,fnopNone)
  12108. case knopEndCode:
  12109. Indent(indentAmt);
  12110. Output::Print(_u("<endcode>\n"));
  12111. break;
  12112. //PTNODE(knopDebugger , "debugger" ,None ,None ,fnopNone)
  12113. case knopDebugger:
  12114. Indent(indentAmt);
  12115. Output::Print(_u("<debugger>\n"));
  12116. break;
  12117. //PTNODE(knopFor , "for" ,None ,For ,fnopBreak|fnopContinue)
  12118. case knopFor:
  12119. Indent(indentAmt);
  12120. Output::Print(_u("for\n"));
  12121. PrintScopesWIndent(pnode, indentAmt+INDENT_SIZE);
  12122. PrintPnodeWIndent(pnode->AsParseNodeFor()->pnodeInit,indentAmt+INDENT_SIZE);
  12123. PrintPnodeWIndent(pnode->AsParseNodeFor()->pnodeCond,indentAmt+INDENT_SIZE);
  12124. PrintPnodeWIndent(pnode->AsParseNodeFor()->pnodeIncr,indentAmt+INDENT_SIZE);
  12125. PrintPnodeWIndent(pnode->AsParseNodeFor()->pnodeBody,indentAmt+INDENT_SIZE);
  12126. break;
  12127. //PTNODE(knopIf , "if" ,None ,If ,fnopNone)
  12128. case knopIf:
  12129. Indent(indentAmt);
  12130. Output::Print(_u("if\n"));
  12131. PrintPnodeWIndent(pnode->AsParseNodeIf()->pnodeCond,indentAmt+INDENT_SIZE);
  12132. PrintPnodeWIndent(pnode->AsParseNodeIf()->pnodeTrue,indentAmt+INDENT_SIZE);
  12133. if (pnode->AsParseNodeIf()->pnodeFalse!=NULL)
  12134. PrintPnodeWIndent(pnode->AsParseNodeIf()->pnodeFalse,indentAmt+INDENT_SIZE);
  12135. break;
  12136. //PTNODE(knopWhile , "while" ,None ,While,fnopBreak|fnopContinue)
  12137. case knopWhile:
  12138. Indent(indentAmt);
  12139. Output::Print(_u("while\n"));
  12140. PrintPnodeWIndent(pnode->AsParseNodeWhile()->pnodeCond,indentAmt+INDENT_SIZE);
  12141. PrintPnodeWIndent(pnode->AsParseNodeWhile()->pnodeBody,indentAmt+INDENT_SIZE);
  12142. break;
  12143. //PTNODE(knopDoWhile , "do-while" ,None ,While,fnopBreak|fnopContinue)
  12144. case knopDoWhile:
  12145. Indent(indentAmt);
  12146. Output::Print(_u("do\n"));
  12147. PrintPnodeWIndent(pnode->AsParseNodeWhile()->pnodeCond,indentAmt+INDENT_SIZE);
  12148. PrintPnodeWIndent(pnode->AsParseNodeWhile()->pnodeBody,indentAmt+INDENT_SIZE);
  12149. break;
  12150. //PTNODE(knopForIn , "for in" ,None ,ForIn,fnopBreak|fnopContinue|fnopCleanup)
  12151. case knopForIn:
  12152. Indent(indentAmt);
  12153. Output::Print(_u("forIn\n"));
  12154. PrintScopesWIndent(pnode, indentAmt+INDENT_SIZE);
  12155. PrintPnodeWIndent(pnode->AsParseNodeForInOrForOf()->pnodeLval,indentAmt+INDENT_SIZE);
  12156. PrintPnodeWIndent(pnode->AsParseNodeForInOrForOf()->pnodeObj,indentAmt+INDENT_SIZE);
  12157. PrintPnodeWIndent(pnode->AsParseNodeForInOrForOf()->pnodeBody,indentAmt+INDENT_SIZE);
  12158. break;
  12159. case knopForOf:
  12160. Indent(indentAmt);
  12161. Output::Print(_u("forOf\n"));
  12162. PrintScopesWIndent(pnode, indentAmt+INDENT_SIZE);
  12163. PrintPnodeWIndent(pnode->AsParseNodeForInOrForOf()->pnodeLval,indentAmt+INDENT_SIZE);
  12164. PrintPnodeWIndent(pnode->AsParseNodeForInOrForOf()->pnodeObj,indentAmt+INDENT_SIZE);
  12165. PrintPnodeWIndent(pnode->AsParseNodeForInOrForOf()->pnodeBody,indentAmt+INDENT_SIZE);
  12166. break;
  12167. //PTNODE(knopReturn , "return" ,None ,Uni ,fnopNone)
  12168. case knopReturn:
  12169. Indent(indentAmt);
  12170. Output::Print(_u("return\n"));
  12171. if (pnode->AsParseNodeReturn()->pnodeExpr!=NULL)
  12172. PrintPnodeWIndent(pnode->AsParseNodeReturn()->pnodeExpr,indentAmt+INDENT_SIZE);
  12173. break;
  12174. //PTNODE(knopBlock , "{}" ,None ,Block,fnopNone)
  12175. case knopBlock:
  12176. Indent(indentAmt);
  12177. Output::Print(_u("block "));
  12178. if (pnode->grfpn & fpnSyntheticNode)
  12179. Output::Print(_u("synthetic "));
  12180. PrintBlockType(pnode->AsParseNodeBlock()->blockType);
  12181. Output::Print(_u("(%d-%d)\n"),pnode->ichMin,pnode->ichLim);
  12182. PrintScopesWIndent(pnode, indentAmt+INDENT_SIZE);
  12183. if (pnode->AsParseNodeBlock()->pnodeStmt!=NULL)
  12184. PrintPnodeWIndent(pnode->AsParseNodeBlock()->pnodeStmt,indentAmt+INDENT_SIZE);
  12185. break;
  12186. //PTNODE(knopWith , "with" ,None ,With ,fnopCleanup)
  12187. case knopWith:
  12188. Indent(indentAmt);
  12189. Output::Print(_u("with (%d-%d)\n"), pnode->ichMin,pnode->ichLim);
  12190. PrintScopesWIndent(pnode, indentAmt+INDENT_SIZE);
  12191. PrintPnodeWIndent(pnode->AsParseNodeWith()->pnodeObj,indentAmt+INDENT_SIZE);
  12192. PrintPnodeWIndent(pnode->AsParseNodeWith()->pnodeBody,indentAmt+INDENT_SIZE);
  12193. break;
  12194. //PTNODE(knopBreak , "break" ,None ,Jump ,fnopNone)
  12195. case knopBreak:
  12196. Indent(indentAmt);
  12197. Output::Print(_u("break\n"));
  12198. // TODO: some representation of target
  12199. break;
  12200. //PTNODE(knopContinue , "continue" ,None ,Jump ,fnopNone)
  12201. case knopContinue:
  12202. Indent(indentAmt);
  12203. Output::Print(_u("continue\n"));
  12204. // TODO: some representation of target
  12205. break;
  12206. //PTNODE(knopSwitch , "switch" ,None ,Switch,fnopBreak)
  12207. case knopSwitch:
  12208. Indent(indentAmt);
  12209. Output::Print(_u("switch\n"));
  12210. PrintScopesWIndent(pnode, indentAmt+INDENT_SIZE);
  12211. for (ParseNode *pnodeT = pnode->AsParseNodeSwitch()->pnodeCases; NULL != pnodeT;pnodeT = pnodeT->AsParseNodeCase()->pnodeNext) {
  12212. PrintPnodeWIndent(pnodeT,indentAmt+2);
  12213. }
  12214. break;
  12215. //PTNODE(knopCase , "case" ,None ,Case ,fnopNone)
  12216. case knopCase:
  12217. Indent(indentAmt);
  12218. Output::Print(_u("case\n"));
  12219. PrintPnodeWIndent(pnode->AsParseNodeCase()->pnodeExpr,indentAmt+INDENT_SIZE);
  12220. PrintPnodeWIndent(pnode->AsParseNodeCase()->pnodeBody,indentAmt+INDENT_SIZE);
  12221. break;
  12222. //PTNODE(knopTryFinally,"try-finally",None,TryFinally,fnopCleanup)
  12223. case knopTryFinally:
  12224. PrintPnodeWIndent(pnode->AsParseNodeTryFinally()->pnodeTry,indentAmt);
  12225. PrintPnodeWIndent(pnode->AsParseNodeTryFinally()->pnodeFinally,indentAmt);
  12226. break;
  12227. case knopFinally:
  12228. Indent(indentAmt);
  12229. Output::Print(_u("finally\n"));
  12230. PrintPnodeWIndent(pnode->AsParseNodeFinally()->pnodeBody,indentAmt+INDENT_SIZE);
  12231. break;
  12232. //PTNODE(knopCatch , "catch" ,None ,Catch,fnopNone)
  12233. case knopCatch:
  12234. Indent(indentAmt);
  12235. Output::Print(_u("catch (%d-%d)\n"), pnode->ichMin,pnode->ichLim);
  12236. PrintScopesWIndent(pnode, indentAmt+INDENT_SIZE);
  12237. PrintPnodeWIndent(pnode->AsParseNodeCatch()->pnodeParam,indentAmt+INDENT_SIZE);
  12238. // if (pnode->AsParseNodeCatch()->pnodeGuard!=NULL)
  12239. // PrintPnodeWIndent(pnode->AsParseNodeCatch()->pnodeGuard,indentAmt+INDENT_SIZE);
  12240. PrintPnodeWIndent(pnode->AsParseNodeCatch()->pnodeBody,indentAmt+INDENT_SIZE);
  12241. break;
  12242. //PTNODE(knopTryCatch , "try-catch" ,None ,TryCatch ,fnopCleanup)
  12243. case knopTryCatch:
  12244. PrintPnodeWIndent(pnode->AsParseNodeTryCatch()->pnodeTry,indentAmt);
  12245. PrintPnodeWIndent(pnode->AsParseNodeTryCatch()->pnodeCatch,indentAmt);
  12246. break;
  12247. //PTNODE(knopTry , "try" ,None ,Try ,fnopCleanup)
  12248. case knopTry:
  12249. Indent(indentAmt);
  12250. Output::Print(_u("try\n"));
  12251. PrintPnodeWIndent(pnode->AsParseNodeTry()->pnodeBody,indentAmt+INDENT_SIZE);
  12252. break;
  12253. //PTNODE(knopThrow , "throw" ,None ,Uni ,fnopNone)
  12254. case knopThrow:
  12255. Indent(indentAmt);
  12256. Output::Print(_u("throw\n"));
  12257. PrintPnodeWIndent(pnode->AsParseNodeUni()->pnode1,indentAmt+INDENT_SIZE);
  12258. break;
  12259. //PTNODE(knopClassDecl, "classDecl", None , Class, fnopLeaf)
  12260. case knopClassDecl:
  12261. Indent(indentAmt);
  12262. Output::Print(_u("class %s"), pnode->AsParseNodeClass()->pnodeName->AsParseNodeVar()->pid->Psz());
  12263. if (pnode->AsParseNodeClass()->pnodeExtends != nullptr)
  12264. {
  12265. Output::Print(_u(" extends "));
  12266. PrintPnodeWIndent(pnode->AsParseNodeClass()->pnodeExtends, 0);
  12267. }
  12268. else {
  12269. Output::Print(_u("\n"));
  12270. }
  12271. PrintPnodeWIndent(pnode->AsParseNodeClass()->pnodeConstructor, indentAmt + INDENT_SIZE);
  12272. PrintPnodeWIndent(pnode->AsParseNodeClass()->pnodeMembers, indentAmt + INDENT_SIZE);
  12273. PrintPnodeWIndent(pnode->AsParseNodeClass()->pnodeStaticMembers, indentAmt + INDENT_SIZE);
  12274. break;
  12275. case knopStrTemplate:
  12276. Indent(indentAmt);
  12277. Output::Print(_u("string template\n"));
  12278. PrintPnodeListWIndent(pnode->AsParseNodeStrTemplate()->pnodeSubstitutionExpressions, indentAmt + INDENT_SIZE);
  12279. break;
  12280. case knopYieldStar:
  12281. Indent(indentAmt);
  12282. Output::Print(_u("yield*\n"));
  12283. PrintPnodeListWIndent(pnode->AsParseNodeUni()->pnode1, indentAmt + INDENT_SIZE);
  12284. break;
  12285. case knopYield:
  12286. case knopYieldLeaf:
  12287. Indent(indentAmt);
  12288. Output::Print(_u("yield\n"));
  12289. PrintPnodeListWIndent(pnode->AsParseNodeUni()->pnode1, indentAmt + INDENT_SIZE);
  12290. break;
  12291. case knopAwait:
  12292. Indent(indentAmt);
  12293. Output::Print(_u("await\n"));
  12294. PrintPnodeListWIndent(pnode->AsParseNodeUni()->pnode1, indentAmt + INDENT_SIZE);
  12295. break;
  12296. case knopExportDefault:
  12297. Indent(indentAmt);
  12298. Output::Print(_u("export default\n"));
  12299. PrintPnodeListWIndent(pnode->AsParseNodeExportDefault()->pnodeExpr, indentAmt + INDENT_SIZE);
  12300. break;
  12301. default:
  12302. Output::Print(_u("unhandled pnode op %d\n"),pnode->nop);
  12303. break;
  12304. }
  12305. }
  12306. void PrintPnodeListWIndent(ParseNode *pnode,int indentAmt) {
  12307. if (pnode!=NULL) {
  12308. while(pnode->nop==knopList) {
  12309. PrintPnodeWIndent(pnode->AsParseNodeBin()->pnode1,indentAmt);
  12310. pnode = pnode->AsParseNodeBin()->pnode2;
  12311. }
  12312. PrintPnodeWIndent(pnode,indentAmt);
  12313. }
  12314. }
  12315. void PrintFormalsWIndent(ParseNode *pnodeArgs, int indentAmt)
  12316. {
  12317. for (ParseNode *pnode = pnodeArgs; pnode != nullptr; pnode = pnode->GetFormalNext())
  12318. {
  12319. PrintPnodeWIndent(pnode->nop == knopParamPattern ? pnode->AsParseNodeParamPattern()->pnode1 : pnode, indentAmt);
  12320. }
  12321. }
  12322. void PrintPnode(ParseNode *pnode) {
  12323. PrintPnodeWIndent(pnode,0);
  12324. }
  12325. void ParseNode::Dump()
  12326. {
  12327. switch(nop)
  12328. {
  12329. case knopFncDecl:
  12330. case knopProg:
  12331. LPCOLESTR name = Js::Constants::AnonymousFunction;
  12332. if(this->AsParseNodeFnc()->pnodeName)
  12333. {
  12334. name = this->AsParseNodeFnc()->pnodeName->AsParseNodeVar()->pid->Psz();
  12335. }
  12336. Output::Print(_u("%s (%d) [%d, %d]:\n"), name, this->AsParseNodeFnc()->functionId, this->AsParseNodeFnc()->lineNumber, this->AsParseNodeFnc()->columnNumber);
  12337. Output::Print(_u("hasArguments: %s callsEval:%s childCallsEval:%s HasReferenceableBuiltInArguments:%s ArgumentsObjectEscapes:%s HasWith:%s HasOnlyThis:%s \n"),
  12338. IsTrueOrFalse(this->AsParseNodeFnc()->HasHeapArguments()),
  12339. IsTrueOrFalse(this->AsParseNodeFnc()->CallsEval()),
  12340. IsTrueOrFalse(this->AsParseNodeFnc()->ChildCallsEval()),
  12341. IsTrueOrFalse(this->AsParseNodeFnc()->HasReferenceableBuiltInArguments()),
  12342. IsTrueOrFalse(this->AsParseNodeFnc()->GetArgumentsObjectEscapes()),
  12343. IsTrueOrFalse(this->AsParseNodeFnc()->HasWithStmt()),
  12344. IsTrueOrFalse(this->AsParseNodeFnc()->HasOnlyThisStmts()));
  12345. if(this->AsParseNodeFnc()->funcInfo)
  12346. {
  12347. this->AsParseNodeFnc()->funcInfo->Dump();
  12348. }
  12349. break;
  12350. }
  12351. }
  12352. #endif
  12353. DeferredFunctionStub * BuildDeferredStubTree(ParseNode *pnodeFnc, Recycler *recycler)
  12354. {
  12355. Assert(pnodeFnc->nop == knopFncDecl);
  12356. uint nestedCount = pnodeFnc->AsParseNodeFnc()->nestedCount;
  12357. if (nestedCount == 0)
  12358. {
  12359. return nullptr;
  12360. }
  12361. if (pnodeFnc->AsParseNodeFnc()->deferredStub)
  12362. {
  12363. return pnodeFnc->AsParseNodeFnc()->deferredStub;
  12364. }
  12365. DeferredFunctionStub *deferredStubs = RecyclerNewArray(recycler, DeferredFunctionStub, nestedCount);
  12366. uint i = 0;
  12367. ParseNode *pnodeBlock = pnodeFnc->AsParseNodeFnc()->pnodeBodyScope;
  12368. Assert(pnodeBlock != nullptr
  12369. && pnodeBlock->nop == knopBlock
  12370. && (pnodeBlock->AsParseNodeBlock()->blockType == PnodeBlockType::Function
  12371. || pnodeBlock->AsParseNodeBlock()->blockType == PnodeBlockType::Parameter));
  12372. for (ParseNode *pnodeChild = pnodeBlock->AsParseNodeBlock()->pnodeScopes; pnodeChild != nullptr;)
  12373. {
  12374. if (pnodeChild->nop != knopFncDecl)
  12375. {
  12376. // We only expect to find a function body block in a parameter scope block.
  12377. Assert(pnodeChild->nop == knopBlock
  12378. && (pnodeBlock->AsParseNodeBlock()->blockType == PnodeBlockType::Parameter
  12379. || pnodeChild->AsParseNodeBlock()->blockType == PnodeBlockType::Function));
  12380. pnodeChild = pnodeChild->AsParseNodeBlock()->pnodeNext;
  12381. continue;
  12382. }
  12383. AssertOrFailFast(i < nestedCount);
  12384. if (pnodeChild->AsParseNodeFnc()->pnodeBody != nullptr)
  12385. {
  12386. // Anomalous case of a non-deferred function nested within a deferred one.
  12387. // Work around by discarding the stub tree.
  12388. return nullptr;
  12389. }
  12390. if (pnodeChild->AsParseNodeFnc()->IsGeneratedDefault())
  12391. {
  12392. ++i;
  12393. pnodeChild = pnodeChild->AsParseNodeFnc()->pnodeNext;
  12394. continue;
  12395. }
  12396. AnalysisAssertOrFailFast(i < nestedCount);
  12397. deferredStubs[i].fncFlags = pnodeChild->AsParseNodeFnc()->fncFlags;
  12398. deferredStubs[i].nestedCount = pnodeChild->AsParseNodeFnc()->nestedCount;
  12399. deferredStubs[i].restorePoint = *pnodeChild->AsParseNodeFnc()->pRestorePoint;
  12400. deferredStubs[i].deferredStubs = BuildDeferredStubTree(pnodeChild, recycler);
  12401. deferredStubs[i].ichMin = pnodeChild->ichMin;
  12402. ++i;
  12403. pnodeChild = pnodeChild->AsParseNodeFnc()->pnodeNext;
  12404. }
  12405. return deferredStubs;
  12406. }