Parse.cpp 473 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065
  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. ParseNodePtr pnodeLab; // Labels for this statement.
  43. };
  44. struct
  45. {
  46. bool isDeferred : 1;
  47. OpCode op; // This statement operation.
  48. LabelId* pLabelId; // Labels for this statement.
  49. };
  50. };
  51. StmtNest *pstmtOuter; // Enclosing statement.
  52. OpCode GetNop() const
  53. {
  54. AnalysisAssert(isDeferred || pnodeStmt != nullptr);
  55. return isDeferred ? op : pnodeStmt->nop;
  56. }
  57. };
  58. struct BlockInfoStack
  59. {
  60. StmtNest pstmt;
  61. ParseNode *pnodeBlock;
  62. ParseNodePtr *m_ppnodeLex; // lexical variable list tail
  63. BlockInfoStack *pBlockInfoOuter; // containing block's BlockInfoStack
  64. BlockInfoStack *pBlockInfoFunction; // nearest function's BlockInfoStack (if pnodeBlock is a function, this points to itself)
  65. };
  66. #if DEBUG
  67. Parser::Parser(Js::ScriptContext* scriptContext, BOOL strictMode, PageAllocator *alloc, bool isBackground, size_t size)
  68. #else
  69. Parser::Parser(Js::ScriptContext* scriptContext, BOOL strictMode, PageAllocator *alloc, bool isBackground)
  70. #endif
  71. : m_nodeAllocator(_u("Parser"), alloc ? alloc : scriptContext->GetThreadContext()->GetPageAllocator(), Parser::OutOfMemory),
  72. // use the GuestArena directly for keeping the RegexPattern* alive during byte code generation
  73. m_registeredRegexPatterns(scriptContext->GetGuestArena())
  74. {
  75. AssertMsg(size == sizeof(Parser), "verify conditionals affecting the size of Parser agree");
  76. Assert(scriptContext != nullptr);
  77. m_phtbl = nullptr;
  78. m_pscan = nullptr;
  79. m_deferringAST = FALSE;
  80. m_stoppedDeferredParse = FALSE;
  81. #if ENABLE_BACKGROUND_PARSING
  82. m_isInBackground = isBackground;
  83. m_hasParallelJob = false;
  84. m_doingFastScan = false;
  85. #endif
  86. m_isInParsingArgList = false;
  87. m_hasDestructuringPattern = false;
  88. m_scriptContext = scriptContext;
  89. m_pCurrentAstSize = nullptr;
  90. m_arrayDepth = 0;
  91. m_funcInArrayDepth = 0;
  92. m_funcParenExprDepth = 0;
  93. m_funcInArray = 0;
  94. m_tryCatchOrFinallyDepth = 0;
  95. m_UsesArgumentsAtGlobal = false;
  96. m_currentNodeFunc = nullptr;
  97. m_currentNodeDeferredFunc = nullptr;
  98. m_currentNodeNonLambdaFunc = nullptr;
  99. m_currentNodeNonLambdaDeferredFunc = nullptr;
  100. m_currentNodeProg = nullptr;
  101. m_currDeferredStub = nullptr;
  102. m_prevSiblingDeferredStub = nullptr;
  103. m_pstmtCur = nullptr;
  104. m_currentBlockInfo = nullptr;
  105. m_currentScope = nullptr;
  106. m_currentDynamicBlock = nullptr;
  107. m_grfscr = fscrNil;
  108. m_length = 0;
  109. m_originalLength = 0;
  110. m_nextFunctionId = nullptr;
  111. m_reparsingLambdaParams = false;
  112. currBackgroundParseItem = nullptr;
  113. backgroundParseItems = nullptr;
  114. fastScannedRegExpNodes = nullptr;
  115. m_fUseStrictMode = strictMode;
  116. m_InAsmMode = false;
  117. m_deferAsmJs = true;
  118. m_scopeCountNoAst = 0;
  119. m_fExpectExternalSource = 0;
  120. m_parseType = ParseType_Upfront;
  121. m_deferEllipsisError = false;
  122. m_hasDeferredShorthandInitError = false;
  123. m_parsingSuperRestrictionState = ParsingSuperRestrictionState_SuperDisallowed;
  124. m_disallowImportExportStmt = false;
  125. }
  126. Parser::~Parser(void)
  127. {
  128. if (m_scriptContext == nullptr || m_scriptContext->GetGuestArena() == nullptr)
  129. {
  130. // If the scriptContext or guestArena have gone away, there is no point clearing each item of this list.
  131. // Just reset it so that destructor of the SList will be no-op
  132. m_registeredRegexPatterns.Reset();
  133. }
  134. #if ENABLE_BACKGROUND_PARSING
  135. if (this->m_hasParallelJob)
  136. {
  137. // Let the background threads know that they can decommit their arena pages.
  138. BackgroundParser *bgp = m_scriptContext->GetBackgroundParser();
  139. Assert(bgp);
  140. if (bgp->Processor()->ProcessesInBackground())
  141. {
  142. JsUtil::BackgroundJobProcessor *processor = static_cast<JsUtil::BackgroundJobProcessor*>(bgp->Processor());
  143. bool result = processor->IterateBackgroundThreads([&](JsUtil::ParallelThreadData *threadData)->bool {
  144. threadData->canDecommit = true;
  145. return false;
  146. });
  147. Assert(result);
  148. }
  149. }
  150. #endif
  151. Release();
  152. }
  153. void Parser::OutOfMemory()
  154. {
  155. throw ParseExceptionObject(ERRnoMemory);
  156. }
  157. void Parser::Error(HRESULT hr)
  158. {
  159. throw ParseExceptionObject(hr);
  160. }
  161. void Parser::Error(HRESULT hr, ParseNodePtr pnode)
  162. {
  163. if (pnode && pnode->ichLim)
  164. {
  165. Error(hr, pnode->ichMin, pnode->ichLim);
  166. }
  167. else
  168. {
  169. Error(hr);
  170. }
  171. }
  172. void Parser::Error(HRESULT hr, charcount_t ichMin, charcount_t ichLim)
  173. {
  174. m_pscan->SetErrorPosition(ichMin, ichLim);
  175. Error(hr);
  176. }
  177. void Parser::IdentifierExpectedError(const Token& token)
  178. {
  179. Assert(token.tk != tkID);
  180. HRESULT hr;
  181. if (token.IsReservedWord())
  182. {
  183. if (token.IsKeyword())
  184. {
  185. hr = ERRKeywordNotId;
  186. }
  187. else
  188. {
  189. Assert(token.IsFutureReservedWord(true));
  190. if (token.IsFutureReservedWord(false))
  191. {
  192. // Future reserved word in strict and non-strict modes
  193. hr = ERRFutureReservedWordNotId;
  194. }
  195. else
  196. {
  197. // Future reserved word only in strict mode. The token would have been converted to tkID by the scanner if not
  198. // in strict mode.
  199. Assert(IsStrictMode());
  200. hr = ERRFutureReservedWordInStrictModeNotId;
  201. }
  202. }
  203. }
  204. else
  205. {
  206. hr = ERRnoIdent;
  207. }
  208. Error(hr);
  209. }
  210. HRESULT Parser::ValidateSyntax(LPCUTF8 pszSrc, size_t encodedCharCount, bool isGenerator, bool isAsync, CompileScriptException *pse, void (Parser::*validateFunction)())
  211. {
  212. AssertPsz(pszSrc);
  213. AssertMemN(pse);
  214. PROBE_STACK_NO_DISPOSE(m_scriptContext, Js::Constants::MinStackDefault);
  215. HRESULT hr;
  216. SmartFPUControl smartFpuControl;
  217. BOOL fDeferSave = m_deferringAST;
  218. try
  219. {
  220. hr = NOERROR;
  221. this->PrepareScanner(false);
  222. m_length = encodedCharCount;
  223. m_originalLength = encodedCharCount;
  224. // make sure deferred parsing is turned off
  225. ULONG grfscr = fscrNil;
  226. // Give the scanner the source and get the first token
  227. m_pscan->SetText(pszSrc, 0, encodedCharCount, 0, grfscr);
  228. m_pscan->SetYieldIsKeywordRegion(isGenerator);
  229. m_pscan->SetAwaitIsKeywordRegion(isAsync);
  230. m_pscan->Scan();
  231. uint nestedCount = 0;
  232. m_pnestedCount = &nestedCount;
  233. ParseNodePtr pnodeScope = nullptr;
  234. m_ppnodeScope = &pnodeScope;
  235. m_ppnodeExprScope = nullptr;
  236. uint nextFunctionId = 0;
  237. m_nextFunctionId = &nextFunctionId;
  238. m_inDeferredNestedFunc = false;
  239. m_deferringAST = true;
  240. m_nextBlockId = 0;
  241. ParseNode *pnodeFnc = CreateNode(knopFncDecl);
  242. pnodeFnc->sxFnc.ClearFlags();
  243. pnodeFnc->sxFnc.SetDeclaration(false);
  244. pnodeFnc->sxFnc.functionId = 0;
  245. pnodeFnc->sxFnc.astSize = 0;
  246. pnodeFnc->sxFnc.pnodeVars = nullptr;
  247. pnodeFnc->sxFnc.pnodeParams = nullptr;
  248. pnodeFnc->sxFnc.pnodeBody = nullptr;
  249. pnodeFnc->sxFnc.pnodeName = nullptr;
  250. pnodeFnc->sxFnc.pnodeRest = nullptr;
  251. pnodeFnc->sxFnc.deferredStub = nullptr;
  252. pnodeFnc->sxFnc.SetIsGenerator(isGenerator);
  253. pnodeFnc->sxFnc.SetIsAsync(isAsync);
  254. m_ppnodeVar = &pnodeFnc->sxFnc.pnodeVars;
  255. m_currentNodeFunc = pnodeFnc;
  256. m_currentNodeDeferredFunc = NULL;
  257. m_sourceContextInfo = nullptr;
  258. AssertMsg(m_pstmtCur == NULL, "Statement stack should be empty when we start parse function body");
  259. ParseNodePtr block = StartParseBlock<false>(PnodeBlockType::Function, ScopeType_FunctionBody);
  260. (this->*validateFunction)();
  261. FinishParseBlock(block);
  262. pnodeFnc->ichLim = m_pscan->IchLimTok();
  263. pnodeFnc->sxFnc.cbLim = m_pscan->IecpLimTok();
  264. pnodeFnc->sxFnc.pnodeVars = nullptr;
  265. // there should be nothing after successful parsing for a given construct
  266. if (m_token.tk != tkEOF)
  267. Error(ERRsyntax);
  268. RELEASEPTR(m_pscan);
  269. m_deferringAST = fDeferSave;
  270. }
  271. catch(ParseExceptionObject& e)
  272. {
  273. m_deferringAST = fDeferSave;
  274. hr = e.GetError();
  275. }
  276. if (nullptr != pse && FAILED(hr))
  277. {
  278. hr = pse->ProcessError(m_pscan, hr, /* pnodeBase */ NULL);
  279. }
  280. return hr;
  281. }
  282. HRESULT Parser::ParseSourceInternal(
  283. __out ParseNodePtr* parseTree, LPCUTF8 pszSrc, size_t offsetInBytes, size_t encodedCharCount, charcount_t offsetInChars,
  284. bool fromExternal, ULONG grfscr, CompileScriptException *pse, Js::LocalFunctionId * nextFunctionId, ULONG lineNumber, SourceContextInfo * sourceContextInfo)
  285. {
  286. AssertMem(parseTree);
  287. AssertPsz(pszSrc);
  288. AssertMemN(pse);
  289. if (this->IsBackgroundParser())
  290. {
  291. PROBE_STACK_NO_DISPOSE(m_scriptContext, Js::Constants::MinStackDefault);
  292. }
  293. else
  294. {
  295. PROBE_STACK(m_scriptContext, Js::Constants::MinStackDefault);
  296. }
  297. #ifdef PROFILE_EXEC
  298. m_scriptContext->ProfileBegin(Js::ParsePhase);
  299. #endif
  300. JS_ETW_INTERNAL(EventWriteJSCRIPT_PARSE_START(m_scriptContext,0));
  301. *parseTree = NULL;
  302. m_sourceLim = 0;
  303. m_grfscr = grfscr;
  304. m_sourceContextInfo = sourceContextInfo;
  305. ParseNodePtr pnodeBase = NULL;
  306. HRESULT hr;
  307. SmartFPUControl smartFpuControl;
  308. try
  309. {
  310. this->PrepareScanner(fromExternal);
  311. if ((grfscr & fscrEvalCode) != 0)
  312. {
  313. this->m_parsingSuperRestrictionState = Parser::ParsingSuperRestrictionState_SuperPropertyAllowed;
  314. }
  315. if ((grfscr & fscrIsModuleCode) != 0)
  316. {
  317. // Module source flag should not be enabled unless module is enabled
  318. Assert(m_scriptContext->GetConfig()->IsES6ModuleEnabled());
  319. // Module code is always strict mode code.
  320. this->m_fUseStrictMode = TRUE;
  321. }
  322. // parse the source
  323. pnodeBase = Parse(pszSrc, offsetInBytes, encodedCharCount, offsetInChars, grfscr, lineNumber, nextFunctionId, pse);
  324. AssertNodeMem(pnodeBase);
  325. // Record the actual number of words parsed.
  326. m_sourceLim = pnodeBase->ichLim - offsetInChars;
  327. // TODO: The assert can be false positive in some scenarios and chuckj to fix it later
  328. // Assert(utf8::ByteIndexIntoCharacterIndex(pszSrc + offsetInBytes, encodedCharCount, fromExternal ? utf8::doDefault : utf8::doAllowThreeByteSurrogates) == m_sourceLim);
  329. #if DBG_DUMP
  330. if (Js::Configuration::Global.flags.Trace.IsEnabled(Js::ParsePhase))
  331. {
  332. PrintPnodeWIndent(pnodeBase,4);
  333. fflush(stdout);
  334. }
  335. #endif
  336. *parseTree = pnodeBase;
  337. hr = NOERROR;
  338. }
  339. catch(ParseExceptionObject& e)
  340. {
  341. hr = e.GetError();
  342. }
  343. catch (Js::AsmJsParseException&)
  344. {
  345. hr = JSERR_AsmJsCompileError;
  346. }
  347. if (FAILED(hr))
  348. {
  349. hr = pse->ProcessError(m_pscan, hr, pnodeBase);
  350. }
  351. #if ENABLE_BACKGROUND_PARSING
  352. if (this->m_hasParallelJob)
  353. {
  354. ///// Wait here for remaining jobs to finish. Then look for errors, do final const bindings.
  355. // pleath TODO: If there are remaining jobs, let the main thread help finish them.
  356. BackgroundParser *bgp = m_scriptContext->GetBackgroundParser();
  357. Assert(bgp);
  358. CompileScriptException se;
  359. this->WaitForBackgroundJobs(bgp, &se);
  360. BackgroundParseItem *failedItem = bgp->GetFailedBackgroundParseItem();
  361. if (failedItem)
  362. {
  363. CompileScriptException *bgPse = failedItem->GetPSE();
  364. Assert(bgPse);
  365. *pse = *bgPse;
  366. hr = failedItem->GetHR();
  367. bgp->SetFailedBackgroundParseItem(nullptr);
  368. }
  369. if (this->fastScannedRegExpNodes != nullptr)
  370. {
  371. this->FinishBackgroundRegExpNodes();
  372. }
  373. for (BackgroundParseItem *item = this->backgroundParseItems; item; item = item->GetNext())
  374. {
  375. Parser *parser = item->GetParser();
  376. parser->FinishBackgroundPidRefs(item, this != parser);
  377. }
  378. }
  379. #endif
  380. // done with the scanner
  381. RELEASEPTR(m_pscan);
  382. #ifdef PROFILE_EXEC
  383. m_scriptContext->ProfileEnd(Js::ParsePhase);
  384. #endif
  385. JS_ETW_INTERNAL(EventWriteJSCRIPT_PARSE_STOP(m_scriptContext, 0));
  386. return hr;
  387. }
  388. #if ENABLE_BACKGROUND_PARSING
  389. void Parser::WaitForBackgroundJobs(BackgroundParser *bgp, CompileScriptException *pse)
  390. {
  391. // The scan of the script is done, but there may be unfinished background jobs in the queue.
  392. // Enlist the main thread to help with those.
  393. BackgroundParseItem *item;
  394. if (!*bgp->GetPendingBackgroundItemsPtr())
  395. {
  396. // We're done.
  397. return;
  398. }
  399. // Save parser state, since we'll need to restore it in order to bind references correctly later.
  400. this->m_isInBackground = true;
  401. this->SetCurrBackgroundParseItem(nullptr);
  402. uint blockIdSave = this->m_nextBlockId;
  403. uint functionIdSave = *this->m_nextFunctionId;
  404. StmtNest *pstmtSave = this->m_pstmtCur;
  405. if (!bgp->Processor()->ProcessesInBackground())
  406. {
  407. // No background thread. Just walk the jobs with no locking and process them.
  408. for (item = bgp->GetNextUnprocessedItem(); item; item = bgp->GetNextUnprocessedItem())
  409. {
  410. bgp->Processor()->RemoveJob(item);
  411. bool succeeded = bgp->Process(item, this, pse);
  412. bgp->JobProcessed(item, succeeded);
  413. }
  414. Assert(!*bgp->GetPendingBackgroundItemsPtr());
  415. }
  416. else
  417. {
  418. // Background threads. We need to have the critical section in order to:
  419. // - Check for unprocessed jobs;
  420. // - Remove jobs from the processor queue;
  421. // - Do JobsProcessed work (such as removing jobs from the BackgroundParser's unprocessed list).
  422. CriticalSection *pcs = static_cast<JsUtil::BackgroundJobProcessor*>(bgp->Processor())->GetCriticalSection();
  423. pcs->Enter();
  424. for (;;)
  425. {
  426. // Grab a job (in lock)
  427. item = bgp->GetNextUnprocessedItem();
  428. if (item == nullptr)
  429. {
  430. break;
  431. }
  432. bgp->Processor()->RemoveJob(item);
  433. pcs->Leave();
  434. // Process job (if there is one) (outside lock)
  435. bool succeeded = bgp->Process(item, this, pse);
  436. pcs->Enter();
  437. bgp->JobProcessed(item, succeeded);
  438. }
  439. pcs->Leave();
  440. // Wait for the background threads to finish jobs they're already processing (if any).
  441. // TODO: Replace with a proper semaphore.
  442. while(*bgp->GetPendingBackgroundItemsPtr());
  443. }
  444. Assert(!*bgp->GetPendingBackgroundItemsPtr());
  445. // Restore parser state.
  446. this->m_pstmtCur = pstmtSave;
  447. this->m_isInBackground = false;
  448. this->m_nextBlockId = blockIdSave;
  449. *this->m_nextFunctionId = functionIdSave;
  450. }
  451. void Parser::FinishBackgroundPidRefs(BackgroundParseItem *item, bool isOtherParser)
  452. {
  453. for (BlockInfoStack *blockInfo = item->GetParseContext()->currentBlockInfo; blockInfo; blockInfo = blockInfo->pBlockInfoOuter)
  454. {
  455. if (isOtherParser)
  456. {
  457. this->BindPidRefs<true>(blockInfo, item->GetMaxBlockId());
  458. }
  459. else
  460. {
  461. this->BindPidRefs<false>(blockInfo, item->GetMaxBlockId());
  462. }
  463. }
  464. }
  465. void Parser::FinishBackgroundRegExpNodes()
  466. {
  467. // We have a list of RegExp nodes that we saw on the UI thread in functions we're parallel parsing,
  468. // and for each background job we have a list of RegExp nodes for which we couldn't allocate patterns.
  469. // We need to copy the pattern pointers from the UI thread nodes to the corresponding nodes on the
  470. // background nodes.
  471. // There may be UI thread nodes for which there are no background thread equivalents, because the UI thread
  472. // has to assume that the background thread won't defer anything.
  473. // Note that because these lists (and the list of background jobs) are SList's built by prepending, they are
  474. // all in reverse lexical order.
  475. Assert(!this->IsBackgroundParser());
  476. Assert(this->fastScannedRegExpNodes);
  477. Assert(this->backgroundParseItems != nullptr);
  478. BackgroundParseItem *currBackgroundItem;
  479. #if DBG
  480. for (currBackgroundItem = this->backgroundParseItems;
  481. currBackgroundItem;
  482. currBackgroundItem = currBackgroundItem->GetNext())
  483. {
  484. if (currBackgroundItem->RegExpNodeList())
  485. {
  486. FOREACH_DLIST_ENTRY(ParseNodePtr, ArenaAllocator, pnode, currBackgroundItem->RegExpNodeList())
  487. {
  488. Assert(pnode->sxPid.regexPattern == nullptr);
  489. }
  490. NEXT_DLIST_ENTRY;
  491. }
  492. }
  493. #endif
  494. // Hook up the patterns allocated on the main thread to the nodes created on the background thread.
  495. // Walk the list of foreground nodes, advancing through the work items and looking up each item.
  496. // Note that the background thread may have chosen to defer a given RegEx literal, so not every foreground
  497. // node will have a matching background node. Doesn't matter for correctness.
  498. // (It's inefficient, of course, to have to restart the inner loop from the beginning of the work item's
  499. // list, but it should be unusual to have many RegExes in a single work item's chunk of code. Figure out how
  500. // to start the inner loop from a known internal node within the list if that turns out to be important.)
  501. currBackgroundItem = this->backgroundParseItems;
  502. FOREACH_DLIST_ENTRY(ParseNodePtr, ArenaAllocator, pnodeFgnd, this->fastScannedRegExpNodes)
  503. {
  504. Assert(pnodeFgnd->nop == knopRegExp);
  505. Assert(pnodeFgnd->sxPid.regexPattern != nullptr);
  506. bool quit = false;
  507. while (!quit)
  508. {
  509. // Find the next work item with a RegEx in it.
  510. while (currBackgroundItem && currBackgroundItem->RegExpNodeList() == nullptr)
  511. {
  512. currBackgroundItem = currBackgroundItem->GetNext();
  513. }
  514. if (!currBackgroundItem)
  515. {
  516. break;
  517. }
  518. // Walk the RegExps in the work item.
  519. FOREACH_DLIST_ENTRY(ParseNodePtr, ArenaAllocator, pnodeBgnd, currBackgroundItem->RegExpNodeList())
  520. {
  521. Assert(pnodeBgnd->nop == knopRegExp);
  522. if (pnodeFgnd->ichMin <= pnodeBgnd->ichMin)
  523. {
  524. // Either we found a match, or the next background node is past the foreground node.
  525. // In any case, we can stop searching.
  526. if (pnodeFgnd->ichMin == pnodeBgnd->ichMin)
  527. {
  528. Assert(pnodeFgnd->ichLim == pnodeBgnd->ichLim);
  529. pnodeBgnd->sxPid.regexPattern = pnodeFgnd->sxPid.regexPattern;
  530. }
  531. quit = true;
  532. break;
  533. }
  534. }
  535. NEXT_DLIST_ENTRY;
  536. if (!quit)
  537. {
  538. // Need to advance to the next work item.
  539. currBackgroundItem = currBackgroundItem->GetNext();
  540. }
  541. }
  542. }
  543. NEXT_DLIST_ENTRY;
  544. #if DBG
  545. for (currBackgroundItem = this->backgroundParseItems;
  546. currBackgroundItem;
  547. currBackgroundItem = currBackgroundItem->GetNext())
  548. {
  549. if (currBackgroundItem->RegExpNodeList())
  550. {
  551. FOREACH_DLIST_ENTRY(ParseNodePtr, ArenaAllocator, pnode, currBackgroundItem->RegExpNodeList())
  552. {
  553. Assert(pnode->sxPid.regexPattern != nullptr);
  554. }
  555. NEXT_DLIST_ENTRY;
  556. }
  557. }
  558. #endif
  559. }
  560. #endif
  561. LabelId* Parser::CreateLabelId(IdentToken* pToken)
  562. {
  563. LabelId* pLabelId;
  564. pLabelId = (LabelId*)m_nodeAllocator.Alloc(sizeof(LabelId));
  565. if (NULL == pLabelId)
  566. Error(ERRnoMemory);
  567. pLabelId->pid = pToken->pid;
  568. pLabelId->next = NULL;
  569. return pLabelId;
  570. }
  571. /*****************************************************************************
  572. The following set of routines allocate parse tree nodes of various kinds.
  573. They catch an exception on out of memory.
  574. *****************************************************************************/
  575. static const int g_mpnopcbNode[] =
  576. {
  577. #define PTNODE(nop,sn,pc,nk,ok,json) kcbPn##nk,
  578. #include "ptlist.h"
  579. };
  580. const Js::RegSlot NoRegister = (Js::RegSlot)-1;
  581. const Js::RegSlot OneByteRegister = (Js::RegSlot_OneByte)-1;
  582. void Parser::InitNode(OpCode nop,ParseNodePtr pnode) {
  583. pnode->nop = nop;
  584. pnode->grfpn = PNodeFlags::fpnNone;
  585. pnode->location = NoRegister;
  586. pnode->emitLabels = false;
  587. pnode->isUsed = true;
  588. pnode->notEscapedUse = false;
  589. pnode->isInList = false;
  590. pnode->isCallApplyTargetLoad = false;
  591. pnode->isSpecialName = false;
  592. }
  593. // Create nodes using Arena
  594. ParseNodePtr
  595. Parser::StaticCreateBlockNode(ArenaAllocator* alloc, charcount_t ichMin , charcount_t ichLim, int blockId, PnodeBlockType blockType)
  596. {
  597. ParseNodePtr pnode = StaticCreateNodeT<knopBlock>(alloc, ichMin, ichLim);
  598. InitBlockNode(pnode, blockId, blockType);
  599. return pnode;
  600. }
  601. void Parser::InitBlockNode(ParseNodePtr pnode, int blockId, PnodeBlockType blockType)
  602. {
  603. Assert(pnode->nop == knopBlock);
  604. pnode->sxBlock.pnodeScopes = nullptr;
  605. pnode->sxBlock.pnodeNext = nullptr;
  606. pnode->sxBlock.scope = nullptr;
  607. pnode->sxBlock.enclosingBlock = nullptr;
  608. pnode->sxBlock.pnodeLexVars = nullptr;
  609. pnode->sxBlock.pnodeStmt = nullptr;
  610. pnode->sxBlock.pnodeLastValStmt = nullptr;
  611. pnode->sxBlock.callsEval = false;
  612. pnode->sxBlock.childCallsEval = false;
  613. pnode->sxBlock.blockType = blockType;
  614. pnode->sxBlock.blockId = blockId;
  615. if (blockType != PnodeBlockType::Regular)
  616. {
  617. pnode->grfpn |= PNodeFlags::fpnSyntheticNode;
  618. }
  619. }
  620. // Create Node with limit
  621. template <OpCode nop>
  622. ParseNodePtr Parser::CreateNodeT(charcount_t ichMin,charcount_t ichLim)
  623. {
  624. Assert(!this->m_deferringAST);
  625. ParseNodePtr pnode = StaticCreateNodeT<nop>(&m_nodeAllocator, ichMin, ichLim);
  626. Assert(m_pCurrentAstSize != NULL);
  627. *m_pCurrentAstSize += GetNodeSize<nop>();
  628. return pnode;
  629. }
  630. ParseNodePtr Parser::CreateDeclNode(OpCode nop, IdentPtr pid, SymbolType symbolType, bool errorOnRedecl)
  631. {
  632. ParseNodePtr pnode = CreateNode(nop);
  633. pnode->sxVar.InitDeclNode(pid, NULL);
  634. if (symbolType != STUnknown)
  635. {
  636. pnode->sxVar.sym = AddDeclForPid(pnode, pid, symbolType, errorOnRedecl);
  637. }
  638. return pnode;
  639. }
  640. Symbol* Parser::AddDeclForPid(ParseNodePtr pnode, IdentPtr pid, SymbolType symbolType, bool errorOnRedecl)
  641. {
  642. Assert(pnode->IsVarLetOrConst());
  643. PidRefStack *refForUse = nullptr, *refForDecl = nullptr;
  644. BlockInfoStack *blockInfo;
  645. bool fBlockScope = false;
  646. if (pnode->nop != knopVarDecl || symbolType == STFunction)
  647. {
  648. Assert(m_pstmtCur);
  649. if (m_pstmtCur->GetNop() != knopBlock)
  650. {
  651. // Let/const declared in a bare statement context.
  652. Error(ERRDeclOutOfStmt);
  653. }
  654. if (m_pstmtCur->pstmtOuter && m_pstmtCur->pstmtOuter->GetNop() == knopSwitch)
  655. {
  656. // Let/const declared inside a switch block (requiring conservative use-before-decl check).
  657. pnode->sxVar.isSwitchStmtDecl = true;
  658. }
  659. fBlockScope = pnode->nop != knopVarDecl ||
  660. (
  661. !GetCurrentBlockInfo()->pnodeBlock->sxBlock.scope ||
  662. GetCurrentBlockInfo()->pnodeBlock->sxBlock.scope->GetScopeType() != ScopeType_GlobalEvalBlock
  663. );
  664. }
  665. if (fBlockScope)
  666. {
  667. blockInfo = GetCurrentBlockInfo();
  668. }
  669. else
  670. {
  671. blockInfo = GetCurrentFunctionBlockInfo();
  672. }
  673. refForDecl = this->FindOrAddPidRef(pid, blockInfo->pnodeBlock->sxBlock.blockId, GetCurrentFunctionNode()->sxFnc.functionId);
  674. if (refForDecl == nullptr)
  675. {
  676. Error(ERRnoMemory);
  677. }
  678. if (refForDecl->funcId != GetCurrentFunctionNode()->sxFnc.functionId)
  679. {
  680. // Fix up the function id, which is incorrect if we're reparsing lambda parameters
  681. Assert(this->m_reparsingLambdaParams);
  682. refForDecl->funcId = GetCurrentFunctionNode()->sxFnc.functionId;
  683. }
  684. if (blockInfo == GetCurrentBlockInfo())
  685. {
  686. refForUse = refForDecl;
  687. }
  688. else
  689. {
  690. refForUse = this->PushPidRef(pid);
  691. }
  692. pnode->sxVar.symRef = refForUse->GetSymRef();
  693. Symbol *sym = refForDecl->GetSym();
  694. if (sym != nullptr)
  695. {
  696. // Multiple declarations in the same scope. 3 possibilities: error, existing one wins, new one wins.
  697. switch (pnode->nop)
  698. {
  699. case knopLetDecl:
  700. case knopConstDecl:
  701. if (!sym->GetDecl()->sxVar.isBlockScopeFncDeclVar && !sym->IsArguments())
  702. {
  703. // If the built-in arguments is shadowed then don't throw
  704. Assert(errorOnRedecl);
  705. // Redeclaration error.
  706. Error(ERRRedeclaration);
  707. }
  708. else
  709. {
  710. // (New) let/const hides the (old) var
  711. sym->SetSymbolType(symbolType);
  712. sym->SetDecl(pnode);
  713. }
  714. break;
  715. case knopVarDecl:
  716. if (m_currentScope->GetScopeType() == ScopeType_Parameter && !sym->IsArguments())
  717. {
  718. // If this is a parameter list, mark the scope to indicate that it has duplicate definition unless it is shadowing the default arguments symbol.
  719. // 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.
  720. m_currentScope->SetHasDuplicateFormals();
  721. }
  722. if (sym->GetDecl() == nullptr)
  723. {
  724. sym->SetDecl(pnode);
  725. break;
  726. }
  727. switch (sym->GetDecl()->nop)
  728. {
  729. case knopLetDecl:
  730. case knopConstDecl:
  731. // Destructuring made possible to have the formals to be the let bind. But that shouldn't throw the error.
  732. if (errorOnRedecl && (!IsES6DestructuringEnabled() || sym->GetSymbolType() != STFormal))
  733. {
  734. Error(ERRRedeclaration);
  735. }
  736. // If !errorOnRedecl, (old) let/const hides the (new) var, so do nothing.
  737. break;
  738. case knopVarDecl:
  739. // Legal redeclaration. Who wins?
  740. if (errorOnRedecl || sym->GetDecl()->sxVar.isBlockScopeFncDeclVar || sym->IsArguments())
  741. {
  742. if (symbolType == STFormal ||
  743. (symbolType == STFunction && sym->GetSymbolType() != STFormal) ||
  744. sym->GetSymbolType() == STVariable)
  745. {
  746. // New decl wins.
  747. sym->SetSymbolType(symbolType);
  748. sym->SetDecl(pnode);
  749. }
  750. }
  751. break;
  752. }
  753. break;
  754. }
  755. }
  756. else
  757. {
  758. Scope *scope = blockInfo->pnodeBlock->sxBlock.scope;
  759. if (scope == nullptr)
  760. {
  761. Assert(blockInfo->pnodeBlock->sxBlock.blockType == PnodeBlockType::Regular);
  762. scope = Anew(&m_nodeAllocator, Scope, &m_nodeAllocator, ScopeType_Block);
  763. if (this->IsCurBlockInLoop())
  764. {
  765. scope->SetIsBlockInLoop();
  766. }
  767. blockInfo->pnodeBlock->sxBlock.scope = scope;
  768. PushScope(scope);
  769. }
  770. ParseNodePtr pnodeFnc = GetCurrentFunctionNode();
  771. if (scope->GetScopeType() == ScopeType_GlobalEvalBlock)
  772. {
  773. Assert(fBlockScope);
  774. Assert(scope->GetEnclosingScope() == m_currentNodeProg->sxProg.scope);
  775. // Check for same-named decl in Global scope.
  776. CheckRedeclarationErrorForBlockId(pid, 0);
  777. }
  778. else if (scope->GetScopeType() == ScopeType_Global && (this->m_grfscr & fscrEvalCode) &&
  779. !(m_functionBody && m_functionBody->GetScopeInfo()))
  780. {
  781. // Check for same-named decl in GlobalEvalBlock scope. Note that this is not necessary
  782. // if we're compiling a deferred nested function and the global scope was restored from cached info,
  783. // because in that case we don't need a GlobalEvalScope.
  784. Assert(!fBlockScope || (this->m_grfscr & fscrConsoleScopeEval) == fscrConsoleScopeEval);
  785. CheckRedeclarationErrorForBlockId(pid, 1);
  786. }
  787. else if (!pnodeFnc->sxFnc.IsBodyAndParamScopeMerged()
  788. && scope->GetScopeType() == ScopeType_FunctionBody
  789. && (pnode->nop == knopLetDecl || pnode->nop == knopConstDecl))
  790. {
  791. // In case of split scope function when we add a new let or const declaration to the body
  792. // we have to check whether the param scope already has the same symbol defined.
  793. CheckRedeclarationErrorForBlockId(pid, pnodeFnc->sxFnc.pnodeScopes->sxBlock.blockId);
  794. }
  795. if ((scope->GetScopeType() == ScopeType_FunctionBody || scope->GetScopeType() == ScopeType_Parameter) && symbolType != STFunction)
  796. {
  797. AnalysisAssert(pnodeFnc);
  798. if (pnodeFnc->sxFnc.pnodeName &&
  799. pnodeFnc->sxFnc.pnodeName->nop == knopVarDecl &&
  800. pnodeFnc->sxFnc.pnodeName->sxVar.pid == pid &&
  801. (pnodeFnc->sxFnc.IsBodyAndParamScopeMerged() || scope->GetScopeType() == ScopeType_Parameter))
  802. {
  803. // Named function expression has its name hidden by a local declaration.
  804. // This is important to know if we don't know whether nested deferred functions refer to it,
  805. // because if the name has a non-local reference then we have to create a scope object.
  806. m_currentNodeFunc->sxFnc.SetNameIsHidden();
  807. }
  808. }
  809. if (!sym)
  810. {
  811. const char16 *name = reinterpret_cast<const char16*>(pid->Psz());
  812. int nameLength = pid->Cch();
  813. SymbolName const symName(name, nameLength);
  814. Assert(!scope->FindLocalSymbol(symName));
  815. sym = Anew(&m_nodeAllocator, Symbol, symName, pnode, symbolType);
  816. scope->AddNewSymbol(sym);
  817. sym->SetPid(pid);
  818. }
  819. refForDecl->SetSym(sym);
  820. }
  821. return sym;
  822. }
  823. void Parser::CheckRedeclarationErrorForBlockId(IdentPtr pid, int blockId)
  824. {
  825. // If the ref stack entry for the blockId contains a sym then throw redeclaration error
  826. PidRefStack *pidRefOld = pid->GetPidRefForScopeId(blockId);
  827. if (pidRefOld && pidRefOld->GetSym() && !pidRefOld->GetSym()->IsArguments())
  828. {
  829. Error(ERRRedeclaration);
  830. }
  831. }
  832. bool Parser::IsCurBlockInLoop() const
  833. {
  834. for (StmtNest *stmt = this->m_pstmtCur; stmt != nullptr; stmt = stmt->pstmtOuter)
  835. {
  836. OpCode nop = stmt->GetNop();
  837. if (ParseNode::Grfnop(nop) & fnopContinue)
  838. {
  839. return true;
  840. }
  841. if (nop == knopFncDecl)
  842. {
  843. return false;
  844. }
  845. }
  846. return false;
  847. }
  848. void Parser::RestorePidRefForSym(Symbol *sym)
  849. {
  850. IdentPtr pid = m_pscan->m_phtbl->PidHashNameLen(sym->GetName().GetBuffer(), sym->GetName().GetLength());
  851. Assert(pid);
  852. sym->SetPid(pid);
  853. PidRefStack *ref = this->PushPidRef(pid);
  854. ref->SetSym(sym);
  855. }
  856. IdentPtr Parser::PidFromNode(ParseNodePtr pnode)
  857. {
  858. for (;;)
  859. {
  860. switch (pnode->nop)
  861. {
  862. case knopName:
  863. return pnode->sxPid.pid;
  864. case knopVarDecl:
  865. return pnode->sxVar.pid;
  866. case knopDot:
  867. Assert(pnode->sxBin.pnode2->nop == knopName);
  868. return pnode->sxBin.pnode2->sxPid.pid;
  869. case knopComma:
  870. // Advance to the RHS and iterate.
  871. pnode = pnode->sxBin.pnode2;
  872. break;
  873. default:
  874. return nullptr;
  875. }
  876. }
  877. }
  878. #if DBG
  879. void VerifyNodeSize(OpCode nop, int size)
  880. {
  881. Assert(nop >= 0 && nop < knopLim);
  882. __analysis_assume(nop < knopLim);
  883. Assert(g_mpnopcbNode[nop] == size);
  884. }
  885. #endif
  886. ParseNodePtr Parser::StaticCreateSuperReferenceNode(OpCode nop,
  887. ParseNodePtr pnode1,
  888. ParseNodePtr pnode2,
  889. ArenaAllocator* alloc)
  890. {
  891. return StaticCreateBinNode(nop, pnode1, pnode2, alloc, kcbPnSuperReference, knopSuperReference);
  892. }
  893. ParseNodePtr Parser::StaticCreateBinNode(OpCode nop,
  894. ParseNodePtr pnode1,
  895. ParseNodePtr pnode2,
  896. ArenaAllocator* alloc)
  897. {
  898. return StaticCreateBinNode(nop, pnode1, pnode2, alloc, kcbPnBin, nop);
  899. }
  900. ParseNodePtr Parser::StaticCreateBinNode(OpCode nop,
  901. ParseNodePtr pnode1,
  902. ParseNodePtr pnode2,
  903. ArenaAllocator* alloc,
  904. int allocSize,
  905. OpCode nopForSize)
  906. {
  907. DebugOnly(VerifyNodeSize(nopForSize, allocSize));
  908. ParseNodePtr pnode = (ParseNodePtr)alloc->Alloc(allocSize);
  909. InitNode(nop, pnode);
  910. pnode->sxBin.pnodeNext = nullptr;
  911. pnode->sxBin.pnode1 = pnode1;
  912. pnode->sxBin.pnode2 = pnode2;
  913. // Statically detect if the add is a concat
  914. if (!PHASE_OFF1(Js::ByteCodeConcatExprOptPhase))
  915. {
  916. // We can't flatten the concat expression if the LHS is not a flatten concat already
  917. // e.g. a + (<str> + b)
  918. // Side effect of ToStr(b) need to happen first before ToStr(a)
  919. // If we flatten the concat expression, we will do ToStr(a) before ToStr(b)
  920. if ((nop == knopAdd) && (pnode1->CanFlattenConcatExpr() || pnode2->nop == knopStr))
  921. {
  922. pnode->grfpn |= fpnCanFlattenConcatExpr;
  923. }
  924. }
  925. return pnode;
  926. }
  927. // Create nodes using parser allocator
  928. ParseNodePtr Parser::CreateNode(OpCode nop, charcount_t ichMin)
  929. {
  930. bool nodeAllowed = IsNodeAllowedInCurrentDeferralState(nop);
  931. Assert(nodeAllowed);
  932. Assert(nop >= 0 && nop < knopLim);
  933. ParseNodePtr pnode;
  934. int cb = (nop >= knopNone && nop < knopLim) ? g_mpnopcbNode[nop] : g_mpnopcbNode[knopEmpty];
  935. pnode = (ParseNodePtr)m_nodeAllocator.Alloc(cb);
  936. Assert(pnode != nullptr);
  937. if (!m_deferringAST)
  938. {
  939. Assert(m_pCurrentAstSize != nullptr);
  940. *m_pCurrentAstSize += cb;
  941. }
  942. InitNode(nop,pnode);
  943. // default - may be changed
  944. pnode->ichMin = ichMin;
  945. if (m_pscan!= nullptr) {
  946. pnode->ichLim = m_pscan->IchLimTok();
  947. }
  948. else pnode->ichLim=0;
  949. return pnode;
  950. }
  951. ParseNodePtr Parser::CreateUniNode(OpCode nop, ParseNodePtr pnode1)
  952. {
  953. Assert(!this->m_deferringAST);
  954. DebugOnly(VerifyNodeSize(nop, kcbPnUni));
  955. ParseNodePtr pnode = (ParseNodePtr)m_nodeAllocator.Alloc(kcbPnUni);
  956. Assert(m_pCurrentAstSize != nullptr);
  957. *m_pCurrentAstSize += kcbPnUni;
  958. InitNode(nop, pnode);
  959. pnode->sxUni.pnode1 = pnode1;
  960. if (nullptr == pnode1)
  961. {
  962. // no ops
  963. pnode->ichMin = m_pscan->IchMinTok();
  964. pnode->ichLim = m_pscan->IchLimTok();
  965. }
  966. else
  967. {
  968. // 1 op
  969. pnode->ichMin = pnode1->ichMin;
  970. pnode->ichLim = pnode1->ichLim;
  971. this->CheckArguments(pnode);
  972. }
  973. return pnode;
  974. }
  975. ParseNodePtr Parser::CreateBinNode(OpCode nop, ParseNodePtr pnode1, ParseNodePtr pnode2)
  976. {
  977. Assert(!this->m_deferringAST);
  978. charcount_t ichMin;
  979. charcount_t ichLim;
  980. if (nullptr == pnode1)
  981. {
  982. // no ops
  983. Assert(nullptr == pnode2);
  984. ichMin = m_pscan->IchMinTok();
  985. ichLim = m_pscan->IchLimTok();
  986. }
  987. else
  988. {
  989. if (nullptr == pnode2)
  990. {
  991. // 1 op
  992. ichMin = pnode1->ichMin;
  993. ichLim = pnode1->ichLim;
  994. }
  995. else
  996. {
  997. // 2 ops
  998. ichMin = pnode1->ichMin;
  999. ichLim = pnode2->ichLim;
  1000. if (nop != knopDot && nop != knopIndex)
  1001. {
  1002. this->CheckArguments(pnode2);
  1003. }
  1004. }
  1005. if (nop != knopDot && nop != knopIndex)
  1006. {
  1007. this->CheckArguments(pnode1);
  1008. }
  1009. }
  1010. return CreateBinNode(nop, pnode1, pnode2, ichMin, ichLim);
  1011. }
  1012. ParseNodePtr Parser::CreateSuperReferenceNode(OpCode nop, ParseNodePtr pnode1, ParseNodePtr pnode2)
  1013. {
  1014. Assert(!this->m_deferringAST);
  1015. Assert(pnode1 && pnode1->isSpecialName && pnode1->sxSpecialName.isSuper);
  1016. Assert(pnode2 != nullptr);
  1017. Assert(nop == knopDot || nop == knopIndex);
  1018. ParseNodePtr pnode = StaticCreateSuperReferenceNode(nop, pnode1, pnode2, &m_nodeAllocator);
  1019. Assert(m_pCurrentAstSize != NULL);
  1020. *m_pCurrentAstSize += kcbPnSuperReference;
  1021. pnode->ichMin = pnode1->ichMin;
  1022. pnode->ichLim = pnode2->ichLim;
  1023. pnode->sxSuperReference.pnodeThis = nullptr;
  1024. return pnode;
  1025. }
  1026. ParseNodePtr Parser::CreateTriNode(OpCode nop, ParseNodePtr pnode1,
  1027. ParseNodePtr pnode2, ParseNodePtr pnode3)
  1028. {
  1029. charcount_t ichMin;
  1030. charcount_t ichLim;
  1031. if (nullptr == pnode1)
  1032. {
  1033. // no ops
  1034. Assert(nullptr == pnode2);
  1035. Assert(nullptr == pnode3);
  1036. ichMin = m_pscan->IchMinTok();
  1037. ichLim = m_pscan->IchLimTok();
  1038. }
  1039. else if (nullptr == pnode2)
  1040. {
  1041. // 1 op
  1042. Assert(nullptr == pnode3);
  1043. ichMin = pnode1->ichMin;
  1044. ichLim = pnode1->ichLim;
  1045. }
  1046. else if (nullptr == pnode3)
  1047. {
  1048. // 2 op
  1049. ichMin = pnode1->ichMin;
  1050. ichLim = pnode2->ichLim;
  1051. }
  1052. else
  1053. {
  1054. // 3 ops
  1055. ichMin = pnode1->ichMin;
  1056. ichLim = pnode3->ichLim;
  1057. }
  1058. return CreateTriNode(nop, pnode1, pnode2, pnode3, ichMin, ichLim);
  1059. }
  1060. ParseNodePtr Parser::CreateBlockNode(charcount_t ichMin,charcount_t ichLim, PnodeBlockType blockType)
  1061. {
  1062. return StaticCreateBlockNode(&m_nodeAllocator, ichMin, ichLim, this->m_nextBlockId++, blockType);
  1063. }
  1064. ParseNodePtr
  1065. Parser::CreateCallNode(OpCode nop, ParseNodePtr pnode1, ParseNodePtr pnode2,charcount_t ichMin,charcount_t ichLim)
  1066. {
  1067. Assert(!this->m_deferringAST);
  1068. DebugOnly(VerifyNodeSize(nop, kcbPnCall));
  1069. ParseNodePtr pnode = (ParseNodePtr)m_nodeAllocator.Alloc(kcbPnCall);
  1070. Assert(m_pCurrentAstSize != nullptr);
  1071. *m_pCurrentAstSize += kcbPnCall;
  1072. InitNode(nop, pnode);
  1073. pnode->sxCall.pnodeTarget = pnode1;
  1074. pnode->sxCall.pnodeArgs = pnode2;
  1075. pnode->sxCall.argCount = 0;
  1076. pnode->sxCall.spreadArgCount = 0;
  1077. pnode->sxCall.callOfConstants = false;
  1078. pnode->sxCall.isApplyCall = false;
  1079. pnode->sxCall.isEvalCall = false;
  1080. pnode->sxCall.isSuperCall = false;
  1081. pnode->sxCall.hasDestructuring = false;
  1082. pnode->ichMin = ichMin;
  1083. pnode->ichLim = ichLim;
  1084. return pnode;
  1085. }
  1086. ParseNodePtr Parser::CreateStrNode(IdentPtr pid)
  1087. {
  1088. Assert(!this->m_deferringAST);
  1089. ParseNodePtr pnode = CreateNode(knopStr);
  1090. pnode->sxPid.pid=pid;
  1091. pnode->grfpn |= PNodeFlags::fpnCanFlattenConcatExpr;
  1092. return pnode;
  1093. }
  1094. ParseNodePtr Parser::CreateIntNode(int32 lw)
  1095. {
  1096. ParseNodePtr pnode = CreateNode(knopInt);
  1097. pnode->sxInt.lw = lw;
  1098. return pnode;
  1099. }
  1100. // Create Node with scanner limit
  1101. template <OpCode nop>
  1102. ParseNodePtr Parser::CreateNodeWithScanner()
  1103. {
  1104. Assert(m_pscan != nullptr);
  1105. return CreateNodeWithScanner<nop>(m_pscan->IchMinTok());
  1106. }
  1107. template <OpCode nop>
  1108. ParseNodePtr Parser::CreateNodeWithScanner(charcount_t ichMin)
  1109. {
  1110. Assert(m_pscan != nullptr);
  1111. return CreateNodeT<nop>(ichMin, m_pscan->IchLimTok());
  1112. }
  1113. ParseNodePtr Parser::CreateProgNodeWithScanner(bool isModuleSource)
  1114. {
  1115. ParseNodePtr pnodeProg;
  1116. if (isModuleSource)
  1117. {
  1118. pnodeProg = CreateNodeWithScanner<knopModule>();
  1119. // knopModule is not actually handled anywhere since we would need to handle it everywhere we could
  1120. // have knopProg and it would be treated exactly the same except for import/export statements.
  1121. // We are only using it as a way to get the correct size for PnModule.
  1122. // Consider: Should we add a flag to PnProg which is false but set to true in PnModule?
  1123. // If we do, it can't be a virtual method since the parse nodes are all in a union.
  1124. pnodeProg->nop = knopProg;
  1125. }
  1126. else
  1127. {
  1128. pnodeProg = CreateNodeWithScanner<knopProg>();
  1129. }
  1130. return pnodeProg;
  1131. }
  1132. ParseNodePtr Parser::CreateCallNode(OpCode nop, ParseNodePtr pnode1, ParseNodePtr pnode2)
  1133. {
  1134. charcount_t ichMin;
  1135. charcount_t ichLim;
  1136. if (nullptr == pnode1)
  1137. {
  1138. Assert(nullptr == pnode2);
  1139. ichMin = m_pscan->IchMinTok();
  1140. ichLim = m_pscan->IchLimTok();
  1141. }
  1142. else
  1143. {
  1144. if (nullptr == pnode2)
  1145. {
  1146. ichMin = pnode1->ichMin;
  1147. ichLim = pnode1->ichLim;
  1148. }
  1149. else
  1150. {
  1151. ichMin = pnode1->ichMin;
  1152. ichLim = pnode2->ichLim;
  1153. }
  1154. if (pnode1->nop == knopDot || pnode1->nop == knopIndex)
  1155. {
  1156. this->CheckArguments(pnode1->sxBin.pnode1);
  1157. }
  1158. }
  1159. return CreateCallNode(nop, pnode1, pnode2, ichMin, ichLim);
  1160. }
  1161. ParseNodePtr Parser::CreateSuperCallNode(ParseNodePtr pnode1, ParseNodePtr pnode2)
  1162. {
  1163. Assert(!this->m_deferringAST);
  1164. Assert(pnode1 && pnode1->isSpecialName && pnode1->sxSpecialName.isSuper);
  1165. DebugOnly(VerifyNodeSize(knopSuperCall, kcbPnSuperCall));
  1166. ParseNodePtr pnode = (ParseNodePtr)m_nodeAllocator.Alloc(kcbPnSuperCall);
  1167. Assert(m_pCurrentAstSize != nullptr);
  1168. *m_pCurrentAstSize += kcbPnSuperCall;
  1169. InitNode(knopCall, pnode);
  1170. pnode->sxCall.pnodeTarget = pnode1;
  1171. pnode->sxCall.pnodeArgs = pnode2;
  1172. pnode->sxCall.argCount = 0;
  1173. pnode->sxCall.spreadArgCount = 0;
  1174. pnode->sxCall.callOfConstants = false;
  1175. pnode->sxCall.isApplyCall = false;
  1176. pnode->sxCall.isEvalCall = false;
  1177. pnode->sxCall.isSuperCall = true;
  1178. pnode->sxSuperCall.pnodeThis = nullptr;
  1179. pnode->sxSuperCall.pnodeNewTarget = nullptr;
  1180. pnode->ichMin = pnode1->ichMin;
  1181. pnode->ichLim = pnode2 == nullptr ? pnode1->ichLim : pnode2->ichLim;
  1182. return pnode;
  1183. }
  1184. ParseNodePtr Parser::CreateStrNodeWithScanner(IdentPtr pid)
  1185. {
  1186. Assert(!this->m_deferringAST);
  1187. ParseNodePtr pnode = CreateNodeWithScanner<knopStr>();
  1188. pnode->sxPid.pid=pid;
  1189. pnode->grfpn |= PNodeFlags::fpnCanFlattenConcatExpr;
  1190. return pnode;
  1191. }
  1192. ParseNodePtr Parser::CreateIntNodeWithScanner(int32 lw)
  1193. {
  1194. Assert(!this->m_deferringAST);
  1195. ParseNodePtr pnode = CreateNodeWithScanner<knopInt>();
  1196. pnode->sxInt.lw = lw;
  1197. return pnode;
  1198. }
  1199. ParseNodePtr Parser::CreateTempNode(ParseNode* initExpr)
  1200. {
  1201. ParseNodePtr pnode = CreateNode(knopTemp, (charcount_t)0);
  1202. pnode->sxVar.pnodeInit =initExpr;
  1203. pnode->sxVar.pnodeNext = nullptr;
  1204. return pnode;
  1205. }
  1206. ParseNodePtr Parser::CreateTempRef(ParseNode* tempNode)
  1207. {
  1208. ParseNodePtr pnode = CreateUniNode(knopTempRef, tempNode);
  1209. return pnode;
  1210. }
  1211. void Parser::CheckPidIsValid(IdentPtr pid, bool autoArgumentsObject)
  1212. {
  1213. if (IsStrictMode())
  1214. {
  1215. // in strict mode, variable named 'eval' cannot be created
  1216. if (pid == wellKnownPropertyPids.eval)
  1217. {
  1218. Error(ERREvalUsage);
  1219. }
  1220. else if (pid == wellKnownPropertyPids.arguments && !autoArgumentsObject)
  1221. {
  1222. Error(ERRArgsUsage);
  1223. }
  1224. }
  1225. }
  1226. // CreateVarDecl needs m_ppnodeVar to be pointing to the right function.
  1227. // Post-parsing rewriting during bytecode gen may have m_ppnodeVar pointing to the last parsed function.
  1228. // This function sets up m_ppnodeVar to point to the given pnodeFnc and creates the new var declaration.
  1229. // This prevents accidentally adding var declarations to the last parsed function.
  1230. ParseNodePtr Parser::AddVarDeclNode(IdentPtr pid, ParseNodePtr pnodeFnc)
  1231. {
  1232. AnalysisAssert(pnodeFnc);
  1233. ParseNodePtr *const ppnodeVarSave = m_ppnodeVar;
  1234. m_ppnodeVar = &pnodeFnc->sxFnc.pnodeVars;
  1235. while (*m_ppnodeVar != nullptr)
  1236. {
  1237. m_ppnodeVar = &(*m_ppnodeVar)->sxVar.pnodeNext;
  1238. }
  1239. ParseNodePtr pnode = CreateVarDeclNode(pid, STUnknown, false, 0, /* checkReDecl = */ false);
  1240. m_ppnodeVar = ppnodeVarSave;
  1241. return pnode;
  1242. }
  1243. ParseNodePtr Parser::CreateModuleImportDeclNode(IdentPtr localName)
  1244. {
  1245. ParseNodePtr declNode = CreateBlockScopedDeclNode(localName, knopConstDecl);
  1246. Symbol* sym = declNode->sxVar.sym;
  1247. sym->SetIsModuleExportStorage(true);
  1248. sym->SetIsModuleImport(true);
  1249. return declNode;
  1250. }
  1251. ParseNodePtr Parser::CreateVarDeclNode(IdentPtr pid, SymbolType symbolType, bool autoArgumentsObject, ParseNodePtr pnodeFnc, bool errorOnRedecl)
  1252. {
  1253. ParseNodePtr pnode = CreateDeclNode(knopVarDecl, pid, symbolType, errorOnRedecl);
  1254. // Append the variable to the end of the current variable list.
  1255. AssertMem(m_ppnodeVar);
  1256. pnode->sxVar.pnodeNext = *m_ppnodeVar;
  1257. *m_ppnodeVar = pnode;
  1258. if (nullptr != pid)
  1259. {
  1260. // this is not a temp - make sure temps go after this node
  1261. AssertMem(pid);
  1262. m_ppnodeVar = &pnode->sxVar.pnodeNext;
  1263. CheckPidIsValid(pid, autoArgumentsObject);
  1264. }
  1265. return pnode;
  1266. }
  1267. ParseNodePtr Parser::CreateBlockScopedDeclNode(IdentPtr pid, OpCode nodeType)
  1268. {
  1269. Assert(nodeType == knopConstDecl || nodeType == knopLetDecl);
  1270. ParseNodePtr pnode = CreateDeclNode(nodeType, pid, STVariable, true);
  1271. if (nullptr != pid)
  1272. {
  1273. AssertMem(pid);
  1274. AddVarDeclToBlock(pnode);
  1275. CheckPidIsValid(pid);
  1276. }
  1277. return pnode;
  1278. }
  1279. void Parser::AddVarDeclToBlock(ParseNode *pnode)
  1280. {
  1281. Assert(pnode->nop == knopConstDecl || pnode->nop == knopLetDecl);
  1282. // Maintain a combined list of let and const declarations to keep
  1283. // track of declaration order.
  1284. AssertMem(m_currentBlockInfo->m_ppnodeLex);
  1285. *m_currentBlockInfo->m_ppnodeLex = pnode;
  1286. m_currentBlockInfo->m_ppnodeLex = &pnode->sxVar.pnodeNext;
  1287. pnode->sxVar.pnodeNext = nullptr;
  1288. }
  1289. void Parser::SetCurrentStatement(StmtNest *stmt)
  1290. {
  1291. m_pstmtCur = stmt;
  1292. }
  1293. template<bool buildAST>
  1294. ParseNodePtr Parser::StartParseBlockWithCapacity(PnodeBlockType blockType, ScopeType scopeType, int capacity)
  1295. {
  1296. Scope *scope = nullptr;
  1297. // Block scopes are not created lazily in the case where we're repopulating a persisted scope.
  1298. scope = Anew(&m_nodeAllocator, Scope, &m_nodeAllocator, scopeType, capacity);
  1299. PushScope(scope);
  1300. return StartParseBlockHelper<buildAST>(blockType, scope, nullptr, nullptr);
  1301. }
  1302. template<bool buildAST>
  1303. ParseNodePtr Parser::StartParseBlock(PnodeBlockType blockType, ScopeType scopeType, ParseNodePtr pnodeLabel, LabelId* pLabelId)
  1304. {
  1305. Scope *scope = nullptr;
  1306. // Block scopes are created lazily when we discover block-scoped content.
  1307. if (scopeType != ScopeType_Unknown && scopeType != ScopeType_Block)
  1308. {
  1309. scope = Anew(&m_nodeAllocator, Scope, &m_nodeAllocator, scopeType);
  1310. PushScope(scope);
  1311. }
  1312. return StartParseBlockHelper<buildAST>(blockType, scope, pnodeLabel, pLabelId);
  1313. }
  1314. template<bool buildAST>
  1315. ParseNodePtr Parser::StartParseBlockHelper(PnodeBlockType blockType, Scope *scope, ParseNodePtr pnodeLabel, LabelId* pLabelId)
  1316. {
  1317. ParseNodePtr pnodeBlock = CreateBlockNode(blockType);
  1318. pnodeBlock->sxBlock.scope = scope;
  1319. BlockInfoStack *newBlockInfo = PushBlockInfo(pnodeBlock);
  1320. PushStmt<buildAST>(&newBlockInfo->pstmt, pnodeBlock, knopBlock, pnodeLabel, pLabelId);
  1321. return pnodeBlock;
  1322. }
  1323. void Parser::PushScope(Scope *scope)
  1324. {
  1325. Assert(scope);
  1326. scope->SetEnclosingScope(m_currentScope);
  1327. m_currentScope = scope;
  1328. }
  1329. void Parser::PopScope(Scope *scope)
  1330. {
  1331. Assert(scope == m_currentScope);
  1332. m_currentScope = scope->GetEnclosingScope();
  1333. scope->SetEnclosingScope(nullptr);
  1334. }
  1335. void Parser::PushFuncBlockScope(ParseNodePtr pnodeBlock, ParseNodePtr **ppnodeScopeSave, ParseNodePtr **ppnodeExprScopeSave)
  1336. {
  1337. // Maintain the scope tree.
  1338. pnodeBlock->sxBlock.pnodeScopes = nullptr;
  1339. pnodeBlock->sxBlock.pnodeNext = nullptr;
  1340. // Insert this block into the active list of scopes (m_ppnodeExprScope or m_ppnodeScope).
  1341. // Save the current block's "next" pointer as the new endpoint of that list.
  1342. if (m_ppnodeExprScope)
  1343. {
  1344. *ppnodeScopeSave = m_ppnodeScope;
  1345. Assert(*m_ppnodeExprScope == nullptr);
  1346. *m_ppnodeExprScope = pnodeBlock;
  1347. *ppnodeExprScopeSave = &pnodeBlock->sxBlock.pnodeNext;
  1348. }
  1349. else
  1350. {
  1351. Assert(m_ppnodeScope);
  1352. Assert(*m_ppnodeScope == nullptr);
  1353. *m_ppnodeScope = pnodeBlock;
  1354. *ppnodeScopeSave = &pnodeBlock->sxBlock.pnodeNext;
  1355. *ppnodeExprScopeSave = m_ppnodeExprScope;
  1356. }
  1357. // Advance the global scope list pointer to the new block's child list.
  1358. m_ppnodeScope = &pnodeBlock->sxBlock.pnodeScopes;
  1359. // Set m_ppnodeExprScope to NULL to make that list inactive.
  1360. m_ppnodeExprScope = nullptr;
  1361. }
  1362. void Parser::PopFuncBlockScope(ParseNodePtr *ppnodeScopeSave, ParseNodePtr *ppnodeExprScopeSave)
  1363. {
  1364. Assert(m_ppnodeExprScope == nullptr || *m_ppnodeExprScope == nullptr);
  1365. m_ppnodeExprScope = ppnodeExprScopeSave;
  1366. AssertMem(m_ppnodeScope);
  1367. Assert(nullptr == *m_ppnodeScope);
  1368. m_ppnodeScope = ppnodeScopeSave;
  1369. }
  1370. template<bool buildAST>
  1371. ParseNodePtr Parser::ParseBlock(ParseNodePtr pnodeLabel, LabelId* pLabelId)
  1372. {
  1373. ParseNodePtr pnodeBlock = nullptr;
  1374. ParseNodePtr *ppnodeScopeSave = nullptr;
  1375. ParseNodePtr *ppnodeExprScopeSave = nullptr;
  1376. pnodeBlock = StartParseBlock<buildAST>(PnodeBlockType::Regular, ScopeType_Block, pnodeLabel, pLabelId);
  1377. BlockInfoStack* outerBlockInfo = m_currentBlockInfo->pBlockInfoOuter;
  1378. if (outerBlockInfo != nullptr && outerBlockInfo->pnodeBlock != nullptr
  1379. && outerBlockInfo->pnodeBlock->sxBlock.scope != nullptr
  1380. && outerBlockInfo->pnodeBlock->sxBlock.scope->GetScopeType() == ScopeType_CatchParamPattern)
  1381. {
  1382. // If we are parsing the catch block then destructured params can have let declrations. Let's add them to the new block.
  1383. for (ParseNodePtr pnode = m_currentBlockInfo->pBlockInfoOuter->pnodeBlock->sxBlock.pnodeLexVars; pnode; pnode = pnode->sxVar.pnodeNext)
  1384. {
  1385. PidRefStack* ref = PushPidRef(pnode->sxVar.sym->GetPid());
  1386. ref->SetSym(pnode->sxVar.sym);
  1387. }
  1388. }
  1389. ChkCurTok(tkLCurly, ERRnoLcurly);
  1390. ParseNodePtr * ppnodeList = nullptr;
  1391. if (buildAST)
  1392. {
  1393. PushFuncBlockScope(pnodeBlock, &ppnodeScopeSave, &ppnodeExprScopeSave);
  1394. ppnodeList = &pnodeBlock->sxBlock.pnodeStmt;
  1395. }
  1396. ParseStmtList<buildAST>(ppnodeList);
  1397. if (buildAST)
  1398. {
  1399. PopFuncBlockScope(ppnodeScopeSave, ppnodeExprScopeSave);
  1400. }
  1401. FinishParseBlock(pnodeBlock);
  1402. ChkCurTok(tkRCurly, ERRnoRcurly);
  1403. return pnodeBlock;
  1404. }
  1405. ParseNodePtr Parser::ReferenceSpecialName(IdentPtr pid, charcount_t ichMin, charcount_t ichLim, bool createNode)
  1406. {
  1407. PidRefStack* ref = this->PushPidRef(pid);
  1408. if (!createNode)
  1409. {
  1410. return nullptr;
  1411. }
  1412. ParseNode* pnode = CreateSpecialNameNode(pid);
  1413. pnode->ichMin = ichMin;
  1414. pnode->ichLim = ichLim;
  1415. pnode->sxPid.SetSymRef(ref);
  1416. if (pid == wellKnownPropertyPids._this)
  1417. {
  1418. pnode->sxSpecialName.isThis = true;
  1419. }
  1420. else if (pid == wellKnownPropertyPids._super || pid == wellKnownPropertyPids._superConstructor)
  1421. {
  1422. pnode->sxSpecialName.isSuper = true;
  1423. }
  1424. return pnode;
  1425. }
  1426. ParseNodePtr Parser::CreateSpecialVarDeclIfNeeded(ParseNodePtr pnodeFnc, IdentPtr pid, bool forceCreate)
  1427. {
  1428. Assert(pid != nullptr);
  1429. PidRefStack* ref = pid->GetTopRef();
  1430. // If the function has a reference to pid or we set forceCreate, make a special var decl
  1431. if (forceCreate || (ref && ref->GetScopeId() >= m_currentBlockInfo->pnodeBlock->sxBlock.blockId))
  1432. {
  1433. return this->CreateSpecialVarDeclNode(pnodeFnc, pid);
  1434. }
  1435. return nullptr;
  1436. }
  1437. void Parser::CreateSpecialSymbolDeclarations(ParseNodePtr pnodeFnc, bool isGlobal)
  1438. {
  1439. // Lambda function cannot have any special bindings.
  1440. if (pnodeFnc->sxFnc.IsLambda())
  1441. {
  1442. return;
  1443. }
  1444. Assert(!(isGlobal && (this->m_grfscr & fscrEval)));
  1445. Assert(!isGlobal || (this->m_grfscr & fscrEvalCode));
  1446. bool isTopLevelEventHandler = (this->m_grfscr & fscrImplicitThis || this->m_grfscr & fscrImplicitParents) && !pnodeFnc->sxFnc.IsNested();
  1447. // Create a 'this' symbol for indirect eval, non-lambda functions with references to 'this', and all class constructors and top level event hanlders.
  1448. ParseNodePtr varDeclNode = CreateSpecialVarDeclIfNeeded(pnodeFnc, wellKnownPropertyPids._this, pnodeFnc->sxFnc.IsClassConstructor() || isTopLevelEventHandler);
  1449. if (varDeclNode)
  1450. {
  1451. varDeclNode->sxPid.sym->SetIsThis(true);
  1452. if (pnodeFnc->sxFnc.IsDerivedClassConstructor())
  1453. {
  1454. varDeclNode->sxPid.sym->SetNeedDeclaration(true);
  1455. }
  1456. }
  1457. // Global code cannot have 'new.target' or 'super' bindings.
  1458. if (isGlobal)
  1459. {
  1460. return;
  1461. }
  1462. // Create a 'new.target' symbol for any ordinary function with a reference and all class constructors.
  1463. varDeclNode = CreateSpecialVarDeclIfNeeded(pnodeFnc, wellKnownPropertyPids._newTarget, pnodeFnc->sxFnc.IsClassConstructor());
  1464. if (varDeclNode)
  1465. {
  1466. varDeclNode->sxPid.sym->SetIsNewTarget(true);
  1467. }
  1468. // Create a 'super' (as a reference) symbol.
  1469. varDeclNode = CreateSpecialVarDeclIfNeeded(pnodeFnc, wellKnownPropertyPids._super);
  1470. if (varDeclNode)
  1471. {
  1472. varDeclNode->sxPid.sym->SetIsSuper(true);
  1473. }
  1474. // Create a 'super' (as the call target for super()) symbol only for derived class constructors.
  1475. if (pnodeFnc->sxFnc.IsDerivedClassConstructor())
  1476. {
  1477. varDeclNode = CreateSpecialVarDeclIfNeeded(pnodeFnc, wellKnownPropertyPids._superConstructor);
  1478. if (varDeclNode)
  1479. {
  1480. varDeclNode->sxPid.sym->SetIsSuperConstructor(true);
  1481. }
  1482. }
  1483. }
  1484. void Parser::FinishParseBlock(ParseNode *pnodeBlock, bool needScanRCurly)
  1485. {
  1486. Assert(m_currentBlockInfo != nullptr && pnodeBlock == m_currentBlockInfo->pnodeBlock);
  1487. if (needScanRCurly)
  1488. {
  1489. // Only update the ichLim if we were expecting an RCurly. If there is an
  1490. // expression body without a necessary RCurly, the correct ichLim will
  1491. // have been set already.
  1492. pnodeBlock->ichLim = m_pscan->IchLimTok();
  1493. }
  1494. BindPidRefs<false>(GetCurrentBlockInfo(), m_nextBlockId - 1);
  1495. PopStmt(&m_currentBlockInfo->pstmt);
  1496. PopBlockInfo();
  1497. Scope *scope = pnodeBlock->sxBlock.scope;
  1498. if (scope)
  1499. {
  1500. PopScope(scope);
  1501. }
  1502. }
  1503. void Parser::FinishParseFncExprScope(ParseNodePtr pnodeFnc, ParseNodePtr pnodeFncExprScope)
  1504. {
  1505. int fncExprScopeId = pnodeFncExprScope->sxBlock.blockId;
  1506. ParseNodePtr pnodeName = pnodeFnc->sxFnc.pnodeName;
  1507. if (pnodeName)
  1508. {
  1509. Assert(pnodeName->nop == knopVarDecl);
  1510. BindPidRefsInScope(pnodeName->sxVar.pid, pnodeName->sxVar.sym, fncExprScopeId, m_nextBlockId - 1);
  1511. }
  1512. FinishParseBlock(pnodeFncExprScope);
  1513. }
  1514. template <const bool backgroundPidRef>
  1515. void Parser::BindPidRefs(BlockInfoStack *blockInfo, uint maxBlockId)
  1516. {
  1517. // We need to bind all assignments in order to emit assignment to 'const' error
  1518. int blockId = blockInfo->pnodeBlock->sxBlock.blockId;
  1519. Scope *scope = blockInfo->pnodeBlock->sxBlock.scope;
  1520. if (scope)
  1521. {
  1522. auto bindPidRefs = [blockId, maxBlockId, this](Symbol *sym)
  1523. {
  1524. ParseNodePtr pnode = sym->GetDecl();
  1525. IdentPtr pid;
  1526. #if PROFILE_DICTIONARY
  1527. int depth = 0;
  1528. #endif
  1529. Assert(pnode);
  1530. switch (pnode->nop)
  1531. {
  1532. case knopVarDecl:
  1533. case knopLetDecl:
  1534. case knopConstDecl:
  1535. pid = pnode->sxVar.pid;
  1536. if (backgroundPidRef)
  1537. {
  1538. pid = this->m_pscan->m_phtbl->FindExistingPid(pid->Psz(), pid->Psz() + pid->Cch(), pid->Cch(), pid->Hash(), nullptr, nullptr
  1539. #if PROFILE_DICTIONARY
  1540. , depth
  1541. #endif
  1542. );
  1543. if (pid == nullptr)
  1544. {
  1545. break;
  1546. }
  1547. }
  1548. this->BindPidRefsInScope(pid, sym, blockId, maxBlockId);
  1549. break;
  1550. case knopName:
  1551. pid = pnode->sxPid.pid;
  1552. if (backgroundPidRef)
  1553. {
  1554. pid = this->m_pscan->m_phtbl->FindExistingPid(pid->Psz(), pid->Psz() + pid->Cch(), pid->Cch(), pid->Hash(), nullptr, nullptr
  1555. #if PROFILE_DICTIONARY
  1556. , depth
  1557. #endif
  1558. );
  1559. if (pid == nullptr)
  1560. {
  1561. break;
  1562. }
  1563. }
  1564. this->BindPidRefsInScope(pid, sym, blockId, maxBlockId);
  1565. break;
  1566. default:
  1567. Assert(0);
  1568. break;
  1569. }
  1570. };
  1571. scope->ForEachSymbol(bindPidRefs);
  1572. }
  1573. }
  1574. void Parser::BindPidRefsInScope(IdentPtr pid, Symbol *sym, int blockId, uint maxBlockId)
  1575. {
  1576. PidRefStack *ref, *nextRef, *lastRef = nullptr;
  1577. Js::LocalFunctionId funcId = GetCurrentFunctionNode()->sxFnc.functionId;
  1578. Assert(sym);
  1579. if (pid->GetIsModuleExport())
  1580. {
  1581. sym->SetIsModuleExportStorage(true);
  1582. }
  1583. bool hasFuncAssignment = sym->GetHasFuncAssignment();
  1584. bool doesEscape = false;
  1585. for (ref = pid->GetTopRef(); ref && ref->GetScopeId() >= blockId; ref = nextRef)
  1586. {
  1587. // Fix up sym* on PID ref.
  1588. Assert(!ref->GetSym() || ref->GetSym() == sym);
  1589. nextRef = ref->prev;
  1590. Assert(ref->GetScopeId() >= 0);
  1591. if ((uint)ref->GetScopeId() > maxBlockId)
  1592. {
  1593. lastRef = ref;
  1594. continue;
  1595. }
  1596. ref->SetSym(sym);
  1597. this->RemovePrevPidRef(pid, lastRef);
  1598. if (ref->IsUsedInLdElem())
  1599. {
  1600. sym->SetIsUsedInLdElem(true);
  1601. }
  1602. if (ref->IsAssignment())
  1603. {
  1604. sym->PromoteAssignmentState();
  1605. if (sym->GetIsFormal())
  1606. {
  1607. GetCurrentFunctionNode()->sxFnc.SetHasAnyWriteToFormals(true);
  1608. }
  1609. }
  1610. if (ref->GetFuncScopeId() != funcId && !sym->GetIsGlobal() && !sym->GetIsModuleExportStorage())
  1611. {
  1612. Assert(ref->GetFuncScopeId() > funcId);
  1613. sym->SetHasNonLocalReference();
  1614. if (ref->IsDynamicBinding())
  1615. {
  1616. sym->SetNeedsScopeObject();
  1617. }
  1618. }
  1619. if (ref->IsFuncAssignment())
  1620. {
  1621. hasFuncAssignment = true;
  1622. }
  1623. if (ref->IsEscape())
  1624. {
  1625. doesEscape = true;
  1626. }
  1627. if (m_currentNodeFunc && doesEscape && hasFuncAssignment)
  1628. {
  1629. if (m_sourceContextInfo ?
  1630. !PHASE_OFF_RAW(Js::DisableStackFuncOnDeferredEscapePhase, m_sourceContextInfo->sourceContextId, m_currentNodeFunc->sxFnc.functionId) :
  1631. !PHASE_OFF1(Js::DisableStackFuncOnDeferredEscapePhase))
  1632. {
  1633. m_currentNodeFunc->sxFnc.SetNestedFuncEscapes();
  1634. }
  1635. }
  1636. if (ref->GetScopeId() == blockId)
  1637. {
  1638. break;
  1639. }
  1640. }
  1641. }
  1642. void Parser::MarkEscapingRef(ParseNodePtr pnode, IdentToken *pToken)
  1643. {
  1644. if (m_currentNodeFunc == nullptr)
  1645. {
  1646. return;
  1647. }
  1648. if (pnode && pnode->nop == knopFncDecl)
  1649. {
  1650. this->SetNestedFuncEscapes();
  1651. }
  1652. else if (pToken->pid)
  1653. {
  1654. PidRefStack *pidRef = pToken->pid->GetTopRef();
  1655. if (pidRef->sym)
  1656. {
  1657. if (pidRef->sym->GetSymbolType() == STFunction)
  1658. {
  1659. this->SetNestedFuncEscapes();
  1660. }
  1661. }
  1662. else
  1663. {
  1664. pidRef->isEscape = true;
  1665. }
  1666. }
  1667. }
  1668. void Parser::SetNestedFuncEscapes() const
  1669. {
  1670. if (m_sourceContextInfo ?
  1671. !PHASE_OFF_RAW(Js::DisableStackFuncOnDeferredEscapePhase, m_sourceContextInfo->sourceContextId, m_currentNodeFunc->sxFnc.functionId) :
  1672. !PHASE_OFF1(Js::DisableStackFuncOnDeferredEscapePhase))
  1673. {
  1674. m_currentNodeFunc->sxFnc.SetNestedFuncEscapes();
  1675. }
  1676. }
  1677. void Parser::PopStmt(StmtNest *pStmt)
  1678. {
  1679. Assert(pStmt == m_pstmtCur);
  1680. SetCurrentStatement(m_pstmtCur->pstmtOuter);
  1681. }
  1682. BlockInfoStack *Parser::PushBlockInfo(ParseNodePtr pnodeBlock)
  1683. {
  1684. BlockInfoStack *newBlockInfo = (BlockInfoStack *)m_nodeAllocator.Alloc(sizeof(BlockInfoStack));
  1685. Assert(nullptr != newBlockInfo);
  1686. newBlockInfo->pnodeBlock = pnodeBlock;
  1687. newBlockInfo->pBlockInfoOuter = m_currentBlockInfo;
  1688. newBlockInfo->m_ppnodeLex = &pnodeBlock->sxBlock.pnodeLexVars;
  1689. if (pnodeBlock->sxBlock.blockType != PnodeBlockType::Regular)
  1690. {
  1691. newBlockInfo->pBlockInfoFunction = newBlockInfo;
  1692. }
  1693. else
  1694. {
  1695. Assert(m_currentBlockInfo);
  1696. newBlockInfo->pBlockInfoFunction = m_currentBlockInfo->pBlockInfoFunction;
  1697. }
  1698. m_currentBlockInfo = newBlockInfo;
  1699. return newBlockInfo;
  1700. }
  1701. void Parser::PopBlockInfo()
  1702. {
  1703. Assert(m_currentBlockInfo);
  1704. PopDynamicBlock();
  1705. m_currentBlockInfo = m_currentBlockInfo->pBlockInfoOuter;
  1706. }
  1707. void Parser::PushDynamicBlock()
  1708. {
  1709. Assert(GetCurrentBlock());
  1710. int blockId = GetCurrentBlock()->sxBlock.blockId;
  1711. if (m_currentDynamicBlock && m_currentDynamicBlock->id == blockId)
  1712. {
  1713. return;
  1714. }
  1715. BlockIdsStack *info = (BlockIdsStack *)m_nodeAllocator.Alloc(sizeof(BlockIdsStack));
  1716. if (nullptr == info)
  1717. {
  1718. Error(ERRnoMemory);
  1719. }
  1720. info->id = blockId;
  1721. info->prev = m_currentDynamicBlock;
  1722. m_currentDynamicBlock = info;
  1723. }
  1724. void Parser::PopDynamicBlock()
  1725. {
  1726. int blockId = GetCurrentDynamicBlockId();
  1727. if (GetCurrentBlock()->sxBlock.blockId != blockId || blockId == -1)
  1728. {
  1729. return;
  1730. }
  1731. Assert(m_currentDynamicBlock);
  1732. m_phtbl->VisitPids([&](IdentPtr pid) {
  1733. for (PidRefStack *ref = pid->GetTopRef(); ref && ref->GetScopeId() >= blockId; ref = ref->prev)
  1734. {
  1735. ref->SetDynamicBinding();
  1736. }
  1737. });
  1738. m_currentDynamicBlock = m_currentDynamicBlock->prev;
  1739. }
  1740. int Parser::GetCurrentDynamicBlockId() const
  1741. {
  1742. return m_currentDynamicBlock ? m_currentDynamicBlock->id : -1;
  1743. }
  1744. ParseNode *Parser::GetCurrentFunctionNode()
  1745. {
  1746. if (m_currentNodeDeferredFunc != nullptr)
  1747. {
  1748. return m_currentNodeDeferredFunc;
  1749. }
  1750. else if (m_currentNodeFunc != nullptr)
  1751. {
  1752. return m_currentNodeFunc;
  1753. }
  1754. else
  1755. {
  1756. AssertMsg(GetFunctionBlock()->sxBlock.blockType == PnodeBlockType::Global,
  1757. "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'");
  1758. return m_currentNodeProg;
  1759. }
  1760. }
  1761. ParseNode *Parser::GetCurrentNonLambdaFunctionNode()
  1762. {
  1763. if (m_currentNodeNonLambdaDeferredFunc != nullptr)
  1764. {
  1765. return m_currentNodeNonLambdaDeferredFunc;
  1766. }
  1767. return m_currentNodeNonLambdaFunc;
  1768. }
  1769. void Parser::RegisterRegexPattern(UnifiedRegex::RegexPattern *const regexPattern)
  1770. {
  1771. Assert(regexPattern);
  1772. // ensure a no-throw add behavior here, to catch out of memory exceptions, using the guest arena allocator
  1773. if (!m_registeredRegexPatterns.PrependNoThrow(m_scriptContext->GetGuestArena(), regexPattern))
  1774. {
  1775. Parser::Error(ERRnoMemory);
  1776. }
  1777. }
  1778. void Parser::CaptureState(ParserState *state)
  1779. {
  1780. Assert(state != nullptr);
  1781. state->m_funcInArraySave = m_funcInArray;
  1782. state->m_funcInArrayDepthSave = m_funcInArrayDepth;
  1783. state->m_nestedCountSave = *m_pnestedCount;
  1784. state->m_ppnodeScopeSave = m_ppnodeScope;
  1785. state->m_ppnodeExprScopeSave = m_ppnodeExprScope;
  1786. state->m_pCurrentAstSizeSave = m_pCurrentAstSize;
  1787. state->m_nextBlockId = m_nextBlockId;
  1788. Assert(state->m_ppnodeScopeSave == nullptr || *state->m_ppnodeScopeSave == nullptr);
  1789. Assert(state->m_ppnodeExprScopeSave == nullptr || *state->m_ppnodeExprScopeSave == nullptr);
  1790. #if DEBUG
  1791. state->m_currentBlockInfo = m_currentBlockInfo;
  1792. #endif
  1793. }
  1794. void Parser::RestoreStateFrom(ParserState *state)
  1795. {
  1796. Assert(state != nullptr);
  1797. Assert(state->m_currentBlockInfo == m_currentBlockInfo);
  1798. m_funcInArray = state->m_funcInArraySave;
  1799. m_funcInArrayDepth = state->m_funcInArrayDepthSave;
  1800. *m_pnestedCount = state->m_nestedCountSave;
  1801. m_pCurrentAstSize = state->m_pCurrentAstSizeSave;
  1802. m_nextBlockId = state->m_nextBlockId;
  1803. if (state->m_ppnodeScopeSave != nullptr)
  1804. {
  1805. *state->m_ppnodeScopeSave = nullptr;
  1806. }
  1807. if (state->m_ppnodeExprScopeSave != nullptr)
  1808. {
  1809. *state->m_ppnodeExprScopeSave = nullptr;
  1810. }
  1811. m_ppnodeScope = state->m_ppnodeScopeSave;
  1812. m_ppnodeExprScope = state->m_ppnodeExprScopeSave;
  1813. }
  1814. void Parser::AddToNodeListEscapedUse(ParseNode ** ppnodeList, ParseNode *** pppnodeLast,
  1815. ParseNode * pnodeAdd)
  1816. {
  1817. AddToNodeList(ppnodeList, pppnodeLast, pnodeAdd);
  1818. pnodeAdd->SetIsInList();
  1819. }
  1820. void Parser::AddToNodeList(ParseNode ** ppnodeList, ParseNode *** pppnodeLast,
  1821. ParseNode * pnodeAdd)
  1822. {
  1823. Assert(!this->m_deferringAST);
  1824. if (nullptr == *pppnodeLast)
  1825. {
  1826. // should be an empty list
  1827. Assert(nullptr == *ppnodeList);
  1828. *ppnodeList = pnodeAdd;
  1829. *pppnodeLast = ppnodeList;
  1830. }
  1831. else
  1832. {
  1833. //
  1834. AssertNodeMem(*ppnodeList);
  1835. AssertNodeMem(**pppnodeLast);
  1836. ParseNode *pnodeT = CreateBinNode(knopList, **pppnodeLast, pnodeAdd);
  1837. **pppnodeLast = pnodeT;
  1838. *pppnodeLast = &pnodeT->sxBin.pnode2;
  1839. }
  1840. }
  1841. // Check reference to "arguments" that indicates the object may escape.
  1842. void Parser::CheckArguments(ParseNodePtr pnode)
  1843. {
  1844. if (m_currentNodeFunc && this->NodeIsIdent(pnode, wellKnownPropertyPids.arguments))
  1845. {
  1846. m_currentNodeFunc->sxFnc.SetHasHeapArguments();
  1847. }
  1848. }
  1849. // Check use of "arguments" that requires instantiation of the object.
  1850. void Parser::CheckArgumentsUse(IdentPtr pid, ParseNodePtr pnodeFnc)
  1851. {
  1852. if (pid == wellKnownPropertyPids.arguments)
  1853. {
  1854. if (pnodeFnc != nullptr && pnodeFnc != m_currentNodeProg)
  1855. {
  1856. pnodeFnc->sxFnc.SetUsesArguments(TRUE);
  1857. }
  1858. else
  1859. {
  1860. m_UsesArgumentsAtGlobal = true;
  1861. }
  1862. }
  1863. }
  1864. void Parser::CheckStrictModeEvalArgumentsUsage(IdentPtr pid, ParseNodePtr pnode)
  1865. {
  1866. if (pid != nullptr)
  1867. {
  1868. // In strict mode, 'eval' / 'arguments' cannot be assigned to.
  1869. if ( pid == wellKnownPropertyPids.eval)
  1870. {
  1871. Error(ERREvalUsage, pnode);
  1872. }
  1873. if (pid == wellKnownPropertyPids.arguments)
  1874. {
  1875. Error(ERRArgsUsage, pnode);
  1876. }
  1877. }
  1878. }
  1879. void Parser::ReduceDeferredScriptLength(size_t chars)
  1880. {
  1881. // If we're in deferred mode, subtract the given char count from the total length,
  1882. // and see if this puts us under the deferral threshold.
  1883. if ((m_grfscr & fscrDeferFncParse) &&
  1884. (
  1885. PHASE_OFF1(Js::DeferEventHandlersPhase) ||
  1886. (m_grfscr & fscrGlobalCode)
  1887. )
  1888. )
  1889. {
  1890. if (m_length > chars)
  1891. {
  1892. m_length -= chars;
  1893. }
  1894. else
  1895. {
  1896. m_length = 0;
  1897. }
  1898. if (m_length < Parser::GetDeferralThreshold(this->m_sourceContextInfo->IsSourceProfileLoaded()))
  1899. {
  1900. // Stop deferring.
  1901. m_grfscr &= ~fscrDeferFncParse;
  1902. m_stoppedDeferredParse = TRUE;
  1903. }
  1904. }
  1905. }
  1906. /***************************************************************************
  1907. Look for an existing label with the given name.
  1908. ***************************************************************************/
  1909. BOOL Parser::PnodeLabelNoAST(IdentToken* pToken, LabelId* pLabelIdList)
  1910. {
  1911. StmtNest* pStmt;
  1912. LabelId* pLabelId;
  1913. // Look in the label stack.
  1914. for (pStmt = m_pstmtCur; pStmt != nullptr; pStmt = pStmt->pstmtOuter)
  1915. {
  1916. for (pLabelId = pStmt->pLabelId; pLabelId != nullptr; pLabelId = pLabelId->next)
  1917. {
  1918. if (pLabelId->pid == pToken->pid)
  1919. return TRUE;
  1920. }
  1921. }
  1922. // Also look in the pnodeLabels list.
  1923. for (pLabelId = pLabelIdList; pLabelId != nullptr; pLabelId = pLabelId->next)
  1924. {
  1925. if (pLabelId->pid == pToken->pid)
  1926. return TRUE;
  1927. }
  1928. return FALSE;
  1929. }
  1930. void Parser::EnsureStackAvailable()
  1931. {
  1932. if (!m_scriptContext->GetThreadContext()->IsStackAvailable(Js::Constants::MinStackCompile))
  1933. {
  1934. Error(ERRnoMemory);
  1935. }
  1936. }
  1937. void Parser::ThrowNewTargetSyntaxErrForGlobalScope()
  1938. {
  1939. // If we are parsing a previously deferred function, we can skip throwing the SyntaxError for `new.target` at global scope.
  1940. // If we are at global scope, we would have thrown a SyntaxError when we did the Upfront parse pass and we would not have
  1941. // deferred the function in order to come back now and reparse it.
  1942. if (m_parseType == ParseType_Deferred)
  1943. {
  1944. return;
  1945. }
  1946. if (GetCurrentNonLambdaFunctionNode() != nullptr)
  1947. {
  1948. return;
  1949. }
  1950. if ((this->m_grfscr & fscrEval) != 0)
  1951. {
  1952. Js::JavascriptFunction * caller = nullptr;
  1953. if (Js::JavascriptStackWalker::GetCaller(&caller, m_scriptContext))
  1954. {
  1955. Js::FunctionBody * callerBody = caller->GetFunctionBody();
  1956. Assert(callerBody);
  1957. if (!callerBody->GetIsGlobalFunc() && !(callerBody->IsLambda() && callerBody->GetEnclosedByGlobalFunc()))
  1958. {
  1959. return;
  1960. }
  1961. }
  1962. }
  1963. Error(ERRInvalidNewTarget);
  1964. }
  1965. template<bool buildAST>
  1966. IdentPtr Parser::ParseMetaProperty(tokens metaParentKeyword, charcount_t ichMin, _Out_opt_ BOOL* pfCanAssign)
  1967. {
  1968. AssertMsg(metaParentKeyword == tkNEW, "Only supported for tkNEW parent keywords");
  1969. AssertMsg(this->m_token.tk == tkDot, "We must be currently sitting on the dot after the parent keyword");
  1970. m_pscan->Scan();
  1971. if (this->m_token.tk == tkID && this->m_token.GetIdentifier(m_phtbl) == this->GetTargetPid())
  1972. {
  1973. ThrowNewTargetSyntaxErrForGlobalScope();
  1974. if (pfCanAssign)
  1975. {
  1976. *pfCanAssign = FALSE;
  1977. }
  1978. return wellKnownPropertyPids._newTarget;
  1979. }
  1980. else
  1981. {
  1982. Error(ERRsyntax);
  1983. }
  1984. }
  1985. template<bool buildAST>
  1986. void Parser::ParseNamedImportOrExportClause(ModuleImportOrExportEntryList* importOrExportEntryList, bool isExportClause)
  1987. {
  1988. Assert(m_token.tk == tkLCurly);
  1989. Assert(importOrExportEntryList != nullptr);
  1990. m_pscan->Scan();
  1991. while (m_token.tk != tkRCurly && m_token.tk != tkEOF)
  1992. {
  1993. tokens firstToken = m_token.tk;
  1994. if (!(m_token.IsIdentifier() || m_token.IsReservedWord()))
  1995. {
  1996. Error(ERRsyntax);
  1997. }
  1998. IdentPtr identifierName = m_token.GetIdentifier(m_phtbl);
  1999. IdentPtr identifierAs = identifierName;
  2000. m_pscan->Scan();
  2001. if (m_token.tk == tkID)
  2002. {
  2003. // We have the pattern "IdentifierName as"
  2004. if (wellKnownPropertyPids.as != m_token.GetIdentifier(m_phtbl))
  2005. {
  2006. Error(ERRsyntax);
  2007. }
  2008. m_pscan->Scan();
  2009. // If we are parsing an import statement, the token after 'as' must be a BindingIdentifier.
  2010. if (!isExportClause)
  2011. {
  2012. ChkCurTokNoScan(tkID, ERRsyntax);
  2013. }
  2014. if (!(m_token.IsIdentifier() || m_token.IsReservedWord()))
  2015. {
  2016. Error(ERRsyntax);
  2017. }
  2018. identifierAs = m_token.GetIdentifier(m_phtbl);
  2019. // Scan to the next token.
  2020. m_pscan->Scan();
  2021. }
  2022. else if (!isExportClause && firstToken != tkID)
  2023. {
  2024. // If we are parsing an import statement and this ImportSpecifier clause did not have
  2025. // 'as ImportedBinding' at the end of it, identifierName must be a BindingIdentifier.
  2026. Error(ERRsyntax);
  2027. }
  2028. if (m_token.tk == tkComma)
  2029. {
  2030. // Consume a trailing comma
  2031. m_pscan->Scan();
  2032. }
  2033. if (buildAST)
  2034. {
  2035. // The name we will use 'as' this import/export is a binding identifier in import statements.
  2036. if (!isExportClause)
  2037. {
  2038. CreateModuleImportDeclNode(identifierAs);
  2039. AddModuleImportOrExportEntry(importOrExportEntryList, identifierName, identifierAs, nullptr, nullptr);
  2040. }
  2041. else
  2042. {
  2043. identifierName->SetIsModuleExport();
  2044. AddModuleImportOrExportEntry(importOrExportEntryList, nullptr, identifierName, identifierAs, nullptr);
  2045. }
  2046. }
  2047. }
  2048. // Final token in a named import or export clause must be a '}'
  2049. ChkCurTokNoScan(tkRCurly, ERRsyntax);
  2050. }
  2051. IdentPtrList* Parser::GetRequestedModulesList()
  2052. {
  2053. return m_currentNodeProg->sxModule.requestedModules;
  2054. }
  2055. ModuleImportOrExportEntryList* Parser::GetModuleImportEntryList()
  2056. {
  2057. return m_currentNodeProg->sxModule.importEntries;
  2058. }
  2059. ModuleImportOrExportEntryList* Parser::GetModuleLocalExportEntryList()
  2060. {
  2061. return m_currentNodeProg->sxModule.localExportEntries;
  2062. }
  2063. ModuleImportOrExportEntryList* Parser::GetModuleIndirectExportEntryList()
  2064. {
  2065. return m_currentNodeProg->sxModule.indirectExportEntries;
  2066. }
  2067. ModuleImportOrExportEntryList* Parser::GetModuleStarExportEntryList()
  2068. {
  2069. return m_currentNodeProg->sxModule.starExportEntries;
  2070. }
  2071. IdentPtrList* Parser::EnsureRequestedModulesList()
  2072. {
  2073. if (m_currentNodeProg->sxModule.requestedModules == nullptr)
  2074. {
  2075. m_currentNodeProg->sxModule.requestedModules = Anew(&m_nodeAllocator, IdentPtrList, &m_nodeAllocator);
  2076. }
  2077. return m_currentNodeProg->sxModule.requestedModules;
  2078. }
  2079. ModuleImportOrExportEntryList* Parser::EnsureModuleImportEntryList()
  2080. {
  2081. if (m_currentNodeProg->sxModule.importEntries == nullptr)
  2082. {
  2083. m_currentNodeProg->sxModule.importEntries = Anew(&m_nodeAllocator, ModuleImportOrExportEntryList, &m_nodeAllocator);
  2084. }
  2085. return m_currentNodeProg->sxModule.importEntries;
  2086. }
  2087. ModuleImportOrExportEntryList* Parser::EnsureModuleLocalExportEntryList()
  2088. {
  2089. if (m_currentNodeProg->sxModule.localExportEntries == nullptr)
  2090. {
  2091. m_currentNodeProg->sxModule.localExportEntries = Anew(&m_nodeAllocator, ModuleImportOrExportEntryList, &m_nodeAllocator);
  2092. }
  2093. return m_currentNodeProg->sxModule.localExportEntries;
  2094. }
  2095. ModuleImportOrExportEntryList* Parser::EnsureModuleIndirectExportEntryList()
  2096. {
  2097. if (m_currentNodeProg->sxModule.indirectExportEntries == nullptr)
  2098. {
  2099. m_currentNodeProg->sxModule.indirectExportEntries = Anew(&m_nodeAllocator, ModuleImportOrExportEntryList, &m_nodeAllocator);
  2100. }
  2101. return m_currentNodeProg->sxModule.indirectExportEntries;
  2102. }
  2103. ModuleImportOrExportEntryList* Parser::EnsureModuleStarExportEntryList()
  2104. {
  2105. if (m_currentNodeProg->sxModule.starExportEntries == nullptr)
  2106. {
  2107. m_currentNodeProg->sxModule.starExportEntries = Anew(&m_nodeAllocator, ModuleImportOrExportEntryList, &m_nodeAllocator);
  2108. }
  2109. return m_currentNodeProg->sxModule.starExportEntries;
  2110. }
  2111. void Parser::AddModuleSpecifier(IdentPtr moduleRequest)
  2112. {
  2113. IdentPtrList* requestedModulesList = EnsureRequestedModulesList();
  2114. if (!requestedModulesList->Has(moduleRequest))
  2115. {
  2116. requestedModulesList->Prepend(moduleRequest);
  2117. }
  2118. }
  2119. ModuleImportOrExportEntry* Parser::AddModuleImportOrExportEntry(ModuleImportOrExportEntryList* importOrExportEntryList, ModuleImportOrExportEntry* importOrExportEntry)
  2120. {
  2121. if (importOrExportEntry->exportName != nullptr)
  2122. {
  2123. CheckForDuplicateExportEntry(importOrExportEntryList, importOrExportEntry->exportName);
  2124. }
  2125. importOrExportEntryList->Prepend(*importOrExportEntry);
  2126. return importOrExportEntry;
  2127. }
  2128. ModuleImportOrExportEntry* Parser::AddModuleImportOrExportEntry(ModuleImportOrExportEntryList* importOrExportEntryList, IdentPtr importName, IdentPtr localName, IdentPtr exportName, IdentPtr moduleRequest)
  2129. {
  2130. ModuleImportOrExportEntry* importOrExportEntry = Anew(&m_nodeAllocator, ModuleImportOrExportEntry);
  2131. importOrExportEntry->importName = importName;
  2132. importOrExportEntry->localName = localName;
  2133. importOrExportEntry->exportName = exportName;
  2134. importOrExportEntry->moduleRequest = moduleRequest;
  2135. return AddModuleImportOrExportEntry(importOrExportEntryList, importOrExportEntry);
  2136. }
  2137. void Parser::AddModuleLocalExportEntry(ParseNodePtr varDeclNode)
  2138. {
  2139. Assert(varDeclNode->nop == knopVarDecl || varDeclNode->nop == knopLetDecl || varDeclNode->nop == knopConstDecl);
  2140. IdentPtr localName = varDeclNode->sxVar.pid;
  2141. varDeclNode->sxVar.sym->SetIsModuleExportStorage(true);
  2142. AddModuleImportOrExportEntry(EnsureModuleLocalExportEntryList(), nullptr, localName, localName, nullptr);
  2143. }
  2144. void Parser::CheckForDuplicateExportEntry(ModuleImportOrExportEntryList* exportEntryList, IdentPtr exportName)
  2145. {
  2146. ModuleImportOrExportEntry* findResult = exportEntryList->Find([&](ModuleImportOrExportEntry exportEntry)
  2147. {
  2148. if (exportName == exportEntry.exportName)
  2149. {
  2150. return true;
  2151. }
  2152. return false;
  2153. });
  2154. if (findResult != nullptr)
  2155. {
  2156. Error(ERRsyntax);
  2157. }
  2158. }
  2159. template<bool buildAST>
  2160. void Parser::ParseImportClause(ModuleImportOrExportEntryList* importEntryList, bool parsingAfterComma)
  2161. {
  2162. bool parsedNamespaceOrNamedImport = false;
  2163. switch (m_token.tk)
  2164. {
  2165. case tkID:
  2166. // This is the default binding identifier.
  2167. // If we already saw a comma in the import clause, this is a syntax error.
  2168. if (parsingAfterComma)
  2169. {
  2170. Error(ERRsyntax);
  2171. }
  2172. if (buildAST)
  2173. {
  2174. IdentPtr localName = m_token.GetIdentifier(m_phtbl);
  2175. IdentPtr importName = wellKnownPropertyPids._default;
  2176. CreateModuleImportDeclNode(localName);
  2177. AddModuleImportOrExportEntry(importEntryList, importName, localName, nullptr, nullptr);
  2178. }
  2179. break;
  2180. case tkLCurly:
  2181. // This begins a list of named imports.
  2182. ParseNamedImportOrExportClause<buildAST>(importEntryList, false);
  2183. parsedNamespaceOrNamedImport = true;
  2184. break;
  2185. case tkStar:
  2186. // This begins a namespace import clause.
  2187. // "* as ImportedBinding"
  2188. // Token following * must be the identifier 'as'
  2189. m_pscan->Scan();
  2190. if (m_token.tk != tkID || wellKnownPropertyPids.as != m_token.GetIdentifier(m_phtbl))
  2191. {
  2192. Error(ERRsyntax);
  2193. }
  2194. // Token following 'as' must be a binding identifier.
  2195. m_pscan->Scan();
  2196. ChkCurTokNoScan(tkID, ERRsyntax);
  2197. if (buildAST)
  2198. {
  2199. IdentPtr localName = m_token.GetIdentifier(m_phtbl);
  2200. IdentPtr importName = wellKnownPropertyPids._star;
  2201. CreateModuleImportDeclNode(localName);
  2202. AddModuleImportOrExportEntry(importEntryList, importName, localName, nullptr, nullptr);
  2203. }
  2204. parsedNamespaceOrNamedImport = true;
  2205. break;
  2206. default:
  2207. Error(ERRsyntax);
  2208. }
  2209. m_pscan->Scan();
  2210. if (m_token.tk == tkComma)
  2211. {
  2212. // There cannot be more than one comma in a module import clause.
  2213. // There cannot be a namespace import or named imports list on the left of the comma in a module import clause.
  2214. if (parsingAfterComma || parsedNamespaceOrNamedImport)
  2215. {
  2216. Error(ERRsyntax);
  2217. }
  2218. m_pscan->Scan();
  2219. ParseImportClause<buildAST>(importEntryList, true);
  2220. }
  2221. }
  2222. bool Parser::IsImportOrExportStatementValidHere()
  2223. {
  2224. ParseNodePtr curFunc = GetCurrentFunctionNode();
  2225. // Import must be located in the top scope of the module body.
  2226. return curFunc->nop == knopFncDecl
  2227. && curFunc->sxFnc.IsModule()
  2228. && this->m_currentBlockInfo->pnodeBlock == curFunc->sxFnc.pnodeBodyScope
  2229. && (this->m_grfscr & fscrEvalCode) != fscrEvalCode
  2230. && this->m_tryCatchOrFinallyDepth == 0
  2231. && !this->m_disallowImportExportStmt;
  2232. }
  2233. bool Parser::IsTopLevelModuleFunc()
  2234. {
  2235. ParseNodePtr curFunc = GetCurrentFunctionNode();
  2236. return curFunc->nop == knopFncDecl && curFunc->sxFnc.IsModule();
  2237. }
  2238. template<bool buildAST> ParseNodePtr Parser::ParseImportCall()
  2239. {
  2240. m_pscan->Scan();
  2241. ParseNodePtr specifier = ParseExpr<buildAST>(koplCma, nullptr, /* fAllowIn */FALSE, /* fAllowEllipsis */FALSE);
  2242. if (m_token.tk != tkRParen)
  2243. {
  2244. Error(ERRnoRparen);
  2245. }
  2246. m_pscan->Scan();
  2247. return buildAST ? CreateCallNode(knopCall, CreateNodeWithScanner<knopImport>(), specifier) : nullptr;
  2248. }
  2249. template<bool buildAST>
  2250. ParseNodePtr Parser::ParseImport()
  2251. {
  2252. Assert(m_scriptContext->GetConfig()->IsES6ModuleEnabled());
  2253. Assert(m_token.tk == tkIMPORT);
  2254. RestorePoint parsedImport;
  2255. m_pscan->Capture(&parsedImport);
  2256. m_pscan->Scan();
  2257. // import()
  2258. if (m_token.tk == tkLParen)
  2259. {
  2260. ParseNodePtr pnode = ParseImportCall<buildAST>();
  2261. BOOL fCanAssign;
  2262. IdentToken token;
  2263. return ParsePostfixOperators<buildAST>(pnode, TRUE, FALSE, FALSE, &fCanAssign, &token);
  2264. }
  2265. m_pscan->SeekTo(parsedImport);
  2266. if (!IsImportOrExportStatementValidHere())
  2267. {
  2268. Error(ERRInvalidModuleImportOrExport);
  2269. }
  2270. // We just parsed an import token. Next valid token is *, {, string constant, or binding identifier.
  2271. m_pscan->Scan();
  2272. if (m_token.tk == tkStrCon)
  2273. {
  2274. // This import declaration has no import clause.
  2275. // "import ModuleSpecifier;"
  2276. if (buildAST)
  2277. {
  2278. AddModuleSpecifier(m_token.GetStr());
  2279. }
  2280. // Scan past the module identifier.
  2281. m_pscan->Scan();
  2282. }
  2283. else
  2284. {
  2285. ModuleImportOrExportEntryList importEntryList(&m_nodeAllocator);
  2286. // Parse the import clause (default binding can only exist before the comma).
  2287. ParseImportClause<buildAST>(&importEntryList);
  2288. // Token following import clause must be the identifier 'from'
  2289. IdentPtr moduleSpecifier = ParseImportOrExportFromClause<buildAST>(true);
  2290. if (buildAST)
  2291. {
  2292. Assert(moduleSpecifier != nullptr);
  2293. AddModuleSpecifier(moduleSpecifier);
  2294. importEntryList.Map([this, moduleSpecifier](ModuleImportOrExportEntry& importEntry) {
  2295. importEntry.moduleRequest = moduleSpecifier;
  2296. AddModuleImportOrExportEntry(EnsureModuleImportEntryList(), &importEntry);
  2297. });
  2298. }
  2299. importEntryList.Clear();
  2300. }
  2301. // Import statement is actually a nop, we hoist all the imported bindings to the top of the module.
  2302. return nullptr;
  2303. }
  2304. template<bool buildAST>
  2305. IdentPtr Parser::ParseImportOrExportFromClause(bool throwIfNotFound)
  2306. {
  2307. IdentPtr moduleSpecifier = nullptr;
  2308. if (m_token.tk == tkID && wellKnownPropertyPids.from == m_token.GetIdentifier(m_phtbl))
  2309. {
  2310. m_pscan->Scan();
  2311. // Token following the 'from' token must be a string constant - the module specifier.
  2312. ChkCurTokNoScan(tkStrCon, ERRsyntax);
  2313. if (buildAST)
  2314. {
  2315. moduleSpecifier = m_token.GetStr();
  2316. }
  2317. m_pscan->Scan();
  2318. }
  2319. else if (throwIfNotFound)
  2320. {
  2321. Error(ERRsyntax);
  2322. }
  2323. return moduleSpecifier;
  2324. }
  2325. template<bool buildAST>
  2326. ParseNodePtr Parser::ParseDefaultExportClause()
  2327. {
  2328. Assert(m_token.tk == tkDEFAULT);
  2329. m_pscan->Scan();
  2330. ParseNodePtr pnode = nullptr;
  2331. ushort flags = fFncNoFlgs;
  2332. switch (m_token.tk)
  2333. {
  2334. case tkCLASS:
  2335. {
  2336. if (!m_scriptContext->GetConfig()->IsES6ClassAndExtendsEnabled())
  2337. {
  2338. goto LDefault;
  2339. }
  2340. // Before we parse the class itself we need to know if the class has an identifier name.
  2341. // If it does, we'll treat this class as an ordinary class declaration which will bind
  2342. // it to that name. Otherwise the class should parse as a nameless class expression and
  2343. // bind only to the export binding.
  2344. BOOL classHasName = false;
  2345. RestorePoint parsedClass;
  2346. m_pscan->Capture(&parsedClass);
  2347. m_pscan->Scan();
  2348. if (m_token.tk == tkID)
  2349. {
  2350. classHasName = true;
  2351. }
  2352. m_pscan->SeekTo(parsedClass);
  2353. pnode = ParseClassDecl<buildAST>(classHasName, nullptr, nullptr, nullptr);
  2354. if (buildAST)
  2355. {
  2356. AnalysisAssert(pnode != nullptr);
  2357. Assert(pnode->nop == knopClassDecl);
  2358. pnode->sxClass.SetIsDefaultModuleExport(true);
  2359. }
  2360. break;
  2361. }
  2362. case tkID:
  2363. // If we parsed an async token, it could either modify the next token (if it is a
  2364. // function token) or it could be an identifier (let async = 0; export default async;).
  2365. // To handle both cases, when we parse an async token we need to keep the parser state
  2366. // and rewind if the next token is not function.
  2367. if (wellKnownPropertyPids.async == m_token.GetIdentifier(m_phtbl))
  2368. {
  2369. RestorePoint parsedAsync;
  2370. m_pscan->Capture(&parsedAsync);
  2371. m_pscan->Scan();
  2372. if (m_token.tk == tkFUNCTION)
  2373. {
  2374. // Token after async is function, consume the async token and continue to parse the
  2375. // function as an async function.
  2376. flags |= fFncAsync;
  2377. goto LFunction;
  2378. }
  2379. // Token after async is not function, no idea what the async token is supposed to mean
  2380. // so rewind and let the default case handle it.
  2381. m_pscan->SeekTo(parsedAsync);
  2382. }
  2383. goto LDefault;
  2384. break;
  2385. case tkFUNCTION:
  2386. {
  2387. LFunction:
  2388. // We just parsed a function token but we need to figure out if the function
  2389. // has an identifier name or not before we call the helper.
  2390. RestorePoint parsedFunction;
  2391. m_pscan->Capture(&parsedFunction);
  2392. m_pscan->Scan();
  2393. if (m_token.tk == tkStar)
  2394. {
  2395. // If we saw 'function*' that indicates we are going to parse a generator,
  2396. // but doesn't tell us if the generator has an identifier or not.
  2397. // Skip the '*' token for now as it doesn't matter yet.
  2398. m_pscan->Scan();
  2399. }
  2400. // We say that if the function has an identifier name, it is a 'normal' declaration
  2401. // and should create a binding to that identifier as well as one for our default export.
  2402. if (m_token.tk == tkID)
  2403. {
  2404. flags |= fFncDeclaration;
  2405. }
  2406. else
  2407. {
  2408. flags |= fFncNoName;
  2409. }
  2410. // Rewind back to the function token and let the helper handle the parsing.
  2411. m_pscan->SeekTo(parsedFunction);
  2412. pnode = ParseFncDecl<buildAST>(flags);
  2413. if (buildAST)
  2414. {
  2415. AnalysisAssert(pnode != nullptr);
  2416. Assert(pnode->nop == knopFncDecl);
  2417. pnode->sxFnc.SetIsDefaultModuleExport(true);
  2418. }
  2419. break;
  2420. }
  2421. default:
  2422. LDefault:
  2423. {
  2424. ParseNodePtr pnodeExpression = ParseExpr<buildAST>();
  2425. // Consider: Can we detect this syntax error earlier?
  2426. if (pnodeExpression && pnodeExpression->nop == knopComma)
  2427. {
  2428. Error(ERRsyntax);
  2429. }
  2430. if (buildAST)
  2431. {
  2432. AnalysisAssert(pnodeExpression != nullptr);
  2433. // Mark this node as the default module export. We need to make sure it is put into the correct
  2434. // module export slot when we emit the node.
  2435. pnode = CreateNode(knopExportDefault);
  2436. pnode->sxExportDefault.pnodeExpr = pnodeExpression;
  2437. }
  2438. break;
  2439. }
  2440. }
  2441. IdentPtr exportName = wellKnownPropertyPids._default;
  2442. IdentPtr localName = wellKnownPropertyPids._starDefaultStar;
  2443. AddModuleImportOrExportEntry(EnsureModuleLocalExportEntryList(), nullptr, localName, exportName, nullptr);
  2444. return pnode;
  2445. }
  2446. template<bool buildAST>
  2447. ParseNodePtr Parser::ParseExportDeclaration(bool *needTerminator)
  2448. {
  2449. Assert(m_scriptContext->GetConfig()->IsES6ModuleEnabled());
  2450. Assert(m_token.tk == tkEXPORT);
  2451. if (!IsImportOrExportStatementValidHere())
  2452. {
  2453. Error(ERRInvalidModuleImportOrExport);
  2454. }
  2455. ParseNodePtr pnode = nullptr;
  2456. IdentPtr moduleIdentifier = nullptr;
  2457. tokens declarationType;
  2458. if (needTerminator != nullptr)
  2459. {
  2460. *needTerminator = false;
  2461. }
  2462. // We just parsed an export token. Next valid tokens are *, {, var, let, const, async, function, class, default.
  2463. m_pscan->Scan();
  2464. switch (m_token.tk)
  2465. {
  2466. case tkStar:
  2467. m_pscan->Scan();
  2468. // A star token in an export declaration must be followed by a from clause which begins with a token 'from'.
  2469. moduleIdentifier = ParseImportOrExportFromClause<buildAST>(true);
  2470. if (buildAST)
  2471. {
  2472. Assert(moduleIdentifier != nullptr);
  2473. AddModuleSpecifier(moduleIdentifier);
  2474. IdentPtr importName = wellKnownPropertyPids._star;
  2475. AddModuleImportOrExportEntry(EnsureModuleStarExportEntryList(), importName, nullptr, nullptr, moduleIdentifier);
  2476. }
  2477. if (needTerminator != nullptr)
  2478. {
  2479. *needTerminator = true;
  2480. }
  2481. break;
  2482. case tkLCurly:
  2483. {
  2484. ModuleImportOrExportEntryList exportEntryList(&m_nodeAllocator);
  2485. ParseNamedImportOrExportClause<buildAST>(&exportEntryList, true);
  2486. m_pscan->Scan();
  2487. // Export clause may be followed by a from clause.
  2488. moduleIdentifier = ParseImportOrExportFromClause<buildAST>(false);
  2489. if (buildAST)
  2490. {
  2491. if (moduleIdentifier != nullptr)
  2492. {
  2493. AddModuleSpecifier(moduleIdentifier);
  2494. }
  2495. exportEntryList.Map([this, moduleIdentifier](ModuleImportOrExportEntry& exportEntry) {
  2496. if (moduleIdentifier != nullptr)
  2497. {
  2498. exportEntry.moduleRequest = moduleIdentifier;
  2499. // We need to swap localname and importname when this is a re-export.
  2500. exportEntry.importName = exportEntry.localName;
  2501. exportEntry.localName = nullptr;
  2502. AddModuleImportOrExportEntry(EnsureModuleIndirectExportEntryList(), &exportEntry);
  2503. }
  2504. else
  2505. {
  2506. AddModuleImportOrExportEntry(EnsureModuleLocalExportEntryList(), &exportEntry);
  2507. }
  2508. });
  2509. exportEntryList.Clear();
  2510. }
  2511. }
  2512. if (needTerminator != nullptr)
  2513. {
  2514. *needTerminator = true;
  2515. }
  2516. break;
  2517. case tkID:
  2518. {
  2519. IdentPtr pid = m_token.GetIdentifier(m_phtbl);
  2520. if (wellKnownPropertyPids.let == pid)
  2521. {
  2522. declarationType = tkLET;
  2523. goto ParseVarDecl;
  2524. }
  2525. if (wellKnownPropertyPids.async == pid && m_scriptContext->GetConfig()->IsES7AsyncAndAwaitEnabled())
  2526. {
  2527. // In module export statements, async token is only valid if it's followed by function.
  2528. // We need to check here because ParseStatement would think 'async = 20' is a var decl.
  2529. RestorePoint parsedAsync;
  2530. m_pscan->Capture(&parsedAsync);
  2531. m_pscan->Scan();
  2532. if (m_token.tk == tkFUNCTION)
  2533. {
  2534. // Token after async is function, rewind to the async token and let ParseStatement handle it.
  2535. m_pscan->SeekTo(parsedAsync);
  2536. goto ParseFunctionDecl;
  2537. }
  2538. // Token after async is not function, it's a syntax error.
  2539. }
  2540. goto ErrorToken;
  2541. }
  2542. case tkVAR:
  2543. case tkLET:
  2544. case tkCONST:
  2545. {
  2546. declarationType = m_token.tk;
  2547. ParseVarDecl:
  2548. m_pscan->Scan();
  2549. pnode = ParseVariableDeclaration<buildAST>(declarationType, m_pscan->IchMinTok());
  2550. if (buildAST)
  2551. {
  2552. ParseNodePtr temp = pnode;
  2553. while (temp->nop == knopList)
  2554. {
  2555. ParseNodePtr varDeclNode = temp->sxBin.pnode1;
  2556. temp = temp->sxBin.pnode2;
  2557. AddModuleLocalExportEntry(varDeclNode);
  2558. }
  2559. AddModuleLocalExportEntry(temp);
  2560. }
  2561. }
  2562. break;
  2563. case tkFUNCTION:
  2564. case tkCLASS:
  2565. {
  2566. ParseFunctionDecl:
  2567. pnode = ParseStatement<buildAST>();
  2568. if (buildAST)
  2569. {
  2570. IdentPtr localName;
  2571. if (pnode->nop == knopClassDecl)
  2572. {
  2573. pnode->sxClass.pnodeName->sxVar.sym->SetIsModuleExportStorage(true);
  2574. pnode->sxClass.pnodeDeclName->sxVar.sym->SetIsModuleExportStorage(true);
  2575. localName = pnode->sxClass.pnodeName->sxVar.pid;
  2576. }
  2577. else
  2578. {
  2579. Assert(pnode->nop == knopFncDecl);
  2580. pnode->sxFnc.GetFuncSymbol()->SetIsModuleExportStorage(true);
  2581. localName = pnode->sxFnc.pid;
  2582. }
  2583. Assert(localName != nullptr);
  2584. AddModuleImportOrExportEntry(EnsureModuleLocalExportEntryList(), nullptr, localName, localName, nullptr);
  2585. }
  2586. }
  2587. break;
  2588. case tkDEFAULT:
  2589. {
  2590. pnode = ParseDefaultExportClause<buildAST>();
  2591. }
  2592. break;
  2593. default:
  2594. {
  2595. ErrorToken:
  2596. Error(ERRsyntax);
  2597. }
  2598. }
  2599. return pnode;
  2600. }
  2601. /***************************************************************************
  2602. Parse an expression term.
  2603. ***************************************************************************/
  2604. template<bool buildAST>
  2605. ParseNodePtr Parser::ParseTerm(BOOL fAllowCall,
  2606. LPCOLESTR pNameHint,
  2607. uint32 *pHintLength,
  2608. uint32 *pShortNameOffset,
  2609. _Inout_opt_ IdentToken* pToken /*= nullptr*/,
  2610. bool fUnaryOrParen /*= false*/,
  2611. _Out_opt_ BOOL* pfCanAssign /*= nullptr*/,
  2612. _Inout_opt_ BOOL* pfLikelyPattern /*= nullptr*/,
  2613. _Out_opt_ bool* pfIsDotOrIndex /*= nullptr*/,
  2614. _Inout_opt_ charcount_t *plastRParen /*= nullptr*/)
  2615. {
  2616. ParseNodePtr pnode = nullptr;
  2617. PidRefStack *savedTopAsyncRef = nullptr;
  2618. charcount_t ichMin = 0;
  2619. charcount_t ichLim = 0;
  2620. size_t iecpMin = 0;
  2621. size_t iecpLim = 0;
  2622. size_t iuMin;
  2623. IdentToken term;
  2624. BOOL fInNew = FALSE;
  2625. BOOL fCanAssign = TRUE;
  2626. bool isAsyncExpr = false;
  2627. bool isLambdaExpr = false;
  2628. bool isSpecialName = false;
  2629. IdentPtr pid = nullptr;
  2630. Assert(pToken == nullptr || pToken->tk == tkNone); // Must be empty initially
  2631. PROBE_STACK_NO_DISPOSE(m_scriptContext, Js::Constants::MinStackParseOneTerm);
  2632. switch (m_token.tk)
  2633. {
  2634. case tkID:
  2635. {
  2636. pid = m_token.GetIdentifier(m_phtbl);
  2637. ichMin = m_pscan->IchMinTok();
  2638. iecpMin = m_pscan->IecpMinTok();
  2639. ichLim = m_pscan->IchLimTok();
  2640. iecpLim = m_pscan->IecpLimTok();
  2641. if (pid == wellKnownPropertyPids.async &&
  2642. m_scriptContext->GetConfig()->IsES7AsyncAndAwaitEnabled())
  2643. {
  2644. isAsyncExpr = true;
  2645. }
  2646. // Put this into a block to avoid previousAwaitIsKeyword being not initialized after jump to LIdentifier
  2647. {
  2648. bool previousAwaitIsKeyword = m_pscan->SetAwaitIsKeywordRegion(isAsyncExpr);
  2649. m_pscan->Scan();
  2650. m_pscan->SetAwaitIsKeywordRegion(previousAwaitIsKeyword);
  2651. }
  2652. // We search for an Async expression (a function declaration or an async lambda expression)
  2653. if (isAsyncExpr && !m_pscan->FHadNewLine())
  2654. {
  2655. if (m_token.tk == tkFUNCTION)
  2656. {
  2657. goto LFunction;
  2658. }
  2659. else if (m_token.tk == tkID || m_token.tk == tkAWAIT)
  2660. {
  2661. isLambdaExpr = true;
  2662. goto LFunction;
  2663. }
  2664. else if (m_token.tk == tkLParen)
  2665. {
  2666. // This is potentially an async arrow function. Save the state of the async references
  2667. // in case it needs to be restored. (Note that the case of a single parameter with no ()'s
  2668. // is detected upstream and need not be handled here.)
  2669. savedTopAsyncRef = pid->GetTopRef();
  2670. }
  2671. }
  2672. CheckArgumentsUse(pid, GetCurrentFunctionNode());
  2673. // Assume this pid is not special - overwrite when we parse a special name
  2674. isSpecialName = false;
  2675. LIdentifier:
  2676. PidRefStack *ref = nullptr;
  2677. // Don't push a reference if this is a single lambda parameter, because we'll reparse with
  2678. // a correct function ID.
  2679. if (m_token.tk != tkDArrow)
  2680. {
  2681. ref = this->PushPidRef(pid);
  2682. }
  2683. if (buildAST)
  2684. {
  2685. if (isSpecialName)
  2686. {
  2687. pnode = CreateSpecialNameNode(pid);
  2688. if (pid == wellKnownPropertyPids._super ||
  2689. pid == wellKnownPropertyPids._superConstructor)
  2690. {
  2691. pnode->sxSpecialName.isSuper = true;
  2692. }
  2693. else if (pid == wellKnownPropertyPids._this)
  2694. {
  2695. pnode->sxSpecialName.isThis = true;
  2696. }
  2697. }
  2698. else
  2699. {
  2700. pnode = CreateNameNode(pid);
  2701. }
  2702. pnode->ichMin = ichMin;
  2703. pnode->ichLim = ichLim;
  2704. pnode->sxPid.SetSymRef(ref);
  2705. }
  2706. else
  2707. {
  2708. // Remember the identifier start and end in case it turns out to be a statement label.
  2709. term.tk = tkID;
  2710. term.pid = pid; // Record the identifier for detection of eval
  2711. term.ichMin = static_cast<charcount_t>(iecpMin);
  2712. term.ichLim = static_cast<charcount_t>(iecpLim);
  2713. }
  2714. break;
  2715. }
  2716. case tkSUPER:
  2717. ichMin = m_pscan->IchMinTok();
  2718. iecpMin = m_pscan->IecpMinTok();
  2719. ichLim = m_pscan->IchLimTok();
  2720. iecpLim = m_pscan->IecpLimTok();
  2721. if (!m_scriptContext->GetConfig()->IsES6ClassAndExtendsEnabled())
  2722. {
  2723. goto LUnknown;
  2724. }
  2725. m_pscan->Scan();
  2726. pid = ParseSuper<buildAST>(!!fAllowCall);
  2727. isSpecialName = true;
  2728. goto LIdentifier;
  2729. case tkTHIS:
  2730. ichMin = m_pscan->IchMinTok();
  2731. iecpMin = m_pscan->IecpMinTok();
  2732. ichLim = m_pscan->IchLimTok();
  2733. iecpLim = m_pscan->IecpLimTok();
  2734. pid = wellKnownPropertyPids._this;
  2735. m_pscan->Scan();
  2736. isSpecialName = true;
  2737. goto LIdentifier;
  2738. case tkLParen:
  2739. {
  2740. ichMin = m_pscan->IchMinTok();
  2741. iuMin = m_pscan->IecpMinTok();
  2742. m_pscan->Scan();
  2743. if (m_token.tk == tkRParen)
  2744. {
  2745. // Empty parens can only be legal as an empty parameter list to a lambda declaration.
  2746. // We're in a lambda if the next token is =>.
  2747. fAllowCall = FALSE;
  2748. m_pscan->Scan();
  2749. // If the token after the right paren is not => or if there was a newline between () and => this is a syntax error
  2750. if (!IsDoingFastScan() && (m_token.tk != tkDArrow || m_pscan->FHadNewLine()))
  2751. {
  2752. Error(ERRsyntax);
  2753. }
  2754. if (buildAST)
  2755. {
  2756. pnode = CreateNodeWithScanner<knopEmpty>();
  2757. }
  2758. break;
  2759. }
  2760. // Advance the block ID here in case this parenthetical expression turns out to be a lambda parameter list.
  2761. // That way the pid ref stacks will be created in their correct final form, and we can simply fix
  2762. // up function ID's.
  2763. uint saveNextBlockId = m_nextBlockId;
  2764. uint saveCurrBlockId = GetCurrentBlock()->sxBlock.blockId;
  2765. GetCurrentBlock()->sxBlock.blockId = m_nextBlockId++;
  2766. // Push the deferred error state for ellipsis errors. It is possible that another syntax error will occur before we undefer this one.
  2767. bool deferEllipsisErrorSave = m_deferEllipsisError;
  2768. RestorePoint ellipsisErrorLocSave = m_deferEllipsisErrorLoc;
  2769. this->m_funcParenExprDepth++;
  2770. pnode = ParseExpr<buildAST>(koplNo, &fCanAssign, TRUE, FALSE, nullptr, nullptr /*nameLength*/, nullptr /*pShortNameOffset*/, &term, true, nullptr, plastRParen);
  2771. this->m_funcParenExprDepth--;
  2772. if (buildAST && plastRParen)
  2773. {
  2774. *plastRParen = m_pscan->IchLimTok();
  2775. }
  2776. ChkCurTok(tkRParen, ERRnoRparen);
  2777. GetCurrentBlock()->sxBlock.blockId = saveCurrBlockId;
  2778. if (m_token.tk == tkDArrow)
  2779. {
  2780. // We're going to rewind and reinterpret the expression as a parameter list.
  2781. // Put back the original next-block-ID so the existing pid ref stacks will be correct.
  2782. m_nextBlockId = saveNextBlockId;
  2783. }
  2784. // Emit a deferred ... error if one was parsed.
  2785. if (m_deferEllipsisError && m_token.tk != tkDArrow)
  2786. {
  2787. m_pscan->SeekTo(m_deferEllipsisErrorLoc);
  2788. Error(ERRInvalidSpreadUse);
  2789. }
  2790. else
  2791. {
  2792. m_deferEllipsisError = false;
  2793. }
  2794. // We didn't error out, so restore the deferred error state.
  2795. m_deferEllipsisError = deferEllipsisErrorSave;
  2796. m_deferEllipsisErrorLoc = ellipsisErrorLocSave;
  2797. break;
  2798. }
  2799. case tkIntCon:
  2800. if (IsStrictMode() && m_pscan->IsOctOrLeadingZeroOnLastTKNumber())
  2801. {
  2802. Error(ERRES5NoOctal);
  2803. }
  2804. if (buildAST)
  2805. {
  2806. pnode = CreateIntNodeWithScanner(m_token.GetLong());
  2807. }
  2808. fCanAssign = FALSE;
  2809. m_pscan->Scan();
  2810. break;
  2811. case tkFltCon:
  2812. if (IsStrictMode() && m_pscan->IsOctOrLeadingZeroOnLastTKNumber())
  2813. {
  2814. Error(ERRES5NoOctal);
  2815. }
  2816. if (buildAST)
  2817. {
  2818. pnode = CreateNodeWithScanner<knopFlt>();
  2819. pnode->sxFlt.dbl = m_token.GetDouble();
  2820. pnode->sxFlt.maybeInt = m_token.GetDoubleMayBeInt();
  2821. }
  2822. fCanAssign = FALSE;
  2823. m_pscan->Scan();
  2824. break;
  2825. case tkStrCon:
  2826. if (IsStrictMode() && m_pscan->IsOctOrLeadingZeroOnLastTKNumber())
  2827. {
  2828. Error(ERRES5NoOctal);
  2829. }
  2830. if (buildAST)
  2831. {
  2832. pnode = CreateStrNodeWithScanner(m_token.GetStr());
  2833. }
  2834. else
  2835. {
  2836. // Subtract the string literal length from the total char count for the purpose
  2837. // of deciding whether to defer parsing and byte code generation.
  2838. this->ReduceDeferredScriptLength(m_pscan->IchLimTok() - m_pscan->IchMinTok());
  2839. }
  2840. fCanAssign = FALSE;
  2841. m_pscan->Scan();
  2842. break;
  2843. case tkTRUE:
  2844. if (buildAST)
  2845. {
  2846. pnode = CreateNodeWithScanner<knopTrue>();
  2847. }
  2848. fCanAssign = FALSE;
  2849. m_pscan->Scan();
  2850. break;
  2851. case tkFALSE:
  2852. if (buildAST)
  2853. {
  2854. pnode = CreateNodeWithScanner<knopFalse>();
  2855. }
  2856. fCanAssign = FALSE;
  2857. m_pscan->Scan();
  2858. break;
  2859. case tkNULL:
  2860. if (buildAST)
  2861. {
  2862. pnode = CreateNodeWithScanner<knopNull>();
  2863. }
  2864. fCanAssign = FALSE;
  2865. m_pscan->Scan();
  2866. break;
  2867. case tkDiv:
  2868. case tkAsgDiv:
  2869. pnode = ParseRegExp<buildAST>();
  2870. fCanAssign = FALSE;
  2871. m_pscan->Scan();
  2872. break;
  2873. case tkNEW:
  2874. {
  2875. ichMin = m_pscan->IchMinTok();
  2876. iecpMin = m_pscan->IecpMinTok();
  2877. m_pscan->Scan();
  2878. if (m_token.tk == tkDot && m_scriptContext->GetConfig()->IsES6ClassAndExtendsEnabled())
  2879. {
  2880. pid = ParseMetaProperty<buildAST>(tkNEW, ichMin, &fCanAssign);
  2881. ichLim = m_pscan->IchLimTok();
  2882. iecpLim = m_pscan->IecpLimTok();
  2883. m_pscan->Scan();
  2884. isSpecialName = true;
  2885. goto LIdentifier;
  2886. }
  2887. else
  2888. {
  2889. ParseNodePtr pnodeExpr = ParseTerm<buildAST>(FALSE, pNameHint, pHintLength, pShortNameOffset, nullptr, false, nullptr, nullptr, nullptr, plastRParen);
  2890. if (buildAST)
  2891. {
  2892. pnode = CreateCallNode(knopNew, pnodeExpr, nullptr);
  2893. pnode->ichMin = ichMin;
  2894. }
  2895. fInNew = TRUE;
  2896. fCanAssign = FALSE;
  2897. }
  2898. break;
  2899. }
  2900. case tkLBrack:
  2901. {
  2902. ichMin = m_pscan->IchMinTok();
  2903. m_pscan->Scan();
  2904. pnode = ParseArrayLiteral<buildAST>();
  2905. if (buildAST)
  2906. {
  2907. pnode->ichMin = ichMin;
  2908. pnode->ichLim = m_pscan->IchLimTok();
  2909. }
  2910. if (this->m_arrayDepth == 0)
  2911. {
  2912. Assert(m_pscan->IchLimTok() - ichMin > m_funcInArray);
  2913. this->ReduceDeferredScriptLength(m_pscan->IchLimTok() - ichMin - this->m_funcInArray);
  2914. this->m_funcInArray = 0;
  2915. this->m_funcInArrayDepth = 0;
  2916. }
  2917. ChkCurTok(tkRBrack, ERRnoRbrack);
  2918. if (!IsES6DestructuringEnabled())
  2919. {
  2920. fCanAssign = FALSE;
  2921. }
  2922. else if (pfLikelyPattern != nullptr && !IsPostFixOperators())
  2923. {
  2924. *pfLikelyPattern = TRUE;
  2925. }
  2926. break;
  2927. }
  2928. case tkLCurly:
  2929. {
  2930. ichMin = m_pscan->IchMinTok();
  2931. m_pscan->ScanForcingPid();
  2932. ParseNodePtr pnodeMemberList = ParseMemberList<buildAST>(pNameHint, pHintLength);
  2933. if (buildAST)
  2934. {
  2935. pnode = CreateUniNode(knopObject, pnodeMemberList);
  2936. pnode->ichMin = ichMin;
  2937. pnode->ichLim = m_pscan->IchLimTok();
  2938. }
  2939. ChkCurTok(tkRCurly, ERRnoRcurly);
  2940. if (!IsES6DestructuringEnabled())
  2941. {
  2942. fCanAssign = FALSE;
  2943. }
  2944. else if (pfLikelyPattern != nullptr && !IsPostFixOperators())
  2945. {
  2946. *pfLikelyPattern = TRUE;
  2947. }
  2948. break;
  2949. }
  2950. case tkFUNCTION:
  2951. {
  2952. LFunction :
  2953. if (m_grfscr & fscrDeferredFncExpression)
  2954. {
  2955. // The top-level deferred function body was defined by a function expression whose parsing was deferred. We are now
  2956. // parsing it, so unset the flag so that any nested functions are parsed normally. This flag is only applicable the
  2957. // first time we see it.
  2958. //
  2959. // Normally, deferred functions will be parsed in ParseStatement upon encountering the 'function' token. The first
  2960. // token of the source code of the function may not a 'function' token though, so we still need to reset this flag
  2961. // for the first function we parse. This can happen in compat modes, for instance, for a function expression enclosed
  2962. // in parentheses, where the legacy behavior was to include the parentheses in the function's source code.
  2963. m_grfscr &= ~fscrDeferredFncExpression;
  2964. }
  2965. ushort flags = fFncNoFlgs;
  2966. if (isLambdaExpr)
  2967. {
  2968. flags |= fFncLambda;
  2969. }
  2970. if (isAsyncExpr)
  2971. {
  2972. flags |= fFncAsync;
  2973. }
  2974. pnode = ParseFncDecl<buildAST>(flags, pNameHint, false, true, fUnaryOrParen);
  2975. if (isAsyncExpr)
  2976. {
  2977. pnode->sxFnc.cbMin = iecpMin;
  2978. pnode->ichMin = ichMin;
  2979. }
  2980. fCanAssign = FALSE;
  2981. break;
  2982. }
  2983. case tkCLASS:
  2984. if (m_scriptContext->GetConfig()->IsES6ClassAndExtendsEnabled())
  2985. {
  2986. pnode = ParseClassDecl<buildAST>(FALSE, pNameHint, pHintLength, pShortNameOffset);
  2987. }
  2988. else
  2989. {
  2990. goto LUnknown;
  2991. }
  2992. fCanAssign = FALSE;
  2993. break;
  2994. case tkStrTmplBasic:
  2995. case tkStrTmplBegin:
  2996. pnode = ParseStringTemplateDecl<buildAST>(nullptr);
  2997. fCanAssign = FALSE;
  2998. break;
  2999. case tkIMPORT:
  3000. if (m_scriptContext->GetConfig()->IsES6ModuleEnabled())
  3001. {
  3002. m_pscan->Scan();
  3003. ChkCurTokNoScan(tkLParen, ERRnoLparen);
  3004. pnode = ParseImportCall<buildAST>();
  3005. }
  3006. else
  3007. {
  3008. goto LUnknown;
  3009. }
  3010. break;
  3011. #if ENABLE_BACKGROUND_PARSING
  3012. case tkCASE:
  3013. {
  3014. if (!m_doingFastScan)
  3015. {
  3016. goto LUnknown;
  3017. }
  3018. ParseNodePtr pnodeUnused;
  3019. pnode = ParseCase<buildAST>(&pnodeUnused);
  3020. break;
  3021. }
  3022. case tkELSE:
  3023. if (!m_doingFastScan)
  3024. {
  3025. goto LUnknown;
  3026. }
  3027. m_pscan->Scan();
  3028. ParseStatement<buildAST>();
  3029. break;
  3030. #endif
  3031. default:
  3032. LUnknown :
  3033. Error(ERRsyntax);
  3034. break;
  3035. }
  3036. pnode = ParsePostfixOperators<buildAST>(pnode, fAllowCall, fInNew, isAsyncExpr, &fCanAssign, &term, pfIsDotOrIndex);
  3037. if (savedTopAsyncRef != nullptr &&
  3038. this->m_token.tk == tkDArrow)
  3039. {
  3040. // This is an async arrow function; we're going to back up and reparse it.
  3041. // Make sure we don't leave behind a bogus reference to the 'async' identifier.
  3042. for (pid = wellKnownPropertyPids.async; pid->GetTopRef() != savedTopAsyncRef;)
  3043. {
  3044. Assert(pid->GetTopRef() != nullptr);
  3045. pid->RemovePrevPidRef(nullptr);
  3046. }
  3047. }
  3048. // Pass back identifier if requested
  3049. if (pToken && term.tk == tkID)
  3050. {
  3051. *pToken = term;
  3052. }
  3053. if (pfCanAssign)
  3054. {
  3055. *pfCanAssign = fCanAssign;
  3056. }
  3057. return pnode;
  3058. }
  3059. template <bool buildAST>
  3060. ParseNodePtr Parser::ParseRegExp()
  3061. {
  3062. ParseNodePtr pnode = nullptr;
  3063. if (buildAST || IsDoingFastScan())
  3064. {
  3065. m_pscan->RescanRegExp();
  3066. #if ENABLE_BACKGROUND_PARSING
  3067. BOOL saveDeferringAST = this->m_deferringAST;
  3068. if (m_doingFastScan)
  3069. {
  3070. this->m_deferringAST = false;
  3071. }
  3072. #endif
  3073. pnode = CreateNodeWithScanner<knopRegExp>();
  3074. pnode->sxPid.regexPattern = m_token.GetRegex();
  3075. #if ENABLE_BACKGROUND_PARSING
  3076. if (m_doingFastScan)
  3077. {
  3078. this->m_deferringAST = saveDeferringAST;
  3079. this->AddFastScannedRegExpNode(pnode);
  3080. if (!buildAST)
  3081. {
  3082. pnode = nullptr;
  3083. }
  3084. }
  3085. else if (this->IsBackgroundParser())
  3086. {
  3087. Assert(pnode->sxPid.regexPattern == nullptr);
  3088. this->AddBackgroundRegExpNode(pnode);
  3089. }
  3090. #endif
  3091. }
  3092. else
  3093. {
  3094. m_pscan->RescanRegExpNoAST();
  3095. }
  3096. Assert(m_token.tk == tkRegExp);
  3097. return pnode;
  3098. }
  3099. BOOL Parser::NodeIsEvalName(ParseNodePtr pnode)
  3100. {
  3101. //WOOB 1107758 Special case of indirect eval binds to local scope in standards mode
  3102. return pnode->nop == knopName && (pnode->sxPid.pid == wellKnownPropertyPids.eval);
  3103. }
  3104. BOOL Parser::NodeIsSuperName(ParseNodePtr pnode)
  3105. {
  3106. return pnode->nop == knopName && (pnode->sxPid.pid == wellKnownPropertyPids._superConstructor);
  3107. }
  3108. BOOL Parser::NodeEqualsName(ParseNodePtr pnode, LPCOLESTR sz, uint32 cch)
  3109. {
  3110. return pnode->nop == knopName &&
  3111. pnode->sxPid.pid->Cch() == cch &&
  3112. !wmemcmp(pnode->sxPid.pid->Psz(), sz, cch);
  3113. }
  3114. BOOL Parser::NodeIsIdent(ParseNodePtr pnode, IdentPtr pid)
  3115. {
  3116. for (;;)
  3117. {
  3118. switch (pnode->nop)
  3119. {
  3120. case knopName:
  3121. return (pnode->sxPid.pid == pid);
  3122. case knopComma:
  3123. pnode = pnode->sxBin.pnode2;
  3124. break;
  3125. default:
  3126. return FALSE;
  3127. }
  3128. }
  3129. }
  3130. template<bool buildAST>
  3131. ParseNodePtr Parser::ParsePostfixOperators(
  3132. ParseNodePtr pnode,
  3133. BOOL fAllowCall,
  3134. BOOL fInNew,
  3135. BOOL isAsyncExpr,
  3136. BOOL *pfCanAssign,
  3137. _Inout_ IdentToken* pToken,
  3138. _Out_opt_ bool* pfIsDotOrIndex /*= nullptr */)
  3139. {
  3140. uint16 count = 0;
  3141. bool callOfConstants = false;
  3142. if (pfIsDotOrIndex)
  3143. {
  3144. *pfIsDotOrIndex = false;
  3145. }
  3146. for (;;)
  3147. {
  3148. uint16 spreadArgCount = 0;
  3149. switch (m_token.tk)
  3150. {
  3151. case tkLParen:
  3152. {
  3153. AutoMarkInParsingArgs autoMarkInParsingArgs(this);
  3154. if (fInNew)
  3155. {
  3156. ParseNodePtr pnodeArgs = ParseArgList<buildAST>(&callOfConstants, &spreadArgCount, &count);
  3157. if (buildAST)
  3158. {
  3159. Assert(pnode->nop == knopNew);
  3160. Assert(pnode->sxCall.pnodeArgs == nullptr);
  3161. pnode->sxCall.pnodeArgs = pnodeArgs;
  3162. pnode->sxCall.callOfConstants = callOfConstants;
  3163. pnode->sxCall.isApplyCall = false;
  3164. pnode->sxCall.isEvalCall = false;
  3165. pnode->sxCall.isSuperCall = false;
  3166. pnode->sxCall.hasDestructuring = m_hasDestructuringPattern;
  3167. Assert(!m_hasDestructuringPattern || count > 0);
  3168. pnode->sxCall.argCount = count;
  3169. pnode->sxCall.spreadArgCount = spreadArgCount;
  3170. pnode->ichLim = m_pscan->IchLimTok();
  3171. }
  3172. else
  3173. {
  3174. pnode = nullptr;
  3175. pToken->tk = tkNone; // This is no longer an identifier
  3176. }
  3177. fInNew = FALSE;
  3178. ChkCurTok(tkRParen, ERRnoRparen);
  3179. }
  3180. else
  3181. {
  3182. bool fCallIsEval = false;
  3183. if (!fAllowCall)
  3184. {
  3185. return pnode;
  3186. }
  3187. uint saveNextBlockId = m_nextBlockId;
  3188. uint saveCurrBlockId = GetCurrentBlock()->sxBlock.blockId;
  3189. if (isAsyncExpr)
  3190. {
  3191. // Advance the block ID here in case this parenthetical expression turns out to be a lambda parameter list.
  3192. // That way the pid ref stacks will be created in their correct final form, and we can simply fix
  3193. // up function ID's.
  3194. GetCurrentBlock()->sxBlock.blockId = m_nextBlockId++;
  3195. }
  3196. ParseNodePtr pnodeArgs = ParseArgList<buildAST>(&callOfConstants, &spreadArgCount, &count);
  3197. // We used to un-defer a deferred function body here if it was called as part of the expression that declared it.
  3198. // We now detect this case up front in ParseFncDecl, which is cheaper and simpler.
  3199. if (buildAST)
  3200. {
  3201. // Detect super()
  3202. if (this->NodeIsSuperName(pnode))
  3203. {
  3204. pnode = CreateSuperCallNode(pnode, pnodeArgs);
  3205. Assert(pnode);
  3206. pnode->sxSuperCall.pnodeThis = ReferenceSpecialName(wellKnownPropertyPids._this, pnode->ichMin, m_pscan->IchLimTok(), true);
  3207. pnode->sxSuperCall.pnodeNewTarget = ReferenceSpecialName(wellKnownPropertyPids._newTarget, pnode->ichMin, m_pscan->IchLimTok(), true);
  3208. }
  3209. else
  3210. {
  3211. pnode = CreateCallNode(knopCall, pnode, pnodeArgs);
  3212. Assert(pnode);
  3213. }
  3214. // Detect call to "eval" and record it on the function.
  3215. // Note: we used to leave it up to the byte code generator to detect eval calls
  3216. // at global scope, but now it relies on the flag the parser sets, so set it here.
  3217. if (count > 0 && this->NodeIsEvalName(pnode->sxCall.pnodeTarget))
  3218. {
  3219. this->MarkEvalCaller();
  3220. fCallIsEval = true;
  3221. // Eval may reference any of the special symbols so we need to push refs to them here.
  3222. ReferenceSpecialName(wellKnownPropertyPids._this);
  3223. ReferenceSpecialName(wellKnownPropertyPids._newTarget);
  3224. ReferenceSpecialName(wellKnownPropertyPids._super);
  3225. ReferenceSpecialName(wellKnownPropertyPids._superConstructor);
  3226. }
  3227. pnode->sxCall.callOfConstants = callOfConstants;
  3228. pnode->sxCall.spreadArgCount = spreadArgCount;
  3229. pnode->sxCall.isApplyCall = false;
  3230. pnode->sxCall.isEvalCall = fCallIsEval;
  3231. pnode->sxCall.hasDestructuring = m_hasDestructuringPattern;
  3232. Assert(!m_hasDestructuringPattern || count > 0);
  3233. pnode->sxCall.argCount = count;
  3234. pnode->ichLim = m_pscan->IchLimTok();
  3235. }
  3236. else
  3237. {
  3238. pnode = nullptr;
  3239. if (pToken->tk == tkID && pToken->pid == wellKnownPropertyPids.eval && count > 0) // Detect eval
  3240. {
  3241. this->MarkEvalCaller();
  3242. ReferenceSpecialName(wellKnownPropertyPids._this);
  3243. ReferenceSpecialName(wellKnownPropertyPids._newTarget);
  3244. ReferenceSpecialName(wellKnownPropertyPids._super);
  3245. ReferenceSpecialName(wellKnownPropertyPids._superConstructor);
  3246. }
  3247. pToken->tk = tkNone; // This is no longer an identifier
  3248. }
  3249. ChkCurTok(tkRParen, ERRnoRparen);
  3250. if (isAsyncExpr)
  3251. {
  3252. GetCurrentBlock()->sxBlock.blockId = saveCurrBlockId;
  3253. if (m_token.tk == tkDArrow)
  3254. {
  3255. // We're going to rewind and reinterpret the expression as a parameter list.
  3256. // Put back the original next-block-ID so the existing pid ref stacks will be correct.
  3257. m_nextBlockId = saveNextBlockId;
  3258. }
  3259. }
  3260. }
  3261. if (pfCanAssign)
  3262. {
  3263. *pfCanAssign = FALSE;
  3264. }
  3265. if (pfIsDotOrIndex)
  3266. {
  3267. *pfIsDotOrIndex = false;
  3268. }
  3269. break;
  3270. }
  3271. case tkLBrack:
  3272. {
  3273. m_pscan->Scan();
  3274. IdentToken tok;
  3275. ParseNodePtr pnodeExpr = ParseExpr<buildAST>(0, FALSE, TRUE, FALSE, nullptr, nullptr, nullptr, &tok);
  3276. if (buildAST)
  3277. {
  3278. if (pnode && pnode->isSpecialName && pnode->sxSpecialName.isSuper)
  3279. {
  3280. pnode = CreateSuperReferenceNode(knopIndex, pnode, pnodeExpr);
  3281. pnode->sxSuperReference.pnodeThis = ReferenceSpecialName(wellKnownPropertyPids._this, pnode->ichMin, pnode->ichLim, true);
  3282. }
  3283. else
  3284. {
  3285. pnode = CreateBinNode(knopIndex, pnode, pnodeExpr);
  3286. }
  3287. AnalysisAssert(pnode);
  3288. pnode->ichLim = m_pscan->IchLimTok();
  3289. }
  3290. else
  3291. {
  3292. pnode = nullptr;
  3293. pToken->tk = tkNone; // This is no longer an identifier
  3294. }
  3295. ChkCurTok(tkRBrack, ERRnoRbrack);
  3296. if (pfCanAssign)
  3297. {
  3298. *pfCanAssign = TRUE;
  3299. }
  3300. if (pfIsDotOrIndex)
  3301. {
  3302. *pfIsDotOrIndex = true;
  3303. }
  3304. PidRefStack * topPidRef = nullptr;
  3305. if (buildAST)
  3306. {
  3307. if (pnodeExpr && pnodeExpr->nop == knopName)
  3308. {
  3309. topPidRef = pnodeExpr->sxPid.pid->GetTopRef();
  3310. }
  3311. }
  3312. else if (tok.tk == tkID)
  3313. {
  3314. topPidRef = tok.pid->GetTopRef();
  3315. }
  3316. if (topPidRef)
  3317. {
  3318. topPidRef->SetIsUsedInLdElem(true);
  3319. }
  3320. if (!buildAST)
  3321. {
  3322. break;
  3323. }
  3324. bool shouldConvertToDot = false;
  3325. if (pnode->sxBin.pnode2->nop == knopStr)
  3326. {
  3327. // if the string is empty or contains escape character, we will not convert them to dot node
  3328. shouldConvertToDot = pnode->sxBin.pnode2->sxPid.pid->Cch() > 0 && !m_pscan->IsEscapeOnLastTkStrCon();
  3329. }
  3330. if (shouldConvertToDot)
  3331. {
  3332. LPCOLESTR str = pnode->sxBin.pnode2->sxPid.pid->Psz();
  3333. // See if we can convert o["p"] into o.p and o["0"] into o[0] since they're equivalent and the latter forms
  3334. // are faster
  3335. uint32 uintValue;
  3336. if(Js::JavascriptOperators::TryConvertToUInt32(
  3337. str,
  3338. pnode->sxBin.pnode2->sxPid.pid->Cch(),
  3339. &uintValue) &&
  3340. !Js::TaggedInt::IsOverflow(uintValue)) // the optimization is not very useful if the number can't be represented as a TaggedInt
  3341. {
  3342. // No need to verify that uintValue != JavascriptArray::InvalidIndex since all nonnegative TaggedInts are valid indexes
  3343. auto intNode = CreateIntNodeWithScanner(uintValue); // implicit conversion from uint32 to int32
  3344. pnode->sxBin.pnode2 = intNode;
  3345. }
  3346. // Field optimization (see GlobOpt::KillLiveElems) checks for value being a Number,
  3347. // and since NaN/Infinity is a number it won't kill o.NaN/o.Infinity which would cause a problem
  3348. // if we decide to hoist o.NaN/o.Infinity.
  3349. // We need to keep o["NaN"] and o["+/-Infinity"] as array element access (we don't hoist that but we may hoist field access),
  3350. // so no matter if it's killed by o[x] inside a loop, we make sure that we never hoist these.
  3351. // We need to follow same logic for strings that convert to a floating point number.
  3352. else
  3353. {
  3354. bool doConvertToProperty = false; // Convert a["x"] -> a.x.
  3355. if (!Parser::IsNaNOrInfinityLiteral<true>(str))
  3356. {
  3357. const OLECHAR* terminalChar;
  3358. double dbl = Js::NumberUtilities::StrToDbl(str, &terminalChar, m_scriptContext);
  3359. bool convertsToFloat = !Js::NumberUtilities::IsNan(dbl);
  3360. doConvertToProperty = !convertsToFloat;
  3361. }
  3362. if (doConvertToProperty)
  3363. {
  3364. pnode->sxBin.pnode2->nop = knopName;
  3365. pnode->nop = knopDot;
  3366. pnode->grfpn |= PNodeFlags::fpnIndexOperator;
  3367. }
  3368. }
  3369. }
  3370. }
  3371. break;
  3372. case tkDot:
  3373. {
  3374. ParseNodePtr name = nullptr;
  3375. OpCode opCode = knopDot;
  3376. m_pscan->Scan();
  3377. if (!m_token.IsIdentifier())
  3378. {
  3379. //allow reserved words in ES5 mode
  3380. if (!(m_token.IsReservedWord()))
  3381. {
  3382. IdentifierExpectedError(m_token);
  3383. }
  3384. }
  3385. // Note: see comment above about field optimization WRT NaN/Infinity/-Infinity.
  3386. // Convert a.Nan, a.Infinity into a["NaN"], a["Infinity"].
  3387. // We don't care about -Infinity case here because x.-Infinity is invalid in JavaScript.
  3388. // Both NaN and Infinity are identifiers.
  3389. else if (buildAST && Parser::IsNaNOrInfinityLiteral<false>(m_token.GetIdentifier(m_phtbl)->Psz()))
  3390. {
  3391. opCode = knopIndex;
  3392. }
  3393. if (buildAST)
  3394. {
  3395. if (opCode == knopDot)
  3396. {
  3397. name = CreateNameNode(m_token.GetIdentifier(m_phtbl));
  3398. }
  3399. else
  3400. {
  3401. Assert(opCode == knopIndex);
  3402. name = CreateStrNodeWithScanner(m_token.GetIdentifier(m_phtbl));
  3403. }
  3404. if (pnode && pnode->isSpecialName && pnode->sxSpecialName.isSuper)
  3405. {
  3406. pnode = CreateSuperReferenceNode(opCode, pnode, name);
  3407. pnode->sxSuperReference.pnodeThis = ReferenceSpecialName(wellKnownPropertyPids._this, pnode->ichMin, pnode->ichLim, true);
  3408. }
  3409. else
  3410. {
  3411. pnode = CreateBinNode(opCode, pnode, name);
  3412. }
  3413. }
  3414. else
  3415. {
  3416. pnode = nullptr;
  3417. pToken->tk = tkNone;
  3418. }
  3419. if (pfCanAssign)
  3420. {
  3421. *pfCanAssign = TRUE;
  3422. }
  3423. if (pfIsDotOrIndex)
  3424. {
  3425. *pfIsDotOrIndex = true;
  3426. }
  3427. m_pscan->Scan();
  3428. break;
  3429. }
  3430. case tkStrTmplBasic:
  3431. case tkStrTmplBegin:
  3432. {
  3433. ParseNode* templateNode = ParseStringTemplateDecl<buildAST>(pnode);
  3434. if (!buildAST)
  3435. {
  3436. pToken->tk = tkNone; // This is no longer an identifier
  3437. }
  3438. pnode = templateNode;
  3439. if (pfCanAssign)
  3440. {
  3441. *pfCanAssign = FALSE;
  3442. }
  3443. if (pfIsDotOrIndex)
  3444. {
  3445. *pfIsDotOrIndex = false;
  3446. }
  3447. break;
  3448. }
  3449. default:
  3450. return pnode;
  3451. }
  3452. }
  3453. }
  3454. /***************************************************************************
  3455. Look for an existing label with the given name.
  3456. ***************************************************************************/
  3457. ParseNodePtr Parser::PnodeLabel(IdentPtr pid, ParseNodePtr pnodeLabels)
  3458. {
  3459. AssertMem(pid);
  3460. AssertNodeMemN(pnodeLabels);
  3461. StmtNest *pstmt;
  3462. ParseNodePtr pnodeT;
  3463. // Look in the statement stack.
  3464. for (pstmt = m_pstmtCur; nullptr != pstmt; pstmt = pstmt->pstmtOuter)
  3465. {
  3466. AssertNodeMem(pstmt->pnodeStmt);
  3467. AssertNodeMemN(pstmt->pnodeLab);
  3468. for (pnodeT = pstmt->pnodeLab; nullptr != pnodeT;
  3469. pnodeT = pnodeT->sxLabel.pnodeNext)
  3470. {
  3471. Assert(knopLabel == pnodeT->nop);
  3472. if (pid == pnodeT->sxLabel.pid)
  3473. return pnodeT;
  3474. }
  3475. }
  3476. // Also look in the pnodeLabels list.
  3477. for (pnodeT = pnodeLabels; nullptr != pnodeT;
  3478. pnodeT = pnodeT->sxLabel.pnodeNext)
  3479. {
  3480. Assert(knopLabel == pnodeT->nop);
  3481. if (pid == pnodeT->sxLabel.pid)
  3482. return pnodeT;
  3483. }
  3484. return nullptr;
  3485. }
  3486. // Currently only ints and floats are treated as constants in function call
  3487. // TODO: Check if we need for other constants as well
  3488. BOOL Parser::IsConstantInFunctionCall(ParseNodePtr pnode)
  3489. {
  3490. if (pnode->nop == knopInt && !Js::TaggedInt::IsOverflow(pnode->sxInt.lw))
  3491. {
  3492. return TRUE;
  3493. }
  3494. if (pnode->nop == knopFlt)
  3495. {
  3496. return TRUE;
  3497. }
  3498. return FALSE;
  3499. }
  3500. /***************************************************************************
  3501. Parse a list of arguments.
  3502. ***************************************************************************/
  3503. template<bool buildAST>
  3504. ParseNodePtr Parser::ParseArgList( bool *pCallOfConstants, uint16 *pSpreadArgCount, uint16 * pCount)
  3505. {
  3506. ParseNodePtr pnodeArg;
  3507. ParseNodePtr pnodeList = nullptr;
  3508. ParseNodePtr *lastNodeRef = nullptr;
  3509. // Check for an empty list
  3510. Assert(m_token.tk == tkLParen);
  3511. if (m_pscan->Scan() == tkRParen)
  3512. {
  3513. return nullptr;
  3514. }
  3515. *pCallOfConstants = true;
  3516. *pSpreadArgCount = 0;
  3517. int count=0;
  3518. while (true)
  3519. {
  3520. if (count >= Js::Constants::MaxAllowedArgs)
  3521. {
  3522. Error(ERRnoMemory);
  3523. }
  3524. // Allow spread in argument lists.
  3525. IdentToken token;
  3526. pnodeArg = ParseExpr<buildAST>(koplCma, nullptr, TRUE, /* fAllowEllipsis */TRUE, NULL, nullptr, nullptr, &token);
  3527. ++count;
  3528. this->MarkEscapingRef(pnodeArg, &token);
  3529. if (buildAST)
  3530. {
  3531. this->CheckArguments(pnodeArg);
  3532. if (*pCallOfConstants && !IsConstantInFunctionCall(pnodeArg))
  3533. {
  3534. *pCallOfConstants = false;
  3535. }
  3536. if (pnodeArg->nop == knopEllipsis)
  3537. {
  3538. (*pSpreadArgCount)++;
  3539. }
  3540. AddToNodeListEscapedUse(&pnodeList, &lastNodeRef, pnodeArg);
  3541. }
  3542. if (m_token.tk != tkComma)
  3543. {
  3544. break;
  3545. }
  3546. m_pscan->Scan();
  3547. if (m_token.tk == tkRParen && m_scriptContext->GetConfig()->IsES7TrailingCommaEnabled())
  3548. {
  3549. break;
  3550. }
  3551. }
  3552. if (pSpreadArgCount!=nullptr && (*pSpreadArgCount) > 0){
  3553. CHAKRATEL_LANGSTATS_INC_LANGFEATURECOUNT(SpreadFeature, m_scriptContext);
  3554. }
  3555. *pCount = static_cast<uint16>(count);
  3556. if (buildAST)
  3557. {
  3558. AssertMem(lastNodeRef);
  3559. AssertNodeMem(*lastNodeRef);
  3560. pnodeList->ichLim = (*lastNodeRef)->ichLim;
  3561. }
  3562. return pnodeList;
  3563. }
  3564. // Currently only ints are treated as constants in ArrayLiterals
  3565. BOOL Parser::IsConstantInArrayLiteral(ParseNodePtr pnode)
  3566. {
  3567. if (pnode->nop == knopInt && !Js::TaggedInt::IsOverflow(pnode->sxInt.lw))
  3568. {
  3569. return TRUE;
  3570. }
  3571. return FALSE;
  3572. }
  3573. template<bool buildAST>
  3574. ParseNodePtr Parser::ParseArrayLiteral()
  3575. {
  3576. ParseNodePtr pnode = nullptr;
  3577. bool arrayOfTaggedInts = false;
  3578. bool arrayOfInts = false;
  3579. bool arrayOfNumbers = false;
  3580. bool hasMissingValues = false;
  3581. uint count = 0;
  3582. uint spreadCount = 0;
  3583. ParseNodePtr pnode1 = ParseArrayList<buildAST>(&arrayOfTaggedInts, &arrayOfInts, &arrayOfNumbers, &hasMissingValues, &count, &spreadCount);
  3584. if (buildAST)
  3585. {
  3586. pnode = CreateNodeWithScanner<knopArray>();
  3587. pnode->sxArrLit.pnode1 = pnode1;
  3588. pnode->sxArrLit.arrayOfTaggedInts = arrayOfTaggedInts;
  3589. pnode->sxArrLit.arrayOfInts = arrayOfInts;
  3590. pnode->sxArrLit.arrayOfNumbers = arrayOfNumbers;
  3591. pnode->sxArrLit.hasMissingValues = hasMissingValues;
  3592. pnode->sxArrLit.count = count;
  3593. pnode->sxArrLit.spreadCount = spreadCount;
  3594. if (pnode->sxArrLit.pnode1)
  3595. {
  3596. this->CheckArguments(pnode->sxArrLit.pnode1);
  3597. }
  3598. }
  3599. return pnode;
  3600. }
  3601. /***************************************************************************
  3602. Create an ArrayLiteral node
  3603. Parse a list of array elements. [ a, b, , c, ]
  3604. ***************************************************************************/
  3605. template<bool buildAST>
  3606. ParseNodePtr Parser::ParseArrayList(bool *pArrayOfTaggedInts, bool *pArrayOfInts, bool *pArrayOfNumbers, bool *pHasMissingValues, uint *count, uint *spreadCount)
  3607. {
  3608. ParseNodePtr pnodeArg = nullptr;
  3609. ParseNodePtr pnodeList = nullptr;
  3610. ParseNodePtr *lastNodeRef = nullptr;
  3611. *count = 0;
  3612. // Check for an empty list
  3613. if (tkRBrack == m_token.tk)
  3614. {
  3615. return nullptr;
  3616. }
  3617. this->m_arrayDepth++;
  3618. bool arrayOfTaggedInts = buildAST;
  3619. bool arrayOfInts = buildAST;
  3620. bool arrayOfNumbers = buildAST;
  3621. bool arrayOfVarInts = false;
  3622. bool hasMissingValues = false;
  3623. for (;;)
  3624. {
  3625. (*count)++;
  3626. if (tkComma == m_token.tk || tkRBrack == m_token.tk)
  3627. {
  3628. hasMissingValues = true;
  3629. arrayOfTaggedInts = false;
  3630. arrayOfInts = false;
  3631. arrayOfNumbers = false;
  3632. if (buildAST)
  3633. {
  3634. pnodeArg = CreateNodeWithScanner<knopEmpty>();
  3635. }
  3636. }
  3637. else
  3638. {
  3639. // Allow Spread in array literals.
  3640. pnodeArg = ParseExpr<buildAST>(koplCma, nullptr, TRUE, /* fAllowEllipsis */ TRUE);
  3641. if (buildAST)
  3642. {
  3643. if (pnodeArg->nop == knopEllipsis)
  3644. {
  3645. (*spreadCount)++;
  3646. }
  3647. this->CheckArguments(pnodeArg);
  3648. }
  3649. }
  3650. #if DEBUG
  3651. if(m_grfscr & fscrEnforceJSON && !IsJSONValid(pnodeArg))
  3652. {
  3653. Error(ERRsyntax);
  3654. }
  3655. #endif
  3656. if (buildAST)
  3657. {
  3658. if (arrayOfNumbers)
  3659. {
  3660. if (pnodeArg->nop != knopInt)
  3661. {
  3662. arrayOfTaggedInts = false;
  3663. if (pnodeArg->nop != knopFlt)
  3664. {
  3665. // Not an array of constants.
  3666. arrayOfInts = false;
  3667. arrayOfNumbers = false;
  3668. }
  3669. else if (arrayOfInts && Js::JavascriptNumber::IsInt32OrUInt32(pnodeArg->sxFlt.dbl) && (!Js::JavascriptNumber::IsInt32(pnodeArg->sxFlt.dbl) || pnodeArg->sxFlt.dbl == -2147483648.0))
  3670. {
  3671. // We've seen nothing but ints, and this is a uint32 but not an int32.
  3672. // Unless we see an actual float at some point, we want an array of vars
  3673. // so we can work with tagged ints.
  3674. arrayOfVarInts = true;
  3675. }
  3676. else
  3677. {
  3678. // Not an int array, but it may still be a float array.
  3679. arrayOfInts = false;
  3680. }
  3681. }
  3682. else
  3683. {
  3684. if (Js::SparseArraySegment<int32>::IsMissingItem((int32*)&pnodeArg->sxInt.lw))
  3685. {
  3686. arrayOfInts = false;
  3687. }
  3688. if (Js::TaggedInt::IsOverflow(pnodeArg->sxInt.lw))
  3689. {
  3690. arrayOfTaggedInts = false;
  3691. }
  3692. }
  3693. }
  3694. AddToNodeListEscapedUse(&pnodeList, &lastNodeRef, pnodeArg);
  3695. }
  3696. if (tkComma != m_token.tk)
  3697. {
  3698. break;
  3699. }
  3700. m_pscan->Scan();
  3701. if (tkRBrack == m_token.tk)
  3702. {
  3703. break;
  3704. }
  3705. }
  3706. if (spreadCount != nullptr && *spreadCount > 0){
  3707. CHAKRATEL_LANGSTATS_INC_LANGFEATURECOUNT(SpreadFeature, m_scriptContext);
  3708. }
  3709. if (buildAST)
  3710. {
  3711. AssertMem(lastNodeRef);
  3712. AssertNodeMem(*lastNodeRef);
  3713. pnodeList->ichLim = (*lastNodeRef)->ichLim;
  3714. if (arrayOfVarInts && arrayOfInts)
  3715. {
  3716. arrayOfInts = false;
  3717. arrayOfNumbers = false;
  3718. }
  3719. *pArrayOfTaggedInts = arrayOfTaggedInts;
  3720. *pArrayOfInts = arrayOfInts;
  3721. *pArrayOfNumbers = arrayOfNumbers;
  3722. *pHasMissingValues = hasMissingValues;
  3723. }
  3724. this->m_arrayDepth--;
  3725. return pnodeList;
  3726. }
  3727. Parser::MemberNameToTypeMap* Parser::CreateMemberNameMap(ArenaAllocator* pAllocator)
  3728. {
  3729. Assert(pAllocator);
  3730. return Anew(pAllocator, MemberNameToTypeMap, pAllocator, 5);
  3731. }
  3732. template<bool buildAST> void Parser::ParseComputedName(ParseNodePtr* ppnodeName, LPCOLESTR* ppNameHint, LPCOLESTR* ppFullNameHint, uint32 *pNameLength, uint32 *pShortNameOffset)
  3733. {
  3734. m_pscan->Scan();
  3735. ParseNodePtr pnodeNameExpr = ParseExpr<buildAST>(koplCma, nullptr, TRUE, FALSE, *ppNameHint, pNameLength, pShortNameOffset);
  3736. if (buildAST)
  3737. {
  3738. *ppnodeName = CreateNodeT<knopComputedName>(pnodeNameExpr->ichMin, pnodeNameExpr->ichLim);
  3739. (*ppnodeName)->sxUni.pnode1 = pnodeNameExpr;
  3740. }
  3741. if (ppFullNameHint && buildAST && CONFIG_FLAG(UseFullName))
  3742. {
  3743. *ppFullNameHint = FormatPropertyString(*ppNameHint, pnodeNameExpr, pNameLength, pShortNameOffset);
  3744. }
  3745. ChkCurTokNoScan(tkRBrack, ERRnoRbrack);
  3746. }
  3747. /***************************************************************************
  3748. Parse a list of object set/get members, e.g.:
  3749. { get foo(){ ... }, set bar(arg) { ... } }
  3750. ***************************************************************************/
  3751. template<bool buildAST>
  3752. ParseNodePtr Parser::ParseMemberGetSet(OpCode nop, LPCOLESTR* ppNameHint)
  3753. {
  3754. ParseNodePtr pnodeName = nullptr;
  3755. Assert(nop == knopGetMember || nop == knopSetMember);
  3756. AssertMem(ppNameHint);
  3757. IdentPtr pid = nullptr;
  3758. bool isComputedName = false;
  3759. *ppNameHint=nullptr;
  3760. switch(m_token.tk)
  3761. {
  3762. default:
  3763. if (!m_token.IsReservedWord())
  3764. {
  3765. Error(ERRnoMemberIdent);
  3766. }
  3767. // fall through
  3768. case tkID:
  3769. pid = m_token.GetIdentifier(m_phtbl);
  3770. *ppNameHint = pid->Psz();
  3771. if (buildAST)
  3772. {
  3773. pnodeName = CreateStrNodeWithScanner(pid);
  3774. }
  3775. break;
  3776. case tkStrCon:
  3777. if (IsStrictMode() && m_pscan->IsOctOrLeadingZeroOnLastTKNumber())
  3778. {
  3779. Error(ERRES5NoOctal);
  3780. }
  3781. pid = m_token.GetStr();
  3782. *ppNameHint = pid->Psz();
  3783. if (buildAST)
  3784. {
  3785. pnodeName = CreateStrNodeWithScanner(pid);
  3786. }
  3787. break;
  3788. case tkIntCon:
  3789. if (IsStrictMode() && m_pscan->IsOctOrLeadingZeroOnLastTKNumber())
  3790. {
  3791. Error(ERRES5NoOctal);
  3792. }
  3793. pid = m_pscan->PidFromLong(m_token.GetLong());
  3794. if (buildAST)
  3795. {
  3796. pnodeName = CreateStrNodeWithScanner(pid);
  3797. }
  3798. break;
  3799. case tkFltCon:
  3800. if (IsStrictMode() && m_pscan->IsOctOrLeadingZeroOnLastTKNumber())
  3801. {
  3802. Error(ERRES5NoOctal);
  3803. }
  3804. pid = m_pscan->PidFromDbl(m_token.GetDouble());
  3805. if (buildAST)
  3806. {
  3807. pnodeName = CreateStrNodeWithScanner(pid);
  3808. }
  3809. break;
  3810. case tkLBrack:
  3811. // Computed property name: get|set [expr] () { }
  3812. if (!m_scriptContext->GetConfig()->IsES6ObjectLiteralsEnabled())
  3813. {
  3814. Error(ERRnoMemberIdent);
  3815. }
  3816. LPCOLESTR emptyHint = nullptr;
  3817. uint32 offset = 0;
  3818. ParseComputedName<buildAST>(&pnodeName, &emptyHint, ppNameHint, &offset);
  3819. isComputedName = true;
  3820. break;
  3821. }
  3822. MemberType memberType;
  3823. ushort flags = fFncMethod | fFncNoName;
  3824. if (nop == knopGetMember)
  3825. {
  3826. memberType = MemberTypeGetter;
  3827. flags |= fFncNoArg;
  3828. }
  3829. else
  3830. {
  3831. Assert(nop == knopSetMember);
  3832. memberType = MemberTypeSetter;
  3833. flags |= fFncOneArg;
  3834. }
  3835. this->m_parsingSuperRestrictionState = ParsingSuperRestrictionState_SuperPropertyAllowed;
  3836. ParseNodePtr pnodeFnc = ParseFncDecl<buildAST>(flags, *ppNameHint,
  3837. /*needsPIDOnRCurlyScan*/ false, /*resetParsingSuperRestrictionState*/ false);
  3838. if (buildAST)
  3839. {
  3840. pnodeFnc->sxFnc.SetIsAccessor();
  3841. return CreateBinNode(nop, pnodeName, pnodeFnc);
  3842. }
  3843. else
  3844. {
  3845. return nullptr;
  3846. }
  3847. }
  3848. /***************************************************************************
  3849. Parse a list of object members. e.g. { x:foo, 'y me':bar }
  3850. ***************************************************************************/
  3851. template<bool buildAST>
  3852. ParseNodePtr Parser::ParseMemberList(LPCOLESTR pNameHint, uint32* pNameHintLength, tokens declarationType)
  3853. {
  3854. ParseNodePtr pnodeArg = nullptr;
  3855. ParseNodePtr pnodeName = nullptr;
  3856. ParseNodePtr pnodeList = nullptr;
  3857. ParseNodePtr *lastNodeRef = nullptr;
  3858. LPCOLESTR pFullNameHint = nullptr; // A calculated full name
  3859. uint32 fullNameHintLength = pNameHintLength ? *pNameHintLength : 0;
  3860. uint32 shortNameOffset = 0;
  3861. bool isProtoDeclared = false;
  3862. // we get declaration tkLCurly - when the possible object pattern found under the expression.
  3863. bool isObjectPattern = (declarationType == tkVAR || declarationType == tkLET || declarationType == tkCONST || declarationType == tkLCurly) && IsES6DestructuringEnabled();
  3864. // Check for an empty list
  3865. if (tkRCurly == m_token.tk)
  3866. {
  3867. return nullptr;
  3868. }
  3869. ArenaAllocator tempAllocator(_u("MemberNames"), m_nodeAllocator.GetPageAllocator(), Parser::OutOfMemory);
  3870. bool hasDeferredInitError = false;
  3871. for (;;)
  3872. {
  3873. bool isComputedName = false;
  3874. #if DEBUG
  3875. if((m_grfscr & fscrEnforceJSON) && (tkStrCon != m_token.tk || !(m_pscan->IsDoubleQuoteOnLastTkStrCon())))
  3876. {
  3877. Error(ERRsyntax);
  3878. }
  3879. #endif
  3880. bool isAsyncMethod = false;
  3881. charcount_t ichMin = 0;
  3882. size_t iecpMin = 0;
  3883. if (m_token.tk == tkID && m_token.GetIdentifier(m_phtbl) == wellKnownPropertyPids.async && m_scriptContext->GetConfig()->IsES7AsyncAndAwaitEnabled())
  3884. {
  3885. RestorePoint parsedAsync;
  3886. m_pscan->Capture(&parsedAsync);
  3887. ichMin = m_pscan->IchMinTok();
  3888. iecpMin = m_pscan->IecpMinTok();
  3889. m_pscan->ScanForcingPid();
  3890. if (m_token.tk == tkLParen || m_token.tk == tkColon || m_token.tk == tkRCurly || m_pscan->FHadNewLine())
  3891. {
  3892. m_pscan->SeekTo(parsedAsync);
  3893. }
  3894. else
  3895. {
  3896. isAsyncMethod = true;
  3897. }
  3898. }
  3899. bool isGenerator = m_scriptContext->GetConfig()->IsES6GeneratorsEnabled() &&
  3900. m_token.tk == tkStar;
  3901. ushort fncDeclFlags = fFncNoName | fFncMethod;
  3902. if (isGenerator)
  3903. {
  3904. if (isAsyncMethod)
  3905. {
  3906. Error(ERRsyntax);
  3907. }
  3908. m_pscan->ScanForcingPid();
  3909. fncDeclFlags |= fFncGenerator;
  3910. }
  3911. IdentPtr pidHint = nullptr; // A name scoped to current expression
  3912. Token tkHint = m_token;
  3913. charcount_t idHintIchMin = static_cast<charcount_t>(m_pscan->IecpMinTok());
  3914. charcount_t idHintIchLim = static_cast< charcount_t >(m_pscan->IecpLimTok());
  3915. bool wrapInBrackets = false;
  3916. switch (m_token.tk)
  3917. {
  3918. default:
  3919. if (!m_token.IsReservedWord())
  3920. {
  3921. Error(ERRnoMemberIdent);
  3922. }
  3923. // allow reserved words
  3924. wrapInBrackets = true;
  3925. // fall-through
  3926. case tkID:
  3927. pidHint = m_token.GetIdentifier(m_phtbl);
  3928. if (buildAST)
  3929. {
  3930. pnodeName = CreateStrNodeWithScanner(pidHint);
  3931. }
  3932. break;
  3933. case tkStrCon:
  3934. if (IsStrictMode() && m_pscan->IsOctOrLeadingZeroOnLastTKNumber())
  3935. {
  3936. Error(ERRES5NoOctal);
  3937. }
  3938. wrapInBrackets = true;
  3939. pidHint = m_token.GetStr();
  3940. if (buildAST)
  3941. {
  3942. pnodeName = CreateStrNodeWithScanner(pidHint);
  3943. }
  3944. break;
  3945. case tkIntCon:
  3946. // Object initializers with numeric labels allowed in JS6
  3947. if (IsStrictMode() && m_pscan->IsOctOrLeadingZeroOnLastTKNumber())
  3948. {
  3949. Error(ERRES5NoOctal);
  3950. }
  3951. pidHint = m_pscan->PidFromLong(m_token.GetLong());
  3952. if (buildAST)
  3953. {
  3954. pnodeName = CreateStrNodeWithScanner(pidHint);
  3955. }
  3956. break;
  3957. case tkFltCon:
  3958. if (IsStrictMode() && m_pscan->IsOctOrLeadingZeroOnLastTKNumber())
  3959. {
  3960. Error(ERRES5NoOctal);
  3961. }
  3962. pidHint = m_pscan->PidFromDbl(m_token.GetDouble());
  3963. if (buildAST)
  3964. {
  3965. pnodeName = CreateStrNodeWithScanner(pidHint);
  3966. }
  3967. wrapInBrackets = true;
  3968. break;
  3969. case tkLBrack:
  3970. // Computed property name: [expr] : value
  3971. if (!m_scriptContext->GetConfig()->IsES6ObjectLiteralsEnabled())
  3972. {
  3973. Error(ERRnoMemberIdent);
  3974. }
  3975. ParseComputedName<buildAST>(&pnodeName, &pNameHint, &pFullNameHint, &fullNameHintLength, &shortNameOffset);
  3976. isComputedName = true;
  3977. break;
  3978. }
  3979. if (pFullNameHint == nullptr)
  3980. {
  3981. if (CONFIG_FLAG(UseFullName))
  3982. {
  3983. pFullNameHint = AppendNameHints(pNameHint, pidHint, &fullNameHintLength, &shortNameOffset, false, wrapInBrackets);
  3984. }
  3985. else
  3986. {
  3987. pFullNameHint = pidHint? pidHint->Psz() : nullptr;
  3988. fullNameHintLength = pidHint ? pidHint->Cch() : 0;
  3989. shortNameOffset = 0;
  3990. }
  3991. }
  3992. RestorePoint atPid;
  3993. m_pscan->Capture(&atPid);
  3994. m_pscan->ScanForcingPid();
  3995. if (isGenerator && m_token.tk != tkLParen)
  3996. {
  3997. Error(ERRnoLparen);
  3998. }
  3999. if (tkColon == m_token.tk)
  4000. {
  4001. // It is a syntax error is the production of the form __proto__ : <> occurs more than once. From B.3.1 in spec.
  4002. // Note that previous scan is important because only after that we can determine we have a variable.
  4003. if (!isComputedName && pidHint == wellKnownPropertyPids.__proto__)
  4004. {
  4005. if (isProtoDeclared)
  4006. {
  4007. Error(ERRsyntax);
  4008. }
  4009. else
  4010. {
  4011. isProtoDeclared = true;
  4012. }
  4013. }
  4014. m_pscan->Scan();
  4015. ParseNodePtr pnodeExpr = nullptr;
  4016. if (isObjectPattern)
  4017. {
  4018. if (m_token.tk == tkEllipsis)
  4019. {
  4020. Error(ERRUnexpectedEllipsis);
  4021. }
  4022. pnodeExpr = ParseDestructuredVarDecl<buildAST>(declarationType, declarationType != tkLCurly, nullptr/* *hasSeenRest*/, false /*topLevel*/, false /*allowEmptyExpression*/);
  4023. if (m_token.tk != tkComma && m_token.tk != tkRCurly)
  4024. {
  4025. if (m_token.IsOperator())
  4026. {
  4027. Error(ERRDestructNoOper);
  4028. }
  4029. Error(ERRsyntax);
  4030. }
  4031. }
  4032. else
  4033. {
  4034. pnodeExpr = ParseExpr<buildAST>(koplCma, nullptr, TRUE, FALSE, pFullNameHint, &fullNameHintLength, &shortNameOffset);
  4035. }
  4036. #if DEBUG
  4037. if((m_grfscr & fscrEnforceJSON) && !IsJSONValid(pnodeExpr))
  4038. {
  4039. Error(ERRsyntax);
  4040. }
  4041. #endif
  4042. if (buildAST)
  4043. {
  4044. pnodeArg = CreateBinNode(isObjectPattern ? knopObjectPatternMember : knopMember, pnodeName, pnodeExpr);
  4045. if (pnodeArg->sxBin.pnode1->nop == knopStr)
  4046. {
  4047. pnodeArg->sxBin.pnode1->sxPid.pid->PromoteAssignmentState();
  4048. }
  4049. }
  4050. }
  4051. else if (m_token.tk == tkLParen && m_scriptContext->GetConfig()->IsES6ObjectLiteralsEnabled())
  4052. {
  4053. if (isObjectPattern)
  4054. {
  4055. Error(ERRInvalidAssignmentTarget);
  4056. }
  4057. // Shorthand syntax: foo() {} -> foo: function() {}
  4058. // Rewind to the PID and parse a function expression.
  4059. m_pscan->SeekTo(atPid);
  4060. this->m_parsingSuperRestrictionState = ParsingSuperRestrictionState_SuperPropertyAllowed;
  4061. ParseNodePtr pnodeFunc = ParseFncDecl<buildAST>(fncDeclFlags | (isAsyncMethod ? fFncAsync : fFncNoFlgs), pFullNameHint,
  4062. /*needsPIDOnRCurlyScan*/ false, /*resetParsingSuperRestrictionState*/ false);
  4063. if (isAsyncMethod)
  4064. {
  4065. pnodeFunc->sxFnc.cbMin = iecpMin;
  4066. pnodeFunc->ichMin = ichMin;
  4067. }
  4068. if (buildAST)
  4069. {
  4070. pnodeArg = CreateBinNode(knopMember, pnodeName, pnodeFunc);
  4071. }
  4072. }
  4073. else if (nullptr != pidHint) //Its either tkID/tkStrCon/tkFloatCon/tkIntCon
  4074. {
  4075. Assert(pidHint->Psz() != nullptr);
  4076. if ((pidHint == wellKnownPropertyPids.get || pidHint == wellKnownPropertyPids.set) &&
  4077. // get/set are only pseudo keywords when they are identifiers (i.e. not strings)
  4078. tkHint.tk == tkID && NextTokenIsPropertyNameStart())
  4079. {
  4080. if (isObjectPattern)
  4081. {
  4082. Error(ERRInvalidAssignmentTarget);
  4083. }
  4084. LPCOLESTR pNameGetOrSet = nullptr;
  4085. OpCode op = pidHint == wellKnownPropertyPids.get ? knopGetMember : knopSetMember;
  4086. pnodeArg = ParseMemberGetSet<buildAST>(op, &pNameGetOrSet);
  4087. if (CONFIG_FLAG(UseFullName) && buildAST && pnodeArg->sxBin.pnode2->nop == knopFncDecl)
  4088. {
  4089. if (m_scriptContext->GetConfig()->IsES6FunctionNameEnabled())
  4090. {
  4091. // displays as "get object.funcname" or "set object.funcname"
  4092. uint32 getOrSetOffset = 0;
  4093. LPCOLESTR intermediateHint = AppendNameHints(pNameHint, pNameGetOrSet, &fullNameHintLength, &shortNameOffset);
  4094. pFullNameHint = AppendNameHints(pidHint, intermediateHint, &fullNameHintLength, &getOrSetOffset, true);
  4095. shortNameOffset += getOrSetOffset;
  4096. }
  4097. else
  4098. {
  4099. // displays as "object.funcname.get" or "object.funcname.set"
  4100. LPCOLESTR intermediateHint = AppendNameHints(pNameGetOrSet, pidHint, &fullNameHintLength, &shortNameOffset);
  4101. pFullNameHint = AppendNameHints(pNameHint, intermediateHint, &fullNameHintLength, &shortNameOffset);
  4102. }
  4103. }
  4104. }
  4105. else if ((m_token.tk == tkRCurly || m_token.tk == tkComma || m_token.tk == tkAsg) && m_scriptContext->GetConfig()->IsES6ObjectLiteralsEnabled())
  4106. {
  4107. // Shorthand {foo} -> {foo:foo} syntax.
  4108. // {foo = <initializer>} supported only when on object pattern rules are being applied
  4109. if (tkHint.tk != tkID)
  4110. {
  4111. Assert(tkHint.IsReservedWord()
  4112. || tkHint.tk == tkIntCon || tkHint.tk == tkFltCon || tkHint.tk == tkStrCon);
  4113. // All keywords are banned in non-strict mode.
  4114. // Future reserved words are banned in strict mode.
  4115. if (IsStrictMode() || !tkHint.IsFutureReservedWord(true))
  4116. {
  4117. IdentifierExpectedError(tkHint);
  4118. }
  4119. }
  4120. if (buildAST)
  4121. {
  4122. CheckArgumentsUse(pidHint, GetCurrentFunctionNode());
  4123. }
  4124. bool couldBeObjectPattern = !isObjectPattern && m_token.tk == tkAsg;
  4125. // Saving the current state as we may change the isObjectPattern down below.
  4126. bool oldState = isObjectPattern;
  4127. if (couldBeObjectPattern)
  4128. {
  4129. declarationType = tkLCurly;
  4130. isObjectPattern = true;
  4131. // This may be an error but we are deferring for favouring destructuring.
  4132. hasDeferredInitError = true;
  4133. }
  4134. ParseNodePtr pnodeIdent = nullptr;
  4135. if (isObjectPattern)
  4136. {
  4137. m_pscan->SeekTo(atPid);
  4138. pnodeIdent = ParseDestructuredVarDecl<buildAST>(declarationType, declarationType != tkLCurly, nullptr/* *hasSeenRest*/, false /*topLevel*/, false /*allowEmptyExpression*/);
  4139. if (m_token.tk != tkComma && m_token.tk != tkRCurly)
  4140. {
  4141. if (m_token.IsOperator())
  4142. {
  4143. Error(ERRDestructNoOper);
  4144. }
  4145. Error(ERRsyntax);
  4146. }
  4147. }
  4148. else
  4149. {
  4150. // Add a reference to the hinted name so we can bind it properly.
  4151. PidRefStack *ref = PushPidRef(pidHint);
  4152. if (buildAST)
  4153. {
  4154. pnodeIdent = CreateNameNode(pidHint, idHintIchMin, idHintIchLim);
  4155. pnodeIdent->sxPid.SetSymRef(ref);
  4156. }
  4157. }
  4158. if (buildAST)
  4159. {
  4160. pnodeArg = CreateBinNode(isObjectPattern && !couldBeObjectPattern ? knopObjectPatternMember : knopMemberShort, pnodeName, pnodeIdent);
  4161. }
  4162. isObjectPattern = oldState;
  4163. }
  4164. else
  4165. {
  4166. Error(ERRnoColon);
  4167. }
  4168. }
  4169. else
  4170. {
  4171. Error(ERRnoColon);
  4172. }
  4173. if (buildAST)
  4174. {
  4175. Assert(pnodeArg->sxBin.pnode2 != nullptr);
  4176. if (pnodeArg->sxBin.pnode2->nop == knopFncDecl)
  4177. {
  4178. Assert(fullNameHintLength >= shortNameOffset);
  4179. pnodeArg->sxBin.pnode2->sxFnc.hint = pFullNameHint;
  4180. pnodeArg->sxBin.pnode2->sxFnc.hintLength = fullNameHintLength;
  4181. pnodeArg->sxBin.pnode2->sxFnc.hintOffset = shortNameOffset;
  4182. }
  4183. AddToNodeListEscapedUse(&pnodeList, &lastNodeRef, pnodeArg);
  4184. }
  4185. pidHint = nullptr;
  4186. pFullNameHint = nullptr;
  4187. if (tkComma != m_token.tk)
  4188. {
  4189. break;
  4190. }
  4191. m_pscan->ScanForcingPid();
  4192. if (tkRCurly == m_token.tk)
  4193. {
  4194. break;
  4195. }
  4196. }
  4197. m_hasDeferredShorthandInitError = m_hasDeferredShorthandInitError || hasDeferredInitError;
  4198. if (buildAST)
  4199. {
  4200. AssertMem(lastNodeRef);
  4201. AssertNodeMem(*lastNodeRef);
  4202. pnodeList->ichLim = (*lastNodeRef)->ichLim;
  4203. }
  4204. return pnodeList;
  4205. }
  4206. BOOL Parser::DeferredParse(Js::LocalFunctionId functionId)
  4207. {
  4208. if ((m_grfscr & fscrDeferFncParse) != 0)
  4209. {
  4210. if (m_stoppedDeferredParse)
  4211. {
  4212. return false;
  4213. }
  4214. if (PHASE_OFF_RAW(Js::DeferParsePhase, m_sourceContextInfo->sourceContextId, functionId))
  4215. {
  4216. return false;
  4217. }
  4218. if (PHASE_FORCE_RAW(Js::DeferParsePhase, m_sourceContextInfo->sourceContextId, functionId)
  4219. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  4220. || Js::Configuration::Global.flags.IsEnabled(Js::ForceUndoDeferFlag)
  4221. #endif
  4222. )
  4223. {
  4224. return true;
  4225. }
  4226. #if ENABLE_PROFILE_INFO
  4227. #ifndef DISABLE_DYNAMIC_PROFILE_DEFER_PARSE
  4228. if (m_sourceContextInfo->sourceDynamicProfileManager != nullptr)
  4229. {
  4230. Js::ExecutionFlags flags = m_sourceContextInfo->sourceDynamicProfileManager->IsFunctionExecuted(functionId);
  4231. return flags != Js::ExecutionFlags_Executed;
  4232. }
  4233. #endif
  4234. #endif
  4235. return true;
  4236. }
  4237. return false;
  4238. }
  4239. //
  4240. // Call this in ParseFncDecl only to check (and reset) if ParseFncDecl is re-parsing a deferred
  4241. // function body. If a deferred function is called and being re-parsed, it shouldn't be deferred again.
  4242. //
  4243. BOOL Parser::IsDeferredFnc()
  4244. {
  4245. if (m_grfscr & fscrDeferredFnc)
  4246. {
  4247. m_grfscr &= ~fscrDeferredFnc;
  4248. return true;
  4249. }
  4250. return false;
  4251. }
  4252. template<bool buildAST>
  4253. ParseNodePtr Parser::ParseFncDecl(ushort flags, LPCOLESTR pNameHint, const bool needsPIDOnRCurlyScan, bool resetParsingSuperRestrictionState, bool fUnaryOrParen)
  4254. {
  4255. AutoParsingSuperRestrictionStateRestorer restorer(this);
  4256. if (resetParsingSuperRestrictionState)
  4257. {
  4258. // ParseFncDecl will always reset m_parsingSuperRestrictionState to super disallowed unless explicitly disabled
  4259. this->m_parsingSuperRestrictionState = ParsingSuperRestrictionState_SuperDisallowed;
  4260. }
  4261. ParseNodePtr pnodeFnc = nullptr;
  4262. ParseNodePtr *ppnodeVarSave = nullptr;
  4263. ParseNodePtr pnodeFncBlockScope = nullptr;
  4264. ParseNodePtr *ppnodeScopeSave = nullptr;
  4265. ParseNodePtr *ppnodeExprScopeSave = nullptr;
  4266. bool funcHasName = false;
  4267. bool fDeclaration = flags & fFncDeclaration;
  4268. bool fModule = (flags & fFncModule) != 0;
  4269. bool fLambda = (flags & fFncLambda) != 0;
  4270. charcount_t ichMin = this->m_pscan->IchMinTok();
  4271. bool wasInDeferredNestedFunc = false;
  4272. uint tryCatchOrFinallyDepthSave = this->m_tryCatchOrFinallyDepth;
  4273. this->m_tryCatchOrFinallyDepth = 0;
  4274. if (this->m_arrayDepth)
  4275. {
  4276. this->m_funcInArrayDepth++; // Count function depth within array literal
  4277. }
  4278. // Update the count of functions nested in the current parent.
  4279. Assert(m_pnestedCount || !buildAST);
  4280. uint *pnestedCountSave = m_pnestedCount;
  4281. if (buildAST || m_pnestedCount)
  4282. {
  4283. (*m_pnestedCount)++;
  4284. }
  4285. uint scopeCountNoAstSave = m_scopeCountNoAst;
  4286. m_scopeCountNoAst = 0;
  4287. bool noStmtContext = false;
  4288. if (fDeclaration)
  4289. {
  4290. noStmtContext = m_pstmtCur->GetNop() != knopBlock;
  4291. if (noStmtContext)
  4292. {
  4293. // We have a function declaration like "if (a) function f() {}". We didn't see
  4294. // a block scope on the way in, so we need to pretend we did. Note that this is a syntax error
  4295. // in strict mode.
  4296. if (!this->FncDeclAllowedWithoutContext(flags))
  4297. {
  4298. Error(ERRsyntax);
  4299. }
  4300. pnodeFncBlockScope = StartParseBlock<buildAST>(PnodeBlockType::Regular, ScopeType_Block);
  4301. if (buildAST)
  4302. {
  4303. PushFuncBlockScope(pnodeFncBlockScope, &ppnodeScopeSave, &ppnodeExprScopeSave);
  4304. }
  4305. }
  4306. }
  4307. // Create the node.
  4308. pnodeFnc = CreateNode(knopFncDecl);
  4309. pnodeFnc->sxFnc.ClearFlags();
  4310. pnodeFnc->sxFnc.SetDeclaration(fDeclaration);
  4311. pnodeFnc->sxFnc.astSize = 0;
  4312. pnodeFnc->sxFnc.pnodeName = nullptr;
  4313. pnodeFnc->sxFnc.pnodeScopes = nullptr;
  4314. pnodeFnc->sxFnc.pnodeRest = nullptr;
  4315. pnodeFnc->sxFnc.pid = nullptr;
  4316. pnodeFnc->sxFnc.hint = nullptr;
  4317. pnodeFnc->sxFnc.hintOffset = 0;
  4318. pnodeFnc->sxFnc.hintLength = 0;
  4319. pnodeFnc->sxFnc.isNameIdentifierRef = true;
  4320. pnodeFnc->sxFnc.nestedFuncEscapes = false;
  4321. pnodeFnc->sxFnc.pnodeNext = nullptr;
  4322. pnodeFnc->sxFnc.pnodeParams = nullptr;
  4323. pnodeFnc->sxFnc.pnodeVars = nullptr;
  4324. pnodeFnc->sxFnc.funcInfo = nullptr;
  4325. pnodeFnc->sxFnc.deferredStub = nullptr;
  4326. pnodeFnc->sxFnc.nestedCount = 0;
  4327. pnodeFnc->sxFnc.cbMin = m_pscan->IecpMinTok();
  4328. pnodeFnc->sxFnc.functionId = (*m_nextFunctionId)++;
  4329. pnodeFnc->sxFnc.isBodyAndParamScopeMerged = true;
  4330. // Push new parser state with this new function node
  4331. AppendFunctionToScopeList(fDeclaration, pnodeFnc);
  4332. // Start the argument list.
  4333. ppnodeVarSave = m_ppnodeVar;
  4334. if (buildAST)
  4335. {
  4336. pnodeFnc->sxFnc.lineNumber = m_pscan->LineCur();
  4337. pnodeFnc->sxFnc.columnNumber = CalculateFunctionColumnNumber();
  4338. pnodeFnc->sxFnc.SetNested(m_currentNodeFunc != nullptr); // If there is a current function, then we're a nested function.
  4339. pnodeFnc->sxFnc.SetStrictMode(IsStrictMode()); // Inherit current strict mode -- may be overridden by the function itself if it contains a strict mode directive.
  4340. pnodeFnc->sxFnc.firstDefaultArg = 0;
  4341. m_pCurrentAstSize = &pnodeFnc->sxFnc.astSize;
  4342. }
  4343. else // if !buildAST
  4344. {
  4345. wasInDeferredNestedFunc = m_inDeferredNestedFunc;
  4346. m_inDeferredNestedFunc = true;
  4347. }
  4348. m_pnestedCount = &pnodeFnc->sxFnc.nestedCount;
  4349. AnalysisAssert(pnodeFnc);
  4350. pnodeFnc->sxFnc.SetIsAsync((flags & fFncAsync) != 0);
  4351. pnodeFnc->sxFnc.SetIsLambda(fLambda);
  4352. pnodeFnc->sxFnc.SetIsMethod((flags & fFncMethod) != 0);
  4353. pnodeFnc->sxFnc.SetIsClassMember((flags & fFncClassMember) != 0);
  4354. pnodeFnc->sxFnc.SetIsModule(fModule);
  4355. pnodeFnc->sxFnc.SetIsClassConstructor((flags & fFncClassConstructor) != 0);
  4356. pnodeFnc->sxFnc.SetIsBaseClassConstructor((flags & fFncBaseClassConstructor) != 0);
  4357. bool needScanRCurly = true;
  4358. bool result = ParseFncDeclHelper<buildAST>(pnodeFnc, pNameHint, flags, &funcHasName, fUnaryOrParen, noStmtContext, &needScanRCurly, fModule);
  4359. if (!result)
  4360. {
  4361. Assert(!pnodeFncBlockScope);
  4362. return pnodeFnc;
  4363. }
  4364. AnalysisAssert(pnodeFnc);
  4365. *m_ppnodeVar = nullptr;
  4366. m_ppnodeVar = ppnodeVarSave;
  4367. if (m_currentNodeFunc && (pnodeFnc->sxFnc.CallsEval() || pnodeFnc->sxFnc.ChildCallsEval()))
  4368. {
  4369. GetCurrentFunctionNode()->sxFnc.SetChildCallsEval(true);
  4370. }
  4371. ParseNodePtr pnodeFncParent = buildAST ? m_currentNodeFunc : m_currentNodeDeferredFunc;
  4372. // Lambdas do not have "arguments" and instead capture their parent's
  4373. // binding of "arguments. To ensure the arguments object of the enclosing
  4374. // non-lambda function is loaded propagate the UsesArguments flag up to
  4375. // the parent function
  4376. if ((flags & fFncLambda) != 0)
  4377. {
  4378. if (pnodeFnc->sxFnc.UsesArguments())
  4379. {
  4380. if (pnodeFncParent != nullptr)
  4381. {
  4382. pnodeFncParent->sxFnc.SetUsesArguments();
  4383. }
  4384. else
  4385. {
  4386. m_UsesArgumentsAtGlobal = true;
  4387. }
  4388. }
  4389. }
  4390. if (needScanRCurly && !fModule)
  4391. {
  4392. // Consume the next token now that we're back in the enclosing function (whose strictness may be
  4393. // different from the function we just finished).
  4394. #if DBG
  4395. bool expectedTokenValid = m_token.tk == tkRCurly;
  4396. AssertMsg(expectedTokenValid, "Invalid token expected for RCurly match");
  4397. #endif
  4398. // The next token may need to have a PID created in !buildAST mode, as we may be parsing a method with a string name.
  4399. if (needsPIDOnRCurlyScan)
  4400. {
  4401. m_pscan->ScanForcingPid();
  4402. }
  4403. else
  4404. {
  4405. m_pscan->Scan();
  4406. }
  4407. }
  4408. m_pnestedCount = pnestedCountSave;
  4409. Assert(!buildAST || !wasInDeferredNestedFunc);
  4410. m_inDeferredNestedFunc = wasInDeferredNestedFunc;
  4411. if (this->m_arrayDepth)
  4412. {
  4413. this->m_funcInArrayDepth--;
  4414. if (this->m_funcInArrayDepth == 0)
  4415. {
  4416. // We disable deferred parsing if array literals dominate.
  4417. // But don't do this if the array literal is dominated by function bodies.
  4418. if (flags & (fFncMethod | fFncClassMember) && m_token.tk != tkSColon)
  4419. {
  4420. // Class member methods have optional separators. We need to check whether we are
  4421. // getting the IchLim of the correct token.
  4422. Assert(m_pscan->m_tkPrevious == tkRCurly && needScanRCurly);
  4423. this->m_funcInArray += m_pscan->IchMinTok() - /*tkRCurly*/ 1 - ichMin;
  4424. }
  4425. else
  4426. {
  4427. this->m_funcInArray += m_pscan->IchLimTok() - ichMin;
  4428. }
  4429. }
  4430. }
  4431. m_scopeCountNoAst = scopeCountNoAstSave;
  4432. if (buildAST && fDeclaration && !IsStrictMode())
  4433. {
  4434. if (pnodeFnc->sxFnc.pnodeName != nullptr && pnodeFnc->sxFnc.pnodeName->nop == knopVarDecl &&
  4435. GetCurrentBlock()->sxBlock.blockType == PnodeBlockType::Regular)
  4436. {
  4437. // Add a function-scoped VarDecl with the same name as the function for
  4438. // back compat with pre-ES6 code that declares functions in blocks. The
  4439. // idea is that the last executed declaration wins at the function scope
  4440. // level and we accomplish this by having each block scoped function
  4441. // declaration assign to both the block scoped "let" binding, as well
  4442. // as the function scoped "var" binding.
  4443. ParseNodePtr vardecl = CreateVarDeclNode(pnodeFnc->sxFnc.pnodeName->sxVar.pid, STVariable, false, nullptr, false);
  4444. vardecl->sxVar.isBlockScopeFncDeclVar = true;
  4445. }
  4446. }
  4447. if (pnodeFncBlockScope)
  4448. {
  4449. Assert(pnodeFncBlockScope->sxBlock.pnodeStmt == nullptr);
  4450. pnodeFncBlockScope->sxBlock.pnodeStmt = pnodeFnc;
  4451. if (buildAST)
  4452. {
  4453. PopFuncBlockScope(ppnodeScopeSave, ppnodeExprScopeSave);
  4454. }
  4455. FinishParseBlock(pnodeFncBlockScope);
  4456. return pnodeFncBlockScope;
  4457. }
  4458. this->m_tryCatchOrFinallyDepth = tryCatchOrFinallyDepthSave;
  4459. return pnodeFnc;
  4460. }
  4461. bool Parser::FncDeclAllowedWithoutContext(ushort flags)
  4462. {
  4463. // Statement context required for strict mode, async functions, and generators.
  4464. // Note that generators aren't detected yet when this method is called; they're checked elsewhere.
  4465. return !IsStrictMode() && !(flags & fFncAsync);
  4466. }
  4467. uint Parser::CalculateFunctionColumnNumber()
  4468. {
  4469. uint columnNumber;
  4470. if (m_pscan->IchMinTok() >= m_pscan->IchMinLine())
  4471. {
  4472. // In scenarios involving defer parse IchMinLine() can be incorrect for the first line after defer parse
  4473. columnNumber = m_pscan->IchMinTok() - m_pscan->IchMinLine();
  4474. if (m_functionBody != nullptr && m_functionBody->GetRelativeLineNumber() == m_pscan->LineCur())
  4475. {
  4476. // Adjust the column if it falls on the first line, where the re-parse is happening.
  4477. columnNumber += m_functionBody->GetRelativeColumnNumber();
  4478. }
  4479. }
  4480. else if (m_currentNodeFunc)
  4481. {
  4482. // For the first line after defer parse, compute the column relative to the column number
  4483. // of the lexically parent function.
  4484. ULONG offsetFromCurrentFunction = m_pscan->IchMinTok() - m_currentNodeFunc->ichMin;
  4485. columnNumber = m_currentNodeFunc->sxFnc.columnNumber + offsetFromCurrentFunction ;
  4486. }
  4487. else
  4488. {
  4489. // if there is no current function, lets give a default of 0.
  4490. columnNumber = 0;
  4491. }
  4492. return columnNumber;
  4493. }
  4494. void Parser::AppendFunctionToScopeList(bool fDeclaration, ParseNodePtr pnodeFnc)
  4495. {
  4496. if (!fDeclaration && m_ppnodeExprScope)
  4497. {
  4498. // We're tracking function expressions separately from declarations in this scope
  4499. // (e.g., inside a catch scope in standards mode).
  4500. Assert(*m_ppnodeExprScope == nullptr);
  4501. *m_ppnodeExprScope = pnodeFnc;
  4502. m_ppnodeExprScope = &pnodeFnc->sxFnc.pnodeNext;
  4503. }
  4504. else
  4505. {
  4506. Assert(*m_ppnodeScope == nullptr);
  4507. *m_ppnodeScope = pnodeFnc;
  4508. m_ppnodeScope = &pnodeFnc->sxFnc.pnodeNext;
  4509. }
  4510. }
  4511. /***************************************************************************
  4512. Parse a function definition.
  4513. ***************************************************************************/
  4514. template<bool buildAST>
  4515. bool Parser::ParseFncDeclHelper(ParseNodePtr pnodeFnc, LPCOLESTR pNameHint, ushort flags, bool *pHasName, bool fUnaryOrParen, bool noStmtContext, bool *pNeedScanRCurly, bool skipFormals)
  4516. {
  4517. ParseNodePtr pnodeFncParent = GetCurrentFunctionNode();
  4518. // is the following correct? When buildAST is false, m_currentNodeDeferredFunc can be nullptr on transition to deferred parse from non-deferred
  4519. ParseNodePtr pnodeFncSave = buildAST ? m_currentNodeFunc : m_currentNodeDeferredFunc;
  4520. ParseNodePtr pnodeFncSaveNonLambda = buildAST ? m_currentNodeNonLambdaFunc : m_currentNodeNonLambdaDeferredFunc;
  4521. int32* pAstSizeSave = m_pCurrentAstSize;
  4522. bool fDeclaration = (flags & fFncDeclaration) != 0;
  4523. bool fLambda = (flags & fFncLambda) != 0;
  4524. bool fAsync = (flags & fFncAsync) != 0;
  4525. bool fModule = (flags & fFncModule) != 0;
  4526. bool fDeferred = false;
  4527. StmtNest *pstmtSave;
  4528. ParseNodePtr *lastNodeRef = nullptr;
  4529. bool fFunctionInBlock = false;
  4530. if (buildAST)
  4531. {
  4532. fFunctionInBlock = GetCurrentBlockInfo() != GetCurrentFunctionBlockInfo() &&
  4533. (GetCurrentBlockInfo()->pnodeBlock->sxBlock.scope == nullptr ||
  4534. GetCurrentBlockInfo()->pnodeBlock->sxBlock.scope->GetScopeType() != ScopeType_GlobalEvalBlock);
  4535. }
  4536. // Save the position of the scanner in case we need to inspect the name hint later
  4537. RestorePoint beginNameHint;
  4538. m_pscan->Capture(&beginNameHint);
  4539. ParseNodePtr pnodeFncExprScope = nullptr;
  4540. Scope *fncExprScope = nullptr;
  4541. if (!fDeclaration)
  4542. {
  4543. if (!fLambda)
  4544. {
  4545. pnodeFncExprScope = StartParseBlock<buildAST>(PnodeBlockType::Function, ScopeType_FuncExpr);
  4546. fncExprScope = pnodeFncExprScope->sxBlock.scope;
  4547. }
  4548. // Function expression: push the new function onto the stack now so that the name (if any) will be
  4549. // local to the new function.
  4550. this->UpdateCurrentNodeFunc<buildAST>(pnodeFnc, fLambda);
  4551. }
  4552. *pHasName = !fLambda && !fModule && this->ParseFncNames<buildAST>(pnodeFnc, pnodeFncSave, flags, &lastNodeRef);
  4553. if (fDeclaration)
  4554. {
  4555. // Declaration statement: push the new function now, after parsing the name, so the name is local to the
  4556. // enclosing function.
  4557. this->UpdateCurrentNodeFunc<buildAST>(pnodeFnc, fLambda);
  4558. }
  4559. if (noStmtContext && pnodeFnc->sxFnc.IsGenerator())
  4560. {
  4561. // Generator decl not allowed outside stmt context. (We have to wait until we've parsed the '*' to
  4562. // detect generator.)
  4563. Error(ERRsyntax, pnodeFnc);
  4564. }
  4565. // switch scanner to treat 'yield' as keyword in generator functions
  4566. // or as an identifier in non-generator functions
  4567. bool fPreviousYieldIsKeyword = m_pscan->SetYieldIsKeywordRegion(pnodeFnc && pnodeFnc->sxFnc.IsGenerator());
  4568. bool fPreviousAwaitIsKeyword = m_pscan->SetAwaitIsKeywordRegion(fAsync);
  4569. if (pnodeFnc && pnodeFnc->sxFnc.IsGenerator())
  4570. {
  4571. CHAKRATEL_LANGSTATS_INC_LANGFEATURECOUNT(Generator, m_scriptContext);
  4572. }
  4573. if (fncExprScope && !*pHasName)
  4574. {
  4575. FinishParseBlock(pnodeFncExprScope);
  4576. m_nextBlockId--;
  4577. Adelete(&m_nodeAllocator, fncExprScope);
  4578. fncExprScope = nullptr;
  4579. pnodeFncExprScope = nullptr;
  4580. }
  4581. if (pnodeFnc)
  4582. {
  4583. pnodeFnc->sxFnc.scope = fncExprScope;
  4584. }
  4585. // Start a new statement stack.
  4586. bool topLevelStmt =
  4587. buildAST &&
  4588. !fFunctionInBlock &&
  4589. (this->m_pstmtCur == nullptr || this->m_pstmtCur->pnodeStmt->nop == knopBlock);
  4590. pstmtSave = m_pstmtCur;
  4591. SetCurrentStatement(nullptr);
  4592. RestorePoint beginFormals;
  4593. m_pscan->Capture(&beginFormals);
  4594. BOOL fWasAlreadyStrictMode = IsStrictMode();
  4595. BOOL oldStrictMode = this->m_fUseStrictMode;
  4596. if (fLambda)
  4597. {
  4598. CHAKRATEL_LANGSTATS_INC_LANGFEATURECOUNT(Lambda, m_scriptContext);
  4599. }
  4600. uint uDeferSave = m_grfscr & fscrDeferFncParse;
  4601. if (flags & (fFncNoName | fFncLambda))
  4602. {
  4603. // Disable deferral on getter/setter or other construct with unusual text bounds
  4604. // (fFncNoName|fFncLambda) as these are usually trivial, and re-parsing is problematic.
  4605. // NOTE: It is probably worth supporting these cases for memory and load-time purposes,
  4606. // especially as they become more and more common.
  4607. m_grfscr &= ~fscrDeferFncParse;
  4608. }
  4609. bool isTopLevelDeferredFunc = false;
  4610. #if ENABLE_BACKGROUND_PARSING
  4611. struct AutoFastScanFlag {
  4612. bool savedDoingFastScan;
  4613. AutoFastScanFlag(Parser *parser) : m_parser(parser) { savedDoingFastScan = m_parser->m_doingFastScan; }
  4614. ~AutoFastScanFlag() { m_parser->m_doingFastScan = savedDoingFastScan; }
  4615. Parser *m_parser;
  4616. } flag(this);
  4617. #endif
  4618. bool doParallel = false;
  4619. bool parallelJobStarted = false;
  4620. if (buildAST)
  4621. {
  4622. bool isLikelyIIFE = !fDeclaration && pnodeFnc && fUnaryOrParen;
  4623. BOOL isDeferredFnc = IsDeferredFnc();
  4624. AnalysisAssert(isDeferredFnc || pnodeFnc);
  4625. // These are the conditions that prohibit upfront deferral *and* redeferral.
  4626. isTopLevelDeferredFunc =
  4627. (!fLambda
  4628. && pnodeFnc
  4629. && DeferredParse(pnodeFnc->sxFnc.functionId)
  4630. && (!pnodeFnc->sxFnc.IsNested() || CONFIG_FLAG(DeferNested))
  4631. && !m_InAsmMode
  4632. // Don't defer a module function wrapper because we need to do export resolution at parse time
  4633. && !fModule
  4634. );
  4635. if (pnodeFnc)
  4636. {
  4637. pnodeFnc->sxFnc.SetCanBeDeferred(isTopLevelDeferredFunc && PnFnc::CanBeRedeferred(pnodeFnc->sxFnc.fncFlags));
  4638. }
  4639. // These are heuristic conditions that prohibit upfront deferral but not redeferral.
  4640. isTopLevelDeferredFunc = isTopLevelDeferredFunc && !isDeferredFnc &&
  4641. (!isLikelyIIFE || !topLevelStmt || PHASE_FORCE_RAW(Js::DeferParsePhase, m_sourceContextInfo->sourceContextId, pnodeFnc->sxFnc.functionId));
  4642. #if ENABLE_BACKGROUND_PARSING
  4643. if (!fLambda &&
  4644. !isDeferredFnc &&
  4645. !isLikelyIIFE &&
  4646. !this->IsBackgroundParser() &&
  4647. !this->m_doingFastScan &&
  4648. !(pnodeFncSave && m_currDeferredStub) &&
  4649. !(this->m_parseType == ParseType_Deferred && this->m_functionBody && this->m_functionBody->GetScopeInfo() && !isTopLevelDeferredFunc))
  4650. {
  4651. doParallel = DoParallelParse(pnodeFnc);
  4652. if (doParallel)
  4653. {
  4654. BackgroundParser *bgp = m_scriptContext->GetBackgroundParser();
  4655. Assert(bgp);
  4656. if (bgp->HasFailedBackgroundParseItem())
  4657. {
  4658. Error(ERRsyntax);
  4659. }
  4660. doParallel = bgp->ParseBackgroundItem(this, pnodeFnc, isTopLevelDeferredFunc);
  4661. if (doParallel)
  4662. {
  4663. parallelJobStarted = true;
  4664. this->m_hasParallelJob = true;
  4665. this->m_doingFastScan = true;
  4666. doParallel = FastScanFormalsAndBody();
  4667. if (doParallel)
  4668. {
  4669. // Let the foreground thread take care of marking the limit on the function node,
  4670. // because in some cases this function's caller will want to change that limit,
  4671. // so we don't want the background thread to try and touch it.
  4672. pnodeFnc->ichLim = m_pscan->IchLimTok();
  4673. pnodeFnc->sxFnc.cbLim = m_pscan->IecpLimTok();
  4674. }
  4675. }
  4676. }
  4677. }
  4678. #endif
  4679. }
  4680. if (!doParallel)
  4681. {
  4682. // We don't want to, or couldn't, let the main thread scan past this function body, so parse
  4683. // it for real.
  4684. ParseNodePtr pnodeRealFnc = pnodeFnc;
  4685. if (parallelJobStarted)
  4686. {
  4687. // We have to deal with a failure to fast-scan the function (due to syntax error? "/"?) when
  4688. // a background thread may already have begun to work on the job. Both threads can't be allowed to
  4689. // operate on the same node.
  4690. pnodeFnc = CreateDummyFuncNode(fDeclaration);
  4691. }
  4692. AnalysisAssert(pnodeFnc);
  4693. ParseNodePtr pnodeBlock = StartParseBlock<buildAST>(PnodeBlockType::Parameter, ScopeType_Parameter);
  4694. AnalysisAssert(pnodeBlock != nullptr);
  4695. pnodeFnc->sxFnc.pnodeScopes = pnodeBlock;
  4696. m_ppnodeVar = &pnodeFnc->sxFnc.pnodeParams;
  4697. pnodeFnc->sxFnc.pnodeVars = nullptr;
  4698. ParseNodePtr* varNodesList = &pnodeFnc->sxFnc.pnodeVars;
  4699. ParseNodePtr argNode = nullptr;
  4700. if (!fModule && !fLambda)
  4701. {
  4702. ParseNodePtr *const ppnodeVarSave = m_ppnodeVar;
  4703. m_ppnodeVar = &pnodeFnc->sxFnc.pnodeVars;
  4704. // Create the built-in arguments symbol
  4705. argNode = this->AddArgumentsNodeToVars(pnodeFnc);
  4706. // Save the updated var list
  4707. varNodesList = m_ppnodeVar;
  4708. m_ppnodeVar = ppnodeVarSave;
  4709. }
  4710. ParseNodePtr *ppnodeScopeSave = nullptr;
  4711. ParseNodePtr *ppnodeExprScopeSave = nullptr;
  4712. ppnodeScopeSave = m_ppnodeScope;
  4713. if (pnodeBlock)
  4714. {
  4715. // This synthetic block scope will contain all the nested scopes.
  4716. m_ppnodeScope = &pnodeBlock->sxBlock.pnodeScopes;
  4717. pnodeBlock->sxBlock.pnodeStmt = pnodeFnc;
  4718. }
  4719. // Keep nested function declarations and expressions in the same list at function scope.
  4720. // (Indicate this by nulling out the current function expressions list.)
  4721. ppnodeExprScopeSave = m_ppnodeExprScope;
  4722. m_ppnodeExprScope = nullptr;
  4723. uint parenExprDepthSave = m_funcParenExprDepth;
  4724. m_funcParenExprDepth = 0;
  4725. if (!skipFormals)
  4726. {
  4727. bool fLambdaParamsSave = m_reparsingLambdaParams;
  4728. if (fLambda)
  4729. {
  4730. m_reparsingLambdaParams = true;
  4731. }
  4732. DeferredFunctionStub *saveDeferredStub = nullptr;
  4733. if (buildAST)
  4734. {
  4735. // Don't try to make use of stubs while parsing formals. Issues with arrow functions, nested functions.
  4736. saveDeferredStub = m_currDeferredStub;
  4737. m_currDeferredStub = nullptr;
  4738. }
  4739. this->ParseFncFormals<buildAST>(pnodeFnc, pnodeFncParent, flags, isTopLevelDeferredFunc);
  4740. if (buildAST)
  4741. {
  4742. m_currDeferredStub = saveDeferredStub;
  4743. }
  4744. m_reparsingLambdaParams = fLambdaParamsSave;
  4745. }
  4746. // Create function body scope
  4747. ParseNodePtr pnodeInnerBlock = StartParseBlock<buildAST>(PnodeBlockType::Function, ScopeType_FunctionBody);
  4748. // Set the parameter block's child to the function body block.
  4749. // The pnodeFnc->sxFnc.pnodeScopes list is constructed in such a way that it includes all the scopes in this list.
  4750. // For example if the param scope has one function and body scope has one function then the list will look like below,
  4751. // param scope block -> function decl from param scope -> body socpe block -> function decl from body scope.
  4752. *m_ppnodeScope = pnodeInnerBlock;
  4753. pnodeFnc->sxFnc.pnodeBodyScope = pnodeInnerBlock;
  4754. // This synthetic block scope will contain all the nested scopes.
  4755. m_ppnodeScope = &pnodeInnerBlock->sxBlock.pnodeScopes;
  4756. pnodeInnerBlock->sxBlock.pnodeStmt = pnodeFnc;
  4757. // DEFER: Begin deferral here (after names are parsed and name nodes created).
  4758. // Create no more AST nodes until we're done.
  4759. // Try to defer this func if all these are true:
  4760. // 0. We are not already in deferred parsing (i.e. buildAST is true)
  4761. // 1. We are not re-parsing a deferred func which is being invoked.
  4762. // 2. Dynamic profile suggests this func can be deferred (and deferred parse is on).
  4763. // 3. This func is top level or defer nested func is on.
  4764. // 4. Optionally, the function is non-nested and not in eval, or the deferral decision was based on cached profile info,
  4765. // or the function is sufficiently long. (I.e., don't defer little nested functions unless we're
  4766. // confident they'll never be executed, because un-deferring nested functions is more expensive.)
  4767. // NOTE: I'm disabling #4 by default, because we've found other ways to reduce the cost of un-deferral,
  4768. // and we don't want to create function bodies aggressively for little functions.
  4769. // We will also temporarily defer all asm.js functions, except for the asm.js
  4770. // module itself, which we will never defer
  4771. bool strictModeTurnedOn = false;
  4772. if (isTopLevelDeferredFunc &&
  4773. !(this->m_grfscr & fscrEvalCode) &&
  4774. pnodeFnc->sxFnc.IsNested() &&
  4775. #ifndef DISABLE_DYNAMIC_PROFILE_DEFER_PARSE
  4776. m_sourceContextInfo->sourceDynamicProfileManager == nullptr &&
  4777. #endif
  4778. PHASE_ON_RAW(Js::ScanAheadPhase, m_sourceContextInfo->sourceContextId, pnodeFnc->sxFnc.functionId) &&
  4779. (
  4780. !PHASE_FORCE_RAW(Js::DeferParsePhase, m_sourceContextInfo->sourceContextId, pnodeFnc->sxFnc.functionId) ||
  4781. PHASE_FORCE_RAW(Js::ScanAheadPhase, m_sourceContextInfo->sourceContextId, pnodeFnc->sxFnc.functionId)
  4782. ))
  4783. {
  4784. // Try to scan ahead to the end of the function. If we get there before we've scanned a minimum
  4785. // number of tokens, don't bother deferring, because it's too small.
  4786. if (this->ScanAheadToFunctionEnd(CONFIG_FLAG(MinDeferredFuncTokenCount)))
  4787. {
  4788. isTopLevelDeferredFunc = false;
  4789. }
  4790. }
  4791. Scope* paramScope = pnodeFnc->sxFnc.pnodeScopes ? pnodeFnc->sxFnc.pnodeScopes->sxBlock.scope : nullptr;
  4792. if (paramScope != nullptr)
  4793. {
  4794. if (CONFIG_FLAG(ForceSplitScope))
  4795. {
  4796. pnodeFnc->sxFnc.ResetBodyAndParamScopeMerged();
  4797. }
  4798. else if (pnodeFnc->sxFnc.HasNonSimpleParameterList() && pnodeFnc->sxFnc.IsBodyAndParamScopeMerged())
  4799. {
  4800. paramScope->ForEachSymbolUntil([this, paramScope, pnodeFnc](Symbol* sym) {
  4801. if (sym->GetPid()->GetTopRef()->GetFuncScopeId() > pnodeFnc->sxFnc.functionId)
  4802. {
  4803. // One of the symbol has non local reference. Mark the param scope as we can't merge it with body scope.
  4804. pnodeFnc->sxFnc.ResetBodyAndParamScopeMerged();
  4805. return true;
  4806. }
  4807. return false;
  4808. });
  4809. if (pnodeFnc->sxFnc.IsBodyAndParamScopeMerged() && !fDeclaration && pnodeFnc->sxFnc.pnodeName != nullptr)
  4810. {
  4811. Symbol* funcSym = pnodeFnc->sxFnc.pnodeName->sxVar.sym;
  4812. if (funcSym->GetPid()->GetTopRef()->GetFuncScopeId() > pnodeFnc->sxFnc.functionId)
  4813. {
  4814. // This is a function expression with name captured in the param scope. In non-eval, non-split cases the function
  4815. // name symbol is added to the body scope to make it accessible in the body. But if there is a function or var
  4816. // declaration with the same name in the body then adding to the body will fail. So in this case we have to add
  4817. // the name symbol to the param scope by splitting it.
  4818. pnodeFnc->sxFnc.ResetBodyAndParamScopeMerged();
  4819. }
  4820. }
  4821. }
  4822. }
  4823. // If the param scope is merged with the body scope we want to use the param scope symbols in the body scope.
  4824. // So add a pid ref for the body using the param scope symbol. Note that in this case the same symbol will occur twice
  4825. // in the same pid ref stack.
  4826. if (paramScope != nullptr && pnodeFnc->sxFnc.IsBodyAndParamScopeMerged())
  4827. {
  4828. paramScope->ForEachSymbol([this](Symbol* paramSym)
  4829. {
  4830. PidRefStack* ref = PushPidRef(paramSym->GetPid());
  4831. ref->SetSym(paramSym);
  4832. });
  4833. }
  4834. AssertMsg(m_funcParenExprDepth == 0, "Paren exprs should have been resolved by the time we finish function formals");
  4835. if (isTopLevelDeferredFunc || (m_InAsmMode && m_deferAsmJs))
  4836. {
  4837. #ifdef ASMJS_PLAT
  4838. if (m_InAsmMode && fLambda)
  4839. {
  4840. // asm.js doesn't support lambda functions
  4841. Js::AsmJSCompiler::OutputError(m_scriptContext, _u("Lambda functions are not supported."));
  4842. Js::AsmJSCompiler::OutputError(m_scriptContext, _u("Asm.js compilation failed."));
  4843. throw Js::AsmJsParseException();
  4844. }
  4845. #endif
  4846. AssertMsg(!fLambda, "Deferring function parsing of a function does not handle lambda syntax");
  4847. fDeferred = true;
  4848. this->ParseTopLevelDeferredFunc(pnodeFnc, pnodeFncSave, pNameHint);
  4849. }
  4850. else
  4851. {
  4852. if (m_token.tk == tkRParen) // This might be false due to error recovery or lambda.
  4853. {
  4854. m_pscan->Scan();
  4855. }
  4856. if (fLambda)
  4857. {
  4858. BOOL hadNewLine = m_pscan->FHadNewLine();
  4859. // it can be the case we do not have a fat arrow here if there is a valid expression on the left hand side
  4860. // of the fat arrow, but that expression does not parse as a parameter list. E.g.
  4861. // a.x => { }
  4862. // Therefore check for it and error if not found.
  4863. // LS Mode : since this is a lambda we supposed to get the fat arrow, if not we will skip till we get that fat arrow.
  4864. ChkCurTok(tkDArrow, ERRnoDArrow);
  4865. // Newline character between arrow parameters and fat arrow is a syntax error but we want to check for
  4866. // this after verifying there was a => token. Otherwise we would throw the wrong error.
  4867. if (hadNewLine)
  4868. {
  4869. Error(ERRsyntax);
  4870. }
  4871. }
  4872. AnalysisAssert(pnodeFnc);
  4873. // Shouldn't be any temps in the arg list.
  4874. Assert(*m_ppnodeVar == nullptr);
  4875. // Start the var list.
  4876. m_ppnodeVar = varNodesList;
  4877. if (!pnodeFnc->sxFnc.IsBodyAndParamScopeMerged())
  4878. {
  4879. OUTPUT_TRACE_DEBUGONLY(Js::ParsePhase, _u("The param and body scope of the function %s cannot be merged\n"), pnodeFnc->sxFnc.pnodeName ? pnodeFnc->sxFnc.pnodeName->sxVar.pid->Psz() : _u("Anonymous function"));
  4880. }
  4881. // Keep nested function declarations and expressions in the same list at function scope.
  4882. // (Indicate this by nulling out the current function expressions list.)
  4883. m_ppnodeExprScope = nullptr;
  4884. if (buildAST)
  4885. {
  4886. DeferredFunctionStub *saveCurrentStub = m_currDeferredStub;
  4887. if (pnodeFncSave && m_currDeferredStub)
  4888. {
  4889. // the Deferred stub will not match for the function which are defined on lambda formals.
  4890. // 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.
  4891. // 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
  4892. // 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
  4893. // functions and we want to avoid getting wrong stub.
  4894. if (pnodeFncSave->sxFnc.nestedCount == 1)
  4895. {
  4896. m_prevSiblingDeferredStub = nullptr;
  4897. }
  4898. if (m_prevSiblingDeferredStub == nullptr)
  4899. {
  4900. m_prevSiblingDeferredStub = (m_currDeferredStub + (pnodeFncSave->sxFnc.nestedCount - 1));
  4901. }
  4902. if (m_prevSiblingDeferredStub->ichMin == pnodeFnc->ichMin)
  4903. {
  4904. m_currDeferredStub = m_prevSiblingDeferredStub->deferredStubs;
  4905. m_prevSiblingDeferredStub = nullptr;
  4906. }
  4907. else
  4908. {
  4909. m_currDeferredStub = nullptr;
  4910. }
  4911. }
  4912. if (m_token.tk != tkLCurly && fLambda)
  4913. {
  4914. ParseExpressionLambdaBody<true>(pnodeFnc);
  4915. *pNeedScanRCurly = false;
  4916. }
  4917. else
  4918. {
  4919. this->FinishFncDecl(pnodeFnc, pNameHint, lastNodeRef, skipFormals);
  4920. }
  4921. m_currDeferredStub = saveCurrentStub;
  4922. }
  4923. else
  4924. {
  4925. this->ParseNestedDeferredFunc(pnodeFnc, fLambda, pNeedScanRCurly, &strictModeTurnedOn);
  4926. }
  4927. }
  4928. // Restore the paren count for any outer spread/rest error checking.
  4929. m_funcParenExprDepth = parenExprDepthSave;
  4930. if (pnodeInnerBlock)
  4931. {
  4932. FinishParseBlock(pnodeInnerBlock, *pNeedScanRCurly);
  4933. }
  4934. if (!fModule && (m_token.tk == tkLCurly || !fLambda))
  4935. {
  4936. UpdateArgumentsNode(pnodeFnc, argNode);
  4937. }
  4938. CreateSpecialSymbolDeclarations(pnodeFnc, false);
  4939. // Restore the lists of scopes that contain function expressions.
  4940. Assert(m_ppnodeExprScope == nullptr || *m_ppnodeExprScope == nullptr);
  4941. m_ppnodeExprScope = ppnodeExprScopeSave;
  4942. AssertMem(m_ppnodeScope);
  4943. Assert(nullptr == *m_ppnodeScope);
  4944. m_ppnodeScope = ppnodeScopeSave;
  4945. if (pnodeBlock)
  4946. {
  4947. FinishParseBlock(pnodeBlock, *pNeedScanRCurly);
  4948. }
  4949. if (IsStrictMode() || strictModeTurnedOn)
  4950. {
  4951. this->m_fUseStrictMode = TRUE; // Now we know this function is in strict mode
  4952. if (!fWasAlreadyStrictMode)
  4953. {
  4954. // If this function turned on strict mode then we didn't check the formal
  4955. // parameters or function name hint for future reserved word usage. So do that now.
  4956. RestorePoint afterFnc;
  4957. m_pscan->Capture(&afterFnc);
  4958. if (*pHasName)
  4959. {
  4960. // Rewind to the function name hint and check if the token is a reserved word.
  4961. m_pscan->SeekTo(beginNameHint);
  4962. m_pscan->Scan();
  4963. if (pnodeFnc->sxFnc.IsGenerator())
  4964. {
  4965. Assert(m_token.tk == tkStar);
  4966. Assert(m_scriptContext->GetConfig()->IsES6GeneratorsEnabled());
  4967. Assert(!(flags & fFncClassMember));
  4968. m_pscan->Scan();
  4969. }
  4970. if (m_token.IsReservedWord())
  4971. {
  4972. IdentifierExpectedError(m_token);
  4973. }
  4974. CheckStrictModeEvalArgumentsUsage(m_token.GetIdentifier(m_phtbl));
  4975. }
  4976. // Fast forward to formal parameter list, check for future reserved words,
  4977. // then restore scanner as it was.
  4978. m_pscan->SeekToForcingPid(beginFormals);
  4979. CheckStrictFormalParameters();
  4980. m_pscan->SeekTo(afterFnc);
  4981. }
  4982. if (buildAST)
  4983. {
  4984. if (pnodeFnc->sxFnc.pnodeName != nullptr && knopVarDecl == pnodeFnc->sxFnc.pnodeName->nop)
  4985. {
  4986. CheckStrictModeEvalArgumentsUsage(pnodeFnc->sxFnc.pnodeName->sxVar.pid, pnodeFnc->sxFnc.pnodeName);
  4987. }
  4988. }
  4989. this->m_fUseStrictMode = oldStrictMode;
  4990. CHAKRATEL_LANGSTATS_INC_LANGFEATURECOUNT(StrictModeFunction, m_scriptContext);
  4991. }
  4992. if (fDeferred)
  4993. {
  4994. AnalysisAssert(pnodeFnc);
  4995. pnodeFnc->sxFnc.pnodeVars = nullptr;
  4996. }
  4997. if (parallelJobStarted)
  4998. {
  4999. pnodeFnc = pnodeRealFnc;
  5000. m_currentNodeFunc = pnodeRealFnc;
  5001. // Let the foreground thread take care of marking the limit on the function node,
  5002. // because in some cases this function's caller will want to change that limit,
  5003. // so we don't want the background thread to try and touch it.
  5004. pnodeFnc->ichLim = m_pscan->IchLimTok();
  5005. pnodeFnc->sxFnc.cbLim = m_pscan->IecpLimTok();
  5006. }
  5007. }
  5008. // after parsing asm.js module, we want to reset asm.js state before continuing
  5009. AnalysisAssert(pnodeFnc);
  5010. if (pnodeFnc->sxFnc.GetAsmjsMode())
  5011. {
  5012. m_InAsmMode = false;
  5013. }
  5014. // Restore the statement stack.
  5015. Assert(nullptr == m_pstmtCur);
  5016. SetCurrentStatement(pstmtSave);
  5017. if (pnodeFncExprScope)
  5018. {
  5019. FinishParseFncExprScope(pnodeFnc, pnodeFncExprScope);
  5020. }
  5021. if (!m_stoppedDeferredParse)
  5022. {
  5023. m_grfscr |= uDeferSave;
  5024. }
  5025. m_pscan->SetYieldIsKeywordRegion(fPreviousYieldIsKeyword);
  5026. m_pscan->SetAwaitIsKeywordRegion(fPreviousAwaitIsKeyword);
  5027. // Restore the current function.
  5028. if (buildAST)
  5029. {
  5030. Assert(pnodeFnc == m_currentNodeFunc);
  5031. m_currentNodeFunc = pnodeFncSave;
  5032. m_pCurrentAstSize = pAstSizeSave;
  5033. if (!fLambda)
  5034. {
  5035. Assert(pnodeFnc == m_currentNodeNonLambdaFunc);
  5036. m_currentNodeNonLambdaFunc = pnodeFncSaveNonLambda;
  5037. }
  5038. }
  5039. else
  5040. {
  5041. Assert(pnodeFnc == m_currentNodeDeferredFunc);
  5042. if (!fLambda)
  5043. {
  5044. Assert(pnodeFnc == m_currentNodeNonLambdaDeferredFunc);
  5045. m_currentNodeNonLambdaDeferredFunc = pnodeFncSaveNonLambda;
  5046. }
  5047. m_currentNodeDeferredFunc = pnodeFncSave;
  5048. }
  5049. if (m_currentNodeFunc && pnodeFnc->sxFnc.HasWithStmt())
  5050. {
  5051. GetCurrentFunctionNode()->sxFnc.SetHasWithStmt(true);
  5052. }
  5053. return true;
  5054. }
  5055. template<bool buildAST>
  5056. void Parser::UpdateCurrentNodeFunc(ParseNodePtr pnodeFnc, bool fLambda)
  5057. {
  5058. if (buildAST)
  5059. {
  5060. // Make this the current function and start its sub-function list.
  5061. m_currentNodeFunc = pnodeFnc;
  5062. Assert(m_currentNodeDeferredFunc == nullptr);
  5063. if (!fLambda)
  5064. {
  5065. m_currentNodeNonLambdaFunc = pnodeFnc;
  5066. }
  5067. }
  5068. else // if !buildAST
  5069. {
  5070. AnalysisAssert(pnodeFnc);
  5071. if (!fLambda)
  5072. {
  5073. m_currentNodeNonLambdaDeferredFunc = pnodeFnc;
  5074. }
  5075. m_currentNodeDeferredFunc = pnodeFnc;
  5076. }
  5077. }
  5078. void Parser::ParseTopLevelDeferredFunc(ParseNodePtr pnodeFnc, ParseNodePtr pnodeFncParent, LPCOLESTR pNameHint)
  5079. {
  5080. // Parse a function body that is a transition point from building AST to doing fast syntax check.
  5081. pnodeFnc->sxFnc.pnodeVars = nullptr;
  5082. pnodeFnc->sxFnc.pnodeBody = nullptr;
  5083. this->m_deferringAST = TRUE;
  5084. // Put the scanner into "no hashing" mode.
  5085. BYTE deferFlags = m_pscan->SetDeferredParse(TRUE);
  5086. m_pscan->Scan();
  5087. ChkCurTok(tkLCurly, ERRnoLcurly);
  5088. ParseNodePtr *ppnodeVarSave = m_ppnodeVar;
  5089. m_ppnodeVar = &pnodeFnc->sxFnc.pnodeVars;
  5090. if (pnodeFncParent != nullptr
  5091. && m_currDeferredStub != nullptr
  5092. // We don't create stubs for function bodies in parameter scope.
  5093. && pnodeFnc->sxFnc.pnodeScopes->sxBlock.blockType != PnodeBlockType::Parameter)
  5094. {
  5095. // We've already parsed this function body for syntax errors on the initial parse of the script.
  5096. // We have information that allows us to skip it, so do so.
  5097. DeferredFunctionStub *stub = m_currDeferredStub + (pnodeFncParent->sxFnc.nestedCount - 1);
  5098. Assert(pnodeFnc->ichMin == stub->ichMin);
  5099. if (stub->fncFlags & kFunctionCallsEval)
  5100. {
  5101. this->MarkEvalCaller();
  5102. }
  5103. if (stub->fncFlags & kFunctionChildCallsEval)
  5104. {
  5105. pnodeFnc->sxFnc.SetChildCallsEval(true);
  5106. }
  5107. if (stub->fncFlags & kFunctionHasWithStmt)
  5108. {
  5109. pnodeFnc->sxFnc.SetHasWithStmt(true);
  5110. }
  5111. PHASE_PRINT_TRACE1(
  5112. Js::SkipNestedDeferredPhase,
  5113. _u("Skipping nested deferred function %d. %s: %d...%d\n"),
  5114. pnodeFnc->sxFnc.functionId, GetFunctionName(pnodeFnc, pNameHint), pnodeFnc->ichMin, stub->restorePoint.m_ichMinTok);
  5115. m_pscan->SeekTo(stub->restorePoint, m_nextFunctionId);
  5116. pnodeFnc->sxFnc.nestedCount = stub->nestedCount;
  5117. pnodeFnc->sxFnc.deferredStub = stub->deferredStubs;
  5118. if (stub->fncFlags & kFunctionStrictMode)
  5119. {
  5120. pnodeFnc->sxFnc.SetStrictMode(true);
  5121. }
  5122. }
  5123. else
  5124. {
  5125. ParseStmtList<false>(nullptr, nullptr, SM_DeferredParse, true /* isSourceElementList */);
  5126. }
  5127. pnodeFnc->ichLim = m_pscan->IchLimTok();
  5128. pnodeFnc->sxFnc.cbLim = m_pscan->IecpLimTok();
  5129. m_ppnodeVar = ppnodeVarSave;
  5130. // Restore the scanner's default hashing mode.
  5131. // Do this before we consume the next token.
  5132. m_pscan->SetDeferredParseFlags(deferFlags);
  5133. ChkCurTokNoScan(tkRCurly, ERRnoRcurly);
  5134. #if DBG
  5135. pnodeFnc->sxFnc.deferredParseNextFunctionId = *this->m_nextFunctionId;
  5136. #endif
  5137. this->m_deferringAST = FALSE;
  5138. }
  5139. bool Parser::DoParallelParse(ParseNodePtr pnodeFnc) const
  5140. {
  5141. #if ENABLE_BACKGROUND_PARSING
  5142. if (!PHASE_ON_RAW(Js::ParallelParsePhase, m_sourceContextInfo->sourceContextId, pnodeFnc->sxFnc.functionId))
  5143. {
  5144. return false;
  5145. }
  5146. BackgroundParser *bgp = m_scriptContext->GetBackgroundParser();
  5147. return bgp != nullptr;
  5148. #else
  5149. return false;
  5150. #endif
  5151. }
  5152. bool Parser::ScanAheadToFunctionEnd(uint count)
  5153. {
  5154. bool found = false;
  5155. uint curlyDepth = 0;
  5156. RestorePoint funcStart;
  5157. m_pscan->Capture(&funcStart);
  5158. for (uint i = 0; i < count; i++)
  5159. {
  5160. switch (m_token.tk)
  5161. {
  5162. case tkStrTmplBegin:
  5163. case tkStrTmplMid:
  5164. case tkStrTmplEnd:
  5165. case tkDiv:
  5166. case tkAsgDiv:
  5167. case tkScanError:
  5168. case tkEOF:
  5169. goto LEnd;
  5170. case tkLCurly:
  5171. UInt32Math::Inc(curlyDepth, Parser::OutOfMemory);
  5172. break;
  5173. case tkRCurly:
  5174. if (curlyDepth == 1)
  5175. {
  5176. found = true;
  5177. goto LEnd;
  5178. }
  5179. if (curlyDepth == 0)
  5180. {
  5181. goto LEnd;
  5182. }
  5183. curlyDepth--;
  5184. break;
  5185. }
  5186. m_pscan->ScanAhead();
  5187. }
  5188. LEnd:
  5189. m_pscan->SeekTo(funcStart);
  5190. return found;
  5191. }
  5192. bool Parser::FastScanFormalsAndBody()
  5193. {
  5194. // The scanner is currently pointing just past the name of a function.
  5195. // The idea here is to find the end of the function body as quickly as possible,
  5196. // by tokenizing and tracking {}'s if possible.
  5197. // String templates require some extra logic but can be handled.
  5198. // The real wrinkle is "/" and "/=", which may indicate either a RegExp literal or a division, depending
  5199. // on the context.
  5200. // To handle this with minimal work, keep track of the last ";" seen at each {} depth. If we see one of the
  5201. // difficult tokens, rewind to the last ";" at the current {} depth and parse statements until we pass the
  5202. // point where we had to rewind. This will process the "/" as required.
  5203. RestorePoint funcStart;
  5204. m_pscan->Capture(&funcStart);
  5205. const int maxRestorePointDepth = 16;
  5206. struct FastScanRestorePoint
  5207. {
  5208. RestorePoint restorePoint;
  5209. uint parenDepth;
  5210. Js::LocalFunctionId functionId;
  5211. int blockId;
  5212. FastScanRestorePoint() : restorePoint(), parenDepth(0) {};
  5213. };
  5214. FastScanRestorePoint lastSColonAtCurlyDepth[maxRestorePointDepth];
  5215. charcount_t ichStart = m_pscan->IchMinTok();
  5216. uint blockIdSave = m_nextBlockId;
  5217. uint functionIdSave = *m_nextFunctionId;
  5218. uint curlyDepth = 0;
  5219. uint strTmplDepth = 0;
  5220. for (;;)
  5221. {
  5222. switch (m_token.tk)
  5223. {
  5224. case tkStrTmplBegin:
  5225. UInt32Math::Inc(strTmplDepth, Parser::OutOfMemory);
  5226. // Fall through
  5227. case tkStrTmplMid:
  5228. case tkLCurly:
  5229. UInt32Math::Inc(curlyDepth, Parser::OutOfMemory);
  5230. Int32Math::Inc(m_nextBlockId, &m_nextBlockId);
  5231. break;
  5232. case tkStrTmplEnd:
  5233. // We can assert here, because the scanner will only return this token if we've told it we're
  5234. // in a string template.
  5235. Assert(strTmplDepth > 0);
  5236. strTmplDepth--;
  5237. break;
  5238. case tkRCurly:
  5239. if (curlyDepth == 1)
  5240. {
  5241. Assert(strTmplDepth == 0);
  5242. if (PHASE_TRACE1(Js::ParallelParsePhase))
  5243. {
  5244. Output::Print(_u("Finished fast seek: %d. %s -- %d...%d\n"),
  5245. m_currentNodeFunc->sxFnc.functionId,
  5246. GetFunctionName(m_currentNodeFunc, m_currentNodeFunc->sxFnc.hint),
  5247. ichStart, m_pscan->IchLimTok());
  5248. }
  5249. return true;
  5250. }
  5251. if (curlyDepth < maxRestorePointDepth)
  5252. {
  5253. lastSColonAtCurlyDepth[curlyDepth].restorePoint.m_ichMinTok = (uint)-1;
  5254. }
  5255. curlyDepth--;
  5256. if (strTmplDepth > 0)
  5257. {
  5258. m_pscan->SetScanState(Scanner_t::ScanState::ScanStateStringTemplateMiddleOrEnd);
  5259. }
  5260. break;
  5261. case tkSColon:
  5262. // Track the location of the ";" (if it's outside parens, as we don't, for instance, want
  5263. // to track the ";"'s in a for-loop header. If we find it's important to rewind within a paren
  5264. // expression, we can do something more sophisticated.)
  5265. if (curlyDepth < maxRestorePointDepth && lastSColonAtCurlyDepth[curlyDepth].parenDepth == 0)
  5266. {
  5267. m_pscan->Capture(&lastSColonAtCurlyDepth[curlyDepth].restorePoint);
  5268. lastSColonAtCurlyDepth[curlyDepth].functionId = *this->m_nextFunctionId;
  5269. lastSColonAtCurlyDepth[curlyDepth].blockId = m_nextBlockId;
  5270. }
  5271. break;
  5272. case tkLParen:
  5273. if (curlyDepth < maxRestorePointDepth)
  5274. {
  5275. UInt32Math::Inc(lastSColonAtCurlyDepth[curlyDepth].parenDepth);
  5276. }
  5277. break;
  5278. case tkRParen:
  5279. if (curlyDepth < maxRestorePointDepth)
  5280. {
  5281. Assert(lastSColonAtCurlyDepth[curlyDepth].parenDepth != 0);
  5282. lastSColonAtCurlyDepth[curlyDepth].parenDepth--;
  5283. }
  5284. break;
  5285. case tkID:
  5286. {
  5287. charcount_t tokLength = m_pscan->IchLimTok() - m_pscan->IchMinTok();
  5288. // Detect the function and class keywords so we can track function ID's.
  5289. // (In fast mode, the scanner doesn't distinguish keywords and doesn't point the token
  5290. // to a PID.)
  5291. // Detect try/catch/for to increment block count for them.
  5292. switch (tokLength)
  5293. {
  5294. case 3:
  5295. if (!memcmp(m_pscan->PchMinTok(), "try", 3) || !memcmp(m_pscan->PchMinTok(), "for", 3))
  5296. {
  5297. Int32Math::Inc(m_nextBlockId, &m_nextBlockId);
  5298. }
  5299. break;
  5300. case 5:
  5301. if (!memcmp(m_pscan->PchMinTok(), "catch", 5))
  5302. {
  5303. Int32Math::Inc(m_nextBlockId, &m_nextBlockId);
  5304. }
  5305. else if (!memcmp(m_pscan->PchMinTok(), "class", 5))
  5306. {
  5307. Int32Math::Inc(m_nextBlockId, &m_nextBlockId);
  5308. Int32Math::Inc(*this->m_nextFunctionId, (int*)this->m_nextFunctionId);
  5309. }
  5310. break;
  5311. case 8:
  5312. if (!memcmp(m_pscan->PchMinTok(), "function", 8))
  5313. {
  5314. // Account for the possible func expr scope or dummy block for missing {}'s around a declaration
  5315. Int32Math::Inc(m_nextBlockId, &m_nextBlockId);
  5316. Int32Math::Inc(*this->m_nextFunctionId, (int*)this->m_nextFunctionId);
  5317. }
  5318. break;
  5319. }
  5320. break;
  5321. }
  5322. case tkDArrow:
  5323. Int32Math::Inc(m_nextBlockId, &m_nextBlockId);
  5324. Int32Math::Inc(*this->m_nextFunctionId, (int*)this->m_nextFunctionId);
  5325. break;
  5326. case tkDiv:
  5327. case tkAsgDiv:
  5328. {
  5329. int opl;
  5330. OpCode nop;
  5331. tokens tkPrev = m_pscan->m_tkPrevious;
  5332. if ((m_pscan->m_phtbl->TokIsBinop(tkPrev, &opl, &nop) && nop != knopNone) ||
  5333. (m_pscan->m_phtbl->TokIsUnop(tkPrev, &opl, &nop) &&
  5334. nop != knopNone &&
  5335. tkPrev != tkInc &&
  5336. tkPrev != tkDec) ||
  5337. tkPrev == tkColon ||
  5338. tkPrev == tkLParen ||
  5339. tkPrev == tkLBrack ||
  5340. tkPrev == tkRETURN)
  5341. {
  5342. // Previous token indicates that we're starting an expression here and can't have a
  5343. // binary operator now.
  5344. // Assume this is a RegExp.
  5345. ParseRegExp<false>();
  5346. break;
  5347. }
  5348. uint tempCurlyDepth = curlyDepth < maxRestorePointDepth ? curlyDepth : maxRestorePointDepth - 1;
  5349. for (; tempCurlyDepth != (uint)-1; tempCurlyDepth--)
  5350. {
  5351. // We don't know whether we've got a RegExp or a divide. Rewind to the last safe ";"
  5352. // if we can and parse statements until we pass this point.
  5353. if (lastSColonAtCurlyDepth[tempCurlyDepth].restorePoint.m_ichMinTok != -1)
  5354. {
  5355. break;
  5356. }
  5357. }
  5358. if (tempCurlyDepth != (uint)-1)
  5359. {
  5360. ParseNodePtr pnodeFncSave = m_currentNodeFunc;
  5361. int32 *pastSizeSave = m_pCurrentAstSize;
  5362. uint *pnestedCountSave = m_pnestedCount;
  5363. ParseNodePtr *ppnodeScopeSave = m_ppnodeScope;
  5364. ParseNodePtr *ppnodeExprScopeSave = m_ppnodeExprScope;
  5365. ParseNodePtr pnodeFnc = CreateDummyFuncNode(true);
  5366. m_ppnodeScope = &pnodeFnc->sxFnc.pnodeScopes;
  5367. m_ppnodeExprScope = nullptr;
  5368. charcount_t ichStop = m_pscan->IchLimTok();
  5369. curlyDepth = tempCurlyDepth;
  5370. m_pscan->SeekTo(lastSColonAtCurlyDepth[tempCurlyDepth].restorePoint);
  5371. m_nextBlockId = lastSColonAtCurlyDepth[tempCurlyDepth].blockId;
  5372. *this->m_nextFunctionId = lastSColonAtCurlyDepth[tempCurlyDepth].functionId;
  5373. ParseNodePtr pnodeBlock = StartParseBlock<true>(PnodeBlockType::Function, ScopeType_FunctionBody);
  5374. m_pscan->Scan();
  5375. do
  5376. {
  5377. ParseStatement<false>();
  5378. }
  5379. while(m_pscan->IchMinTok() < ichStop);
  5380. FinishParseBlock(pnodeBlock);
  5381. m_currentNodeFunc = pnodeFncSave;
  5382. m_pCurrentAstSize = pastSizeSave;
  5383. m_pnestedCount = pnestedCountSave;
  5384. m_ppnodeScope = ppnodeScopeSave;
  5385. m_ppnodeExprScope = ppnodeExprScopeSave;
  5386. // We've already consumed the first token of the next statement, so just continue
  5387. // without a further scan.
  5388. continue;
  5389. }
  5390. }
  5391. // fall through to rewind to function start
  5392. case tkScanError:
  5393. case tkEOF:
  5394. // Unexpected token.
  5395. if (PHASE_TRACE1(Js::ParallelParsePhase))
  5396. {
  5397. Output::Print(_u("Failed fast seek: %d. %s -- %d...%d\n"),
  5398. m_currentNodeFunc->sxFnc.functionId,
  5399. GetFunctionName(m_currentNodeFunc, m_currentNodeFunc->sxFnc.hint),
  5400. ichStart, m_pscan->IchLimTok());
  5401. }
  5402. m_nextBlockId = blockIdSave;
  5403. *m_nextFunctionId = functionIdSave;
  5404. m_pscan->SeekTo(funcStart);
  5405. return false;
  5406. }
  5407. m_pscan->ScanNoKeywords();
  5408. }
  5409. }
  5410. ParseNodePtr Parser::CreateDummyFuncNode(bool fDeclaration)
  5411. {
  5412. // Create a dummy node and make it look like the current function declaration.
  5413. // Do this in situations where we want to parse statements without impacting
  5414. // the state of the "real" AST.
  5415. ParseNodePtr pnodeFnc = CreateNode(knopFncDecl);
  5416. pnodeFnc->sxFnc.ClearFlags();
  5417. pnodeFnc->sxFnc.SetDeclaration(fDeclaration);
  5418. pnodeFnc->sxFnc.astSize = 0;
  5419. pnodeFnc->sxFnc.pnodeName = nullptr;
  5420. pnodeFnc->sxFnc.pnodeScopes = nullptr;
  5421. pnodeFnc->sxFnc.pnodeRest = nullptr;
  5422. pnodeFnc->sxFnc.pid = nullptr;
  5423. pnodeFnc->sxFnc.hint = nullptr;
  5424. pnodeFnc->sxFnc.hintOffset = 0;
  5425. pnodeFnc->sxFnc.hintLength = 0;
  5426. pnodeFnc->sxFnc.isNameIdentifierRef = true;
  5427. pnodeFnc->sxFnc.nestedFuncEscapes = false;
  5428. pnodeFnc->sxFnc.pnodeNext = nullptr;
  5429. pnodeFnc->sxFnc.pnodeParams = nullptr;
  5430. pnodeFnc->sxFnc.pnodeVars = nullptr;
  5431. pnodeFnc->sxFnc.funcInfo = nullptr;
  5432. pnodeFnc->sxFnc.deferredStub = nullptr;
  5433. pnodeFnc->sxFnc.nestedCount = 0;
  5434. pnodeFnc->sxFnc.SetNested(m_currentNodeFunc != nullptr); // If there is a current function, then we're a nested function.
  5435. pnodeFnc->sxFnc.SetStrictMode(IsStrictMode()); // Inherit current strict mode -- may be overridden by the function itself if it contains a strict mode directive.
  5436. pnodeFnc->sxFnc.firstDefaultArg = 0;
  5437. pnodeFnc->sxFnc.isBodyAndParamScopeMerged = true;
  5438. m_pCurrentAstSize = &pnodeFnc->sxFnc.astSize;
  5439. m_currentNodeFunc = pnodeFnc;
  5440. m_pnestedCount = &pnodeFnc->sxFnc.nestedCount;
  5441. return pnodeFnc;
  5442. }
  5443. void Parser::ParseNestedDeferredFunc(ParseNodePtr pnodeFnc, bool fLambda, bool *pNeedScanRCurly, bool *pStrictModeTurnedOn)
  5444. {
  5445. // Parse a function nested inside another deferred function.
  5446. size_t lengthBeforeBody = this->GetSourceLength();
  5447. if (m_token.tk != tkLCurly && fLambda)
  5448. {
  5449. ParseExpressionLambdaBody<false>(pnodeFnc);
  5450. *pNeedScanRCurly = false;
  5451. }
  5452. else
  5453. {
  5454. ChkCurTok(tkLCurly, ERRnoLcurly);
  5455. bool* detectStrictModeOn = IsStrictMode() ? nullptr : pStrictModeTurnedOn;
  5456. m_ppnodeVar = &m_currentNodeDeferredFunc->sxFnc.pnodeVars;
  5457. ParseStmtList<false>(nullptr, nullptr, SM_DeferredParse, true /* isSourceElementList */, detectStrictModeOn);
  5458. ChkCurTokNoScan(tkRCurly, ERRnoRcurly);
  5459. }
  5460. pnodeFnc->ichLim = m_pscan->IchLimTok();
  5461. pnodeFnc->sxFnc.cbLim = m_pscan->IecpLimTok();
  5462. if (*pStrictModeTurnedOn)
  5463. {
  5464. pnodeFnc->sxFnc.SetStrictMode(true);
  5465. }
  5466. if (!PHASE_OFF1(Js::SkipNestedDeferredPhase))
  5467. {
  5468. // Record the end of the function and the function ID increment that happens inside the function.
  5469. // Byte code gen will use this to build stub information to allow us to skip this function when the
  5470. // enclosing function is fully parsed.
  5471. RestorePoint *restorePoint = Anew(&m_nodeAllocator, RestorePoint);
  5472. m_pscan->Capture(restorePoint,
  5473. *m_nextFunctionId - pnodeFnc->sxFnc.functionId - 1,
  5474. lengthBeforeBody - this->GetSourceLength());
  5475. pnodeFnc->sxFnc.pRestorePoint = restorePoint;
  5476. }
  5477. }
  5478. template<bool buildAST>
  5479. bool Parser::ParseFncNames(ParseNodePtr pnodeFnc, ParseNodePtr pnodeFncParent, ushort flags, ParseNodePtr **pLastNodeRef)
  5480. {
  5481. BOOL fDeclaration = flags & fFncDeclaration;
  5482. BOOL fIsAsync = flags & fFncAsync;
  5483. ParseNodePtr pnodeT;
  5484. charcount_t ichMinNames, ichLimNames;
  5485. // Get the names to bind to.
  5486. /*
  5487. * KaushiS [5/15/08]:
  5488. * ECMAScript defines a FunctionExpression as follows:
  5489. *
  5490. * "function" [Identifier] ( [FormalParameterList] ) { FunctionBody }
  5491. *
  5492. * The function name being optional is omitted by most real world
  5493. * code that uses a FunctionExpression to define a function. This however
  5494. * is problematic for tools because there isn't a function name that
  5495. * the runtime can provide.
  5496. *
  5497. * To fix this (primarily for the profiler), I'm adding simple, static
  5498. * name inferencing logic to the parser. When it encounters the following
  5499. * productions
  5500. *
  5501. * "var" Identifier "=" FunctionExpression
  5502. * "var" IdentifierA.IdentifierB...Identifier "=" FunctionExpression
  5503. * Identifier = FunctionExpression
  5504. * "{" Identifier: FunctionExpression "}"
  5505. *
  5506. * it associates Identifier with the function created by the
  5507. * FunctionExpression. This identifier is *not* the function's name. It
  5508. * is ignored by the runtime and is only an additional piece of information
  5509. * about the function (function name hint) that tools could opt to
  5510. * surface.
  5511. */
  5512. m_pscan->Scan();
  5513. // If generators are enabled then we are in a recent enough version
  5514. // that deferred parsing will create a parse node for pnodeFnc and
  5515. // it is safe to assume it is not null.
  5516. if (flags & fFncGenerator)
  5517. {
  5518. Assert(m_scriptContext->GetConfig()->IsES6GeneratorsEnabled());
  5519. pnodeFnc->sxFnc.SetIsGenerator();
  5520. }
  5521. else if (m_scriptContext->GetConfig()->IsES6GeneratorsEnabled() &&
  5522. m_token.tk == tkStar &&
  5523. !(flags & fFncClassMember))
  5524. {
  5525. if (!fDeclaration)
  5526. {
  5527. bool fPreviousYieldIsKeyword = m_pscan->SetYieldIsKeywordRegion(!fDeclaration);
  5528. m_pscan->Scan();
  5529. m_pscan->SetYieldIsKeywordRegion(fPreviousYieldIsKeyword);
  5530. }
  5531. else
  5532. {
  5533. m_pscan->Scan();
  5534. }
  5535. pnodeFnc->sxFnc.SetIsGenerator();
  5536. }
  5537. if (fIsAsync)
  5538. {
  5539. if (pnodeFnc->sxFnc.IsGenerator())
  5540. {
  5541. Error(ERRsyntax);
  5542. }
  5543. pnodeFnc->sxFnc.SetIsAsync();
  5544. }
  5545. if (pnodeFnc)
  5546. {
  5547. pnodeFnc->sxFnc.pnodeName = nullptr;
  5548. }
  5549. if ((m_token.tk != tkID || flags & fFncNoName)
  5550. && (IsStrictMode() || (pnodeFnc && pnodeFnc->sxFnc.IsGenerator()) || m_token.tk != tkYIELD || fDeclaration)) // Function expressions can have the name yield even inside generator functions
  5551. {
  5552. if (fDeclaration ||
  5553. m_token.IsReservedWord()) // For example: var x = (function break(){});
  5554. {
  5555. IdentifierExpectedError(m_token);
  5556. }
  5557. return false;
  5558. }
  5559. ichMinNames = m_pscan->IchMinTok();
  5560. Assert(m_token.tk == tkID || (m_token.tk == tkYIELD && !fDeclaration));
  5561. if (IsStrictMode())
  5562. {
  5563. CheckStrictModeEvalArgumentsUsage(m_token.GetIdentifier(m_phtbl));
  5564. }
  5565. Token tokenBase = m_token;
  5566. charcount_t ichMinBase = m_pscan->IchMinTok();
  5567. charcount_t ichLimBase = m_pscan->IchLimTok();
  5568. m_pscan->Scan();
  5569. IdentPtr pidBase = tokenBase.GetIdentifier(m_phtbl);
  5570. pnodeT = CreateDeclNode(knopVarDecl, pidBase, STFunction);
  5571. pnodeT->ichMin = ichMinBase;
  5572. pnodeT->ichLim = ichLimBase;
  5573. if (fDeclaration &&
  5574. pnodeFncParent &&
  5575. pnodeFncParent->sxFnc.pnodeName &&
  5576. pnodeFncParent->sxFnc.pnodeName->nop == knopVarDecl &&
  5577. pnodeFncParent->sxFnc.pnodeName->sxVar.pid == pidBase)
  5578. {
  5579. pnodeFncParent->sxFnc.SetNameIsHidden();
  5580. }
  5581. if (buildAST)
  5582. {
  5583. AnalysisAssert(pnodeFnc);
  5584. ichLimNames = pnodeT->ichLim;
  5585. AddToNodeList(&pnodeFnc->sxFnc.pnodeName, pLastNodeRef, pnodeT);
  5586. pnodeFnc->sxFnc.pnodeName->ichMin = ichMinNames;
  5587. pnodeFnc->sxFnc.pnodeName->ichLim = ichLimNames;
  5588. if (knopVarDecl == pnodeFnc->sxFnc.pnodeName->nop)
  5589. {
  5590. // Only one name (the common case).
  5591. pnodeFnc->sxFnc.pid = pnodeFnc->sxFnc.pnodeName->sxVar.pid;
  5592. }
  5593. else
  5594. {
  5595. // Multiple names. Turn the source into an IdentPtr.
  5596. pnodeFnc->sxFnc.pid = m_phtbl->PidHashNameLen(
  5597. m_pscan->PchBase() + ichMinNames,
  5598. m_pscan->AdjustedLast(),
  5599. ichLimNames - ichMinNames);
  5600. }
  5601. }
  5602. return true;
  5603. }
  5604. void Parser::ValidateFormals()
  5605. {
  5606. ParseFncFormals<false>(nullptr, nullptr, fFncNoFlgs);
  5607. // Eat the tkRParen. The ParseFncDeclHelper caller expects to see it.
  5608. m_pscan->Scan();
  5609. }
  5610. void Parser::ValidateSourceElementList()
  5611. {
  5612. ParseStmtList<false>(nullptr, nullptr, SM_NotUsed, true);
  5613. }
  5614. void Parser::UpdateOrCheckForDuplicateInFormals(IdentPtr pid, SList<IdentPtr> *formals)
  5615. {
  5616. bool isStrictMode = IsStrictMode();
  5617. if (isStrictMode)
  5618. {
  5619. CheckStrictModeEvalArgumentsUsage(pid);
  5620. }
  5621. if (formals->Has(pid))
  5622. {
  5623. if (isStrictMode)
  5624. {
  5625. Error(ERRES5ArgSame);
  5626. }
  5627. else
  5628. {
  5629. Error(ERRFormalSame);
  5630. }
  5631. }
  5632. else
  5633. {
  5634. formals->Prepend(pid);
  5635. }
  5636. }
  5637. template<bool buildAST>
  5638. void Parser::ParseFncFormals(ParseNodePtr pnodeFnc, ParseNodePtr pnodeParentFnc, ushort flags, bool isTopLevelDeferredFunc)
  5639. {
  5640. bool fLambda = (flags & fFncLambda) != 0;
  5641. bool fMethod = (flags & fFncMethod) != 0;
  5642. bool fNoArg = (flags & fFncNoArg) != 0;
  5643. bool fOneArg = (flags & fFncOneArg) != 0;
  5644. bool fAsync = (flags & fFncAsync) != 0;
  5645. bool fPreviousYieldIsKeyword = false;
  5646. bool fPreviousAwaitIsKeyword = false;
  5647. if (fLambda)
  5648. {
  5649. fPreviousYieldIsKeyword = m_pscan->SetYieldIsKeywordRegion(pnodeParentFnc != nullptr && pnodeParentFnc->sxFnc.IsGenerator());
  5650. fPreviousAwaitIsKeyword = m_pscan->SetAwaitIsKeywordRegion(fAsync || (pnodeParentFnc != nullptr && pnodeParentFnc->sxFnc.IsAsync()));
  5651. }
  5652. Assert(!fNoArg || !fOneArg); // fNoArg and fOneArg can never be true at the same time.
  5653. // strictFormals corresponds to the StrictFormalParameters grammar production
  5654. // in the ES spec which just means duplicate names are not allowed
  5655. bool fStrictFormals = IsStrictMode() || fLambda || fMethod;
  5656. // When detecting duplicated formals pids are needed so force PID creation (unless the function should take 0 or 1 arg).
  5657. bool forcePid = fStrictFormals && !fNoArg && !fOneArg;
  5658. AutoTempForcePid autoForcePid(m_pscan, forcePid);
  5659. // Lambda's allow single formal specified by a single binding identifier without parentheses, special case it.
  5660. if (fLambda && m_token.tk == tkID)
  5661. {
  5662. IdentPtr pid = m_token.GetIdentifier(m_phtbl);
  5663. CreateVarDeclNode(pid, STFormal, false, nullptr, false);
  5664. CheckPidIsValid(pid);
  5665. m_pscan->Scan();
  5666. if (m_token.tk != tkDArrow)
  5667. {
  5668. Error(ERRsyntax, m_pscan->IchMinTok(), m_pscan->IchLimTok());
  5669. }
  5670. if (fLambda)
  5671. {
  5672. m_pscan->SetYieldIsKeywordRegion(fPreviousYieldIsKeyword);
  5673. m_pscan->SetAwaitIsKeywordRegion(fPreviousAwaitIsKeyword);
  5674. }
  5675. return;
  5676. }
  5677. else if (fLambda && m_token.tk == tkAWAIT)
  5678. {
  5679. // async await => {}
  5680. IdentifierExpectedError(m_token);
  5681. }
  5682. // Otherwise, must have a parameter list within parens.
  5683. ChkCurTok(tkLParen, ERRnoLparen);
  5684. // Now parse the list of arguments, if present
  5685. if (m_token.tk == tkRParen)
  5686. {
  5687. if (fOneArg)
  5688. {
  5689. Error(ERRSetterMustHaveOneParameter);
  5690. }
  5691. }
  5692. else
  5693. {
  5694. if (fNoArg)
  5695. {
  5696. Error(ERRGetterMustHaveNoParameters);
  5697. }
  5698. SList<IdentPtr> formals(&m_nodeAllocator);
  5699. ParseNodePtr pnodeT = nullptr;
  5700. bool seenRestParameter = false;
  5701. bool isNonSimpleParameterList = false;
  5702. for (Js::ArgSlot argPos = 0; ; ++argPos)
  5703. {
  5704. bool isBindingPattern = false;
  5705. if (m_scriptContext->GetConfig()->IsES6RestEnabled() && m_token.tk == tkEllipsis)
  5706. {
  5707. // Possible rest parameter
  5708. m_pscan->Scan();
  5709. seenRestParameter = true;
  5710. }
  5711. if (m_token.tk != tkID)
  5712. {
  5713. if (IsES6DestructuringEnabled() && IsPossiblePatternStart())
  5714. {
  5715. // Mark that the function has a non simple parameter list before parsing the pattern since the pattern can have function definitions.
  5716. this->GetCurrentFunctionNode()->sxFnc.SetHasNonSimpleParameterList();
  5717. this->GetCurrentFunctionNode()->sxFnc.SetHasDestructuredParams();
  5718. ParseNodePtr *const ppnodeVarSave = m_ppnodeVar;
  5719. m_ppnodeVar = &pnodeFnc->sxFnc.pnodeVars;
  5720. ParseNodePtr * ppNodeLex = m_currentBlockInfo->m_ppnodeLex;
  5721. Assert(ppNodeLex != nullptr);
  5722. ParseNodePtr paramPattern = nullptr;
  5723. ParseNodePtr pnodePattern = nullptr;
  5724. if (isTopLevelDeferredFunc)
  5725. {
  5726. pnodePattern = ParseDestructuredLiteral<false>(tkLET, true /*isDecl*/, false /*topLevel*/);
  5727. }
  5728. else
  5729. {
  5730. pnodePattern = ParseDestructuredLiteral<buildAST>(tkLET, true /*isDecl*/, false /*topLevel*/);
  5731. }
  5732. // Instead of passing the STFormal all the way on many methods, it seems it is better to change the symbol type afterward.
  5733. for (ParseNodePtr lexNode = *ppNodeLex; lexNode != nullptr; lexNode = lexNode->sxVar.pnodeNext)
  5734. {
  5735. Assert(lexNode->IsVarLetOrConst());
  5736. UpdateOrCheckForDuplicateInFormals(lexNode->sxVar.pid, &formals);
  5737. lexNode->sxVar.sym->SetSymbolType(STFormal);
  5738. if (lexNode->sxVar.pid == wellKnownPropertyPids.arguments)
  5739. {
  5740. GetCurrentFunctionNode()->grfpn |= PNodeFlags::fpnArguments_overriddenInParam;
  5741. }
  5742. }
  5743. m_ppnodeVar = ppnodeVarSave;
  5744. if (buildAST)
  5745. {
  5746. if (isTopLevelDeferredFunc)
  5747. {
  5748. Assert(pnodePattern == nullptr);
  5749. // Create a dummy pattern node as we need the node to be considered for the param count
  5750. paramPattern = CreateDummyParamPatternNode(m_pscan->IchMinTok());
  5751. }
  5752. else
  5753. {
  5754. Assert(pnodePattern);
  5755. paramPattern = CreateParamPatternNode(pnodePattern);
  5756. }
  5757. // Linking the current formal parameter (which is pattern parameter) with other formals.
  5758. *m_ppnodeVar = paramPattern;
  5759. paramPattern->sxParamPattern.pnodeNext = nullptr;
  5760. m_ppnodeVar = &paramPattern->sxParamPattern.pnodeNext;
  5761. }
  5762. isBindingPattern = true;
  5763. isNonSimpleParameterList = true;
  5764. }
  5765. else
  5766. {
  5767. IdentifierExpectedError(m_token);
  5768. }
  5769. }
  5770. if (!isBindingPattern)
  5771. {
  5772. IdentPtr pid = m_token.GetIdentifier(m_phtbl);
  5773. LPCOLESTR pNameHint = pid->Psz();
  5774. uint32 nameHintLength = pid->Cch();
  5775. uint32 nameHintOffset = 0;
  5776. if (seenRestParameter)
  5777. {
  5778. this->GetCurrentFunctionNode()->sxFnc.SetHasNonSimpleParameterList();
  5779. if (flags & fFncOneArg)
  5780. {
  5781. // The parameter of a setter cannot be a rest parameter.
  5782. Error(ERRUnexpectedEllipsis);
  5783. }
  5784. pnodeT = CreateDeclNode(knopVarDecl, pid, STFormal, false);
  5785. pnodeT->sxVar.sym->SetIsNonSimpleParameter(true);
  5786. if (buildAST)
  5787. {
  5788. // When only validating formals, we won't have a function node.
  5789. pnodeFnc->sxFnc.pnodeRest = pnodeT;
  5790. if (!isNonSimpleParameterList)
  5791. {
  5792. // This is the first non-simple parameter we've seen. We need to go back
  5793. // and set the Symbols of all previous parameters.
  5794. MapFormalsWithoutRest(m_currentNodeFunc, [&](ParseNodePtr pnodeArg) { pnodeArg->sxVar.sym->SetIsNonSimpleParameter(true); });
  5795. }
  5796. }
  5797. isNonSimpleParameterList = true;
  5798. }
  5799. else
  5800. {
  5801. pnodeT = CreateVarDeclNode(pid, STFormal, false, nullptr, false);
  5802. if (isNonSimpleParameterList)
  5803. {
  5804. pnodeT->sxVar.sym->SetIsNonSimpleParameter(true);
  5805. }
  5806. }
  5807. if (buildAST && pid == wellKnownPropertyPids.arguments)
  5808. {
  5809. // This formal parameter overrides the built-in 'arguments' object
  5810. m_currentNodeFunc->grfpn |= PNodeFlags::fpnArguments_overriddenInParam;
  5811. }
  5812. if (fStrictFormals)
  5813. {
  5814. UpdateOrCheckForDuplicateInFormals(pid, &formals);
  5815. }
  5816. m_pscan->Scan();
  5817. if (seenRestParameter && m_token.tk != tkRParen && m_token.tk != tkAsg)
  5818. {
  5819. Error(ERRRestLastArg);
  5820. }
  5821. if (m_token.tk == tkAsg && m_scriptContext->GetConfig()->IsES6DefaultArgsEnabled())
  5822. {
  5823. if (seenRestParameter && m_scriptContext->GetConfig()->IsES6RestEnabled())
  5824. {
  5825. Error(ERRRestWithDefault);
  5826. }
  5827. // In defer parse mode we have to flag the function node to indicate that it has default arguments
  5828. // so that it will be considered for any syntax error scenario.
  5829. // Also mark it before parsing the expression as it may contain functions.
  5830. ParseNode* currentFncNode = GetCurrentFunctionNode();
  5831. if (!currentFncNode->sxFnc.HasDefaultArguments())
  5832. {
  5833. currentFncNode->sxFnc.SetHasDefaultArguments();
  5834. currentFncNode->sxFnc.SetHasNonSimpleParameterList();
  5835. currentFncNode->sxFnc.firstDefaultArg = argPos;
  5836. }
  5837. m_pscan->Scan();
  5838. ParseNodePtr pnodeInit;
  5839. if (isTopLevelDeferredFunc)
  5840. {
  5841. // Defer default expressions if the function will be deferred, since we know they can't be evaluated
  5842. // until the function is fully compiled, and generating code for a function nested inside a deferred function
  5843. // creates inconsistencies.
  5844. pnodeInit = ParseExpr<false>(koplCma, nullptr, TRUE, FALSE, pNameHint, &nameHintLength, &nameHintOffset);
  5845. }
  5846. else
  5847. {
  5848. pnodeInit = ParseExpr<buildAST>(koplCma, nullptr, TRUE, FALSE, pNameHint, &nameHintLength, &nameHintOffset);
  5849. }
  5850. if (buildAST && pnodeInit && pnodeInit->nop == knopFncDecl)
  5851. {
  5852. Assert(nameHintLength >= nameHintOffset);
  5853. pnodeInit->sxFnc.hint = pNameHint;
  5854. pnodeInit->sxFnc.hintLength = nameHintLength;
  5855. pnodeInit->sxFnc.hintOffset = nameHintOffset;
  5856. }
  5857. AnalysisAssert(pnodeT);
  5858. pnodeT->sxVar.sym->SetIsNonSimpleParameter(true);
  5859. if (!isNonSimpleParameterList)
  5860. {
  5861. if (buildAST)
  5862. {
  5863. // This is the first non-simple parameter we've seen. We need to go back
  5864. // and set the Symbols of all previous parameters.
  5865. MapFormalsWithoutRest(m_currentNodeFunc, [&](ParseNodePtr pnodeArg) { pnodeArg->sxVar.sym->SetIsNonSimpleParameter(true); });
  5866. }
  5867. // There may be previous parameters that need to be checked for duplicates.
  5868. isNonSimpleParameterList = true;
  5869. }
  5870. if (buildAST)
  5871. {
  5872. if (!m_currentNodeFunc->sxFnc.HasDefaultArguments())
  5873. {
  5874. CHAKRATEL_LANGSTATS_INC_LANGFEATURECOUNT(DefaultArgFunction, m_scriptContext);
  5875. }
  5876. pnodeT->sxVar.pnodeInit = pnodeInit;
  5877. pnodeT->ichLim = m_pscan->IchLimTok();
  5878. }
  5879. }
  5880. }
  5881. if (isNonSimpleParameterList && m_currentScope->GetHasDuplicateFormals())
  5882. {
  5883. Error(ERRFormalSame);
  5884. }
  5885. if (flags & fFncOneArg)
  5886. {
  5887. if (m_token.tk != tkRParen)
  5888. {
  5889. Error(ERRSetterMustHaveOneParameter);
  5890. }
  5891. break; //enforce only one arg
  5892. }
  5893. if (m_token.tk != tkComma)
  5894. {
  5895. break;
  5896. }
  5897. m_pscan->Scan();
  5898. if (m_token.tk == tkRParen && m_scriptContext->GetConfig()->IsES7TrailingCommaEnabled())
  5899. {
  5900. break;
  5901. }
  5902. }
  5903. if (seenRestParameter)
  5904. {
  5905. CHAKRATEL_LANGSTATS_INC_LANGFEATURECOUNT(Rest, m_scriptContext);
  5906. }
  5907. if (m_token.tk != tkRParen)
  5908. {
  5909. Error(ERRnoRparen);
  5910. }
  5911. if (this->GetCurrentFunctionNode()->sxFnc.CallsEval() || this->GetCurrentFunctionNode()->sxFnc.ChildCallsEval())
  5912. {
  5913. Assert(pnodeFnc->sxFnc.HasNonSimpleParameterList());
  5914. pnodeFnc->sxFnc.ResetBodyAndParamScopeMerged();
  5915. }
  5916. }
  5917. Assert(m_token.tk == tkRParen);
  5918. if (fLambda)
  5919. {
  5920. m_pscan->SetYieldIsKeywordRegion(fPreviousYieldIsKeyword);
  5921. m_pscan->SetAwaitIsKeywordRegion(fPreviousAwaitIsKeyword);
  5922. }
  5923. }
  5924. template<bool buildAST>
  5925. ParseNodePtr Parser::GenerateModuleFunctionWrapper()
  5926. {
  5927. ParseNodePtr pnodeFnc = ParseFncDecl<buildAST>(fFncModule, nullptr, false, true, true);
  5928. ParseNodePtr callNode = CreateCallNode(knopCall, pnodeFnc, nullptr);
  5929. return callNode;
  5930. }
  5931. template<bool buildAST>
  5932. ParseNodePtr Parser::GenerateEmptyConstructor(bool extends)
  5933. {
  5934. ParseNodePtr pnodeFnc;
  5935. // Create the node.
  5936. pnodeFnc = CreateNode(knopFncDecl);
  5937. pnodeFnc->sxFnc.ClearFlags();
  5938. pnodeFnc->sxFnc.SetNested(NULL != m_currentNodeFunc);
  5939. pnodeFnc->sxFnc.SetStrictMode();
  5940. pnodeFnc->sxFnc.SetDeclaration(TRUE);
  5941. pnodeFnc->sxFnc.SetIsMethod(TRUE);
  5942. pnodeFnc->sxFnc.SetIsClassMember(TRUE);
  5943. pnodeFnc->sxFnc.SetIsClassConstructor(TRUE);
  5944. pnodeFnc->sxFnc.SetIsBaseClassConstructor(!extends);
  5945. pnodeFnc->sxFnc.SetHasNonThisStmt();
  5946. pnodeFnc->sxFnc.SetIsGeneratedDefault(TRUE);
  5947. pnodeFnc->ichLim = m_pscan->IchLimTok();
  5948. pnodeFnc->ichMin = m_pscan->IchMinTok();
  5949. pnodeFnc->sxFnc.cbLim = m_pscan->IecpLimTok();
  5950. pnodeFnc->sxFnc.cbMin = m_pscan->IecpMinTok();
  5951. pnodeFnc->sxFnc.astSize = 0;
  5952. pnodeFnc->sxFnc.lineNumber = m_pscan->LineCur();
  5953. pnodeFnc->sxFnc.functionId = (*m_nextFunctionId);
  5954. pnodeFnc->sxFnc.pid = nullptr;
  5955. pnodeFnc->sxFnc.hint = nullptr;
  5956. pnodeFnc->sxFnc.hintOffset = 0;
  5957. pnodeFnc->sxFnc.hintLength = 0;
  5958. pnodeFnc->sxFnc.isNameIdentifierRef = true;
  5959. pnodeFnc->sxFnc.nestedFuncEscapes = false;
  5960. pnodeFnc->sxFnc.pnodeName = nullptr;
  5961. pnodeFnc->sxFnc.pnodeScopes = nullptr;
  5962. pnodeFnc->sxFnc.pnodeParams = nullptr;
  5963. pnodeFnc->sxFnc.pnodeVars = nullptr;
  5964. pnodeFnc->sxFnc.pnodeBody = nullptr;
  5965. pnodeFnc->sxFnc.nestedCount = 0;
  5966. pnodeFnc->sxFnc.pnodeNext = nullptr;
  5967. pnodeFnc->sxFnc.pnodeRest = nullptr;
  5968. pnodeFnc->sxFnc.deferredStub = nullptr;
  5969. pnodeFnc->sxFnc.funcInfo = nullptr;
  5970. // In order to (re-)defer the default constructor, we need to, for instance, track
  5971. // deferred class expression the way we track function expression, since we lose the part of the source
  5972. // that tells us which we have.
  5973. pnodeFnc->sxFnc.canBeDeferred = false;
  5974. pnodeFnc->sxFnc.isBodyAndParamScopeMerged = true;
  5975. #ifdef DBG
  5976. pnodeFnc->sxFnc.deferredParseNextFunctionId = *(this->m_nextFunctionId);
  5977. #endif
  5978. AppendFunctionToScopeList(true, pnodeFnc);
  5979. if (m_nextFunctionId)
  5980. {
  5981. (*m_nextFunctionId)++;
  5982. }
  5983. // Update the count of functions nested in the current parent.
  5984. if (m_pnestedCount)
  5985. {
  5986. (*m_pnestedCount)++;
  5987. }
  5988. if (m_pscan->IchMinTok() >= m_pscan->IchMinLine())
  5989. {
  5990. // In scenarios involving defer parse IchMinLine() can be incorrect for the first line after defer parse
  5991. pnodeFnc->sxFnc.columnNumber = m_pscan->IchMinTok() - m_pscan->IchMinLine();
  5992. }
  5993. else if (m_currentNodeFunc)
  5994. {
  5995. // For the first line after defer parse, compute the column relative to the column number
  5996. // of the lexically parent function.
  5997. ULONG offsetFromCurrentFunction = m_pscan->IchMinTok() - m_currentNodeFunc->ichMin;
  5998. pnodeFnc->sxFnc.columnNumber = m_currentNodeFunc->sxFnc.columnNumber + offsetFromCurrentFunction;
  5999. }
  6000. else
  6001. {
  6002. // if there is no current function, lets give a default of 0.
  6003. pnodeFnc->sxFnc.columnNumber = 0;
  6004. }
  6005. int32 * pAstSizeSave = m_pCurrentAstSize;
  6006. m_pCurrentAstSize = &(pnodeFnc->sxFnc.astSize);
  6007. // Make this the current function.
  6008. ParseNodePtr pnodeFncSave = m_currentNodeFunc;
  6009. m_currentNodeFunc = pnodeFnc;
  6010. ParseNodePtr argsId = nullptr;
  6011. ParseNodePtr *lastNodeRef = nullptr;
  6012. ParseNodePtr pnodeBlock = StartParseBlock<buildAST>(PnodeBlockType::Parameter, ScopeType_Parameter);
  6013. if (buildAST && extends)
  6014. {
  6015. // constructor(...args) { super(...args); }
  6016. // ^^^^^^^
  6017. ParseNodePtr *const ppnodeVarSave = m_ppnodeVar;
  6018. m_ppnodeVar = &pnodeFnc->sxFnc.pnodeVars;
  6019. IdentPtr pidargs = m_phtbl->PidHashNameLen(_u("args"), sizeof("args") - 1);
  6020. ParseNodePtr pnodeT = CreateVarDeclNode(pidargs, STFormal);
  6021. pnodeT->sxVar.sym->SetIsNonSimpleParameter(true);
  6022. pnodeFnc->sxFnc.pnodeRest = pnodeT;
  6023. PidRefStack *ref = this->PushPidRef(pidargs);
  6024. argsId = CreateNameNode(pidargs, pnodeFnc->ichMin, pnodeFnc->ichLim);
  6025. argsId->sxPid.symRef = ref->GetSymRef();
  6026. m_ppnodeVar = ppnodeVarSave;
  6027. }
  6028. ParseNodePtr pnodeInnerBlock = StartParseBlock<buildAST>(PnodeBlockType::Function, ScopeType_FunctionBody);
  6029. pnodeBlock->sxBlock.pnodeScopes = pnodeInnerBlock;
  6030. pnodeFnc->sxFnc.pnodeBodyScope = pnodeInnerBlock;
  6031. pnodeFnc->sxFnc.pnodeScopes = pnodeBlock;
  6032. if (buildAST)
  6033. {
  6034. if (extends)
  6035. {
  6036. // constructor(...args) { super(...args); }
  6037. // ^^^^^^^^^^^^^^^
  6038. Assert(argsId);
  6039. ParseNodePtr spreadArg = CreateUniNode(knopEllipsis, argsId, pnodeFnc->ichMin, pnodeFnc->ichLim);
  6040. ParseNodePtr superRef = ReferenceSpecialName(wellKnownPropertyPids._superConstructor, pnodeFnc->ichMin, pnodeFnc->ichLim, true);
  6041. pnodeFnc->sxFnc.SetHasSuperReference(TRUE);
  6042. ParseNodePtr callNode = CreateSuperCallNode(superRef, spreadArg);
  6043. callNode->sxSuperCall.pnodeThis = ReferenceSpecialName(wellKnownPropertyPids._this, pnodeFnc->ichMin, pnodeFnc->ichLim, true);
  6044. callNode->sxSuperCall.pnodeNewTarget = ReferenceSpecialName(wellKnownPropertyPids._newTarget, pnodeFnc->ichMin, pnodeFnc->ichLim, true);
  6045. callNode->sxCall.spreadArgCount = 1;
  6046. AddToNodeList(&pnodeFnc->sxFnc.pnodeBody, &lastNodeRef, callNode);
  6047. }
  6048. AddToNodeList(&pnodeFnc->sxFnc.pnodeBody, &lastNodeRef, CreateNodeWithScanner<knopEndCode>());
  6049. }
  6050. FinishParseBlock(pnodeInnerBlock);
  6051. CreateSpecialSymbolDeclarations(pnodeFnc, false);
  6052. FinishParseBlock(pnodeBlock);
  6053. m_currentNodeFunc = pnodeFncSave;
  6054. m_pCurrentAstSize = pAstSizeSave;
  6055. return pnodeFnc;
  6056. }
  6057. template<bool buildAST>
  6058. void Parser::ParseExpressionLambdaBody(ParseNodePtr pnodeLambda)
  6059. {
  6060. ParseNodePtr *lastNodeRef = nullptr;
  6061. // The lambda body is a single expression, the result of which is the return value.
  6062. ParseNodePtr pnodeRet = nullptr;
  6063. if (buildAST)
  6064. {
  6065. pnodeRet = CreateNodeWithScanner<knopReturn>();
  6066. pnodeRet->grfpn |= PNodeFlags::fpnSyntheticNode;
  6067. pnodeLambda->sxFnc.pnodeScopes->sxBlock.pnodeStmt = pnodeRet;
  6068. }
  6069. IdentToken token;
  6070. charcount_t lastRParen = 0;
  6071. ParseNodePtr result = ParseExpr<buildAST>(koplAsg, nullptr, TRUE, FALSE, nullptr, nullptr, nullptr, &token, false, nullptr, &lastRParen);
  6072. this->MarkEscapingRef(result, &token);
  6073. if (buildAST)
  6074. {
  6075. pnodeRet->sxReturn.pnodeExpr = result;
  6076. pnodeRet->ichMin = pnodeRet->sxReturn.pnodeExpr->ichMin;
  6077. pnodeRet->ichLim = pnodeRet->sxReturn.pnodeExpr->ichLim;
  6078. // Pushing a statement node with PushStmt<>() normally does this initialization
  6079. // but do it here manually since we know there is no outer statement node.
  6080. pnodeRet->sxStmt.grfnop = 0;
  6081. pnodeRet->sxStmt.pnodeOuter = nullptr;
  6082. pnodeLambda->ichLim = max(pnodeRet->ichLim, lastRParen);
  6083. pnodeLambda->sxFnc.cbLim = m_pscan->IecpLimTokPrevious();
  6084. pnodeLambda->sxFnc.pnodeScopes->ichLim = pnodeRet->ichLim;
  6085. pnodeLambda->sxFnc.pnodeBody = nullptr;
  6086. AddToNodeList(&pnodeLambda->sxFnc.pnodeBody, &lastNodeRef, pnodeRet);
  6087. // Append an EndCode node.
  6088. ParseNodePtr end = CreateNodeWithScanner<knopEndCode>(pnodeRet->ichLim);
  6089. end->ichLim = end->ichMin; // make end code zero width at the immediate end of lambda body
  6090. AddToNodeList(&pnodeLambda->sxFnc.pnodeBody, &lastNodeRef, end);
  6091. // Lambda's do not have arguments binding
  6092. pnodeLambda->sxFnc.SetHasReferenceableBuiltInArguments(false);
  6093. }
  6094. }
  6095. void Parser::CheckStrictFormalParameters()
  6096. {
  6097. if (m_token.tk == tkID)
  6098. {
  6099. // single parameter arrow function case
  6100. IdentPtr pid = m_token.GetIdentifier(m_phtbl);
  6101. CheckStrictModeEvalArgumentsUsage(pid);
  6102. return;
  6103. }
  6104. Assert(m_token.tk == tkLParen);
  6105. m_pscan->ScanForcingPid();
  6106. if (m_token.tk != tkRParen)
  6107. {
  6108. SList<IdentPtr> formals(&m_nodeAllocator);
  6109. for (;;)
  6110. {
  6111. if (m_token.tk != tkID)
  6112. {
  6113. IdentifierExpectedError(m_token);
  6114. }
  6115. IdentPtr pid = m_token.GetIdentifier(m_phtbl);
  6116. CheckStrictModeEvalArgumentsUsage(pid);
  6117. if (formals.Has(pid))
  6118. {
  6119. Error(ERRES5ArgSame, m_pscan->IchMinTok(), m_pscan->IchLimTok());
  6120. }
  6121. else
  6122. {
  6123. formals.Prepend(pid);
  6124. }
  6125. m_pscan->Scan();
  6126. if (m_token.tk == tkAsg && m_scriptContext->GetConfig()->IsES6DefaultArgsEnabled())
  6127. {
  6128. m_pscan->Scan();
  6129. // We can avoid building the AST since we are just checking the default expression.
  6130. ParseNodePtr pnodeInit = ParseExpr<false>(koplCma);
  6131. Assert(pnodeInit == nullptr);
  6132. }
  6133. if (m_token.tk != tkComma)
  6134. {
  6135. break;
  6136. }
  6137. m_pscan->ScanForcingPid();
  6138. if (m_token.tk == tkRParen && m_scriptContext->GetConfig()->IsES7TrailingCommaEnabled())
  6139. {
  6140. break;
  6141. }
  6142. }
  6143. }
  6144. Assert(m_token.tk == tkRParen);
  6145. }
  6146. void Parser::FinishFncNode(ParseNodePtr pnodeFnc)
  6147. {
  6148. AnalysisAssert(pnodeFnc);
  6149. // Finish the AST for a function that was deferred earlier, but which we decided
  6150. // to finish after the fact.
  6151. // We assume that the name(s) and arg(s) have already got parse nodes, so
  6152. // we just have to do the function body.
  6153. // Save the current next function Id, and resume from the old one.
  6154. Js::LocalFunctionId * nextFunctionIdSave = m_nextFunctionId;
  6155. Js::LocalFunctionId tempNextFunctionId = pnodeFnc->sxFnc.functionId + 1;
  6156. this->m_nextFunctionId = &tempNextFunctionId;
  6157. ParseNodePtr pnodeFncSave = m_currentNodeFunc;
  6158. uint *pnestedCountSave = m_pnestedCount;
  6159. int32* pAstSizeSave = m_pCurrentAstSize;
  6160. m_currentNodeFunc = pnodeFnc;
  6161. m_pCurrentAstSize = & (pnodeFnc->sxFnc.astSize);
  6162. pnodeFnc->sxFnc.nestedCount = 0;
  6163. m_pnestedCount = &pnodeFnc->sxFnc.nestedCount;
  6164. // Cue up the parser to the start of the function body.
  6165. if (pnodeFnc->sxFnc.pnodeName)
  6166. {
  6167. // Skip the name(s).
  6168. m_pscan->SetCurrentCharacter(pnodeFnc->sxFnc.pnodeName->ichLim, pnodeFnc->sxFnc.lineNumber);
  6169. }
  6170. else
  6171. {
  6172. m_pscan->SetCurrentCharacter(pnodeFnc->ichMin, pnodeFnc->sxFnc.lineNumber);
  6173. if (pnodeFnc->sxFnc.IsAccessor())
  6174. {
  6175. // Getter/setter. The node text starts with the name, so eat that.
  6176. m_pscan->ScanNoKeywords();
  6177. }
  6178. else
  6179. {
  6180. // Anonymous function. Skip any leading "("'s and "function".
  6181. for (;;)
  6182. {
  6183. m_pscan->Scan();
  6184. if (m_token.GetIdentifier(m_phtbl) == wellKnownPropertyPids.async)
  6185. {
  6186. Assert(pnodeFnc->sxFnc.IsAsync());
  6187. continue;
  6188. }
  6189. if (m_token.tk == tkFUNCTION)
  6190. {
  6191. break;
  6192. }
  6193. Assert(m_token.tk == tkLParen || m_token.tk == tkStar);
  6194. }
  6195. }
  6196. }
  6197. // switch scanner to treat 'yield' as keyword in generator functions
  6198. // or as an identifier in non-generator functions
  6199. bool fPreviousYieldIsKeyword = m_pscan->SetYieldIsKeywordRegion(pnodeFnc && pnodeFnc->sxFnc.IsGenerator());
  6200. bool fPreviousAwaitIsKeyword = m_pscan->SetAwaitIsKeywordRegion(pnodeFnc && pnodeFnc->sxFnc.IsAsync());
  6201. // Skip the arg list.
  6202. m_pscan->ScanNoKeywords();
  6203. if (m_token.tk == tkStar)
  6204. {
  6205. Assert(pnodeFnc->sxFnc.IsGenerator());
  6206. m_pscan->ScanNoKeywords();
  6207. }
  6208. Assert(m_token.tk == tkLParen);
  6209. m_pscan->ScanNoKeywords();
  6210. if (m_token.tk != tkRParen)
  6211. {
  6212. for (;;)
  6213. {
  6214. if (m_token.tk == tkEllipsis)
  6215. {
  6216. m_pscan->ScanNoKeywords();
  6217. }
  6218. if (m_token.tk == tkID)
  6219. {
  6220. m_pscan->ScanNoKeywords();
  6221. if (m_token.tk == tkAsg)
  6222. {
  6223. // Eat the default expression
  6224. m_pscan->Scan();
  6225. ParseExpr<false>(koplCma);
  6226. }
  6227. }
  6228. else if (IsPossiblePatternStart())
  6229. {
  6230. ParseDestructuredLiteralWithScopeSave(tkLET, false/*isDecl*/, false /*topLevel*/);
  6231. }
  6232. else
  6233. {
  6234. AssertMsg(false, "Unexpected identifier prefix while fast-scanning formals");
  6235. }
  6236. if (m_token.tk != tkComma)
  6237. {
  6238. break;
  6239. }
  6240. m_pscan->ScanNoKeywords();
  6241. if (m_token.tk == tkRParen && m_scriptContext->GetConfig()->IsES7TrailingCommaEnabled())
  6242. {
  6243. break;
  6244. }
  6245. }
  6246. }
  6247. if (m_token.tk == tkRParen) // This might be false due to a lambda => token.
  6248. {
  6249. m_pscan->Scan();
  6250. }
  6251. // Finish the function body.
  6252. {
  6253. // Note that in IE8- modes, surrounding parentheses are considered part of function body. e.g. "( function x(){} )".
  6254. // We lose that context here since we start from middle of function body. So save and restore source range info.
  6255. ParseNodePtr* lastNodeRef = NULL;
  6256. const charcount_t ichLim = pnodeFnc->ichLim;
  6257. const size_t cbLim = pnodeFnc->sxFnc.cbLim;
  6258. this->FinishFncDecl(pnodeFnc, NULL, lastNodeRef);
  6259. #if DBG
  6260. // The pnode extent may not match the original extent.
  6261. // We expect this to happen only when there are trailing ")"'s.
  6262. // Consume them and make sure that's all we've got.
  6263. if (pnodeFnc->ichLim != ichLim)
  6264. {
  6265. Assert(pnodeFnc->ichLim < ichLim);
  6266. m_pscan->SetCurrentCharacter(pnodeFnc->ichLim);
  6267. while (m_pscan->IchLimTok() != ichLim)
  6268. {
  6269. m_pscan->ScanNoKeywords();
  6270. Assert(m_token.tk == tkRParen);
  6271. }
  6272. }
  6273. #endif
  6274. pnodeFnc->ichLim = ichLim;
  6275. pnodeFnc->sxFnc.cbLim = cbLim;
  6276. }
  6277. m_currentNodeFunc = pnodeFncSave;
  6278. m_pCurrentAstSize = pAstSizeSave;
  6279. m_pnestedCount = pnestedCountSave;
  6280. Assert(m_pnestedCount);
  6281. Assert(tempNextFunctionId == pnodeFnc->sxFnc.deferredParseNextFunctionId);
  6282. this->m_nextFunctionId = nextFunctionIdSave;
  6283. m_pscan->SetYieldIsKeywordRegion(fPreviousYieldIsKeyword);
  6284. m_pscan->SetAwaitIsKeywordRegion(fPreviousAwaitIsKeyword);
  6285. }
  6286. void Parser::FinishFncDecl(ParseNodePtr pnodeFnc, LPCOLESTR pNameHint, ParseNodePtr *lastNodeRef, bool skipCurlyBraces)
  6287. {
  6288. LPCOLESTR name = NULL;
  6289. JS_ETW(int32 startAstSize = *m_pCurrentAstSize);
  6290. if (IS_JS_ETW(EventEnabledJSCRIPT_PARSE_METHOD_START()) || PHASE_TRACE1(Js::DeferParsePhase))
  6291. {
  6292. name = GetFunctionName(pnodeFnc, pNameHint);
  6293. m_functionBody = NULL; // for nested functions we do not want to get the name of the top deferred function return name;
  6294. JS_ETW(EventWriteJSCRIPT_PARSE_METHOD_START(m_sourceContextInfo->dwHostSourceContext, GetScriptContext(), pnodeFnc->sxFnc.functionId, 0, m_parseType, name));
  6295. OUTPUT_TRACE(Js::DeferParsePhase, _u("Parsing function (%s) : %s (%d)\n"), GetParseType(), name, pnodeFnc->sxFnc.functionId);
  6296. }
  6297. JS_ETW_INTERNAL(EventWriteJSCRIPT_PARSE_FUNC(GetScriptContext(), pnodeFnc->sxFnc.functionId, /*Undefer*/FALSE));
  6298. // Do the work of creating an AST for a function body.
  6299. // This is common to the un-deferred case and the case in which we un-defer late in the game.
  6300. Assert(pnodeFnc->nop == knopFncDecl);
  6301. if (!skipCurlyBraces)
  6302. {
  6303. ChkCurTok(tkLCurly, ERRnoLcurly);
  6304. }
  6305. ParseStmtList<true>(&pnodeFnc->sxFnc.pnodeBody, &lastNodeRef, SM_OnFunctionCode, true /* isSourceElementList */);
  6306. // Append an EndCode node.
  6307. AddToNodeList(&pnodeFnc->sxFnc.pnodeBody, &lastNodeRef, CreateNodeWithScanner<knopEndCode>());
  6308. if (!skipCurlyBraces)
  6309. {
  6310. ChkCurTokNoScan(tkRCurly, ERRnoRcurly);
  6311. }
  6312. pnodeFnc->ichLim = m_pscan->IchLimTok();
  6313. pnodeFnc->sxFnc.cbLim = m_pscan->IecpLimTok();
  6314. #ifdef ENABLE_JS_ETW
  6315. int32 astSize = *m_pCurrentAstSize - startAstSize;
  6316. EventWriteJSCRIPT_PARSE_METHOD_STOP(m_sourceContextInfo->dwHostSourceContext, GetScriptContext(), pnodeFnc->sxFnc.functionId, astSize, m_parseType, name);
  6317. #endif
  6318. }
  6319. ParseNodePtr Parser::CreateSpecialVarDeclNode(ParseNodePtr pnodeFnc, IdentPtr pid)
  6320. {
  6321. ParseNodePtr pnode = InsertVarAtBeginning(pnodeFnc, pid);
  6322. pnode->grfpn |= fpnSpecialSymbol;
  6323. // special symbol must not be global
  6324. pnode->sxPid.sym->SetIsGlobal(false);
  6325. return pnode;
  6326. }
  6327. ParseNodePtr Parser::InsertVarAtBeginning(ParseNodePtr pnodeFnc, IdentPtr pid)
  6328. {
  6329. ParseNodePtr pnode = nullptr;
  6330. if (m_ppnodeVar == &pnodeFnc->sxFnc.pnodeVars)
  6331. {
  6332. pnode = CreateVarDeclNode(pid, STVariable, true, pnodeFnc);
  6333. }
  6334. else
  6335. {
  6336. ParseNodePtr *const ppnodeVarSave = m_ppnodeVar;
  6337. m_ppnodeVar = &pnodeFnc->sxFnc.pnodeVars;
  6338. pnode = CreateVarDeclNode(pid, STVariable, true, pnodeFnc);
  6339. m_ppnodeVar = ppnodeVarSave;
  6340. }
  6341. Assert(pnode);
  6342. return pnode;
  6343. }
  6344. ParseNodePtr Parser::AddArgumentsNodeToVars(ParseNodePtr pnodeFnc)
  6345. {
  6346. Assert(!GetCurrentFunctionNode()->sxFnc.IsLambda());
  6347. ParseNodePtr argNode = InsertVarAtBeginning(pnodeFnc, wellKnownPropertyPids.arguments);
  6348. argNode->grfpn |= PNodeFlags::fpnArguments; // Flag this as the built-in arguments node
  6349. return argNode;
  6350. }
  6351. void Parser::UpdateArgumentsNode(ParseNodePtr pnodeFnc, ParseNodePtr argNode)
  6352. {
  6353. if ((pnodeFnc->grfpn & PNodeFlags::fpnArguments_overriddenInParam) || pnodeFnc->sxFnc.IsLambda())
  6354. {
  6355. // There is a parameter named arguments. So we don't have to create the built-in arguments.
  6356. pnodeFnc->sxFnc.SetHasReferenceableBuiltInArguments(false);
  6357. }
  6358. else if ((pnodeFnc->grfpn & PNodeFlags::fpnArguments_overriddenByDecl) && pnodeFnc->sxFnc.IsBodyAndParamScopeMerged())
  6359. {
  6360. // In non-split scope case there is a var or function definition named arguments in the body
  6361. pnodeFnc->sxFnc.SetHasReferenceableBuiltInArguments(false);
  6362. }
  6363. else
  6364. {
  6365. pnodeFnc->sxFnc.SetHasReferenceableBuiltInArguments(true);
  6366. Assert(argNode);
  6367. }
  6368. if (argNode != nullptr && !argNode->sxVar.sym->IsArguments())
  6369. {
  6370. // A duplicate definition has updated the declaration node. Need to reset it back.
  6371. argNode->grfpn |= PNodeFlags::fpnArguments;
  6372. argNode->sxVar.sym->SetDecl(argNode);
  6373. }
  6374. }
  6375. LPCOLESTR Parser::GetFunctionName(ParseNodePtr pnodeFnc, LPCOLESTR pNameHint)
  6376. {
  6377. LPCOLESTR name = nullptr;
  6378. if(pnodeFnc->sxFnc.pnodeName != nullptr && knopVarDecl == pnodeFnc->sxFnc.pnodeName->nop)
  6379. {
  6380. name = pnodeFnc->sxFnc.pnodeName->sxVar.pid->Psz();
  6381. }
  6382. if(name == nullptr && pNameHint != nullptr)
  6383. {
  6384. name = pNameHint;
  6385. }
  6386. if(name == nullptr && m_functionBody != nullptr)
  6387. {
  6388. name = m_functionBody->GetExternalDisplayName();
  6389. }
  6390. else if(name == nullptr)
  6391. {
  6392. name = Js::Constants::AnonymousFunction;
  6393. }
  6394. return name;
  6395. }
  6396. IdentPtr Parser::ParseClassPropertyName(IdentPtr * pidHint)
  6397. {
  6398. if (m_token.tk == tkID || m_token.tk == tkStrCon || m_token.IsReservedWord())
  6399. {
  6400. IdentPtr pid;
  6401. if (m_token.tk == tkStrCon)
  6402. {
  6403. if (m_pscan->IsOctOrLeadingZeroOnLastTKNumber())
  6404. {
  6405. Error(ERRES5NoOctal);
  6406. }
  6407. pid = m_token.GetStr();
  6408. }
  6409. else
  6410. {
  6411. pid = m_token.GetIdentifier(m_phtbl);
  6412. }
  6413. *pidHint = pid;
  6414. return pid;
  6415. }
  6416. else if (m_token.tk == tkIntCon)
  6417. {
  6418. if (m_pscan->IsOctOrLeadingZeroOnLastTKNumber())
  6419. {
  6420. Error(ERRES5NoOctal);
  6421. }
  6422. return m_pscan->PidFromLong(m_token.GetLong());
  6423. }
  6424. else if (m_token.tk == tkFltCon)
  6425. {
  6426. if (m_pscan->IsOctOrLeadingZeroOnLastTKNumber())
  6427. {
  6428. Error(ERRES5NoOctal);
  6429. }
  6430. return m_pscan->PidFromDbl(m_token.GetDouble());
  6431. }
  6432. Error(ERRnoMemberIdent);
  6433. }
  6434. LPCOLESTR Parser::ConstructFinalHintNode(IdentPtr pClassName, IdentPtr pMemberName, IdentPtr pGetSet, bool isStatic, uint32* nameLength, uint32* pShortNameOffset, bool isComputedName, LPCOLESTR pMemberNameHint)
  6435. {
  6436. if ((pMemberName == nullptr && !isComputedName) ||
  6437. (pMemberNameHint == nullptr && isComputedName) ||
  6438. !CONFIG_FLAG(UseFullName))
  6439. {
  6440. return nullptr;
  6441. }
  6442. LPCOLESTR pFinalName = isComputedName? pMemberNameHint : pMemberName->Psz();
  6443. uint32 fullNameHintLength = 0;
  6444. uint32 shortNameOffset = 0;
  6445. if (!isStatic)
  6446. {
  6447. // Add prototype.
  6448. pFinalName = AppendNameHints(wellKnownPropertyPids.prototype, pFinalName, &fullNameHintLength, &shortNameOffset);
  6449. }
  6450. if (pClassName)
  6451. {
  6452. uint32 classNameOffset = 0;
  6453. pFinalName = AppendNameHints(pClassName, pFinalName, &fullNameHintLength, &classNameOffset);
  6454. shortNameOffset += classNameOffset;
  6455. }
  6456. if (pGetSet)
  6457. {
  6458. if (m_scriptContext->GetConfig()->IsES6FunctionNameEnabled())
  6459. {
  6460. // displays as get/set prototype.funcname
  6461. uint32 getSetOffset = 0;
  6462. pFinalName = AppendNameHints(pGetSet, pFinalName, &fullNameHintLength, &getSetOffset, true);
  6463. shortNameOffset += getSetOffset;
  6464. }
  6465. else
  6466. {
  6467. pFinalName = AppendNameHints(pFinalName, pGetSet, &fullNameHintLength, &shortNameOffset);
  6468. }
  6469. }
  6470. if (fullNameHintLength > *nameLength)
  6471. {
  6472. *nameLength = fullNameHintLength;
  6473. }
  6474. if (shortNameOffset > *pShortNameOffset)
  6475. {
  6476. *pShortNameOffset = shortNameOffset;
  6477. }
  6478. return pFinalName;
  6479. }
  6480. class AutoParsingSuperRestrictionStateRestorer
  6481. {
  6482. public:
  6483. AutoParsingSuperRestrictionStateRestorer(Parser* parser) : m_parser(parser)
  6484. {
  6485. AssertMsg(this->m_parser != nullptr, "This just should not happen");
  6486. this->m_originalParsingSuperRestrictionState = this->m_parser->m_parsingSuperRestrictionState;
  6487. }
  6488. ~AutoParsingSuperRestrictionStateRestorer()
  6489. {
  6490. AssertMsg(this->m_parser != nullptr, "This just should not happen");
  6491. this->m_parser->m_parsingSuperRestrictionState = m_originalParsingSuperRestrictionState;
  6492. }
  6493. private:
  6494. Parser* m_parser;
  6495. int m_originalParsingSuperRestrictionState;
  6496. };
  6497. template<bool buildAST>
  6498. ParseNodePtr Parser::ParseClassDecl(BOOL isDeclaration, LPCOLESTR pNameHint, uint32 *pHintLength, uint32 *pShortNameOffset)
  6499. {
  6500. bool hasConstructor = false;
  6501. bool hasExtends = false;
  6502. IdentPtr name = nullptr;
  6503. ParseNodePtr pnodeName = nullptr;
  6504. ParseNodePtr pnodeConstructor = nullptr;
  6505. ParseNodePtr pnodeExtends = nullptr;
  6506. ParseNodePtr pnodeMembers = nullptr;
  6507. ParseNodePtr *lastMemberNodeRef = nullptr;
  6508. ParseNodePtr pnodeStaticMembers = nullptr;
  6509. ParseNodePtr *lastStaticMemberNodeRef = nullptr;
  6510. uint32 nameHintLength = pHintLength ? *pHintLength : 0;
  6511. uint32 nameHintOffset = pShortNameOffset ? *pShortNameOffset : 0;
  6512. ArenaAllocator tempAllocator(_u("ClassMemberNames"), m_nodeAllocator.GetPageAllocator(), Parser::OutOfMemory);
  6513. size_t cbMinConstructor = 0;
  6514. ParseNodePtr pnodeClass = nullptr;
  6515. if (buildAST)
  6516. {
  6517. pnodeClass = CreateNode(knopClassDecl);
  6518. CHAKRATEL_LANGSTATS_INC_LANGFEATURECOUNT(Class, m_scriptContext);
  6519. cbMinConstructor = m_pscan->IecpMinTok();
  6520. }
  6521. m_pscan->Scan();
  6522. if (m_token.tk == tkID)
  6523. {
  6524. name = m_token.GetIdentifier(m_phtbl);
  6525. m_pscan->Scan();
  6526. }
  6527. else if (isDeclaration)
  6528. {
  6529. IdentifierExpectedError(m_token);
  6530. }
  6531. if (isDeclaration && name == wellKnownPropertyPids.arguments && GetCurrentBlockInfo()->pnodeBlock->sxBlock.blockType == Function)
  6532. {
  6533. GetCurrentFunctionNode()->grfpn |= PNodeFlags::fpnArguments_overriddenByDecl;
  6534. }
  6535. BOOL strictSave = m_fUseStrictMode;
  6536. m_fUseStrictMode = TRUE;
  6537. ParseNodePtr pnodeDeclName = nullptr;
  6538. if (isDeclaration)
  6539. {
  6540. pnodeDeclName = CreateBlockScopedDeclNode(name, knopLetDecl);
  6541. }
  6542. ParseNodePtr *ppnodeScopeSave = nullptr;
  6543. ParseNodePtr *ppnodeExprScopeSave = nullptr;
  6544. ParseNodePtr pnodeBlock = StartParseBlock<buildAST>(PnodeBlockType::Regular, ScopeType_Block);
  6545. if (buildAST)
  6546. {
  6547. PushFuncBlockScope(pnodeBlock, &ppnodeScopeSave, &ppnodeExprScopeSave);
  6548. pnodeClass->sxClass.pnodeBlock = pnodeBlock;
  6549. }
  6550. if (name)
  6551. {
  6552. pnodeName = CreateBlockScopedDeclNode(name, knopConstDecl);
  6553. }
  6554. if (m_token.tk == tkEXTENDS)
  6555. {
  6556. m_pscan->Scan();
  6557. pnodeExtends = ParseTerm<buildAST>();
  6558. hasExtends = true;
  6559. }
  6560. if (m_token.tk != tkLCurly)
  6561. {
  6562. Error(ERRnoLcurly);
  6563. }
  6564. OUTPUT_TRACE_DEBUGONLY(Js::ES6VerboseFlag, _u("Parsing class (%s) : %s\n"), GetParseType(), name ? name->Psz() : _u("anonymous class"));
  6565. RestorePoint beginClass;
  6566. m_pscan->Capture(&beginClass);
  6567. m_pscan->ScanForcingPid();
  6568. IdentPtr pClassNamePid = pnodeName ? pnodeName->sxVar.pid : nullptr;
  6569. for (;;)
  6570. {
  6571. if (m_token.tk == tkSColon)
  6572. {
  6573. m_pscan->ScanForcingPid();
  6574. continue;
  6575. }
  6576. if (m_token.tk == tkRCurly)
  6577. {
  6578. break;
  6579. }
  6580. bool isStatic = false;
  6581. if (m_token.tk == tkSTATIC)
  6582. {
  6583. // 'static' can be used as an IdentifierName here, even in strict mode code. We need to see the next token before we know
  6584. // if this is being used as a keyword. This is similar to the way we treat 'let' in some cases.
  6585. // See https://tc39.github.io/ecma262/#sec-keywords for more info.
  6586. RestorePoint beginStatic;
  6587. m_pscan->Capture(&beginStatic);
  6588. m_pscan->ScanForcingPid();
  6589. if (m_token.tk == tkLParen)
  6590. {
  6591. m_pscan->SeekTo(beginStatic);
  6592. }
  6593. else
  6594. {
  6595. isStatic = true;
  6596. }
  6597. }
  6598. ushort fncDeclFlags = fFncNoName | fFncMethod | fFncClassMember;
  6599. charcount_t ichMin = 0;
  6600. size_t iecpMin = 0;
  6601. ParseNodePtr pnodeMemberName = nullptr;
  6602. IdentPtr pidHint = nullptr;
  6603. IdentPtr memberPid = nullptr;
  6604. LPCOLESTR pMemberNameHint = nullptr;
  6605. uint32 memberNameHintLength = 0;
  6606. uint32 memberNameOffset = 0;
  6607. bool isComputedName = false;
  6608. bool isAsyncMethod = false;
  6609. if (m_token.tk == tkID && m_token.GetIdentifier(m_phtbl) == wellKnownPropertyPids.async && m_scriptContext->GetConfig()->IsES7AsyncAndAwaitEnabled())
  6610. {
  6611. RestorePoint parsedAsync;
  6612. m_pscan->Capture(&parsedAsync);
  6613. ichMin = m_pscan->IchMinTok();
  6614. iecpMin = m_pscan->IecpMinTok();
  6615. m_pscan->Scan();
  6616. if (m_token.tk == tkLParen || m_pscan->FHadNewLine())
  6617. {
  6618. m_pscan->SeekTo(parsedAsync);
  6619. }
  6620. else
  6621. {
  6622. isAsyncMethod = true;
  6623. }
  6624. }
  6625. bool isGenerator = m_scriptContext->GetConfig()->IsES6GeneratorsEnabled() &&
  6626. m_token.tk == tkStar;
  6627. if (isGenerator)
  6628. {
  6629. fncDeclFlags |= fFncGenerator;
  6630. m_pscan->ScanForcingPid();
  6631. }
  6632. if (m_token.tk == tkLBrack && m_scriptContext->GetConfig()->IsES6ObjectLiteralsEnabled())
  6633. {
  6634. // Computed member name: [expr] () { }
  6635. LPCOLESTR emptyHint = nullptr;
  6636. ParseComputedName<buildAST>(&pnodeMemberName, &emptyHint, &pMemberNameHint, &memberNameHintLength, &memberNameOffset);
  6637. isComputedName = true;
  6638. }
  6639. else // not computed name
  6640. {
  6641. memberPid = this->ParseClassPropertyName(&pidHint);
  6642. if (pidHint)
  6643. {
  6644. pMemberNameHint = pidHint->Psz();
  6645. memberNameHintLength = pidHint->Cch();
  6646. }
  6647. }
  6648. if (buildAST && memberPid)
  6649. {
  6650. pnodeMemberName = CreateStrNodeWithScanner(memberPid);
  6651. }
  6652. if (!isStatic && memberPid == wellKnownPropertyPids.constructor)
  6653. {
  6654. if (hasConstructor || isAsyncMethod)
  6655. {
  6656. Error(ERRsyntax);
  6657. }
  6658. hasConstructor = true;
  6659. LPCOLESTR pConstructorName = nullptr;
  6660. uint32 constructorNameLength = 0;
  6661. uint32 constructorShortNameHintOffset = 0;
  6662. if (pnodeName && pnodeName->sxVar.pid)
  6663. {
  6664. pConstructorName = pnodeName->sxVar.pid->Psz();
  6665. constructorNameLength = pnodeName->sxVar.pid->Cch();
  6666. }
  6667. else
  6668. {
  6669. pConstructorName = pNameHint;
  6670. constructorNameLength = nameHintLength;
  6671. constructorShortNameHintOffset = nameHintOffset;
  6672. }
  6673. {
  6674. AutoParsingSuperRestrictionStateRestorer restorer(this);
  6675. this->m_parsingSuperRestrictionState = hasExtends ? ParsingSuperRestrictionState_SuperCallAndPropertyAllowed : ParsingSuperRestrictionState_SuperPropertyAllowed;
  6676. // Add the class constructor flag and base class constructor flag if pnodeExtends is nullptr
  6677. fncDeclFlags |= fFncClassConstructor | (pnodeExtends == nullptr ? fFncBaseClassConstructor : kFunctionNone);
  6678. pnodeConstructor = ParseFncDecl<buildAST>(fncDeclFlags, pConstructorName, /* needsPIDOnRCurlyScan */ true, /* resetParsingSuperRestrictionState = */false);
  6679. }
  6680. if (pnodeConstructor->sxFnc.IsGenerator())
  6681. {
  6682. Error(ERRConstructorCannotBeGenerator);
  6683. }
  6684. Assert(constructorNameLength >= constructorShortNameHintOffset);
  6685. // The constructor function will get the same name as class.
  6686. pnodeConstructor->sxFnc.hint = pConstructorName;
  6687. pnodeConstructor->sxFnc.hintLength = constructorNameLength;
  6688. pnodeConstructor->sxFnc.hintOffset = constructorShortNameHintOffset;
  6689. pnodeConstructor->sxFnc.pid = pnodeName && pnodeName->sxVar.pid ? pnodeName->sxVar.pid : wellKnownPropertyPids.constructor;
  6690. pnodeConstructor->sxFnc.SetHasNonThisStmt();
  6691. }
  6692. else
  6693. {
  6694. ParseNodePtr pnodeMember = nullptr;
  6695. bool isMemberNamedGetOrSet = false;
  6696. RestorePoint beginMethodName;
  6697. m_pscan->Capture(&beginMethodName);
  6698. if (memberPid == wellKnownPropertyPids.get || memberPid == wellKnownPropertyPids.set)
  6699. {
  6700. m_pscan->ScanForcingPid();
  6701. }
  6702. if (m_token.tk == tkLParen)
  6703. {
  6704. m_pscan->SeekTo(beginMethodName);
  6705. isMemberNamedGetOrSet = true;
  6706. }
  6707. if ((memberPid == wellKnownPropertyPids.get || memberPid == wellKnownPropertyPids.set) && !isMemberNamedGetOrSet)
  6708. {
  6709. bool isGetter = (memberPid == wellKnownPropertyPids.get);
  6710. if (m_token.tk == tkLBrack && m_scriptContext->GetConfig()->IsES6ObjectLiteralsEnabled())
  6711. {
  6712. // Computed get/set member name: get|set [expr] () { }
  6713. LPCOLESTR emptyHint = nullptr;
  6714. ParseComputedName<buildAST>(&pnodeMemberName, &emptyHint, &pMemberNameHint, &memberNameHintLength, &memberNameOffset);
  6715. isComputedName = true;
  6716. }
  6717. else // not computed name
  6718. {
  6719. memberPid = this->ParseClassPropertyName(&pidHint);
  6720. }
  6721. if ((isStatic ? (memberPid == wellKnownPropertyPids.prototype) : (memberPid == wellKnownPropertyPids.constructor)) || isAsyncMethod)
  6722. {
  6723. Error(ERRsyntax);
  6724. }
  6725. if (buildAST && memberPid && !isComputedName)
  6726. {
  6727. pnodeMemberName = CreateStrNodeWithScanner(memberPid);
  6728. }
  6729. ParseNodePtr pnodeFnc = nullptr;
  6730. {
  6731. AutoParsingSuperRestrictionStateRestorer restorer(this);
  6732. this->m_parsingSuperRestrictionState = ParsingSuperRestrictionState_SuperPropertyAllowed;
  6733. pnodeFnc = ParseFncDecl<buildAST>(fncDeclFlags | (isGetter ? fFncNoArg : fFncOneArg),
  6734. pidHint ? pidHint->Psz() : nullptr, /* needsPIDOnRCurlyScan */ true,
  6735. /* resetParsingSuperRestrictionState */false);
  6736. }
  6737. pnodeFnc->sxFnc.SetIsStaticMember(isStatic);
  6738. if (buildAST)
  6739. {
  6740. pnodeFnc->sxFnc.SetIsAccessor();
  6741. pnodeMember = CreateBinNode(isGetter ? knopGetMember : knopSetMember, pnodeMemberName, pnodeFnc);
  6742. pMemberNameHint = ConstructFinalHintNode(pClassNamePid, pidHint,
  6743. isGetter ? wellKnownPropertyPids.get : wellKnownPropertyPids.set, isStatic,
  6744. &memberNameHintLength, &memberNameOffset, isComputedName, pMemberNameHint);
  6745. }
  6746. }
  6747. else
  6748. {
  6749. if (isStatic && (memberPid == wellKnownPropertyPids.prototype))
  6750. {
  6751. Error(ERRsyntax);
  6752. }
  6753. ParseNodePtr pnodeFnc = nullptr;
  6754. {
  6755. AutoParsingSuperRestrictionStateRestorer restorer(this);
  6756. this->m_parsingSuperRestrictionState = ParsingSuperRestrictionState_SuperPropertyAllowed;
  6757. if (isAsyncMethod)
  6758. {
  6759. fncDeclFlags |= fFncAsync;
  6760. }
  6761. pnodeFnc = ParseFncDecl<buildAST>(fncDeclFlags, pidHint ? pidHint->Psz() : nullptr, /* needsPIDOnRCurlyScan */ true, /* resetParsingSuperRestrictionState */false);
  6762. if (isAsyncMethod)
  6763. {
  6764. pnodeFnc->sxFnc.cbMin = iecpMin;
  6765. pnodeFnc->ichMin = ichMin;
  6766. }
  6767. }
  6768. pnodeFnc->sxFnc.SetIsStaticMember(isStatic);
  6769. if (buildAST)
  6770. {
  6771. pnodeMember = CreateBinNode(knopMember, pnodeMemberName, pnodeFnc);
  6772. pMemberNameHint = ConstructFinalHintNode(pClassNamePid, pidHint, nullptr /*pgetset*/, isStatic, &memberNameHintLength, &memberNameOffset, isComputedName, pMemberNameHint);
  6773. }
  6774. }
  6775. if (buildAST)
  6776. {
  6777. Assert(memberNameHintLength >= memberNameOffset);
  6778. pnodeMember->sxBin.pnode2->sxFnc.hint = pMemberNameHint; // Fully qualified name
  6779. pnodeMember->sxBin.pnode2->sxFnc.hintLength = memberNameHintLength;
  6780. pnodeMember->sxBin.pnode2->sxFnc.hintOffset = memberNameOffset;
  6781. pnodeMember->sxBin.pnode2->sxFnc.pid = memberPid; // Short name
  6782. AddToNodeList(isStatic ? &pnodeStaticMembers : &pnodeMembers, isStatic ? &lastStaticMemberNodeRef : &lastMemberNodeRef, pnodeMember);
  6783. }
  6784. }
  6785. }
  6786. size_t cbLimConstructor = 0;
  6787. if (buildAST)
  6788. {
  6789. pnodeClass->ichLim = m_pscan->IchLimTok();
  6790. cbLimConstructor = m_pscan->IecpLimTok();
  6791. }
  6792. if (!hasConstructor)
  6793. {
  6794. OUTPUT_TRACE_DEBUGONLY(Js::ES6VerboseFlag, _u("Generating constructor (%s) : %s\n"), GetParseType(), name ? name->Psz() : _u("anonymous class"));
  6795. RestorePoint endClass;
  6796. m_pscan->Capture(&endClass);
  6797. m_pscan->SeekTo(beginClass);
  6798. pnodeConstructor = GenerateEmptyConstructor<buildAST>(pnodeExtends != nullptr);
  6799. if (buildAST)
  6800. {
  6801. if (pClassNamePid)
  6802. {
  6803. pnodeConstructor->sxFnc.hint = pClassNamePid->Psz();
  6804. pnodeConstructor->sxFnc.hintLength = pClassNamePid->Cch();
  6805. pnodeConstructor->sxFnc.hintOffset = 0;
  6806. }
  6807. else
  6808. {
  6809. Assert(nameHintLength >= nameHintOffset);
  6810. pnodeConstructor->sxFnc.hint = pNameHint;
  6811. pnodeConstructor->sxFnc.hintLength = nameHintLength;
  6812. pnodeConstructor->sxFnc.hintOffset = nameHintOffset;
  6813. }
  6814. pnodeConstructor->sxFnc.pid = pClassNamePid;
  6815. }
  6816. m_pscan->SeekTo(endClass);
  6817. }
  6818. if (buildAST)
  6819. {
  6820. pnodeConstructor->sxFnc.cbMin = cbMinConstructor;
  6821. pnodeConstructor->sxFnc.cbLim = cbLimConstructor;
  6822. pnodeConstructor->ichMin = pnodeClass->ichMin;
  6823. pnodeConstructor->ichLim = pnodeClass->ichLim;
  6824. PopFuncBlockScope(ppnodeScopeSave, ppnodeExprScopeSave);
  6825. pnodeClass->sxClass.pnodeDeclName = pnodeDeclName;
  6826. pnodeClass->sxClass.pnodeName = pnodeName;
  6827. pnodeClass->sxClass.pnodeConstructor = pnodeConstructor;
  6828. pnodeClass->sxClass.pnodeExtends = pnodeExtends;
  6829. pnodeClass->sxClass.pnodeMembers = pnodeMembers;
  6830. pnodeClass->sxClass.pnodeStaticMembers = pnodeStaticMembers;
  6831. pnodeClass->sxClass.isDefaultModuleExport = false;
  6832. }
  6833. FinishParseBlock(pnodeBlock);
  6834. m_fUseStrictMode = strictSave;
  6835. m_pscan->Scan();
  6836. return pnodeClass;
  6837. }
  6838. template<bool buildAST>
  6839. ParseNodePtr Parser::ParseStringTemplateDecl(ParseNodePtr pnodeTagFnc)
  6840. {
  6841. ParseNodePtr pnodeStringLiterals = nullptr;
  6842. ParseNodePtr* lastStringLiteralNodeRef = nullptr;
  6843. ParseNodePtr pnodeRawStringLiterals = nullptr;
  6844. ParseNodePtr* lastRawStringLiteralNodeRef = nullptr;
  6845. ParseNodePtr pnodeSubstitutionExpressions = nullptr;
  6846. ParseNodePtr* lastSubstitutionExpressionNodeRef = nullptr;
  6847. ParseNodePtr pnodeTagFncArgs = nullptr;
  6848. ParseNodePtr* lastTagFncArgNodeRef = nullptr;
  6849. ParseNodePtr stringLiteral = nullptr;
  6850. ParseNodePtr stringLiteralRaw = nullptr;
  6851. ParseNodePtr pnodeStringTemplate = nullptr;
  6852. bool templateClosed = false;
  6853. const bool isTagged = pnodeTagFnc != nullptr;
  6854. uint16 stringConstantCount = 0;
  6855. charcount_t ichMin = 0;
  6856. Assert(m_token.tk == tkStrTmplBasic || m_token.tk == tkStrTmplBegin);
  6857. if (buildAST)
  6858. {
  6859. pnodeStringTemplate = CreateNode(knopStrTemplate);
  6860. pnodeStringTemplate->sxStrTemplate.countStringLiterals = 0;
  6861. pnodeStringTemplate->sxStrTemplate.isTaggedTemplate = isTagged ? TRUE : FALSE;
  6862. // If this is a tagged string template, we need to start building the arg list for the call
  6863. if (isTagged)
  6864. {
  6865. ichMin = pnodeTagFnc->ichMin;
  6866. AddToNodeListEscapedUse(&pnodeTagFncArgs, &lastTagFncArgNodeRef, pnodeStringTemplate);
  6867. }
  6868. }
  6869. CHAKRATEL_LANGSTATS_INC_LANGFEATURECOUNT(StringTemplates, m_scriptContext);
  6870. OUTPUT_TRACE_DEBUGONLY(
  6871. Js::StringTemplateParsePhase,
  6872. _u("Starting to parse a string template (%s)...\n\tis tagged = %s\n"),
  6873. GetParseType(),
  6874. isTagged ? _u("true") : _u("false (Raw and cooked strings will not differ!)"));
  6875. // String template grammar
  6876. // `...` Simple string template
  6877. // `...${ String template beginning
  6878. // }...${ String template middle
  6879. // }...` String template end
  6880. while (!templateClosed)
  6881. {
  6882. // First, extract the string constant part - we always have one
  6883. if (IsStrictMode() && m_pscan->IsOctOrLeadingZeroOnLastTKNumber())
  6884. {
  6885. Error(ERRES5NoOctal);
  6886. }
  6887. // We are not able to pass more than a ushort worth of arguments to the tag
  6888. // so use that as a logical limit on the number of string constant pieces.
  6889. if (stringConstantCount >= Js::Constants::MaxAllowedArgs)
  6890. {
  6891. Error(ERRnoMemory);
  6892. }
  6893. // Keep track of the string literal count (must be the same for raw strings)
  6894. // We use this in code gen so we don't need to count the string literals list
  6895. stringConstantCount++;
  6896. // If we are not creating parse nodes, there is no need to create strings
  6897. if (buildAST)
  6898. {
  6899. stringLiteral = CreateStrNodeWithScanner(m_token.GetStr());
  6900. AddToNodeList(&pnodeStringLiterals, &lastStringLiteralNodeRef, stringLiteral);
  6901. // We only need to collect a raw string when we are going to pass the string template to a tag
  6902. if (isTagged)
  6903. {
  6904. // Make the scanner create a PID for the raw string constant for the preceding scan
  6905. IdentPtr pid = m_pscan->GetSecondaryBufferAsPid();
  6906. stringLiteralRaw = CreateStrNodeWithScanner(pid);
  6907. // Should have gotten a raw string literal above
  6908. AddToNodeList(&pnodeRawStringLiterals, &lastRawStringLiteralNodeRef, stringLiteralRaw);
  6909. }
  6910. else
  6911. {
  6912. #if DBG
  6913. // Assign the raw string for debug tracing below
  6914. stringLiteralRaw = stringLiteral;
  6915. #endif
  6916. }
  6917. OUTPUT_TRACE_DEBUGONLY(
  6918. Js::StringTemplateParsePhase,
  6919. _u("Parsed string constant: \n\tcooked = \"%s\" \n\traw = \"%s\" \n\tdiffer = %d\n"),
  6920. stringLiteral->sxPid.pid->Psz(),
  6921. stringLiteralRaw->sxPid.pid->Psz(),
  6922. stringLiteral->sxPid.pid->Psz() == stringLiteralRaw->sxPid.pid->Psz() ? 0 : 1);
  6923. }
  6924. switch (m_token.tk)
  6925. {
  6926. case tkStrTmplEnd:
  6927. case tkStrTmplBasic:
  6928. // We do not need to parse an expression for either the end or basic string template tokens
  6929. templateClosed = true;
  6930. break;
  6931. case tkStrTmplBegin:
  6932. case tkStrTmplMid:
  6933. {
  6934. // In the middle or begin string template token case, we need to parse an expression next
  6935. m_pscan->Scan();
  6936. // Parse the contents of the curly braces as an expression
  6937. ParseNodePtr expression = ParseExpr<buildAST>(0);
  6938. // After parsing expression, scan should leave us with an RCurly token.
  6939. // Use the NoScan version so we do not automatically perform a scan - we need to
  6940. // set the scan state before next scan but we don't want to set that state if
  6941. // the token is not as expected since we'll error in that case.
  6942. ChkCurTokNoScan(tkRCurly, ERRnoRcurly);
  6943. // Notify the scanner that it should scan for a middle or end string template token
  6944. m_pscan->SetScanState(Scanner_t::ScanState::ScanStateStringTemplateMiddleOrEnd);
  6945. m_pscan->Scan();
  6946. if (buildAST)
  6947. {
  6948. // If we are going to call the tag function, add this expression into the list of args
  6949. if (isTagged)
  6950. {
  6951. AddToNodeListEscapedUse(&pnodeTagFncArgs, &lastTagFncArgNodeRef, expression);
  6952. }
  6953. else
  6954. {
  6955. // Otherwise add it to the substitution expression list
  6956. // TODO: Store the arguments and substitution expressions in a single list?
  6957. AddToNodeList(&pnodeSubstitutionExpressions, &lastSubstitutionExpressionNodeRef, expression);
  6958. }
  6959. }
  6960. if (!(m_token.tk == tkStrTmplMid || m_token.tk == tkStrTmplEnd))
  6961. {
  6962. // Scan with ScanState ScanStateStringTemplateMiddleOrEnd should only return
  6963. // tkStrTmpMid/End unless it is EOF or tkScanError
  6964. Assert(m_token.tk == tkEOF || m_token.tk == tkScanError);
  6965. Error(ERRsyntax);
  6966. }
  6967. OUTPUT_TRACE_DEBUGONLY(Js::StringTemplateParsePhase, _u("Parsed expression\n"));
  6968. }
  6969. break;
  6970. default:
  6971. Assert(false);
  6972. break;
  6973. }
  6974. }
  6975. if (buildAST)
  6976. {
  6977. pnodeStringTemplate->sxStrTemplate.pnodeStringLiterals = pnodeStringLiterals;
  6978. pnodeStringTemplate->sxStrTemplate.pnodeStringRawLiterals = pnodeRawStringLiterals;
  6979. pnodeStringTemplate->sxStrTemplate.pnodeSubstitutionExpressions = pnodeSubstitutionExpressions;
  6980. pnodeStringTemplate->sxStrTemplate.countStringLiterals = stringConstantCount;
  6981. // We should still have the last string literal.
  6982. // Use the char offset of the end of that constant as the end of the string template.
  6983. pnodeStringTemplate->ichLim = stringLiteral->ichLim;
  6984. // If this is a tagged template, we now have the argument list and can construct a call node
  6985. if (isTagged)
  6986. {
  6987. // Return the call node here and let the byte code generator Emit the string template automagically
  6988. pnodeStringTemplate = CreateCallNode(knopCall, pnodeTagFnc, pnodeTagFncArgs, ichMin, pnodeStringTemplate->ichLim);
  6989. // We need to set the arg count explicitly
  6990. pnodeStringTemplate->sxCall.argCount = stringConstantCount;
  6991. }
  6992. }
  6993. m_pscan->Scan();
  6994. return pnodeStringTemplate;
  6995. }
  6996. LPCOLESTR Parser::FormatPropertyString(LPCOLESTR propertyString, ParseNodePtr pNode, uint32 *fullNameHintLength, uint32 *pShortNameOffset)
  6997. {
  6998. // propertyString could be null, such as 'this.foo' =
  6999. // propertyString could be empty, found in pattern as in (-1)[""][(x = z)]
  7000. OpCode op = pNode->nop;
  7001. LPCOLESTR rightNode = nullptr;
  7002. if (propertyString == nullptr)
  7003. {
  7004. propertyString = _u("");
  7005. }
  7006. if (op != knopInt && op != knopFlt && op != knopName && op != knopStr)
  7007. {
  7008. rightNode = _u("");
  7009. }
  7010. else if (op == knopStr)
  7011. {
  7012. return AppendNameHints(propertyString, pNode->sxPid.pid, fullNameHintLength, pShortNameOffset, false, true/*add brackets*/);
  7013. }
  7014. else if(op == knopFlt)
  7015. {
  7016. rightNode = m_pscan->StringFromDbl(pNode->sxFlt.dbl);
  7017. }
  7018. else
  7019. {
  7020. rightNode = op == knopInt ? m_pscan->StringFromLong(pNode->sxInt.lw)
  7021. : pNode->sxPid.pid->Psz();
  7022. }
  7023. return AppendNameHints(propertyString, rightNode, fullNameHintLength, pShortNameOffset, false, true/*add brackets*/);
  7024. }
  7025. LPCOLESTR Parser::ConstructNameHint(ParseNodePtr pNode, uint32* fullNameHintLength, uint32 *pShortNameOffset)
  7026. {
  7027. Assert(pNode != nullptr);
  7028. Assert(pNode->nop == knopDot || pNode->nop == knopIndex);
  7029. LPCOLESTR leftNode = nullptr;
  7030. if (pNode->sxBin.pnode1->nop == knopDot || pNode->sxBin.pnode1->nop == knopIndex)
  7031. {
  7032. leftNode = ConstructNameHint(pNode->sxBin.pnode1, fullNameHintLength, pShortNameOffset);
  7033. }
  7034. else if (pNode->sxBin.pnode1->nop == knopName && !pNode->sxBin.pnode1->isSpecialName)
  7035. {
  7036. // We need to skip special names like 'this' because those shouldn't be appended to the
  7037. // name hint in the debugger stack trace.
  7038. // function ctor() {
  7039. // this.func = function() {
  7040. // // If we break here, the stack should say we are in 'func' and not 'this.func'
  7041. // }
  7042. // }
  7043. leftNode = pNode->sxBin.pnode1->sxPid.pid->Psz();
  7044. *fullNameHintLength = pNode->sxBin.pnode1->sxPid.pid->Cch();
  7045. *pShortNameOffset = 0;
  7046. }
  7047. if (pNode->nop == knopIndex)
  7048. {
  7049. return FormatPropertyString(
  7050. leftNode ? leftNode : Js::Constants::AnonymousFunction, // e.g. f()[0] = function () {}
  7051. pNode->sxBin.pnode2, fullNameHintLength, pShortNameOffset);
  7052. }
  7053. Assert(pNode->sxBin.pnode2->nop == knopDot || pNode->sxBin.pnode2->nop == knopName);
  7054. LPCOLESTR rightNode = nullptr;
  7055. bool wrapWithBrackets = false;
  7056. if (pNode->sxBin.pnode2->nop == knopDot)
  7057. {
  7058. rightNode = ConstructNameHint(pNode->sxBin.pnode2, fullNameHintLength, pShortNameOffset);
  7059. }
  7060. else
  7061. {
  7062. rightNode = pNode->sxBin.pnode2->sxPid.pid->Psz();
  7063. wrapWithBrackets = PNodeFlags::fpnIndexOperator == (pNode->grfpn & PNodeFlags::fpnIndexOperator);
  7064. }
  7065. Assert(rightNode != nullptr);
  7066. return AppendNameHints(leftNode, rightNode, fullNameHintLength, pShortNameOffset, false, wrapWithBrackets);
  7067. }
  7068. LPCOLESTR Parser::AppendNameHints(LPCOLESTR leftStr, uint32 leftLen, LPCOLESTR rightStr, uint32 rightLen, uint32 *pNameLength, uint32 *pShortNameOffset, bool ignoreAddDotWithSpace, bool wrapInBrackets)
  7069. {
  7070. Assert(rightStr != nullptr);
  7071. Assert(leftLen != 0 || wrapInBrackets);
  7072. Assert(rightLen != 0 || wrapInBrackets);
  7073. 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
  7074. uint32 totalLength = leftLen + rightLen + ((ignoreDot) ? 1 : 2); // 1 (for dot or [) + 1 (for null termination)
  7075. if (wrapInBrackets)
  7076. {
  7077. totalLength++; //1 for ']';
  7078. }
  7079. WCHAR * finalName = AllocateStringOfLength(totalLength);
  7080. if (leftStr != nullptr && leftLen != 0)
  7081. {
  7082. wcscpy_s(finalName, leftLen + 1, leftStr);
  7083. }
  7084. if (ignoreAddDotWithSpace)
  7085. {
  7086. finalName[leftLen++] = (OLECHAR)_u(' ');
  7087. }
  7088. // mutually exclusive from ignoreAddDotWithSpace which is used for getters/setters
  7089. else if (wrapInBrackets)
  7090. {
  7091. finalName[leftLen++] = (OLECHAR)_u('[');
  7092. finalName[totalLength-2] = (OLECHAR)_u(']');
  7093. }
  7094. else if (!ignoreDot)
  7095. {
  7096. finalName[leftLen++] = (OLECHAR)_u('.');
  7097. }
  7098. //ignore case falls through
  7099. js_wmemcpy_s(finalName + leftLen, rightLen, rightStr, rightLen);
  7100. finalName[totalLength-1] = (OLECHAR)_u('\0');
  7101. if (pNameLength != nullptr)
  7102. {
  7103. *pNameLength = totalLength - 1;
  7104. }
  7105. if (pShortNameOffset != nullptr)
  7106. {
  7107. *pShortNameOffset = leftLen;
  7108. }
  7109. return finalName;
  7110. }
  7111. WCHAR * Parser::AllocateStringOfLength(ULONG length)
  7112. {
  7113. Assert(length > 0);
  7114. ULONG totalBytes;
  7115. if (ULongMult(length, sizeof(OLECHAR), &totalBytes) != S_OK)
  7116. {
  7117. Error(ERRnoMemory);
  7118. }
  7119. WCHAR* finalName = (WCHAR*)m_phtbl->GetAllocator()->Alloc(totalBytes);
  7120. if (finalName == nullptr)
  7121. {
  7122. Error(ERRnoMemory);
  7123. }
  7124. return finalName;
  7125. }
  7126. LPCOLESTR Parser::AppendNameHints(IdentPtr left, IdentPtr right, uint32 *pNameLength, uint32 *pShortNameOffset, bool ignoreAddDotWithSpace, bool wrapInBrackets)
  7127. {
  7128. if (pShortNameOffset != nullptr)
  7129. {
  7130. *pShortNameOffset = 0;
  7131. }
  7132. if (left == nullptr && !wrapInBrackets)
  7133. {
  7134. if (right)
  7135. {
  7136. *pNameLength = right->Cch();
  7137. return right->Psz();
  7138. }
  7139. return nullptr;
  7140. }
  7141. uint32 leftLen = 0;
  7142. LPCOLESTR leftStr = _u("");
  7143. if (left != nullptr) // if wrapInBrackets is true
  7144. {
  7145. leftStr = left->Psz();
  7146. leftLen = left->Cch();
  7147. }
  7148. if (right == nullptr)
  7149. {
  7150. *pNameLength = leftLen;
  7151. return left->Psz();
  7152. }
  7153. uint32 rightLen = right->Cch();
  7154. return AppendNameHints(leftStr, leftLen, right->Psz(), rightLen, pNameLength, pShortNameOffset, ignoreAddDotWithSpace, wrapInBrackets);
  7155. }
  7156. LPCOLESTR Parser::AppendNameHints(IdentPtr left, LPCOLESTR right, uint32 *pNameLength, uint32 *pShortNameOffset, bool ignoreAddDotWithSpace, bool wrapInBrackets)
  7157. {
  7158. uint32 rightLen = (right == nullptr) ? 0 : (uint32) wcslen(right);
  7159. if (pShortNameOffset != nullptr)
  7160. {
  7161. *pShortNameOffset = 0;
  7162. }
  7163. Assert(rightLen <= ULONG_MAX); // name hints should not exceed ULONG_MAX characters
  7164. if (left == nullptr && !wrapInBrackets)
  7165. {
  7166. *pNameLength = rightLen;
  7167. return right;
  7168. }
  7169. LPCOLESTR leftStr = _u("");
  7170. uint32 leftLen = 0;
  7171. if (left != nullptr) // if wrapInBrackets is true
  7172. {
  7173. leftStr = left->Psz();
  7174. leftLen = left->Cch();
  7175. }
  7176. if (rightLen == 0 && !wrapInBrackets)
  7177. {
  7178. *pNameLength = leftLen;
  7179. return left->Psz();
  7180. }
  7181. return AppendNameHints(leftStr, leftLen, right, rightLen, pNameLength, pShortNameOffset, ignoreAddDotWithSpace, wrapInBrackets);
  7182. }
  7183. LPCOLESTR Parser::AppendNameHints(LPCOLESTR left, IdentPtr right, uint32 *pNameLength, uint32 *pShortNameOffset, bool ignoreAddDotWithSpace, bool wrapInBrackets)
  7184. {
  7185. uint32 leftLen = (left == nullptr) ? 0 : (uint32) wcslen(left);
  7186. if (pShortNameOffset != nullptr)
  7187. {
  7188. *pShortNameOffset = 0;
  7189. }
  7190. Assert(leftLen <= ULONG_MAX); // name hints should not exceed ULONG_MAX characters
  7191. if (left == nullptr || (leftLen == 0 && !wrapInBrackets))
  7192. {
  7193. if (right != nullptr)
  7194. {
  7195. *pNameLength = right->Cch();
  7196. return right->Psz();
  7197. }
  7198. return nullptr;
  7199. }
  7200. if (right == nullptr)
  7201. {
  7202. *pNameLength = leftLen;
  7203. return left;
  7204. }
  7205. uint32 rightLen = right->Cch();
  7206. return AppendNameHints(left, leftLen, right->Psz(), rightLen, pNameLength, pShortNameOffset, ignoreAddDotWithSpace, wrapInBrackets);
  7207. }
  7208. LPCOLESTR Parser::AppendNameHints(LPCOLESTR left, LPCOLESTR right, uint32 *pNameLength, uint32 *pShortNameOffset, bool ignoreAddDotWithSpace, bool wrapInBrackets)
  7209. {
  7210. uint32 leftLen = (left == nullptr) ? 0 : (uint32) wcslen(left);
  7211. uint32 rightLen = (right == nullptr) ? 0 : (uint32) wcslen(right);
  7212. if (pShortNameOffset != nullptr)
  7213. {
  7214. *pShortNameOffset = 0;
  7215. }
  7216. Assert(rightLen <= ULONG_MAX && leftLen <= ULONG_MAX); // name hints should not exceed ULONG_MAX characters
  7217. if (leftLen == 0 && !wrapInBrackets)
  7218. {
  7219. *pNameLength = right ? rightLen : 0;
  7220. return right;
  7221. }
  7222. if (rightLen == 0 && !wrapInBrackets)
  7223. {
  7224. *pNameLength = leftLen;
  7225. return left;
  7226. }
  7227. return AppendNameHints(left, leftLen, right, rightLen, pNameLength, pShortNameOffset, ignoreAddDotWithSpace, wrapInBrackets);
  7228. }
  7229. /**
  7230. * Emits a spread error if there is no ambiguity, or marks defers the error for
  7231. * when we can determine if it is a rest error or a spread error.
  7232. *
  7233. * The ambiguity arises when we are parsing a lambda parameter list but we have
  7234. * not seen the => token. At this point, we are either in a parenthesized
  7235. * expression or a parameter list, and cannot issue an error until the matching
  7236. * RParen has been scanned.
  7237. *
  7238. * The actual emission of the error happens in ParseExpr, when we first know if
  7239. * the expression is a lambda parameter list or not.
  7240. *
  7241. */
  7242. void Parser::DeferOrEmitPotentialSpreadError(ParseNodePtr pnodeT)
  7243. {
  7244. if (m_funcParenExprDepth > 0)
  7245. {
  7246. if (m_token.tk == tkRParen)
  7247. {
  7248. if (!m_deferEllipsisError)
  7249. {
  7250. // Capture only the first error instance. Because a lambda will cause a reparse in a formals context, we can assume
  7251. // that this will be a spread error. Nested paren exprs will have their own error instance.
  7252. m_pscan->Capture(&m_deferEllipsisErrorLoc);
  7253. m_deferEllipsisError = true;
  7254. }
  7255. }
  7256. else
  7257. {
  7258. Error(ERRUnexpectedEllipsis);
  7259. }
  7260. }
  7261. else
  7262. {
  7263. Error(ERRInvalidSpreadUse);
  7264. }
  7265. }
  7266. /***************************************************************************
  7267. Parse an optional sub expression returning null if there was no expression.
  7268. Checks for no expression by looking for a token that can follow an
  7269. Expression grammar production.
  7270. ***************************************************************************/
  7271. template<bool buildAST>
  7272. bool Parser::ParseOptionalExpr(ParseNodePtr* pnode, bool fUnaryOrParen, int oplMin, BOOL *pfCanAssign, BOOL fAllowIn, BOOL fAllowEllipsis, _Inout_opt_ IdentToken* pToken)
  7273. {
  7274. *pnode = nullptr;
  7275. if (m_token.tk == tkRCurly ||
  7276. m_token.tk == tkRBrack ||
  7277. m_token.tk == tkRParen ||
  7278. m_token.tk == tkSColon ||
  7279. m_token.tk == tkColon ||
  7280. m_token.tk == tkComma ||
  7281. m_token.tk == tkLimKwd ||
  7282. m_pscan->FHadNewLine())
  7283. {
  7284. return false;
  7285. }
  7286. IdentToken token;
  7287. ParseNodePtr pnodeT = ParseExpr<buildAST>(oplMin, pfCanAssign, fAllowIn, fAllowEllipsis, nullptr /*pNameHint*/, nullptr /*pHintLength*/, nullptr /*pShortNameOffset*/, &token, fUnaryOrParen);
  7288. // Detect nested function escapes of the pattern "return function(){...}" or "yield function(){...}".
  7289. // Doing so in the parser allows us to disable stack-nested-functions in common cases where an escape
  7290. // is not detected at byte code gen time because of deferred parsing.
  7291. this->MarkEscapingRef(pnodeT, &token);
  7292. if (pToken)
  7293. {
  7294. *pToken = token;
  7295. }
  7296. *pnode = pnodeT;
  7297. return true;
  7298. }
  7299. /***************************************************************************
  7300. Parse a sub expression.
  7301. 'fAllowIn' indicates if the 'in' operator should be allowed in the initializing
  7302. expression ( it is not allowed in the context of the first expression in a 'for' loop).
  7303. ***************************************************************************/
  7304. template<bool buildAST>
  7305. ParseNodePtr Parser::ParseExpr(int oplMin,
  7306. BOOL *pfCanAssign,
  7307. BOOL fAllowIn,
  7308. BOOL fAllowEllipsis,
  7309. LPCOLESTR pNameHint,
  7310. uint32 *pHintLength,
  7311. uint32 *pShortNameOffset,
  7312. _Inout_opt_ IdentToken* pToken,
  7313. bool fUnaryOrParen,
  7314. _Inout_opt_ bool* pfLikelyPattern,
  7315. _Inout_opt_ charcount_t *plastRParen)
  7316. {
  7317. Assert(pToken == nullptr || pToken->tk == tkNone); // Must be empty initially
  7318. int opl;
  7319. OpCode nop;
  7320. charcount_t ichMin;
  7321. ParseNodePtr pnode = nullptr;
  7322. ParseNodePtr pnodeT = nullptr;
  7323. BOOL fCanAssign = TRUE;
  7324. bool assignmentStmt = false;
  7325. bool fIsDotOrIndex = false;
  7326. IdentToken term;
  7327. RestorePoint termStart;
  7328. uint32 hintLength = 0;
  7329. uint32 hintOffset = 0;
  7330. ParserState parserState;
  7331. if (pHintLength != nullptr)
  7332. {
  7333. hintLength = *pHintLength;
  7334. }
  7335. if (pShortNameOffset != nullptr)
  7336. {
  7337. hintOffset = *pShortNameOffset;
  7338. }
  7339. EnsureStackAvailable();
  7340. // Storing the state here as we need to restore this state back when we need to reparse the grammar under lambda syntax.
  7341. CaptureState(&parserState);
  7342. m_pscan->Capture(&termStart);
  7343. bool deferredErrorFoundOnLeftSide = false;
  7344. bool savedDeferredInitError = m_hasDeferredShorthandInitError;
  7345. m_hasDeferredShorthandInitError = false;
  7346. // Is the current token a unary operator?
  7347. if (m_phtbl->TokIsUnop(m_token.tk, &opl, &nop) && nop != knopNone)
  7348. {
  7349. IdentToken operandToken;
  7350. ichMin = m_pscan->IchMinTok();
  7351. if (nop == knopYield)
  7352. {
  7353. if (!m_pscan->YieldIsKeywordRegion() || oplMin > opl)
  7354. {
  7355. // The case where 'yield' is scanned as a keyword (tkYIELD) but the scanner
  7356. // is not treating yield as a keyword (!m_pscan->YieldIsKeywordRegion()) occurs
  7357. // in strict mode non-generator function contexts.
  7358. //
  7359. // That is, 'yield' is a keyword because of strict mode, but YieldExpression
  7360. // is not a grammar production outside of generator functions.
  7361. //
  7362. // Otherwise it is an error for a yield to appear in the context of a higher level
  7363. // binding operator, be it unary or binary.
  7364. Error(ERRsyntax);
  7365. }
  7366. if (m_currentScope->GetScopeType() == ScopeType_Parameter)
  7367. {
  7368. Error(ERRsyntax);
  7369. }
  7370. }
  7371. else if (nop == knopAwait)
  7372. {
  7373. if (!m_pscan->AwaitIsKeywordRegion() ||
  7374. m_currentScope->GetScopeType() == ScopeType_Parameter)
  7375. {
  7376. // As with the 'yield' keyword, the case where 'await' is scanned as a keyword (tkAWAIT)
  7377. // but the scanner is not treating await as a keyword (!m_pscan->AwaitIsKeyword())
  7378. // occurs in strict mode non-async function contexts.
  7379. //
  7380. // That is, 'await' is a keyword because of strict mode, but AwaitExpression
  7381. // is not a grammar production outside of async functions.
  7382. //
  7383. // Further, await expressions are disallowed within parameter scopes.
  7384. Error(ERRBadAwait);
  7385. }
  7386. }
  7387. m_pscan->Scan();
  7388. if (m_token.tk == tkEllipsis) {
  7389. // ... cannot have a unary prefix.
  7390. Error(ERRUnexpectedEllipsis);
  7391. }
  7392. if (nop == knopYield && !m_pscan->FHadNewLine() && m_token.tk == tkStar)
  7393. {
  7394. m_pscan->Scan();
  7395. nop = knopYieldStar;
  7396. }
  7397. if (nop == knopYield)
  7398. {
  7399. if (!ParseOptionalExpr<buildAST>(&pnodeT, false, opl, NULL, TRUE, fAllowEllipsis))
  7400. {
  7401. nop = knopYieldLeaf;
  7402. if (buildAST)
  7403. {
  7404. pnode = CreateNodeT<knopYieldLeaf>(ichMin, m_pscan->IchLimTok());
  7405. }
  7406. }
  7407. }
  7408. else
  7409. {
  7410. // Disallow spread after a unary operator.
  7411. pnodeT = ParseExpr<buildAST>(opl, &fCanAssign, TRUE, FALSE, nullptr /*hint*/, nullptr /*hintLength*/, nullptr /*hintOffset*/, &operandToken, true, nullptr, plastRParen);
  7412. }
  7413. if (nop != knopYieldLeaf)
  7414. {
  7415. if ((nop == knopIncPre || nop == knopDecPre) && (m_token.tk != tkDArrow))
  7416. {
  7417. if (!fCanAssign && PHASE_ON1(Js::EarlyReferenceErrorsPhase))
  7418. {
  7419. Error(JSERR_CantAssignTo);
  7420. }
  7421. TrackAssignment<buildAST>(pnodeT, &operandToken);
  7422. if (buildAST)
  7423. {
  7424. if (IsStrictMode() && pnodeT->nop == knopName)
  7425. {
  7426. CheckStrictModeEvalArgumentsUsage(pnodeT->sxPid.pid);
  7427. }
  7428. }
  7429. else
  7430. {
  7431. if (IsStrictMode() && operandToken.tk == tkID)
  7432. {
  7433. CheckStrictModeEvalArgumentsUsage(operandToken.pid);
  7434. }
  7435. }
  7436. }
  7437. else if (nop == knopEllipsis)
  7438. {
  7439. if (!fAllowEllipsis)
  7440. {
  7441. DeferOrEmitPotentialSpreadError(pnodeT);
  7442. }
  7443. }
  7444. else if (m_token.tk == tkExpo)
  7445. {
  7446. //Unary operator on the left hand-side of ** is unexpected, except ++, -- or ...
  7447. Error(ERRInvalidUseofExponentiationOperator);
  7448. }
  7449. if (buildAST)
  7450. {
  7451. //Do not do the folding for Asm in case of KnopPos as we need this to determine the type
  7452. if (nop == knopPos && (pnodeT->nop == knopInt || pnodeT->nop == knopFlt) && !this->m_InAsmMode)
  7453. {
  7454. // Fold away a unary '+' on a number.
  7455. pnode = pnodeT;
  7456. }
  7457. else if (nop == knopNeg &&
  7458. ((pnodeT->nop == knopInt && pnodeT->sxInt.lw != 0) ||
  7459. (pnodeT->nop == knopFlt && (pnodeT->sxFlt.dbl != 0 || this->m_InAsmMode))))
  7460. {
  7461. // Fold a unary '-' on a number into the value of the number itself.
  7462. pnode = pnodeT;
  7463. if (pnode->nop == knopInt)
  7464. {
  7465. pnode->sxInt.lw = -pnode->sxInt.lw;
  7466. }
  7467. else
  7468. {
  7469. pnode->sxFlt.dbl = -pnode->sxFlt.dbl;
  7470. }
  7471. }
  7472. else
  7473. {
  7474. pnode = CreateUniNode(nop, pnodeT);
  7475. this->CheckArguments(pnode->sxUni.pnode1);
  7476. }
  7477. pnode->ichMin = ichMin;
  7478. }
  7479. if (nop == knopDelete)
  7480. {
  7481. if (IsStrictMode())
  7482. {
  7483. if ((buildAST && pnode->sxUni.pnode1->nop == knopName) ||
  7484. (!buildAST && operandToken.tk == tkID))
  7485. {
  7486. Error(ERRInvalidDelete);
  7487. }
  7488. }
  7489. if (buildAST)
  7490. {
  7491. ParseNodePtr pnode1 = pnode->sxUni.pnode1;
  7492. if (m_currentNodeFunc)
  7493. {
  7494. if (pnode1->nop == knopDot || pnode1->nop == knopIndex)
  7495. {
  7496. // If we delete an arguments property, use the conservative,
  7497. // heap-allocated arguments object.
  7498. this->CheckArguments(pnode1->sxBin.pnode1);
  7499. }
  7500. }
  7501. }
  7502. }
  7503. }
  7504. fCanAssign = FALSE;
  7505. }
  7506. else
  7507. {
  7508. ichMin = m_pscan->IchMinTok();
  7509. BOOL fLikelyPattern = FALSE;
  7510. pnode = ParseTerm<buildAST>(TRUE, pNameHint, &hintLength, &hintOffset, &term, fUnaryOrParen, &fCanAssign, IsES6DestructuringEnabled() ? &fLikelyPattern : nullptr, &fIsDotOrIndex, plastRParen);
  7511. if (pfLikelyPattern != nullptr)
  7512. {
  7513. *pfLikelyPattern = !!fLikelyPattern;
  7514. }
  7515. if (m_token.tk == tkDArrow)
  7516. {
  7517. m_hasDeferredShorthandInitError = false;
  7518. }
  7519. if (m_token.tk == tkAsg && oplMin <= koplAsg && fLikelyPattern)
  7520. {
  7521. m_pscan->SeekTo(termStart);
  7522. // 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
  7523. // on the pidref stack match.
  7524. int saveNextBlockId = m_nextBlockId;
  7525. m_nextBlockId = parserState.m_nextBlockId;
  7526. ParseDestructuredLiteralWithScopeSave(tkLCurly, false/*isDecl*/, false /*topLevel*/, DIC_ShouldNotParseInitializer);
  7527. // 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
  7528. // because we don't parse initializers during reparse and there may be additional blocks (e.g. a class declaration)
  7529. // in the initializers that will cause the next Block ID at the end of the reparsing to be different.
  7530. m_nextBlockId = saveNextBlockId;
  7531. if (buildAST)
  7532. {
  7533. this->SetHasDestructuringPattern(true);
  7534. pnode = ConvertToPattern(pnode);
  7535. }
  7536. // The left-hand side is found to be destructuring pattern - so the shorthand can have initializer.
  7537. m_hasDeferredShorthandInitError = false;
  7538. }
  7539. if (buildAST)
  7540. {
  7541. pNameHint = NULL;
  7542. if (pnode->nop == knopName)
  7543. {
  7544. pNameHint = pnode->sxPid.pid->Psz();
  7545. hintLength = pnode->sxPid.pid->Cch();
  7546. hintOffset = 0;
  7547. }
  7548. else if (pnode->nop == knopDot || pnode->nop == knopIndex)
  7549. {
  7550. if (CONFIG_FLAG(UseFullName))
  7551. {
  7552. pNameHint = ConstructNameHint(pnode, &hintLength, &hintOffset);
  7553. }
  7554. else
  7555. {
  7556. ParseNodePtr pnodeName = pnode;
  7557. while (pnodeName->nop == knopDot)
  7558. {
  7559. pnodeName = pnodeName->sxBin.pnode2;
  7560. }
  7561. if (pnodeName->nop == knopName)
  7562. {
  7563. pNameHint = pnodeName->sxPid.pid->Psz();
  7564. hintLength = pnodeName->sxPid.pid->Cch();
  7565. hintOffset = 0;
  7566. }
  7567. }
  7568. }
  7569. }
  7570. // Check for postfix unary operators.
  7571. if (!m_pscan->FHadNewLine() &&
  7572. (tkInc == m_token.tk || tkDec == m_token.tk))
  7573. {
  7574. if (!fCanAssign && PHASE_ON1(Js::EarlyReferenceErrorsPhase))
  7575. {
  7576. Error(JSERR_CantAssignTo);
  7577. }
  7578. TrackAssignment<buildAST>(pnode, &term);
  7579. fCanAssign = FALSE;
  7580. if (buildAST)
  7581. {
  7582. if (IsStrictMode() && pnode->nop == knopName)
  7583. {
  7584. CheckStrictModeEvalArgumentsUsage(pnode->sxPid.pid);
  7585. }
  7586. this->CheckArguments(pnode);
  7587. pnode = CreateUniNode(tkInc == m_token.tk ? knopIncPost : knopDecPost, pnode);
  7588. pnode->ichLim = m_pscan->IchLimTok();
  7589. }
  7590. else
  7591. {
  7592. if (IsStrictMode() && term.tk == tkID)
  7593. {
  7594. CheckStrictModeEvalArgumentsUsage(term.pid);
  7595. }
  7596. // This expression is not an identifier
  7597. term.tk = tkNone;
  7598. }
  7599. m_pscan->Scan();
  7600. }
  7601. }
  7602. deferredErrorFoundOnLeftSide = m_hasDeferredShorthandInitError;
  7603. // Process a sequence of operators and operands.
  7604. for (;;)
  7605. {
  7606. if (!m_phtbl->TokIsBinop(m_token.tk, &opl, &nop) || nop == knopNone)
  7607. {
  7608. break;
  7609. }
  7610. if ( ! fAllowIn && nop == knopIn )
  7611. {
  7612. break;
  7613. }
  7614. Assert(opl != koplNo);
  7615. if (opl == koplAsg)
  7616. {
  7617. if (m_token.tk != tkDArrow)
  7618. {
  7619. // Assignment operator. These are the only right associative
  7620. // binary operators. We also need to special case the left
  7621. // operand - it should only be a LeftHandSideExpression.
  7622. Assert(ParseNode::Grfnop(nop) & fnopAsg || nop == knopFncDecl);
  7623. TrackAssignment<buildAST>(pnode, &term);
  7624. if (buildAST)
  7625. {
  7626. if (IsStrictMode() && pnode->nop == knopName)
  7627. {
  7628. CheckStrictModeEvalArgumentsUsage(pnode->sxPid.pid);
  7629. }
  7630. // Assignment stmt of the form "this.<id> = <expr>"
  7631. if (nop == knopAsg
  7632. && pnode->nop == knopDot
  7633. && pnode->sxBin.pnode1->nop == knopName
  7634. && pnode->sxBin.pnode1->sxVar.pid == wellKnownPropertyPids._this
  7635. && pnode->sxBin.pnode2->nop == knopName)
  7636. {
  7637. if (pnode->sxBin.pnode2->sxPid.pid != wellKnownPropertyPids.__proto__)
  7638. {
  7639. assignmentStmt = true;
  7640. }
  7641. }
  7642. }
  7643. else
  7644. {
  7645. if (IsStrictMode() && term.tk == tkID)
  7646. {
  7647. CheckStrictModeEvalArgumentsUsage(term.pid);
  7648. }
  7649. }
  7650. }
  7651. if (opl < oplMin)
  7652. {
  7653. break;
  7654. }
  7655. if (m_token.tk != tkDArrow && !fCanAssign && PHASE_ON1(Js::EarlyReferenceErrorsPhase))
  7656. {
  7657. Error(JSERR_CantAssignTo);
  7658. // No recovery necessary since this is a semantic, not structural, error.
  7659. }
  7660. }
  7661. else if (opl == koplExpo)
  7662. {
  7663. // ** operator is right associative
  7664. if (opl < oplMin)
  7665. {
  7666. break;
  7667. }
  7668. }
  7669. else if (opl <= oplMin)
  7670. {
  7671. break;
  7672. }
  7673. // This expression is not an identifier
  7674. term.tk = tkNone;
  7675. // Precedence is high enough. Consume the operator token.
  7676. m_pscan->Scan();
  7677. fCanAssign = FALSE;
  7678. // Special case the "?:" operator
  7679. if (nop == knopQmark)
  7680. {
  7681. pnodeT = ParseExpr<buildAST>(koplAsg, NULL, fAllowIn);
  7682. ChkCurTok(tkColon, ERRnoColon);
  7683. ParseNodePtr pnodeT2 = ParseExpr<buildAST>(koplAsg, NULL, fAllowIn, 0, nullptr, nullptr, nullptr, nullptr, false, nullptr, plastRParen);
  7684. if (buildAST)
  7685. {
  7686. pnode = CreateTriNode(nop, pnode, pnodeT, pnodeT2);
  7687. this->CheckArguments(pnode->sxTri.pnode2);
  7688. this->CheckArguments(pnode->sxTri.pnode3);
  7689. }
  7690. }
  7691. else if (nop == knopFncDecl)
  7692. {
  7693. ushort flags = fFncLambda;
  7694. size_t iecpMin = 0;
  7695. bool isAsyncMethod = false;
  7696. RestoreStateFrom(&parserState);
  7697. m_pscan->SeekTo(termStart);
  7698. if (m_token.tk == tkID && m_token.GetIdentifier(m_phtbl) == wellKnownPropertyPids.async && m_scriptContext->GetConfig()->IsES7AsyncAndAwaitEnabled())
  7699. {
  7700. ichMin = m_pscan->IchMinTok();
  7701. iecpMin = m_pscan->IecpMinTok();
  7702. m_pscan->Scan();
  7703. if ((m_token.tk == tkID || m_token.tk == tkLParen) && !m_pscan->FHadNewLine())
  7704. {
  7705. flags |= fFncAsync;
  7706. isAsyncMethod = true;
  7707. }
  7708. else
  7709. {
  7710. m_pscan->SeekTo(termStart);
  7711. }
  7712. }
  7713. pnode = ParseFncDecl<buildAST>(flags, nullptr, /* needsPIDOnRCurlyScan = */false, /* resetParsingSuperRestrictionState = */false);
  7714. if (isAsyncMethod)
  7715. {
  7716. pnode->sxFnc.cbMin = iecpMin;
  7717. pnode->ichMin = ichMin;
  7718. }
  7719. // ArrowFunction/AsyncArrowFunction is part of AssignmentExpression, which should terminate the expression unless followed by a comma
  7720. if (m_token.tk != tkComma)
  7721. {
  7722. break;
  7723. }
  7724. }
  7725. else
  7726. {
  7727. // Parse the operand, make a new node, and look for more
  7728. IdentToken token;
  7729. pnodeT = ParseExpr<buildAST>(opl, NULL, fAllowIn, FALSE, pNameHint, &hintLength, &hintOffset, &token, false, nullptr, plastRParen);
  7730. // Detect nested function escapes of the pattern "o.f = function(){...}" or "o[s] = function(){...}".
  7731. // Doing so in the parser allows us to disable stack-nested-functions in common cases where an escape
  7732. // is not detected at byte code gen time because of deferred parsing.
  7733. if (fIsDotOrIndex && nop == knopAsg)
  7734. {
  7735. this->MarkEscapingRef(pnodeT, &token);
  7736. }
  7737. if (buildAST)
  7738. {
  7739. pnode = CreateBinNode(nop, pnode, pnodeT);
  7740. Assert(pnode->sxBin.pnode2 != NULL);
  7741. if (pnode->sxBin.pnode2->nop == knopFncDecl)
  7742. {
  7743. Assert(hintLength >= hintOffset);
  7744. pnode->sxBin.pnode2->sxFnc.hint = pNameHint;
  7745. pnode->sxBin.pnode2->sxFnc.hintLength = hintLength;
  7746. pnode->sxBin.pnode2->sxFnc.hintOffset = hintOffset;
  7747. if (pnode->sxBin.pnode1->nop == knopDot)
  7748. {
  7749. pnode->sxBin.pnode2->sxFnc.isNameIdentifierRef = false;
  7750. }
  7751. else if (pnode->sxBin.pnode1->nop == knopName)
  7752. {
  7753. PidRefStack *pidRef = pnode->sxBin.pnode1->sxPid.pid->GetTopRef();
  7754. pidRef->isFuncAssignment = true;
  7755. }
  7756. }
  7757. if (pnode->sxBin.pnode2->nop == knopClassDecl && pnode->sxBin.pnode1->nop == knopDot)
  7758. {
  7759. Assert(pnode->sxBin.pnode2->sxClass.pnodeConstructor);
  7760. pnode->sxBin.pnode2->sxClass.pnodeConstructor->sxFnc.isNameIdentifierRef = false;
  7761. }
  7762. }
  7763. pNameHint = NULL;
  7764. }
  7765. }
  7766. if (buildAST)
  7767. {
  7768. if (!assignmentStmt)
  7769. {
  7770. // Don't set the flag for following nodes
  7771. switch (pnode->nop)
  7772. {
  7773. case knopName:
  7774. case knopInt:
  7775. case knopFlt:
  7776. case knopStr:
  7777. case knopRegExp:
  7778. case knopNull:
  7779. case knopFalse:
  7780. case knopTrue:
  7781. break;
  7782. default:
  7783. if (m_currentNodeFunc)
  7784. {
  7785. m_currentNodeFunc->sxFnc.SetHasNonThisStmt();
  7786. }
  7787. else if (m_currentNodeProg)
  7788. {
  7789. m_currentNodeProg->sxFnc.SetHasNonThisStmt();
  7790. }
  7791. }
  7792. }
  7793. }
  7794. if (m_hasDeferredShorthandInitError && !deferredErrorFoundOnLeftSide)
  7795. {
  7796. // Raise error only if it is found not on the right side of the expression.
  7797. // such as <expr> = {x = 1}
  7798. Error(ERRnoColon);
  7799. }
  7800. m_hasDeferredShorthandInitError = m_hasDeferredShorthandInitError || savedDeferredInitError;
  7801. if (NULL != pfCanAssign)
  7802. {
  7803. *pfCanAssign = fCanAssign;
  7804. }
  7805. // Pass back identifier if requested
  7806. if (pToken && term.tk == tkID)
  7807. {
  7808. *pToken = term;
  7809. }
  7810. //Track "obj.a" assignment patterns here - Promote the Assignment state for the property's PID.
  7811. // This includes =, += etc.
  7812. if (pnode != NULL)
  7813. {
  7814. uint nodeType = ParseNode::Grfnop(pnode->nop);
  7815. if (nodeType & fnopAsg)
  7816. {
  7817. if (nodeType & fnopBin)
  7818. {
  7819. ParseNodePtr lhs = pnode->sxBin.pnode1;
  7820. Assert(lhs);
  7821. if (lhs->nop == knopDot)
  7822. {
  7823. ParseNodePtr propertyNode = lhs->sxBin.pnode2;
  7824. if (propertyNode->nop == knopName)
  7825. {
  7826. propertyNode->sxPid.pid->PromoteAssignmentState();
  7827. }
  7828. }
  7829. }
  7830. else if (nodeType & fnopUni)
  7831. {
  7832. // cases like obj.a++, ++obj.a
  7833. ParseNodePtr lhs = pnode->sxUni.pnode1;
  7834. if (lhs->nop == knopDot)
  7835. {
  7836. ParseNodePtr propertyNode = lhs->sxBin.pnode2;
  7837. if (propertyNode->nop == knopName)
  7838. {
  7839. propertyNode->sxPid.pid->PromoteAssignmentState();
  7840. }
  7841. }
  7842. }
  7843. }
  7844. }
  7845. return pnode;
  7846. }
  7847. template<bool buildAST>
  7848. void Parser::TrackAssignment(ParseNodePtr pnodeT, IdentToken* pToken)
  7849. {
  7850. if (buildAST)
  7851. {
  7852. Assert(pnodeT != nullptr);
  7853. if (pnodeT->nop == knopName)
  7854. {
  7855. PidRefStack *ref = pnodeT->sxPid.pid->GetTopRef();
  7856. Assert(ref);
  7857. ref->isAsg = true;
  7858. }
  7859. }
  7860. else
  7861. {
  7862. Assert(pToken != nullptr);
  7863. if (pToken->tk == tkID)
  7864. {
  7865. PidRefStack *ref = pToken->pid->GetTopRef();
  7866. Assert(ref);
  7867. ref->isAsg = true;
  7868. }
  7869. }
  7870. }
  7871. void PnPid::SetSymRef(PidRefStack *ref)
  7872. {
  7873. Assert(symRef == nullptr);
  7874. this->symRef = ref->GetSymRef();
  7875. }
  7876. Js::PropertyId PnPid::PropertyIdFromNameNode() const
  7877. {
  7878. Js::PropertyId propertyId;
  7879. Symbol *sym = this->sym;
  7880. if (sym)
  7881. {
  7882. propertyId = sym->GetPosition();
  7883. }
  7884. else
  7885. {
  7886. propertyId = this->pid->GetPropertyId();
  7887. }
  7888. return propertyId;
  7889. }
  7890. PidRefStack* Parser::PushPidRef(IdentPtr pid)
  7891. {
  7892. if (PHASE_ON1(Js::ParallelParsePhase))
  7893. {
  7894. // NOTE: the phase check is here to protect perf. See OSG 1020424.
  7895. // In some LS AST-rewrite cases we lose a lot of perf searching the PID ref stack rather
  7896. // than just pushing on the top. This hasn't shown up as a perf issue in non-LS benchmarks.
  7897. return pid->FindOrAddPidRef(&m_nodeAllocator, GetCurrentBlock()->sxBlock.blockId, GetCurrentFunctionNode()->sxFnc.functionId);
  7898. }
  7899. Assert(GetCurrentBlock() != nullptr);
  7900. AssertMsg(pid != nullptr, "PID should be created");
  7901. PidRefStack *ref = pid->GetTopRef(m_nextBlockId - 1);
  7902. int blockId = GetCurrentBlock()->sxBlock.blockId;
  7903. int funcId = GetCurrentFunctionNode()->sxFnc.functionId;
  7904. if (!ref || (ref->GetScopeId() < blockId))
  7905. {
  7906. ref = Anew(&m_nodeAllocator, PidRefStack);
  7907. if (ref == nullptr)
  7908. {
  7909. Error(ERRnoMemory);
  7910. }
  7911. pid->PushPidRef(blockId, funcId, ref);
  7912. }
  7913. else if (m_reparsingLambdaParams)
  7914. {
  7915. // If we're reparsing params, then we may have pid refs left behind from the first pass. Make sure we're
  7916. // working with the right ref at this point.
  7917. ref = this->FindOrAddPidRef(pid, blockId, funcId);
  7918. // Fix up the function ID if we're reparsing lambda parameters.
  7919. ref->funcId = funcId;
  7920. }
  7921. return ref;
  7922. }
  7923. PidRefStack* Parser::FindOrAddPidRef(IdentPtr pid, int scopeId, Js::LocalFunctionId funcId)
  7924. {
  7925. PidRefStack *ref = pid->FindOrAddPidRef(&m_nodeAllocator, scopeId, funcId);
  7926. if (ref == NULL)
  7927. {
  7928. Error(ERRnoMemory);
  7929. }
  7930. return ref;
  7931. }
  7932. void Parser::RemovePrevPidRef(IdentPtr pid, PidRefStack *ref)
  7933. {
  7934. PidRefStack *prevRef = pid->RemovePrevPidRef(ref);
  7935. Assert(prevRef);
  7936. if (prevRef->GetSym() == nullptr)
  7937. {
  7938. AllocatorDelete(ArenaAllocator, &m_nodeAllocator, prevRef);
  7939. }
  7940. }
  7941. void Parser::SetPidRefsInScopeDynamic(IdentPtr pid, int blockId)
  7942. {
  7943. PidRefStack *ref = pid->GetTopRef();
  7944. while (ref && ref->GetScopeId() >= blockId)
  7945. {
  7946. ref->SetDynamicBinding();
  7947. ref = ref->prev;
  7948. }
  7949. }
  7950. ParseNode* Parser::GetFunctionBlock()
  7951. {
  7952. Assert(m_currentBlockInfo != nullptr);
  7953. return m_currentBlockInfo->pBlockInfoFunction->pnodeBlock;
  7954. }
  7955. ParseNode* Parser::GetCurrentBlock()
  7956. {
  7957. return m_currentBlockInfo != nullptr ? m_currentBlockInfo->pnodeBlock : nullptr;
  7958. }
  7959. BlockInfoStack* Parser::GetCurrentBlockInfo()
  7960. {
  7961. return m_currentBlockInfo;
  7962. }
  7963. BlockInfoStack* Parser::GetCurrentFunctionBlockInfo()
  7964. {
  7965. return m_currentBlockInfo->pBlockInfoFunction;
  7966. }
  7967. /***************************************************************************
  7968. Parse a variable declaration.
  7969. 'fAllowIn' indicates if the 'in' operator should be allowed in the initializing
  7970. expression ( it is not allowed in the context of the first expression in a 'for' loop).
  7971. ***************************************************************************/
  7972. template<bool buildAST>
  7973. ParseNodePtr Parser::ParseVariableDeclaration(
  7974. tokens declarationType, charcount_t ichMin,
  7975. BOOL fAllowIn/* = TRUE*/,
  7976. BOOL* pfForInOk/* = nullptr*/,
  7977. BOOL singleDefOnly/* = FALSE*/,
  7978. BOOL allowInit/* = TRUE*/,
  7979. BOOL isTopVarParse/* = TRUE*/,
  7980. BOOL isFor/* = FALSE*/,
  7981. BOOL* nativeForOk /*= nullptr*/)
  7982. {
  7983. ParseNodePtr pnodeThis = nullptr;
  7984. ParseNodePtr pnodeInit;
  7985. ParseNodePtr pnodeList = nullptr;
  7986. ParseNodePtr *lastNodeRef = nullptr;
  7987. LPCOLESTR pNameHint = nullptr;
  7988. uint32 nameHintLength = 0;
  7989. uint32 nameHintOffset = 0;
  7990. Assert(declarationType == tkVAR || declarationType == tkCONST || declarationType == tkLET);
  7991. for (;;)
  7992. {
  7993. if (IsES6DestructuringEnabled() && IsPossiblePatternStart())
  7994. {
  7995. pnodeThis = ParseDestructuredLiteral<buildAST>(declarationType, true, !!isTopVarParse, DIC_None, !!fAllowIn, pfForInOk, nativeForOk);
  7996. if (pnodeThis != nullptr)
  7997. {
  7998. pnodeThis->ichMin = ichMin;
  7999. }
  8000. }
  8001. else
  8002. {
  8003. if (m_token.tk != tkID)
  8004. {
  8005. IdentifierExpectedError(m_token);
  8006. }
  8007. IdentPtr pid = m_token.GetIdentifier(m_phtbl);
  8008. Assert(pid);
  8009. pNameHint = pid->Psz();
  8010. nameHintLength = pid->Cch();
  8011. nameHintOffset = 0;
  8012. if (pid == wellKnownPropertyPids.let && (declarationType == tkCONST || declarationType == tkLET))
  8013. {
  8014. Error(ERRLetIDInLexicalDecl, pnodeThis);
  8015. }
  8016. if (declarationType == tkVAR)
  8017. {
  8018. pnodeThis = CreateVarDeclNode(pid, STVariable);
  8019. }
  8020. else if (declarationType == tkCONST)
  8021. {
  8022. pnodeThis = CreateBlockScopedDeclNode(pid, knopConstDecl);
  8023. CHAKRATEL_LANGSTATS_INC_LANGFEATURECOUNT(Const, m_scriptContext);
  8024. }
  8025. else
  8026. {
  8027. pnodeThis = CreateBlockScopedDeclNode(pid, knopLetDecl);
  8028. CHAKRATEL_LANGSTATS_INC_LANGFEATURECOUNT(Let, m_scriptContext);
  8029. }
  8030. if (pid == wellKnownPropertyPids.arguments)
  8031. {
  8032. // This var declaration may change the way an 'arguments' identifier in the function is resolved
  8033. if (declarationType == tkVAR)
  8034. {
  8035. GetCurrentFunctionNode()->grfpn |= PNodeFlags::fpnArguments_varDeclaration;
  8036. }
  8037. else
  8038. {
  8039. if (GetCurrentBlockInfo()->pnodeBlock->sxBlock.blockType == Function)
  8040. {
  8041. // Only override arguments if we are at the function block level.
  8042. GetCurrentFunctionNode()->grfpn |= PNodeFlags::fpnArguments_overriddenByDecl;
  8043. }
  8044. }
  8045. }
  8046. if (pnodeThis)
  8047. {
  8048. pnodeThis->ichMin = ichMin;
  8049. }
  8050. m_pscan->Scan();
  8051. if (m_token.tk == tkAsg)
  8052. {
  8053. if (!allowInit)
  8054. {
  8055. Error(ERRUnexpectedDefault);
  8056. }
  8057. if (pfForInOk && (declarationType == tkLET || declarationType == tkCONST || IsStrictMode()))
  8058. {
  8059. *pfForInOk = FALSE;
  8060. }
  8061. m_pscan->Scan();
  8062. pnodeInit = ParseExpr<buildAST>(koplCma, nullptr, fAllowIn, FALSE, pNameHint, &nameHintLength, &nameHintOffset);
  8063. if (buildAST)
  8064. {
  8065. AnalysisAssert(pnodeThis);
  8066. pnodeThis->sxVar.pnodeInit = pnodeInit;
  8067. pnodeThis->ichLim = pnodeInit->ichLim;
  8068. if (pnodeInit->nop == knopFncDecl)
  8069. {
  8070. Assert(nameHintLength >= nameHintOffset);
  8071. pnodeInit->sxFnc.hint = pNameHint;
  8072. pnodeInit->sxFnc.hintLength = nameHintLength;
  8073. pnodeInit->sxFnc.hintOffset = nameHintOffset;
  8074. pnodeThis->sxVar.pid->GetTopRef()->isFuncAssignment = true;
  8075. }
  8076. else
  8077. {
  8078. this->CheckArguments(pnodeInit);
  8079. }
  8080. pNameHint = nullptr;
  8081. }
  8082. //Track var a =, let a= , const a =
  8083. // This is for FixedFields Constant Heuristics
  8084. if (pnodeThis && pnodeThis->sxVar.pnodeInit != nullptr)
  8085. {
  8086. pnodeThis->sxVar.sym->PromoteAssignmentState();
  8087. if (m_currentNodeFunc && pnodeThis->sxVar.sym->GetIsFormal())
  8088. {
  8089. m_currentNodeFunc->sxFnc.SetHasAnyWriteToFormals(true);
  8090. }
  8091. }
  8092. }
  8093. else if (declarationType == tkCONST /*pnodeThis->nop == knopConstDecl*/
  8094. && !singleDefOnly
  8095. && !(isFor && TokIsForInOrForOf()))
  8096. {
  8097. Error(ERRUninitializedConst);
  8098. }
  8099. }
  8100. if (singleDefOnly)
  8101. {
  8102. return pnodeThis;
  8103. }
  8104. if (buildAST)
  8105. {
  8106. AddToNodeListEscapedUse(&pnodeList, &lastNodeRef, pnodeThis);
  8107. }
  8108. if (m_token.tk != tkComma)
  8109. {
  8110. return pnodeList;
  8111. }
  8112. if (pfForInOk)
  8113. {
  8114. // don't allow "for (var a, b in c)"
  8115. *pfForInOk = FALSE;
  8116. }
  8117. m_pscan->Scan();
  8118. ichMin = m_pscan->IchMinTok();
  8119. }
  8120. }
  8121. /***************************************************************************
  8122. Parse try-catch-finally statement
  8123. ***************************************************************************/
  8124. // The try-catch-finally tree nests the try-catch within a try-finally.
  8125. // This matches the new runtime implementation.
  8126. template<bool buildAST>
  8127. ParseNodePtr Parser::ParseTryCatchFinally()
  8128. {
  8129. this->m_tryCatchOrFinallyDepth++;
  8130. ParseNodePtr pnodeT = ParseTry<buildAST>();
  8131. ParseNodePtr pnodeTC = nullptr;
  8132. StmtNest stmt;
  8133. bool hasCatch = false;
  8134. if (tkCATCH == m_token.tk)
  8135. {
  8136. hasCatch = true;
  8137. if (buildAST)
  8138. {
  8139. pnodeTC = CreateNodeWithScanner<knopTryCatch>();
  8140. pnodeT->sxStmt.pnodeOuter = pnodeTC;
  8141. pnodeTC->sxTryCatch.pnodeTry = pnodeT;
  8142. }
  8143. PushStmt<buildAST>(&stmt, pnodeTC, knopTryCatch, nullptr, nullptr);
  8144. ParseNodePtr pnodeCatch = ParseCatch<buildAST>();
  8145. if (buildAST)
  8146. {
  8147. pnodeTC->sxTryCatch.pnodeCatch = pnodeCatch;
  8148. }
  8149. PopStmt(&stmt);
  8150. }
  8151. if (tkFINALLY != m_token.tk)
  8152. {
  8153. if (!hasCatch)
  8154. {
  8155. Error(ERRnoCatch);
  8156. }
  8157. Assert(!buildAST || pnodeTC);
  8158. return pnodeTC;
  8159. }
  8160. ParseNodePtr pnodeTF = nullptr;
  8161. if (buildAST)
  8162. {
  8163. pnodeTF = CreateNode(knopTryFinally);
  8164. }
  8165. PushStmt<buildAST>(&stmt, pnodeTF, knopTryFinally, nullptr, nullptr);
  8166. ParseNodePtr pnodeFinally = ParseFinally<buildAST>();
  8167. if (buildAST)
  8168. {
  8169. if (!hasCatch)
  8170. {
  8171. pnodeTF->sxTryFinally.pnodeTry = pnodeT;
  8172. pnodeT->sxStmt.pnodeOuter = pnodeTF;
  8173. }
  8174. else
  8175. {
  8176. pnodeTF->sxTryFinally.pnodeTry = CreateNode(knopTry);
  8177. pnodeTF->sxTryFinally.pnodeTry->sxStmt.pnodeOuter = pnodeTF;
  8178. pnodeTF->sxTryFinally.pnodeTry->sxTry.pnodeBody = pnodeTC;
  8179. pnodeTC->sxStmt.pnodeOuter = pnodeTF->sxTryFinally.pnodeTry;
  8180. }
  8181. pnodeTF->sxTryFinally.pnodeFinally = pnodeFinally;
  8182. }
  8183. PopStmt(&stmt);
  8184. this->m_tryCatchOrFinallyDepth--;
  8185. return pnodeTF;
  8186. }
  8187. template<bool buildAST>
  8188. ParseNodePtr Parser::ParseTry()
  8189. {
  8190. ParseNodePtr pnode = nullptr;
  8191. StmtNest stmt;
  8192. Assert(tkTRY == m_token.tk);
  8193. if (buildAST)
  8194. {
  8195. pnode = CreateNode(knopTry);
  8196. }
  8197. m_pscan->Scan();
  8198. if (tkLCurly != m_token.tk)
  8199. {
  8200. Error(ERRnoLcurly);
  8201. }
  8202. PushStmt<buildAST>(&stmt, pnode, knopTry, nullptr, nullptr);
  8203. ParseNodePtr pnodeBody = ParseStatement<buildAST>();
  8204. if (buildAST)
  8205. {
  8206. pnode->sxTry.pnodeBody = pnodeBody;
  8207. if (pnode->sxTry.pnodeBody)
  8208. pnode->ichLim = pnode->sxTry.pnodeBody->ichLim;
  8209. }
  8210. PopStmt(&stmt);
  8211. return pnode;
  8212. }
  8213. template<bool buildAST>
  8214. ParseNodePtr Parser::ParseFinally()
  8215. {
  8216. ParseNodePtr pnode = nullptr;
  8217. StmtNest stmt;
  8218. Assert(tkFINALLY == m_token.tk);
  8219. if (buildAST)
  8220. {
  8221. pnode = CreateNode(knopFinally);
  8222. }
  8223. m_pscan->Scan();
  8224. if (tkLCurly != m_token.tk)
  8225. {
  8226. Error(ERRnoLcurly);
  8227. }
  8228. PushStmt<buildAST>(&stmt, pnode, knopFinally, nullptr, nullptr);
  8229. ParseNodePtr pnodeBody = ParseStatement<buildAST>();
  8230. if (buildAST)
  8231. {
  8232. pnode->sxFinally.pnodeBody = pnodeBody;
  8233. if (!pnode->sxFinally.pnodeBody)
  8234. // Will only occur due to error correction.
  8235. pnode->sxFinally.pnodeBody = CreateNodeWithScanner<knopEmpty>();
  8236. else
  8237. pnode->ichLim = pnode->sxFinally.pnodeBody->ichLim;
  8238. }
  8239. PopStmt(&stmt);
  8240. return pnode;
  8241. }
  8242. template<bool buildAST>
  8243. ParseNodePtr Parser::ParseCatch()
  8244. {
  8245. ParseNodePtr rootNode = nullptr;
  8246. ParseNodePtr* ppnode = &rootNode;
  8247. ParseNodePtr *ppnodeExprScopeSave = nullptr;
  8248. ParseNodePtr pnode = nullptr;
  8249. ParseNodePtr pnodeCatchScope = nullptr;
  8250. StmtNest stmt;
  8251. IdentPtr pidCatch = nullptr;
  8252. //while (tkCATCH == m_token.tk)
  8253. if (tkCATCH == m_token.tk)
  8254. {
  8255. charcount_t ichMin;
  8256. if (buildAST)
  8257. {
  8258. ichMin = m_pscan->IchMinTok();
  8259. }
  8260. m_pscan->Scan(); //catch
  8261. ChkCurTok(tkLParen, ERRnoLparen); //catch(
  8262. bool isPattern = false;
  8263. if (tkID != m_token.tk)
  8264. {
  8265. isPattern = IsES6DestructuringEnabled() && IsPossiblePatternStart();
  8266. if (!isPattern)
  8267. {
  8268. IdentifierExpectedError(m_token);
  8269. }
  8270. }
  8271. if (buildAST)
  8272. {
  8273. pnode = CreateNodeWithScanner<knopCatch>(ichMin);
  8274. PushStmt<buildAST>(&stmt, pnode, knopCatch, nullptr, nullptr);
  8275. *ppnode = pnode;
  8276. ppnode = &pnode->sxCatch.pnodeNext;
  8277. *ppnode = nullptr;
  8278. }
  8279. pnodeCatchScope = StartParseBlock<buildAST>(PnodeBlockType::Regular, isPattern ? ScopeType_CatchParamPattern : ScopeType_Catch);
  8280. if (buildAST)
  8281. {
  8282. // Add this catch to the current scope list.
  8283. if (m_ppnodeExprScope)
  8284. {
  8285. Assert(*m_ppnodeExprScope == nullptr);
  8286. *m_ppnodeExprScope = pnode;
  8287. m_ppnodeExprScope = &pnode->sxCatch.pnodeNext;
  8288. }
  8289. else
  8290. {
  8291. Assert(m_ppnodeScope);
  8292. Assert(*m_ppnodeScope == nullptr);
  8293. *m_ppnodeScope = pnode;
  8294. m_ppnodeScope = &pnode->sxCatch.pnodeNext;
  8295. }
  8296. // Keep a list of function expressions (not declarations) at this scope.
  8297. ppnodeExprScopeSave = m_ppnodeExprScope;
  8298. m_ppnodeExprScope = &pnode->sxCatch.pnodeScopes;
  8299. pnode->sxCatch.pnodeScopes = nullptr;
  8300. }
  8301. if (isPattern)
  8302. {
  8303. ParseNodePtr pnodePattern = ParseDestructuredLiteral<buildAST>(tkLET, true /*isDecl*/, true /*topLevel*/, DIC_ForceErrorOnInitializer);
  8304. if (buildAST)
  8305. {
  8306. pnode->sxCatch.pnodeParam = CreateParamPatternNode(pnodePattern);
  8307. Scope *scope = pnodeCatchScope->sxBlock.scope;
  8308. pnode->sxCatch.scope = scope;
  8309. }
  8310. }
  8311. else
  8312. {
  8313. if (IsStrictMode())
  8314. {
  8315. IdentPtr pid = m_token.GetIdentifier(m_phtbl);
  8316. if (pid == wellKnownPropertyPids.eval)
  8317. {
  8318. Error(ERREvalUsage);
  8319. }
  8320. else if (pid == wellKnownPropertyPids.arguments)
  8321. {
  8322. Error(ERRArgsUsage);
  8323. }
  8324. }
  8325. pidCatch = m_token.GetIdentifier(m_phtbl);
  8326. PidRefStack *ref = this->FindOrAddPidRef(pidCatch, GetCurrentBlock()->sxBlock.blockId, GetCurrentFunctionNode()->sxFnc.functionId);
  8327. ParseNodePtr pnodeParam = CreateNameNode(pidCatch);
  8328. pnodeParam->sxPid.symRef = ref->GetSymRef();
  8329. const char16 *name = reinterpret_cast<const char16*>(pidCatch->Psz());
  8330. int nameLength = pidCatch->Cch();
  8331. SymbolName const symName(name, nameLength);
  8332. Symbol *sym = Anew(&m_nodeAllocator, Symbol, symName, pnodeParam, STVariable);
  8333. sym->SetPid(pidCatch);
  8334. if (sym == nullptr)
  8335. {
  8336. Error(ERRnoMemory);
  8337. }
  8338. Assert(ref->GetSym() == nullptr);
  8339. ref->SetSym(sym);
  8340. Scope *scope = pnodeCatchScope->sxBlock.scope;
  8341. scope->AddNewSymbol(sym);
  8342. if (buildAST)
  8343. {
  8344. pnode->sxCatch.pnodeParam = pnodeParam;
  8345. pnode->sxCatch.scope = scope;
  8346. }
  8347. m_pscan->Scan();
  8348. }
  8349. charcount_t ichLim;
  8350. if (buildAST)
  8351. {
  8352. ichLim = m_pscan->IchLimTok();
  8353. }
  8354. ChkCurTok(tkRParen, ERRnoRparen); //catch(id[:expr])
  8355. if (tkLCurly != m_token.tk)
  8356. {
  8357. Error(ERRnoLcurly);
  8358. }
  8359. ParseNodePtr pnodeBody = ParseStatement<buildAST>(); //catch(id[:expr]) {block}
  8360. if (buildAST)
  8361. {
  8362. pnode->sxCatch.pnodeBody = pnodeBody;
  8363. pnode->ichLim = ichLim;
  8364. }
  8365. if (pnodeCatchScope != nullptr)
  8366. {
  8367. FinishParseBlock(pnodeCatchScope);
  8368. }
  8369. if (pnodeCatchScope->sxBlock.GetCallsEval() || pnodeCatchScope->sxBlock.GetChildCallsEval())
  8370. {
  8371. GetCurrentBlock()->sxBlock.SetChildCallsEval(true);
  8372. }
  8373. if (buildAST)
  8374. {
  8375. PopStmt(&stmt);
  8376. // Restore the lists of function expression scopes.
  8377. AssertMem(m_ppnodeExprScope);
  8378. Assert(*m_ppnodeExprScope == nullptr);
  8379. m_ppnodeExprScope = ppnodeExprScopeSave;
  8380. }
  8381. }
  8382. return rootNode;
  8383. }
  8384. template<bool buildAST>
  8385. ParseNodePtr Parser::ParseCase(ParseNodePtr *ppnodeBody)
  8386. {
  8387. ParseNodePtr pnodeT = nullptr;
  8388. charcount_t ichMinT = m_pscan->IchMinTok();
  8389. m_pscan->Scan();
  8390. ParseNodePtr pnodeExpr = ParseExpr<buildAST>();
  8391. charcount_t ichLim = m_pscan->IchLimTok();
  8392. ChkCurTok(tkColon, ERRnoColon);
  8393. if (buildAST)
  8394. {
  8395. pnodeT = CreateNodeWithScanner<knopCase>(ichMinT);
  8396. pnodeT->sxCase.pnodeExpr = pnodeExpr;
  8397. pnodeT->ichLim = ichLim;
  8398. }
  8399. ParseStmtList<buildAST>(ppnodeBody);
  8400. return pnodeT;
  8401. }
  8402. /***************************************************************************
  8403. Parse a single statement. Digest a trailing semicolon.
  8404. ***************************************************************************/
  8405. template<bool buildAST>
  8406. ParseNodePtr Parser::ParseStatement()
  8407. {
  8408. ParseNodePtr *ppnodeT;
  8409. ParseNodePtr pnodeT;
  8410. ParseNodePtr pnode = nullptr;
  8411. LabelId* pLabelIdList = nullptr;
  8412. charcount_t ichMin = 0;
  8413. size_t iecpMin = 0;
  8414. StmtNest stmt;
  8415. StmtNest *pstmt;
  8416. BOOL fForInOrOfOkay;
  8417. BOOL fCanAssign;
  8418. IdentPtr pid;
  8419. uint fnop;
  8420. ParseNodePtr pnodeLabel = nullptr;
  8421. bool expressionStmt = false;
  8422. bool isAsyncMethod = false;
  8423. tokens tok;
  8424. #if EXCEPTION_RECOVERY
  8425. ParseNodePtr pParentTryCatch = nullptr;
  8426. ParseNodePtr pTryBlock = nullptr;
  8427. ParseNodePtr pTry = nullptr;
  8428. ParseNodePtr pParentTryCatchBlock = nullptr;
  8429. StmtNest stmtTryCatchBlock;
  8430. StmtNest stmtTryCatch;
  8431. StmtNest stmtTry;
  8432. StmtNest stmtTryBlock;
  8433. #endif
  8434. if (buildAST)
  8435. {
  8436. #if EXCEPTION_RECOVERY
  8437. if(Js::Configuration::Global.flags.SwallowExceptions)
  8438. {
  8439. // If we're swallowing exceptions, surround this statement with a try/catch block:
  8440. //
  8441. // Before: x.y = 3;
  8442. // After: try { x.y = 3; } catch(__ehobj) { }
  8443. //
  8444. // This is done to force the runtime to recover from exceptions at the most granular
  8445. // possible point. Recovering from EH dramatically improves coverage of testing via
  8446. // fault injection.
  8447. // create and push the try-catch node
  8448. pParentTryCatchBlock = CreateBlockNode();
  8449. PushStmt<buildAST>(&stmtTryCatchBlock, pParentTryCatchBlock, knopBlock, nullptr, nullptr);
  8450. pParentTryCatch = CreateNodeWithScanner<knopTryCatch>();
  8451. PushStmt<buildAST>(&stmtTryCatch, pParentTryCatch, knopTryCatch, nullptr, nullptr);
  8452. // create and push a try node
  8453. pTry = CreateNodeWithScanner<knopTry>();
  8454. PushStmt<buildAST>(&stmtTry, pTry, knopTry, nullptr, nullptr);
  8455. pTryBlock = CreateBlockNode();
  8456. PushStmt<buildAST>(&stmtTryBlock, pTryBlock, knopBlock, nullptr, nullptr);
  8457. // these nodes will be closed after the statement is parsed.
  8458. }
  8459. #endif // EXCEPTION_RECOVERY
  8460. }
  8461. EnsureStackAvailable();
  8462. LRestart:
  8463. tok = m_token.tk;
  8464. switch (tok)
  8465. {
  8466. case tkEOF:
  8467. if (buildAST)
  8468. {
  8469. pnode = nullptr;
  8470. }
  8471. break;
  8472. case tkFUNCTION:
  8473. {
  8474. LFunctionStatement:
  8475. if (m_grfscr & fscrDeferredFncExpression)
  8476. {
  8477. // The top-level deferred function body was defined by a function expression whose parsing was deferred. We are now
  8478. // parsing it, so unset the flag so that any nested functions are parsed normally. This flag is only applicable the
  8479. // first time we see it.
  8480. m_grfscr &= ~fscrDeferredFncExpression;
  8481. pnode = ParseFncDecl<buildAST>(isAsyncMethod ? fFncAsync : fFncNoFlgs, nullptr);
  8482. }
  8483. else
  8484. {
  8485. pnode = ParseFncDecl<buildAST>(fFncDeclaration | (isAsyncMethod ? fFncAsync : fFncNoFlgs), nullptr);
  8486. }
  8487. if (isAsyncMethod)
  8488. {
  8489. pnode->sxFnc.cbMin = iecpMin;
  8490. pnode->ichMin = ichMin;
  8491. }
  8492. break;
  8493. }
  8494. case tkCLASS:
  8495. if (m_scriptContext->GetConfig()->IsES6ClassAndExtendsEnabled())
  8496. {
  8497. pnode = ParseClassDecl<buildAST>(TRUE, nullptr, nullptr, nullptr);
  8498. }
  8499. else
  8500. {
  8501. goto LDefaultToken;
  8502. }
  8503. break;
  8504. case tkID:
  8505. if (m_token.GetIdentifier(m_phtbl) == wellKnownPropertyPids.let)
  8506. {
  8507. // We see "let" at the start of a statement. This could either be a declaration or an identifier
  8508. // reference. The next token determines which.
  8509. RestorePoint parsedLet;
  8510. m_pscan->Capture(&parsedLet);
  8511. ichMin = m_pscan->IchMinTok();
  8512. m_pscan->Scan();
  8513. if (this->NextTokenConfirmsLetDecl())
  8514. {
  8515. pnode = ParseVariableDeclaration<buildAST>(tkLET, ichMin);
  8516. goto LNeedTerminator;
  8517. }
  8518. m_pscan->SeekTo(parsedLet);
  8519. }
  8520. else if (m_token.GetIdentifier(m_phtbl) == wellKnownPropertyPids.async && m_scriptContext->GetConfig()->IsES7AsyncAndAwaitEnabled())
  8521. {
  8522. RestorePoint parsedAsync;
  8523. m_pscan->Capture(&parsedAsync);
  8524. ichMin = m_pscan->IchMinTok();
  8525. iecpMin = m_pscan->IecpMinTok();
  8526. m_pscan->Scan();
  8527. if (m_token.tk == tkFUNCTION && !m_pscan->FHadNewLine())
  8528. {
  8529. isAsyncMethod = true;
  8530. goto LFunctionStatement;
  8531. }
  8532. m_pscan->SeekTo(parsedAsync);
  8533. }
  8534. goto LDefaultToken;
  8535. case tkCONST:
  8536. case tkLET:
  8537. ichMin = m_pscan->IchMinTok();
  8538. m_pscan->Scan();
  8539. pnode = ParseVariableDeclaration<buildAST>(tok, ichMin);
  8540. goto LNeedTerminator;
  8541. case tkVAR:
  8542. ichMin = m_pscan->IchMinTok();
  8543. m_pscan->Scan();
  8544. pnode = ParseVariableDeclaration<buildAST>(tok, ichMin);
  8545. goto LNeedTerminator;
  8546. case tkFOR:
  8547. {
  8548. ParseNodePtr pnodeBlock = nullptr;
  8549. ParseNodePtr *ppnodeScopeSave = nullptr;
  8550. ParseNodePtr *ppnodeExprScopeSave = nullptr;
  8551. ichMin = m_pscan->IchMinTok();
  8552. ChkNxtTok(tkLParen, ERRnoLparen);
  8553. pnodeBlock = StartParseBlock<buildAST>(PnodeBlockType::Regular, ScopeType_Block);
  8554. if (buildAST)
  8555. {
  8556. PushFuncBlockScope(pnodeBlock, &ppnodeScopeSave, &ppnodeExprScopeSave);
  8557. }
  8558. RestorePoint startExprOrIdentifier;
  8559. fForInOrOfOkay = TRUE;
  8560. fCanAssign = TRUE;
  8561. tok = m_token.tk;
  8562. BOOL nativeForOkay = TRUE;
  8563. switch (tok)
  8564. {
  8565. case tkID:
  8566. if (m_token.GetIdentifier(m_phtbl) == wellKnownPropertyPids.let)
  8567. {
  8568. // We see "let" in the init part of a for loop. This could either be a declaration or an identifier
  8569. // reference. The next token determines which.
  8570. RestorePoint parsedLet;
  8571. m_pscan->Capture(&parsedLet);
  8572. auto ichMinInner = m_pscan->IchMinTok();
  8573. m_pscan->Scan();
  8574. if (IsPossiblePatternStart())
  8575. {
  8576. m_pscan->Capture(&startExprOrIdentifier);
  8577. }
  8578. if (this->NextTokenConfirmsLetDecl() && m_token.tk != tkIN)
  8579. {
  8580. pnodeT = ParseVariableDeclaration<buildAST>(tkLET, ichMinInner
  8581. , /*fAllowIn = */FALSE
  8582. , /*pfForInOk = */&fForInOrOfOkay
  8583. , /*singleDefOnly*/FALSE
  8584. , /*allowInit*/TRUE
  8585. , /*isTopVarParse*/TRUE
  8586. , /*isFor*/TRUE
  8587. , &nativeForOkay);
  8588. break;
  8589. }
  8590. m_pscan->SeekTo(parsedLet);
  8591. }
  8592. goto LDefaultTokenFor;
  8593. case tkLET:
  8594. case tkCONST:
  8595. case tkVAR:
  8596. {
  8597. auto ichMinInner = m_pscan->IchMinTok();
  8598. m_pscan->Scan();
  8599. if (IsPossiblePatternStart())
  8600. {
  8601. m_pscan->Capture(&startExprOrIdentifier);
  8602. }
  8603. pnodeT = ParseVariableDeclaration<buildAST>(tok, ichMinInner
  8604. , /*fAllowIn = */FALSE
  8605. , /*pfForInOk = */&fForInOrOfOkay
  8606. , /*singleDefOnly*/FALSE
  8607. , /*allowInit*/TRUE
  8608. , /*isTopVarParse*/TRUE
  8609. , /*isFor*/TRUE
  8610. , &nativeForOkay);
  8611. }
  8612. break;
  8613. case tkSColon:
  8614. pnodeT = nullptr;
  8615. fForInOrOfOkay = FALSE;
  8616. break;
  8617. default:
  8618. {
  8619. LDefaultTokenFor:
  8620. RestorePoint exprStart;
  8621. tokens beforeToken = tok;
  8622. m_pscan->Capture(&exprStart);
  8623. if (IsPossiblePatternStart())
  8624. {
  8625. m_pscan->Capture(&startExprOrIdentifier);
  8626. }
  8627. bool fLikelyPattern = false;
  8628. if (IsES6DestructuringEnabled() && (beforeToken == tkLBrack || beforeToken == tkLCurly))
  8629. {
  8630. pnodeT = ParseExpr<buildAST>(koplNo,
  8631. &fCanAssign,
  8632. /*fAllowIn = */FALSE,
  8633. /*fAllowEllipsis*/FALSE,
  8634. /*pHint*/nullptr,
  8635. /*pHintLength*/nullptr,
  8636. /*pShortNameOffset*/nullptr,
  8637. /*pToken*/nullptr,
  8638. /**fUnaryOrParen*/false,
  8639. &fLikelyPattern);
  8640. }
  8641. else
  8642. {
  8643. pnodeT = ParseExpr<buildAST>(koplNo, &fCanAssign, /*fAllowIn = */FALSE);
  8644. }
  8645. // 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
  8646. // has already converted them appropriately.
  8647. if (fLikelyPattern && TokIsForInOrForOf())
  8648. {
  8649. m_pscan->SeekTo(exprStart);
  8650. ParseDestructuredLiteralWithScopeSave(tkNone, false/*isDecl*/, false /*topLevel*/, DIC_None, false /*allowIn*/);
  8651. if (buildAST)
  8652. {
  8653. pnodeT = ConvertToPattern(pnodeT);
  8654. }
  8655. }
  8656. if (buildAST)
  8657. {
  8658. Assert(pnodeT);
  8659. pnodeT->isUsed = false;
  8660. }
  8661. }
  8662. break;
  8663. }
  8664. if (TokIsForInOrForOf())
  8665. {
  8666. bool isForOf = (m_token.tk != tkIN);
  8667. Assert(!isForOf || (m_token.tk == tkID && m_token.GetIdentifier(m_phtbl) == wellKnownPropertyPids.of));
  8668. if ((buildAST && nullptr == pnodeT) || !fForInOrOfOkay)
  8669. {
  8670. if (isForOf)
  8671. {
  8672. Error(ERRForOfNoInitAllowed);
  8673. }
  8674. else
  8675. {
  8676. Error(ERRForInNoInitAllowed);
  8677. }
  8678. }
  8679. if (!fCanAssign && PHASE_ON1(Js::EarlyReferenceErrorsPhase))
  8680. {
  8681. Error(JSERR_CantAssignTo);
  8682. }
  8683. m_pscan->Scan();
  8684. ParseNodePtr pnodeObj = ParseExpr<buildAST>(isForOf ? koplCma : koplNo);
  8685. charcount_t ichLim = m_pscan->IchLimTok();
  8686. ChkCurTok(tkRParen, ERRnoRparen);
  8687. if (buildAST)
  8688. {
  8689. if (isForOf)
  8690. {
  8691. pnode = CreateNodeWithScanner<knopForOf>(ichMin);
  8692. }
  8693. else
  8694. {
  8695. pnode = CreateNodeWithScanner<knopForIn>(ichMin);
  8696. }
  8697. pnode->sxForInOrForOf.pnodeBlock = pnodeBlock;
  8698. pnode->sxForInOrForOf.pnodeLval = pnodeT;
  8699. pnode->sxForInOrForOf.pnodeObj = pnodeObj;
  8700. pnode->ichLim = ichLim;
  8701. TrackAssignment<true>(pnodeT, nullptr);
  8702. }
  8703. PushStmt<buildAST>(&stmt, pnode, isForOf ? knopForOf : knopForIn, pnodeLabel, pLabelIdList);
  8704. ParseNodePtr pnodeBody = ParseStatement<buildAST>();
  8705. if (buildAST)
  8706. {
  8707. pnode->sxForInOrForOf.pnodeBody = pnodeBody;
  8708. }
  8709. PopStmt(&stmt);
  8710. }
  8711. else
  8712. {
  8713. if (!nativeForOkay)
  8714. {
  8715. Error(ERRDestructInit);
  8716. }
  8717. ChkCurTok(tkSColon, ERRnoSemic);
  8718. ParseNodePtr pnodeCond = nullptr;
  8719. if (m_token.tk != tkSColon)
  8720. {
  8721. pnodeCond = ParseExpr<buildAST>();
  8722. if (m_token.tk != tkSColon)
  8723. {
  8724. Error(ERRnoSemic);
  8725. }
  8726. }
  8727. tokens tk;
  8728. tk = m_pscan->Scan();
  8729. ParseNodePtr pnodeIncr = nullptr;
  8730. if (tk != tkRParen)
  8731. {
  8732. pnodeIncr = ParseExpr<buildAST>();
  8733. if(pnodeIncr)
  8734. {
  8735. pnodeIncr->isUsed = false;
  8736. }
  8737. }
  8738. charcount_t ichLim = m_pscan->IchLimTok();
  8739. ChkCurTok(tkRParen, ERRnoRparen);
  8740. if (buildAST)
  8741. {
  8742. pnode = CreateNodeWithScanner<knopFor>(ichMin);
  8743. pnode->sxFor.pnodeBlock = pnodeBlock;
  8744. pnode->sxFor.pnodeInverted= nullptr;
  8745. pnode->sxFor.pnodeInit = pnodeT;
  8746. pnode->sxFor.pnodeCond = pnodeCond;
  8747. pnode->sxFor.pnodeIncr = pnodeIncr;
  8748. pnode->ichLim = ichLim;
  8749. }
  8750. PushStmt<buildAST>(&stmt, pnode, knopFor, pnodeLabel, pLabelIdList);
  8751. ParseNodePtr pnodeBody = ParseStatement<buildAST>();
  8752. if (buildAST)
  8753. {
  8754. pnode->sxFor.pnodeBody = pnodeBody;
  8755. }
  8756. PopStmt(&stmt);
  8757. }
  8758. if (buildAST)
  8759. {
  8760. PopFuncBlockScope(ppnodeScopeSave, ppnodeExprScopeSave);
  8761. }
  8762. FinishParseBlock(pnodeBlock);
  8763. break;
  8764. }
  8765. case tkSWITCH:
  8766. {
  8767. BOOL fSeenDefault = FALSE;
  8768. ParseNodePtr pnodeBlock = nullptr;
  8769. ParseNodePtr *ppnodeScopeSave = nullptr;
  8770. ParseNodePtr *ppnodeExprScopeSave = nullptr;
  8771. ichMin = m_pscan->IchMinTok();
  8772. ChkNxtTok(tkLParen, ERRnoLparen);
  8773. ParseNodePtr pnodeVal = ParseExpr<buildAST>();
  8774. charcount_t ichLim = m_pscan->IchLimTok();
  8775. ChkCurTok(tkRParen, ERRnoRparen);
  8776. ChkCurTok(tkLCurly, ERRnoLcurly);
  8777. if (buildAST)
  8778. {
  8779. pnode = CreateNodeWithScanner<knopSwitch>(ichMin);
  8780. }
  8781. PushStmt<buildAST>(&stmt, pnode, knopSwitch, pnodeLabel, pLabelIdList);
  8782. pnodeBlock = StartParseBlock<buildAST>(PnodeBlockType::Regular, ScopeType_Block, nullptr, pLabelIdList);
  8783. if (buildAST)
  8784. {
  8785. pnode->sxSwitch.pnodeVal = pnodeVal;
  8786. pnode->sxSwitch.pnodeBlock = pnodeBlock;
  8787. pnode->ichLim = ichLim;
  8788. PushFuncBlockScope(pnode->sxSwitch.pnodeBlock, &ppnodeScopeSave, &ppnodeExprScopeSave);
  8789. pnode->sxSwitch.pnodeDefault = nullptr;
  8790. ppnodeT = &pnode->sxSwitch.pnodeCases;
  8791. }
  8792. for (;;)
  8793. {
  8794. ParseNodePtr pnodeBody = nullptr;
  8795. switch (m_token.tk)
  8796. {
  8797. default:
  8798. goto LEndSwitch;
  8799. case tkCASE:
  8800. {
  8801. pnodeT = this->ParseCase<buildAST>(&pnodeBody);
  8802. break;
  8803. }
  8804. case tkDEFAULT:
  8805. if (fSeenDefault)
  8806. {
  8807. Error(ERRdupDefault);
  8808. // No recovery necessary since this is a semantic, not structural, error
  8809. }
  8810. fSeenDefault = TRUE;
  8811. charcount_t ichMinT = m_pscan->IchMinTok();
  8812. m_pscan->Scan();
  8813. charcount_t ichMinInner = m_pscan->IchLimTok();
  8814. ChkCurTok(tkColon, ERRnoColon);
  8815. if (buildAST)
  8816. {
  8817. pnodeT = CreateNodeWithScanner<knopCase>(ichMinT);
  8818. pnode->sxSwitch.pnodeDefault = pnodeT;
  8819. pnodeT->ichLim = ichMinInner;
  8820. pnodeT->sxCase.pnodeExpr = nullptr;
  8821. }
  8822. ParseStmtList<buildAST>(&pnodeBody);
  8823. break;
  8824. }
  8825. // Create a block node to contain the statement list for this case.
  8826. // This helps us insert byte code to return the right value from
  8827. // global/eval code.
  8828. ParseNodePtr pnodeFakeBlock = CreateBlockNode();
  8829. if (buildAST)
  8830. {
  8831. if (pnodeBody)
  8832. {
  8833. pnodeFakeBlock->ichMin = pnodeT->ichMin;
  8834. pnodeFakeBlock->ichLim = pnodeT->ichLim;
  8835. pnodeT->sxCase.pnodeBody = pnodeFakeBlock;
  8836. pnodeT->sxCase.pnodeBody->grfpn |= PNodeFlags::fpnSyntheticNode; // block is not a user specifier block
  8837. pnodeT->sxCase.pnodeBody->sxBlock.pnodeStmt = pnodeBody;
  8838. }
  8839. else
  8840. {
  8841. pnodeT->sxCase.pnodeBody = nullptr;
  8842. }
  8843. *ppnodeT = pnodeT;
  8844. ppnodeT = &pnodeT->sxCase.pnodeNext;
  8845. }
  8846. }
  8847. LEndSwitch:
  8848. ChkCurTok(tkRCurly, ERRnoRcurly);
  8849. if (buildAST)
  8850. {
  8851. *ppnodeT = nullptr;
  8852. PopFuncBlockScope(ppnodeScopeSave, ppnodeExprScopeSave);
  8853. FinishParseBlock(pnode->sxSwitch.pnodeBlock);
  8854. }
  8855. else
  8856. {
  8857. FinishParseBlock(pnodeBlock);
  8858. }
  8859. PopStmt(&stmt);
  8860. break;
  8861. }
  8862. case tkWHILE:
  8863. {
  8864. ichMin = m_pscan->IchMinTok();
  8865. ChkNxtTok(tkLParen, ERRnoLparen);
  8866. ParseNodePtr pnodeCond = ParseExpr<buildAST>();
  8867. charcount_t ichLim = m_pscan->IchLimTok();
  8868. ChkCurTok(tkRParen, ERRnoRparen);
  8869. if (buildAST)
  8870. {
  8871. pnode = CreateNodeWithScanner<knopWhile>(ichMin);
  8872. pnode->sxWhile.pnodeCond = pnodeCond;
  8873. pnode->ichLim = ichLim;
  8874. }
  8875. bool stashedDisallowImportExportStmt = m_disallowImportExportStmt;
  8876. m_disallowImportExportStmt = true;
  8877. PushStmt<buildAST>(&stmt, pnode, knopWhile, pnodeLabel, pLabelIdList);
  8878. ParseNodePtr pnodeBody = ParseStatement<buildAST>();
  8879. PopStmt(&stmt);
  8880. if (buildAST)
  8881. {
  8882. pnode->sxWhile.pnodeBody = pnodeBody;
  8883. }
  8884. m_disallowImportExportStmt = stashedDisallowImportExportStmt;
  8885. break;
  8886. }
  8887. case tkDO:
  8888. {
  8889. if (buildAST)
  8890. {
  8891. pnode = CreateNodeWithScanner<knopDoWhile>();
  8892. }
  8893. PushStmt<buildAST>(&stmt, pnode, knopDoWhile, pnodeLabel, pLabelIdList);
  8894. m_pscan->Scan();
  8895. bool stashedDisallowImportExportStmt = m_disallowImportExportStmt;
  8896. m_disallowImportExportStmt = true;
  8897. ParseNodePtr pnodeBody = ParseStatement<buildAST>();
  8898. m_disallowImportExportStmt = stashedDisallowImportExportStmt;
  8899. PopStmt(&stmt);
  8900. charcount_t ichMinT = m_pscan->IchMinTok();
  8901. ChkCurTok(tkWHILE, ERRnoWhile);
  8902. ChkCurTok(tkLParen, ERRnoLparen);
  8903. ParseNodePtr pnodeCond = ParseExpr<buildAST>();
  8904. charcount_t ichLim = m_pscan->IchLimTok();
  8905. ChkCurTok(tkRParen, ERRnoRparen);
  8906. if (buildAST)
  8907. {
  8908. pnode->sxWhile.pnodeBody = pnodeBody;
  8909. pnode->sxWhile.pnodeCond = pnodeCond;
  8910. pnode->ichLim = ichLim;
  8911. pnode->ichMin = ichMinT;
  8912. }
  8913. // REVIEW: Allow do...while statements to be embedded in other compound statements like if..else, or do..while?
  8914. // goto LNeedTerminator;
  8915. // For now just eat the trailing semicolon if present.
  8916. if (m_token.tk == tkSColon)
  8917. {
  8918. if (pnode)
  8919. {
  8920. pnode->grfpn |= PNodeFlags::fpnExplicitSemicolon;
  8921. }
  8922. m_pscan->Scan();
  8923. }
  8924. else if (pnode)
  8925. {
  8926. pnode->grfpn |= PNodeFlags::fpnAutomaticSemicolon;
  8927. }
  8928. break;
  8929. }
  8930. case tkIF:
  8931. {
  8932. ichMin = m_pscan->IchMinTok();
  8933. ChkNxtTok(tkLParen, ERRnoLparen);
  8934. ParseNodePtr pnodeCond = ParseExpr<buildAST>();
  8935. if (buildAST)
  8936. {
  8937. pnode = CreateNodeWithScanner<knopIf>(ichMin);
  8938. pnode->ichLim = m_pscan->IchLimTok();
  8939. pnode->sxIf.pnodeCond = pnodeCond;
  8940. }
  8941. ChkCurTok(tkRParen, ERRnoRparen);
  8942. bool stashedDisallowImportExportStmt = m_disallowImportExportStmt;
  8943. m_disallowImportExportStmt = true;
  8944. PushStmt<buildAST>(&stmt, pnode, knopIf, pnodeLabel, pLabelIdList);
  8945. ParseNodePtr pnodeTrue = ParseStatement<buildAST>();
  8946. ParseNodePtr pnodeFalse = nullptr;
  8947. if (m_token.tk == tkELSE)
  8948. {
  8949. m_pscan->Scan();
  8950. pnodeFalse = ParseStatement<buildAST>();
  8951. }
  8952. if (buildAST)
  8953. {
  8954. pnode->sxIf.pnodeTrue = pnodeTrue;
  8955. pnode->sxIf.pnodeFalse = pnodeFalse;
  8956. }
  8957. PopStmt(&stmt);
  8958. m_disallowImportExportStmt = stashedDisallowImportExportStmt;
  8959. break;
  8960. }
  8961. case tkTRY:
  8962. {
  8963. pnode = CreateBlockNode();
  8964. pnode->grfpn |= PNodeFlags::fpnSyntheticNode; // block is not a user specifier block
  8965. PushStmt<buildAST>(&stmt, pnode, knopBlock, pnodeLabel, pLabelIdList);
  8966. ParseNodePtr pnodeStmt = ParseTryCatchFinally<buildAST>();
  8967. if (buildAST)
  8968. {
  8969. pnode->sxBlock.pnodeStmt = pnodeStmt;
  8970. }
  8971. PopStmt(&stmt);
  8972. break;
  8973. }
  8974. case tkWITH:
  8975. {
  8976. if ( IsStrictMode() )
  8977. {
  8978. Error(ERRES5NoWith);
  8979. }
  8980. if (m_currentNodeFunc)
  8981. {
  8982. GetCurrentFunctionNode()->sxFnc.SetHasWithStmt(); // Used by DeferNested
  8983. }
  8984. ichMin = m_pscan->IchMinTok();
  8985. ChkNxtTok(tkLParen, ERRnoLparen);
  8986. ParseNodePtr pnodeObj = ParseExpr<buildAST>();
  8987. if (!buildAST)
  8988. {
  8989. m_scopeCountNoAst++;
  8990. }
  8991. charcount_t ichLim = m_pscan->IchLimTok();
  8992. ChkCurTok(tkRParen, ERRnoRparen);
  8993. if (buildAST)
  8994. {
  8995. pnode = CreateNodeWithScanner<knopWith>(ichMin);
  8996. }
  8997. PushStmt<buildAST>(&stmt, pnode, knopWith, pnodeLabel, pLabelIdList);
  8998. ParseNodePtr *ppnodeExprScopeSave = nullptr;
  8999. if (buildAST)
  9000. {
  9001. pnode->sxWith.pnodeObj = pnodeObj;
  9002. this->CheckArguments(pnode->sxWith.pnodeObj);
  9003. if (m_ppnodeExprScope)
  9004. {
  9005. Assert(*m_ppnodeExprScope == nullptr);
  9006. *m_ppnodeExprScope = pnode;
  9007. m_ppnodeExprScope = &pnode->sxWith.pnodeNext;
  9008. }
  9009. else
  9010. {
  9011. Assert(m_ppnodeScope);
  9012. Assert(*m_ppnodeScope == nullptr);
  9013. *m_ppnodeScope = pnode;
  9014. m_ppnodeScope = &pnode->sxWith.pnodeNext;
  9015. }
  9016. pnode->sxWith.pnodeNext = nullptr;
  9017. pnode->sxWith.scope = nullptr;
  9018. ppnodeExprScopeSave = m_ppnodeExprScope;
  9019. m_ppnodeExprScope = &pnode->sxWith.pnodeScopes;
  9020. pnode->sxWith.pnodeScopes = nullptr;
  9021. pnode->ichLim = ichLim;
  9022. }
  9023. PushBlockInfo(CreateBlockNode());
  9024. PushDynamicBlock();
  9025. ParseNodePtr pnodeBody = ParseStatement<buildAST>();
  9026. if (buildAST)
  9027. {
  9028. pnode->sxWith.pnodeBody = pnodeBody;
  9029. m_ppnodeExprScope = ppnodeExprScopeSave;
  9030. }
  9031. else
  9032. {
  9033. m_scopeCountNoAst--;
  9034. }
  9035. // The dynamic block is not stored in the actual parse tree and so will not
  9036. // be visited by the byte code generator. Grab the callsEval flag off it and
  9037. // pass on to outer block in case of:
  9038. // with (...) eval(...); // i.e. blockless form of with
  9039. bool callsEval = GetCurrentBlock()->sxBlock.GetCallsEval();
  9040. PopBlockInfo();
  9041. if (callsEval)
  9042. {
  9043. // be careful not to overwrite an existing true with false
  9044. GetCurrentBlock()->sxBlock.SetCallsEval(true);
  9045. }
  9046. PopStmt(&stmt);
  9047. break;
  9048. }
  9049. case tkLCurly:
  9050. pnode = ParseBlock<buildAST>(pnodeLabel, pLabelIdList);
  9051. break;
  9052. case tkSColon:
  9053. pnode = nullptr;
  9054. m_pscan->Scan();
  9055. break;
  9056. case tkBREAK:
  9057. if (buildAST)
  9058. {
  9059. pnode = CreateNodeWithScanner<knopBreak>();
  9060. }
  9061. fnop = fnopBreak;
  9062. goto LGetJumpStatement;
  9063. case tkCONTINUE:
  9064. if (buildAST)
  9065. {
  9066. pnode = CreateNode(knopContinue);
  9067. }
  9068. fnop = fnopContinue;
  9069. LGetJumpStatement:
  9070. m_pscan->ScanForcingPid();
  9071. if (tkID == m_token.tk && !m_pscan->FHadNewLine())
  9072. {
  9073. // Labeled break or continue.
  9074. pid = m_token.GetIdentifier(m_phtbl);
  9075. AssertMem(pid);
  9076. if (buildAST)
  9077. {
  9078. pnode->sxJump.hasExplicitTarget=true;
  9079. pnode->ichLim = m_pscan->IchLimTok();
  9080. m_pscan->Scan();
  9081. PushStmt<buildAST>(&stmt, pnode, pnode->nop, pnodeLabel, nullptr);
  9082. Assert(pnode->sxStmt.grfnop == 0);
  9083. for (pstmt = m_pstmtCur; nullptr != pstmt; pstmt = pstmt->pstmtOuter)
  9084. {
  9085. AssertNodeMem(pstmt->pnodeStmt);
  9086. AssertNodeMemN(pstmt->pnodeLab);
  9087. for (pnodeT = pstmt->pnodeLab; nullptr != pnodeT;
  9088. pnodeT = pnodeT->sxLabel.pnodeNext)
  9089. {
  9090. Assert(knopLabel == pnodeT->nop);
  9091. if (pid == pnodeT->sxLabel.pid)
  9092. {
  9093. // Found the label. Make sure we can use it. We can
  9094. // break out of any statement, but we can only
  9095. // continue loops.
  9096. if (fnop == fnopContinue &&
  9097. !(pstmt->pnodeStmt->Grfnop() & fnop))
  9098. {
  9099. Error(ERRbadContinue);
  9100. }
  9101. else
  9102. {
  9103. pstmt->pnodeStmt->sxStmt.grfnop |= fnop;
  9104. pnode->sxJump.pnodeTarget = pstmt->pnodeStmt;
  9105. }
  9106. PopStmt(&stmt);
  9107. goto LNeedTerminator;
  9108. }
  9109. }
  9110. pnode->sxStmt.grfnop |=
  9111. (pstmt->pnodeStmt->Grfnop() & fnopCleanup);
  9112. }
  9113. }
  9114. else
  9115. {
  9116. m_pscan->Scan();
  9117. for (pstmt = m_pstmtCur; pstmt; pstmt = pstmt->pstmtOuter)
  9118. {
  9119. LabelId* pLabelId;
  9120. for (pLabelId = pstmt->pLabelId; pLabelId; pLabelId = pLabelId->next)
  9121. {
  9122. if (pid == pLabelId->pid)
  9123. {
  9124. // Found the label. Make sure we can use it. We can
  9125. // break out of any statement, but we can only
  9126. // continue loops.
  9127. if (fnop == fnopContinue &&
  9128. !(ParseNode::Grfnop(pstmt->op) & fnop))
  9129. {
  9130. Error(ERRbadContinue);
  9131. }
  9132. goto LNeedTerminator;
  9133. }
  9134. }
  9135. }
  9136. }
  9137. Error(ERRnoLabel);
  9138. }
  9139. else
  9140. {
  9141. // If we're doing a fast scan, we're not tracking labels, so we can't accurately do this analysis.
  9142. // Let the thread that's doing the full parse detect the error, if there is one.
  9143. if (!this->IsDoingFastScan())
  9144. {
  9145. // Unlabeled break or continue.
  9146. if (buildAST)
  9147. {
  9148. pnode->sxJump.hasExplicitTarget=false;
  9149. PushStmt<buildAST>(&stmt, pnode, pnode->nop, pnodeLabel, nullptr);
  9150. Assert(pnode->sxStmt.grfnop == 0);
  9151. }
  9152. for (pstmt = m_pstmtCur; nullptr != pstmt; pstmt = pstmt->pstmtOuter)
  9153. {
  9154. if (buildAST)
  9155. {
  9156. AnalysisAssert(pstmt->pnodeStmt);
  9157. if (pstmt->pnodeStmt->Grfnop() & fnop)
  9158. {
  9159. pstmt->pnodeStmt->sxStmt.grfnop |= fnop;
  9160. pnode->sxJump.pnodeTarget = pstmt->pnodeStmt;
  9161. PopStmt(&stmt);
  9162. goto LNeedTerminator;
  9163. }
  9164. pnode->sxStmt.grfnop |=
  9165. (pstmt->pnodeStmt->Grfnop() & fnopCleanup);
  9166. }
  9167. else
  9168. {
  9169. if (ParseNode::Grfnop(pstmt->GetNop()) & fnop)
  9170. {
  9171. if (!pstmt->isDeferred)
  9172. {
  9173. AnalysisAssert(pstmt->pnodeStmt);
  9174. pstmt->pnodeStmt->sxStmt.grfnop |= fnop;
  9175. }
  9176. goto LNeedTerminator;
  9177. }
  9178. }
  9179. }
  9180. Error(fnop == fnopBreak ? ERRbadBreak : ERRbadContinue);
  9181. }
  9182. goto LNeedTerminator;
  9183. }
  9184. case tkRETURN:
  9185. {
  9186. if (buildAST)
  9187. {
  9188. if (nullptr == m_currentNodeFunc || IsTopLevelModuleFunc())
  9189. {
  9190. Error(ERRbadReturn);
  9191. }
  9192. pnode = CreateNodeWithScanner<knopReturn>();
  9193. }
  9194. m_pscan->Scan();
  9195. ParseNodePtr pnodeExpr = nullptr;
  9196. ParseOptionalExpr<buildAST>(&pnodeExpr, true);
  9197. // Class constructors have special semantics regarding return statements.
  9198. // This might require a reference to 'this'
  9199. if (GetCurrentFunctionNode()->sxFnc.IsClassConstructor())
  9200. {
  9201. ReferenceSpecialName(wellKnownPropertyPids._this);
  9202. }
  9203. if (buildAST)
  9204. {
  9205. pnode->sxReturn.pnodeExpr = pnodeExpr;
  9206. if (pnodeExpr)
  9207. {
  9208. this->CheckArguments(pnode->sxReturn.pnodeExpr);
  9209. pnode->ichLim = pnode->sxReturn.pnodeExpr->ichLim;
  9210. }
  9211. // See if return should call finally
  9212. PushStmt<buildAST>(&stmt, pnode, knopReturn, pnodeLabel, nullptr);
  9213. Assert(pnode->sxStmt.grfnop == 0);
  9214. for (pstmt = m_pstmtCur; nullptr != pstmt; pstmt = pstmt->pstmtOuter)
  9215. {
  9216. AssertNodeMem(pstmt->pnodeStmt);
  9217. AssertNodeMemN(pstmt->pnodeLab);
  9218. if (pstmt->pnodeStmt->Grfnop() & fnopCleanup)
  9219. {
  9220. pnode->sxStmt.grfnop |= fnopCleanup;
  9221. break;
  9222. }
  9223. }
  9224. PopStmt(&stmt);
  9225. }
  9226. goto LNeedTerminator;
  9227. }
  9228. case tkTHROW:
  9229. {
  9230. if (buildAST)
  9231. {
  9232. pnode = CreateUniNode(knopThrow, nullptr);
  9233. }
  9234. m_pscan->Scan();
  9235. ParseNodePtr pnode1 = nullptr;
  9236. if (m_token.tk != tkSColon &&
  9237. m_token.tk != tkRCurly &&
  9238. !m_pscan->FHadNewLine())
  9239. {
  9240. pnode1 = ParseExpr<buildAST>();
  9241. }
  9242. else
  9243. {
  9244. Error(ERRdanglingThrow);
  9245. }
  9246. if (buildAST)
  9247. {
  9248. pnode->sxUni.pnode1 = pnode1;
  9249. if (pnode1)
  9250. {
  9251. this->CheckArguments(pnode->sxUni.pnode1);
  9252. pnode->ichLim = pnode->sxUni.pnode1->ichLim;
  9253. }
  9254. }
  9255. goto LNeedTerminator;
  9256. }
  9257. case tkDEBUGGER:
  9258. if (buildAST)
  9259. {
  9260. pnode = CreateNodeWithScanner<knopDebugger>();
  9261. }
  9262. m_pscan->Scan();
  9263. goto LNeedTerminator;
  9264. case tkIMPORT:
  9265. pnode = ParseImport<buildAST>();
  9266. goto LNeedTerminator;
  9267. case tkEXPORT:
  9268. {
  9269. if (!(m_grfscr & fscrIsModuleCode))
  9270. {
  9271. goto LDefaultToken;
  9272. }
  9273. bool needTerminator = false;
  9274. pnode = ParseExportDeclaration<buildAST>(&needTerminator);
  9275. if (needTerminator)
  9276. {
  9277. goto LNeedTerminator;
  9278. }
  9279. else
  9280. {
  9281. break;
  9282. }
  9283. }
  9284. LDefaultToken:
  9285. default:
  9286. {
  9287. // First check for a label via lookahead. If not found,
  9288. // rewind and reparse as expression statement.
  9289. if (m_token.tk == tkLParen || m_token.tk == tkID)
  9290. {
  9291. RestorePoint idStart;
  9292. m_pscan->Capture(&idStart);
  9293. // Support legacy behavior of allowing parentheses around label identifiers.
  9294. // Require balanced parentheses for correcting parsing. Note unbalanced cases
  9295. // take care of themselves correctly by resulting in rewind and parsing as
  9296. // an expression statement.
  9297. // REVIEW[ianhall]: Can this legacy functionality be removed? Chrome does not support this parsing behavior.
  9298. uint parenCount = 0;
  9299. while (m_token.tk == tkLParen)
  9300. {
  9301. parenCount += 1;
  9302. m_pscan->Scan();
  9303. }
  9304. if (m_token.tk == tkID)
  9305. {
  9306. IdentToken tokInner;
  9307. tokInner.tk = tkID;
  9308. tokInner.ichMin = m_pscan->IchMinTok();
  9309. tokInner.ichLim = m_pscan->IchLimTok();
  9310. tokInner.pid = m_token.GetIdentifier(m_phtbl);
  9311. m_pscan->Scan();
  9312. while (parenCount > 0 && m_token.tk == tkRParen)
  9313. {
  9314. parenCount -= 1;
  9315. m_pscan->Scan();
  9316. }
  9317. if (parenCount == 0 && m_token.tk == tkColon)
  9318. {
  9319. // We have a label.
  9320. // TODO[ianhall]: Refactor to eliminate separate code paths for buildAST and !buildAST
  9321. if (buildAST)
  9322. {
  9323. // See if the label is already defined.
  9324. if (nullptr != PnodeLabel(tokInner.pid, pnodeLabel))
  9325. {
  9326. Error(ERRbadLabel);
  9327. }
  9328. pnodeT = CreateNodeWithScanner<knopLabel>();
  9329. pnodeT->sxLabel.pid = tokInner.pid;
  9330. pnodeT->sxLabel.pnodeNext = pnodeLabel;
  9331. pnodeLabel = pnodeT;
  9332. }
  9333. else
  9334. {
  9335. // See if the label is already defined.
  9336. if (PnodeLabelNoAST(&tokInner, pLabelIdList))
  9337. {
  9338. Error(ERRbadLabel);
  9339. }
  9340. LabelId* pLabelId = CreateLabelId(&tokInner);
  9341. pLabelId->next = pLabelIdList;
  9342. pLabelIdList = pLabelId;
  9343. }
  9344. m_pscan->Scan();
  9345. goto LRestart;
  9346. }
  9347. }
  9348. // No label, rewind back to the tkID and parse an expression
  9349. m_pscan->SeekTo(idStart);
  9350. }
  9351. // Must be an expression statement.
  9352. pnode = ParseExpr<buildAST>();
  9353. if (m_hasDeferredShorthandInitError)
  9354. {
  9355. Error(ERRnoColon);
  9356. }
  9357. if (buildAST)
  9358. {
  9359. expressionStmt = true;
  9360. AnalysisAssert(pnode);
  9361. pnode->isUsed = false;
  9362. }
  9363. }
  9364. LNeedTerminator:
  9365. // Need a semicolon, new-line, } or end-of-file.
  9366. // We digest a semicolon if it's there.
  9367. switch (m_token.tk)
  9368. {
  9369. case tkSColon:
  9370. m_pscan->Scan();
  9371. if (pnode!= nullptr) pnode->grfpn |= PNodeFlags::fpnExplicitSemicolon;
  9372. break;
  9373. case tkEOF:
  9374. case tkRCurly:
  9375. if (pnode!= nullptr) pnode->grfpn |= PNodeFlags::fpnAutomaticSemicolon;
  9376. break;
  9377. default:
  9378. if (!m_pscan->FHadNewLine())
  9379. {
  9380. Error(ERRnoSemic);
  9381. }
  9382. else
  9383. {
  9384. if (pnode!= nullptr) pnode->grfpn |= PNodeFlags::fpnAutomaticSemicolon;
  9385. }
  9386. break;
  9387. }
  9388. break;
  9389. }
  9390. if (m_hasDeferredShorthandInitError)
  9391. {
  9392. Error(ERRnoColon);
  9393. }
  9394. if (buildAST)
  9395. {
  9396. // All non expression statements excluded from the "this.x" optimization
  9397. // Another check while parsing expressions
  9398. if (!expressionStmt)
  9399. {
  9400. if (m_currentNodeFunc)
  9401. {
  9402. m_currentNodeFunc->sxFnc.SetHasNonThisStmt();
  9403. }
  9404. else if (m_currentNodeProg)
  9405. {
  9406. m_currentNodeProg->sxFnc.SetHasNonThisStmt();
  9407. }
  9408. }
  9409. #if EXCEPTION_RECOVERY
  9410. // close the try/catch block
  9411. if(Js::Configuration::Global.flags.SwallowExceptions)
  9412. {
  9413. // pop the try block and fill in the body
  9414. PopStmt(&stmtTryBlock);
  9415. pTryBlock->sxBlock.pnodeStmt = pnode;
  9416. PopStmt(&stmtTry);
  9417. if(pnode != nullptr)
  9418. {
  9419. pTry->ichLim = pnode->ichLim;
  9420. }
  9421. pTry->sxTry.pnodeBody = pTryBlock;
  9422. // create a catch block with an empty body
  9423. StmtNest stmtCatch;
  9424. ParseNodePtr pCatch;
  9425. pCatch = CreateNodeWithScanner<knopCatch>();
  9426. PushStmt<buildAST>(&stmtCatch, pCatch, knopCatch, nullptr, nullptr);
  9427. pCatch->sxCatch.pnodeBody = nullptr;
  9428. if(pnode != nullptr)
  9429. {
  9430. pCatch->ichLim = pnode->ichLim;
  9431. }
  9432. pCatch->sxCatch.grfnop = 0;
  9433. pCatch->sxCatch.pnodeNext = nullptr;
  9434. // create a fake name for the catch var.
  9435. const WCHAR *uniqueNameStr = _u("__ehobj");
  9436. IdentPtr uniqueName = m_phtbl->PidHashNameLen(uniqueNameStr, static_cast<int32>(wcslen(uniqueNameStr)));
  9437. pCatch->sxCatch.pnodeParam = CreateNameNode(uniqueName);
  9438. // Add this catch to the current list. We don't bother adjusting the catch and function expression
  9439. // lists here because the catch is just an empty statement.
  9440. if (m_ppnodeExprScope)
  9441. {
  9442. Assert(*m_ppnodeExprScope == nullptr);
  9443. *m_ppnodeExprScope = pCatch;
  9444. m_ppnodeExprScope = &pCatch->sxCatch.pnodeNext;
  9445. }
  9446. else
  9447. {
  9448. Assert(m_ppnodeScope);
  9449. Assert(*m_ppnodeScope == nullptr);
  9450. *m_ppnodeScope = pCatch;
  9451. m_ppnodeScope = &pCatch->sxCatch.pnodeNext;
  9452. }
  9453. pCatch->sxCatch.pnodeScopes = nullptr;
  9454. PopStmt(&stmtCatch);
  9455. // fill in and pop the try-catch
  9456. pParentTryCatch->sxTryCatch.pnodeTry = pTry;
  9457. pParentTryCatch->sxTryCatch.pnodeCatch = pCatch;
  9458. PopStmt(&stmtTryCatch);
  9459. PopStmt(&stmtTryCatchBlock);
  9460. // replace the node that's being returned
  9461. pParentTryCatchBlock->sxBlock.pnodeStmt = pParentTryCatch;
  9462. pnode = pParentTryCatchBlock;
  9463. }
  9464. #endif // EXCEPTION_RECOVERY
  9465. }
  9466. return pnode;
  9467. }
  9468. BOOL
  9469. Parser::TokIsForInOrForOf()
  9470. {
  9471. return m_token.tk == tkIN ||
  9472. (m_token.tk == tkID &&
  9473. m_token.GetIdentifier(m_phtbl) == wellKnownPropertyPids.of);
  9474. }
  9475. /***************************************************************************
  9476. Parse a sequence of statements.
  9477. ***************************************************************************/
  9478. template<bool buildAST>
  9479. void Parser::ParseStmtList(ParseNodePtr *ppnodeList, ParseNodePtr **pppnodeLast, StrictModeEnvironment smEnvironment, const bool isSourceElementList, bool* strictModeOn)
  9480. {
  9481. BOOL doneDirectives = !isSourceElementList; // directives may only exist in a SourceElementList, not a StatementList
  9482. BOOL seenDirectiveContainingOctal = false; // Have we seen an octal directive before a use strict directive?
  9483. BOOL old_UseStrictMode = m_fUseStrictMode;
  9484. ParseNodePtr pnodeStmt;
  9485. ParseNodePtr *lastNodeRef = nullptr;
  9486. if (buildAST)
  9487. {
  9488. AssertMem(ppnodeList);
  9489. AssertMemN(pppnodeLast);
  9490. *ppnodeList = nullptr;
  9491. }
  9492. if(CONFIG_FLAG(ForceStrictMode))
  9493. {
  9494. m_fUseStrictMode = TRUE;
  9495. }
  9496. for (;;)
  9497. {
  9498. switch (m_token.tk)
  9499. {
  9500. case tkCASE:
  9501. case tkDEFAULT:
  9502. case tkRCurly:
  9503. case tkEOF:
  9504. if (buildAST && nullptr != pppnodeLast)
  9505. {
  9506. *pppnodeLast = lastNodeRef;
  9507. }
  9508. if (!buildAST)
  9509. {
  9510. m_fUseStrictMode = old_UseStrictMode;
  9511. }
  9512. return;
  9513. }
  9514. if (doneDirectives == FALSE)
  9515. {
  9516. bool isOctalInString = false;
  9517. bool isUseStrictDirective = false;
  9518. bool isUseAsmDirective = false;
  9519. if (smEnvironment != SM_NotUsed && CheckForDirective(&isUseStrictDirective, &isUseAsmDirective, &isOctalInString))
  9520. {
  9521. // Ignore "use asm" statement when not building the AST
  9522. isUseAsmDirective &= buildAST;
  9523. if (isUseStrictDirective)
  9524. {
  9525. // Functions with non-simple parameter list cannot be made strict mode
  9526. if (GetCurrentFunctionNode()->sxFnc.HasNonSimpleParameterList())
  9527. {
  9528. Error(ERRNonSimpleParamListInStrictMode);
  9529. }
  9530. if (seenDirectiveContainingOctal)
  9531. {
  9532. // Directives seen before a "use strict" cannot contain an octal.
  9533. Error(ERRES5NoOctal);
  9534. }
  9535. if (!buildAST)
  9536. {
  9537. // Turning on strict mode in deferred code.
  9538. m_fUseStrictMode = TRUE;
  9539. if (!m_inDeferredNestedFunc)
  9540. {
  9541. // Top-level deferred function, so there's a parse node
  9542. Assert(m_currentNodeFunc != nullptr);
  9543. m_currentNodeFunc->sxFnc.SetStrictMode();
  9544. }
  9545. else if (strictModeOn)
  9546. {
  9547. // This turns on strict mode in a deferred function, we need to go back
  9548. // and re-check duplicated formals.
  9549. *strictModeOn = true;
  9550. }
  9551. }
  9552. else
  9553. {
  9554. if (smEnvironment == SM_OnGlobalCode)
  9555. {
  9556. // Turning on strict mode at the top level
  9557. m_fUseStrictMode = TRUE;
  9558. }
  9559. else
  9560. {
  9561. // i.e. smEnvironment == SM_OnFunctionCode
  9562. Assert(m_currentNodeFunc != nullptr);
  9563. m_currentNodeFunc->sxFnc.SetStrictMode();
  9564. }
  9565. }
  9566. }
  9567. else if (isUseAsmDirective)
  9568. {
  9569. if (smEnvironment != SM_OnGlobalCode) //Top level use asm doesn't mean anything.
  9570. {
  9571. // i.e. smEnvironment == SM_OnFunctionCode
  9572. Assert(m_currentNodeFunc != nullptr);
  9573. m_currentNodeFunc->sxFnc.SetAsmjsMode();
  9574. m_currentNodeFunc->sxFnc.SetCanBeDeferred(false);
  9575. m_InAsmMode = true;
  9576. CHAKRATEL_LANGSTATS_INC_LANGFEATURECOUNT(AsmJSFunction, m_scriptContext);
  9577. }
  9578. }
  9579. else if (isOctalInString)
  9580. {
  9581. seenDirectiveContainingOctal = TRUE;
  9582. }
  9583. }
  9584. else
  9585. {
  9586. // The first time we see anything other than a directive we can have no more directives.
  9587. doneDirectives = TRUE;
  9588. }
  9589. }
  9590. if (nullptr != (pnodeStmt = ParseStatement<buildAST>()))
  9591. {
  9592. if (buildAST)
  9593. {
  9594. AddToNodeList(ppnodeList, &lastNodeRef, pnodeStmt);
  9595. }
  9596. }
  9597. }
  9598. }
  9599. template <class Fn>
  9600. void Parser::FinishFunctionsInScope(ParseNodePtr pnodeScopeList, Fn fn)
  9601. {
  9602. Scope * scope;
  9603. Scope * origCurrentScope = this->m_currentScope;
  9604. ParseNodePtr pnodeScope;
  9605. ParseNodePtr pnodeBlock;
  9606. for (pnodeScope = pnodeScopeList; pnodeScope;)
  9607. {
  9608. switch (pnodeScope->nop)
  9609. {
  9610. case knopBlock:
  9611. m_nextBlockId = pnodeScope->sxBlock.blockId + 1;
  9612. PushBlockInfo(pnodeScope);
  9613. scope = pnodeScope->sxBlock.scope;
  9614. if (scope && scope != origCurrentScope)
  9615. {
  9616. PushScope(scope);
  9617. }
  9618. FinishFunctionsInScope(pnodeScope->sxBlock.pnodeScopes, fn);
  9619. if (scope && scope != origCurrentScope)
  9620. {
  9621. BindPidRefs<false>(GetCurrentBlockInfo(), m_nextBlockId - 1);
  9622. PopScope(scope);
  9623. }
  9624. PopBlockInfo();
  9625. pnodeScope = pnodeScope->sxBlock.pnodeNext;
  9626. break;
  9627. case knopFncDecl:
  9628. fn(pnodeScope);
  9629. pnodeScope = pnodeScope->sxFnc.pnodeNext;
  9630. break;
  9631. case knopCatch:
  9632. scope = pnodeScope->sxCatch.scope;
  9633. if (scope)
  9634. {
  9635. PushScope(scope);
  9636. }
  9637. pnodeBlock = CreateBlockNode(PnodeBlockType::Regular);
  9638. pnodeBlock->sxBlock.scope = scope;
  9639. PushBlockInfo(pnodeBlock);
  9640. FinishFunctionsInScope(pnodeScope->sxCatch.pnodeScopes, fn);
  9641. if (scope)
  9642. {
  9643. BindPidRefs<false>(GetCurrentBlockInfo(), m_nextBlockId - 1);
  9644. PopScope(scope);
  9645. }
  9646. PopBlockInfo();
  9647. pnodeScope = pnodeScope->sxCatch.pnodeNext;
  9648. break;
  9649. case knopWith:
  9650. PushBlockInfo(CreateBlockNode());
  9651. PushDynamicBlock();
  9652. FinishFunctionsInScope(pnodeScope->sxWith.pnodeScopes, fn);
  9653. PopBlockInfo();
  9654. pnodeScope = pnodeScope->sxWith.pnodeNext;
  9655. break;
  9656. default:
  9657. AssertMsg(false, "Unexpected node with scope list");
  9658. return;
  9659. }
  9660. }
  9661. }
  9662. // Scripts above this size (minus string literals and comments) will have parsing of
  9663. // function bodies deferred.
  9664. ULONG Parser::GetDeferralThreshold(bool isProfileLoaded)
  9665. {
  9666. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  9667. if (CONFIG_FLAG(ForceDeferParse) ||
  9668. PHASE_FORCE1(Js::DeferParsePhase) ||
  9669. Js::Configuration::Global.flags.IsEnabled(Js::ForceUndoDeferFlag))
  9670. {
  9671. return 0;
  9672. }
  9673. else if (Js::Configuration::Global.flags.IsEnabled(Js::DeferParseFlag))
  9674. {
  9675. return Js::Configuration::Global.flags.DeferParse;
  9676. }
  9677. else
  9678. #endif
  9679. {
  9680. if (isProfileLoaded)
  9681. {
  9682. return DEFAULT_CONFIG_ProfileBasedDeferParseThreshold;
  9683. }
  9684. return DEFAULT_CONFIG_DeferParseThreshold;
  9685. }
  9686. }
  9687. void Parser::FinishDeferredFunction(ParseNodePtr pnodeScopeList)
  9688. {
  9689. uint saveNextBlockId = m_nextBlockId;
  9690. m_nextBlockId = pnodeScopeList->sxBlock.blockId + 1;
  9691. FinishFunctionsInScope(pnodeScopeList,
  9692. [this](ParseNodePtr pnodeFnc)
  9693. {
  9694. Assert(pnodeFnc->nop == knopFncDecl);
  9695. // Non-simple params (such as default) require a good amount of logic to put vars on appropriate scopes. ParseFncDecl handles it
  9696. // properly (both on defer and non-defer case). This is to avoid write duplicated logic here as well. Function with non-simple-param
  9697. // will remain deferred until they are called.
  9698. if (pnodeFnc->sxFnc.pnodeBody == nullptr && !pnodeFnc->sxFnc.HasNonSimpleParameterList())
  9699. {
  9700. // Go back and generate an AST for this function.
  9701. JS_ETW_INTERNAL(EventWriteJSCRIPT_PARSE_FUNC(this->GetScriptContext(), pnodeFnc->sxFnc.functionId, /*Undefer*/TRUE));
  9702. ParseNodePtr pnodeFncSave = this->m_currentNodeFunc;
  9703. this->m_currentNodeFunc = pnodeFnc;
  9704. ParseNodePtr pnodeFncExprBlock = nullptr;
  9705. ParseNodePtr pnodeName = pnodeFnc->sxFnc.pnodeName;
  9706. if (pnodeName)
  9707. {
  9708. Assert(pnodeName->nop == knopVarDecl);
  9709. Assert(pnodeName->sxVar.pnodeNext == nullptr);
  9710. if (!pnodeFnc->sxFnc.IsDeclaration())
  9711. {
  9712. // Set up the named function expression symbol so references inside the function can be bound.
  9713. pnodeFncExprBlock = this->StartParseBlock<true>(PnodeBlockType::Function, ScopeType_FuncExpr);
  9714. PidRefStack *ref = this->PushPidRef(pnodeName->sxVar.pid);
  9715. pnodeName->sxVar.symRef = ref->GetSymRef();
  9716. ref->SetSym(pnodeName->sxVar.sym);
  9717. Scope *fncExprScope = pnodeFncExprBlock->sxBlock.scope;
  9718. fncExprScope->AddNewSymbol(pnodeName->sxVar.sym);
  9719. pnodeFnc->sxFnc.scope = fncExprScope;
  9720. }
  9721. }
  9722. ParseNodePtr pnodeBlock = this->StartParseBlock<true>(PnodeBlockType::Parameter, ScopeType_Parameter);
  9723. pnodeFnc->sxFnc.pnodeScopes = pnodeBlock;
  9724. m_ppnodeScope = &pnodeBlock->sxBlock.pnodeScopes;
  9725. pnodeBlock->sxBlock.pnodeStmt = pnodeFnc;
  9726. ParseNodePtr* varNodesList = &pnodeFnc->sxFnc.pnodeVars;
  9727. ParseNodePtr argNode = nullptr;
  9728. if (!pnodeFnc->sxFnc.IsModule() && !pnodeFnc->sxFnc.IsLambda() && !(pnodeFnc->grfpn & PNodeFlags::fpnArguments_overriddenInParam))
  9729. {
  9730. ParseNodePtr *const ppnodeVarSave = m_ppnodeVar;
  9731. m_ppnodeVar = &pnodeFnc->sxFnc.pnodeVars;
  9732. argNode = this->AddArgumentsNodeToVars(pnodeFnc);
  9733. varNodesList = m_ppnodeVar;
  9734. m_ppnodeVar = ppnodeVarSave;
  9735. }
  9736. // Add the args to the scope, since we won't re-parse those.
  9737. Scope *scope = pnodeBlock->sxBlock.scope;
  9738. uint blockId = GetCurrentBlock()->sxBlock.blockId;
  9739. uint funcId = GetCurrentFunctionNode()->sxFnc.functionId;
  9740. auto addArgsToScope = [&](ParseNodePtr pnodeArg) {
  9741. if (pnodeArg->IsVarLetOrConst())
  9742. {
  9743. PidRefStack *ref = this->FindOrAddPidRef(pnodeArg->sxVar.pid, blockId, funcId);
  9744. pnodeArg->sxVar.symRef = ref->GetSymRef();
  9745. if (ref->GetSym() != nullptr)
  9746. {
  9747. // Duplicate parameter in a configuration that allows them.
  9748. // The symbol is already in the scope, just point it to the right declaration.
  9749. Assert(ref->GetSym() == pnodeArg->sxVar.sym);
  9750. ref->GetSym()->SetDecl(pnodeArg);
  9751. }
  9752. else
  9753. {
  9754. ref->SetSym(pnodeArg->sxVar.sym);
  9755. scope->AddNewSymbol(pnodeArg->sxVar.sym);
  9756. }
  9757. }
  9758. };
  9759. MapFormals(pnodeFnc, addArgsToScope);
  9760. MapFormalsFromPattern(pnodeFnc, addArgsToScope);
  9761. ParseNodePtr pnodeInnerBlock = this->StartParseBlock<true>(PnodeBlockType::Function, ScopeType_FunctionBody);
  9762. pnodeFnc->sxFnc.pnodeBodyScope = pnodeInnerBlock;
  9763. // Set the parameter block's child to the function body block.
  9764. *m_ppnodeScope = pnodeInnerBlock;
  9765. ParseNodePtr *ppnodeScopeSave = nullptr;
  9766. ParseNodePtr *ppnodeExprScopeSave = nullptr;
  9767. ppnodeScopeSave = m_ppnodeScope;
  9768. // This synthetic block scope will contain all the nested scopes.
  9769. m_ppnodeScope = &pnodeInnerBlock->sxBlock.pnodeScopes;
  9770. pnodeInnerBlock->sxBlock.pnodeStmt = pnodeFnc;
  9771. // Keep nested function declarations and expressions in the same list at function scope.
  9772. // (Indicate this by nulling out the current function expressions list.)
  9773. ppnodeExprScopeSave = m_ppnodeExprScope;
  9774. m_ppnodeExprScope = nullptr;
  9775. // Shouldn't be any temps in the arg list.
  9776. Assert(*m_ppnodeVar == nullptr);
  9777. // Start the var list.
  9778. m_ppnodeVar = varNodesList;
  9779. if (scope != nullptr)
  9780. {
  9781. Assert(pnodeFnc->sxFnc.IsBodyAndParamScopeMerged());
  9782. blockId = GetCurrentBlock()->sxBlock.blockId;
  9783. funcId = GetCurrentFunctionNode()->sxFnc.functionId;
  9784. scope->ForEachSymbol([this, blockId, funcId](Symbol* paramSym)
  9785. {
  9786. PidRefStack* ref = this->FindOrAddPidRef(paramSym->GetPid(), blockId, funcId);
  9787. ref->SetSym(paramSym);
  9788. });
  9789. }
  9790. Assert(m_currentNodeNonLambdaFunc == nullptr);
  9791. m_currentNodeNonLambdaFunc = pnodeFnc;
  9792. this->FinishFncNode(pnodeFnc);
  9793. Assert(pnodeFnc == m_currentNodeNonLambdaFunc);
  9794. m_currentNodeNonLambdaFunc = nullptr;
  9795. m_ppnodeExprScope = ppnodeExprScopeSave;
  9796. AssertMem(m_ppnodeScope);
  9797. Assert(nullptr == *m_ppnodeScope);
  9798. m_ppnodeScope = ppnodeScopeSave;
  9799. this->FinishParseBlock(pnodeInnerBlock);
  9800. if (!pnodeFnc->sxFnc.IsModule() && (m_token.tk == tkLCurly || !pnodeFnc->sxFnc.IsLambda()))
  9801. {
  9802. UpdateArgumentsNode(pnodeFnc, argNode);
  9803. }
  9804. CreateSpecialSymbolDeclarations(pnodeFnc, false);
  9805. this->FinishParseBlock(pnodeBlock);
  9806. if (pnodeFncExprBlock)
  9807. {
  9808. this->FinishParseBlock(pnodeFncExprBlock);
  9809. }
  9810. this->m_currentNodeFunc = pnodeFncSave;
  9811. }
  9812. });
  9813. m_nextBlockId = saveNextBlockId;
  9814. }
  9815. void Parser::InitPids()
  9816. {
  9817. AssertMemN(m_phtbl);
  9818. wellKnownPropertyPids.arguments = m_phtbl->PidHashNameLen(g_ssym_arguments.sz, g_ssym_arguments.cch);
  9819. wellKnownPropertyPids.async = m_phtbl->PidHashNameLen(g_ssym_async.sz, g_ssym_async.cch);
  9820. wellKnownPropertyPids.eval = m_phtbl->PidHashNameLen(g_ssym_eval.sz, g_ssym_eval.cch);
  9821. wellKnownPropertyPids.get = m_phtbl->PidHashNameLen(g_ssym_get.sz, g_ssym_get.cch);
  9822. wellKnownPropertyPids.set = m_phtbl->PidHashNameLen(g_ssym_set.sz, g_ssym_set.cch);
  9823. wellKnownPropertyPids.let = m_phtbl->PidHashNameLen(g_ssym_let.sz, g_ssym_let.cch);
  9824. wellKnownPropertyPids.constructor = m_phtbl->PidHashNameLen(g_ssym_constructor.sz, g_ssym_constructor.cch);
  9825. wellKnownPropertyPids.prototype = m_phtbl->PidHashNameLen(g_ssym_prototype.sz, g_ssym_prototype.cch);
  9826. wellKnownPropertyPids.__proto__ = m_phtbl->PidHashNameLen(_u("__proto__"), sizeof("__proto__") - 1);
  9827. wellKnownPropertyPids.of = m_phtbl->PidHashNameLen(_u("of"), sizeof("of") - 1);
  9828. wellKnownPropertyPids.target = m_phtbl->PidHashNameLen(_u("target"), sizeof("target") - 1);
  9829. wellKnownPropertyPids.as = m_phtbl->PidHashNameLen(_u("as"), sizeof("as") - 1);
  9830. wellKnownPropertyPids.from = m_phtbl->PidHashNameLen(_u("from"), sizeof("from") - 1);
  9831. wellKnownPropertyPids._default = m_phtbl->PidHashNameLen(_u("default"), sizeof("default") - 1);
  9832. wellKnownPropertyPids._starDefaultStar = m_phtbl->PidHashNameLen(_u("*default*"), sizeof("*default*") - 1);
  9833. wellKnownPropertyPids._star = m_phtbl->PidHashNameLen(_u("*"), sizeof("*") - 1);
  9834. wellKnownPropertyPids._this = m_phtbl->PidHashNameLen(_u("*this*"), sizeof("*this*") - 1);
  9835. wellKnownPropertyPids._newTarget = m_phtbl->PidHashNameLen(_u("*new.target*"), sizeof("*new.target*") - 1);
  9836. wellKnownPropertyPids._super = m_phtbl->PidHashNameLen(_u("*super*"), sizeof("*super*") - 1);
  9837. wellKnownPropertyPids._superConstructor = m_phtbl->PidHashNameLen(_u("*superconstructor*"), sizeof("*superconstructor*") - 1);
  9838. }
  9839. void Parser::RestoreScopeInfo(Js::ScopeInfo * scopeInfo)
  9840. {
  9841. if (!scopeInfo)
  9842. {
  9843. return;
  9844. }
  9845. PROBE_STACK_NO_DISPOSE(m_scriptContext, Js::Constants::MinStackByteCodeVisitor);
  9846. RestoreScopeInfo(scopeInfo->GetParentScopeInfo()); // Recursively restore outer func scope info
  9847. scopeInfo->SetScopeId(m_nextBlockId);
  9848. ParseNodePtr pnodeScope = nullptr;
  9849. ScopeType scopeType = scopeInfo->GetScopeType();
  9850. PnodeBlockType blockType;
  9851. switch (scopeType)
  9852. {
  9853. case ScopeType_With:
  9854. PushDynamicBlock();
  9855. // fall through
  9856. case ScopeType_Block:
  9857. case ScopeType_Catch:
  9858. case ScopeType_CatchParamPattern:
  9859. case ScopeType_GlobalEvalBlock:
  9860. blockType = PnodeBlockType::Regular;
  9861. break;
  9862. case ScopeType_FunctionBody:
  9863. case ScopeType_FuncExpr:
  9864. blockType = PnodeBlockType::Function;
  9865. break;
  9866. case ScopeType_Parameter:
  9867. blockType = PnodeBlockType::Parameter;
  9868. break;
  9869. default:
  9870. Assert(0);
  9871. return;
  9872. }
  9873. pnodeScope = StartParseBlockWithCapacity<true>(blockType, scopeType, scopeInfo->GetSymbolCount());
  9874. Scope *scope = pnodeScope->sxBlock.scope;
  9875. scope->SetScopeInfo(scopeInfo);
  9876. scopeInfo->ExtractScopeInfo(this, /*nullptr, nullptr,*/ scope);
  9877. }
  9878. void Parser::FinishScopeInfo(Js::ScopeInfo * scopeInfo)
  9879. {
  9880. PROBE_STACK_NO_DISPOSE(m_scriptContext, Js::Constants::MinStackByteCodeVisitor);
  9881. for (;scopeInfo != nullptr; scopeInfo = scopeInfo->GetParentScopeInfo())
  9882. {
  9883. int scopeId = scopeInfo->GetScopeId();
  9884. scopeInfo->GetScope()->ForEachSymbol([this, scopeId](Symbol *sym)
  9885. {
  9886. this->BindPidRefsInScope(sym->GetPid(), sym, scopeId);
  9887. });
  9888. PopScope(scopeInfo->GetScope());
  9889. PopStmt(&m_currentBlockInfo->pstmt);
  9890. PopBlockInfo();
  9891. }
  9892. }
  9893. /***************************************************************************
  9894. Parse the code.
  9895. ***************************************************************************/
  9896. ParseNodePtr Parser::Parse(LPCUTF8 pszSrc, size_t offset, size_t length, charcount_t charOffset, ULONG grfscr, ULONG lineNumber, Js::LocalFunctionId * nextFunctionId, CompileScriptException *pse)
  9897. {
  9898. ParseNodePtr pnodeProg;
  9899. ParseNodePtr *lastNodeRef = nullptr;
  9900. m_nextBlockId = 0;
  9901. if (this->m_scriptContext->IsScriptContextInDebugMode()
  9902. #ifdef ENABLE_PREJIT
  9903. || Js::Configuration::Global.flags.Prejit
  9904. #endif
  9905. || ((grfscr & fscrNoDeferParse) != 0)
  9906. )
  9907. {
  9908. // Don't do deferred parsing if debugger is attached or feature is disabled
  9909. // by command-line switch.
  9910. grfscr &= ~fscrDeferFncParse;
  9911. }
  9912. else if (!(grfscr & fscrGlobalCode) &&
  9913. (
  9914. PHASE_OFF1(Js::Phase::DeferEventHandlersPhase) ||
  9915. this->m_scriptContext->IsScriptContextInSourceRundownOrDebugMode()
  9916. )
  9917. )
  9918. {
  9919. // Don't defer event handlers in debug/rundown mode, because we need to register the document,
  9920. // so we need to create a full FunctionBody for the script body.
  9921. grfscr &= ~fscrDeferFncParse;
  9922. }
  9923. bool isDeferred = (grfscr & fscrDeferredFnc) != 0;
  9924. bool isModuleSource = (grfscr & fscrIsModuleCode) != 0;
  9925. m_grfscr = grfscr;
  9926. m_length = length;
  9927. m_originalLength = length;
  9928. m_nextFunctionId = nextFunctionId;
  9929. if(m_parseType != ParseType_Deferred)
  9930. {
  9931. JS_ETW(EventWriteJSCRIPT_PARSE_METHOD_START(m_sourceContextInfo->dwHostSourceContext, GetScriptContext(), *m_nextFunctionId, 0, m_parseType, Js::Constants::GlobalFunction));
  9932. OUTPUT_TRACE(Js::DeferParsePhase, _u("Parsing function (%s) : %s (%d)\n"), GetParseType(), Js::Constants::GlobalFunction, *m_nextFunctionId);
  9933. }
  9934. // Give the scanner the source and get the first token
  9935. m_pscan->SetText(pszSrc, offset, length, charOffset, grfscr, lineNumber);
  9936. m_pscan->Scan();
  9937. // Make the main 'knopProg' node
  9938. int32 initSize = 0;
  9939. m_pCurrentAstSize = &initSize;
  9940. pnodeProg = CreateProgNodeWithScanner(isModuleSource);
  9941. pnodeProg->grfpn = PNodeFlags::fpnNone;
  9942. pnodeProg->sxFnc.pid = nullptr;
  9943. pnodeProg->sxFnc.pnodeName = nullptr;
  9944. pnodeProg->sxFnc.pnodeRest = nullptr;
  9945. pnodeProg->sxFnc.ClearFlags();
  9946. pnodeProg->sxFnc.SetNested(FALSE);
  9947. pnodeProg->sxFnc.astSize = 0;
  9948. pnodeProg->sxFnc.cbMin = m_pscan->IecpMinTok();
  9949. pnodeProg->sxFnc.lineNumber = lineNumber;
  9950. pnodeProg->sxFnc.columnNumber = 0;
  9951. pnodeProg->sxFnc.isBodyAndParamScopeMerged = true;
  9952. if (!isDeferred || (isDeferred && grfscr & fscrGlobalCode))
  9953. {
  9954. // In the deferred case, if the global function is deferred parse (which is in no-refresh case),
  9955. // we will re-use the same function body, so start with the correct functionId.
  9956. pnodeProg->sxFnc.functionId = (*m_nextFunctionId)++;
  9957. }
  9958. else
  9959. {
  9960. pnodeProg->sxFnc.functionId = Js::Constants::NoFunctionId;
  9961. }
  9962. if (isModuleSource)
  9963. {
  9964. Assert(m_scriptContext->GetConfig()->IsES6ModuleEnabled());
  9965. pnodeProg->sxModule.localExportEntries = nullptr;
  9966. pnodeProg->sxModule.indirectExportEntries = nullptr;
  9967. pnodeProg->sxModule.starExportEntries = nullptr;
  9968. pnodeProg->sxModule.importEntries = nullptr;
  9969. pnodeProg->sxModule.requestedModules = nullptr;
  9970. }
  9971. m_pCurrentAstSize = & (pnodeProg->sxFnc.astSize);
  9972. pnodeProg->sxFnc.hint = nullptr;
  9973. pnodeProg->sxFnc.hintLength = 0;
  9974. pnodeProg->sxFnc.hintOffset = 0;
  9975. pnodeProg->sxFnc.isNameIdentifierRef = true;
  9976. pnodeProg->sxFnc.nestedFuncEscapes = false;
  9977. // initialize parsing variables
  9978. pnodeProg->sxFnc.pnodeNext = nullptr;
  9979. m_currentNodeFunc = nullptr;
  9980. m_currentNodeDeferredFunc = nullptr;
  9981. m_currentNodeProg = pnodeProg;
  9982. m_cactIdentToNodeLookup = 1;
  9983. pnodeProg->sxFnc.nestedCount = 0;
  9984. m_pnestedCount = &pnodeProg->sxFnc.nestedCount;
  9985. m_inDeferredNestedFunc = false;
  9986. pnodeProg->sxFnc.pnodeParams = nullptr;
  9987. pnodeProg->sxFnc.pnodeVars = nullptr;
  9988. pnodeProg->sxFnc.pnodeRest = nullptr;
  9989. m_ppnodeVar = &pnodeProg->sxFnc.pnodeVars;
  9990. SetCurrentStatement(nullptr);
  9991. AssertMsg(m_pstmtCur == nullptr, "Statement stack should be empty when we start parse global code");
  9992. // Create block for const's and let's
  9993. ParseNodePtr pnodeGlobalBlock = StartParseBlock<true>(PnodeBlockType::Global, ScopeType_Global);
  9994. pnodeProg->sxProg.scope = pnodeGlobalBlock->sxBlock.scope;
  9995. ParseNodePtr pnodeGlobalEvalBlock = nullptr;
  9996. // Don't track function expressions separately from declarations at global scope.
  9997. m_ppnodeExprScope = nullptr;
  9998. // This synthetic block scope will contain all the nested scopes.
  9999. pnodeProg->sxFnc.pnodeBodyScope = nullptr;
  10000. pnodeProg->sxFnc.pnodeScopes = pnodeGlobalBlock;
  10001. m_ppnodeScope = &pnodeGlobalBlock->sxBlock.pnodeScopes;
  10002. if ((this->m_grfscr & fscrEvalCode) &&
  10003. !(this->m_functionBody && this->m_functionBody->GetScopeInfo()))
  10004. {
  10005. pnodeGlobalEvalBlock = StartParseBlock<true>(PnodeBlockType::Regular, ScopeType_GlobalEvalBlock);
  10006. pnodeProg->sxFnc.pnodeScopes = pnodeGlobalEvalBlock;
  10007. m_ppnodeScope = &pnodeGlobalEvalBlock->sxBlock.pnodeScopes;
  10008. }
  10009. Js::ScopeInfo *scopeInfo = nullptr;
  10010. if (m_parseType == ParseType_Deferred && m_functionBody)
  10011. {
  10012. // this->m_functionBody can be cleared during parsing, but we need access to the scope info later.
  10013. scopeInfo = m_functionBody->GetScopeInfo();
  10014. if (scopeInfo)
  10015. {
  10016. // Create an enclosing function context.
  10017. m_currentNodeFunc = CreateNode(knopFncDecl);
  10018. m_currentNodeFunc->sxFnc.pnodeName = nullptr;
  10019. m_currentNodeFunc->sxFnc.functionId = m_functionBody->GetLocalFunctionId();
  10020. m_currentNodeFunc->sxFnc.nestedCount = m_functionBody->GetNestedCount();
  10021. m_currentNodeFunc->sxFnc.SetStrictMode(!!this->m_fUseStrictMode);
  10022. this->RestoreScopeInfo(scopeInfo);
  10023. }
  10024. }
  10025. // It's possible for the module global to be defer-parsed in debug scenarios.
  10026. if (isModuleSource && (!isDeferred || (isDeferred && grfscr & fscrGlobalCode)))
  10027. {
  10028. ParseNodePtr moduleFunction = GenerateModuleFunctionWrapper<true>();
  10029. pnodeProg->sxFnc.pnodeBody = nullptr;
  10030. AddToNodeList(&pnodeProg->sxFnc.pnodeBody, &lastNodeRef, moduleFunction);
  10031. }
  10032. else
  10033. {
  10034. // Process a sequence of statements/declarations
  10035. ParseStmtList<true>(
  10036. &pnodeProg->sxFnc.pnodeBody,
  10037. &lastNodeRef,
  10038. SM_OnGlobalCode,
  10039. !(m_grfscr & fscrDeferredFncExpression) /* isSourceElementList */);
  10040. }
  10041. if (m_parseType == ParseType_Deferred)
  10042. {
  10043. if (scopeInfo)
  10044. {
  10045. this->FinishScopeInfo(scopeInfo);
  10046. }
  10047. }
  10048. pnodeProg->sxProg.m_UsesArgumentsAtGlobal = m_UsesArgumentsAtGlobal;
  10049. if (IsStrictMode())
  10050. {
  10051. pnodeProg->sxFnc.SetStrictMode();
  10052. }
  10053. #if DEBUG
  10054. if(m_grfscr & fscrEnforceJSON && !IsJSONValid(pnodeProg->sxFnc.pnodeBody))
  10055. {
  10056. Error(ERRsyntax);
  10057. }
  10058. #endif
  10059. if (tkEOF != m_token.tk)
  10060. Error(ERRsyntax);
  10061. // We only need to create special symbol bindings for 'this' for indirect eval
  10062. if ((this->m_grfscr & fscrEvalCode) && !(this->m_grfscr & fscrEval))
  10063. {
  10064. CreateSpecialSymbolDeclarations(pnodeProg, true);
  10065. }
  10066. // Append an EndCode node.
  10067. AddToNodeList(&pnodeProg->sxFnc.pnodeBody, &lastNodeRef,
  10068. CreateNodeWithScanner<knopEndCode>());
  10069. AssertMem(lastNodeRef);
  10070. AssertNodeMem(*lastNodeRef);
  10071. Assert((*lastNodeRef)->nop == knopEndCode);
  10072. (*lastNodeRef)->ichMin = 0;
  10073. (*lastNodeRef)->ichLim = 0;
  10074. // Get the extent of the code.
  10075. pnodeProg->ichLim = m_pscan->IchLimTok();
  10076. pnodeProg->sxFnc.cbLim = m_pscan->IecpLimTok();
  10077. // Terminate the local list
  10078. *m_ppnodeVar = nullptr;
  10079. Assert(nullptr == *m_ppnodeScope);
  10080. Assert(nullptr == pnodeProg->sxFnc.pnodeNext);
  10081. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  10082. if (Js::Configuration::Global.flags.IsEnabled(Js::ForceUndoDeferFlag))
  10083. {
  10084. m_stoppedDeferredParse = true;
  10085. }
  10086. #endif
  10087. if (m_stoppedDeferredParse)
  10088. {
  10089. #if ENABLE_BACKGROUND_PARSING
  10090. if (this->m_hasParallelJob)
  10091. {
  10092. BackgroundParser *bgp = static_cast<BackgroundParser*>(m_scriptContext->GetBackgroundParser());
  10093. Assert(bgp);
  10094. this->WaitForBackgroundJobs(bgp, pse);
  10095. }
  10096. #endif
  10097. // Do any remaining bindings of globals referenced in non-deferred functions.
  10098. if (pnodeGlobalEvalBlock)
  10099. {
  10100. FinishParseBlock(pnodeGlobalEvalBlock);
  10101. }
  10102. FinishParseBlock(pnodeGlobalBlock);
  10103. // Clear out references to undeclared identifiers.
  10104. m_phtbl->VisitPids([&](IdentPtr pid) { pid->SetTopRef(nullptr); });
  10105. // Restore global scope and blockinfo stacks preparatory to reparsing deferred functions.
  10106. PushScope(pnodeGlobalBlock->sxBlock.scope);
  10107. BlockInfoStack *newBlockInfo = PushBlockInfo(pnodeGlobalBlock);
  10108. PushStmt<true>(&newBlockInfo->pstmt, pnodeGlobalBlock, knopBlock, nullptr, nullptr);
  10109. if (pnodeGlobalEvalBlock)
  10110. {
  10111. PushScope(pnodeGlobalEvalBlock->sxBlock.scope);
  10112. newBlockInfo = PushBlockInfo(pnodeGlobalEvalBlock);
  10113. PushStmt<true>(&newBlockInfo->pstmt, pnodeGlobalEvalBlock, knopBlock, nullptr, nullptr);
  10114. }
  10115. // Finally, see if there are any function bodies we now want to generate because we
  10116. // decided to stop deferring.
  10117. FinishDeferredFunction(pnodeProg->sxFnc.pnodeScopes);
  10118. }
  10119. if (pnodeGlobalEvalBlock)
  10120. {
  10121. FinishParseBlock(pnodeGlobalEvalBlock);
  10122. }
  10123. // Append block as body of pnodeProg
  10124. FinishParseBlock(pnodeGlobalBlock);
  10125. m_scriptContext->AddSourceSize(m_length);
  10126. if (m_parseType != ParseType_Deferred)
  10127. {
  10128. JS_ETW(EventWriteJSCRIPT_PARSE_METHOD_STOP(m_sourceContextInfo->dwHostSourceContext, GetScriptContext(), pnodeProg->sxFnc.functionId, *m_pCurrentAstSize, false, Js::Constants::GlobalFunction));
  10129. }
  10130. return pnodeProg;
  10131. }
  10132. bool Parser::CheckForDirective(bool* pIsUseStrict, bool *pIsUseAsm, bool* pIsOctalInString)
  10133. {
  10134. // A directive is a string constant followed by a statement terminating token
  10135. if (m_token.tk != tkStrCon)
  10136. return false;
  10137. // Careful, need to check for octal before calling m_pscan->Scan()
  10138. // because Scan() clears the "had octal" flag on the scanner and
  10139. // m_pscan->Restore() does not restore this flag.
  10140. if (pIsOctalInString != nullptr)
  10141. {
  10142. *pIsOctalInString = m_pscan->IsOctOrLeadingZeroOnLastTKNumber();
  10143. }
  10144. Ident* pidDirective = m_token.GetStr();
  10145. RestorePoint start;
  10146. m_pscan->Capture(&start);
  10147. m_pscan->Scan();
  10148. bool isDirective = true;
  10149. switch (m_token.tk)
  10150. {
  10151. case tkSColon:
  10152. case tkEOF:
  10153. case tkLCurly:
  10154. case tkRCurly:
  10155. break;
  10156. default:
  10157. if (!m_pscan->FHadNewLine())
  10158. {
  10159. isDirective = false;
  10160. }
  10161. break;
  10162. }
  10163. if (isDirective)
  10164. {
  10165. if (pIsUseStrict != nullptr)
  10166. {
  10167. *pIsUseStrict = CheckStrictModeStrPid(pidDirective);
  10168. }
  10169. if (pIsUseAsm != nullptr)
  10170. {
  10171. *pIsUseAsm = CheckAsmjsModeStrPid(pidDirective);
  10172. }
  10173. }
  10174. m_pscan->SeekTo(start);
  10175. return isDirective;
  10176. }
  10177. bool Parser::CheckStrictModeStrPid(IdentPtr pid)
  10178. {
  10179. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  10180. if (Js::Configuration::Global.flags.NoStrictMode)
  10181. return false;
  10182. #endif
  10183. return pid != nullptr &&
  10184. pid->Cch() == 10 &&
  10185. !m_pscan->IsEscapeOnLastTkStrCon() &&
  10186. wcsncmp(pid->Psz(), _u("use strict"), 10) == 0;
  10187. }
  10188. bool Parser::CheckAsmjsModeStrPid(IdentPtr pid)
  10189. {
  10190. #ifdef ASMJS_PLAT
  10191. if (!CONFIG_FLAG_RELEASE(Asmjs))
  10192. {
  10193. return false;
  10194. }
  10195. bool isAsmCandidate = (pid != nullptr &&
  10196. AutoSystemInfo::Data.SSE2Available() &&
  10197. pid->Cch() == 7 &&
  10198. !m_pscan->IsEscapeOnLastTkStrCon() &&
  10199. wcsncmp(pid->Psz(), _u("use asm"), 10) == 0);
  10200. #ifdef ENABLE_SCRIPT_DEBUGGING
  10201. if (isAsmCandidate && m_scriptContext->IsScriptContextInDebugMode())
  10202. {
  10203. // We would like to report this to debugger - they may choose to disable debugging.
  10204. // TODO : localization of the string?
  10205. 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);
  10206. return false;
  10207. }
  10208. #endif
  10209. return isAsmCandidate && !(m_grfscr & fscrNoAsmJs);
  10210. #else
  10211. return false;
  10212. #endif
  10213. }
  10214. HRESULT Parser::ParseUtf8Source(__out ParseNodePtr* parseTree, LPCUTF8 pSrc, size_t length, ULONG grfsrc, CompileScriptException *pse,
  10215. Js::LocalFunctionId * nextFunctionId, SourceContextInfo * sourceContextInfo)
  10216. {
  10217. m_functionBody = nullptr;
  10218. m_parseType = ParseType_Upfront;
  10219. return ParseSourceInternal( parseTree, pSrc, 0, length, 0, true, grfsrc, pse, nextFunctionId, 0, sourceContextInfo);
  10220. }
  10221. HRESULT Parser::ParseCesu8Source(__out ParseNodePtr* parseTree, LPCUTF8 pSrc, size_t length, ULONG grfsrc, CompileScriptException *pse,
  10222. Js::LocalFunctionId * nextFunctionId, SourceContextInfo * sourceContextInfo)
  10223. {
  10224. m_functionBody = nullptr;
  10225. m_parseType = ParseType_Upfront;
  10226. return ParseSourceInternal( parseTree, pSrc, 0, length, 0, false, grfsrc, pse, nextFunctionId, 0, sourceContextInfo);
  10227. }
  10228. void Parser::PrepareScanner(bool fromExternal)
  10229. {
  10230. // NOTE: HashTbl and Scanner are currently allocated from the CRT heap. If we want to allocate them from the
  10231. // parser arena, then we also need to change the way the HashTbl allocates PID's from its underlying
  10232. // allocator (which also currently uses the CRT heap). This is not trivial, because we still need to support
  10233. // heap allocation for the colorizer interface.
  10234. // create the hash table and init PID members
  10235. if (nullptr == (m_phtbl = HashTbl::Create(HASH_TABLE_SIZE)))
  10236. Error(ERRnoMemory);
  10237. InitPids();
  10238. // create the scanner
  10239. if (nullptr == (m_pscan = Scanner_t::Create(this, m_phtbl, &m_token, m_scriptContext)))
  10240. Error(ERRnoMemory);
  10241. if (fromExternal)
  10242. m_pscan->FromExternalSource();
  10243. }
  10244. #if ENABLE_BACKGROUND_PARSING
  10245. void Parser::PrepareForBackgroundParse()
  10246. {
  10247. m_pscan->PrepareForBackgroundParse(m_scriptContext);
  10248. }
  10249. void Parser::AddBackgroundParseItem(BackgroundParseItem *const item)
  10250. {
  10251. if (currBackgroundParseItem == nullptr)
  10252. {
  10253. backgroundParseItems = item;
  10254. }
  10255. else
  10256. {
  10257. currBackgroundParseItem->SetNext(item);
  10258. }
  10259. currBackgroundParseItem = item;
  10260. }
  10261. void Parser::AddFastScannedRegExpNode(ParseNodePtr const pnode)
  10262. {
  10263. Assert(!IsBackgroundParser());
  10264. Assert(m_doingFastScan);
  10265. if (fastScannedRegExpNodes == nullptr)
  10266. {
  10267. fastScannedRegExpNodes = Anew(&m_nodeAllocator, NodeDList, &m_nodeAllocator);
  10268. }
  10269. fastScannedRegExpNodes->Append(pnode);
  10270. }
  10271. void Parser::AddBackgroundRegExpNode(ParseNodePtr const pnode)
  10272. {
  10273. Assert(IsBackgroundParser());
  10274. Assert(currBackgroundParseItem != nullptr);
  10275. currBackgroundParseItem->AddRegExpNode(pnode, &m_nodeAllocator);
  10276. }
  10277. HRESULT Parser::ParseFunctionInBackground(ParseNodePtr pnodeFnc, ParseContext *parseContext, bool topLevelDeferred, CompileScriptException *pse)
  10278. {
  10279. m_functionBody = nullptr;
  10280. m_parseType = ParseType_Upfront;
  10281. HRESULT hr = S_OK;
  10282. SmartFPUControl smartFpuControl;
  10283. uint nextFunctionId = pnodeFnc->sxFnc.functionId + 1;
  10284. this->RestoreContext(parseContext);
  10285. m_nextFunctionId = &nextFunctionId;
  10286. m_deferringAST = topLevelDeferred;
  10287. m_inDeferredNestedFunc = false;
  10288. m_scopeCountNoAst = 0;
  10289. SetCurrentStatement(nullptr);
  10290. pnodeFnc->sxFnc.pnodeVars = nullptr;
  10291. pnodeFnc->sxFnc.pnodeParams = nullptr;
  10292. pnodeFnc->sxFnc.pnodeBody = nullptr;
  10293. pnodeFnc->sxFnc.nestedCount = 0;
  10294. ParseNodePtr pnodeParentFnc = GetCurrentFunctionNode();
  10295. m_currentNodeFunc = pnodeFnc;
  10296. m_currentNodeDeferredFunc = nullptr;
  10297. m_ppnodeScope = nullptr;
  10298. m_ppnodeExprScope = nullptr;
  10299. m_pnestedCount = &pnodeFnc->sxFnc.nestedCount;
  10300. m_pCurrentAstSize = &pnodeFnc->sxFnc.astSize;
  10301. ParseNodePtr pnodeBlock = StartParseBlock<true>(PnodeBlockType::Function, ScopeType_FunctionBody);
  10302. pnodeFnc->sxFnc.pnodeScopes = pnodeBlock;
  10303. m_ppnodeScope = &pnodeBlock->sxBlock.pnodeScopes;
  10304. uint uDeferSave = m_grfscr & fscrDeferFncParse;
  10305. try
  10306. {
  10307. m_pscan->Scan();
  10308. m_ppnodeVar = &pnodeFnc->sxFnc.pnodeParams;
  10309. this->ParseFncFormals<true>(pnodeFnc, pnodeParentFnc, fFncNoFlgs);
  10310. if (m_token.tk == tkRParen)
  10311. {
  10312. m_pscan->Scan();
  10313. }
  10314. ChkCurTok(tkLCurly, ERRnoLcurly);
  10315. m_ppnodeVar = &pnodeFnc->sxFnc.pnodeVars;
  10316. // Put the scanner into "no hashing" mode.
  10317. BYTE deferFlags = m_pscan->SetDeferredParse(topLevelDeferred);
  10318. // Process a sequence of statements/declarations
  10319. if (topLevelDeferred)
  10320. {
  10321. ParseStmtList<false>(nullptr, nullptr, SM_DeferredParse, true);
  10322. }
  10323. else
  10324. {
  10325. ParseNodePtr *lastNodeRef = nullptr;
  10326. ParseStmtList<true>(&pnodeFnc->sxFnc.pnodeBody, &lastNodeRef, SM_OnFunctionCode, true);
  10327. AddArgumentsNodeToVars(pnodeFnc);
  10328. // Append an EndCode node.
  10329. AddToNodeList(&pnodeFnc->sxFnc.pnodeBody, &lastNodeRef, CreateNodeWithScanner<knopEndCode>());
  10330. }
  10331. // Restore the scanner's default hashing mode.
  10332. m_pscan->SetDeferredParseFlags(deferFlags);
  10333. #if DBG
  10334. pnodeFnc->sxFnc.deferredParseNextFunctionId = *this->m_nextFunctionId;
  10335. #endif
  10336. this->m_deferringAST = FALSE;
  10337. // Append block as body of pnodeProg
  10338. FinishParseBlock(pnodeBlock);
  10339. }
  10340. catch(ParseExceptionObject& e)
  10341. {
  10342. hr = e.GetError();
  10343. }
  10344. if (FAILED(hr))
  10345. {
  10346. hr = pse->ProcessError(m_pscan, hr, nullptr);
  10347. }
  10348. if (IsStrictMode())
  10349. {
  10350. pnodeFnc->sxFnc.SetStrictMode();
  10351. }
  10352. if (topLevelDeferred)
  10353. {
  10354. pnodeFnc->sxFnc.pnodeVars = nullptr;
  10355. }
  10356. m_grfscr |= uDeferSave;
  10357. Assert(nullptr == *m_ppnodeScope);
  10358. return hr;
  10359. }
  10360. #endif
  10361. HRESULT Parser::ParseSourceWithOffset(__out ParseNodePtr* parseTree, LPCUTF8 pSrc, size_t offset, size_t cbLength, charcount_t cchOffset,
  10362. bool isCesu8, ULONG grfscr, CompileScriptException *pse, Js::LocalFunctionId * nextFunctionId, ULONG lineNumber, SourceContextInfo * sourceContextInfo,
  10363. Js::ParseableFunctionInfo* functionInfo)
  10364. {
  10365. m_functionBody = functionInfo;
  10366. if (m_functionBody)
  10367. {
  10368. m_currDeferredStub = m_functionBody->GetDeferredStubs();
  10369. m_InAsmMode = grfscr & fscrNoAsmJs ? false : m_functionBody->GetIsAsmjsMode();
  10370. }
  10371. m_deferAsmJs = !m_InAsmMode;
  10372. m_parseType = ParseType_Deferred;
  10373. return ParseSourceInternal( parseTree, pSrc, offset, cbLength, cchOffset, !isCesu8, grfscr, pse, nextFunctionId, lineNumber, sourceContextInfo);
  10374. }
  10375. bool Parser::IsStrictMode() const
  10376. {
  10377. return (m_fUseStrictMode ||
  10378. (m_currentNodeFunc != nullptr && m_currentNodeFunc->sxFnc.GetStrictMode()));
  10379. }
  10380. BOOL Parser::ExpectingExternalSource()
  10381. {
  10382. return m_fExpectExternalSource;
  10383. }
  10384. Symbol *PnFnc::GetFuncSymbol()
  10385. {
  10386. if (pnodeName &&
  10387. pnodeName->nop == knopVarDecl)
  10388. {
  10389. return pnodeName->sxVar.sym;
  10390. }
  10391. return nullptr;
  10392. }
  10393. void PnFnc::SetFuncSymbol(Symbol *sym)
  10394. {
  10395. Assert(pnodeName &&
  10396. pnodeName->nop == knopVarDecl);
  10397. pnodeName->sxVar.sym = sym;
  10398. }
  10399. ParseNodePtr PnFnc::GetParamScope() const
  10400. {
  10401. if (this->pnodeScopes == nullptr)
  10402. {
  10403. return nullptr;
  10404. }
  10405. Assert(this->pnodeScopes->nop == knopBlock &&
  10406. this->pnodeScopes->sxBlock.pnodeNext == nullptr);
  10407. return this->pnodeScopes->sxBlock.pnodeScopes;
  10408. }
  10409. ParseNodePtr PnFnc::GetBodyScope() const
  10410. {
  10411. if (this->pnodeBodyScope == nullptr)
  10412. {
  10413. return nullptr;
  10414. }
  10415. Assert(this->pnodeBodyScope->nop == knopBlock &&
  10416. this->pnodeBodyScope->sxBlock.pnodeNext == nullptr);
  10417. return this->pnodeBodyScope->sxBlock.pnodeScopes;
  10418. }
  10419. // Create node versions with explicit token limits
  10420. ParseNodePtr Parser::CreateNode(OpCode nop, charcount_t ichMin, charcount_t ichLim)
  10421. {
  10422. Assert(!this->m_deferringAST);
  10423. Assert(nop >= 0 && nop < knopLim);
  10424. ParseNodePtr pnode;
  10425. __analysis_assume(nop < knopLim);
  10426. int cb = nop >= 0 && nop < knopLim ? g_mpnopcbNode[nop] : kcbPnNone;
  10427. pnode = (ParseNodePtr)m_nodeAllocator.Alloc(cb);
  10428. Assert(pnode);
  10429. Assert(m_pCurrentAstSize != NULL);
  10430. *m_pCurrentAstSize += cb;
  10431. InitNode(nop,pnode);
  10432. pnode->ichMin = ichMin;
  10433. pnode->ichLim = ichLim;
  10434. return pnode;
  10435. }
  10436. ParseNodePtr Parser::CreateNameNode(IdentPtr pid,charcount_t ichMin,charcount_t ichLim) {
  10437. ParseNodePtr pnode = CreateNodeT<knopName>(ichMin,ichLim);
  10438. pnode->sxPid.pid = pid;
  10439. pnode->sxPid.sym=NULL;
  10440. pnode->sxPid.symRef=NULL;
  10441. return pnode;
  10442. }
  10443. ParseNodePtr Parser::CreateUniNode(OpCode nop, ParseNodePtr pnode1, charcount_t ichMin,charcount_t ichLim)
  10444. {
  10445. Assert(!this->m_deferringAST);
  10446. DebugOnly(VerifyNodeSize(nop, kcbPnUni));
  10447. ParseNodePtr pnode = (ParseNodePtr)m_nodeAllocator.Alloc(kcbPnUni);
  10448. Assert(m_pCurrentAstSize != NULL);
  10449. *m_pCurrentAstSize += kcbPnUni;
  10450. InitNode(nop, pnode);
  10451. pnode->sxUni.pnode1 = pnode1;
  10452. pnode->ichMin = ichMin;
  10453. pnode->ichLim = ichLim;
  10454. return pnode;
  10455. }
  10456. ParseNodePtr Parser::CreateBinNode(OpCode nop, ParseNodePtr pnode1,
  10457. ParseNodePtr pnode2,charcount_t ichMin,charcount_t ichLim)
  10458. {
  10459. Assert(!this->m_deferringAST);
  10460. ParseNodePtr pnode = StaticCreateBinNode(nop, pnode1, pnode2, &m_nodeAllocator);
  10461. Assert(m_pCurrentAstSize != NULL);
  10462. *m_pCurrentAstSize += kcbPnBin;
  10463. pnode->ichMin = ichMin;
  10464. pnode->ichLim = ichLim;
  10465. return pnode;
  10466. }
  10467. ParseNodePtr Parser::CreateTriNode(OpCode nop, ParseNodePtr pnode1,
  10468. ParseNodePtr pnode2, ParseNodePtr pnode3,
  10469. charcount_t ichMin,charcount_t ichLim)
  10470. {
  10471. Assert(!this->m_deferringAST);
  10472. DebugOnly(VerifyNodeSize(nop, kcbPnTri));
  10473. ParseNodePtr pnode = (ParseNodePtr)m_nodeAllocator.Alloc(kcbPnTri);
  10474. Assert(m_pCurrentAstSize != NULL);
  10475. *m_pCurrentAstSize += kcbPnTri;
  10476. InitNode(nop, pnode);
  10477. pnode->sxTri.pnodeNext = NULL;
  10478. pnode->sxTri.pnode1 = pnode1;
  10479. pnode->sxTri.pnode2 = pnode2;
  10480. pnode->sxTri.pnode3 = pnode3;
  10481. pnode->ichMin = ichMin;
  10482. pnode->ichLim = ichLim;
  10483. return pnode;
  10484. }
  10485. bool PnBlock::HasBlockScopedContent() const
  10486. {
  10487. // A block has its own content if a let, const, or function is declared there.
  10488. if (this->pnodeLexVars != nullptr || this->blockType == Parameter)
  10489. {
  10490. return true;
  10491. }
  10492. // The enclosing scopes can contain functions and other things, so walk the list
  10493. // looking specifically for functions.
  10494. for (ParseNodePtr pnode = this->pnodeScopes; pnode;)
  10495. {
  10496. switch (pnode->nop) {
  10497. case knopFncDecl:
  10498. return true;
  10499. case knopBlock:
  10500. pnode = pnode->sxBlock.pnodeNext;
  10501. break;
  10502. case knopCatch:
  10503. pnode = pnode->sxCatch.pnodeNext;
  10504. break;
  10505. case knopWith:
  10506. pnode = pnode->sxWith.pnodeNext;
  10507. break;
  10508. default:
  10509. Assert(UNREACHED);
  10510. return true;
  10511. }
  10512. }
  10513. return false;
  10514. }
  10515. class ByteCodeGenerator;
  10516. // Copy AST; this works mostly on expressions for now
  10517. ParseNode* Parser::CopyPnode(ParseNode *pnode) {
  10518. if (pnode==NULL)
  10519. return NULL;
  10520. switch (pnode->nop) {
  10521. //PTNODE(knopName , "name" ,None ,Pid ,fnopLeaf)
  10522. case knopName: {
  10523. ParseNode* nameNode=CreateNameNode(pnode->sxPid.pid,pnode->ichMin,pnode->ichLim);
  10524. nameNode->sxPid.sym=pnode->sxPid.sym;
  10525. return nameNode;
  10526. }
  10527. //PTNODE(knopInt , "int const" ,None ,Int ,fnopLeaf|fnopConst)
  10528. case knopInt:
  10529. return pnode;
  10530. //PTNODE(knopFlt , "flt const" ,None ,Flt ,fnopLeaf|fnopConst)
  10531. case knopFlt:
  10532. return pnode;
  10533. //PTNODE(knopStr , "str const" ,None ,Pid ,fnopLeaf|fnopConst)
  10534. case knopStr:
  10535. return pnode;
  10536. //PTNODE(knopRegExp , "reg expr" ,None ,Pid ,fnopLeaf|fnopConst)
  10537. case knopRegExp:
  10538. return pnode;
  10539. break;
  10540. //PTNODE(knopNull , "null" ,Null ,None ,fnopLeaf)
  10541. case knopNull:
  10542. return pnode;
  10543. //PTNODE(knopFalse , "false" ,False ,None ,fnopLeaf)
  10544. case knopFalse:
  10545. {
  10546. ParseNode* ret = CreateNodeT<knopFalse>(pnode->ichMin, pnode->ichLim);
  10547. ret->location = pnode->location;
  10548. return ret;
  10549. }
  10550. //PTNODE(knopTrue , "true" ,True ,None ,fnopLeaf)
  10551. case knopTrue:
  10552. {
  10553. ParseNode* ret = CreateNodeT<knopTrue>(pnode->ichMin, pnode->ichLim);
  10554. ret->location = pnode->location;
  10555. return ret;
  10556. }
  10557. //PTNODE(knopEmpty , "empty" ,Empty ,None ,fnopLeaf)
  10558. case knopEmpty:
  10559. return CreateNodeT<knopEmpty>(pnode->ichMin,pnode->ichLim);
  10560. // Unary operators.
  10561. //PTNODE(knopNot , "~" ,BitNot ,Uni ,fnopUni)
  10562. //PTNODE(knopNeg , "unary -" ,Neg ,Uni ,fnopUni)
  10563. //PTNODE(knopPos , "unary +" ,Pos ,Uni ,fnopUni)
  10564. //PTNODE(knopLogNot , "!" ,LogNot ,Uni ,fnopUni)
  10565. //PTNODE(knopEllipsis , "..." ,Spread ,Uni , fnopUni)
  10566. //PTNODE(knopDecPost , "-- post" ,Dec ,Uni ,fnopUni|fnopAsg)
  10567. //PTNODE(knopIncPre , "++ pre" ,Inc ,Uni ,fnopUni|fnopAsg)
  10568. //PTNODE(knopDecPre , "-- pre" ,Dec ,Uni ,fnopUni|fnopAsg)
  10569. //PTNODE(knopTypeof , "typeof" ,None ,Uni ,fnopUni)
  10570. //PTNODE(knopVoid , "void" ,Void ,Uni ,fnopUni)
  10571. //PTNODE(knopDelete , "delete" ,None ,Uni ,fnopUni)
  10572. case knopNot:
  10573. case knopNeg:
  10574. case knopPos:
  10575. case knopLogNot:
  10576. case knopEllipsis:
  10577. case knopIncPost:
  10578. case knopDecPost:
  10579. case knopIncPre:
  10580. case knopDecPre:
  10581. case knopTypeof:
  10582. case knopVoid:
  10583. case knopDelete:
  10584. return CreateUniNode(pnode->nop,CopyPnode(pnode->sxUni.pnode1),pnode->ichMin,pnode->ichLim);
  10585. //PTNODE(knopArray , "arr cnst" ,None ,Uni ,fnopUni)
  10586. //PTNODE(knopObject , "obj cnst" ,None ,Uni ,fnopUni)
  10587. case knopArray:
  10588. case knopObject:
  10589. // TODO: need to copy arr
  10590. Assert(false);
  10591. break;
  10592. // Binary operators
  10593. //PTNODE(knopAdd , "+" ,Add ,Bin ,fnopBin)
  10594. //PTNODE(knopSub , "-" ,Sub ,Bin ,fnopBin)
  10595. //PTNODE(knopMul , "*" ,Mul ,Bin ,fnopBin)
  10596. //PTNODE(knopExpo , "**" ,Expo ,Bin ,fnopBin)
  10597. //PTNODE(knopDiv , "/" ,Div ,Bin ,fnopBin)
  10598. //PTNODE(knopMod , "%" ,Mod ,Bin ,fnopBin)
  10599. //PTNODE(knopOr , "|" ,BitOr ,Bin ,fnopBin)
  10600. //PTNODE(knopXor , "^" ,BitXor ,Bin ,fnopBin)
  10601. //PTNODE(knopAnd , "&" ,BitAnd ,Bin ,fnopBin)
  10602. //PTNODE(knopEq , "==" ,EQ ,Bin ,fnopBin|fnopRel)
  10603. //PTNODE(knopNe , "!=" ,NE ,Bin ,fnopBin|fnopRel)
  10604. //PTNODE(knopLt , "<" ,LT ,Bin ,fnopBin|fnopRel)
  10605. //PTNODE(knopLe , "<=" ,LE ,Bin ,fnopBin|fnopRel)
  10606. //PTNODE(knopGe , ">=" ,GE ,Bin ,fnopBin|fnopRel)
  10607. //PTNODE(knopGt , ">" ,GT ,Bin ,fnopBin|fnopRel)
  10608. //PTNODE(knopEqv , "===" ,Eqv ,Bin ,fnopBin|fnopRel)
  10609. //PTNODE(knopIn , "in" ,In ,Bin ,fnopBin|fnopRel)
  10610. //PTNODE(knopInstOf , "instanceof",InstOf ,Bin ,fnopBin|fnopRel)
  10611. //PTNODE(knopNEqv , "!==" ,NEqv ,Bin ,fnopBin|fnopRel)
  10612. //PTNODE(knopComma , "," ,None ,Bin ,fnopBin)
  10613. //PTNODE(knopLogOr , "||" ,None ,Bin ,fnopBin)
  10614. //PTNODE(knopLogAnd , "&&" ,None ,Bin ,fnopBin)
  10615. //PTNODE(knopLsh , "<<" ,Lsh ,Bin ,fnopBin)
  10616. //PTNODE(knopRsh , ">>" ,Rsh ,Bin ,fnopBin)
  10617. //PTNODE(knopRs2 , ">>>" ,Rs2 ,Bin ,fnopBin)
  10618. case knopAdd:
  10619. case knopSub:
  10620. case knopMul:
  10621. case knopExpo:
  10622. case knopDiv:
  10623. case knopMod:
  10624. case knopOr:
  10625. case knopXor:
  10626. case knopAnd:
  10627. case knopEq:
  10628. case knopNe:
  10629. case knopLt:
  10630. case knopLe:
  10631. case knopGe:
  10632. case knopGt:
  10633. case knopEqv:
  10634. case knopIn:
  10635. case knopInstOf:
  10636. case knopNEqv:
  10637. case knopComma:
  10638. case knopLogOr:
  10639. case knopLogAnd:
  10640. case knopLsh:
  10641. case knopRsh:
  10642. case knopRs2:
  10643. //PTNODE(knopAsg , "=" ,None ,Bin ,fnopBin|fnopAsg)
  10644. case knopAsg:
  10645. //PTNODE(knopDot , "." ,None ,Bin ,fnopBin)
  10646. case knopDot:
  10647. //PTNODE(knopAsgAdd , "+=" ,Add ,Bin ,fnopBin|fnopAsg)
  10648. case knopAsgAdd:
  10649. //PTNODE(knopAsgSub , "-=" ,Sub ,Bin ,fnopBin|fnopAsg)
  10650. case knopAsgSub:
  10651. //PTNODE(knopAsgMul , "*=" ,Mul ,Bin ,fnopBin|fnopAsg)
  10652. case knopAsgMul:
  10653. //PTNODE(knopAsgDiv , "/=" ,Div ,Bin ,fnopBin|fnopAsg)
  10654. case knopAsgExpo:
  10655. //PTNODE(knopAsgExpo , "**=" ,Expo ,Bin ,fnopBin|fnopAsg)
  10656. case knopAsgDiv:
  10657. //PTNODE(knopAsgMod , "%=" ,Mod ,Bin ,fnopBin|fnopAsg)
  10658. case knopAsgMod:
  10659. //PTNODE(knopAsgAnd , "&=" ,BitAnd ,Bin ,fnopBin|fnopAsg)
  10660. case knopAsgAnd:
  10661. //PTNODE(knopAsgXor , "^=" ,BitXor ,Bin ,fnopBin|fnopAsg)
  10662. case knopAsgXor:
  10663. //PTNODE(knopAsgOr , "|=" ,BitOr ,Bin ,fnopBin|fnopAsg)
  10664. case knopAsgOr:
  10665. //PTNODE(knopAsgLsh , "<<=" ,Lsh ,Bin ,fnopBin|fnopAsg)
  10666. case knopAsgLsh:
  10667. //PTNODE(knopAsgRsh , ">>=" ,Rsh ,Bin ,fnopBin|fnopAsg)
  10668. case knopAsgRsh:
  10669. //PTNODE(knopAsgRs2 , ">>>=" ,Rs2 ,Bin ,fnopBin|fnopAsg)
  10670. case knopAsgRs2:
  10671. //PTNODE(knopMember , ":" ,None ,Bin ,fnopBin)
  10672. case knopMember:
  10673. case knopMemberShort:
  10674. //PTNODE(knopIndex , "[]" ,None ,Bin ,fnopBin)
  10675. //PTNODE(knopList , "<list>" ,None ,Bin ,fnopNone)
  10676. case knopIndex:
  10677. case knopList:
  10678. return CreateBinNode(pnode->nop,CopyPnode(pnode->sxBin.pnode1),
  10679. CopyPnode(pnode->sxBin.pnode2),pnode->ichMin,pnode->ichLim);
  10680. //PTNODE(knopCall , "()" ,None ,Bin ,fnopBin)
  10681. //PTNODE(knopNew , "new" ,None ,Bin ,fnopBin)
  10682. case knopNew:
  10683. case knopCall:
  10684. return CreateCallNode(pnode->nop,CopyPnode(pnode->sxCall.pnodeTarget),
  10685. CopyPnode(pnode->sxCall.pnodeArgs),pnode->ichMin,pnode->ichLim);
  10686. //PTNODE(knopQmark , "?" ,None ,Tri ,fnopBin)
  10687. case knopQmark:
  10688. return CreateTriNode(pnode->nop,CopyPnode(pnode->sxTri.pnode1),
  10689. CopyPnode(pnode->sxTri.pnode2),CopyPnode(pnode->sxTri.pnode3),
  10690. pnode->ichMin,pnode->ichLim);
  10691. // General nodes.
  10692. //PTNODE(knopVarDecl , "varDcl" ,None ,Var ,fnopNone)
  10693. case knopVarDecl: {
  10694. ParseNode* copyNode=CreateNodeT<knopVarDecl>(pnode->ichMin,pnode->ichLim);
  10695. copyNode->sxVar.pnodeInit=CopyPnode(pnode->sxVar.pnodeInit);
  10696. copyNode->sxVar.sym=pnode->sxVar.sym;
  10697. // TODO: mult-decl
  10698. Assert(pnode->sxVar.pnodeNext==NULL);
  10699. copyNode->sxVar.pnodeNext=NULL;
  10700. return copyNode;
  10701. }
  10702. //PTNODE(knopFncDecl , "fncDcl" ,None ,Fnc ,fnopLeaf)
  10703. //PTNODE(knopProg , "program" ,None ,Fnc ,fnopNone)
  10704. case knopFncDecl:
  10705. case knopProg:
  10706. Assert(false);
  10707. break;
  10708. //PTNODE(knopEndCode , "<endcode>" ,None ,None ,fnopNone)
  10709. case knopEndCode:
  10710. break;
  10711. //PTNODE(knopDebugger , "debugger" ,None ,None ,fnopNone)
  10712. case knopDebugger:
  10713. break;
  10714. //PTNODE(knopFor , "for" ,None ,For ,fnopBreak|fnopContinue)
  10715. case knopFor: {
  10716. ParseNode* copyNode=CreateNodeT<knopFor>(pnode->ichMin,pnode->ichLim);
  10717. copyNode->sxFor.pnodeInverted=NULL;
  10718. copyNode->sxFor.pnodeInit=CopyPnode(pnode->sxFor.pnodeInit);
  10719. copyNode->sxFor.pnodeCond=CopyPnode(pnode->sxFor.pnodeCond);
  10720. copyNode->sxFor.pnodeIncr=CopyPnode(pnode->sxFor.pnodeIncr);
  10721. copyNode->sxFor.pnodeBody=CopyPnode(pnode->sxFor.pnodeBody);
  10722. return copyNode;
  10723. }
  10724. //PTNODE(knopIf , "if" ,None ,If ,fnopNone)
  10725. case knopIf:
  10726. Assert(false);
  10727. break;
  10728. //PTNODE(knopWhile , "while" ,None ,While,fnopBreak|fnopContinue)
  10729. case knopWhile:
  10730. Assert(false);
  10731. break;
  10732. //PTNODE(knopDoWhile , "do-while" ,None ,While,fnopBreak|fnopContinue)
  10733. case knopDoWhile:
  10734. Assert(false);
  10735. break;
  10736. //PTNODE(knopForIn , "for in" ,None ,ForIn,fnopBreak|fnopContinue|fnopCleanup)
  10737. case knopForIn:
  10738. Assert(false);
  10739. break;
  10740. case knopForOf:
  10741. Assert(false);
  10742. break;
  10743. //PTNODE(knopReturn , "return" ,None ,Uni ,fnopNone)
  10744. case knopReturn: {
  10745. ParseNode* copyNode=CreateNodeT<knopReturn>(pnode->ichMin,pnode->ichLim);
  10746. copyNode->sxReturn.pnodeExpr=CopyPnode(pnode->sxReturn.pnodeExpr);
  10747. return copyNode;
  10748. }
  10749. //PTNODE(knopBlock , "{}" ,None ,Block,fnopNone)
  10750. case knopBlock: {
  10751. ParseNode* copyNode=CreateBlockNode(pnode->ichMin,pnode->ichLim,pnode->sxBlock.blockType);
  10752. if (pnode->grfpn & PNodeFlags::fpnSyntheticNode) {
  10753. // fpnSyntheticNode is sometimes set on PnodeBlockType::Regular blocks which
  10754. // CreateBlockNode() will not automatically set for us, so set it here if it's
  10755. // specified on the source node.
  10756. copyNode->grfpn |= PNodeFlags::fpnSyntheticNode;
  10757. }
  10758. copyNode->sxBlock.pnodeStmt=CopyPnode(pnode->sxBlock.pnodeStmt);
  10759. return copyNode;
  10760. }
  10761. //PTNODE(knopWith , "with" ,None ,With ,fnopCleanup)
  10762. case knopWith:
  10763. Assert(false);
  10764. break;
  10765. //PTNODE(knopBreak , "break" ,None ,Jump ,fnopNone)
  10766. case knopBreak:
  10767. Assert(false);
  10768. break;
  10769. //PTNODE(knopContinue , "continue" ,None ,Jump ,fnopNone)
  10770. case knopContinue:
  10771. Assert(false);
  10772. break;
  10773. //PTNODE(knopLabel , "label" ,None ,Label,fnopNone)
  10774. case knopLabel:
  10775. Assert(false);
  10776. break;
  10777. //PTNODE(knopSwitch , "switch" ,None ,Switch,fnopBreak)
  10778. case knopSwitch:
  10779. Assert(false);
  10780. break;
  10781. //PTNODE(knopCase , "case" ,None ,Case ,fnopNone)
  10782. case knopCase:
  10783. Assert(false);
  10784. break;
  10785. //PTNODE(knopTryFinally,"try-finally",None,TryFinally,fnopCleanup)
  10786. case knopTryFinally:
  10787. Assert(false);
  10788. break;
  10789. case knopFinally:
  10790. Assert(false);
  10791. break;
  10792. //PTNODE(knopCatch , "catch" ,None ,Catch,fnopNone)
  10793. case knopCatch:
  10794. Assert(false);
  10795. break;
  10796. //PTNODE(knopTryCatch , "try-catch" ,None ,TryCatch ,fnopCleanup)
  10797. case knopTryCatch:
  10798. Assert(false);
  10799. break;
  10800. //PTNODE(knopTry , "try" ,None ,Try ,fnopCleanup)
  10801. case knopTry:
  10802. Assert(false);
  10803. break;
  10804. //PTNODE(knopThrow , "throw" ,None ,Uni ,fnopNone)
  10805. case knopThrow:
  10806. Assert(false);
  10807. break;
  10808. default:
  10809. Assert(false);
  10810. break;
  10811. }
  10812. return NULL;
  10813. }
  10814. // Returns true when str is string for Nan, Infinity or -Infinity.
  10815. // Does not check for double number value being in NaN/Infinity range.
  10816. // static
  10817. template<bool CheckForNegativeInfinity>
  10818. inline bool Parser::IsNaNOrInfinityLiteral(LPCOLESTR str)
  10819. {
  10820. // Note: wcscmp crashes when one of the parameters is NULL.
  10821. return str &&
  10822. (wcscmp(_u("NaN"), str) == 0 ||
  10823. wcscmp(_u("Infinity"), str) == 0 ||
  10824. (CheckForNegativeInfinity && wcscmp(_u("-Infinity"), str) == 0));
  10825. }
  10826. template <bool buildAST>
  10827. IdentPtr Parser::ParseSuper(bool fAllowCall)
  10828. {
  10829. ParseNodePtr currentNodeFunc = GetCurrentFunctionNode();
  10830. IdentPtr superPid = nullptr;
  10831. switch (m_token.tk)
  10832. {
  10833. case tkDot: // super.prop
  10834. case tkLBrack: // super[foo]
  10835. superPid = wellKnownPropertyPids._super;
  10836. break;
  10837. case tkLParen: // super(args)
  10838. superPid = wellKnownPropertyPids._superConstructor;
  10839. break;
  10840. default:
  10841. Error(ERRInvalidSuper);
  10842. break;
  10843. }
  10844. if (!fAllowCall && (m_token.tk == tkLParen))
  10845. {
  10846. Error(ERRInvalidSuper); // new super() is not allowed
  10847. }
  10848. else if (this->m_parsingSuperRestrictionState == ParsingSuperRestrictionState_SuperCallAndPropertyAllowed)
  10849. {
  10850. // Any super access is good within a class constructor
  10851. }
  10852. else if (this->m_parsingSuperRestrictionState == ParsingSuperRestrictionState_SuperPropertyAllowed)
  10853. {
  10854. if (m_token.tk == tkLParen)
  10855. {
  10856. if ((this->m_grfscr & fscrEval) == fscrNil)
  10857. {
  10858. // Cannot call super within a class member
  10859. Error(ERRInvalidSuper);
  10860. }
  10861. else
  10862. {
  10863. Js::JavascriptFunction * caller = nullptr;
  10864. if (Js::JavascriptStackWalker::GetCaller(&caller, m_scriptContext))
  10865. {
  10866. Js::FunctionBody * callerBody = caller->GetFunctionBody();
  10867. Assert(callerBody);
  10868. if (!callerBody->GetFunctionInfo()->GetAllowDirectSuper())
  10869. {
  10870. Error(ERRInvalidSuper);
  10871. }
  10872. }
  10873. }
  10874. }
  10875. }
  10876. else
  10877. {
  10878. // Anything else is an error
  10879. Error(ERRInvalidSuper);
  10880. }
  10881. currentNodeFunc->sxFnc.SetHasSuperReference(TRUE);
  10882. CHAKRATEL_LANGSTATS_INC_LANGFEATURECOUNT(Super, m_scriptContext);
  10883. return superPid;
  10884. }
  10885. void Parser::AppendToList(ParseNodePtr *node, ParseNodePtr nodeToAppend)
  10886. {
  10887. Assert(nodeToAppend);
  10888. ParseNodePtr* lastPtr = node;
  10889. while ((*lastPtr) && (*lastPtr)->nop == knopList)
  10890. {
  10891. lastPtr = &(*lastPtr)->sxBin.pnode2;
  10892. }
  10893. auto last = (*lastPtr);
  10894. if (last)
  10895. {
  10896. *lastPtr = CreateBinNode(knopList, last, nodeToAppend, last->ichMin, nodeToAppend->ichLim);
  10897. }
  10898. else
  10899. {
  10900. *lastPtr = nodeToAppend;
  10901. }
  10902. }
  10903. ParseNodePtr Parser::ConvertArrayToArrayPattern(ParseNodePtr pnode)
  10904. {
  10905. Assert(pnode->nop == knopArray);
  10906. pnode->nop = knopArrayPattern;
  10907. ForEachItemRefInList(&pnode->sxArrLit.pnode1, [&](ParseNodePtr *itemRef) {
  10908. ParseNodePtr item = *itemRef;
  10909. if (item->nop == knopEllipsis)
  10910. {
  10911. itemRef = &item->sxUni.pnode1;
  10912. item = *itemRef;
  10913. if (!(item->nop == knopName
  10914. || item->nop == knopDot
  10915. || item->nop == knopIndex
  10916. || item->nop == knopArray
  10917. || item->nop == knopObject))
  10918. {
  10919. Error(ERRInvalidAssignmentTarget);
  10920. }
  10921. }
  10922. else if (item->nop == knopAsg)
  10923. {
  10924. itemRef = &item->sxBin.pnode1;
  10925. item = *itemRef;
  10926. }
  10927. if (item->nop == knopArray)
  10928. {
  10929. ConvertArrayToArrayPattern(item);
  10930. }
  10931. else if (item->nop == knopObject)
  10932. {
  10933. *itemRef = ConvertObjectToObjectPattern(item);
  10934. }
  10935. else if (item->nop == knopName)
  10936. {
  10937. TrackAssignment<true>(item, nullptr);
  10938. }
  10939. });
  10940. return pnode;
  10941. }
  10942. ParseNodePtr Parser::CreateParamPatternNode(ParseNodePtr pnode1)
  10943. {
  10944. ParseNodePtr paramPatternNode = CreateNode(knopParamPattern, pnode1->ichMin, pnode1->ichLim);
  10945. paramPatternNode->sxParamPattern.pnode1 = pnode1;
  10946. paramPatternNode->sxParamPattern.pnodeNext = nullptr;
  10947. paramPatternNode->sxParamPattern.location = Js::Constants::NoRegister;
  10948. return paramPatternNode;
  10949. }
  10950. ParseNodePtr Parser::CreateDummyParamPatternNode(charcount_t ichMin)
  10951. {
  10952. ParseNodePtr paramPatternNode = CreateNode(knopParamPattern, ichMin);
  10953. paramPatternNode->sxParamPattern.pnode1 = nullptr;
  10954. paramPatternNode->sxParamPattern.pnodeNext = nullptr;
  10955. paramPatternNode->sxParamPattern.location = Js::Constants::NoRegister;
  10956. return paramPatternNode;
  10957. }
  10958. ParseNodePtr Parser::ConvertObjectToObjectPattern(ParseNodePtr pnodeMemberList)
  10959. {
  10960. charcount_t ichMin = m_pscan->IchMinTok();
  10961. charcount_t ichLim = m_pscan->IchLimTok();
  10962. ParseNodePtr pnodeMemberNodeList = nullptr;
  10963. if (pnodeMemberList != nullptr && pnodeMemberList->nop == knopObject)
  10964. {
  10965. ichMin = pnodeMemberList->ichMin;
  10966. ichLim = pnodeMemberList->ichLim;
  10967. pnodeMemberList = pnodeMemberList->sxUni.pnode1;
  10968. }
  10969. ForEachItemInList(pnodeMemberList, [&](ParseNodePtr item) {
  10970. ParseNodePtr memberNode = ConvertMemberToMemberPattern(item);
  10971. AppendToList(&pnodeMemberNodeList, memberNode);
  10972. });
  10973. return CreateUniNode(knopObjectPattern, pnodeMemberNodeList, ichMin, ichLim);
  10974. }
  10975. ParseNodePtr Parser::GetRightSideNodeFromPattern(ParseNodePtr pnode)
  10976. {
  10977. Assert(pnode != nullptr);
  10978. ParseNodePtr rightNode = nullptr;
  10979. OpCode op = pnode->nop;
  10980. if (op == knopObject)
  10981. {
  10982. rightNode = ConvertObjectToObjectPattern(pnode);
  10983. }
  10984. else if (op == knopArray)
  10985. {
  10986. rightNode = ConvertArrayToArrayPattern(pnode);
  10987. }
  10988. else
  10989. {
  10990. rightNode = pnode;
  10991. if (op == knopName)
  10992. {
  10993. TrackAssignment<true>(pnode, nullptr);
  10994. }
  10995. }
  10996. return rightNode;
  10997. }
  10998. ParseNodePtr Parser::ConvertMemberToMemberPattern(ParseNodePtr pnodeMember)
  10999. {
  11000. if (pnodeMember->nop == knopObjectPatternMember)
  11001. {
  11002. return pnodeMember;
  11003. }
  11004. Assert(pnodeMember->nop == knopMember || pnodeMember->nop == knopMemberShort);
  11005. ParseNodePtr rightNode = GetRightSideNodeFromPattern(pnodeMember->sxBin.pnode2);
  11006. ParseNodePtr resultNode = CreateBinNode(knopObjectPatternMember, pnodeMember->sxBin.pnode1, rightNode);
  11007. resultNode->ichMin = pnodeMember->ichMin;
  11008. resultNode->ichLim = pnodeMember->ichLim;
  11009. return resultNode;
  11010. }
  11011. ParseNodePtr Parser::ConvertToPattern(ParseNodePtr pnode)
  11012. {
  11013. if (pnode != nullptr)
  11014. {
  11015. if (pnode->nop == knopArray)
  11016. {
  11017. ConvertArrayToArrayPattern(pnode);
  11018. }
  11019. else if (pnode->nop == knopObject)
  11020. {
  11021. pnode = ConvertObjectToObjectPattern(pnode);
  11022. }
  11023. }
  11024. return pnode;
  11025. }
  11026. // This essentially be called for verifying the structure of the current tree with satisfying the destructuring grammar.
  11027. void Parser::ParseDestructuredLiteralWithScopeSave(tokens declarationType,
  11028. bool isDecl,
  11029. bool topLevel,
  11030. DestructuringInitializerContext initializerContext/* = DIC_None*/,
  11031. bool allowIn /*= true*/)
  11032. {
  11033. // We are going to parse the text again to validate the current grammar as Destructuring. Saving some scopes and
  11034. // AST related information before the validation parsing and later they will be restored.
  11035. ParseNodePtr pnodeFncSave = m_currentNodeFunc;
  11036. ParseNodePtr pnodeDeferredFncSave = m_currentNodeDeferredFunc;
  11037. if (m_currentNodeDeferredFunc == nullptr)
  11038. {
  11039. m_currentNodeDeferredFunc = m_currentNodeFunc;
  11040. }
  11041. int32 *pAstSizeSave = m_pCurrentAstSize;
  11042. uint *pNestedCountSave = m_pnestedCount;
  11043. ParseNodePtr *ppnodeScopeSave = m_ppnodeScope;
  11044. ParseNodePtr *ppnodeExprScopeSave = m_ppnodeExprScope;
  11045. ParseNodePtr newTempScope = nullptr;
  11046. m_ppnodeScope = &newTempScope;
  11047. int32 newTempAstSize = 0;
  11048. m_pCurrentAstSize = &newTempAstSize;
  11049. uint newTempNestedCount = 0;
  11050. m_pnestedCount = &newTempNestedCount;
  11051. m_ppnodeExprScope = nullptr;
  11052. charcount_t funcInArraySave = m_funcInArray;
  11053. uint funcInArrayDepthSave = m_funcInArrayDepth;
  11054. // we need to reset this as we are going to parse the grammar again.
  11055. m_hasDeferredShorthandInitError = false;
  11056. ParseDestructuredLiteral<false>(declarationType, isDecl, topLevel, initializerContext, allowIn);
  11057. m_currentNodeFunc = pnodeFncSave;
  11058. m_currentNodeDeferredFunc = pnodeDeferredFncSave;
  11059. m_pCurrentAstSize = pAstSizeSave;
  11060. m_pnestedCount = pNestedCountSave;
  11061. m_ppnodeScope = ppnodeScopeSave;
  11062. m_ppnodeExprScope = ppnodeExprScopeSave;
  11063. m_funcInArray = funcInArraySave;
  11064. m_funcInArrayDepth = funcInArrayDepthSave;
  11065. }
  11066. template <bool buildAST>
  11067. ParseNodePtr Parser::ParseDestructuredLiteral(tokens declarationType,
  11068. bool isDecl,
  11069. bool topLevel/* = true*/,
  11070. DestructuringInitializerContext initializerContext/* = DIC_None*/,
  11071. bool allowIn/* = true*/,
  11072. BOOL *forInOfOkay/* = nullptr*/,
  11073. BOOL *nativeForOkay/* = nullptr*/)
  11074. {
  11075. ParseNodePtr pnode = nullptr;
  11076. Assert(IsPossiblePatternStart());
  11077. if (m_token.tk == tkLCurly)
  11078. {
  11079. pnode = ParseDestructuredObjectLiteral<buildAST>(declarationType, isDecl, topLevel);
  11080. }
  11081. else
  11082. {
  11083. pnode = ParseDestructuredArrayLiteral<buildAST>(declarationType, isDecl, topLevel);
  11084. }
  11085. return ParseDestructuredInitializer<buildAST>(pnode, isDecl, topLevel, initializerContext, allowIn, forInOfOkay, nativeForOkay);
  11086. }
  11087. template <bool buildAST>
  11088. ParseNodePtr Parser::ParseDestructuredInitializer(ParseNodePtr lhsNode,
  11089. bool isDecl,
  11090. bool topLevel,
  11091. DestructuringInitializerContext initializerContext,
  11092. bool allowIn,
  11093. BOOL *forInOfOkay,
  11094. BOOL *nativeForOkay)
  11095. {
  11096. m_pscan->Scan();
  11097. if (topLevel && nativeForOkay == nullptr)
  11098. {
  11099. if (initializerContext != DIC_ForceErrorOnInitializer && m_token.tk != tkAsg)
  11100. {
  11101. // e.g. var {x};
  11102. Error(ERRDestructInit);
  11103. }
  11104. else if (initializerContext == DIC_ForceErrorOnInitializer && m_token.tk == tkAsg)
  11105. {
  11106. // e.g. catch([x] = [0])
  11107. Error(ERRDestructNotInit);
  11108. }
  11109. }
  11110. if (m_token.tk != tkAsg || initializerContext == DIC_ShouldNotParseInitializer)
  11111. {
  11112. if (topLevel && nativeForOkay != nullptr)
  11113. {
  11114. // Native loop should have destructuring initializer
  11115. *nativeForOkay = FALSE;
  11116. }
  11117. return lhsNode;
  11118. }
  11119. if (forInOfOkay)
  11120. {
  11121. *forInOfOkay = FALSE;
  11122. }
  11123. m_pscan->Scan();
  11124. bool alreadyHasInitError = m_hasDeferredShorthandInitError;
  11125. ParseNodePtr pnodeDefault = ParseExpr<buildAST>(koplCma, nullptr, allowIn);
  11126. if (m_hasDeferredShorthandInitError && !alreadyHasInitError)
  11127. {
  11128. Error(ERRnoColon);
  11129. }
  11130. ParseNodePtr pnodeDestructAsg = nullptr;
  11131. if (buildAST)
  11132. {
  11133. Assert(lhsNode != nullptr);
  11134. pnodeDestructAsg = CreateNodeWithScanner<knopAsg>();
  11135. pnodeDestructAsg->sxBin.pnode1 = lhsNode;
  11136. pnodeDestructAsg->sxBin.pnode2 = pnodeDefault;
  11137. pnodeDestructAsg->ichMin = lhsNode->ichMin;
  11138. pnodeDestructAsg->ichLim = pnodeDefault->ichLim;
  11139. }
  11140. return pnodeDestructAsg;
  11141. }
  11142. template <bool buildAST>
  11143. ParseNodePtr Parser::ParseDestructuredObjectLiteral(tokens declarationType, bool isDecl, bool topLevel/* = true*/)
  11144. {
  11145. Assert(m_token.tk == tkLCurly);
  11146. charcount_t ichMin = m_pscan->IchMinTok();
  11147. m_pscan->Scan();
  11148. if (!isDecl)
  11149. {
  11150. declarationType = tkLCurly;
  11151. }
  11152. ParseNodePtr pnodeMemberList = ParseMemberList<buildAST>(nullptr/*pNameHint*/, nullptr/*pHintLength*/, declarationType);
  11153. Assert(m_token.tk == tkRCurly);
  11154. ParseNodePtr objectPatternNode = nullptr;
  11155. if (buildAST)
  11156. {
  11157. charcount_t ichLim = m_pscan->IchLimTok();
  11158. objectPatternNode = CreateUniNode(knopObjectPattern, pnodeMemberList, ichMin, ichLim);
  11159. }
  11160. return objectPatternNode;
  11161. }
  11162. template <bool buildAST>
  11163. ParseNodePtr Parser::ParseDestructuredVarDecl(tokens declarationType, bool isDecl, bool *hasSeenRest, bool topLevel/* = true*/, bool allowEmptyExpression/* = true*/)
  11164. {
  11165. ParseNodePtr pnodeElem = nullptr;
  11166. int parenCount = 0;
  11167. bool seenRest = false;
  11168. // Save the Block ID prior to the increments, so we can restore it back.
  11169. int originalCurrentBlockId = GetCurrentBlock()->sxBlock.blockId;
  11170. // Eat the left parentheses only when its not a declaration. This will make sure we throw syntax errors early.
  11171. if (!isDecl)
  11172. {
  11173. while (m_token.tk == tkLParen)
  11174. {
  11175. m_pscan->Scan();
  11176. ++parenCount;
  11177. // Match the block increment we do upon entering parenthetical expressions
  11178. // so that the block ID's will match on reparsing of parameters.
  11179. GetCurrentBlock()->sxBlock.blockId = m_nextBlockId++;
  11180. }
  11181. }
  11182. if (m_token.tk == tkEllipsis)
  11183. {
  11184. // As per ES 2015 : Rest can have left-hand-side-expression when on assignment expression, but under declaration only binding identifier is allowed
  11185. // But spec is going to change for this one to allow LHS-expression both on expression and declaration - so making that happen early.
  11186. seenRest = true;
  11187. m_pscan->Scan();
  11188. // Eat the left parentheses only when its not a declaration. This will make sure we throw syntax errors early.
  11189. if (!isDecl)
  11190. {
  11191. while (m_token.tk == tkLParen)
  11192. {
  11193. m_pscan->Scan();
  11194. ++parenCount;
  11195. // Match the block increment we do upon entering parenthetical expressions
  11196. // so that the block ID's will match on reparsing of parameters.
  11197. GetCurrentBlock()->sxBlock.blockId = m_nextBlockId++;
  11198. }
  11199. }
  11200. if (m_token.tk != tkID && m_token.tk != tkTHIS && m_token.tk != tkSUPER && m_token.tk != tkLCurly && m_token.tk != tkLBrack)
  11201. {
  11202. if (isDecl)
  11203. {
  11204. Error(ERRnoIdent);
  11205. }
  11206. else
  11207. {
  11208. Error(ERRInvalidAssignmentTarget);
  11209. }
  11210. }
  11211. }
  11212. if (IsPossiblePatternStart())
  11213. {
  11214. // Go recursively
  11215. pnodeElem = ParseDestructuredLiteral<buildAST>(declarationType, isDecl, false /*topLevel*/, seenRest ? DIC_ShouldNotParseInitializer : DIC_None);
  11216. if (!isDecl)
  11217. {
  11218. BOOL fCanAssign;
  11219. IdentToken token;
  11220. // Look for postfix operator
  11221. pnodeElem = ParsePostfixOperators<buildAST>(pnodeElem, TRUE, FALSE, FALSE, &fCanAssign, &token);
  11222. }
  11223. }
  11224. else if (m_token.tk == tkSUPER || m_token.tk == tkID || m_token.tk == tkTHIS)
  11225. {
  11226. if (isDecl)
  11227. {
  11228. charcount_t ichMin = m_pscan->IchMinTok();
  11229. pnodeElem = ParseVariableDeclaration<buildAST>(declarationType, ichMin
  11230. ,/* fAllowIn */false, /* pfForInOk */nullptr, /* singleDefOnly */true, /* allowInit */!seenRest, false /*topLevelParse*/);
  11231. }
  11232. else
  11233. {
  11234. BOOL fCanAssign;
  11235. IdentToken token;
  11236. // We aren't declaring anything, so scan the ID reference manually.
  11237. pnodeElem = ParseTerm<buildAST>(/* fAllowCall */ m_token.tk != tkSUPER, nullptr /*pNameHint*/, nullptr /*pHintLength*/, nullptr /*pShortNameOffset*/, &token, false,
  11238. &fCanAssign);
  11239. // In this destructuring case we can force error here as we cannot assign.
  11240. if (!fCanAssign)
  11241. {
  11242. Error(ERRInvalidAssignmentTarget);
  11243. }
  11244. if (buildAST)
  11245. {
  11246. if (IsStrictMode() && pnodeElem != nullptr && pnodeElem->nop == knopName)
  11247. {
  11248. CheckStrictModeEvalArgumentsUsage(pnodeElem->sxPid.pid);
  11249. }
  11250. }
  11251. else
  11252. {
  11253. if (IsStrictMode() && token.tk == tkID)
  11254. {
  11255. CheckStrictModeEvalArgumentsUsage(token.pid);
  11256. }
  11257. token.tk = tkNone;
  11258. }
  11259. }
  11260. }
  11261. else if (!((m_token.tk == tkComma || m_token.tk == tkRBrack || m_token.tk == tkRCurly) && allowEmptyExpression))
  11262. {
  11263. if (m_token.IsOperator())
  11264. {
  11265. Error(ERRDestructNoOper);
  11266. }
  11267. Error(ERRDestructIDRef);
  11268. }
  11269. // Swallow RParens before a default expression, if any.
  11270. // 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.
  11271. if (!isDecl)
  11272. {
  11273. while (m_token.tk == tkRParen)
  11274. {
  11275. m_pscan->Scan();
  11276. --parenCount;
  11277. }
  11278. }
  11279. if (hasSeenRest != nullptr)
  11280. {
  11281. *hasSeenRest = seenRest;
  11282. }
  11283. if (m_token.tk == tkAsg)
  11284. {
  11285. // Parse the initializer.
  11286. if (seenRest)
  11287. {
  11288. Error(ERRRestWithDefault);
  11289. }
  11290. m_pscan->Scan();
  11291. bool alreadyHasInitError = m_hasDeferredShorthandInitError;
  11292. ParseNodePtr pnodeInit = ParseExpr<buildAST>(koplCma);
  11293. if (m_hasDeferredShorthandInitError && !alreadyHasInitError)
  11294. {
  11295. Error(ERRnoColon);
  11296. }
  11297. if (buildAST)
  11298. {
  11299. pnodeElem = CreateBinNode(knopAsg, pnodeElem, pnodeInit);
  11300. }
  11301. }
  11302. if (buildAST && seenRest)
  11303. {
  11304. ParseNodePtr pnodeRest = CreateNodeWithScanner<knopEllipsis>();
  11305. pnodeRest->sxUni.pnode1 = pnodeElem;
  11306. pnodeElem = pnodeRest;
  11307. }
  11308. // 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.
  11309. if (!isDecl)
  11310. {
  11311. while (m_token.tk == tkRParen)
  11312. {
  11313. m_pscan->Scan();
  11314. --parenCount;
  11315. }
  11316. // Restore the Block ID of the current block after the parsing of destructured variable declarations and initializers.
  11317. GetCurrentBlock()->sxBlock.blockId = originalCurrentBlockId;
  11318. }
  11319. if (!(m_token.tk == tkComma || m_token.tk == tkRBrack || m_token.tk == tkRCurly))
  11320. {
  11321. if (m_token.IsOperator())
  11322. {
  11323. Error(ERRDestructNoOper);
  11324. }
  11325. Error(ERRsyntax);
  11326. }
  11327. if (parenCount != 0)
  11328. {
  11329. Error(ERRnoRparen);
  11330. }
  11331. return pnodeElem;
  11332. }
  11333. template <bool buildAST>
  11334. ParseNodePtr Parser::ParseDestructuredArrayLiteral(tokens declarationType, bool isDecl, bool topLevel)
  11335. {
  11336. Assert(m_token.tk == tkLBrack);
  11337. charcount_t ichMin = m_pscan->IchMinTok();
  11338. m_pscan->Scan();
  11339. ParseNodePtr pnodeDestructArr = nullptr;
  11340. ParseNodePtr pnodeList = nullptr;
  11341. ParseNodePtr *lastNodeRef = nullptr;
  11342. uint count = 0;
  11343. bool hasMissingValues = false;
  11344. bool seenRest = false;
  11345. if (m_token.tk != tkRBrack)
  11346. {
  11347. while (true)
  11348. {
  11349. ParseNodePtr pnodeElem = ParseDestructuredVarDecl<buildAST>(declarationType, isDecl, &seenRest, topLevel);
  11350. if (buildAST)
  11351. {
  11352. if (pnodeElem == nullptr && buildAST)
  11353. {
  11354. pnodeElem = CreateNodeWithScanner<knopEmpty>();
  11355. hasMissingValues = true;
  11356. }
  11357. AddToNodeListEscapedUse(&pnodeList, &lastNodeRef, pnodeElem);
  11358. }
  11359. count++;
  11360. if (m_token.tk == tkRBrack)
  11361. {
  11362. break;
  11363. }
  11364. if (m_token.tk != tkComma)
  11365. {
  11366. Error(ERRDestructNoOper);
  11367. }
  11368. if (seenRest) // Rest must be in the last position.
  11369. {
  11370. Error(ERRDestructRestLast);
  11371. }
  11372. m_pscan->Scan();
  11373. // break if we have the trailing comma as well, eg. [a,]
  11374. if (m_token.tk == tkRBrack)
  11375. {
  11376. break;
  11377. }
  11378. }
  11379. }
  11380. if (buildAST)
  11381. {
  11382. pnodeDestructArr = CreateNodeWithScanner<knopArrayPattern>();
  11383. pnodeDestructArr->sxArrLit.pnode1 = pnodeList;
  11384. pnodeDestructArr->sxArrLit.arrayOfTaggedInts = false;
  11385. pnodeDestructArr->sxArrLit.arrayOfInts = false;
  11386. pnodeDestructArr->sxArrLit.arrayOfNumbers = false;
  11387. pnodeDestructArr->sxArrLit.hasMissingValues = hasMissingValues;
  11388. pnodeDestructArr->sxArrLit.count = count;
  11389. pnodeDestructArr->sxArrLit.spreadCount = seenRest ? 1 : 0;
  11390. pnodeDestructArr->ichMin = ichMin;
  11391. pnodeDestructArr->ichLim = m_pscan->IchLimTok();
  11392. if (pnodeDestructArr->sxArrLit.pnode1)
  11393. {
  11394. this->CheckArguments(pnodeDestructArr->sxArrLit.pnode1);
  11395. }
  11396. }
  11397. return pnodeDestructArr;
  11398. }
  11399. void Parser::CaptureContext(ParseContext *parseContext) const
  11400. {
  11401. parseContext->pszSrc = m_pscan->PchBase();
  11402. parseContext->length = this->m_originalLength;
  11403. parseContext->characterOffset = m_pscan->IchMinTok();
  11404. parseContext->offset = parseContext->characterOffset + m_pscan->m_cMultiUnits;
  11405. parseContext->grfscr = this->m_grfscr;
  11406. parseContext->lineNumber = m_pscan->LineCur();
  11407. parseContext->pnodeProg = this->m_currentNodeProg;
  11408. parseContext->fromExternal = m_pscan->IsFromExternalSource();
  11409. parseContext->strictMode = this->IsStrictMode();
  11410. parseContext->sourceContextInfo = this->m_sourceContextInfo;
  11411. parseContext->currentBlockInfo = this->m_currentBlockInfo;
  11412. parseContext->nextBlockId = this->m_nextBlockId;
  11413. }
  11414. void Parser::RestoreContext(ParseContext *const parseContext)
  11415. {
  11416. m_sourceContextInfo = parseContext->sourceContextInfo;
  11417. m_currentBlockInfo = parseContext->currentBlockInfo;
  11418. m_nextBlockId = parseContext->nextBlockId;
  11419. m_grfscr = parseContext->grfscr;
  11420. m_length = parseContext->length;
  11421. m_pscan->SetText(parseContext->pszSrc, parseContext->offset, parseContext->length, parseContext->characterOffset, parseContext->grfscr, parseContext->lineNumber);
  11422. m_currentNodeProg = parseContext->pnodeProg;
  11423. m_fUseStrictMode = parseContext->strictMode;
  11424. }
  11425. class ByteCodeGenerator;
  11426. #if DBG_DUMP
  11427. #define INDENT_SIZE 2
  11428. void PrintPnodeListWIndent(ParseNode *pnode,int indentAmt);
  11429. void PrintFormalsWIndent(ParseNode *pnode, int indentAmt);
  11430. void Indent(int indentAmt) {
  11431. for (int i=0;i<indentAmt;i++) {
  11432. Output::Print(_u(" "));
  11433. }
  11434. }
  11435. void PrintBlockType(PnodeBlockType type)
  11436. {
  11437. switch (type)
  11438. {
  11439. case Global:
  11440. Output::Print(_u("(Global)"));
  11441. break;
  11442. case Function:
  11443. Output::Print(_u("(Function)"));
  11444. break;
  11445. case Regular:
  11446. Output::Print(_u("(Regular)"));
  11447. break;
  11448. case Parameter:
  11449. Output::Print(_u("(Parameter)"));
  11450. break;
  11451. default:
  11452. Output::Print(_u("(unknown blocktype)"));
  11453. break;
  11454. }
  11455. }
  11456. void PrintScopesWIndent(ParseNode *pnode,int indentAmt) {
  11457. ParseNode *scope = nullptr;
  11458. bool firstOnly = false;
  11459. switch(pnode->nop)
  11460. {
  11461. case knopProg:
  11462. case knopFncDecl: scope = pnode->sxFnc.pnodeScopes; break;
  11463. case knopBlock: scope = pnode->sxBlock.pnodeScopes; break;
  11464. case knopCatch: scope = pnode->sxCatch.pnodeScopes; break;
  11465. case knopWith: scope = pnode->sxWith.pnodeScopes; break;
  11466. case knopSwitch: scope = pnode->sxSwitch.pnodeBlock; firstOnly = true; break;
  11467. case knopFor: scope = pnode->sxFor.pnodeBlock; firstOnly = true; break;
  11468. case knopForIn: scope = pnode->sxForInOrForOf.pnodeBlock; firstOnly = true; break;
  11469. case knopForOf: scope = pnode->sxForInOrForOf.pnodeBlock; firstOnly = true; break;
  11470. }
  11471. if (scope) {
  11472. Output::Print(_u("[%4d, %4d): "), scope->ichMin, scope->ichLim);
  11473. Indent(indentAmt);
  11474. Output::Print(_u("Scopes: "));
  11475. ParseNode *next = nullptr;
  11476. ParseNode *syntheticBlock = nullptr;
  11477. while (scope) {
  11478. switch (scope->nop) {
  11479. case knopFncDecl: Output::Print(_u("knopFncDecl")); next = scope->sxFnc.pnodeNext; break;
  11480. case knopBlock: Output::Print(_u("knopBlock")); PrintBlockType(scope->sxBlock.blockType); next = scope->sxBlock.pnodeNext; break;
  11481. case knopCatch: Output::Print(_u("knopCatch")); next = scope->sxCatch.pnodeNext; break;
  11482. case knopWith: Output::Print(_u("knopWith")); next = scope->sxWith.pnodeNext; break;
  11483. default: Output::Print(_u("unknown")); break;
  11484. }
  11485. if (firstOnly) {
  11486. next = nullptr;
  11487. syntheticBlock = scope;
  11488. }
  11489. if (scope->grfpn & fpnSyntheticNode) {
  11490. Output::Print(_u(" synthetic"));
  11491. if (scope->nop == knopBlock)
  11492. syntheticBlock = scope;
  11493. }
  11494. Output::Print(_u(" (%d-%d)"), scope->ichMin, scope->ichLim);
  11495. if (next) Output::Print(_u(", "));
  11496. scope = next;
  11497. }
  11498. Output::Print(_u("\n"));
  11499. if (syntheticBlock || firstOnly) {
  11500. PrintScopesWIndent(syntheticBlock, indentAmt + INDENT_SIZE);
  11501. }
  11502. }
  11503. }
  11504. void PrintPnodeWIndent(ParseNode *pnode,int indentAmt) {
  11505. if (pnode==NULL)
  11506. return;
  11507. Output::Print(_u("[%4d, %4d): "), pnode->ichMin, pnode->ichLim);
  11508. switch (pnode->nop) {
  11509. //PTNODE(knopName , "name" ,None ,Pid ,fnopLeaf)
  11510. case knopName:
  11511. Indent(indentAmt);
  11512. if (pnode->sxPid.pid!=NULL) {
  11513. Output::Print(_u("id: %s\n"),pnode->sxPid.pid->Psz());
  11514. }
  11515. else {
  11516. Output::Print(_u("name node\n"));
  11517. }
  11518. break;
  11519. //PTNODE(knopInt , "int const" ,None ,Int ,fnopLeaf|fnopConst)
  11520. case knopInt:
  11521. Indent(indentAmt);
  11522. Output::Print(_u("%d\n"),pnode->sxInt.lw);
  11523. break;
  11524. //PTNODE(knopFlt , "flt const" ,None ,Flt ,fnopLeaf|fnopConst)
  11525. case knopFlt:
  11526. Indent(indentAmt);
  11527. Output::Print(_u("%lf\n"),pnode->sxFlt.dbl);
  11528. break;
  11529. //PTNODE(knopStr , "str const" ,None ,Pid ,fnopLeaf|fnopConst)
  11530. case knopStr:
  11531. Indent(indentAmt);
  11532. Output::Print(_u("\"%s\"\n"),pnode->sxPid.pid->Psz());
  11533. break;
  11534. //PTNODE(knopRegExp , "reg expr" ,None ,Pid ,fnopLeaf|fnopConst)
  11535. case knopRegExp:
  11536. Indent(indentAmt);
  11537. Output::Print(_u("/%x/\n"),pnode->sxPid.regexPattern);
  11538. break;
  11539. //PTNODE(knopNull , "null" ,Null ,None ,fnopLeaf)
  11540. case knopNull:
  11541. Indent(indentAmt);
  11542. Output::Print(_u("null\n"));
  11543. break;
  11544. //PTNODE(knopFalse , "false" ,False ,None ,fnopLeaf)
  11545. case knopFalse:
  11546. Indent(indentAmt);
  11547. Output::Print(_u("false\n"));
  11548. break;
  11549. //PTNODE(knopTrue , "true" ,True ,None ,fnopLeaf)
  11550. case knopTrue:
  11551. Indent(indentAmt);
  11552. Output::Print(_u("true\n"));
  11553. break;
  11554. //PTNODE(knopEmpty , "empty" ,Empty ,None ,fnopLeaf)
  11555. case knopEmpty:
  11556. Indent(indentAmt);
  11557. Output::Print(_u("empty\n"));
  11558. break;
  11559. // Unary operators.
  11560. //PTNODE(knopNot , "~" ,BitNot ,Uni ,fnopUni)
  11561. case knopNot:
  11562. Indent(indentAmt);
  11563. Output::Print(_u("~\n"));
  11564. PrintPnodeWIndent(pnode->sxUni.pnode1,indentAmt+INDENT_SIZE);
  11565. break;
  11566. //PTNODE(knopNeg , "unary -" ,Neg ,Uni ,fnopUni)
  11567. case knopNeg:
  11568. Indent(indentAmt);
  11569. Output::Print(_u("U-\n"));
  11570. PrintPnodeWIndent(pnode->sxUni.pnode1,indentAmt+INDENT_SIZE);
  11571. break;
  11572. //PTNODE(knopPos , "unary +" ,Pos ,Uni ,fnopUni)
  11573. case knopPos:
  11574. Indent(indentAmt);
  11575. Output::Print(_u("U+\n"));
  11576. PrintPnodeWIndent(pnode->sxUni.pnode1,indentAmt+INDENT_SIZE);
  11577. break;
  11578. //PTNODE(knopLogNot , "!" ,LogNot ,Uni ,fnopUni)
  11579. case knopLogNot:
  11580. Indent(indentAmt);
  11581. Output::Print(_u("!\n"));
  11582. PrintPnodeWIndent(pnode->sxUni.pnode1,indentAmt+INDENT_SIZE);
  11583. break;
  11584. //PTNODE(knopEllipsis , "..." ,Spread ,Uni , fnopUni)
  11585. case knopEllipsis:
  11586. Indent(indentAmt);
  11587. Output::Print(_u("...<expr>\n"));
  11588. PrintPnodeWIndent(pnode->sxUni.pnode1,indentAmt+INDENT_SIZE);
  11589. break;
  11590. //PTNODE(knopIncPost , "++ post" ,Inc ,Uni ,fnopUni|fnopAsg)
  11591. case knopIncPost:
  11592. Indent(indentAmt);
  11593. Output::Print(_u("<expr>++\n"));
  11594. PrintPnodeWIndent(pnode->sxUni.pnode1,indentAmt+INDENT_SIZE);
  11595. break;
  11596. //PTNODE(knopDecPost , "-- post" ,Dec ,Uni ,fnopUni|fnopAsg)
  11597. case knopDecPost:
  11598. Indent(indentAmt);
  11599. Output::Print(_u("<expr>--\n"));
  11600. PrintPnodeWIndent(pnode->sxUni.pnode1,indentAmt+INDENT_SIZE);
  11601. break;
  11602. //PTNODE(knopIncPre , "++ pre" ,Inc ,Uni ,fnopUni|fnopAsg)
  11603. case knopIncPre:
  11604. Indent(indentAmt);
  11605. Output::Print(_u("++<expr>\n"));
  11606. PrintPnodeWIndent(pnode->sxUni.pnode1,indentAmt+INDENT_SIZE);
  11607. break;
  11608. //PTNODE(knopDecPre , "-- pre" ,Dec ,Uni ,fnopUni|fnopAsg)
  11609. case knopDecPre:
  11610. Indent(indentAmt);
  11611. Output::Print(_u("--<expr>\n"));
  11612. PrintPnodeWIndent(pnode->sxUni.pnode1,indentAmt+INDENT_SIZE);
  11613. break;
  11614. //PTNODE(knopTypeof , "typeof" ,None ,Uni ,fnopUni)
  11615. case knopTypeof:
  11616. Indent(indentAmt);
  11617. Output::Print(_u("typeof\n"));
  11618. PrintPnodeWIndent(pnode->sxUni.pnode1,indentAmt+INDENT_SIZE);
  11619. break;
  11620. //PTNODE(knopVoid , "void" ,Void ,Uni ,fnopUni)
  11621. case knopVoid:
  11622. Indent(indentAmt);
  11623. Output::Print(_u("void\n"));
  11624. PrintPnodeWIndent(pnode->sxUni.pnode1,indentAmt+INDENT_SIZE);
  11625. break;
  11626. //PTNODE(knopDelete , "delete" ,None ,Uni ,fnopUni)
  11627. case knopDelete:
  11628. Indent(indentAmt);
  11629. Output::Print(_u("delete\n"));
  11630. PrintPnodeWIndent(pnode->sxUni.pnode1,indentAmt+INDENT_SIZE);
  11631. break;
  11632. //PTNODE(knopArray , "arr cnst" ,None ,Uni ,fnopUni)
  11633. case knopArrayPattern:
  11634. Indent(indentAmt);
  11635. Output::Print(_u("Array Pattern\n"));
  11636. PrintPnodeListWIndent(pnode->sxUni.pnode1, indentAmt + INDENT_SIZE);
  11637. break;
  11638. case knopObjectPattern:
  11639. Indent(indentAmt);
  11640. Output::Print(_u("Object Pattern\n"));
  11641. PrintPnodeListWIndent(pnode->sxUni.pnode1, indentAmt + INDENT_SIZE);
  11642. break;
  11643. case knopArray:
  11644. Indent(indentAmt);
  11645. Output::Print(_u("Array Literal\n"));
  11646. PrintPnodeListWIndent(pnode->sxUni.pnode1,indentAmt+INDENT_SIZE);
  11647. break;
  11648. //PTNODE(knopObject , "obj cnst" ,None ,Uni ,fnopUni)
  11649. case knopObject:
  11650. Indent(indentAmt);
  11651. Output::Print(_u("Object Literal\n"));
  11652. PrintPnodeListWIndent(pnode->sxUni.pnode1,indentAmt+INDENT_SIZE);
  11653. break;
  11654. // Binary and Ternary Operators
  11655. //PTNODE(knopAdd , "+" ,Add ,Bin ,fnopBin)
  11656. case knopAdd:
  11657. Indent(indentAmt);
  11658. Output::Print(_u("+\n"));
  11659. PrintPnodeWIndent(pnode->sxBin.pnode1,indentAmt+INDENT_SIZE);
  11660. PrintPnodeWIndent(pnode->sxBin.pnode2,indentAmt+INDENT_SIZE);
  11661. break;
  11662. //PTNODE(knopSub , "-" ,Sub ,Bin ,fnopBin)
  11663. case knopSub:
  11664. Indent(indentAmt);
  11665. Output::Print(_u("-\n"));
  11666. PrintPnodeWIndent(pnode->sxBin.pnode1,indentAmt+INDENT_SIZE);
  11667. PrintPnodeWIndent(pnode->sxBin.pnode2,indentAmt+INDENT_SIZE);
  11668. break;
  11669. //PTNODE(knopMul , "*" ,Mul ,Bin ,fnopBin)
  11670. case knopMul:
  11671. Indent(indentAmt);
  11672. Output::Print(_u("*\n"));
  11673. PrintPnodeWIndent(pnode->sxBin.pnode1,indentAmt+INDENT_SIZE);
  11674. PrintPnodeWIndent(pnode->sxBin.pnode2,indentAmt+INDENT_SIZE);
  11675. break;
  11676. //PTNODE(knopDiv , "/" ,Div ,Bin ,fnopBin)
  11677. case knopExpo:
  11678. Indent(indentAmt);
  11679. Output::Print(_u("**\n"));
  11680. PrintPnodeWIndent(pnode->sxBin.pnode1, indentAmt + INDENT_SIZE);
  11681. PrintPnodeWIndent(pnode->sxBin.pnode2, indentAmt + INDENT_SIZE);
  11682. break;
  11683. //PTNODE(knopExpo , "**" ,Expo ,Bin ,fnopBin)
  11684. case knopDiv:
  11685. Indent(indentAmt);
  11686. Output::Print(_u("/\n"));
  11687. PrintPnodeWIndent(pnode->sxBin.pnode1,indentAmt+INDENT_SIZE);
  11688. PrintPnodeWIndent(pnode->sxBin.pnode2,indentAmt+INDENT_SIZE);
  11689. break;
  11690. //PTNODE(knopMod , "%" ,Mod ,Bin ,fnopBin)
  11691. case knopMod:
  11692. Indent(indentAmt);
  11693. Output::Print(_u("%\n"));
  11694. PrintPnodeWIndent(pnode->sxBin.pnode1,indentAmt+INDENT_SIZE);
  11695. PrintPnodeWIndent(pnode->sxBin.pnode2,indentAmt+INDENT_SIZE);
  11696. break;
  11697. //PTNODE(knopOr , "|" ,BitOr ,Bin ,fnopBin)
  11698. case knopOr:
  11699. Indent(indentAmt);
  11700. Output::Print(_u("|\n"));
  11701. PrintPnodeWIndent(pnode->sxBin.pnode1,indentAmt+INDENT_SIZE);
  11702. PrintPnodeWIndent(pnode->sxBin.pnode2,indentAmt+INDENT_SIZE);
  11703. break;
  11704. //PTNODE(knopXor , "^" ,BitXor ,Bin ,fnopBin)
  11705. case knopXor:
  11706. Indent(indentAmt);
  11707. Output::Print(_u("^\n"));
  11708. PrintPnodeWIndent(pnode->sxBin.pnode1,indentAmt+INDENT_SIZE);
  11709. PrintPnodeWIndent(pnode->sxBin.pnode2,indentAmt+INDENT_SIZE);
  11710. break;
  11711. //PTNODE(knopAnd , "&" ,BitAnd ,Bin ,fnopBin)
  11712. case knopAnd:
  11713. Indent(indentAmt);
  11714. Output::Print(_u("&\n"));
  11715. PrintPnodeWIndent(pnode->sxBin.pnode1,indentAmt+INDENT_SIZE);
  11716. PrintPnodeWIndent(pnode->sxBin.pnode2,indentAmt+INDENT_SIZE);
  11717. break;
  11718. //PTNODE(knopEq , "==" ,EQ ,Bin ,fnopBin|fnopRel)
  11719. case knopEq:
  11720. Indent(indentAmt);
  11721. Output::Print(_u("==\n"));
  11722. PrintPnodeWIndent(pnode->sxBin.pnode1,indentAmt+INDENT_SIZE);
  11723. PrintPnodeWIndent(pnode->sxBin.pnode2,indentAmt+INDENT_SIZE);
  11724. break;
  11725. //PTNODE(knopNe , "!=" ,NE ,Bin ,fnopBin|fnopRel)
  11726. case knopNe:
  11727. Indent(indentAmt);
  11728. Output::Print(_u("!=\n"));
  11729. PrintPnodeWIndent(pnode->sxBin.pnode1,indentAmt+INDENT_SIZE);
  11730. PrintPnodeWIndent(pnode->sxBin.pnode2,indentAmt+INDENT_SIZE);
  11731. break;
  11732. //PTNODE(knopLt , "<" ,LT ,Bin ,fnopBin|fnopRel)
  11733. case knopLt:
  11734. Indent(indentAmt);
  11735. Output::Print(_u("<\n"));
  11736. PrintPnodeWIndent(pnode->sxBin.pnode1,indentAmt+INDENT_SIZE);
  11737. PrintPnodeWIndent(pnode->sxBin.pnode2,indentAmt+INDENT_SIZE);
  11738. break;
  11739. //PTNODE(knopLe , "<=" ,LE ,Bin ,fnopBin|fnopRel)
  11740. case knopLe:
  11741. Indent(indentAmt);
  11742. Output::Print(_u("<=\n"));
  11743. PrintPnodeWIndent(pnode->sxBin.pnode1,indentAmt+INDENT_SIZE);
  11744. PrintPnodeWIndent(pnode->sxBin.pnode2,indentAmt+INDENT_SIZE);
  11745. break;
  11746. //PTNODE(knopGe , ">=" ,GE ,Bin ,fnopBin|fnopRel)
  11747. case knopGe:
  11748. Indent(indentAmt);
  11749. Output::Print(_u(">=\n"));
  11750. PrintPnodeWIndent(pnode->sxBin.pnode1,indentAmt+INDENT_SIZE);
  11751. PrintPnodeWIndent(pnode->sxBin.pnode2,indentAmt+INDENT_SIZE);
  11752. break;
  11753. //PTNODE(knopGt , ">" ,GT ,Bin ,fnopBin|fnopRel)
  11754. case knopGt:
  11755. Indent(indentAmt);
  11756. Output::Print(_u(">\n"));
  11757. PrintPnodeWIndent(pnode->sxBin.pnode1,indentAmt+INDENT_SIZE);
  11758. PrintPnodeWIndent(pnode->sxBin.pnode2,indentAmt+INDENT_SIZE);
  11759. break;
  11760. //PTNODE(knopCall , "()" ,None ,Bin ,fnopBin)
  11761. case knopCall:
  11762. Indent(indentAmt);
  11763. Output::Print(_u("Call\n"));
  11764. PrintPnodeWIndent(pnode->sxBin.pnode1,indentAmt+INDENT_SIZE);
  11765. PrintPnodeListWIndent(pnode->sxBin.pnode2,indentAmt+INDENT_SIZE);
  11766. break;
  11767. //PTNODE(knopDot , "." ,None ,Bin ,fnopBin)
  11768. case knopDot:
  11769. Indent(indentAmt);
  11770. Output::Print(_u(".\n"));
  11771. PrintPnodeWIndent(pnode->sxBin.pnode1,indentAmt+INDENT_SIZE);
  11772. PrintPnodeWIndent(pnode->sxBin.pnode2,indentAmt+INDENT_SIZE);
  11773. break;
  11774. //PTNODE(knopAsg , "=" ,None ,Bin ,fnopBin|fnopAsg)
  11775. case knopAsg:
  11776. Indent(indentAmt);
  11777. Output::Print(_u("=\n"));
  11778. PrintPnodeWIndent(pnode->sxBin.pnode1,indentAmt+INDENT_SIZE);
  11779. PrintPnodeWIndent(pnode->sxBin.pnode2,indentAmt+INDENT_SIZE);
  11780. break;
  11781. //PTNODE(knopInstOf , "instanceof",InstOf ,Bin ,fnopBin|fnopRel)
  11782. case knopInstOf:
  11783. Indent(indentAmt);
  11784. Output::Print(_u("instanceof\n"));
  11785. PrintPnodeWIndent(pnode->sxBin.pnode1,indentAmt+INDENT_SIZE);
  11786. PrintPnodeWIndent(pnode->sxBin.pnode2,indentAmt+INDENT_SIZE);
  11787. break;
  11788. //PTNODE(knopIn , "in" ,In ,Bin ,fnopBin|fnopRel)
  11789. case knopIn:
  11790. Indent(indentAmt);
  11791. Output::Print(_u("in\n"));
  11792. PrintPnodeWIndent(pnode->sxBin.pnode1,indentAmt+INDENT_SIZE);
  11793. PrintPnodeWIndent(pnode->sxBin.pnode2,indentAmt+INDENT_SIZE);
  11794. break;
  11795. //PTNODE(knopEqv , "===" ,Eqv ,Bin ,fnopBin|fnopRel)
  11796. case knopEqv:
  11797. Indent(indentAmt);
  11798. Output::Print(_u("===\n"));
  11799. PrintPnodeWIndent(pnode->sxBin.pnode1,indentAmt+INDENT_SIZE);
  11800. PrintPnodeWIndent(pnode->sxBin.pnode2,indentAmt+INDENT_SIZE);
  11801. break;
  11802. //PTNODE(knopNEqv , "!==" ,NEqv ,Bin ,fnopBin|fnopRel)
  11803. case knopNEqv:
  11804. Indent(indentAmt);
  11805. Output::Print(_u("!==\n"));
  11806. PrintPnodeWIndent(pnode->sxBin.pnode1,indentAmt+INDENT_SIZE);
  11807. PrintPnodeWIndent(pnode->sxBin.pnode2,indentAmt+INDENT_SIZE);
  11808. break;
  11809. //PTNODE(knopComma , "," ,None ,Bin ,fnopBin)
  11810. case knopComma:
  11811. Indent(indentAmt);
  11812. Output::Print(_u(",\n"));
  11813. PrintPnodeWIndent(pnode->sxBin.pnode1,indentAmt+INDENT_SIZE);
  11814. PrintPnodeWIndent(pnode->sxBin.pnode2,indentAmt+INDENT_SIZE);
  11815. break;
  11816. //PTNODE(knopLogOr , "||" ,None ,Bin ,fnopBin)
  11817. case knopLogOr:
  11818. Indent(indentAmt);
  11819. Output::Print(_u("||\n"));
  11820. PrintPnodeWIndent(pnode->sxBin.pnode1,indentAmt+INDENT_SIZE);
  11821. PrintPnodeWIndent(pnode->sxBin.pnode2,indentAmt+INDENT_SIZE);
  11822. break;
  11823. //PTNODE(knopLogAnd , "&&" ,None ,Bin ,fnopBin)
  11824. case knopLogAnd:
  11825. Indent(indentAmt);
  11826. Output::Print(_u("&&\n"));
  11827. PrintPnodeWIndent(pnode->sxBin.pnode1,indentAmt+INDENT_SIZE);
  11828. PrintPnodeWIndent(pnode->sxBin.pnode2,indentAmt+INDENT_SIZE);
  11829. break;
  11830. //PTNODE(knopLsh , "<<" ,Lsh ,Bin ,fnopBin)
  11831. case knopLsh:
  11832. Indent(indentAmt);
  11833. Output::Print(_u("<<\n"));
  11834. PrintPnodeWIndent(pnode->sxBin.pnode1,indentAmt+INDENT_SIZE);
  11835. PrintPnodeWIndent(pnode->sxBin.pnode2,indentAmt+INDENT_SIZE);
  11836. break;
  11837. //PTNODE(knopRsh , ">>" ,Rsh ,Bin ,fnopBin)
  11838. case knopRsh:
  11839. Indent(indentAmt);
  11840. Output::Print(_u(">>\n"));
  11841. PrintPnodeWIndent(pnode->sxBin.pnode1,indentAmt+INDENT_SIZE);
  11842. PrintPnodeWIndent(pnode->sxBin.pnode2,indentAmt+INDENT_SIZE);
  11843. break;
  11844. //PTNODE(knopRs2 , ">>>" ,Rs2 ,Bin ,fnopBin)
  11845. case knopRs2:
  11846. Indent(indentAmt);
  11847. Output::Print(_u(">>>\n"));
  11848. PrintPnodeWIndent(pnode->sxBin.pnode1,indentAmt+INDENT_SIZE);
  11849. PrintPnodeWIndent(pnode->sxBin.pnode2,indentAmt+INDENT_SIZE);
  11850. break;
  11851. //PTNODE(knopNew , "new" ,None ,Bin ,fnopBin)
  11852. case knopNew:
  11853. Indent(indentAmt);
  11854. Output::Print(_u("new\n"));
  11855. PrintPnodeWIndent(pnode->sxBin.pnode1,indentAmt+INDENT_SIZE);
  11856. PrintPnodeListWIndent(pnode->sxBin.pnode2,indentAmt+INDENT_SIZE);
  11857. break;
  11858. //PTNODE(knopIndex , "[]" ,None ,Bin ,fnopBin)
  11859. case knopIndex:
  11860. Indent(indentAmt);
  11861. Output::Print(_u("[]\n"));
  11862. PrintPnodeWIndent(pnode->sxBin.pnode1,indentAmt+INDENT_SIZE);
  11863. PrintPnodeListWIndent(pnode->sxBin.pnode2,indentAmt+INDENT_SIZE);
  11864. break;
  11865. //PTNODE(knopQmark , "?" ,None ,Tri ,fnopBin)
  11866. case knopQmark:
  11867. Indent(indentAmt);
  11868. Output::Print(_u("?:\n"));
  11869. PrintPnodeWIndent(pnode->sxTri.pnode1,indentAmt+INDENT_SIZE);
  11870. PrintPnodeWIndent(pnode->sxTri.pnode2,indentAmt+INDENT_SIZE);
  11871. PrintPnodeWIndent(pnode->sxTri.pnode3,indentAmt+INDENT_SIZE);
  11872. break;
  11873. //PTNODE(knopAsgAdd , "+=" ,Add ,Bin ,fnopBin|fnopAsg)
  11874. case knopAsgAdd:
  11875. Indent(indentAmt);
  11876. Output::Print(_u("+=\n"));
  11877. PrintPnodeWIndent(pnode->sxBin.pnode1,indentAmt+INDENT_SIZE);
  11878. PrintPnodeWIndent(pnode->sxBin.pnode2,indentAmt+INDENT_SIZE);
  11879. break;
  11880. //PTNODE(knopAsgSub , "-=" ,Sub ,Bin ,fnopBin|fnopAsg)
  11881. case knopAsgSub:
  11882. Indent(indentAmt);
  11883. Output::Print(_u("-=\n"));
  11884. PrintPnodeWIndent(pnode->sxBin.pnode1,indentAmt+INDENT_SIZE);
  11885. PrintPnodeWIndent(pnode->sxBin.pnode2,indentAmt+INDENT_SIZE);
  11886. break;
  11887. //PTNODE(knopAsgMul , "*=" ,Mul ,Bin ,fnopBin|fnopAsg)
  11888. case knopAsgMul:
  11889. Indent(indentAmt);
  11890. Output::Print(_u("*=\n"));
  11891. PrintPnodeWIndent(pnode->sxBin.pnode1,indentAmt+INDENT_SIZE);
  11892. PrintPnodeWIndent(pnode->sxBin.pnode2,indentAmt+INDENT_SIZE);
  11893. break;
  11894. //PTNODE(knopAsgDiv , "/=" ,Div ,Bin ,fnopBin|fnopAsg)
  11895. case knopAsgExpo:
  11896. Indent(indentAmt);
  11897. Output::Print(_u("**=\n"));
  11898. PrintPnodeWIndent(pnode->sxBin.pnode1, indentAmt + INDENT_SIZE);
  11899. PrintPnodeWIndent(pnode->sxBin.pnode2, indentAmt + INDENT_SIZE);
  11900. break;
  11901. //PTNODE(knopAsgExpo , "**=" ,Expo ,Bin ,fnopBin|fnopAsg)
  11902. case knopAsgDiv:
  11903. Indent(indentAmt);
  11904. Output::Print(_u("/=\n"));
  11905. PrintPnodeWIndent(pnode->sxBin.pnode1,indentAmt+INDENT_SIZE);
  11906. PrintPnodeWIndent(pnode->sxBin.pnode2,indentAmt+INDENT_SIZE);
  11907. break;
  11908. //PTNODE(knopAsgMod , "%=" ,Mod ,Bin ,fnopBin|fnopAsg)
  11909. case knopAsgMod:
  11910. Indent(indentAmt);
  11911. Output::Print(_u("%=\n"));
  11912. PrintPnodeWIndent(pnode->sxBin.pnode1,indentAmt+INDENT_SIZE);
  11913. PrintPnodeWIndent(pnode->sxBin.pnode2,indentAmt+INDENT_SIZE);
  11914. break;
  11915. //PTNODE(knopAsgAnd , "&=" ,BitAnd ,Bin ,fnopBin|fnopAsg)
  11916. case knopAsgAnd:
  11917. Indent(indentAmt);
  11918. Output::Print(_u("&=\n"));
  11919. PrintPnodeWIndent(pnode->sxBin.pnode1,indentAmt+INDENT_SIZE);
  11920. PrintPnodeWIndent(pnode->sxBin.pnode2,indentAmt+INDENT_SIZE);
  11921. break;
  11922. //PTNODE(knopAsgXor , "^=" ,BitXor ,Bin ,fnopBin|fnopAsg)
  11923. case knopAsgXor:
  11924. Indent(indentAmt);
  11925. Output::Print(_u("^=\n"));
  11926. PrintPnodeWIndent(pnode->sxBin.pnode1,indentAmt+INDENT_SIZE);
  11927. PrintPnodeWIndent(pnode->sxBin.pnode2,indentAmt+INDENT_SIZE);
  11928. break;
  11929. //PTNODE(knopAsgOr , "|=" ,BitOr ,Bin ,fnopBin|fnopAsg)
  11930. case knopAsgOr:
  11931. Indent(indentAmt);
  11932. Output::Print(_u("|=\n"));
  11933. PrintPnodeWIndent(pnode->sxBin.pnode1,indentAmt+INDENT_SIZE);
  11934. PrintPnodeWIndent(pnode->sxBin.pnode2,indentAmt+INDENT_SIZE);
  11935. break;
  11936. //PTNODE(knopAsgLsh , "<<=" ,Lsh ,Bin ,fnopBin|fnopAsg)
  11937. case knopAsgLsh:
  11938. Indent(indentAmt);
  11939. Output::Print(_u("<<=\n"));
  11940. PrintPnodeWIndent(pnode->sxBin.pnode1,indentAmt+INDENT_SIZE);
  11941. PrintPnodeWIndent(pnode->sxBin.pnode2,indentAmt+INDENT_SIZE);
  11942. break;
  11943. //PTNODE(knopAsgRsh , ">>=" ,Rsh ,Bin ,fnopBin|fnopAsg)
  11944. case knopAsgRsh:
  11945. Indent(indentAmt);
  11946. Output::Print(_u(">>=\n"));
  11947. PrintPnodeWIndent(pnode->sxBin.pnode1,indentAmt+INDENT_SIZE);
  11948. PrintPnodeWIndent(pnode->sxBin.pnode2,indentAmt+INDENT_SIZE);
  11949. break;
  11950. //PTNODE(knopAsgRs2 , ">>>=" ,Rs2 ,Bin ,fnopBin|fnopAsg)
  11951. case knopAsgRs2:
  11952. Indent(indentAmt);
  11953. Output::Print(_u(">>>=\n"));
  11954. PrintPnodeWIndent(pnode->sxBin.pnode1,indentAmt+INDENT_SIZE);
  11955. PrintPnodeWIndent(pnode->sxBin.pnode2,indentAmt+INDENT_SIZE);
  11956. break;
  11957. case knopComputedName:
  11958. Indent(indentAmt);
  11959. Output::Print(_u("ComputedProperty\n"));
  11960. PrintPnodeWIndent(pnode->sxUni.pnode1, indentAmt + INDENT_SIZE);
  11961. break;
  11962. //PTNODE(knopMember , ":" ,None ,Bin ,fnopBin)
  11963. case knopMember:
  11964. case knopMemberShort:
  11965. case knopObjectPatternMember:
  11966. Indent(indentAmt);
  11967. Output::Print(_u(":\n"));
  11968. PrintPnodeWIndent(pnode->sxBin.pnode1,indentAmt+INDENT_SIZE);
  11969. PrintPnodeWIndent(pnode->sxBin.pnode2,indentAmt+INDENT_SIZE);
  11970. break;
  11971. // General nodes.
  11972. //PTNODE(knopList , "<list>" ,None ,Bin ,fnopNone)
  11973. case knopList:
  11974. Indent(indentAmt);
  11975. Output::Print(_u("List\n"));
  11976. PrintPnodeListWIndent(pnode,indentAmt+INDENT_SIZE);
  11977. break;
  11978. //PTNODE(knopVarDecl , "varDcl" ,None ,Var ,fnopNone)
  11979. case knopVarDecl:
  11980. Indent(indentAmt);
  11981. Output::Print(_u("var %s\n"),pnode->sxVar.pid->Psz());
  11982. if (pnode->sxVar.pnodeInit!=NULL)
  11983. PrintPnodeWIndent(pnode->sxVar.pnodeInit,indentAmt+INDENT_SIZE);
  11984. break;
  11985. case knopConstDecl:
  11986. Indent(indentAmt);
  11987. Output::Print(_u("const %s\n"),pnode->sxVar.pid->Psz());
  11988. if (pnode->sxVar.pnodeInit!=NULL)
  11989. PrintPnodeWIndent(pnode->sxVar.pnodeInit,indentAmt+INDENT_SIZE);
  11990. break;
  11991. case knopLetDecl:
  11992. Indent(indentAmt);
  11993. Output::Print(_u("let %s\n"),pnode->sxVar.pid->Psz());
  11994. if (pnode->sxVar.pnodeInit!=NULL)
  11995. PrintPnodeWIndent(pnode->sxVar.pnodeInit,indentAmt+INDENT_SIZE);
  11996. break;
  11997. //PTNODE(knopFncDecl , "fncDcl" ,None ,Fnc ,fnopLeaf)
  11998. case knopFncDecl:
  11999. Indent(indentAmt);
  12000. if (pnode->sxFnc.pid!=NULL)
  12001. {
  12002. Output::Print(_u("fn decl %d nested %d name %s (%d-%d)\n"),pnode->sxFnc.IsDeclaration(),pnode->sxFnc.IsNested(),
  12003. pnode->sxFnc.pid->Psz(), pnode->ichMin, pnode->ichLim);
  12004. }
  12005. else
  12006. {
  12007. Output::Print(_u("fn decl %d nested %d anonymous (%d-%d)\n"),pnode->sxFnc.IsDeclaration(),pnode->sxFnc.IsNested(),pnode->ichMin,pnode->ichLim);
  12008. }
  12009. PrintScopesWIndent(pnode, indentAmt+INDENT_SIZE);
  12010. PrintFormalsWIndent(pnode->sxFnc.pnodeParams, indentAmt + INDENT_SIZE);
  12011. PrintPnodeWIndent(pnode->sxFnc.pnodeRest, indentAmt + INDENT_SIZE);
  12012. PrintPnodeWIndent(pnode->sxFnc.pnodeBody, indentAmt + INDENT_SIZE);
  12013. if (pnode->sxFnc.pnodeBody == nullptr)
  12014. {
  12015. Output::Print(_u("[%4d, %4d): "), pnode->ichMin, pnode->ichLim);
  12016. Indent(indentAmt + INDENT_SIZE);
  12017. Output::Print(_u("<parse deferred body>\n"));
  12018. }
  12019. break;
  12020. //PTNODE(knopProg , "program" ,None ,Fnc ,fnopNone)
  12021. case knopProg:
  12022. Indent(indentAmt);
  12023. Output::Print(_u("program\n"));
  12024. PrintScopesWIndent(pnode, indentAmt+INDENT_SIZE);
  12025. PrintPnodeListWIndent(pnode->sxFnc.pnodeBody,indentAmt+INDENT_SIZE);
  12026. break;
  12027. //PTNODE(knopEndCode , "<endcode>" ,None ,None ,fnopNone)
  12028. case knopEndCode:
  12029. Indent(indentAmt);
  12030. Output::Print(_u("<endcode>\n"));
  12031. break;
  12032. //PTNODE(knopDebugger , "debugger" ,None ,None ,fnopNone)
  12033. case knopDebugger:
  12034. Indent(indentAmt);
  12035. Output::Print(_u("<debugger>\n"));
  12036. break;
  12037. //PTNODE(knopFor , "for" ,None ,For ,fnopBreak|fnopContinue)
  12038. case knopFor:
  12039. Indent(indentAmt);
  12040. Output::Print(_u("for\n"));
  12041. PrintScopesWIndent(pnode, indentAmt+INDENT_SIZE);
  12042. PrintPnodeWIndent(pnode->sxFor.pnodeInit,indentAmt+INDENT_SIZE);
  12043. PrintPnodeWIndent(pnode->sxFor.pnodeCond,indentAmt+INDENT_SIZE);
  12044. PrintPnodeWIndent(pnode->sxFor.pnodeIncr,indentAmt+INDENT_SIZE);
  12045. PrintPnodeWIndent(pnode->sxFor.pnodeBody,indentAmt+INDENT_SIZE);
  12046. break;
  12047. //PTNODE(knopIf , "if" ,None ,If ,fnopNone)
  12048. case knopIf:
  12049. Indent(indentAmt);
  12050. Output::Print(_u("if\n"));
  12051. PrintPnodeWIndent(pnode->sxIf.pnodeCond,indentAmt+INDENT_SIZE);
  12052. PrintPnodeWIndent(pnode->sxIf.pnodeTrue,indentAmt+INDENT_SIZE);
  12053. if (pnode->sxIf.pnodeFalse!=NULL)
  12054. PrintPnodeWIndent(pnode->sxIf.pnodeFalse,indentAmt+INDENT_SIZE);
  12055. break;
  12056. //PTNODE(knopWhile , "while" ,None ,While,fnopBreak|fnopContinue)
  12057. case knopWhile:
  12058. Indent(indentAmt);
  12059. Output::Print(_u("while\n"));
  12060. PrintPnodeWIndent(pnode->sxWhile.pnodeCond,indentAmt+INDENT_SIZE);
  12061. PrintPnodeWIndent(pnode->sxWhile.pnodeBody,indentAmt+INDENT_SIZE);
  12062. break;
  12063. //PTNODE(knopDoWhile , "do-while" ,None ,While,fnopBreak|fnopContinue)
  12064. case knopDoWhile:
  12065. Indent(indentAmt);
  12066. Output::Print(_u("do\n"));
  12067. PrintPnodeWIndent(pnode->sxWhile.pnodeCond,indentAmt+INDENT_SIZE);
  12068. PrintPnodeWIndent(pnode->sxWhile.pnodeBody,indentAmt+INDENT_SIZE);
  12069. break;
  12070. //PTNODE(knopForIn , "for in" ,None ,ForIn,fnopBreak|fnopContinue|fnopCleanup)
  12071. case knopForIn:
  12072. Indent(indentAmt);
  12073. Output::Print(_u("forIn\n"));
  12074. PrintScopesWIndent(pnode, indentAmt+INDENT_SIZE);
  12075. PrintPnodeWIndent(pnode->sxForInOrForOf.pnodeLval,indentAmt+INDENT_SIZE);
  12076. PrintPnodeWIndent(pnode->sxForInOrForOf.pnodeObj,indentAmt+INDENT_SIZE);
  12077. PrintPnodeWIndent(pnode->sxForInOrForOf.pnodeBody,indentAmt+INDENT_SIZE);
  12078. break;
  12079. case knopForOf:
  12080. Indent(indentAmt);
  12081. Output::Print(_u("forOf\n"));
  12082. PrintScopesWIndent(pnode, indentAmt+INDENT_SIZE);
  12083. PrintPnodeWIndent(pnode->sxForInOrForOf.pnodeLval,indentAmt+INDENT_SIZE);
  12084. PrintPnodeWIndent(pnode->sxForInOrForOf.pnodeObj,indentAmt+INDENT_SIZE);
  12085. PrintPnodeWIndent(pnode->sxForInOrForOf.pnodeBody,indentAmt+INDENT_SIZE);
  12086. break;
  12087. //PTNODE(knopReturn , "return" ,None ,Uni ,fnopNone)
  12088. case knopReturn:
  12089. Indent(indentAmt);
  12090. Output::Print(_u("return\n"));
  12091. if (pnode->sxReturn.pnodeExpr!=NULL)
  12092. PrintPnodeWIndent(pnode->sxReturn.pnodeExpr,indentAmt+INDENT_SIZE);
  12093. break;
  12094. //PTNODE(knopBlock , "{}" ,None ,Block,fnopNone)
  12095. case knopBlock:
  12096. Indent(indentAmt);
  12097. Output::Print(_u("block "));
  12098. if (pnode->grfpn & fpnSyntheticNode)
  12099. Output::Print(_u("synthetic "));
  12100. PrintBlockType(pnode->sxBlock.blockType);
  12101. Output::Print(_u("(%d-%d)\n"),pnode->ichMin,pnode->ichLim);
  12102. PrintScopesWIndent(pnode, indentAmt+INDENT_SIZE);
  12103. if (pnode->sxBlock.pnodeStmt!=NULL)
  12104. PrintPnodeWIndent(pnode->sxBlock.pnodeStmt,indentAmt+INDENT_SIZE);
  12105. break;
  12106. //PTNODE(knopWith , "with" ,None ,With ,fnopCleanup)
  12107. case knopWith:
  12108. Indent(indentAmt);
  12109. Output::Print(_u("with (%d-%d)\n"), pnode->ichMin,pnode->ichLim);
  12110. PrintScopesWIndent(pnode, indentAmt+INDENT_SIZE);
  12111. PrintPnodeWIndent(pnode->sxWith.pnodeObj,indentAmt+INDENT_SIZE);
  12112. PrintPnodeWIndent(pnode->sxWith.pnodeBody,indentAmt+INDENT_SIZE);
  12113. break;
  12114. //PTNODE(knopBreak , "break" ,None ,Jump ,fnopNone)
  12115. case knopBreak:
  12116. Indent(indentAmt);
  12117. Output::Print(_u("break\n"));
  12118. // TODO: some representation of target
  12119. break;
  12120. //PTNODE(knopContinue , "continue" ,None ,Jump ,fnopNone)
  12121. case knopContinue:
  12122. Indent(indentAmt);
  12123. Output::Print(_u("continue\n"));
  12124. // TODO: some representation of target
  12125. break;
  12126. //PTNODE(knopLabel , "label" ,None ,Label,fnopNone)
  12127. case knopLabel:
  12128. Indent(indentAmt);
  12129. Output::Print(_u("label %s"),pnode->sxLabel.pid->Psz());
  12130. // TODO: print labeled statement
  12131. break;
  12132. //PTNODE(knopSwitch , "switch" ,None ,Switch,fnopBreak)
  12133. case knopSwitch:
  12134. Indent(indentAmt);
  12135. Output::Print(_u("switch\n"));
  12136. PrintScopesWIndent(pnode, indentAmt+INDENT_SIZE);
  12137. for (ParseNode *pnodeT = pnode->sxSwitch.pnodeCases; NULL != pnodeT;pnodeT = pnodeT->sxCase.pnodeNext) {
  12138. PrintPnodeWIndent(pnodeT,indentAmt+2);
  12139. }
  12140. break;
  12141. //PTNODE(knopCase , "case" ,None ,Case ,fnopNone)
  12142. case knopCase:
  12143. Indent(indentAmt);
  12144. Output::Print(_u("case\n"));
  12145. PrintPnodeWIndent(pnode->sxCase.pnodeExpr,indentAmt+INDENT_SIZE);
  12146. PrintPnodeWIndent(pnode->sxCase.pnodeBody,indentAmt+INDENT_SIZE);
  12147. break;
  12148. //PTNODE(knopTryFinally,"try-finally",None,TryFinally,fnopCleanup)
  12149. case knopTryFinally:
  12150. PrintPnodeWIndent(pnode->sxTryFinally.pnodeTry,indentAmt);
  12151. PrintPnodeWIndent(pnode->sxTryFinally.pnodeFinally,indentAmt);
  12152. break;
  12153. case knopFinally:
  12154. Indent(indentAmt);
  12155. Output::Print(_u("finally\n"));
  12156. PrintPnodeWIndent(pnode->sxFinally.pnodeBody,indentAmt+INDENT_SIZE);
  12157. break;
  12158. //PTNODE(knopCatch , "catch" ,None ,Catch,fnopNone)
  12159. case knopCatch:
  12160. Indent(indentAmt);
  12161. Output::Print(_u("catch (%d-%d)\n"), pnode->ichMin,pnode->ichLim);
  12162. PrintScopesWIndent(pnode, indentAmt+INDENT_SIZE);
  12163. PrintPnodeWIndent(pnode->sxCatch.pnodeParam,indentAmt+INDENT_SIZE);
  12164. // if (pnode->sxCatch.pnodeGuard!=NULL)
  12165. // PrintPnodeWIndent(pnode->sxCatch.pnodeGuard,indentAmt+INDENT_SIZE);
  12166. PrintPnodeWIndent(pnode->sxCatch.pnodeBody,indentAmt+INDENT_SIZE);
  12167. break;
  12168. //PTNODE(knopTryCatch , "try-catch" ,None ,TryCatch ,fnopCleanup)
  12169. case knopTryCatch:
  12170. PrintPnodeWIndent(pnode->sxTryCatch.pnodeTry,indentAmt);
  12171. PrintPnodeWIndent(pnode->sxTryCatch.pnodeCatch,indentAmt);
  12172. break;
  12173. //PTNODE(knopTry , "try" ,None ,Try ,fnopCleanup)
  12174. case knopTry:
  12175. Indent(indentAmt);
  12176. Output::Print(_u("try\n"));
  12177. PrintPnodeWIndent(pnode->sxTry.pnodeBody,indentAmt+INDENT_SIZE);
  12178. break;
  12179. //PTNODE(knopThrow , "throw" ,None ,Uni ,fnopNone)
  12180. case knopThrow:
  12181. Indent(indentAmt);
  12182. Output::Print(_u("throw\n"));
  12183. PrintPnodeWIndent(pnode->sxUni.pnode1,indentAmt+INDENT_SIZE);
  12184. break;
  12185. //PTNODE(knopClassDecl, "classDecl", None , Class, fnopLeaf)
  12186. case knopClassDecl:
  12187. Indent(indentAmt);
  12188. Output::Print(_u("class %s"), pnode->sxClass.pnodeName->sxVar.pid->Psz());
  12189. if (pnode->sxClass.pnodeExtends != nullptr)
  12190. {
  12191. Output::Print(_u(" extends "));
  12192. PrintPnodeWIndent(pnode->sxClass.pnodeExtends, 0);
  12193. }
  12194. else {
  12195. Output::Print(_u("\n"));
  12196. }
  12197. PrintPnodeWIndent(pnode->sxClass.pnodeConstructor, indentAmt + INDENT_SIZE);
  12198. PrintPnodeWIndent(pnode->sxClass.pnodeMembers, indentAmt + INDENT_SIZE);
  12199. PrintPnodeWIndent(pnode->sxClass.pnodeStaticMembers, indentAmt + INDENT_SIZE);
  12200. break;
  12201. case knopStrTemplate:
  12202. Indent(indentAmt);
  12203. Output::Print(_u("string template\n"));
  12204. PrintPnodeListWIndent(pnode->sxStrTemplate.pnodeSubstitutionExpressions, indentAmt + INDENT_SIZE);
  12205. break;
  12206. case knopYieldStar:
  12207. Indent(indentAmt);
  12208. Output::Print(_u("yield*\n"));
  12209. PrintPnodeListWIndent(pnode->sxUni.pnode1, indentAmt + INDENT_SIZE);
  12210. break;
  12211. case knopYield:
  12212. case knopYieldLeaf:
  12213. Indent(indentAmt);
  12214. Output::Print(_u("yield\n"));
  12215. PrintPnodeListWIndent(pnode->sxUni.pnode1, indentAmt + INDENT_SIZE);
  12216. break;
  12217. case knopAwait:
  12218. Indent(indentAmt);
  12219. Output::Print(_u("await\n"));
  12220. PrintPnodeListWIndent(pnode->sxUni.pnode1, indentAmt + INDENT_SIZE);
  12221. break;
  12222. case knopExportDefault:
  12223. Indent(indentAmt);
  12224. Output::Print(_u("export default\n"));
  12225. PrintPnodeListWIndent(pnode->sxExportDefault.pnodeExpr, indentAmt + INDENT_SIZE);
  12226. break;
  12227. default:
  12228. Output::Print(_u("unhandled pnode op %d\n"),pnode->nop);
  12229. break;
  12230. }
  12231. }
  12232. void PrintPnodeListWIndent(ParseNode *pnode,int indentAmt) {
  12233. if (pnode!=NULL) {
  12234. while(pnode->nop==knopList) {
  12235. PrintPnodeWIndent(pnode->sxBin.pnode1,indentAmt);
  12236. pnode = pnode->sxBin.pnode2;
  12237. }
  12238. PrintPnodeWIndent(pnode,indentAmt);
  12239. }
  12240. }
  12241. void PrintFormalsWIndent(ParseNode *pnodeArgs, int indentAmt)
  12242. {
  12243. for (ParseNode *pnode = pnodeArgs; pnode != nullptr; pnode = pnode->GetFormalNext())
  12244. {
  12245. PrintPnodeWIndent(pnode->nop == knopParamPattern ? pnode->sxParamPattern.pnode1 : pnode, indentAmt);
  12246. }
  12247. }
  12248. void PrintPnode(ParseNode *pnode) {
  12249. PrintPnodeWIndent(pnode,0);
  12250. }
  12251. void ParseNode::Dump()
  12252. {
  12253. switch(nop)
  12254. {
  12255. case knopFncDecl:
  12256. case knopProg:
  12257. LPCOLESTR name = Js::Constants::AnonymousFunction;
  12258. if(this->sxFnc.pnodeName)
  12259. {
  12260. name = this->sxFnc.pnodeName->sxVar.pid->Psz();
  12261. }
  12262. Output::Print(_u("%s (%d) [%d, %d]:\n"), name, this->sxFnc.functionId, this->sxFnc.lineNumber, this->sxFnc.columnNumber);
  12263. Output::Print(_u("hasArguments: %s callsEval:%s childCallsEval:%s HasReferenceableBuiltInArguments:%s ArgumentsObjectEscapes:%s HasWith:%s HasOnlyThis:%s \n"),
  12264. IsTrueOrFalse(this->sxFnc.HasHeapArguments()),
  12265. IsTrueOrFalse(this->sxFnc.CallsEval()),
  12266. IsTrueOrFalse(this->sxFnc.ChildCallsEval()),
  12267. IsTrueOrFalse(this->sxFnc.HasReferenceableBuiltInArguments()),
  12268. IsTrueOrFalse(this->sxFnc.GetArgumentsObjectEscapes()),
  12269. IsTrueOrFalse(this->sxFnc.HasWithStmt()),
  12270. IsTrueOrFalse(this->sxFnc.HasOnlyThisStmts()));
  12271. if(this->sxFnc.funcInfo)
  12272. {
  12273. this->sxFnc.funcInfo->Dump();
  12274. }
  12275. break;
  12276. }
  12277. }
  12278. #endif
  12279. DeferredFunctionStub * BuildDeferredStubTree(ParseNode *pnodeFnc, Recycler *recycler)
  12280. {
  12281. Assert(pnodeFnc->nop == knopFncDecl);
  12282. uint nestedCount = pnodeFnc->sxFnc.nestedCount;
  12283. if (nestedCount == 0)
  12284. {
  12285. return nullptr;
  12286. }
  12287. if (pnodeFnc->sxFnc.deferredStub)
  12288. {
  12289. return pnodeFnc->sxFnc.deferredStub;
  12290. }
  12291. DeferredFunctionStub *deferredStubs = RecyclerNewArray(recycler, DeferredFunctionStub, nestedCount);
  12292. uint i = 0;
  12293. ParseNode *pnodeBlock = pnodeFnc->sxFnc.pnodeBodyScope;
  12294. Assert(pnodeBlock != nullptr
  12295. && pnodeBlock->nop == knopBlock
  12296. && (pnodeBlock->sxBlock.blockType == PnodeBlockType::Function
  12297. || pnodeBlock->sxBlock.blockType == PnodeBlockType::Parameter));
  12298. for (ParseNode *pnodeChild = pnodeBlock->sxBlock.pnodeScopes; pnodeChild != nullptr;)
  12299. {
  12300. if (pnodeChild->nop != knopFncDecl)
  12301. {
  12302. // We only expect to find a function body block in a parameter scope block.
  12303. Assert(pnodeChild->nop == knopBlock
  12304. && (pnodeBlock->sxBlock.blockType == PnodeBlockType::Parameter
  12305. || pnodeChild->sxBlock.blockType == PnodeBlockType::Function));
  12306. pnodeChild = pnodeChild->sxBlock.pnodeNext;
  12307. continue;
  12308. }
  12309. AssertOrFailFast(i < nestedCount);
  12310. if (pnodeChild->sxFnc.pnodeBody != nullptr)
  12311. {
  12312. // Anomalous case of a non-deferred function nested within a deferred one.
  12313. // Work around by discarding the stub tree.
  12314. return nullptr;
  12315. }
  12316. if (pnodeChild->sxFnc.IsGeneratedDefault())
  12317. {
  12318. ++i;
  12319. pnodeChild = pnodeChild->sxFnc.pnodeNext;
  12320. continue;
  12321. }
  12322. AnalysisAssertOrFailFast(i < nestedCount);
  12323. deferredStubs[i].fncFlags = pnodeChild->sxFnc.fncFlags;
  12324. deferredStubs[i].nestedCount = pnodeChild->sxFnc.nestedCount;
  12325. deferredStubs[i].restorePoint = *pnodeChild->sxFnc.pRestorePoint;
  12326. deferredStubs[i].deferredStubs = BuildDeferredStubTree(pnodeChild, recycler);
  12327. deferredStubs[i].ichMin = pnodeChild->ichMin;
  12328. ++i;
  12329. pnodeChild = pnodeChild->sxFnc.pnodeNext;
  12330. }
  12331. return deferredStubs;
  12332. }