index.js 290 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761
  1. /***********************************************************************
  2. A JavaScript tokenizer / parser / beautifier / compressor.
  3. https://github.com/mishoo/UglifyJS2
  4. -------------------------------- (C) ---------------------------------
  5. Author: Mihai Bazon
  6. <mihai.bazon@gmail.com>
  7. http://mihai.bazon.net/blog
  8. Distributed under the BSD license:
  9. Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com>
  10. Redistribution and use in source and binary forms, with or without
  11. modification, are permitted provided that the following conditions
  12. are met:
  13. * Redistributions of source code must retain the above
  14. copyright notice, this list of conditions and the following
  15. disclaimer.
  16. * Redistributions in binary form must reproduce the above
  17. copyright notice, this list of conditions and the following
  18. disclaimer in the documentation and/or other materials
  19. provided with the distribution.
  20. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
  21. EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  22. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  23. PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
  24. LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
  25. OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  26. PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  27. PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  28. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
  29. TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
  30. THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  31. SUCH DAMAGE.
  32. ***********************************************************************/
  33. "use strict";
  34. import {
  35. defaults,
  36. HOP,
  37. keep_name,
  38. make_node,
  39. makePredicate,
  40. map_add,
  41. MAP,
  42. member,
  43. noop,
  44. remove,
  45. return_false,
  46. return_null,
  47. return_this,
  48. return_true,
  49. string_template,
  50. regexp_source_fix,
  51. has_annotation
  52. } from "../utils/index.js";
  53. import { first_in_statement, } from "../utils/first_in_statement.js";
  54. import {
  55. AST_Accessor,
  56. AST_Array,
  57. AST_Arrow,
  58. AST_Assign,
  59. AST_Await,
  60. AST_BigInt,
  61. AST_Binary,
  62. AST_Block,
  63. AST_BlockStatement,
  64. AST_Boolean,
  65. AST_Break,
  66. AST_Call,
  67. AST_Case,
  68. AST_Catch,
  69. AST_Chain,
  70. AST_Class,
  71. AST_ClassExpression,
  72. AST_ClassProperty,
  73. AST_ConciseMethod,
  74. AST_Conditional,
  75. AST_Const,
  76. AST_Constant,
  77. AST_Continue,
  78. AST_Debugger,
  79. AST_Default,
  80. AST_DefaultAssign,
  81. AST_DefClass,
  82. AST_Definitions,
  83. AST_Defun,
  84. AST_Destructuring,
  85. AST_Directive,
  86. AST_Do,
  87. AST_Dot,
  88. AST_DWLoop,
  89. AST_EmptyStatement,
  90. AST_Exit,
  91. AST_Expansion,
  92. AST_Export,
  93. AST_False,
  94. AST_Finally,
  95. AST_For,
  96. AST_ForIn,
  97. AST_Function,
  98. AST_Hole,
  99. AST_If,
  100. AST_Import,
  101. AST_Infinity,
  102. AST_IterationStatement,
  103. AST_Jump,
  104. AST_LabeledStatement,
  105. AST_Lambda,
  106. AST_Let,
  107. AST_LoopControl,
  108. AST_NaN,
  109. AST_New,
  110. AST_Node,
  111. AST_Null,
  112. AST_Number,
  113. AST_Object,
  114. AST_ObjectGetter,
  115. AST_ObjectKeyVal,
  116. AST_ObjectProperty,
  117. AST_ObjectSetter,
  118. AST_PrefixedTemplateString,
  119. AST_PropAccess,
  120. AST_RegExp,
  121. AST_Return,
  122. AST_Scope,
  123. AST_Sequence,
  124. AST_SimpleStatement,
  125. AST_Statement,
  126. AST_String,
  127. AST_Sub,
  128. AST_Switch,
  129. AST_SwitchBranch,
  130. AST_Symbol,
  131. AST_SymbolBlockDeclaration,
  132. AST_SymbolCatch,
  133. AST_SymbolClassProperty,
  134. AST_SymbolConst,
  135. AST_SymbolDeclaration,
  136. AST_SymbolDefun,
  137. AST_SymbolExport,
  138. AST_SymbolFunarg,
  139. AST_SymbolLambda,
  140. AST_SymbolLet,
  141. AST_SymbolMethod,
  142. AST_SymbolRef,
  143. AST_SymbolVar,
  144. AST_TemplateSegment,
  145. AST_TemplateString,
  146. AST_This,
  147. AST_Toplevel,
  148. AST_True,
  149. AST_Try,
  150. AST_Unary,
  151. AST_UnaryPostfix,
  152. AST_UnaryPrefix,
  153. AST_Undefined,
  154. AST_Var,
  155. AST_VarDef,
  156. AST_While,
  157. AST_With,
  158. AST_Yield,
  159. TreeTransformer,
  160. TreeWalker,
  161. walk,
  162. walk_abort,
  163. walk_body,
  164. walk_parent,
  165. _INLINE,
  166. _NOINLINE,
  167. _PURE
  168. } from "../ast.js";
  169. import { equivalent_to } from "../equivalent-to.js";
  170. import {
  171. is_basic_identifier_string,
  172. JS_Parse_Error,
  173. parse,
  174. PRECEDENCE,
  175. } from "../parse.js";
  176. import { OutputStream } from "../output.js";
  177. import {
  178. base54,
  179. SymbolDef,
  180. } from "../scope.js";
  181. import "../size.js";
  182. const UNUSED = 0b00000001;
  183. const TRUTHY = 0b00000010;
  184. const FALSY = 0b00000100;
  185. const UNDEFINED = 0b00001000;
  186. const INLINED = 0b00010000;
  187. // Nodes to which values are ever written. Used when keep_assign is part of the unused option string.
  188. const WRITE_ONLY= 0b00100000;
  189. // information specific to a single compression pass
  190. const SQUEEZED = 0b0000000100000000;
  191. const OPTIMIZED = 0b0000001000000000;
  192. const TOP = 0b0000010000000000;
  193. const CLEAR_BETWEEN_PASSES = SQUEEZED | OPTIMIZED | TOP;
  194. const has_flag = (node, flag) => node.flags & flag;
  195. const set_flag = (node, flag) => { node.flags |= flag; };
  196. const clear_flag = (node, flag) => { node.flags &= ~flag; };
  197. class Compressor extends TreeWalker {
  198. constructor(options, { false_by_default = false, mangle_options = false }) {
  199. super();
  200. if (options.defaults !== undefined && !options.defaults) false_by_default = true;
  201. this.options = defaults(options, {
  202. arguments : false,
  203. arrows : !false_by_default,
  204. booleans : !false_by_default,
  205. booleans_as_integers : false,
  206. collapse_vars : !false_by_default,
  207. comparisons : !false_by_default,
  208. computed_props: !false_by_default,
  209. conditionals : !false_by_default,
  210. dead_code : !false_by_default,
  211. defaults : true,
  212. directives : !false_by_default,
  213. drop_console : false,
  214. drop_debugger : !false_by_default,
  215. ecma : 5,
  216. evaluate : !false_by_default,
  217. expression : false,
  218. global_defs : false,
  219. hoist_funs : false,
  220. hoist_props : !false_by_default,
  221. hoist_vars : false,
  222. ie8 : false,
  223. if_return : !false_by_default,
  224. inline : !false_by_default,
  225. join_vars : !false_by_default,
  226. keep_classnames: false,
  227. keep_fargs : true,
  228. keep_fnames : false,
  229. keep_infinity : false,
  230. loops : !false_by_default,
  231. module : false,
  232. negate_iife : !false_by_default,
  233. passes : 1,
  234. properties : !false_by_default,
  235. pure_getters : !false_by_default && "strict",
  236. pure_funcs : null,
  237. reduce_funcs : !false_by_default,
  238. reduce_vars : !false_by_default,
  239. sequences : !false_by_default,
  240. side_effects : !false_by_default,
  241. switches : !false_by_default,
  242. top_retain : null,
  243. toplevel : !!(options && options["top_retain"]),
  244. typeofs : !false_by_default,
  245. unsafe : false,
  246. unsafe_arrows : false,
  247. unsafe_comps : false,
  248. unsafe_Function: false,
  249. unsafe_math : false,
  250. unsafe_symbols: false,
  251. unsafe_methods: false,
  252. unsafe_proto : false,
  253. unsafe_regexp : false,
  254. unsafe_undefined: false,
  255. unused : !false_by_default,
  256. warnings : false // legacy
  257. }, true);
  258. var global_defs = this.options["global_defs"];
  259. if (typeof global_defs == "object") for (var key in global_defs) {
  260. if (key[0] === "@" && HOP(global_defs, key)) {
  261. global_defs[key.slice(1)] = parse(global_defs[key], {
  262. expression: true
  263. });
  264. }
  265. }
  266. if (this.options["inline"] === true) this.options["inline"] = 3;
  267. var pure_funcs = this.options["pure_funcs"];
  268. if (typeof pure_funcs == "function") {
  269. this.pure_funcs = pure_funcs;
  270. } else {
  271. this.pure_funcs = pure_funcs ? function(node) {
  272. return !pure_funcs.includes(node.expression.print_to_string());
  273. } : return_true;
  274. }
  275. var top_retain = this.options["top_retain"];
  276. if (top_retain instanceof RegExp) {
  277. this.top_retain = function(def) {
  278. return top_retain.test(def.name);
  279. };
  280. } else if (typeof top_retain == "function") {
  281. this.top_retain = top_retain;
  282. } else if (top_retain) {
  283. if (typeof top_retain == "string") {
  284. top_retain = top_retain.split(/,/);
  285. }
  286. this.top_retain = function(def) {
  287. return top_retain.includes(def.name);
  288. };
  289. }
  290. if (this.options["module"]) {
  291. this.directives["use strict"] = true;
  292. this.options["toplevel"] = true;
  293. }
  294. var toplevel = this.options["toplevel"];
  295. this.toplevel = typeof toplevel == "string" ? {
  296. funcs: /funcs/.test(toplevel),
  297. vars: /vars/.test(toplevel)
  298. } : {
  299. funcs: toplevel,
  300. vars: toplevel
  301. };
  302. var sequences = this.options["sequences"];
  303. this.sequences_limit = sequences == 1 ? 800 : sequences | 0;
  304. this.evaluated_regexps = new Map();
  305. this._toplevel = undefined;
  306. this.mangle_options = mangle_options;
  307. }
  308. option(key) {
  309. return this.options[key];
  310. }
  311. exposed(def) {
  312. if (def.export) return true;
  313. if (def.global) for (var i = 0, len = def.orig.length; i < len; i++)
  314. if (!this.toplevel[def.orig[i] instanceof AST_SymbolDefun ? "funcs" : "vars"])
  315. return true;
  316. return false;
  317. }
  318. in_boolean_context() {
  319. if (!this.option("booleans")) return false;
  320. var self = this.self();
  321. for (var i = 0, p; p = this.parent(i); i++) {
  322. if (p instanceof AST_SimpleStatement
  323. || p instanceof AST_Conditional && p.condition === self
  324. || p instanceof AST_DWLoop && p.condition === self
  325. || p instanceof AST_For && p.condition === self
  326. || p instanceof AST_If && p.condition === self
  327. || p instanceof AST_UnaryPrefix && p.operator == "!" && p.expression === self) {
  328. return true;
  329. }
  330. if (
  331. p instanceof AST_Binary
  332. && (
  333. p.operator == "&&"
  334. || p.operator == "||"
  335. || p.operator == "??"
  336. )
  337. || p instanceof AST_Conditional
  338. || p.tail_node() === self
  339. ) {
  340. self = p;
  341. } else {
  342. return false;
  343. }
  344. }
  345. }
  346. get_toplevel() {
  347. return this._toplevel;
  348. }
  349. compress(toplevel) {
  350. toplevel = toplevel.resolve_defines(this);
  351. this._toplevel = toplevel;
  352. if (this.option("expression")) {
  353. this._toplevel.process_expression(true);
  354. }
  355. var passes = +this.options.passes || 1;
  356. var min_count = 1 / 0;
  357. var stopping = false;
  358. var mangle = { ie8: this.option("ie8") };
  359. for (var pass = 0; pass < passes; pass++) {
  360. this._toplevel.figure_out_scope(mangle);
  361. if (pass === 0 && this.option("drop_console")) {
  362. // must be run before reduce_vars and compress pass
  363. this._toplevel = this._toplevel.drop_console();
  364. }
  365. if (pass > 0 || this.option("reduce_vars")) {
  366. this._toplevel.reset_opt_flags(this);
  367. }
  368. this._toplevel = this._toplevel.transform(this);
  369. if (passes > 1) {
  370. let count = 0;
  371. walk(this._toplevel, () => { count++; });
  372. if (count < min_count) {
  373. min_count = count;
  374. stopping = false;
  375. } else if (stopping) {
  376. break;
  377. } else {
  378. stopping = true;
  379. }
  380. }
  381. }
  382. if (this.option("expression")) {
  383. this._toplevel.process_expression(false);
  384. }
  385. toplevel = this._toplevel;
  386. this._toplevel = undefined;
  387. return toplevel;
  388. }
  389. before(node, descend) {
  390. if (has_flag(node, SQUEEZED)) return node;
  391. var was_scope = false;
  392. if (node instanceof AST_Scope) {
  393. node = node.hoist_properties(this);
  394. node = node.hoist_declarations(this);
  395. was_scope = true;
  396. }
  397. // Before https://github.com/mishoo/UglifyJS2/pull/1602 AST_Node.optimize()
  398. // would call AST_Node.transform() if a different instance of AST_Node is
  399. // produced after def_optimize().
  400. // This corrupts TreeWalker.stack, which cause AST look-ups to malfunction.
  401. // Migrate and defer all children's AST_Node.transform() to below, which
  402. // will now happen after this parent AST_Node has been properly substituted
  403. // thus gives a consistent AST snapshot.
  404. descend(node, this);
  405. // Existing code relies on how AST_Node.optimize() worked, and omitting the
  406. // following replacement call would result in degraded efficiency of both
  407. // output and performance.
  408. descend(node, this);
  409. var opt = node.optimize(this);
  410. if (was_scope && opt instanceof AST_Scope) {
  411. opt.drop_unused(this);
  412. descend(opt, this);
  413. }
  414. if (opt === node) set_flag(opt, SQUEEZED);
  415. return opt;
  416. }
  417. }
  418. function def_optimize(node, optimizer) {
  419. node.DEFMETHOD("optimize", function(compressor) {
  420. var self = this;
  421. if (has_flag(self, OPTIMIZED)) return self;
  422. if (compressor.has_directive("use asm")) return self;
  423. var opt = optimizer(self, compressor);
  424. set_flag(opt, OPTIMIZED);
  425. return opt;
  426. });
  427. }
  428. def_optimize(AST_Node, function(self) {
  429. return self;
  430. });
  431. AST_Toplevel.DEFMETHOD("drop_console", function() {
  432. return this.transform(new TreeTransformer(function(self) {
  433. if (self.TYPE == "Call") {
  434. var exp = self.expression;
  435. if (exp instanceof AST_PropAccess) {
  436. var name = exp.expression;
  437. while (name.expression) {
  438. name = name.expression;
  439. }
  440. if (is_undeclared_ref(name) && name.name == "console") {
  441. return make_node(AST_Undefined, self);
  442. }
  443. }
  444. }
  445. }));
  446. });
  447. AST_Node.DEFMETHOD("equivalent_to", function(node) {
  448. return equivalent_to(this, node);
  449. });
  450. AST_Scope.DEFMETHOD("process_expression", function(insert, compressor) {
  451. var self = this;
  452. var tt = new TreeTransformer(function(node) {
  453. if (insert && node instanceof AST_SimpleStatement) {
  454. return make_node(AST_Return, node, {
  455. value: node.body
  456. });
  457. }
  458. if (!insert && node instanceof AST_Return) {
  459. if (compressor) {
  460. var value = node.value && node.value.drop_side_effect_free(compressor, true);
  461. return value ? make_node(AST_SimpleStatement, node, {
  462. body: value
  463. }) : make_node(AST_EmptyStatement, node);
  464. }
  465. return make_node(AST_SimpleStatement, node, {
  466. body: node.value || make_node(AST_UnaryPrefix, node, {
  467. operator: "void",
  468. expression: make_node(AST_Number, node, {
  469. value: 0
  470. })
  471. })
  472. });
  473. }
  474. if (node instanceof AST_Class || node instanceof AST_Lambda && node !== self) {
  475. return node;
  476. }
  477. if (node instanceof AST_Block) {
  478. var index = node.body.length - 1;
  479. if (index >= 0) {
  480. node.body[index] = node.body[index].transform(tt);
  481. }
  482. } else if (node instanceof AST_If) {
  483. node.body = node.body.transform(tt);
  484. if (node.alternative) {
  485. node.alternative = node.alternative.transform(tt);
  486. }
  487. } else if (node instanceof AST_With) {
  488. node.body = node.body.transform(tt);
  489. }
  490. return node;
  491. });
  492. self.transform(tt);
  493. });
  494. function read_property(obj, key) {
  495. key = get_value(key);
  496. if (key instanceof AST_Node) return;
  497. var value;
  498. if (obj instanceof AST_Array) {
  499. var elements = obj.elements;
  500. if (key == "length") return make_node_from_constant(elements.length, obj);
  501. if (typeof key == "number" && key in elements) value = elements[key];
  502. } else if (obj instanceof AST_Object) {
  503. key = "" + key;
  504. var props = obj.properties;
  505. for (var i = props.length; --i >= 0;) {
  506. var prop = props[i];
  507. if (!(prop instanceof AST_ObjectKeyVal)) return;
  508. if (!value && props[i].key === key) value = props[i].value;
  509. }
  510. }
  511. return value instanceof AST_SymbolRef && value.fixed_value() || value;
  512. }
  513. function is_modified(compressor, tw, node, value, level, immutable) {
  514. var parent = tw.parent(level);
  515. var lhs = is_lhs(node, parent);
  516. if (lhs) return lhs;
  517. if (!immutable
  518. && parent instanceof AST_Call
  519. && parent.expression === node
  520. && !(value instanceof AST_Arrow)
  521. && !(value instanceof AST_Class)
  522. && !parent.is_callee_pure(compressor)
  523. && (!(value instanceof AST_Function)
  524. || !(parent instanceof AST_New) && value.contains_this())) {
  525. return true;
  526. }
  527. if (parent instanceof AST_Array) {
  528. return is_modified(compressor, tw, parent, parent, level + 1);
  529. }
  530. if (parent instanceof AST_ObjectKeyVal && node === parent.value) {
  531. var obj = tw.parent(level + 1);
  532. return is_modified(compressor, tw, obj, obj, level + 2);
  533. }
  534. if (parent instanceof AST_PropAccess && parent.expression === node) {
  535. var prop = read_property(value, parent.property);
  536. return !immutable && is_modified(compressor, tw, parent, prop, level + 1);
  537. }
  538. }
  539. (function(def_reduce_vars) {
  540. def_reduce_vars(AST_Node, noop);
  541. function reset_def(compressor, def) {
  542. def.assignments = 0;
  543. def.chained = false;
  544. def.direct_access = false;
  545. def.escaped = 0;
  546. def.recursive_refs = 0;
  547. def.references = [];
  548. def.single_use = undefined;
  549. if (def.scope.pinned()) {
  550. def.fixed = false;
  551. } else if (def.orig[0] instanceof AST_SymbolConst || !compressor.exposed(def)) {
  552. def.fixed = def.init;
  553. } else {
  554. def.fixed = false;
  555. }
  556. }
  557. function reset_variables(tw, compressor, node) {
  558. node.variables.forEach(function(def) {
  559. reset_def(compressor, def);
  560. if (def.fixed === null) {
  561. tw.defs_to_safe_ids.set(def.id, tw.safe_ids);
  562. mark(tw, def, true);
  563. } else if (def.fixed) {
  564. tw.loop_ids.set(def.id, tw.in_loop);
  565. mark(tw, def, true);
  566. }
  567. });
  568. }
  569. function reset_block_variables(compressor, node) {
  570. if (node.block_scope) node.block_scope.variables.forEach((def) => {
  571. reset_def(compressor, def);
  572. });
  573. }
  574. function push(tw) {
  575. tw.safe_ids = Object.create(tw.safe_ids);
  576. }
  577. function pop(tw) {
  578. tw.safe_ids = Object.getPrototypeOf(tw.safe_ids);
  579. }
  580. function mark(tw, def, safe) {
  581. tw.safe_ids[def.id] = safe;
  582. }
  583. function safe_to_read(tw, def) {
  584. if (def.single_use == "m") return false;
  585. if (tw.safe_ids[def.id]) {
  586. if (def.fixed == null) {
  587. var orig = def.orig[0];
  588. if (orig instanceof AST_SymbolFunarg || orig.name == "arguments") return false;
  589. def.fixed = make_node(AST_Undefined, orig);
  590. }
  591. return true;
  592. }
  593. return def.fixed instanceof AST_Defun;
  594. }
  595. function safe_to_assign(tw, def, scope, value) {
  596. if (def.fixed === undefined) return true;
  597. let def_safe_ids;
  598. if (def.fixed === null
  599. && (def_safe_ids = tw.defs_to_safe_ids.get(def.id))
  600. ) {
  601. def_safe_ids[def.id] = false;
  602. tw.defs_to_safe_ids.delete(def.id);
  603. return true;
  604. }
  605. if (!HOP(tw.safe_ids, def.id)) return false;
  606. if (!safe_to_read(tw, def)) return false;
  607. if (def.fixed === false) return false;
  608. if (def.fixed != null && (!value || def.references.length > def.assignments)) return false;
  609. if (def.fixed instanceof AST_Defun) {
  610. return value instanceof AST_Node && def.fixed.parent_scope === scope;
  611. }
  612. return def.orig.every((sym) => {
  613. return !(sym instanceof AST_SymbolConst
  614. || sym instanceof AST_SymbolDefun
  615. || sym instanceof AST_SymbolLambda);
  616. });
  617. }
  618. function ref_once(tw, compressor, def) {
  619. return compressor.option("unused")
  620. && !def.scope.pinned()
  621. && def.references.length - def.recursive_refs == 1
  622. && tw.loop_ids.get(def.id) === tw.in_loop;
  623. }
  624. function is_immutable(value) {
  625. if (!value) return false;
  626. return value.is_constant()
  627. || value instanceof AST_Lambda
  628. || value instanceof AST_This;
  629. }
  630. // A definition "escapes" when its value can leave the point of use.
  631. // Example: `a = b || c`
  632. // In this example, "b" and "c" are escaping, because they're going into "a"
  633. //
  634. // def.escaped is != 0 when it escapes.
  635. //
  636. // When greater than 1, it means that N chained properties will be read off
  637. // of that def before an escape occurs. This is useful for evaluating
  638. // property accesses, where you need to know when to stop.
  639. function mark_escaped(tw, d, scope, node, value, level = 0, depth = 1) {
  640. var parent = tw.parent(level);
  641. if (value) {
  642. if (value.is_constant()) return;
  643. if (value instanceof AST_ClassExpression) return;
  644. }
  645. if (
  646. parent instanceof AST_Assign && (parent.operator === "=" || parent.logical) && node === parent.right
  647. || parent instanceof AST_Call && (node !== parent.expression || parent instanceof AST_New)
  648. || parent instanceof AST_Exit && node === parent.value && node.scope !== d.scope
  649. || parent instanceof AST_VarDef && node === parent.value
  650. || parent instanceof AST_Yield && node === parent.value && node.scope !== d.scope
  651. ) {
  652. if (depth > 1 && !(value && value.is_constant_expression(scope))) depth = 1;
  653. if (!d.escaped || d.escaped > depth) d.escaped = depth;
  654. return;
  655. } else if (
  656. parent instanceof AST_Array
  657. || parent instanceof AST_Await
  658. || parent instanceof AST_Binary && lazy_op.has(parent.operator)
  659. || parent instanceof AST_Conditional && node !== parent.condition
  660. || parent instanceof AST_Expansion
  661. || parent instanceof AST_Sequence && node === parent.tail_node()
  662. ) {
  663. mark_escaped(tw, d, scope, parent, parent, level + 1, depth);
  664. } else if (parent instanceof AST_ObjectKeyVal && node === parent.value) {
  665. var obj = tw.parent(level + 1);
  666. mark_escaped(tw, d, scope, obj, obj, level + 2, depth);
  667. } else if (parent instanceof AST_PropAccess && node === parent.expression) {
  668. value = read_property(value, parent.property);
  669. mark_escaped(tw, d, scope, parent, value, level + 1, depth + 1);
  670. if (value) return;
  671. }
  672. if (level > 0) return;
  673. if (parent instanceof AST_Sequence && node !== parent.tail_node()) return;
  674. if (parent instanceof AST_SimpleStatement) return;
  675. d.direct_access = true;
  676. }
  677. const suppress = node => walk(node, node => {
  678. if (!(node instanceof AST_Symbol)) return;
  679. var d = node.definition();
  680. if (!d) return;
  681. if (node instanceof AST_SymbolRef) d.references.push(node);
  682. d.fixed = false;
  683. });
  684. def_reduce_vars(AST_Accessor, function(tw, descend, compressor) {
  685. push(tw);
  686. reset_variables(tw, compressor, this);
  687. descend();
  688. pop(tw);
  689. return true;
  690. });
  691. def_reduce_vars(AST_Assign, function(tw, descend, compressor) {
  692. var node = this;
  693. if (node.left instanceof AST_Destructuring) {
  694. suppress(node.left);
  695. return;
  696. }
  697. const finish_walk = () => {
  698. if (node.logical) {
  699. node.left.walk(tw);
  700. push(tw);
  701. node.right.walk(tw);
  702. pop(tw);
  703. return true;
  704. }
  705. };
  706. var sym = node.left;
  707. if (!(sym instanceof AST_SymbolRef)) return finish_walk();
  708. var def = sym.definition();
  709. var safe = safe_to_assign(tw, def, sym.scope, node.right);
  710. def.assignments++;
  711. if (!safe) return finish_walk();
  712. var fixed = def.fixed;
  713. if (!fixed && node.operator != "=" && !node.logical) return finish_walk();
  714. var eq = node.operator == "=";
  715. var value = eq ? node.right : node;
  716. if (is_modified(compressor, tw, node, value, 0)) return finish_walk();
  717. def.references.push(sym);
  718. if (!node.logical) {
  719. if (!eq) def.chained = true;
  720. def.fixed = eq ? function() {
  721. return node.right;
  722. } : function() {
  723. return make_node(AST_Binary, node, {
  724. operator: node.operator.slice(0, -1),
  725. left: fixed instanceof AST_Node ? fixed : fixed(),
  726. right: node.right
  727. });
  728. };
  729. }
  730. if (node.logical) {
  731. mark(tw, def, false);
  732. push(tw);
  733. node.right.walk(tw);
  734. pop(tw);
  735. return true;
  736. }
  737. mark(tw, def, false);
  738. node.right.walk(tw);
  739. mark(tw, def, true);
  740. mark_escaped(tw, def, sym.scope, node, value, 0, 1);
  741. return true;
  742. });
  743. def_reduce_vars(AST_Binary, function(tw) {
  744. if (!lazy_op.has(this.operator)) return;
  745. this.left.walk(tw);
  746. push(tw);
  747. this.right.walk(tw);
  748. pop(tw);
  749. return true;
  750. });
  751. def_reduce_vars(AST_Block, function(tw, descend, compressor) {
  752. reset_block_variables(compressor, this);
  753. });
  754. def_reduce_vars(AST_Case, function(tw) {
  755. push(tw);
  756. this.expression.walk(tw);
  757. pop(tw);
  758. push(tw);
  759. walk_body(this, tw);
  760. pop(tw);
  761. return true;
  762. });
  763. def_reduce_vars(AST_Class, function(tw, descend) {
  764. clear_flag(this, INLINED);
  765. push(tw);
  766. descend();
  767. pop(tw);
  768. return true;
  769. });
  770. def_reduce_vars(AST_Conditional, function(tw) {
  771. this.condition.walk(tw);
  772. push(tw);
  773. this.consequent.walk(tw);
  774. pop(tw);
  775. push(tw);
  776. this.alternative.walk(tw);
  777. pop(tw);
  778. return true;
  779. });
  780. def_reduce_vars(AST_Chain, function(tw, descend) {
  781. // Chains' conditions apply left-to-right, cumulatively.
  782. // If we walk normally we don't go in that order because we would pop before pushing again
  783. // Solution: AST_PropAccess and AST_Call push when they are optional, and never pop.
  784. // Then we pop everything when they are done being walked.
  785. const safe_ids = tw.safe_ids;
  786. descend();
  787. // Unroll back to start
  788. tw.safe_ids = safe_ids;
  789. return true;
  790. });
  791. def_reduce_vars(AST_Call, function (tw) {
  792. this.expression.walk(tw);
  793. if (this.optional) {
  794. // Never pop -- it's popped at AST_Chain above
  795. push(tw);
  796. }
  797. for (const arg of this.args) arg.walk(tw);
  798. return true;
  799. });
  800. def_reduce_vars(AST_PropAccess, function (tw) {
  801. if (!this.optional) return;
  802. this.expression.walk(tw);
  803. // Never pop -- it's popped at AST_Chain above
  804. push(tw);
  805. if (this.property instanceof AST_Node) this.property.walk(tw);
  806. return true;
  807. });
  808. def_reduce_vars(AST_Default, function(tw, descend) {
  809. push(tw);
  810. descend();
  811. pop(tw);
  812. return true;
  813. });
  814. function mark_lambda(tw, descend, compressor) {
  815. clear_flag(this, INLINED);
  816. push(tw);
  817. reset_variables(tw, compressor, this);
  818. if (this.uses_arguments) {
  819. descend();
  820. pop(tw);
  821. return;
  822. }
  823. var iife;
  824. if (!this.name
  825. && (iife = tw.parent()) instanceof AST_Call
  826. && iife.expression === this
  827. && !iife.args.some(arg => arg instanceof AST_Expansion)
  828. && this.argnames.every(arg_name => arg_name instanceof AST_Symbol)
  829. ) {
  830. // Virtually turn IIFE parameters into variable definitions:
  831. // (function(a,b) {...})(c,d) => (function() {var a=c,b=d; ...})()
  832. // So existing transformation rules can work on them.
  833. this.argnames.forEach((arg, i) => {
  834. if (!arg.definition) return;
  835. var d = arg.definition();
  836. // Avoid setting fixed when there's more than one origin for a variable value
  837. if (d.orig.length > 1) return;
  838. if (d.fixed === undefined && (!this.uses_arguments || tw.has_directive("use strict"))) {
  839. d.fixed = function() {
  840. return iife.args[i] || make_node(AST_Undefined, iife);
  841. };
  842. tw.loop_ids.set(d.id, tw.in_loop);
  843. mark(tw, d, true);
  844. } else {
  845. d.fixed = false;
  846. }
  847. });
  848. }
  849. descend();
  850. pop(tw);
  851. return true;
  852. }
  853. def_reduce_vars(AST_Lambda, mark_lambda);
  854. def_reduce_vars(AST_Do, function(tw, descend, compressor) {
  855. reset_block_variables(compressor, this);
  856. const saved_loop = tw.in_loop;
  857. tw.in_loop = this;
  858. push(tw);
  859. this.body.walk(tw);
  860. if (has_break_or_continue(this)) {
  861. pop(tw);
  862. push(tw);
  863. }
  864. this.condition.walk(tw);
  865. pop(tw);
  866. tw.in_loop = saved_loop;
  867. return true;
  868. });
  869. def_reduce_vars(AST_For, function(tw, descend, compressor) {
  870. reset_block_variables(compressor, this);
  871. if (this.init) this.init.walk(tw);
  872. const saved_loop = tw.in_loop;
  873. tw.in_loop = this;
  874. push(tw);
  875. if (this.condition) this.condition.walk(tw);
  876. this.body.walk(tw);
  877. if (this.step) {
  878. if (has_break_or_continue(this)) {
  879. pop(tw);
  880. push(tw);
  881. }
  882. this.step.walk(tw);
  883. }
  884. pop(tw);
  885. tw.in_loop = saved_loop;
  886. return true;
  887. });
  888. def_reduce_vars(AST_ForIn, function(tw, descend, compressor) {
  889. reset_block_variables(compressor, this);
  890. suppress(this.init);
  891. this.object.walk(tw);
  892. const saved_loop = tw.in_loop;
  893. tw.in_loop = this;
  894. push(tw);
  895. this.body.walk(tw);
  896. pop(tw);
  897. tw.in_loop = saved_loop;
  898. return true;
  899. });
  900. def_reduce_vars(AST_If, function(tw) {
  901. this.condition.walk(tw);
  902. push(tw);
  903. this.body.walk(tw);
  904. pop(tw);
  905. if (this.alternative) {
  906. push(tw);
  907. this.alternative.walk(tw);
  908. pop(tw);
  909. }
  910. return true;
  911. });
  912. def_reduce_vars(AST_LabeledStatement, function(tw) {
  913. push(tw);
  914. this.body.walk(tw);
  915. pop(tw);
  916. return true;
  917. });
  918. def_reduce_vars(AST_SymbolCatch, function() {
  919. this.definition().fixed = false;
  920. });
  921. def_reduce_vars(AST_SymbolRef, function(tw, descend, compressor) {
  922. var d = this.definition();
  923. d.references.push(this);
  924. if (d.references.length == 1
  925. && !d.fixed
  926. && d.orig[0] instanceof AST_SymbolDefun) {
  927. tw.loop_ids.set(d.id, tw.in_loop);
  928. }
  929. var fixed_value;
  930. if (d.fixed === undefined || !safe_to_read(tw, d)) {
  931. d.fixed = false;
  932. } else if (d.fixed) {
  933. fixed_value = this.fixed_value();
  934. if (
  935. fixed_value instanceof AST_Lambda
  936. && recursive_ref(tw, d)
  937. ) {
  938. d.recursive_refs++;
  939. } else if (fixed_value
  940. && !compressor.exposed(d)
  941. && ref_once(tw, compressor, d)
  942. ) {
  943. d.single_use =
  944. fixed_value instanceof AST_Lambda && !fixed_value.pinned()
  945. || fixed_value instanceof AST_Class
  946. || d.scope === this.scope && fixed_value.is_constant_expression();
  947. } else {
  948. d.single_use = false;
  949. }
  950. if (is_modified(compressor, tw, this, fixed_value, 0, is_immutable(fixed_value))) {
  951. if (d.single_use) {
  952. d.single_use = "m";
  953. } else {
  954. d.fixed = false;
  955. }
  956. }
  957. }
  958. mark_escaped(tw, d, this.scope, this, fixed_value, 0, 1);
  959. });
  960. def_reduce_vars(AST_Toplevel, function(tw, descend, compressor) {
  961. this.globals.forEach(function(def) {
  962. reset_def(compressor, def);
  963. });
  964. reset_variables(tw, compressor, this);
  965. });
  966. def_reduce_vars(AST_Try, function(tw, descend, compressor) {
  967. reset_block_variables(compressor, this);
  968. push(tw);
  969. walk_body(this, tw);
  970. pop(tw);
  971. if (this.bcatch) {
  972. push(tw);
  973. this.bcatch.walk(tw);
  974. pop(tw);
  975. }
  976. if (this.bfinally) this.bfinally.walk(tw);
  977. return true;
  978. });
  979. def_reduce_vars(AST_Unary, function(tw) {
  980. var node = this;
  981. if (node.operator !== "++" && node.operator !== "--") return;
  982. var exp = node.expression;
  983. if (!(exp instanceof AST_SymbolRef)) return;
  984. var def = exp.definition();
  985. var safe = safe_to_assign(tw, def, exp.scope, true);
  986. def.assignments++;
  987. if (!safe) return;
  988. var fixed = def.fixed;
  989. if (!fixed) return;
  990. def.references.push(exp);
  991. def.chained = true;
  992. def.fixed = function() {
  993. return make_node(AST_Binary, node, {
  994. operator: node.operator.slice(0, -1),
  995. left: make_node(AST_UnaryPrefix, node, {
  996. operator: "+",
  997. expression: fixed instanceof AST_Node ? fixed : fixed()
  998. }),
  999. right: make_node(AST_Number, node, {
  1000. value: 1
  1001. })
  1002. });
  1003. };
  1004. mark(tw, def, true);
  1005. return true;
  1006. });
  1007. def_reduce_vars(AST_VarDef, function(tw, descend) {
  1008. var node = this;
  1009. if (node.name instanceof AST_Destructuring) {
  1010. suppress(node.name);
  1011. return;
  1012. }
  1013. var d = node.name.definition();
  1014. if (node.value) {
  1015. if (safe_to_assign(tw, d, node.name.scope, node.value)) {
  1016. d.fixed = function() {
  1017. return node.value;
  1018. };
  1019. tw.loop_ids.set(d.id, tw.in_loop);
  1020. mark(tw, d, false);
  1021. descend();
  1022. mark(tw, d, true);
  1023. return true;
  1024. } else {
  1025. d.fixed = false;
  1026. }
  1027. }
  1028. });
  1029. def_reduce_vars(AST_While, function(tw, descend, compressor) {
  1030. reset_block_variables(compressor, this);
  1031. const saved_loop = tw.in_loop;
  1032. tw.in_loop = this;
  1033. push(tw);
  1034. descend();
  1035. pop(tw);
  1036. tw.in_loop = saved_loop;
  1037. return true;
  1038. });
  1039. })(function(node, func) {
  1040. node.DEFMETHOD("reduce_vars", func);
  1041. });
  1042. AST_Toplevel.DEFMETHOD("reset_opt_flags", function(compressor) {
  1043. const self = this;
  1044. const reduce_vars = compressor.option("reduce_vars");
  1045. const preparation = new TreeWalker(function(node, descend) {
  1046. clear_flag(node, CLEAR_BETWEEN_PASSES);
  1047. if (reduce_vars) {
  1048. if (compressor.top_retain
  1049. && node instanceof AST_Defun // Only functions are retained
  1050. && preparation.parent() === self
  1051. ) {
  1052. set_flag(node, TOP);
  1053. }
  1054. return node.reduce_vars(preparation, descend, compressor);
  1055. }
  1056. });
  1057. // Stack of look-up tables to keep track of whether a `SymbolDef` has been
  1058. // properly assigned before use:
  1059. // - `push()` & `pop()` when visiting conditional branches
  1060. preparation.safe_ids = Object.create(null);
  1061. preparation.in_loop = null;
  1062. preparation.loop_ids = new Map();
  1063. preparation.defs_to_safe_ids = new Map();
  1064. self.walk(preparation);
  1065. });
  1066. AST_Symbol.DEFMETHOD("fixed_value", function() {
  1067. var fixed = this.thedef.fixed;
  1068. if (!fixed || fixed instanceof AST_Node) return fixed;
  1069. return fixed();
  1070. });
  1071. AST_SymbolRef.DEFMETHOD("is_immutable", function() {
  1072. var orig = this.definition().orig;
  1073. return orig.length == 1 && orig[0] instanceof AST_SymbolLambda;
  1074. });
  1075. function is_func_expr(node) {
  1076. return node instanceof AST_Arrow || node instanceof AST_Function;
  1077. }
  1078. function is_lhs_read_only(lhs) {
  1079. if (lhs instanceof AST_This) return true;
  1080. if (lhs instanceof AST_SymbolRef) return lhs.definition().orig[0] instanceof AST_SymbolLambda;
  1081. if (lhs instanceof AST_PropAccess) {
  1082. lhs = lhs.expression;
  1083. if (lhs instanceof AST_SymbolRef) {
  1084. if (lhs.is_immutable()) return false;
  1085. lhs = lhs.fixed_value();
  1086. }
  1087. if (!lhs) return true;
  1088. if (lhs instanceof AST_RegExp) return false;
  1089. if (lhs instanceof AST_Constant) return true;
  1090. return is_lhs_read_only(lhs);
  1091. }
  1092. return false;
  1093. }
  1094. function is_ref_of(ref, type) {
  1095. if (!(ref instanceof AST_SymbolRef)) return false;
  1096. var orig = ref.definition().orig;
  1097. for (var i = orig.length; --i >= 0;) {
  1098. if (orig[i] instanceof type) return true;
  1099. }
  1100. }
  1101. function find_scope(tw) {
  1102. for (let i = 0;;i++) {
  1103. const p = tw.parent(i);
  1104. if (p instanceof AST_Toplevel) return p;
  1105. if (p instanceof AST_Lambda) return p;
  1106. if (p.block_scope) return p.block_scope;
  1107. }
  1108. }
  1109. function find_variable(compressor, name) {
  1110. var scope, i = 0;
  1111. while (scope = compressor.parent(i++)) {
  1112. if (scope instanceof AST_Scope) break;
  1113. if (scope instanceof AST_Catch && scope.argname) {
  1114. scope = scope.argname.definition().scope;
  1115. break;
  1116. }
  1117. }
  1118. return scope.find_variable(name);
  1119. }
  1120. function make_sequence(orig, expressions) {
  1121. if (expressions.length == 1) return expressions[0];
  1122. if (expressions.length == 0) throw new Error("trying to create a sequence with length zero!");
  1123. return make_node(AST_Sequence, orig, {
  1124. expressions: expressions.reduce(merge_sequence, [])
  1125. });
  1126. }
  1127. function make_node_from_constant(val, orig) {
  1128. switch (typeof val) {
  1129. case "string":
  1130. return make_node(AST_String, orig, {
  1131. value: val
  1132. });
  1133. case "number":
  1134. if (isNaN(val)) return make_node(AST_NaN, orig);
  1135. if (isFinite(val)) {
  1136. return 1 / val < 0 ? make_node(AST_UnaryPrefix, orig, {
  1137. operator: "-",
  1138. expression: make_node(AST_Number, orig, { value: -val })
  1139. }) : make_node(AST_Number, orig, { value: val });
  1140. }
  1141. return val < 0 ? make_node(AST_UnaryPrefix, orig, {
  1142. operator: "-",
  1143. expression: make_node(AST_Infinity, orig)
  1144. }) : make_node(AST_Infinity, orig);
  1145. case "boolean":
  1146. return make_node(val ? AST_True : AST_False, orig);
  1147. case "undefined":
  1148. return make_node(AST_Undefined, orig);
  1149. default:
  1150. if (val === null) {
  1151. return make_node(AST_Null, orig, { value: null });
  1152. }
  1153. if (val instanceof RegExp) {
  1154. return make_node(AST_RegExp, orig, {
  1155. value: {
  1156. source: regexp_source_fix(val.source),
  1157. flags: val.flags
  1158. }
  1159. });
  1160. }
  1161. throw new Error(string_template("Can't handle constant of type: {type}", {
  1162. type: typeof val
  1163. }));
  1164. }
  1165. }
  1166. // we shouldn't compress (1,func)(something) to
  1167. // func(something) because that changes the meaning of
  1168. // the func (becomes lexical instead of global).
  1169. function maintain_this_binding(parent, orig, val) {
  1170. if (parent instanceof AST_UnaryPrefix && parent.operator == "delete"
  1171. || parent instanceof AST_Call && parent.expression === orig
  1172. && (val instanceof AST_PropAccess || val instanceof AST_SymbolRef && val.name == "eval")) {
  1173. return make_sequence(orig, [ make_node(AST_Number, orig, { value: 0 }), val ]);
  1174. }
  1175. return val;
  1176. }
  1177. function merge_sequence(array, node) {
  1178. if (node instanceof AST_Sequence) {
  1179. array.push(...node.expressions);
  1180. } else {
  1181. array.push(node);
  1182. }
  1183. return array;
  1184. }
  1185. function as_statement_array(thing) {
  1186. if (thing === null) return [];
  1187. if (thing instanceof AST_BlockStatement) return thing.body;
  1188. if (thing instanceof AST_EmptyStatement) return [];
  1189. if (thing instanceof AST_Statement) return [ thing ];
  1190. throw new Error("Can't convert thing to statement array");
  1191. }
  1192. function is_empty(thing) {
  1193. if (thing === null) return true;
  1194. if (thing instanceof AST_EmptyStatement) return true;
  1195. if (thing instanceof AST_BlockStatement) return thing.body.length == 0;
  1196. return false;
  1197. }
  1198. function can_be_evicted_from_block(node) {
  1199. return !(
  1200. node instanceof AST_DefClass ||
  1201. node instanceof AST_Defun ||
  1202. node instanceof AST_Let ||
  1203. node instanceof AST_Const ||
  1204. node instanceof AST_Export ||
  1205. node instanceof AST_Import
  1206. );
  1207. }
  1208. function loop_body(x) {
  1209. if (x instanceof AST_IterationStatement) {
  1210. return x.body instanceof AST_BlockStatement ? x.body : x;
  1211. }
  1212. return x;
  1213. }
  1214. function is_iife_call(node) {
  1215. // Used to determine whether the node can benefit from negation.
  1216. // Not the case with arrow functions (you need an extra set of parens).
  1217. if (node.TYPE != "Call") return false;
  1218. return node.expression instanceof AST_Function || is_iife_call(node.expression);
  1219. }
  1220. function is_undeclared_ref(node) {
  1221. return node instanceof AST_SymbolRef && node.definition().undeclared;
  1222. }
  1223. var global_names = makePredicate("Array Boolean clearInterval clearTimeout console Date decodeURI decodeURIComponent encodeURI encodeURIComponent Error escape eval EvalError Function isFinite isNaN JSON Math Number parseFloat parseInt RangeError ReferenceError RegExp Object setInterval setTimeout String SyntaxError TypeError unescape URIError");
  1224. AST_SymbolRef.DEFMETHOD("is_declared", function(compressor) {
  1225. return !this.definition().undeclared
  1226. || compressor.option("unsafe") && global_names.has(this.name);
  1227. });
  1228. var identifier_atom = makePredicate("Infinity NaN undefined");
  1229. function is_identifier_atom(node) {
  1230. return node instanceof AST_Infinity
  1231. || node instanceof AST_NaN
  1232. || node instanceof AST_Undefined;
  1233. }
  1234. // Tighten a bunch of statements together. Used whenever there is a block.
  1235. function tighten_body(statements, compressor) {
  1236. var in_loop, in_try;
  1237. var scope = compressor.find_parent(AST_Scope).get_defun_scope();
  1238. find_loop_scope_try();
  1239. var CHANGED, max_iter = 10;
  1240. do {
  1241. CHANGED = false;
  1242. eliminate_spurious_blocks(statements);
  1243. if (compressor.option("dead_code")) {
  1244. eliminate_dead_code(statements, compressor);
  1245. }
  1246. if (compressor.option("if_return")) {
  1247. handle_if_return(statements, compressor);
  1248. }
  1249. if (compressor.sequences_limit > 0) {
  1250. sequencesize(statements, compressor);
  1251. sequencesize_2(statements, compressor);
  1252. }
  1253. if (compressor.option("join_vars")) {
  1254. join_consecutive_vars(statements);
  1255. }
  1256. if (compressor.option("collapse_vars")) {
  1257. collapse(statements, compressor);
  1258. }
  1259. } while (CHANGED && max_iter-- > 0);
  1260. function find_loop_scope_try() {
  1261. var node = compressor.self(), level = 0;
  1262. do {
  1263. if (node instanceof AST_Catch || node instanceof AST_Finally) {
  1264. level++;
  1265. } else if (node instanceof AST_IterationStatement) {
  1266. in_loop = true;
  1267. } else if (node instanceof AST_Scope) {
  1268. scope = node;
  1269. break;
  1270. } else if (node instanceof AST_Try) {
  1271. in_try = true;
  1272. }
  1273. } while (node = compressor.parent(level++));
  1274. }
  1275. // Search from right to left for assignment-like expressions:
  1276. // - `var a = x;`
  1277. // - `a = x;`
  1278. // - `++a`
  1279. // For each candidate, scan from left to right for first usage, then try
  1280. // to fold assignment into the site for compression.
  1281. // Will not attempt to collapse assignments into or past code blocks
  1282. // which are not sequentially executed, e.g. loops and conditionals.
  1283. function collapse(statements, compressor) {
  1284. if (scope.pinned()) return statements;
  1285. var args;
  1286. var candidates = [];
  1287. var stat_index = statements.length;
  1288. var scanner = new TreeTransformer(function(node) {
  1289. if (abort) return node;
  1290. // Skip nodes before `candidate` as quickly as possible
  1291. if (!hit) {
  1292. if (node !== hit_stack[hit_index]) return node;
  1293. hit_index++;
  1294. if (hit_index < hit_stack.length) return handle_custom_scan_order(node);
  1295. hit = true;
  1296. stop_after = find_stop(node, 0);
  1297. if (stop_after === node) abort = true;
  1298. return node;
  1299. }
  1300. // Stop immediately if these node types are encountered
  1301. var parent = scanner.parent();
  1302. if (node instanceof AST_Assign
  1303. && (node.logical || node.operator != "=" && lhs.equivalent_to(node.left))
  1304. || node instanceof AST_Await
  1305. || node instanceof AST_Call && lhs instanceof AST_PropAccess && lhs.equivalent_to(node.expression)
  1306. || node instanceof AST_Debugger
  1307. || node instanceof AST_Destructuring
  1308. || node instanceof AST_Expansion
  1309. && node.expression instanceof AST_Symbol
  1310. && (
  1311. node.expression instanceof AST_This
  1312. || node.expression.definition().references.length > 1
  1313. )
  1314. || node instanceof AST_IterationStatement && !(node instanceof AST_For)
  1315. || node instanceof AST_LoopControl
  1316. || node instanceof AST_Try
  1317. || node instanceof AST_With
  1318. || node instanceof AST_Yield
  1319. || node instanceof AST_Export
  1320. || node instanceof AST_Class
  1321. || parent instanceof AST_For && node !== parent.init
  1322. || !replace_all
  1323. && (
  1324. node instanceof AST_SymbolRef
  1325. && !node.is_declared(compressor)
  1326. && !pure_prop_access_globals.has(node))
  1327. || node instanceof AST_SymbolRef
  1328. && parent instanceof AST_Call
  1329. && has_annotation(parent, _NOINLINE)
  1330. ) {
  1331. abort = true;
  1332. return node;
  1333. }
  1334. // Stop only if candidate is found within conditional branches
  1335. if (!stop_if_hit && (!lhs_local || !replace_all)
  1336. && (parent instanceof AST_Binary && lazy_op.has(parent.operator) && parent.left !== node
  1337. || parent instanceof AST_Conditional && parent.condition !== node
  1338. || parent instanceof AST_If && parent.condition !== node)) {
  1339. stop_if_hit = parent;
  1340. }
  1341. // Replace variable with assignment when found
  1342. if (can_replace
  1343. && !(node instanceof AST_SymbolDeclaration)
  1344. && lhs.equivalent_to(node)
  1345. ) {
  1346. if (stop_if_hit) {
  1347. abort = true;
  1348. return node;
  1349. }
  1350. if (is_lhs(node, parent)) {
  1351. if (value_def) replaced++;
  1352. return node;
  1353. } else {
  1354. replaced++;
  1355. if (value_def && candidate instanceof AST_VarDef) return node;
  1356. }
  1357. CHANGED = abort = true;
  1358. if (candidate instanceof AST_UnaryPostfix) {
  1359. return make_node(AST_UnaryPrefix, candidate, candidate);
  1360. }
  1361. if (candidate instanceof AST_VarDef) {
  1362. var def = candidate.name.definition();
  1363. var value = candidate.value;
  1364. if (def.references.length - def.replaced == 1 && !compressor.exposed(def)) {
  1365. def.replaced++;
  1366. if (funarg && is_identifier_atom(value)) {
  1367. return value.transform(compressor);
  1368. } else {
  1369. return maintain_this_binding(parent, node, value);
  1370. }
  1371. }
  1372. return make_node(AST_Assign, candidate, {
  1373. operator: "=",
  1374. logical: false,
  1375. left: make_node(AST_SymbolRef, candidate.name, candidate.name),
  1376. right: value
  1377. });
  1378. }
  1379. clear_flag(candidate, WRITE_ONLY);
  1380. return candidate;
  1381. }
  1382. // These node types have child nodes that execute sequentially,
  1383. // but are otherwise not safe to scan into or beyond them.
  1384. var sym;
  1385. if (node instanceof AST_Call
  1386. || node instanceof AST_Exit
  1387. && (side_effects || lhs instanceof AST_PropAccess || may_modify(lhs))
  1388. || node instanceof AST_PropAccess
  1389. && (side_effects || node.expression.may_throw_on_access(compressor))
  1390. || node instanceof AST_SymbolRef
  1391. && (lvalues.get(node.name) || side_effects && may_modify(node))
  1392. || node instanceof AST_VarDef && node.value
  1393. && (lvalues.has(node.name.name) || side_effects && may_modify(node.name))
  1394. || (sym = is_lhs(node.left, node))
  1395. && (sym instanceof AST_PropAccess || lvalues.has(sym.name))
  1396. || may_throw
  1397. && (in_try ? node.has_side_effects(compressor) : side_effects_external(node))) {
  1398. stop_after = node;
  1399. if (node instanceof AST_Scope) abort = true;
  1400. }
  1401. return handle_custom_scan_order(node);
  1402. }, function(node) {
  1403. if (abort) return;
  1404. if (stop_after === node) abort = true;
  1405. if (stop_if_hit === node) stop_if_hit = null;
  1406. });
  1407. var multi_replacer = new TreeTransformer(function(node) {
  1408. if (abort) return node;
  1409. // Skip nodes before `candidate` as quickly as possible
  1410. if (!hit) {
  1411. if (node !== hit_stack[hit_index]) return node;
  1412. hit_index++;
  1413. if (hit_index < hit_stack.length) return;
  1414. hit = true;
  1415. return node;
  1416. }
  1417. // Replace variable when found
  1418. if (node instanceof AST_SymbolRef
  1419. && node.name == def.name) {
  1420. if (!--replaced) abort = true;
  1421. if (is_lhs(node, multi_replacer.parent())) return node;
  1422. def.replaced++;
  1423. value_def.replaced--;
  1424. return candidate.value;
  1425. }
  1426. // Skip (non-executed) functions and (leading) default case in switch statements
  1427. if (node instanceof AST_Default || node instanceof AST_Scope) return node;
  1428. });
  1429. while (--stat_index >= 0) {
  1430. // Treat parameters as collapsible in IIFE, i.e.
  1431. // function(a, b){ ... }(x());
  1432. // would be translated into equivalent assignments:
  1433. // var a = x(), b = undefined;
  1434. if (stat_index == 0 && compressor.option("unused")) extract_args();
  1435. // Find collapsible assignments
  1436. var hit_stack = [];
  1437. extract_candidates(statements[stat_index]);
  1438. while (candidates.length > 0) {
  1439. hit_stack = candidates.pop();
  1440. var hit_index = 0;
  1441. var candidate = hit_stack[hit_stack.length - 1];
  1442. var value_def = null;
  1443. var stop_after = null;
  1444. var stop_if_hit = null;
  1445. var lhs = get_lhs(candidate);
  1446. if (!lhs || is_lhs_read_only(lhs) || lhs.has_side_effects(compressor)) continue;
  1447. // Locate symbols which may execute code outside of scanning range
  1448. var lvalues = get_lvalues(candidate);
  1449. var lhs_local = is_lhs_local(lhs);
  1450. if (lhs instanceof AST_SymbolRef) lvalues.set(lhs.name, false);
  1451. var side_effects = value_has_side_effects(candidate);
  1452. var replace_all = replace_all_symbols();
  1453. var may_throw = candidate.may_throw(compressor);
  1454. var funarg = candidate.name instanceof AST_SymbolFunarg;
  1455. var hit = funarg;
  1456. var abort = false, replaced = 0, can_replace = !args || !hit;
  1457. if (!can_replace) {
  1458. for (var j = compressor.self().argnames.lastIndexOf(candidate.name) + 1; !abort && j < args.length; j++) {
  1459. args[j].transform(scanner);
  1460. }
  1461. can_replace = true;
  1462. }
  1463. for (var i = stat_index; !abort && i < statements.length; i++) {
  1464. statements[i].transform(scanner);
  1465. }
  1466. if (value_def) {
  1467. var def = candidate.name.definition();
  1468. if (abort && def.references.length - def.replaced > replaced) replaced = false;
  1469. else {
  1470. abort = false;
  1471. hit_index = 0;
  1472. hit = funarg;
  1473. for (var i = stat_index; !abort && i < statements.length; i++) {
  1474. statements[i].transform(multi_replacer);
  1475. }
  1476. value_def.single_use = false;
  1477. }
  1478. }
  1479. if (replaced && !remove_candidate(candidate)) statements.splice(stat_index, 1);
  1480. }
  1481. }
  1482. function handle_custom_scan_order(node) {
  1483. // Skip (non-executed) functions
  1484. if (node instanceof AST_Scope) return node;
  1485. // Scan case expressions first in a switch statement
  1486. if (node instanceof AST_Switch) {
  1487. node.expression = node.expression.transform(scanner);
  1488. for (var i = 0, len = node.body.length; !abort && i < len; i++) {
  1489. var branch = node.body[i];
  1490. if (branch instanceof AST_Case) {
  1491. if (!hit) {
  1492. if (branch !== hit_stack[hit_index]) continue;
  1493. hit_index++;
  1494. }
  1495. branch.expression = branch.expression.transform(scanner);
  1496. if (!replace_all) break;
  1497. }
  1498. }
  1499. abort = true;
  1500. return node;
  1501. }
  1502. }
  1503. function redefined_within_scope(def, scope) {
  1504. if (def.global) return false;
  1505. let cur_scope = def.scope;
  1506. while (cur_scope && cur_scope !== scope) {
  1507. if (cur_scope.variables.has(def.name)) return true;
  1508. cur_scope = cur_scope.parent_scope;
  1509. }
  1510. return false;
  1511. }
  1512. function has_overlapping_symbol(fn, arg, fn_strict) {
  1513. var found = false, scan_this = !(fn instanceof AST_Arrow);
  1514. arg.walk(new TreeWalker(function(node, descend) {
  1515. if (found) return true;
  1516. if (node instanceof AST_SymbolRef && (fn.variables.has(node.name) || redefined_within_scope(node.definition(), fn))) {
  1517. var s = node.definition().scope;
  1518. if (s !== scope) while (s = s.parent_scope) {
  1519. if (s === scope) return true;
  1520. }
  1521. return found = true;
  1522. }
  1523. if ((fn_strict || scan_this) && node instanceof AST_This) {
  1524. return found = true;
  1525. }
  1526. if (node instanceof AST_Scope && !(node instanceof AST_Arrow)) {
  1527. var prev = scan_this;
  1528. scan_this = false;
  1529. descend();
  1530. scan_this = prev;
  1531. return true;
  1532. }
  1533. }));
  1534. return found;
  1535. }
  1536. function extract_args() {
  1537. var iife, fn = compressor.self();
  1538. if (is_func_expr(fn)
  1539. && !fn.name
  1540. && !fn.uses_arguments
  1541. && !fn.pinned()
  1542. && (iife = compressor.parent()) instanceof AST_Call
  1543. && iife.expression === fn
  1544. && iife.args.every((arg) => !(arg instanceof AST_Expansion))
  1545. ) {
  1546. var fn_strict = compressor.has_directive("use strict");
  1547. if (fn_strict && !member(fn_strict, fn.body)) fn_strict = false;
  1548. var len = fn.argnames.length;
  1549. args = iife.args.slice(len);
  1550. var names = new Set();
  1551. for (var i = len; --i >= 0;) {
  1552. var sym = fn.argnames[i];
  1553. var arg = iife.args[i];
  1554. // The following two line fix is a duplicate of the fix at
  1555. // https://github.com/terser/terser/commit/011d3eb08cefe6922c7d1bdfa113fc4aeaca1b75
  1556. // This might mean that these two pieces of code (one here in collapse_vars and another in reduce_vars
  1557. // Might be doing the exact same thing.
  1558. const def = sym.definition && sym.definition();
  1559. const is_reassigned = def && def.orig.length > 1;
  1560. if (is_reassigned) continue;
  1561. args.unshift(make_node(AST_VarDef, sym, {
  1562. name: sym,
  1563. value: arg
  1564. }));
  1565. if (names.has(sym.name)) continue;
  1566. names.add(sym.name);
  1567. if (sym instanceof AST_Expansion) {
  1568. var elements = iife.args.slice(i);
  1569. if (elements.every((arg) =>
  1570. !has_overlapping_symbol(fn, arg, fn_strict)
  1571. )) {
  1572. candidates.unshift([ make_node(AST_VarDef, sym, {
  1573. name: sym.expression,
  1574. value: make_node(AST_Array, iife, {
  1575. elements: elements
  1576. })
  1577. }) ]);
  1578. }
  1579. } else {
  1580. if (!arg) {
  1581. arg = make_node(AST_Undefined, sym).transform(compressor);
  1582. } else if (arg instanceof AST_Lambda && arg.pinned()
  1583. || has_overlapping_symbol(fn, arg, fn_strict)
  1584. ) {
  1585. arg = null;
  1586. }
  1587. if (arg) candidates.unshift([ make_node(AST_VarDef, sym, {
  1588. name: sym,
  1589. value: arg
  1590. }) ]);
  1591. }
  1592. }
  1593. }
  1594. }
  1595. function extract_candidates(expr) {
  1596. hit_stack.push(expr);
  1597. if (expr instanceof AST_Assign) {
  1598. if (!expr.left.has_side_effects(compressor)) {
  1599. candidates.push(hit_stack.slice());
  1600. }
  1601. extract_candidates(expr.right);
  1602. } else if (expr instanceof AST_Binary) {
  1603. extract_candidates(expr.left);
  1604. extract_candidates(expr.right);
  1605. } else if (expr instanceof AST_Call && !has_annotation(expr, _NOINLINE)) {
  1606. extract_candidates(expr.expression);
  1607. expr.args.forEach(extract_candidates);
  1608. } else if (expr instanceof AST_Case) {
  1609. extract_candidates(expr.expression);
  1610. } else if (expr instanceof AST_Conditional) {
  1611. extract_candidates(expr.condition);
  1612. extract_candidates(expr.consequent);
  1613. extract_candidates(expr.alternative);
  1614. } else if (expr instanceof AST_Definitions) {
  1615. var len = expr.definitions.length;
  1616. // limit number of trailing variable definitions for consideration
  1617. var i = len - 200;
  1618. if (i < 0) i = 0;
  1619. for (; i < len; i++) {
  1620. extract_candidates(expr.definitions[i]);
  1621. }
  1622. } else if (expr instanceof AST_DWLoop) {
  1623. extract_candidates(expr.condition);
  1624. if (!(expr.body instanceof AST_Block)) {
  1625. extract_candidates(expr.body);
  1626. }
  1627. } else if (expr instanceof AST_Exit) {
  1628. if (expr.value) extract_candidates(expr.value);
  1629. } else if (expr instanceof AST_For) {
  1630. if (expr.init) extract_candidates(expr.init);
  1631. if (expr.condition) extract_candidates(expr.condition);
  1632. if (expr.step) extract_candidates(expr.step);
  1633. if (!(expr.body instanceof AST_Block)) {
  1634. extract_candidates(expr.body);
  1635. }
  1636. } else if (expr instanceof AST_ForIn) {
  1637. extract_candidates(expr.object);
  1638. if (!(expr.body instanceof AST_Block)) {
  1639. extract_candidates(expr.body);
  1640. }
  1641. } else if (expr instanceof AST_If) {
  1642. extract_candidates(expr.condition);
  1643. if (!(expr.body instanceof AST_Block)) {
  1644. extract_candidates(expr.body);
  1645. }
  1646. if (expr.alternative && !(expr.alternative instanceof AST_Block)) {
  1647. extract_candidates(expr.alternative);
  1648. }
  1649. } else if (expr instanceof AST_Sequence) {
  1650. expr.expressions.forEach(extract_candidates);
  1651. } else if (expr instanceof AST_SimpleStatement) {
  1652. extract_candidates(expr.body);
  1653. } else if (expr instanceof AST_Switch) {
  1654. extract_candidates(expr.expression);
  1655. expr.body.forEach(extract_candidates);
  1656. } else if (expr instanceof AST_Unary) {
  1657. if (expr.operator == "++" || expr.operator == "--") {
  1658. candidates.push(hit_stack.slice());
  1659. }
  1660. } else if (expr instanceof AST_VarDef) {
  1661. if (expr.value) {
  1662. candidates.push(hit_stack.slice());
  1663. extract_candidates(expr.value);
  1664. }
  1665. }
  1666. hit_stack.pop();
  1667. }
  1668. function find_stop(node, level, write_only) {
  1669. var parent = scanner.parent(level);
  1670. if (parent instanceof AST_Assign) {
  1671. if (write_only
  1672. && !parent.logical
  1673. && !(parent.left instanceof AST_PropAccess
  1674. || lvalues.has(parent.left.name))) {
  1675. return find_stop(parent, level + 1, write_only);
  1676. }
  1677. return node;
  1678. }
  1679. if (parent instanceof AST_Binary) {
  1680. if (write_only && (!lazy_op.has(parent.operator) || parent.left === node)) {
  1681. return find_stop(parent, level + 1, write_only);
  1682. }
  1683. return node;
  1684. }
  1685. if (parent instanceof AST_Call) return node;
  1686. if (parent instanceof AST_Case) return node;
  1687. if (parent instanceof AST_Conditional) {
  1688. if (write_only && parent.condition === node) {
  1689. return find_stop(parent, level + 1, write_only);
  1690. }
  1691. return node;
  1692. }
  1693. if (parent instanceof AST_Definitions) {
  1694. return find_stop(parent, level + 1, true);
  1695. }
  1696. if (parent instanceof AST_Exit) {
  1697. return write_only ? find_stop(parent, level + 1, write_only) : node;
  1698. }
  1699. if (parent instanceof AST_If) {
  1700. if (write_only && parent.condition === node) {
  1701. return find_stop(parent, level + 1, write_only);
  1702. }
  1703. return node;
  1704. }
  1705. if (parent instanceof AST_IterationStatement) return node;
  1706. if (parent instanceof AST_Sequence) {
  1707. return find_stop(parent, level + 1, parent.tail_node() !== node);
  1708. }
  1709. if (parent instanceof AST_SimpleStatement) {
  1710. return find_stop(parent, level + 1, true);
  1711. }
  1712. if (parent instanceof AST_Switch) return node;
  1713. if (parent instanceof AST_VarDef) return node;
  1714. return null;
  1715. }
  1716. function mangleable_var(var_def) {
  1717. var value = var_def.value;
  1718. if (!(value instanceof AST_SymbolRef)) return;
  1719. if (value.name == "arguments") return;
  1720. var def = value.definition();
  1721. if (def.undeclared) return;
  1722. return value_def = def;
  1723. }
  1724. function get_lhs(expr) {
  1725. if (expr instanceof AST_Assign && expr.logical) {
  1726. return false;
  1727. } else if (expr instanceof AST_VarDef && expr.name instanceof AST_SymbolDeclaration) {
  1728. var def = expr.name.definition();
  1729. if (!member(expr.name, def.orig)) return;
  1730. var referenced = def.references.length - def.replaced;
  1731. if (!referenced) return;
  1732. var declared = def.orig.length - def.eliminated;
  1733. if (declared > 1 && !(expr.name instanceof AST_SymbolFunarg)
  1734. || (referenced > 1 ? mangleable_var(expr) : !compressor.exposed(def))) {
  1735. return make_node(AST_SymbolRef, expr.name, expr.name);
  1736. }
  1737. } else {
  1738. const lhs = expr instanceof AST_Assign
  1739. ? expr.left
  1740. : expr.expression;
  1741. return !is_ref_of(lhs, AST_SymbolConst)
  1742. && !is_ref_of(lhs, AST_SymbolLet) && lhs;
  1743. }
  1744. }
  1745. function get_rvalue(expr) {
  1746. if (expr instanceof AST_Assign) {
  1747. return expr.right;
  1748. } else {
  1749. return expr.value;
  1750. }
  1751. }
  1752. function get_lvalues(expr) {
  1753. var lvalues = new Map();
  1754. if (expr instanceof AST_Unary) return lvalues;
  1755. var tw = new TreeWalker(function(node) {
  1756. var sym = node;
  1757. while (sym instanceof AST_PropAccess) sym = sym.expression;
  1758. if (sym instanceof AST_SymbolRef || sym instanceof AST_This) {
  1759. lvalues.set(sym.name, lvalues.get(sym.name) || is_modified(compressor, tw, node, node, 0));
  1760. }
  1761. });
  1762. get_rvalue(expr).walk(tw);
  1763. return lvalues;
  1764. }
  1765. function remove_candidate(expr) {
  1766. if (expr.name instanceof AST_SymbolFunarg) {
  1767. var iife = compressor.parent(), argnames = compressor.self().argnames;
  1768. var index = argnames.indexOf(expr.name);
  1769. if (index < 0) {
  1770. iife.args.length = Math.min(iife.args.length, argnames.length - 1);
  1771. } else {
  1772. var args = iife.args;
  1773. if (args[index]) args[index] = make_node(AST_Number, args[index], {
  1774. value: 0
  1775. });
  1776. }
  1777. return true;
  1778. }
  1779. var found = false;
  1780. return statements[stat_index].transform(new TreeTransformer(function(node, descend, in_list) {
  1781. if (found) return node;
  1782. if (node === expr || node.body === expr) {
  1783. found = true;
  1784. if (node instanceof AST_VarDef) {
  1785. node.value = node.name instanceof AST_SymbolConst
  1786. ? make_node(AST_Undefined, node.value) // `const` always needs value.
  1787. : null;
  1788. return node;
  1789. }
  1790. return in_list ? MAP.skip : null;
  1791. }
  1792. }, function(node) {
  1793. if (node instanceof AST_Sequence) switch (node.expressions.length) {
  1794. case 0: return null;
  1795. case 1: return node.expressions[0];
  1796. }
  1797. }));
  1798. }
  1799. function is_lhs_local(lhs) {
  1800. while (lhs instanceof AST_PropAccess) lhs = lhs.expression;
  1801. return lhs instanceof AST_SymbolRef
  1802. && lhs.definition().scope === scope
  1803. && !(in_loop
  1804. && (lvalues.has(lhs.name)
  1805. || candidate instanceof AST_Unary
  1806. || (candidate instanceof AST_Assign
  1807. && !candidate.logical
  1808. && candidate.operator != "=")));
  1809. }
  1810. function value_has_side_effects(expr) {
  1811. if (expr instanceof AST_Unary) return unary_side_effects.has(expr.operator);
  1812. return get_rvalue(expr).has_side_effects(compressor);
  1813. }
  1814. function replace_all_symbols() {
  1815. if (side_effects) return false;
  1816. if (value_def) return true;
  1817. if (lhs instanceof AST_SymbolRef) {
  1818. var def = lhs.definition();
  1819. if (def.references.length - def.replaced == (candidate instanceof AST_VarDef ? 1 : 2)) {
  1820. return true;
  1821. }
  1822. }
  1823. return false;
  1824. }
  1825. function may_modify(sym) {
  1826. if (!sym.definition) return true; // AST_Destructuring
  1827. var def = sym.definition();
  1828. if (def.orig.length == 1 && def.orig[0] instanceof AST_SymbolDefun) return false;
  1829. if (def.scope.get_defun_scope() !== scope) return true;
  1830. return !def.references.every((ref) => {
  1831. var s = ref.scope.get_defun_scope();
  1832. // "block" scope within AST_Catch
  1833. if (s.TYPE == "Scope") s = s.parent_scope;
  1834. return s === scope;
  1835. });
  1836. }
  1837. function side_effects_external(node, lhs) {
  1838. if (node instanceof AST_Assign) return side_effects_external(node.left, true);
  1839. if (node instanceof AST_Unary) return side_effects_external(node.expression, true);
  1840. if (node instanceof AST_VarDef) return node.value && side_effects_external(node.value);
  1841. if (lhs) {
  1842. if (node instanceof AST_Dot) return side_effects_external(node.expression, true);
  1843. if (node instanceof AST_Sub) return side_effects_external(node.expression, true);
  1844. if (node instanceof AST_SymbolRef) return node.definition().scope !== scope;
  1845. }
  1846. return false;
  1847. }
  1848. }
  1849. function eliminate_spurious_blocks(statements) {
  1850. var seen_dirs = [];
  1851. for (var i = 0; i < statements.length;) {
  1852. var stat = statements[i];
  1853. if (stat instanceof AST_BlockStatement && stat.body.every(can_be_evicted_from_block)) {
  1854. CHANGED = true;
  1855. eliminate_spurious_blocks(stat.body);
  1856. statements.splice(i, 1, ...stat.body);
  1857. i += stat.body.length;
  1858. } else if (stat instanceof AST_EmptyStatement) {
  1859. CHANGED = true;
  1860. statements.splice(i, 1);
  1861. } else if (stat instanceof AST_Directive) {
  1862. if (seen_dirs.indexOf(stat.value) < 0) {
  1863. i++;
  1864. seen_dirs.push(stat.value);
  1865. } else {
  1866. CHANGED = true;
  1867. statements.splice(i, 1);
  1868. }
  1869. } else i++;
  1870. }
  1871. }
  1872. function handle_if_return(statements, compressor) {
  1873. var self = compressor.self();
  1874. var multiple_if_returns = has_multiple_if_returns(statements);
  1875. var in_lambda = self instanceof AST_Lambda;
  1876. for (var i = statements.length; --i >= 0;) {
  1877. var stat = statements[i];
  1878. var j = next_index(i);
  1879. var next = statements[j];
  1880. if (in_lambda && !next && stat instanceof AST_Return) {
  1881. if (!stat.value) {
  1882. CHANGED = true;
  1883. statements.splice(i, 1);
  1884. continue;
  1885. }
  1886. if (stat.value instanceof AST_UnaryPrefix && stat.value.operator == "void") {
  1887. CHANGED = true;
  1888. statements[i] = make_node(AST_SimpleStatement, stat, {
  1889. body: stat.value.expression
  1890. });
  1891. continue;
  1892. }
  1893. }
  1894. if (stat instanceof AST_If) {
  1895. var ab = aborts(stat.body);
  1896. if (can_merge_flow(ab)) {
  1897. if (ab.label) {
  1898. remove(ab.label.thedef.references, ab);
  1899. }
  1900. CHANGED = true;
  1901. stat = stat.clone();
  1902. stat.condition = stat.condition.negate(compressor);
  1903. var body = as_statement_array_with_return(stat.body, ab);
  1904. stat.body = make_node(AST_BlockStatement, stat, {
  1905. body: as_statement_array(stat.alternative).concat(extract_functions())
  1906. });
  1907. stat.alternative = make_node(AST_BlockStatement, stat, {
  1908. body: body
  1909. });
  1910. statements[i] = stat.transform(compressor);
  1911. continue;
  1912. }
  1913. var ab = aborts(stat.alternative);
  1914. if (can_merge_flow(ab)) {
  1915. if (ab.label) {
  1916. remove(ab.label.thedef.references, ab);
  1917. }
  1918. CHANGED = true;
  1919. stat = stat.clone();
  1920. stat.body = make_node(AST_BlockStatement, stat.body, {
  1921. body: as_statement_array(stat.body).concat(extract_functions())
  1922. });
  1923. var body = as_statement_array_with_return(stat.alternative, ab);
  1924. stat.alternative = make_node(AST_BlockStatement, stat.alternative, {
  1925. body: body
  1926. });
  1927. statements[i] = stat.transform(compressor);
  1928. continue;
  1929. }
  1930. }
  1931. if (stat instanceof AST_If && stat.body instanceof AST_Return) {
  1932. var value = stat.body.value;
  1933. //---
  1934. // pretty silly case, but:
  1935. // if (foo()) return; return; ==> foo(); return;
  1936. if (!value && !stat.alternative
  1937. && (in_lambda && !next || next instanceof AST_Return && !next.value)) {
  1938. CHANGED = true;
  1939. statements[i] = make_node(AST_SimpleStatement, stat.condition, {
  1940. body: stat.condition
  1941. });
  1942. continue;
  1943. }
  1944. //---
  1945. // if (foo()) return x; return y; ==> return foo() ? x : y;
  1946. if (value && !stat.alternative && next instanceof AST_Return && next.value) {
  1947. CHANGED = true;
  1948. stat = stat.clone();
  1949. stat.alternative = next;
  1950. statements[i] = stat.transform(compressor);
  1951. statements.splice(j, 1);
  1952. continue;
  1953. }
  1954. //---
  1955. // if (foo()) return x; [ return ; ] ==> return foo() ? x : undefined;
  1956. if (value && !stat.alternative
  1957. && (!next && in_lambda && multiple_if_returns
  1958. || next instanceof AST_Return)) {
  1959. CHANGED = true;
  1960. stat = stat.clone();
  1961. stat.alternative = next || make_node(AST_Return, stat, {
  1962. value: null
  1963. });
  1964. statements[i] = stat.transform(compressor);
  1965. if (next) statements.splice(j, 1);
  1966. continue;
  1967. }
  1968. //---
  1969. // if (a) return b; if (c) return d; e; ==> return a ? b : c ? d : void e;
  1970. //
  1971. // if sequences is not enabled, this can lead to an endless loop (issue #866).
  1972. // however, with sequences on this helps producing slightly better output for
  1973. // the example code.
  1974. var prev = statements[prev_index(i)];
  1975. if (compressor.option("sequences") && in_lambda && !stat.alternative
  1976. && prev instanceof AST_If && prev.body instanceof AST_Return
  1977. && next_index(j) == statements.length && next instanceof AST_SimpleStatement) {
  1978. CHANGED = true;
  1979. stat = stat.clone();
  1980. stat.alternative = make_node(AST_BlockStatement, next, {
  1981. body: [
  1982. next,
  1983. make_node(AST_Return, next, {
  1984. value: null
  1985. })
  1986. ]
  1987. });
  1988. statements[i] = stat.transform(compressor);
  1989. statements.splice(j, 1);
  1990. continue;
  1991. }
  1992. }
  1993. }
  1994. function has_multiple_if_returns(statements) {
  1995. var n = 0;
  1996. for (var i = statements.length; --i >= 0;) {
  1997. var stat = statements[i];
  1998. if (stat instanceof AST_If && stat.body instanceof AST_Return) {
  1999. if (++n > 1) return true;
  2000. }
  2001. }
  2002. return false;
  2003. }
  2004. function is_return_void(value) {
  2005. return !value || value instanceof AST_UnaryPrefix && value.operator == "void";
  2006. }
  2007. function can_merge_flow(ab) {
  2008. if (!ab) return false;
  2009. for (var j = i + 1, len = statements.length; j < len; j++) {
  2010. var stat = statements[j];
  2011. if (stat instanceof AST_Const || stat instanceof AST_Let) return false;
  2012. }
  2013. var lct = ab instanceof AST_LoopControl ? compressor.loopcontrol_target(ab) : null;
  2014. return ab instanceof AST_Return && in_lambda && is_return_void(ab.value)
  2015. || ab instanceof AST_Continue && self === loop_body(lct)
  2016. || ab instanceof AST_Break && lct instanceof AST_BlockStatement && self === lct;
  2017. }
  2018. function extract_functions() {
  2019. var tail = statements.slice(i + 1);
  2020. statements.length = i + 1;
  2021. return tail.filter(function(stat) {
  2022. if (stat instanceof AST_Defun) {
  2023. statements.push(stat);
  2024. return false;
  2025. }
  2026. return true;
  2027. });
  2028. }
  2029. function as_statement_array_with_return(node, ab) {
  2030. var body = as_statement_array(node).slice(0, -1);
  2031. if (ab.value) {
  2032. body.push(make_node(AST_SimpleStatement, ab.value, {
  2033. body: ab.value.expression
  2034. }));
  2035. }
  2036. return body;
  2037. }
  2038. function next_index(i) {
  2039. for (var j = i + 1, len = statements.length; j < len; j++) {
  2040. var stat = statements[j];
  2041. if (!(stat instanceof AST_Var && declarations_only(stat))) {
  2042. break;
  2043. }
  2044. }
  2045. return j;
  2046. }
  2047. function prev_index(i) {
  2048. for (var j = i; --j >= 0;) {
  2049. var stat = statements[j];
  2050. if (!(stat instanceof AST_Var && declarations_only(stat))) {
  2051. break;
  2052. }
  2053. }
  2054. return j;
  2055. }
  2056. }
  2057. function eliminate_dead_code(statements, compressor) {
  2058. var has_quit;
  2059. var self = compressor.self();
  2060. for (var i = 0, n = 0, len = statements.length; i < len; i++) {
  2061. var stat = statements[i];
  2062. if (stat instanceof AST_LoopControl) {
  2063. var lct = compressor.loopcontrol_target(stat);
  2064. if (stat instanceof AST_Break
  2065. && !(lct instanceof AST_IterationStatement)
  2066. && loop_body(lct) === self
  2067. || stat instanceof AST_Continue
  2068. && loop_body(lct) === self) {
  2069. if (stat.label) {
  2070. remove(stat.label.thedef.references, stat);
  2071. }
  2072. } else {
  2073. statements[n++] = stat;
  2074. }
  2075. } else {
  2076. statements[n++] = stat;
  2077. }
  2078. if (aborts(stat)) {
  2079. has_quit = statements.slice(i + 1);
  2080. break;
  2081. }
  2082. }
  2083. statements.length = n;
  2084. CHANGED = n != len;
  2085. if (has_quit) has_quit.forEach(function(stat) {
  2086. trim_unreachable_code(compressor, stat, statements);
  2087. });
  2088. }
  2089. function declarations_only(node) {
  2090. return node.definitions.every((var_def) =>
  2091. !var_def.value
  2092. );
  2093. }
  2094. function sequencesize(statements, compressor) {
  2095. if (statements.length < 2) return;
  2096. var seq = [], n = 0;
  2097. function push_seq() {
  2098. if (!seq.length) return;
  2099. var body = make_sequence(seq[0], seq);
  2100. statements[n++] = make_node(AST_SimpleStatement, body, { body: body });
  2101. seq = [];
  2102. }
  2103. for (var i = 0, len = statements.length; i < len; i++) {
  2104. var stat = statements[i];
  2105. if (stat instanceof AST_SimpleStatement) {
  2106. if (seq.length >= compressor.sequences_limit) push_seq();
  2107. var body = stat.body;
  2108. if (seq.length > 0) body = body.drop_side_effect_free(compressor);
  2109. if (body) merge_sequence(seq, body);
  2110. } else if (stat instanceof AST_Definitions && declarations_only(stat)
  2111. || stat instanceof AST_Defun) {
  2112. statements[n++] = stat;
  2113. } else {
  2114. push_seq();
  2115. statements[n++] = stat;
  2116. }
  2117. }
  2118. push_seq();
  2119. statements.length = n;
  2120. if (n != len) CHANGED = true;
  2121. }
  2122. function to_simple_statement(block, decls) {
  2123. if (!(block instanceof AST_BlockStatement)) return block;
  2124. var stat = null;
  2125. for (var i = 0, len = block.body.length; i < len; i++) {
  2126. var line = block.body[i];
  2127. if (line instanceof AST_Var && declarations_only(line)) {
  2128. decls.push(line);
  2129. } else if (stat) {
  2130. return false;
  2131. } else {
  2132. stat = line;
  2133. }
  2134. }
  2135. return stat;
  2136. }
  2137. function sequencesize_2(statements, compressor) {
  2138. function cons_seq(right) {
  2139. n--;
  2140. CHANGED = true;
  2141. var left = prev.body;
  2142. return make_sequence(left, [ left, right ]).transform(compressor);
  2143. }
  2144. var n = 0, prev;
  2145. for (var i = 0; i < statements.length; i++) {
  2146. var stat = statements[i];
  2147. if (prev) {
  2148. if (stat instanceof AST_Exit) {
  2149. stat.value = cons_seq(stat.value || make_node(AST_Undefined, stat).transform(compressor));
  2150. } else if (stat instanceof AST_For) {
  2151. if (!(stat.init instanceof AST_Definitions)) {
  2152. const abort = walk(prev.body, node => {
  2153. if (node instanceof AST_Scope) return true;
  2154. if (
  2155. node instanceof AST_Binary
  2156. && node.operator === "in"
  2157. ) {
  2158. return walk_abort;
  2159. }
  2160. });
  2161. if (!abort) {
  2162. if (stat.init) stat.init = cons_seq(stat.init);
  2163. else {
  2164. stat.init = prev.body;
  2165. n--;
  2166. CHANGED = true;
  2167. }
  2168. }
  2169. }
  2170. } else if (stat instanceof AST_ForIn) {
  2171. if (!(stat.init instanceof AST_Const) && !(stat.init instanceof AST_Let)) {
  2172. stat.object = cons_seq(stat.object);
  2173. }
  2174. } else if (stat instanceof AST_If) {
  2175. stat.condition = cons_seq(stat.condition);
  2176. } else if (stat instanceof AST_Switch) {
  2177. stat.expression = cons_seq(stat.expression);
  2178. } else if (stat instanceof AST_With) {
  2179. stat.expression = cons_seq(stat.expression);
  2180. }
  2181. }
  2182. if (compressor.option("conditionals") && stat instanceof AST_If) {
  2183. var decls = [];
  2184. var body = to_simple_statement(stat.body, decls);
  2185. var alt = to_simple_statement(stat.alternative, decls);
  2186. if (body !== false && alt !== false && decls.length > 0) {
  2187. var len = decls.length;
  2188. decls.push(make_node(AST_If, stat, {
  2189. condition: stat.condition,
  2190. body: body || make_node(AST_EmptyStatement, stat.body),
  2191. alternative: alt
  2192. }));
  2193. decls.unshift(n, 1);
  2194. [].splice.apply(statements, decls);
  2195. i += len;
  2196. n += len + 1;
  2197. prev = null;
  2198. CHANGED = true;
  2199. continue;
  2200. }
  2201. }
  2202. statements[n++] = stat;
  2203. prev = stat instanceof AST_SimpleStatement ? stat : null;
  2204. }
  2205. statements.length = n;
  2206. }
  2207. function join_object_assignments(defn, body) {
  2208. if (!(defn instanceof AST_Definitions)) return;
  2209. var def = defn.definitions[defn.definitions.length - 1];
  2210. if (!(def.value instanceof AST_Object)) return;
  2211. var exprs;
  2212. if (body instanceof AST_Assign && !body.logical) {
  2213. exprs = [ body ];
  2214. } else if (body instanceof AST_Sequence) {
  2215. exprs = body.expressions.slice();
  2216. }
  2217. if (!exprs) return;
  2218. var trimmed = false;
  2219. do {
  2220. var node = exprs[0];
  2221. if (!(node instanceof AST_Assign)) break;
  2222. if (node.operator != "=") break;
  2223. if (!(node.left instanceof AST_PropAccess)) break;
  2224. var sym = node.left.expression;
  2225. if (!(sym instanceof AST_SymbolRef)) break;
  2226. if (def.name.name != sym.name) break;
  2227. if (!node.right.is_constant_expression(scope)) break;
  2228. var prop = node.left.property;
  2229. if (prop instanceof AST_Node) {
  2230. prop = prop.evaluate(compressor);
  2231. }
  2232. if (prop instanceof AST_Node) break;
  2233. prop = "" + prop;
  2234. var diff = compressor.option("ecma") < 2015
  2235. && compressor.has_directive("use strict") ? function(node) {
  2236. return node.key != prop && (node.key && node.key.name != prop);
  2237. } : function(node) {
  2238. return node.key && node.key.name != prop;
  2239. };
  2240. if (!def.value.properties.every(diff)) break;
  2241. var p = def.value.properties.filter(function (p) { return p.key === prop; })[0];
  2242. if (!p) {
  2243. def.value.properties.push(make_node(AST_ObjectKeyVal, node, {
  2244. key: prop,
  2245. value: node.right
  2246. }));
  2247. } else {
  2248. p.value = new AST_Sequence({
  2249. start: p.start,
  2250. expressions: [p.value.clone(), node.right.clone()],
  2251. end: p.end
  2252. });
  2253. }
  2254. exprs.shift();
  2255. trimmed = true;
  2256. } while (exprs.length);
  2257. return trimmed && exprs;
  2258. }
  2259. function join_consecutive_vars(statements) {
  2260. var defs;
  2261. for (var i = 0, j = -1, len = statements.length; i < len; i++) {
  2262. var stat = statements[i];
  2263. var prev = statements[j];
  2264. if (stat instanceof AST_Definitions) {
  2265. if (prev && prev.TYPE == stat.TYPE) {
  2266. prev.definitions = prev.definitions.concat(stat.definitions);
  2267. CHANGED = true;
  2268. } else if (defs && defs.TYPE == stat.TYPE && declarations_only(stat)) {
  2269. defs.definitions = defs.definitions.concat(stat.definitions);
  2270. CHANGED = true;
  2271. } else {
  2272. statements[++j] = stat;
  2273. defs = stat;
  2274. }
  2275. } else if (stat instanceof AST_Exit) {
  2276. stat.value = extract_object_assignments(stat.value);
  2277. } else if (stat instanceof AST_For) {
  2278. var exprs = join_object_assignments(prev, stat.init);
  2279. if (exprs) {
  2280. CHANGED = true;
  2281. stat.init = exprs.length ? make_sequence(stat.init, exprs) : null;
  2282. statements[++j] = stat;
  2283. } else if (prev instanceof AST_Var && (!stat.init || stat.init.TYPE == prev.TYPE)) {
  2284. if (stat.init) {
  2285. prev.definitions = prev.definitions.concat(stat.init.definitions);
  2286. }
  2287. stat.init = prev;
  2288. statements[j] = stat;
  2289. CHANGED = true;
  2290. } else if (defs && stat.init && defs.TYPE == stat.init.TYPE && declarations_only(stat.init)) {
  2291. defs.definitions = defs.definitions.concat(stat.init.definitions);
  2292. stat.init = null;
  2293. statements[++j] = stat;
  2294. CHANGED = true;
  2295. } else {
  2296. statements[++j] = stat;
  2297. }
  2298. } else if (stat instanceof AST_ForIn) {
  2299. stat.object = extract_object_assignments(stat.object);
  2300. } else if (stat instanceof AST_If) {
  2301. stat.condition = extract_object_assignments(stat.condition);
  2302. } else if (stat instanceof AST_SimpleStatement) {
  2303. var exprs = join_object_assignments(prev, stat.body);
  2304. if (exprs) {
  2305. CHANGED = true;
  2306. if (!exprs.length) continue;
  2307. stat.body = make_sequence(stat.body, exprs);
  2308. }
  2309. statements[++j] = stat;
  2310. } else if (stat instanceof AST_Switch) {
  2311. stat.expression = extract_object_assignments(stat.expression);
  2312. } else if (stat instanceof AST_With) {
  2313. stat.expression = extract_object_assignments(stat.expression);
  2314. } else {
  2315. statements[++j] = stat;
  2316. }
  2317. }
  2318. statements.length = j + 1;
  2319. function extract_object_assignments(value) {
  2320. statements[++j] = stat;
  2321. var exprs = join_object_assignments(prev, value);
  2322. if (exprs) {
  2323. CHANGED = true;
  2324. if (exprs.length) {
  2325. return make_sequence(value, exprs);
  2326. } else if (value instanceof AST_Sequence) {
  2327. return value.tail_node().left;
  2328. } else {
  2329. return value.left;
  2330. }
  2331. }
  2332. return value;
  2333. }
  2334. }
  2335. }
  2336. function trim_unreachable_code(compressor, stat, target) {
  2337. walk(stat, node => {
  2338. if (node instanceof AST_Var) {
  2339. node.remove_initializers();
  2340. target.push(node);
  2341. return true;
  2342. }
  2343. if (
  2344. node instanceof AST_Defun
  2345. && (node === stat || !compressor.has_directive("use strict"))
  2346. ) {
  2347. target.push(node === stat ? node : make_node(AST_Var, node, {
  2348. definitions: [
  2349. make_node(AST_VarDef, node, {
  2350. name: make_node(AST_SymbolVar, node.name, node.name),
  2351. value: null
  2352. })
  2353. ]
  2354. }));
  2355. return true;
  2356. }
  2357. if (node instanceof AST_Export || node instanceof AST_Import) {
  2358. target.push(node);
  2359. return true;
  2360. }
  2361. if (node instanceof AST_Scope) {
  2362. return true;
  2363. }
  2364. });
  2365. }
  2366. function get_value(key) {
  2367. if (key instanceof AST_Constant) {
  2368. return key.getValue();
  2369. }
  2370. if (key instanceof AST_UnaryPrefix
  2371. && key.operator == "void"
  2372. && key.expression instanceof AST_Constant) {
  2373. return;
  2374. }
  2375. return key;
  2376. }
  2377. function is_undefined(node, compressor) {
  2378. return (
  2379. has_flag(node, UNDEFINED)
  2380. || node instanceof AST_Undefined
  2381. || node instanceof AST_UnaryPrefix
  2382. && node.operator == "void"
  2383. && !node.expression.has_side_effects(compressor)
  2384. );
  2385. }
  2386. // may_throw_on_access()
  2387. // returns true if this node may be null, undefined or contain `AST_Accessor`
  2388. (function(def_may_throw_on_access) {
  2389. AST_Node.DEFMETHOD("may_throw_on_access", function(compressor) {
  2390. return !compressor.option("pure_getters")
  2391. || this._dot_throw(compressor);
  2392. });
  2393. function is_strict(compressor) {
  2394. return /strict/.test(compressor.option("pure_getters"));
  2395. }
  2396. def_may_throw_on_access(AST_Node, is_strict);
  2397. def_may_throw_on_access(AST_Null, return_true);
  2398. def_may_throw_on_access(AST_Undefined, return_true);
  2399. def_may_throw_on_access(AST_Constant, return_false);
  2400. def_may_throw_on_access(AST_Array, return_false);
  2401. def_may_throw_on_access(AST_Object, function(compressor) {
  2402. if (!is_strict(compressor)) return false;
  2403. for (var i = this.properties.length; --i >=0;)
  2404. if (this.properties[i]._dot_throw(compressor)) return true;
  2405. return false;
  2406. });
  2407. // Do not be as strict with classes as we are with objects.
  2408. // Hopefully the community is not going to abuse static getters and setters.
  2409. // https://github.com/terser/terser/issues/724#issuecomment-643655656
  2410. def_may_throw_on_access(AST_Class, return_false);
  2411. def_may_throw_on_access(AST_ObjectProperty, return_false);
  2412. def_may_throw_on_access(AST_ObjectGetter, return_true);
  2413. def_may_throw_on_access(AST_Expansion, function(compressor) {
  2414. return this.expression._dot_throw(compressor);
  2415. });
  2416. def_may_throw_on_access(AST_Function, return_false);
  2417. def_may_throw_on_access(AST_Arrow, return_false);
  2418. def_may_throw_on_access(AST_UnaryPostfix, return_false);
  2419. def_may_throw_on_access(AST_UnaryPrefix, function() {
  2420. return this.operator == "void";
  2421. });
  2422. def_may_throw_on_access(AST_Binary, function(compressor) {
  2423. return (this.operator == "&&" || this.operator == "||" || this.operator == "??")
  2424. && (this.left._dot_throw(compressor) || this.right._dot_throw(compressor));
  2425. });
  2426. def_may_throw_on_access(AST_Assign, function(compressor) {
  2427. if (this.logical) return true;
  2428. return this.operator == "="
  2429. && this.right._dot_throw(compressor);
  2430. });
  2431. def_may_throw_on_access(AST_Conditional, function(compressor) {
  2432. return this.consequent._dot_throw(compressor)
  2433. || this.alternative._dot_throw(compressor);
  2434. });
  2435. def_may_throw_on_access(AST_Dot, function(compressor) {
  2436. if (!is_strict(compressor)) return false;
  2437. if (this.property == "prototype") {
  2438. return !(
  2439. this.expression instanceof AST_Function
  2440. || this.expression instanceof AST_Class
  2441. );
  2442. }
  2443. return true;
  2444. });
  2445. def_may_throw_on_access(AST_Chain, function(compressor) {
  2446. return this.expression._dot_throw(compressor);
  2447. });
  2448. def_may_throw_on_access(AST_Sequence, function(compressor) {
  2449. return this.tail_node()._dot_throw(compressor);
  2450. });
  2451. def_may_throw_on_access(AST_SymbolRef, function(compressor) {
  2452. if (this.name === "arguments") return false;
  2453. if (has_flag(this, UNDEFINED)) return true;
  2454. if (!is_strict(compressor)) return false;
  2455. if (is_undeclared_ref(this) && this.is_declared(compressor)) return false;
  2456. if (this.is_immutable()) return false;
  2457. var fixed = this.fixed_value();
  2458. return !fixed || fixed._dot_throw(compressor);
  2459. });
  2460. })(function(node, func) {
  2461. node.DEFMETHOD("_dot_throw", func);
  2462. });
  2463. /* -----[ boolean/negation helpers ]----- */
  2464. // methods to determine whether an expression has a boolean result type
  2465. (function(def_is_boolean) {
  2466. const unary_bool = makePredicate("! delete");
  2467. const binary_bool = makePredicate("in instanceof == != === !== < <= >= >");
  2468. def_is_boolean(AST_Node, return_false);
  2469. def_is_boolean(AST_UnaryPrefix, function() {
  2470. return unary_bool.has(this.operator);
  2471. });
  2472. def_is_boolean(AST_Binary, function() {
  2473. return binary_bool.has(this.operator)
  2474. || lazy_op.has(this.operator)
  2475. && this.left.is_boolean()
  2476. && this.right.is_boolean();
  2477. });
  2478. def_is_boolean(AST_Conditional, function() {
  2479. return this.consequent.is_boolean() && this.alternative.is_boolean();
  2480. });
  2481. def_is_boolean(AST_Assign, function() {
  2482. return this.operator == "=" && this.right.is_boolean();
  2483. });
  2484. def_is_boolean(AST_Sequence, function() {
  2485. return this.tail_node().is_boolean();
  2486. });
  2487. def_is_boolean(AST_True, return_true);
  2488. def_is_boolean(AST_False, return_true);
  2489. })(function(node, func) {
  2490. node.DEFMETHOD("is_boolean", func);
  2491. });
  2492. // methods to determine if an expression has a numeric result type
  2493. (function(def_is_number) {
  2494. def_is_number(AST_Node, return_false);
  2495. def_is_number(AST_Number, return_true);
  2496. var unary = makePredicate("+ - ~ ++ --");
  2497. def_is_number(AST_Unary, function() {
  2498. return unary.has(this.operator);
  2499. });
  2500. var binary = makePredicate("- * / % & | ^ << >> >>>");
  2501. def_is_number(AST_Binary, function(compressor) {
  2502. return binary.has(this.operator) || this.operator == "+"
  2503. && this.left.is_number(compressor)
  2504. && this.right.is_number(compressor);
  2505. });
  2506. def_is_number(AST_Assign, function(compressor) {
  2507. return binary.has(this.operator.slice(0, -1))
  2508. || this.operator == "=" && this.right.is_number(compressor);
  2509. });
  2510. def_is_number(AST_Sequence, function(compressor) {
  2511. return this.tail_node().is_number(compressor);
  2512. });
  2513. def_is_number(AST_Conditional, function(compressor) {
  2514. return this.consequent.is_number(compressor) && this.alternative.is_number(compressor);
  2515. });
  2516. })(function(node, func) {
  2517. node.DEFMETHOD("is_number", func);
  2518. });
  2519. // methods to determine if an expression has a string result type
  2520. (function(def_is_string) {
  2521. def_is_string(AST_Node, return_false);
  2522. def_is_string(AST_String, return_true);
  2523. def_is_string(AST_TemplateString, return_true);
  2524. def_is_string(AST_UnaryPrefix, function() {
  2525. return this.operator == "typeof";
  2526. });
  2527. def_is_string(AST_Binary, function(compressor) {
  2528. return this.operator == "+" &&
  2529. (this.left.is_string(compressor) || this.right.is_string(compressor));
  2530. });
  2531. def_is_string(AST_Assign, function(compressor) {
  2532. return (this.operator == "=" || this.operator == "+=") && this.right.is_string(compressor);
  2533. });
  2534. def_is_string(AST_Sequence, function(compressor) {
  2535. return this.tail_node().is_string(compressor);
  2536. });
  2537. def_is_string(AST_Conditional, function(compressor) {
  2538. return this.consequent.is_string(compressor) && this.alternative.is_string(compressor);
  2539. });
  2540. })(function(node, func) {
  2541. node.DEFMETHOD("is_string", func);
  2542. });
  2543. var lazy_op = makePredicate("&& || ??");
  2544. var unary_side_effects = makePredicate("delete ++ --");
  2545. function is_lhs(node, parent) {
  2546. if (parent instanceof AST_Unary && unary_side_effects.has(parent.operator)) return parent.expression;
  2547. if (parent instanceof AST_Assign && parent.left === node) return node;
  2548. }
  2549. (function(def_find_defs) {
  2550. function to_node(value, orig) {
  2551. if (value instanceof AST_Node) return make_node(value.CTOR, orig, value);
  2552. if (Array.isArray(value)) return make_node(AST_Array, orig, {
  2553. elements: value.map(function(value) {
  2554. return to_node(value, orig);
  2555. })
  2556. });
  2557. if (value && typeof value == "object") {
  2558. var props = [];
  2559. for (var key in value) if (HOP(value, key)) {
  2560. props.push(make_node(AST_ObjectKeyVal, orig, {
  2561. key: key,
  2562. value: to_node(value[key], orig)
  2563. }));
  2564. }
  2565. return make_node(AST_Object, orig, {
  2566. properties: props
  2567. });
  2568. }
  2569. return make_node_from_constant(value, orig);
  2570. }
  2571. AST_Toplevel.DEFMETHOD("resolve_defines", function(compressor) {
  2572. if (!compressor.option("global_defs")) return this;
  2573. this.figure_out_scope({ ie8: compressor.option("ie8") });
  2574. return this.transform(new TreeTransformer(function(node) {
  2575. var def = node._find_defs(compressor, "");
  2576. if (!def) return;
  2577. var level = 0, child = node, parent;
  2578. while (parent = this.parent(level++)) {
  2579. if (!(parent instanceof AST_PropAccess)) break;
  2580. if (parent.expression !== child) break;
  2581. child = parent;
  2582. }
  2583. if (is_lhs(child, parent)) {
  2584. return;
  2585. }
  2586. return def;
  2587. }));
  2588. });
  2589. def_find_defs(AST_Node, noop);
  2590. def_find_defs(AST_Chain, function(compressor, suffix) {
  2591. return this.expression._find_defs(compressor, suffix);
  2592. });
  2593. def_find_defs(AST_Dot, function(compressor, suffix) {
  2594. return this.expression._find_defs(compressor, "." + this.property + suffix);
  2595. });
  2596. def_find_defs(AST_SymbolDeclaration, function() {
  2597. if (!this.global()) return;
  2598. });
  2599. def_find_defs(AST_SymbolRef, function(compressor, suffix) {
  2600. if (!this.global()) return;
  2601. var defines = compressor.option("global_defs");
  2602. var name = this.name + suffix;
  2603. if (HOP(defines, name)) return to_node(defines[name], this);
  2604. });
  2605. })(function(node, func) {
  2606. node.DEFMETHOD("_find_defs", func);
  2607. });
  2608. function best_of_expression(ast1, ast2) {
  2609. return ast1.size() > ast2.size() ? ast2 : ast1;
  2610. }
  2611. function best_of_statement(ast1, ast2) {
  2612. return best_of_expression(
  2613. make_node(AST_SimpleStatement, ast1, {
  2614. body: ast1
  2615. }),
  2616. make_node(AST_SimpleStatement, ast2, {
  2617. body: ast2
  2618. })
  2619. ).body;
  2620. }
  2621. function best_of(compressor, ast1, ast2) {
  2622. return (first_in_statement(compressor) ? best_of_statement : best_of_expression)(ast1, ast2);
  2623. }
  2624. function convert_to_predicate(obj) {
  2625. const out = new Map();
  2626. for (var key of Object.keys(obj)) {
  2627. out.set(key, makePredicate(obj[key]));
  2628. }
  2629. return out;
  2630. }
  2631. var object_fns = [
  2632. "constructor",
  2633. "toString",
  2634. "valueOf",
  2635. ];
  2636. var native_fns = convert_to_predicate({
  2637. Array: [
  2638. "indexOf",
  2639. "join",
  2640. "lastIndexOf",
  2641. "slice",
  2642. ].concat(object_fns),
  2643. Boolean: object_fns,
  2644. Function: object_fns,
  2645. Number: [
  2646. "toExponential",
  2647. "toFixed",
  2648. "toPrecision",
  2649. ].concat(object_fns),
  2650. Object: object_fns,
  2651. RegExp: [
  2652. "test",
  2653. ].concat(object_fns),
  2654. String: [
  2655. "charAt",
  2656. "charCodeAt",
  2657. "concat",
  2658. "indexOf",
  2659. "italics",
  2660. "lastIndexOf",
  2661. "match",
  2662. "replace",
  2663. "search",
  2664. "slice",
  2665. "split",
  2666. "substr",
  2667. "substring",
  2668. "toLowerCase",
  2669. "toUpperCase",
  2670. "trim",
  2671. ].concat(object_fns),
  2672. });
  2673. var static_fns = convert_to_predicate({
  2674. Array: [
  2675. "isArray",
  2676. ],
  2677. Math: [
  2678. "abs",
  2679. "acos",
  2680. "asin",
  2681. "atan",
  2682. "ceil",
  2683. "cos",
  2684. "exp",
  2685. "floor",
  2686. "log",
  2687. "round",
  2688. "sin",
  2689. "sqrt",
  2690. "tan",
  2691. "atan2",
  2692. "pow",
  2693. "max",
  2694. "min",
  2695. ],
  2696. Number: [
  2697. "isFinite",
  2698. "isNaN",
  2699. ],
  2700. Object: [
  2701. "create",
  2702. "getOwnPropertyDescriptor",
  2703. "getOwnPropertyNames",
  2704. "getPrototypeOf",
  2705. "isExtensible",
  2706. "isFrozen",
  2707. "isSealed",
  2708. "keys",
  2709. ],
  2710. String: [
  2711. "fromCharCode",
  2712. ],
  2713. });
  2714. // methods to evaluate a constant expression
  2715. (function(def_eval) {
  2716. // If the node has been successfully reduced to a constant,
  2717. // then its value is returned; otherwise the element itself
  2718. // is returned.
  2719. // They can be distinguished as constant value is never a
  2720. // descendant of AST_Node.
  2721. AST_Node.DEFMETHOD("evaluate", function(compressor) {
  2722. if (!compressor.option("evaluate")) return this;
  2723. var val = this._eval(compressor, 1);
  2724. if (!val || val instanceof RegExp) return val;
  2725. if (typeof val == "function" || typeof val == "object") return this;
  2726. return val;
  2727. });
  2728. var unaryPrefix = makePredicate("! ~ - + void");
  2729. AST_Node.DEFMETHOD("is_constant", function() {
  2730. // Accomodate when compress option evaluate=false
  2731. // as well as the common constant expressions !0 and -1
  2732. if (this instanceof AST_Constant) {
  2733. return !(this instanceof AST_RegExp);
  2734. } else {
  2735. return this instanceof AST_UnaryPrefix
  2736. && this.expression instanceof AST_Constant
  2737. && unaryPrefix.has(this.operator);
  2738. }
  2739. });
  2740. def_eval(AST_Statement, function() {
  2741. throw new Error(string_template("Cannot evaluate a statement [{file}:{line},{col}]", this.start));
  2742. });
  2743. def_eval(AST_Lambda, return_this);
  2744. def_eval(AST_Class, return_this);
  2745. def_eval(AST_Node, return_this);
  2746. def_eval(AST_Constant, function() {
  2747. return this.getValue();
  2748. });
  2749. def_eval(AST_BigInt, return_this);
  2750. def_eval(AST_RegExp, function(compressor) {
  2751. let evaluated = compressor.evaluated_regexps.get(this);
  2752. if (evaluated === undefined) {
  2753. try {
  2754. evaluated = (0, eval)(this.print_to_string());
  2755. } catch (e) {
  2756. evaluated = null;
  2757. }
  2758. compressor.evaluated_regexps.set(this, evaluated);
  2759. }
  2760. return evaluated || this;
  2761. });
  2762. def_eval(AST_TemplateString, function() {
  2763. if (this.segments.length !== 1) return this;
  2764. return this.segments[0].value;
  2765. });
  2766. def_eval(AST_Function, function(compressor) {
  2767. if (compressor.option("unsafe")) {
  2768. var fn = function() {};
  2769. fn.node = this;
  2770. fn.toString = () => this.print_to_string();
  2771. return fn;
  2772. }
  2773. return this;
  2774. });
  2775. def_eval(AST_Array, function(compressor, depth) {
  2776. if (compressor.option("unsafe")) {
  2777. var elements = [];
  2778. for (var i = 0, len = this.elements.length; i < len; i++) {
  2779. var element = this.elements[i];
  2780. var value = element._eval(compressor, depth);
  2781. if (element === value) return this;
  2782. elements.push(value);
  2783. }
  2784. return elements;
  2785. }
  2786. return this;
  2787. });
  2788. def_eval(AST_Object, function(compressor, depth) {
  2789. if (compressor.option("unsafe")) {
  2790. var val = {};
  2791. for (var i = 0, len = this.properties.length; i < len; i++) {
  2792. var prop = this.properties[i];
  2793. if (prop instanceof AST_Expansion) return this;
  2794. var key = prop.key;
  2795. if (key instanceof AST_Symbol) {
  2796. key = key.name;
  2797. } else if (key instanceof AST_Node) {
  2798. key = key._eval(compressor, depth);
  2799. if (key === prop.key) return this;
  2800. }
  2801. if (typeof Object.prototype[key] === "function") {
  2802. return this;
  2803. }
  2804. if (prop.value instanceof AST_Function) continue;
  2805. val[key] = prop.value._eval(compressor, depth);
  2806. if (val[key] === prop.value) return this;
  2807. }
  2808. return val;
  2809. }
  2810. return this;
  2811. });
  2812. var non_converting_unary = makePredicate("! typeof void");
  2813. def_eval(AST_UnaryPrefix, function(compressor, depth) {
  2814. var e = this.expression;
  2815. // Function would be evaluated to an array and so typeof would
  2816. // incorrectly return 'object'. Hence making is a special case.
  2817. if (compressor.option("typeofs")
  2818. && this.operator == "typeof"
  2819. && (e instanceof AST_Lambda
  2820. || e instanceof AST_SymbolRef
  2821. && e.fixed_value() instanceof AST_Lambda)) {
  2822. return typeof function() {};
  2823. }
  2824. if (!non_converting_unary.has(this.operator)) depth++;
  2825. e = e._eval(compressor, depth);
  2826. if (e === this.expression) return this;
  2827. switch (this.operator) {
  2828. case "!": return !e;
  2829. case "typeof":
  2830. // typeof <RegExp> returns "object" or "function" on different platforms
  2831. // so cannot evaluate reliably
  2832. if (e instanceof RegExp) return this;
  2833. return typeof e;
  2834. case "void": return void e;
  2835. case "~": return ~e;
  2836. case "-": return -e;
  2837. case "+": return +e;
  2838. }
  2839. return this;
  2840. });
  2841. var non_converting_binary = makePredicate("&& || ?? === !==");
  2842. const identity_comparison = makePredicate("== != === !==");
  2843. const has_identity = value =>
  2844. typeof value === "object"
  2845. || typeof value === "function"
  2846. || typeof value === "symbol";
  2847. def_eval(AST_Binary, function(compressor, depth) {
  2848. if (!non_converting_binary.has(this.operator)) depth++;
  2849. var left = this.left._eval(compressor, depth);
  2850. if (left === this.left) return this;
  2851. var right = this.right._eval(compressor, depth);
  2852. if (right === this.right) return this;
  2853. var result;
  2854. if (
  2855. left != null
  2856. && right != null
  2857. && identity_comparison.has(this.operator)
  2858. && has_identity(left)
  2859. && has_identity(right)
  2860. && typeof left === typeof right
  2861. ) {
  2862. // Do not compare by reference
  2863. return this;
  2864. }
  2865. switch (this.operator) {
  2866. case "&&" : result = left && right; break;
  2867. case "||" : result = left || right; break;
  2868. case "??" : result = left != null ? left : right; break;
  2869. case "|" : result = left | right; break;
  2870. case "&" : result = left & right; break;
  2871. case "^" : result = left ^ right; break;
  2872. case "+" : result = left + right; break;
  2873. case "*" : result = left * right; break;
  2874. case "**" : result = Math.pow(left, right); break;
  2875. case "/" : result = left / right; break;
  2876. case "%" : result = left % right; break;
  2877. case "-" : result = left - right; break;
  2878. case "<<" : result = left << right; break;
  2879. case ">>" : result = left >> right; break;
  2880. case ">>>" : result = left >>> right; break;
  2881. case "==" : result = left == right; break;
  2882. case "===" : result = left === right; break;
  2883. case "!=" : result = left != right; break;
  2884. case "!==" : result = left !== right; break;
  2885. case "<" : result = left < right; break;
  2886. case "<=" : result = left <= right; break;
  2887. case ">" : result = left > right; break;
  2888. case ">=" : result = left >= right; break;
  2889. default:
  2890. return this;
  2891. }
  2892. if (isNaN(result) && compressor.find_parent(AST_With)) {
  2893. // leave original expression as is
  2894. return this;
  2895. }
  2896. return result;
  2897. });
  2898. def_eval(AST_Conditional, function(compressor, depth) {
  2899. var condition = this.condition._eval(compressor, depth);
  2900. if (condition === this.condition) return this;
  2901. var node = condition ? this.consequent : this.alternative;
  2902. var value = node._eval(compressor, depth);
  2903. return value === node ? this : value;
  2904. });
  2905. // Set of AST_SymbolRef which are currently being evaluated.
  2906. // Avoids infinite recursion of ._eval()
  2907. const reentrant_ref_eval = new Set();
  2908. def_eval(AST_SymbolRef, function(compressor, depth) {
  2909. if (reentrant_ref_eval.has(this)) return this;
  2910. var fixed = this.fixed_value();
  2911. if (!fixed) return this;
  2912. reentrant_ref_eval.add(this);
  2913. const value = fixed._eval(compressor, depth);
  2914. reentrant_ref_eval.delete(this);
  2915. if (value === fixed) return this;
  2916. if (value && typeof value == "object") {
  2917. var escaped = this.definition().escaped;
  2918. if (escaped && depth > escaped) return this;
  2919. }
  2920. return value;
  2921. });
  2922. var global_objs = { Array, Math, Number, Object, String };
  2923. var static_values = convert_to_predicate({
  2924. Math: [
  2925. "E",
  2926. "LN10",
  2927. "LN2",
  2928. "LOG2E",
  2929. "LOG10E",
  2930. "PI",
  2931. "SQRT1_2",
  2932. "SQRT2",
  2933. ],
  2934. Number: [
  2935. "MAX_VALUE",
  2936. "MIN_VALUE",
  2937. "NaN",
  2938. "NEGATIVE_INFINITY",
  2939. "POSITIVE_INFINITY",
  2940. ],
  2941. });
  2942. const regexp_flags = new Set([
  2943. "dotAll",
  2944. "global",
  2945. "ignoreCase",
  2946. "multiline",
  2947. "sticky",
  2948. "unicode",
  2949. ]);
  2950. def_eval(AST_PropAccess, function(compressor, depth) {
  2951. if (this.optional) {
  2952. const obj = this.expression._eval(compressor, depth);
  2953. if (obj == null) return undefined;
  2954. }
  2955. if (compressor.option("unsafe")) {
  2956. var key = this.property;
  2957. if (key instanceof AST_Node) {
  2958. key = key._eval(compressor, depth);
  2959. if (key === this.property) return this;
  2960. }
  2961. var exp = this.expression;
  2962. var val;
  2963. if (is_undeclared_ref(exp)) {
  2964. var aa;
  2965. var first_arg = exp.name === "hasOwnProperty"
  2966. && key === "call"
  2967. && (aa = compressor.parent() && compressor.parent().args)
  2968. && (aa && aa[0]
  2969. && aa[0].evaluate(compressor));
  2970. first_arg = first_arg instanceof AST_Dot ? first_arg.expression : first_arg;
  2971. if (first_arg == null || first_arg.thedef && first_arg.thedef.undeclared) {
  2972. return this.clone();
  2973. }
  2974. var static_value = static_values.get(exp.name);
  2975. if (!static_value || !static_value.has(key)) return this;
  2976. val = global_objs[exp.name];
  2977. } else {
  2978. val = exp._eval(compressor, depth + 1);
  2979. if (val instanceof RegExp) {
  2980. if (key == "source") {
  2981. return regexp_source_fix(val.source);
  2982. } else if (key == "flags" || regexp_flags.has(key)) {
  2983. return val[key];
  2984. }
  2985. }
  2986. if (!val || val === exp || !HOP(val, key)) return this;
  2987. if (typeof val == "function") switch (key) {
  2988. case "name":
  2989. return val.node.name ? val.node.name.name : "";
  2990. case "length":
  2991. return val.node.length_property();
  2992. default:
  2993. return this;
  2994. }
  2995. }
  2996. return val[key];
  2997. }
  2998. return this;
  2999. });
  3000. def_eval(AST_Chain, function(compressor, depth) {
  3001. const evaluated = this.expression._eval(compressor, depth);
  3002. return evaluated === this.expression ? this : evaluated;
  3003. });
  3004. def_eval(AST_Call, function(compressor, depth) {
  3005. var exp = this.expression;
  3006. if (this.optional) {
  3007. const callee = this.expression._eval(compressor, depth);
  3008. if (callee == null) return undefined;
  3009. }
  3010. if (compressor.option("unsafe") && exp instanceof AST_PropAccess) {
  3011. var key = exp.property;
  3012. if (key instanceof AST_Node) {
  3013. key = key._eval(compressor, depth);
  3014. if (key === exp.property) return this;
  3015. }
  3016. var val;
  3017. var e = exp.expression;
  3018. if (is_undeclared_ref(e)) {
  3019. var first_arg =
  3020. e.name === "hasOwnProperty" &&
  3021. key === "call" &&
  3022. (this.args[0] && this.args[0].evaluate(compressor));
  3023. first_arg = first_arg instanceof AST_Dot ? first_arg.expression : first_arg;
  3024. if ((first_arg == null || first_arg.thedef && first_arg.thedef.undeclared)) {
  3025. return this.clone();
  3026. }
  3027. var static_fn = static_fns.get(e.name);
  3028. if (!static_fn || !static_fn.has(key)) return this;
  3029. val = global_objs[e.name];
  3030. } else {
  3031. val = e._eval(compressor, depth + 1);
  3032. if (val === e || !val) return this;
  3033. var native_fn = native_fns.get(val.constructor.name);
  3034. if (!native_fn || !native_fn.has(key)) return this;
  3035. }
  3036. var args = [];
  3037. for (var i = 0, len = this.args.length; i < len; i++) {
  3038. var arg = this.args[i];
  3039. var value = arg._eval(compressor, depth);
  3040. if (arg === value) return this;
  3041. if (arg instanceof AST_Lambda) return this;
  3042. args.push(value);
  3043. }
  3044. try {
  3045. return val[key].apply(val, args);
  3046. } catch (ex) {
  3047. // We don't really care
  3048. }
  3049. }
  3050. return this;
  3051. });
  3052. def_eval(AST_New, return_this);
  3053. })(function(node, func) {
  3054. node.DEFMETHOD("_eval", func);
  3055. });
  3056. // method to negate an expression
  3057. (function(def_negate) {
  3058. function basic_negation(exp) {
  3059. return make_node(AST_UnaryPrefix, exp, {
  3060. operator: "!",
  3061. expression: exp
  3062. });
  3063. }
  3064. function best(orig, alt, first_in_statement) {
  3065. var negated = basic_negation(orig);
  3066. if (first_in_statement) {
  3067. var stat = make_node(AST_SimpleStatement, alt, {
  3068. body: alt
  3069. });
  3070. return best_of_expression(negated, stat) === stat ? alt : negated;
  3071. }
  3072. return best_of_expression(negated, alt);
  3073. }
  3074. def_negate(AST_Node, function() {
  3075. return basic_negation(this);
  3076. });
  3077. def_negate(AST_Statement, function() {
  3078. throw new Error("Cannot negate a statement");
  3079. });
  3080. def_negate(AST_Function, function() {
  3081. return basic_negation(this);
  3082. });
  3083. def_negate(AST_Arrow, function() {
  3084. return basic_negation(this);
  3085. });
  3086. def_negate(AST_UnaryPrefix, function() {
  3087. if (this.operator == "!")
  3088. return this.expression;
  3089. return basic_negation(this);
  3090. });
  3091. def_negate(AST_Sequence, function(compressor) {
  3092. var expressions = this.expressions.slice();
  3093. expressions.push(expressions.pop().negate(compressor));
  3094. return make_sequence(this, expressions);
  3095. });
  3096. def_negate(AST_Conditional, function(compressor, first_in_statement) {
  3097. var self = this.clone();
  3098. self.consequent = self.consequent.negate(compressor);
  3099. self.alternative = self.alternative.negate(compressor);
  3100. return best(this, self, first_in_statement);
  3101. });
  3102. def_negate(AST_Binary, function(compressor, first_in_statement) {
  3103. var self = this.clone(), op = this.operator;
  3104. if (compressor.option("unsafe_comps")) {
  3105. switch (op) {
  3106. case "<=" : self.operator = ">" ; return self;
  3107. case "<" : self.operator = ">=" ; return self;
  3108. case ">=" : self.operator = "<" ; return self;
  3109. case ">" : self.operator = "<=" ; return self;
  3110. }
  3111. }
  3112. switch (op) {
  3113. case "==" : self.operator = "!="; return self;
  3114. case "!=" : self.operator = "=="; return self;
  3115. case "===": self.operator = "!=="; return self;
  3116. case "!==": self.operator = "==="; return self;
  3117. case "&&":
  3118. self.operator = "||";
  3119. self.left = self.left.negate(compressor, first_in_statement);
  3120. self.right = self.right.negate(compressor);
  3121. return best(this, self, first_in_statement);
  3122. case "||":
  3123. self.operator = "&&";
  3124. self.left = self.left.negate(compressor, first_in_statement);
  3125. self.right = self.right.negate(compressor);
  3126. return best(this, self, first_in_statement);
  3127. case "??":
  3128. self.right = self.right.negate(compressor);
  3129. return best(this, self, first_in_statement);
  3130. }
  3131. return basic_negation(this);
  3132. });
  3133. })(function(node, func) {
  3134. node.DEFMETHOD("negate", function(compressor, first_in_statement) {
  3135. return func.call(this, compressor, first_in_statement);
  3136. });
  3137. });
  3138. var global_pure_fns = makePredicate("Boolean decodeURI decodeURIComponent Date encodeURI encodeURIComponent Error escape EvalError isFinite isNaN Number Object parseFloat parseInt RangeError ReferenceError String SyntaxError TypeError unescape URIError");
  3139. AST_Call.DEFMETHOD("is_callee_pure", function(compressor) {
  3140. if (compressor.option("unsafe")) {
  3141. var expr = this.expression;
  3142. var first_arg = (this.args && this.args[0] && this.args[0].evaluate(compressor));
  3143. if (
  3144. expr.expression && expr.expression.name === "hasOwnProperty" &&
  3145. (first_arg == null || first_arg.thedef && first_arg.thedef.undeclared)
  3146. ) {
  3147. return false;
  3148. }
  3149. if (is_undeclared_ref(expr) && global_pure_fns.has(expr.name)) return true;
  3150. let static_fn;
  3151. if (expr instanceof AST_Dot
  3152. && is_undeclared_ref(expr.expression)
  3153. && (static_fn = static_fns.get(expr.expression.name))
  3154. && static_fn.has(expr.property)) {
  3155. return true;
  3156. }
  3157. }
  3158. return !!has_annotation(this, _PURE) || !compressor.pure_funcs(this);
  3159. });
  3160. AST_Node.DEFMETHOD("is_call_pure", return_false);
  3161. AST_Dot.DEFMETHOD("is_call_pure", function(compressor) {
  3162. if (!compressor.option("unsafe")) return;
  3163. const expr = this.expression;
  3164. let map;
  3165. if (expr instanceof AST_Array) {
  3166. map = native_fns.get("Array");
  3167. } else if (expr.is_boolean()) {
  3168. map = native_fns.get("Boolean");
  3169. } else if (expr.is_number(compressor)) {
  3170. map = native_fns.get("Number");
  3171. } else if (expr instanceof AST_RegExp) {
  3172. map = native_fns.get("RegExp");
  3173. } else if (expr.is_string(compressor)) {
  3174. map = native_fns.get("String");
  3175. } else if (!this.may_throw_on_access(compressor)) {
  3176. map = native_fns.get("Object");
  3177. }
  3178. return map && map.has(this.property);
  3179. });
  3180. const pure_prop_access_globals = new Set([
  3181. "Number",
  3182. "String",
  3183. "Array",
  3184. "Object",
  3185. "Function",
  3186. "Promise",
  3187. ]);
  3188. // determine if expression has side effects
  3189. (function(def_has_side_effects) {
  3190. def_has_side_effects(AST_Node, return_true);
  3191. def_has_side_effects(AST_EmptyStatement, return_false);
  3192. def_has_side_effects(AST_Constant, return_false);
  3193. def_has_side_effects(AST_This, return_false);
  3194. function any(list, compressor) {
  3195. for (var i = list.length; --i >= 0;)
  3196. if (list[i].has_side_effects(compressor))
  3197. return true;
  3198. return false;
  3199. }
  3200. def_has_side_effects(AST_Block, function(compressor) {
  3201. return any(this.body, compressor);
  3202. });
  3203. def_has_side_effects(AST_Call, function(compressor) {
  3204. if (
  3205. !this.is_callee_pure(compressor)
  3206. && (!this.expression.is_call_pure(compressor)
  3207. || this.expression.has_side_effects(compressor))
  3208. ) {
  3209. return true;
  3210. }
  3211. return any(this.args, compressor);
  3212. });
  3213. def_has_side_effects(AST_Switch, function(compressor) {
  3214. return this.expression.has_side_effects(compressor)
  3215. || any(this.body, compressor);
  3216. });
  3217. def_has_side_effects(AST_Case, function(compressor) {
  3218. return this.expression.has_side_effects(compressor)
  3219. || any(this.body, compressor);
  3220. });
  3221. def_has_side_effects(AST_Try, function(compressor) {
  3222. return any(this.body, compressor)
  3223. || this.bcatch && this.bcatch.has_side_effects(compressor)
  3224. || this.bfinally && this.bfinally.has_side_effects(compressor);
  3225. });
  3226. def_has_side_effects(AST_If, function(compressor) {
  3227. return this.condition.has_side_effects(compressor)
  3228. || this.body && this.body.has_side_effects(compressor)
  3229. || this.alternative && this.alternative.has_side_effects(compressor);
  3230. });
  3231. def_has_side_effects(AST_LabeledStatement, function(compressor) {
  3232. return this.body.has_side_effects(compressor);
  3233. });
  3234. def_has_side_effects(AST_SimpleStatement, function(compressor) {
  3235. return this.body.has_side_effects(compressor);
  3236. });
  3237. def_has_side_effects(AST_Lambda, return_false);
  3238. def_has_side_effects(AST_Class, function (compressor) {
  3239. if (this.extends && this.extends.has_side_effects(compressor)) {
  3240. return true;
  3241. }
  3242. return any(this.properties, compressor);
  3243. });
  3244. def_has_side_effects(AST_Binary, function(compressor) {
  3245. return this.left.has_side_effects(compressor)
  3246. || this.right.has_side_effects(compressor);
  3247. });
  3248. def_has_side_effects(AST_Assign, return_true);
  3249. def_has_side_effects(AST_Conditional, function(compressor) {
  3250. return this.condition.has_side_effects(compressor)
  3251. || this.consequent.has_side_effects(compressor)
  3252. || this.alternative.has_side_effects(compressor);
  3253. });
  3254. def_has_side_effects(AST_Unary, function(compressor) {
  3255. return unary_side_effects.has(this.operator)
  3256. || this.expression.has_side_effects(compressor);
  3257. });
  3258. def_has_side_effects(AST_SymbolRef, function(compressor) {
  3259. return !this.is_declared(compressor) && !pure_prop_access_globals.has(this.name);
  3260. });
  3261. def_has_side_effects(AST_SymbolClassProperty, return_false);
  3262. def_has_side_effects(AST_SymbolDeclaration, return_false);
  3263. def_has_side_effects(AST_Object, function(compressor) {
  3264. return any(this.properties, compressor);
  3265. });
  3266. def_has_side_effects(AST_ObjectProperty, function(compressor) {
  3267. return (
  3268. this.computed_key() && this.key.has_side_effects(compressor)
  3269. || this.value && this.value.has_side_effects(compressor)
  3270. );
  3271. });
  3272. def_has_side_effects(AST_ClassProperty, function(compressor) {
  3273. return (
  3274. this.computed_key() && this.key.has_side_effects(compressor)
  3275. || this.static && this.value && this.value.has_side_effects(compressor)
  3276. );
  3277. });
  3278. def_has_side_effects(AST_ConciseMethod, function(compressor) {
  3279. return this.computed_key() && this.key.has_side_effects(compressor);
  3280. });
  3281. def_has_side_effects(AST_ObjectGetter, function(compressor) {
  3282. return this.computed_key() && this.key.has_side_effects(compressor);
  3283. });
  3284. def_has_side_effects(AST_ObjectSetter, function(compressor) {
  3285. return this.computed_key() && this.key.has_side_effects(compressor);
  3286. });
  3287. def_has_side_effects(AST_Array, function(compressor) {
  3288. return any(this.elements, compressor);
  3289. });
  3290. def_has_side_effects(AST_Dot, function(compressor) {
  3291. return !this.optional && this.expression.may_throw_on_access(compressor)
  3292. || this.expression.has_side_effects(compressor);
  3293. });
  3294. def_has_side_effects(AST_Sub, function(compressor) {
  3295. if (this.optional && is_nullish(this.expression)) {
  3296. return false;
  3297. }
  3298. return !this.optional && this.expression.may_throw_on_access(compressor)
  3299. || this.expression.has_side_effects(compressor)
  3300. || this.property.has_side_effects(compressor);
  3301. });
  3302. def_has_side_effects(AST_Chain, function (compressor) {
  3303. return this.expression.has_side_effects(compressor);
  3304. });
  3305. def_has_side_effects(AST_Sequence, function(compressor) {
  3306. return any(this.expressions, compressor);
  3307. });
  3308. def_has_side_effects(AST_Definitions, function(compressor) {
  3309. return any(this.definitions, compressor);
  3310. });
  3311. def_has_side_effects(AST_VarDef, function() {
  3312. return this.value;
  3313. });
  3314. def_has_side_effects(AST_TemplateSegment, return_false);
  3315. def_has_side_effects(AST_TemplateString, function(compressor) {
  3316. return any(this.segments, compressor);
  3317. });
  3318. })(function(node, func) {
  3319. node.DEFMETHOD("has_side_effects", func);
  3320. });
  3321. // determine if expression may throw
  3322. (function(def_may_throw) {
  3323. def_may_throw(AST_Node, return_true);
  3324. def_may_throw(AST_Constant, return_false);
  3325. def_may_throw(AST_EmptyStatement, return_false);
  3326. def_may_throw(AST_Lambda, return_false);
  3327. def_may_throw(AST_SymbolDeclaration, return_false);
  3328. def_may_throw(AST_This, return_false);
  3329. function any(list, compressor) {
  3330. for (var i = list.length; --i >= 0;)
  3331. if (list[i].may_throw(compressor))
  3332. return true;
  3333. return false;
  3334. }
  3335. def_may_throw(AST_Class, function(compressor) {
  3336. if (this.extends && this.extends.may_throw(compressor)) return true;
  3337. return any(this.properties, compressor);
  3338. });
  3339. def_may_throw(AST_Array, function(compressor) {
  3340. return any(this.elements, compressor);
  3341. });
  3342. def_may_throw(AST_Assign, function(compressor) {
  3343. if (this.right.may_throw(compressor)) return true;
  3344. if (!compressor.has_directive("use strict")
  3345. && this.operator == "="
  3346. && this.left instanceof AST_SymbolRef) {
  3347. return false;
  3348. }
  3349. return this.left.may_throw(compressor);
  3350. });
  3351. def_may_throw(AST_Binary, function(compressor) {
  3352. return this.left.may_throw(compressor)
  3353. || this.right.may_throw(compressor);
  3354. });
  3355. def_may_throw(AST_Block, function(compressor) {
  3356. return any(this.body, compressor);
  3357. });
  3358. def_may_throw(AST_Call, function(compressor) {
  3359. if (this.optional && is_nullish(this.expression)) return false;
  3360. if (any(this.args, compressor)) return true;
  3361. if (this.is_callee_pure(compressor)) return false;
  3362. if (this.expression.may_throw(compressor)) return true;
  3363. return !(this.expression instanceof AST_Lambda)
  3364. || any(this.expression.body, compressor);
  3365. });
  3366. def_may_throw(AST_Case, function(compressor) {
  3367. return this.expression.may_throw(compressor)
  3368. || any(this.body, compressor);
  3369. });
  3370. def_may_throw(AST_Conditional, function(compressor) {
  3371. return this.condition.may_throw(compressor)
  3372. || this.consequent.may_throw(compressor)
  3373. || this.alternative.may_throw(compressor);
  3374. });
  3375. def_may_throw(AST_Definitions, function(compressor) {
  3376. return any(this.definitions, compressor);
  3377. });
  3378. def_may_throw(AST_If, function(compressor) {
  3379. return this.condition.may_throw(compressor)
  3380. || this.body && this.body.may_throw(compressor)
  3381. || this.alternative && this.alternative.may_throw(compressor);
  3382. });
  3383. def_may_throw(AST_LabeledStatement, function(compressor) {
  3384. return this.body.may_throw(compressor);
  3385. });
  3386. def_may_throw(AST_Object, function(compressor) {
  3387. return any(this.properties, compressor);
  3388. });
  3389. def_may_throw(AST_ObjectProperty, function(compressor) {
  3390. // TODO key may throw too
  3391. return this.value ? this.value.may_throw(compressor) : false;
  3392. });
  3393. def_may_throw(AST_ClassProperty, function(compressor) {
  3394. return (
  3395. this.computed_key() && this.key.may_throw(compressor)
  3396. || this.static && this.value && this.value.may_throw(compressor)
  3397. );
  3398. });
  3399. def_may_throw(AST_ConciseMethod, function(compressor) {
  3400. return this.computed_key() && this.key.may_throw(compressor);
  3401. });
  3402. def_may_throw(AST_ObjectGetter, function(compressor) {
  3403. return this.computed_key() && this.key.may_throw(compressor);
  3404. });
  3405. def_may_throw(AST_ObjectSetter, function(compressor) {
  3406. return this.computed_key() && this.key.may_throw(compressor);
  3407. });
  3408. def_may_throw(AST_Return, function(compressor) {
  3409. return this.value && this.value.may_throw(compressor);
  3410. });
  3411. def_may_throw(AST_Sequence, function(compressor) {
  3412. return any(this.expressions, compressor);
  3413. });
  3414. def_may_throw(AST_SimpleStatement, function(compressor) {
  3415. return this.body.may_throw(compressor);
  3416. });
  3417. def_may_throw(AST_Dot, function(compressor) {
  3418. return !this.optional && this.expression.may_throw_on_access(compressor)
  3419. || this.expression.may_throw(compressor);
  3420. });
  3421. def_may_throw(AST_Sub, function(compressor) {
  3422. if (this.optional && is_nullish(this.expression)) return false;
  3423. return !this.optional && this.expression.may_throw_on_access(compressor)
  3424. || this.expression.may_throw(compressor)
  3425. || this.property.may_throw(compressor);
  3426. });
  3427. def_may_throw(AST_Chain, function(compressor) {
  3428. return this.expression.may_throw(compressor);
  3429. });
  3430. def_may_throw(AST_Switch, function(compressor) {
  3431. return this.expression.may_throw(compressor)
  3432. || any(this.body, compressor);
  3433. });
  3434. def_may_throw(AST_SymbolRef, function(compressor) {
  3435. return !this.is_declared(compressor) && !pure_prop_access_globals.has(this.name);
  3436. });
  3437. def_may_throw(AST_SymbolClassProperty, return_false);
  3438. def_may_throw(AST_Try, function(compressor) {
  3439. return this.bcatch ? this.bcatch.may_throw(compressor) : any(this.body, compressor)
  3440. || this.bfinally && this.bfinally.may_throw(compressor);
  3441. });
  3442. def_may_throw(AST_Unary, function(compressor) {
  3443. if (this.operator == "typeof" && this.expression instanceof AST_SymbolRef)
  3444. return false;
  3445. return this.expression.may_throw(compressor);
  3446. });
  3447. def_may_throw(AST_VarDef, function(compressor) {
  3448. if (!this.value) return false;
  3449. return this.value.may_throw(compressor);
  3450. });
  3451. })(function(node, func) {
  3452. node.DEFMETHOD("may_throw", func);
  3453. });
  3454. // determine if expression is constant
  3455. (function(def_is_constant_expression) {
  3456. function all_refs_local(scope) {
  3457. let result = true;
  3458. walk(this, node => {
  3459. if (node instanceof AST_SymbolRef) {
  3460. if (has_flag(this, INLINED)) {
  3461. result = false;
  3462. return walk_abort;
  3463. }
  3464. var def = node.definition();
  3465. if (
  3466. member(def, this.enclosed)
  3467. && !this.variables.has(def.name)
  3468. ) {
  3469. if (scope) {
  3470. var scope_def = scope.find_variable(node);
  3471. if (def.undeclared ? !scope_def : scope_def === def) {
  3472. result = "f";
  3473. return true;
  3474. }
  3475. }
  3476. result = false;
  3477. return walk_abort;
  3478. }
  3479. return true;
  3480. }
  3481. if (node instanceof AST_This && this instanceof AST_Arrow) {
  3482. // TODO check arguments too!
  3483. result = false;
  3484. return walk_abort;
  3485. }
  3486. });
  3487. return result;
  3488. }
  3489. def_is_constant_expression(AST_Node, return_false);
  3490. def_is_constant_expression(AST_Constant, return_true);
  3491. def_is_constant_expression(AST_Class, function(scope) {
  3492. if (this.extends && !this.extends.is_constant_expression(scope)) {
  3493. return false;
  3494. }
  3495. for (const prop of this.properties) {
  3496. if (prop.computed_key() && !prop.key.is_constant_expression(scope)) {
  3497. return false;
  3498. }
  3499. if (prop.static && prop.value && !prop.value.is_constant_expression(scope)) {
  3500. return false;
  3501. }
  3502. }
  3503. return all_refs_local.call(this, scope);
  3504. });
  3505. def_is_constant_expression(AST_Lambda, all_refs_local);
  3506. def_is_constant_expression(AST_Unary, function() {
  3507. return this.expression.is_constant_expression();
  3508. });
  3509. def_is_constant_expression(AST_Binary, function() {
  3510. return this.left.is_constant_expression()
  3511. && this.right.is_constant_expression();
  3512. });
  3513. def_is_constant_expression(AST_Array, function() {
  3514. return this.elements.every((l) => l.is_constant_expression());
  3515. });
  3516. def_is_constant_expression(AST_Object, function() {
  3517. return this.properties.every((l) => l.is_constant_expression());
  3518. });
  3519. def_is_constant_expression(AST_ObjectProperty, function() {
  3520. return !!(!(this.key instanceof AST_Node) && this.value && this.value.is_constant_expression());
  3521. });
  3522. })(function(node, func) {
  3523. node.DEFMETHOD("is_constant_expression", func);
  3524. });
  3525. // tell me if a statement aborts
  3526. function aborts(thing) {
  3527. return thing && thing.aborts();
  3528. }
  3529. (function(def_aborts) {
  3530. def_aborts(AST_Statement, return_null);
  3531. def_aborts(AST_Jump, return_this);
  3532. function block_aborts() {
  3533. for (var i = 0; i < this.body.length; i++) {
  3534. if (aborts(this.body[i])) {
  3535. return this.body[i];
  3536. }
  3537. }
  3538. return null;
  3539. }
  3540. def_aborts(AST_Import, function() { return null; });
  3541. def_aborts(AST_BlockStatement, block_aborts);
  3542. def_aborts(AST_SwitchBranch, block_aborts);
  3543. def_aborts(AST_If, function() {
  3544. return this.alternative && aborts(this.body) && aborts(this.alternative) && this;
  3545. });
  3546. })(function(node, func) {
  3547. node.DEFMETHOD("aborts", func);
  3548. });
  3549. /* -----[ optimizers ]----- */
  3550. var directives = new Set(["use asm", "use strict"]);
  3551. def_optimize(AST_Directive, function(self, compressor) {
  3552. if (compressor.option("directives")
  3553. && (!directives.has(self.value) || compressor.has_directive(self.value) !== self)) {
  3554. return make_node(AST_EmptyStatement, self);
  3555. }
  3556. return self;
  3557. });
  3558. def_optimize(AST_Debugger, function(self, compressor) {
  3559. if (compressor.option("drop_debugger"))
  3560. return make_node(AST_EmptyStatement, self);
  3561. return self;
  3562. });
  3563. def_optimize(AST_LabeledStatement, function(self, compressor) {
  3564. if (self.body instanceof AST_Break
  3565. && compressor.loopcontrol_target(self.body) === self.body) {
  3566. return make_node(AST_EmptyStatement, self);
  3567. }
  3568. return self.label.references.length == 0 ? self.body : self;
  3569. });
  3570. def_optimize(AST_Block, function(self, compressor) {
  3571. tighten_body(self.body, compressor);
  3572. return self;
  3573. });
  3574. function can_be_extracted_from_if_block(node) {
  3575. return !(
  3576. node instanceof AST_Const
  3577. || node instanceof AST_Let
  3578. || node instanceof AST_Class
  3579. );
  3580. }
  3581. def_optimize(AST_BlockStatement, function(self, compressor) {
  3582. tighten_body(self.body, compressor);
  3583. switch (self.body.length) {
  3584. case 1:
  3585. if (!compressor.has_directive("use strict")
  3586. && compressor.parent() instanceof AST_If
  3587. && can_be_extracted_from_if_block(self.body[0])
  3588. || can_be_evicted_from_block(self.body[0])) {
  3589. return self.body[0];
  3590. }
  3591. break;
  3592. case 0: return make_node(AST_EmptyStatement, self);
  3593. }
  3594. return self;
  3595. });
  3596. function opt_AST_Lambda(self, compressor) {
  3597. tighten_body(self.body, compressor);
  3598. if (compressor.option("side_effects")
  3599. && self.body.length == 1
  3600. && self.body[0] === compressor.has_directive("use strict")) {
  3601. self.body.length = 0;
  3602. }
  3603. return self;
  3604. }
  3605. def_optimize(AST_Lambda, opt_AST_Lambda);
  3606. const r_keep_assign = /keep_assign/;
  3607. AST_Scope.DEFMETHOD("drop_unused", function(compressor) {
  3608. if (!compressor.option("unused")) return;
  3609. if (compressor.has_directive("use asm")) return;
  3610. var self = this;
  3611. if (self.pinned()) return;
  3612. var drop_funcs = !(self instanceof AST_Toplevel) || compressor.toplevel.funcs;
  3613. var drop_vars = !(self instanceof AST_Toplevel) || compressor.toplevel.vars;
  3614. const assign_as_unused = r_keep_assign.test(compressor.option("unused")) ? return_false : function(node) {
  3615. if (node instanceof AST_Assign
  3616. && !node.logical
  3617. && (has_flag(node, WRITE_ONLY) || node.operator == "=")
  3618. ) {
  3619. return node.left;
  3620. }
  3621. if (node instanceof AST_Unary && has_flag(node, WRITE_ONLY)) {
  3622. return node.expression;
  3623. }
  3624. };
  3625. var in_use_ids = new Map();
  3626. var fixed_ids = new Map();
  3627. if (self instanceof AST_Toplevel && compressor.top_retain) {
  3628. self.variables.forEach(function(def) {
  3629. if (compressor.top_retain(def) && !in_use_ids.has(def.id)) {
  3630. in_use_ids.set(def.id, def);
  3631. }
  3632. });
  3633. }
  3634. var var_defs_by_id = new Map();
  3635. var initializations = new Map();
  3636. // pass 1: find out which symbols are directly used in
  3637. // this scope (not in nested scopes).
  3638. var scope = this;
  3639. var tw = new TreeWalker(function(node, descend) {
  3640. if (node instanceof AST_Lambda && node.uses_arguments && !tw.has_directive("use strict")) {
  3641. node.argnames.forEach(function(argname) {
  3642. if (!(argname instanceof AST_SymbolDeclaration)) return;
  3643. var def = argname.definition();
  3644. if (!in_use_ids.has(def.id)) {
  3645. in_use_ids.set(def.id, def);
  3646. }
  3647. });
  3648. }
  3649. if (node === self) return;
  3650. if (node instanceof AST_Defun || node instanceof AST_DefClass) {
  3651. var node_def = node.name.definition();
  3652. const in_export = tw.parent() instanceof AST_Export;
  3653. if (in_export || !drop_funcs && scope === self) {
  3654. if (node_def.global && !in_use_ids.has(node_def.id)) {
  3655. in_use_ids.set(node_def.id, node_def);
  3656. }
  3657. }
  3658. if (node instanceof AST_DefClass) {
  3659. if (
  3660. node.extends
  3661. && (node.extends.has_side_effects(compressor)
  3662. || node.extends.may_throw(compressor))
  3663. ) {
  3664. node.extends.walk(tw);
  3665. }
  3666. for (const prop of node.properties) {
  3667. if (
  3668. prop.has_side_effects(compressor) ||
  3669. prop.may_throw(compressor)
  3670. ) {
  3671. prop.walk(tw);
  3672. }
  3673. }
  3674. }
  3675. map_add(initializations, node_def.id, node);
  3676. return true; // don't go in nested scopes
  3677. }
  3678. if (node instanceof AST_SymbolFunarg && scope === self) {
  3679. map_add(var_defs_by_id, node.definition().id, node);
  3680. }
  3681. if (node instanceof AST_Definitions && scope === self) {
  3682. const in_export = tw.parent() instanceof AST_Export;
  3683. node.definitions.forEach(function(def) {
  3684. if (def.name instanceof AST_SymbolVar) {
  3685. map_add(var_defs_by_id, def.name.definition().id, def);
  3686. }
  3687. if (in_export || !drop_vars) {
  3688. walk(def.name, node => {
  3689. if (node instanceof AST_SymbolDeclaration) {
  3690. const def = node.definition();
  3691. if (
  3692. (in_export || def.global)
  3693. && !in_use_ids.has(def.id)
  3694. ) {
  3695. in_use_ids.set(def.id, def);
  3696. }
  3697. }
  3698. });
  3699. }
  3700. if (def.value) {
  3701. if (def.name instanceof AST_Destructuring) {
  3702. def.walk(tw);
  3703. } else {
  3704. var node_def = def.name.definition();
  3705. map_add(initializations, node_def.id, def.value);
  3706. if (!node_def.chained && def.name.fixed_value() === def.value) {
  3707. fixed_ids.set(node_def.id, def);
  3708. }
  3709. }
  3710. if (def.value.has_side_effects(compressor)) {
  3711. def.value.walk(tw);
  3712. }
  3713. }
  3714. });
  3715. return true;
  3716. }
  3717. return scan_ref_scoped(node, descend);
  3718. });
  3719. self.walk(tw);
  3720. // pass 2: for every used symbol we need to walk its
  3721. // initialization code to figure out if it uses other
  3722. // symbols (that may not be in_use).
  3723. tw = new TreeWalker(scan_ref_scoped);
  3724. in_use_ids.forEach(function (def) {
  3725. var init = initializations.get(def.id);
  3726. if (init) init.forEach(function(init) {
  3727. init.walk(tw);
  3728. });
  3729. });
  3730. // pass 3: we should drop declarations not in_use
  3731. var tt = new TreeTransformer(
  3732. function before(node, descend, in_list) {
  3733. var parent = tt.parent();
  3734. if (drop_vars) {
  3735. const sym = assign_as_unused(node);
  3736. if (sym instanceof AST_SymbolRef) {
  3737. var def = sym.definition();
  3738. var in_use = in_use_ids.has(def.id);
  3739. if (node instanceof AST_Assign) {
  3740. if (!in_use || fixed_ids.has(def.id) && fixed_ids.get(def.id) !== node) {
  3741. return maintain_this_binding(parent, node, node.right.transform(tt));
  3742. }
  3743. } else if (!in_use) return in_list ? MAP.skip : make_node(AST_Number, node, {
  3744. value: 0
  3745. });
  3746. }
  3747. }
  3748. if (scope !== self) return;
  3749. var def;
  3750. if (node.name
  3751. && (node instanceof AST_ClassExpression
  3752. && !keep_name(compressor.option("keep_classnames"), (def = node.name.definition()).name)
  3753. || node instanceof AST_Function
  3754. && !keep_name(compressor.option("keep_fnames"), (def = node.name.definition()).name))) {
  3755. // any declarations with same name will overshadow
  3756. // name of this anonymous function and can therefore
  3757. // never be used anywhere
  3758. if (!in_use_ids.has(def.id) || def.orig.length > 1) node.name = null;
  3759. }
  3760. if (node instanceof AST_Lambda && !(node instanceof AST_Accessor)) {
  3761. var trim = !compressor.option("keep_fargs");
  3762. for (var a = node.argnames, i = a.length; --i >= 0;) {
  3763. var sym = a[i];
  3764. if (sym instanceof AST_Expansion) {
  3765. sym = sym.expression;
  3766. }
  3767. if (sym instanceof AST_DefaultAssign) {
  3768. sym = sym.left;
  3769. }
  3770. // Do not drop destructuring arguments.
  3771. // They constitute a type assertion, so dropping
  3772. // them would stop that TypeError which would happen
  3773. // if someone called it with an incorrectly formatted
  3774. // parameter.
  3775. if (!(sym instanceof AST_Destructuring) && !in_use_ids.has(sym.definition().id)) {
  3776. set_flag(sym, UNUSED);
  3777. if (trim) {
  3778. a.pop();
  3779. }
  3780. } else {
  3781. trim = false;
  3782. }
  3783. }
  3784. }
  3785. if ((node instanceof AST_Defun || node instanceof AST_DefClass) && node !== self) {
  3786. const def = node.name.definition();
  3787. let keep = def.global && !drop_funcs || in_use_ids.has(def.id);
  3788. if (!keep) {
  3789. def.eliminated++;
  3790. if (node instanceof AST_DefClass) {
  3791. // Classes might have extends with side effects
  3792. const side_effects = node.drop_side_effect_free(compressor);
  3793. if (side_effects) {
  3794. return make_node(AST_SimpleStatement, node, {
  3795. body: side_effects
  3796. });
  3797. }
  3798. }
  3799. return in_list ? MAP.skip : make_node(AST_EmptyStatement, node);
  3800. }
  3801. }
  3802. if (node instanceof AST_Definitions && !(parent instanceof AST_ForIn && parent.init === node)) {
  3803. var drop_block = !(parent instanceof AST_Toplevel) && !(node instanceof AST_Var);
  3804. // place uninitialized names at the start
  3805. var body = [], head = [], tail = [];
  3806. // for unused names whose initialization has
  3807. // side effects, we can cascade the init. code
  3808. // into the next one, or next statement.
  3809. var side_effects = [];
  3810. node.definitions.forEach(function(def) {
  3811. if (def.value) def.value = def.value.transform(tt);
  3812. var is_destructure = def.name instanceof AST_Destructuring;
  3813. var sym = is_destructure
  3814. ? new SymbolDef(null, { name: "<destructure>" }) /* fake SymbolDef */
  3815. : def.name.definition();
  3816. if (drop_block && sym.global) return tail.push(def);
  3817. if (!(drop_vars || drop_block)
  3818. || is_destructure
  3819. && (def.name.names.length
  3820. || def.name.is_array
  3821. || compressor.option("pure_getters") != true)
  3822. || in_use_ids.has(sym.id)
  3823. ) {
  3824. if (def.value && fixed_ids.has(sym.id) && fixed_ids.get(sym.id) !== def) {
  3825. def.value = def.value.drop_side_effect_free(compressor);
  3826. }
  3827. if (def.name instanceof AST_SymbolVar) {
  3828. var var_defs = var_defs_by_id.get(sym.id);
  3829. if (var_defs.length > 1 && (!def.value || sym.orig.indexOf(def.name) > sym.eliminated)) {
  3830. if (def.value) {
  3831. var ref = make_node(AST_SymbolRef, def.name, def.name);
  3832. sym.references.push(ref);
  3833. var assign = make_node(AST_Assign, def, {
  3834. operator: "=",
  3835. logical: false,
  3836. left: ref,
  3837. right: def.value
  3838. });
  3839. if (fixed_ids.get(sym.id) === def) {
  3840. fixed_ids.set(sym.id, assign);
  3841. }
  3842. side_effects.push(assign.transform(tt));
  3843. }
  3844. remove(var_defs, def);
  3845. sym.eliminated++;
  3846. return;
  3847. }
  3848. }
  3849. if (def.value) {
  3850. if (side_effects.length > 0) {
  3851. if (tail.length > 0) {
  3852. side_effects.push(def.value);
  3853. def.value = make_sequence(def.value, side_effects);
  3854. } else {
  3855. body.push(make_node(AST_SimpleStatement, node, {
  3856. body: make_sequence(node, side_effects)
  3857. }));
  3858. }
  3859. side_effects = [];
  3860. }
  3861. tail.push(def);
  3862. } else {
  3863. head.push(def);
  3864. }
  3865. } else if (sym.orig[0] instanceof AST_SymbolCatch) {
  3866. var value = def.value && def.value.drop_side_effect_free(compressor);
  3867. if (value) side_effects.push(value);
  3868. def.value = null;
  3869. head.push(def);
  3870. } else {
  3871. var value = def.value && def.value.drop_side_effect_free(compressor);
  3872. if (value) {
  3873. side_effects.push(value);
  3874. }
  3875. sym.eliminated++;
  3876. }
  3877. });
  3878. if (head.length > 0 || tail.length > 0) {
  3879. node.definitions = head.concat(tail);
  3880. body.push(node);
  3881. }
  3882. if (side_effects.length > 0) {
  3883. body.push(make_node(AST_SimpleStatement, node, {
  3884. body: make_sequence(node, side_effects)
  3885. }));
  3886. }
  3887. switch (body.length) {
  3888. case 0:
  3889. return in_list ? MAP.skip : make_node(AST_EmptyStatement, node);
  3890. case 1:
  3891. return body[0];
  3892. default:
  3893. return in_list ? MAP.splice(body) : make_node(AST_BlockStatement, node, {
  3894. body: body
  3895. });
  3896. }
  3897. }
  3898. // certain combination of unused name + side effect leads to:
  3899. // https://github.com/mishoo/UglifyJS2/issues/44
  3900. // https://github.com/mishoo/UglifyJS2/issues/1830
  3901. // https://github.com/mishoo/UglifyJS2/issues/1838
  3902. // that's an invalid AST.
  3903. // We fix it at this stage by moving the `var` outside the `for`.
  3904. if (node instanceof AST_For) {
  3905. descend(node, this);
  3906. var block;
  3907. if (node.init instanceof AST_BlockStatement) {
  3908. block = node.init;
  3909. node.init = block.body.pop();
  3910. block.body.push(node);
  3911. }
  3912. if (node.init instanceof AST_SimpleStatement) {
  3913. node.init = node.init.body;
  3914. } else if (is_empty(node.init)) {
  3915. node.init = null;
  3916. }
  3917. return !block ? node : in_list ? MAP.splice(block.body) : block;
  3918. }
  3919. if (node instanceof AST_LabeledStatement
  3920. && node.body instanceof AST_For
  3921. ) {
  3922. descend(node, this);
  3923. if (node.body instanceof AST_BlockStatement) {
  3924. var block = node.body;
  3925. node.body = block.body.pop();
  3926. block.body.push(node);
  3927. return in_list ? MAP.splice(block.body) : block;
  3928. }
  3929. return node;
  3930. }
  3931. if (node instanceof AST_BlockStatement) {
  3932. descend(node, this);
  3933. if (in_list && node.body.every(can_be_evicted_from_block)) {
  3934. return MAP.splice(node.body);
  3935. }
  3936. return node;
  3937. }
  3938. if (node instanceof AST_Scope) {
  3939. const save_scope = scope;
  3940. scope = node;
  3941. descend(node, this);
  3942. scope = save_scope;
  3943. return node;
  3944. }
  3945. }
  3946. );
  3947. self.transform(tt);
  3948. function scan_ref_scoped(node, descend) {
  3949. var node_def;
  3950. const sym = assign_as_unused(node);
  3951. if (sym instanceof AST_SymbolRef
  3952. && !is_ref_of(node.left, AST_SymbolBlockDeclaration)
  3953. && self.variables.get(sym.name) === (node_def = sym.definition())
  3954. ) {
  3955. if (node instanceof AST_Assign) {
  3956. node.right.walk(tw);
  3957. if (!node_def.chained && node.left.fixed_value() === node.right) {
  3958. fixed_ids.set(node_def.id, node);
  3959. }
  3960. }
  3961. return true;
  3962. }
  3963. if (node instanceof AST_SymbolRef) {
  3964. node_def = node.definition();
  3965. if (!in_use_ids.has(node_def.id)) {
  3966. in_use_ids.set(node_def.id, node_def);
  3967. if (node_def.orig[0] instanceof AST_SymbolCatch) {
  3968. const redef = node_def.scope.is_block_scope()
  3969. && node_def.scope.get_defun_scope().variables.get(node_def.name);
  3970. if (redef) in_use_ids.set(redef.id, redef);
  3971. }
  3972. }
  3973. return true;
  3974. }
  3975. if (node instanceof AST_Scope) {
  3976. var save_scope = scope;
  3977. scope = node;
  3978. descend();
  3979. scope = save_scope;
  3980. return true;
  3981. }
  3982. }
  3983. });
  3984. AST_Scope.DEFMETHOD("hoist_declarations", function(compressor) {
  3985. var self = this;
  3986. if (compressor.has_directive("use asm")) return self;
  3987. // Hoisting makes no sense in an arrow func
  3988. if (!Array.isArray(self.body)) return self;
  3989. var hoist_funs = compressor.option("hoist_funs");
  3990. var hoist_vars = compressor.option("hoist_vars");
  3991. if (hoist_funs || hoist_vars) {
  3992. var dirs = [];
  3993. var hoisted = [];
  3994. var vars = new Map(), vars_found = 0, var_decl = 0;
  3995. // let's count var_decl first, we seem to waste a lot of
  3996. // space if we hoist `var` when there's only one.
  3997. walk(self, node => {
  3998. if (node instanceof AST_Scope && node !== self)
  3999. return true;
  4000. if (node instanceof AST_Var) {
  4001. ++var_decl;
  4002. return true;
  4003. }
  4004. });
  4005. hoist_vars = hoist_vars && var_decl > 1;
  4006. var tt = new TreeTransformer(
  4007. function before(node) {
  4008. if (node !== self) {
  4009. if (node instanceof AST_Directive) {
  4010. dirs.push(node);
  4011. return make_node(AST_EmptyStatement, node);
  4012. }
  4013. if (hoist_funs && node instanceof AST_Defun
  4014. && !(tt.parent() instanceof AST_Export)
  4015. && tt.parent() === self) {
  4016. hoisted.push(node);
  4017. return make_node(AST_EmptyStatement, node);
  4018. }
  4019. if (
  4020. hoist_vars
  4021. && node instanceof AST_Var
  4022. && !node.definitions.some(def => def.name instanceof AST_Destructuring)
  4023. ) {
  4024. node.definitions.forEach(function(def) {
  4025. vars.set(def.name.name, def);
  4026. ++vars_found;
  4027. });
  4028. var seq = node.to_assignments(compressor);
  4029. var p = tt.parent();
  4030. if (p instanceof AST_ForIn && p.init === node) {
  4031. if (seq == null) {
  4032. var def = node.definitions[0].name;
  4033. return make_node(AST_SymbolRef, def, def);
  4034. }
  4035. return seq;
  4036. }
  4037. if (p instanceof AST_For && p.init === node) {
  4038. return seq;
  4039. }
  4040. if (!seq) return make_node(AST_EmptyStatement, node);
  4041. return make_node(AST_SimpleStatement, node, {
  4042. body: seq
  4043. });
  4044. }
  4045. if (node instanceof AST_Scope)
  4046. return node; // to avoid descending in nested scopes
  4047. }
  4048. }
  4049. );
  4050. self = self.transform(tt);
  4051. if (vars_found > 0) {
  4052. // collect only vars which don't show up in self's arguments list
  4053. var defs = [];
  4054. const is_lambda = self instanceof AST_Lambda;
  4055. const args_as_names = is_lambda ? self.args_as_names() : null;
  4056. vars.forEach((def, name) => {
  4057. if (is_lambda && args_as_names.some((x) => x.name === def.name.name)) {
  4058. vars.delete(name);
  4059. } else {
  4060. def = def.clone();
  4061. def.value = null;
  4062. defs.push(def);
  4063. vars.set(name, def);
  4064. }
  4065. });
  4066. if (defs.length > 0) {
  4067. // try to merge in assignments
  4068. for (var i = 0; i < self.body.length;) {
  4069. if (self.body[i] instanceof AST_SimpleStatement) {
  4070. var expr = self.body[i].body, sym, assign;
  4071. if (expr instanceof AST_Assign
  4072. && expr.operator == "="
  4073. && (sym = expr.left) instanceof AST_Symbol
  4074. && vars.has(sym.name)
  4075. ) {
  4076. var def = vars.get(sym.name);
  4077. if (def.value) break;
  4078. def.value = expr.right;
  4079. remove(defs, def);
  4080. defs.push(def);
  4081. self.body.splice(i, 1);
  4082. continue;
  4083. }
  4084. if (expr instanceof AST_Sequence
  4085. && (assign = expr.expressions[0]) instanceof AST_Assign
  4086. && assign.operator == "="
  4087. && (sym = assign.left) instanceof AST_Symbol
  4088. && vars.has(sym.name)
  4089. ) {
  4090. var def = vars.get(sym.name);
  4091. if (def.value) break;
  4092. def.value = assign.right;
  4093. remove(defs, def);
  4094. defs.push(def);
  4095. self.body[i].body = make_sequence(expr, expr.expressions.slice(1));
  4096. continue;
  4097. }
  4098. }
  4099. if (self.body[i] instanceof AST_EmptyStatement) {
  4100. self.body.splice(i, 1);
  4101. continue;
  4102. }
  4103. if (self.body[i] instanceof AST_BlockStatement) {
  4104. self.body.splice(i, 1, ...self.body[i].body);
  4105. continue;
  4106. }
  4107. break;
  4108. }
  4109. defs = make_node(AST_Var, self, {
  4110. definitions: defs
  4111. });
  4112. hoisted.push(defs);
  4113. }
  4114. }
  4115. self.body = dirs.concat(hoisted, self.body);
  4116. }
  4117. return self;
  4118. });
  4119. AST_Scope.DEFMETHOD("hoist_properties", function(compressor) {
  4120. var self = this;
  4121. if (!compressor.option("hoist_props") || compressor.has_directive("use asm")) return self;
  4122. var top_retain = self instanceof AST_Toplevel && compressor.top_retain || return_false;
  4123. var defs_by_id = new Map();
  4124. var hoister = new TreeTransformer(function(node, descend) {
  4125. if (node instanceof AST_Definitions
  4126. && hoister.parent() instanceof AST_Export) return node;
  4127. if (node instanceof AST_VarDef) {
  4128. const sym = node.name;
  4129. let def;
  4130. let value;
  4131. if (sym.scope === self
  4132. && (def = sym.definition()).escaped != 1
  4133. && !def.assignments
  4134. && !def.direct_access
  4135. && !def.single_use
  4136. && !compressor.exposed(def)
  4137. && !top_retain(def)
  4138. && (value = sym.fixed_value()) === node.value
  4139. && value instanceof AST_Object
  4140. && !value.properties.some(prop =>
  4141. prop instanceof AST_Expansion || prop.computed_key()
  4142. )
  4143. ) {
  4144. descend(node, this);
  4145. const defs = new Map();
  4146. const assignments = [];
  4147. value.properties.forEach(({ key, value }) => {
  4148. const scope = find_scope(hoister);
  4149. const symbol = self.create_symbol(sym.CTOR, {
  4150. source: sym,
  4151. scope,
  4152. conflict_scopes: new Set([
  4153. scope,
  4154. ...sym.definition().references.map(ref => ref.scope)
  4155. ]),
  4156. tentative_name: sym.name + "_" + key
  4157. });
  4158. defs.set(String(key), symbol.definition());
  4159. assignments.push(make_node(AST_VarDef, node, {
  4160. name: symbol,
  4161. value
  4162. }));
  4163. });
  4164. defs_by_id.set(def.id, defs);
  4165. return MAP.splice(assignments);
  4166. }
  4167. } else if (node instanceof AST_PropAccess
  4168. && node.expression instanceof AST_SymbolRef
  4169. ) {
  4170. const defs = defs_by_id.get(node.expression.definition().id);
  4171. if (defs) {
  4172. const def = defs.get(String(get_value(node.property)));
  4173. const sym = make_node(AST_SymbolRef, node, {
  4174. name: def.name,
  4175. scope: node.expression.scope,
  4176. thedef: def
  4177. });
  4178. sym.reference({});
  4179. return sym;
  4180. }
  4181. }
  4182. });
  4183. return self.transform(hoister);
  4184. });
  4185. // drop_side_effect_free()
  4186. // remove side-effect-free parts which only affects return value
  4187. (function(def_drop_side_effect_free) {
  4188. // Drop side-effect-free elements from an array of expressions.
  4189. // Returns an array of expressions with side-effects or null
  4190. // if all elements were dropped. Note: original array may be
  4191. // returned if nothing changed.
  4192. function trim(nodes, compressor, first_in_statement) {
  4193. var len = nodes.length;
  4194. if (!len) return null;
  4195. var ret = [], changed = false;
  4196. for (var i = 0; i < len; i++) {
  4197. var node = nodes[i].drop_side_effect_free(compressor, first_in_statement);
  4198. changed |= node !== nodes[i];
  4199. if (node) {
  4200. ret.push(node);
  4201. first_in_statement = false;
  4202. }
  4203. }
  4204. return changed ? ret.length ? ret : null : nodes;
  4205. }
  4206. def_drop_side_effect_free(AST_Node, return_this);
  4207. def_drop_side_effect_free(AST_Constant, return_null);
  4208. def_drop_side_effect_free(AST_This, return_null);
  4209. def_drop_side_effect_free(AST_Call, function(compressor, first_in_statement) {
  4210. if (this.optional && is_nullish(this.expression)) {
  4211. return make_node(AST_Undefined, this);
  4212. }
  4213. if (!this.is_callee_pure(compressor)) {
  4214. if (this.expression.is_call_pure(compressor)) {
  4215. var exprs = this.args.slice();
  4216. exprs.unshift(this.expression.expression);
  4217. exprs = trim(exprs, compressor, first_in_statement);
  4218. return exprs && make_sequence(this, exprs);
  4219. }
  4220. if (is_func_expr(this.expression)
  4221. && (!this.expression.name || !this.expression.name.definition().references.length)) {
  4222. var node = this.clone();
  4223. node.expression.process_expression(false, compressor);
  4224. return node;
  4225. }
  4226. return this;
  4227. }
  4228. var args = trim(this.args, compressor, first_in_statement);
  4229. return args && make_sequence(this, args);
  4230. });
  4231. def_drop_side_effect_free(AST_Accessor, return_null);
  4232. def_drop_side_effect_free(AST_Function, return_null);
  4233. def_drop_side_effect_free(AST_Arrow, return_null);
  4234. def_drop_side_effect_free(AST_Class, function (compressor) {
  4235. const with_effects = [];
  4236. const trimmed_extends = this.extends && this.extends.drop_side_effect_free(compressor);
  4237. if (trimmed_extends) with_effects.push(trimmed_extends);
  4238. for (const prop of this.properties) {
  4239. const trimmed_prop = prop.drop_side_effect_free(compressor);
  4240. if (trimmed_prop) with_effects.push(trimmed_prop);
  4241. }
  4242. if (!with_effects.length) return null;
  4243. return make_sequence(this, with_effects);
  4244. });
  4245. def_drop_side_effect_free(AST_Binary, function(compressor, first_in_statement) {
  4246. var right = this.right.drop_side_effect_free(compressor);
  4247. if (!right) return this.left.drop_side_effect_free(compressor, first_in_statement);
  4248. if (lazy_op.has(this.operator)) {
  4249. if (right === this.right) return this;
  4250. var node = this.clone();
  4251. node.right = right;
  4252. return node;
  4253. } else {
  4254. var left = this.left.drop_side_effect_free(compressor, first_in_statement);
  4255. if (!left) return this.right.drop_side_effect_free(compressor, first_in_statement);
  4256. return make_sequence(this, [ left, right ]);
  4257. }
  4258. });
  4259. def_drop_side_effect_free(AST_Assign, function(compressor) {
  4260. if (this.logical) return this;
  4261. var left = this.left;
  4262. if (left.has_side_effects(compressor)
  4263. || compressor.has_directive("use strict")
  4264. && left instanceof AST_PropAccess
  4265. && left.expression.is_constant()) {
  4266. return this;
  4267. }
  4268. set_flag(this, WRITE_ONLY);
  4269. while (left instanceof AST_PropAccess) {
  4270. left = left.expression;
  4271. }
  4272. if (left.is_constant_expression(compressor.find_parent(AST_Scope))) {
  4273. return this.right.drop_side_effect_free(compressor);
  4274. }
  4275. return this;
  4276. });
  4277. def_drop_side_effect_free(AST_Conditional, function(compressor) {
  4278. var consequent = this.consequent.drop_side_effect_free(compressor);
  4279. var alternative = this.alternative.drop_side_effect_free(compressor);
  4280. if (consequent === this.consequent && alternative === this.alternative) return this;
  4281. if (!consequent) return alternative ? make_node(AST_Binary, this, {
  4282. operator: "||",
  4283. left: this.condition,
  4284. right: alternative
  4285. }) : this.condition.drop_side_effect_free(compressor);
  4286. if (!alternative) return make_node(AST_Binary, this, {
  4287. operator: "&&",
  4288. left: this.condition,
  4289. right: consequent
  4290. });
  4291. var node = this.clone();
  4292. node.consequent = consequent;
  4293. node.alternative = alternative;
  4294. return node;
  4295. });
  4296. def_drop_side_effect_free(AST_Unary, function(compressor, first_in_statement) {
  4297. if (unary_side_effects.has(this.operator)) {
  4298. if (!this.expression.has_side_effects(compressor)) {
  4299. set_flag(this, WRITE_ONLY);
  4300. } else {
  4301. clear_flag(this, WRITE_ONLY);
  4302. }
  4303. return this;
  4304. }
  4305. if (this.operator == "typeof" && this.expression instanceof AST_SymbolRef) return null;
  4306. var expression = this.expression.drop_side_effect_free(compressor, first_in_statement);
  4307. if (first_in_statement && expression && is_iife_call(expression)) {
  4308. if (expression === this.expression && this.operator == "!") return this;
  4309. return expression.negate(compressor, first_in_statement);
  4310. }
  4311. return expression;
  4312. });
  4313. def_drop_side_effect_free(AST_SymbolRef, function(compressor) {
  4314. const safe_access = this.is_declared(compressor)
  4315. || pure_prop_access_globals.has(this.name);
  4316. return safe_access ? null : this;
  4317. });
  4318. def_drop_side_effect_free(AST_Object, function(compressor, first_in_statement) {
  4319. var values = trim(this.properties, compressor, first_in_statement);
  4320. return values && make_sequence(this, values);
  4321. });
  4322. def_drop_side_effect_free(AST_ObjectProperty, function(compressor, first_in_statement) {
  4323. const computed_key = this instanceof AST_ObjectKeyVal && this.key instanceof AST_Node;
  4324. const key = computed_key && this.key.drop_side_effect_free(compressor, first_in_statement);
  4325. const value = this.value && this.value.drop_side_effect_free(compressor, first_in_statement);
  4326. if (key && value) {
  4327. return make_sequence(this, [key, value]);
  4328. }
  4329. return key || value;
  4330. });
  4331. def_drop_side_effect_free(AST_ClassProperty, function (compressor) {
  4332. const key = this.computed_key() && this.key.drop_side_effect_free(compressor);
  4333. const value = this.static && this.value
  4334. && this.value.drop_side_effect_free(compressor);
  4335. if (key && value) return make_sequence(this, [key, value]);
  4336. return key || value || null;
  4337. });
  4338. def_drop_side_effect_free(AST_ConciseMethod, function () {
  4339. return this.computed_key() ? this.key : null;
  4340. });
  4341. def_drop_side_effect_free(AST_ObjectGetter, function () {
  4342. return this.computed_key() ? this.key : null;
  4343. });
  4344. def_drop_side_effect_free(AST_ObjectSetter, function () {
  4345. return this.computed_key() ? this.key : null;
  4346. });
  4347. def_drop_side_effect_free(AST_Array, function(compressor, first_in_statement) {
  4348. var values = trim(this.elements, compressor, first_in_statement);
  4349. return values && make_sequence(this, values);
  4350. });
  4351. def_drop_side_effect_free(AST_Dot, function(compressor, first_in_statement) {
  4352. if (this.optional) {
  4353. return is_nullish(this.expression) ? make_node(AST_Undefined, this) : this;
  4354. }
  4355. if (this.expression.may_throw_on_access(compressor)) return this;
  4356. return this.expression.drop_side_effect_free(compressor, first_in_statement);
  4357. });
  4358. def_drop_side_effect_free(AST_Sub, function(compressor, first_in_statement) {
  4359. if (this.optional) {
  4360. return is_nullish(this.expression) ? make_node(AST_Undefined, this): this;
  4361. }
  4362. if (this.expression.may_throw_on_access(compressor)) return this;
  4363. var expression = this.expression.drop_side_effect_free(compressor, first_in_statement);
  4364. if (!expression) return this.property.drop_side_effect_free(compressor, first_in_statement);
  4365. var property = this.property.drop_side_effect_free(compressor);
  4366. if (!property) return expression;
  4367. return make_sequence(this, [ expression, property ]);
  4368. });
  4369. def_drop_side_effect_free(AST_Chain, function (compressor, first_in_statement) {
  4370. return this.expression.drop_side_effect_free(compressor, first_in_statement);
  4371. });
  4372. def_drop_side_effect_free(AST_Sequence, function(compressor) {
  4373. var last = this.tail_node();
  4374. var expr = last.drop_side_effect_free(compressor);
  4375. if (expr === last) return this;
  4376. var expressions = this.expressions.slice(0, -1);
  4377. if (expr) expressions.push(expr);
  4378. if (!expressions.length) {
  4379. return make_node(AST_Number, this, { value: 0 });
  4380. }
  4381. return make_sequence(this, expressions);
  4382. });
  4383. def_drop_side_effect_free(AST_Expansion, function(compressor, first_in_statement) {
  4384. return this.expression.drop_side_effect_free(compressor, first_in_statement);
  4385. });
  4386. def_drop_side_effect_free(AST_TemplateSegment, return_null);
  4387. def_drop_side_effect_free(AST_TemplateString, function(compressor) {
  4388. var values = trim(this.segments, compressor, first_in_statement);
  4389. return values && make_sequence(this, values);
  4390. });
  4391. })(function(node, func) {
  4392. node.DEFMETHOD("drop_side_effect_free", func);
  4393. });
  4394. def_optimize(AST_SimpleStatement, function(self, compressor) {
  4395. if (compressor.option("side_effects")) {
  4396. var body = self.body;
  4397. var node = body.drop_side_effect_free(compressor, true);
  4398. if (!node) {
  4399. return make_node(AST_EmptyStatement, self);
  4400. }
  4401. if (node !== body) {
  4402. return make_node(AST_SimpleStatement, self, { body: node });
  4403. }
  4404. }
  4405. return self;
  4406. });
  4407. def_optimize(AST_While, function(self, compressor) {
  4408. return compressor.option("loops") ? make_node(AST_For, self, self).optimize(compressor) : self;
  4409. });
  4410. function has_break_or_continue(loop, parent) {
  4411. var found = false;
  4412. var tw = new TreeWalker(function(node) {
  4413. if (found || node instanceof AST_Scope) return true;
  4414. if (node instanceof AST_LoopControl && tw.loopcontrol_target(node) === loop) {
  4415. return found = true;
  4416. }
  4417. });
  4418. if (parent instanceof AST_LabeledStatement) tw.push(parent);
  4419. tw.push(loop);
  4420. loop.body.walk(tw);
  4421. return found;
  4422. }
  4423. def_optimize(AST_Do, function(self, compressor) {
  4424. if (!compressor.option("loops")) return self;
  4425. var cond = self.condition.tail_node().evaluate(compressor);
  4426. if (!(cond instanceof AST_Node)) {
  4427. if (cond) return make_node(AST_For, self, {
  4428. body: make_node(AST_BlockStatement, self.body, {
  4429. body: [
  4430. self.body,
  4431. make_node(AST_SimpleStatement, self.condition, {
  4432. body: self.condition
  4433. })
  4434. ]
  4435. })
  4436. }).optimize(compressor);
  4437. if (!has_break_or_continue(self, compressor.parent())) {
  4438. return make_node(AST_BlockStatement, self.body, {
  4439. body: [
  4440. self.body,
  4441. make_node(AST_SimpleStatement, self.condition, {
  4442. body: self.condition
  4443. })
  4444. ]
  4445. }).optimize(compressor);
  4446. }
  4447. }
  4448. return self;
  4449. });
  4450. function if_break_in_loop(self, compressor) {
  4451. var first = self.body instanceof AST_BlockStatement ? self.body.body[0] : self.body;
  4452. if (compressor.option("dead_code") && is_break(first)) {
  4453. var body = [];
  4454. if (self.init instanceof AST_Statement) {
  4455. body.push(self.init);
  4456. } else if (self.init) {
  4457. body.push(make_node(AST_SimpleStatement, self.init, {
  4458. body: self.init
  4459. }));
  4460. }
  4461. if (self.condition) {
  4462. body.push(make_node(AST_SimpleStatement, self.condition, {
  4463. body: self.condition
  4464. }));
  4465. }
  4466. trim_unreachable_code(compressor, self.body, body);
  4467. return make_node(AST_BlockStatement, self, {
  4468. body: body
  4469. });
  4470. }
  4471. if (first instanceof AST_If) {
  4472. if (is_break(first.body)) {
  4473. if (self.condition) {
  4474. self.condition = make_node(AST_Binary, self.condition, {
  4475. left: self.condition,
  4476. operator: "&&",
  4477. right: first.condition.negate(compressor),
  4478. });
  4479. } else {
  4480. self.condition = first.condition.negate(compressor);
  4481. }
  4482. drop_it(first.alternative);
  4483. } else if (is_break(first.alternative)) {
  4484. if (self.condition) {
  4485. self.condition = make_node(AST_Binary, self.condition, {
  4486. left: self.condition,
  4487. operator: "&&",
  4488. right: first.condition,
  4489. });
  4490. } else {
  4491. self.condition = first.condition;
  4492. }
  4493. drop_it(first.body);
  4494. }
  4495. }
  4496. return self;
  4497. function is_break(node) {
  4498. return node instanceof AST_Break
  4499. && compressor.loopcontrol_target(node) === compressor.self();
  4500. }
  4501. function drop_it(rest) {
  4502. rest = as_statement_array(rest);
  4503. if (self.body instanceof AST_BlockStatement) {
  4504. self.body = self.body.clone();
  4505. self.body.body = rest.concat(self.body.body.slice(1));
  4506. self.body = self.body.transform(compressor);
  4507. } else {
  4508. self.body = make_node(AST_BlockStatement, self.body, {
  4509. body: rest
  4510. }).transform(compressor);
  4511. }
  4512. self = if_break_in_loop(self, compressor);
  4513. }
  4514. }
  4515. def_optimize(AST_For, function(self, compressor) {
  4516. if (!compressor.option("loops")) return self;
  4517. if (compressor.option("side_effects") && self.init) {
  4518. self.init = self.init.drop_side_effect_free(compressor);
  4519. }
  4520. if (self.condition) {
  4521. var cond = self.condition.evaluate(compressor);
  4522. if (!(cond instanceof AST_Node)) {
  4523. if (cond) self.condition = null;
  4524. else if (!compressor.option("dead_code")) {
  4525. var orig = self.condition;
  4526. self.condition = make_node_from_constant(cond, self.condition);
  4527. self.condition = best_of_expression(self.condition.transform(compressor), orig);
  4528. }
  4529. }
  4530. if (compressor.option("dead_code")) {
  4531. if (cond instanceof AST_Node) cond = self.condition.tail_node().evaluate(compressor);
  4532. if (!cond) {
  4533. var body = [];
  4534. trim_unreachable_code(compressor, self.body, body);
  4535. if (self.init instanceof AST_Statement) {
  4536. body.push(self.init);
  4537. } else if (self.init) {
  4538. body.push(make_node(AST_SimpleStatement, self.init, {
  4539. body: self.init
  4540. }));
  4541. }
  4542. body.push(make_node(AST_SimpleStatement, self.condition, {
  4543. body: self.condition
  4544. }));
  4545. return make_node(AST_BlockStatement, self, { body: body }).optimize(compressor);
  4546. }
  4547. }
  4548. }
  4549. return if_break_in_loop(self, compressor);
  4550. });
  4551. def_optimize(AST_If, function(self, compressor) {
  4552. if (is_empty(self.alternative)) self.alternative = null;
  4553. if (!compressor.option("conditionals")) return self;
  4554. // if condition can be statically determined, drop
  4555. // one of the blocks. note, statically determined implies
  4556. // “has no side effects”; also it doesn't work for cases like
  4557. // `x && true`, though it probably should.
  4558. var cond = self.condition.evaluate(compressor);
  4559. if (!compressor.option("dead_code") && !(cond instanceof AST_Node)) {
  4560. var orig = self.condition;
  4561. self.condition = make_node_from_constant(cond, orig);
  4562. self.condition = best_of_expression(self.condition.transform(compressor), orig);
  4563. }
  4564. if (compressor.option("dead_code")) {
  4565. if (cond instanceof AST_Node) cond = self.condition.tail_node().evaluate(compressor);
  4566. if (!cond) {
  4567. var body = [];
  4568. trim_unreachable_code(compressor, self.body, body);
  4569. body.push(make_node(AST_SimpleStatement, self.condition, {
  4570. body: self.condition
  4571. }));
  4572. if (self.alternative) body.push(self.alternative);
  4573. return make_node(AST_BlockStatement, self, { body: body }).optimize(compressor);
  4574. } else if (!(cond instanceof AST_Node)) {
  4575. var body = [];
  4576. body.push(make_node(AST_SimpleStatement, self.condition, {
  4577. body: self.condition
  4578. }));
  4579. body.push(self.body);
  4580. if (self.alternative) {
  4581. trim_unreachable_code(compressor, self.alternative, body);
  4582. }
  4583. return make_node(AST_BlockStatement, self, { body: body }).optimize(compressor);
  4584. }
  4585. }
  4586. var negated = self.condition.negate(compressor);
  4587. var self_condition_length = self.condition.size();
  4588. var negated_length = negated.size();
  4589. var negated_is_best = negated_length < self_condition_length;
  4590. if (self.alternative && negated_is_best) {
  4591. negated_is_best = false; // because we already do the switch here.
  4592. // no need to swap values of self_condition_length and negated_length
  4593. // here because they are only used in an equality comparison later on.
  4594. self.condition = negated;
  4595. var tmp = self.body;
  4596. self.body = self.alternative || make_node(AST_EmptyStatement, self);
  4597. self.alternative = tmp;
  4598. }
  4599. if (is_empty(self.body) && is_empty(self.alternative)) {
  4600. return make_node(AST_SimpleStatement, self.condition, {
  4601. body: self.condition.clone()
  4602. }).optimize(compressor);
  4603. }
  4604. if (self.body instanceof AST_SimpleStatement
  4605. && self.alternative instanceof AST_SimpleStatement) {
  4606. return make_node(AST_SimpleStatement, self, {
  4607. body: make_node(AST_Conditional, self, {
  4608. condition : self.condition,
  4609. consequent : self.body.body,
  4610. alternative : self.alternative.body
  4611. })
  4612. }).optimize(compressor);
  4613. }
  4614. if (is_empty(self.alternative) && self.body instanceof AST_SimpleStatement) {
  4615. if (self_condition_length === negated_length && !negated_is_best
  4616. && self.condition instanceof AST_Binary && self.condition.operator == "||") {
  4617. // although the code length of self.condition and negated are the same,
  4618. // negated does not require additional surrounding parentheses.
  4619. // see https://github.com/mishoo/UglifyJS2/issues/979
  4620. negated_is_best = true;
  4621. }
  4622. if (negated_is_best) return make_node(AST_SimpleStatement, self, {
  4623. body: make_node(AST_Binary, self, {
  4624. operator : "||",
  4625. left : negated,
  4626. right : self.body.body
  4627. })
  4628. }).optimize(compressor);
  4629. return make_node(AST_SimpleStatement, self, {
  4630. body: make_node(AST_Binary, self, {
  4631. operator : "&&",
  4632. left : self.condition,
  4633. right : self.body.body
  4634. })
  4635. }).optimize(compressor);
  4636. }
  4637. if (self.body instanceof AST_EmptyStatement
  4638. && self.alternative instanceof AST_SimpleStatement) {
  4639. return make_node(AST_SimpleStatement, self, {
  4640. body: make_node(AST_Binary, self, {
  4641. operator : "||",
  4642. left : self.condition,
  4643. right : self.alternative.body
  4644. })
  4645. }).optimize(compressor);
  4646. }
  4647. if (self.body instanceof AST_Exit
  4648. && self.alternative instanceof AST_Exit
  4649. && self.body.TYPE == self.alternative.TYPE) {
  4650. return make_node(self.body.CTOR, self, {
  4651. value: make_node(AST_Conditional, self, {
  4652. condition : self.condition,
  4653. consequent : self.body.value || make_node(AST_Undefined, self.body),
  4654. alternative : self.alternative.value || make_node(AST_Undefined, self.alternative)
  4655. }).transform(compressor)
  4656. }).optimize(compressor);
  4657. }
  4658. if (self.body instanceof AST_If
  4659. && !self.body.alternative
  4660. && !self.alternative) {
  4661. self = make_node(AST_If, self, {
  4662. condition: make_node(AST_Binary, self.condition, {
  4663. operator: "&&",
  4664. left: self.condition,
  4665. right: self.body.condition
  4666. }),
  4667. body: self.body.body,
  4668. alternative: null
  4669. });
  4670. }
  4671. if (aborts(self.body)) {
  4672. if (self.alternative) {
  4673. var alt = self.alternative;
  4674. self.alternative = null;
  4675. return make_node(AST_BlockStatement, self, {
  4676. body: [ self, alt ]
  4677. }).optimize(compressor);
  4678. }
  4679. }
  4680. if (aborts(self.alternative)) {
  4681. var body = self.body;
  4682. self.body = self.alternative;
  4683. self.condition = negated_is_best ? negated : self.condition.negate(compressor);
  4684. self.alternative = null;
  4685. return make_node(AST_BlockStatement, self, {
  4686. body: [ self, body ]
  4687. }).optimize(compressor);
  4688. }
  4689. return self;
  4690. });
  4691. def_optimize(AST_Switch, function(self, compressor) {
  4692. if (!compressor.option("switches")) return self;
  4693. var branch;
  4694. var value = self.expression.evaluate(compressor);
  4695. if (!(value instanceof AST_Node)) {
  4696. var orig = self.expression;
  4697. self.expression = make_node_from_constant(value, orig);
  4698. self.expression = best_of_expression(self.expression.transform(compressor), orig);
  4699. }
  4700. if (!compressor.option("dead_code")) return self;
  4701. if (value instanceof AST_Node) {
  4702. value = self.expression.tail_node().evaluate(compressor);
  4703. }
  4704. var decl = [];
  4705. var body = [];
  4706. var default_branch;
  4707. var exact_match;
  4708. for (var i = 0, len = self.body.length; i < len && !exact_match; i++) {
  4709. branch = self.body[i];
  4710. if (branch instanceof AST_Default) {
  4711. if (!default_branch) {
  4712. default_branch = branch;
  4713. } else {
  4714. eliminate_branch(branch, body[body.length - 1]);
  4715. }
  4716. } else if (!(value instanceof AST_Node)) {
  4717. var exp = branch.expression.evaluate(compressor);
  4718. if (!(exp instanceof AST_Node) && exp !== value) {
  4719. eliminate_branch(branch, body[body.length - 1]);
  4720. continue;
  4721. }
  4722. if (exp instanceof AST_Node) exp = branch.expression.tail_node().evaluate(compressor);
  4723. if (exp === value) {
  4724. exact_match = branch;
  4725. if (default_branch) {
  4726. var default_index = body.indexOf(default_branch);
  4727. body.splice(default_index, 1);
  4728. eliminate_branch(default_branch, body[default_index - 1]);
  4729. default_branch = null;
  4730. }
  4731. }
  4732. }
  4733. if (aborts(branch)) {
  4734. var prev = body[body.length - 1];
  4735. if (aborts(prev) && prev.body.length == branch.body.length
  4736. && make_node(AST_BlockStatement, prev, prev).equivalent_to(make_node(AST_BlockStatement, branch, branch))) {
  4737. prev.body = [];
  4738. }
  4739. }
  4740. body.push(branch);
  4741. }
  4742. while (i < len) eliminate_branch(self.body[i++], body[body.length - 1]);
  4743. if (body.length > 0) {
  4744. body[0].body = decl.concat(body[0].body);
  4745. }
  4746. self.body = body;
  4747. while (branch = body[body.length - 1]) {
  4748. var stat = branch.body[branch.body.length - 1];
  4749. if (stat instanceof AST_Break && compressor.loopcontrol_target(stat) === self)
  4750. branch.body.pop();
  4751. if (branch.body.length || branch instanceof AST_Case
  4752. && (default_branch || branch.expression.has_side_effects(compressor))) break;
  4753. if (body.pop() === default_branch) default_branch = null;
  4754. }
  4755. if (body.length == 0) {
  4756. return make_node(AST_BlockStatement, self, {
  4757. body: decl.concat(make_node(AST_SimpleStatement, self.expression, {
  4758. body: self.expression
  4759. }))
  4760. }).optimize(compressor);
  4761. }
  4762. if (body.length == 1 && (body[0] === exact_match || body[0] === default_branch)) {
  4763. var has_break = false;
  4764. var tw = new TreeWalker(function(node) {
  4765. if (has_break
  4766. || node instanceof AST_Lambda
  4767. || node instanceof AST_SimpleStatement) return true;
  4768. if (node instanceof AST_Break && tw.loopcontrol_target(node) === self)
  4769. has_break = true;
  4770. });
  4771. self.walk(tw);
  4772. if (!has_break) {
  4773. var statements = body[0].body.slice();
  4774. var exp = body[0].expression;
  4775. if (exp) statements.unshift(make_node(AST_SimpleStatement, exp, {
  4776. body: exp
  4777. }));
  4778. statements.unshift(make_node(AST_SimpleStatement, self.expression, {
  4779. body:self.expression
  4780. }));
  4781. return make_node(AST_BlockStatement, self, {
  4782. body: statements
  4783. }).optimize(compressor);
  4784. }
  4785. }
  4786. return self;
  4787. function eliminate_branch(branch, prev) {
  4788. if (prev && !aborts(prev)) {
  4789. prev.body = prev.body.concat(branch.body);
  4790. } else {
  4791. trim_unreachable_code(compressor, branch, decl);
  4792. }
  4793. }
  4794. });
  4795. def_optimize(AST_Try, function(self, compressor) {
  4796. tighten_body(self.body, compressor);
  4797. if (self.bcatch && self.bfinally && self.bfinally.body.every(is_empty)) self.bfinally = null;
  4798. if (compressor.option("dead_code") && self.body.every(is_empty)) {
  4799. var body = [];
  4800. if (self.bcatch) {
  4801. trim_unreachable_code(compressor, self.bcatch, body);
  4802. }
  4803. if (self.bfinally) body.push(...self.bfinally.body);
  4804. return make_node(AST_BlockStatement, self, {
  4805. body: body
  4806. }).optimize(compressor);
  4807. }
  4808. return self;
  4809. });
  4810. AST_Definitions.DEFMETHOD("remove_initializers", function() {
  4811. var decls = [];
  4812. this.definitions.forEach(function(def) {
  4813. if (def.name instanceof AST_SymbolDeclaration) {
  4814. def.value = null;
  4815. decls.push(def);
  4816. } else {
  4817. walk(def.name, node => {
  4818. if (node instanceof AST_SymbolDeclaration) {
  4819. decls.push(make_node(AST_VarDef, def, {
  4820. name: node,
  4821. value: null
  4822. }));
  4823. }
  4824. });
  4825. }
  4826. });
  4827. this.definitions = decls;
  4828. });
  4829. AST_Definitions.DEFMETHOD("to_assignments", function(compressor) {
  4830. var reduce_vars = compressor.option("reduce_vars");
  4831. var assignments = [];
  4832. for (const def of this.definitions) {
  4833. if (def.value) {
  4834. var name = make_node(AST_SymbolRef, def.name, def.name);
  4835. assignments.push(make_node(AST_Assign, def, {
  4836. operator : "=",
  4837. logical: false,
  4838. left : name,
  4839. right : def.value
  4840. }));
  4841. if (reduce_vars) name.definition().fixed = false;
  4842. } else if (def.value) {
  4843. // Because it's a destructuring, do not turn into an assignment.
  4844. var varDef = make_node(AST_VarDef, def, {
  4845. name: def.name,
  4846. value: def.value
  4847. });
  4848. var var_ = make_node(AST_Var, def, {
  4849. definitions: [ varDef ]
  4850. });
  4851. assignments.push(var_);
  4852. }
  4853. const thedef = def.name.definition();
  4854. thedef.eliminated++;
  4855. thedef.replaced--;
  4856. }
  4857. if (assignments.length == 0) return null;
  4858. return make_sequence(this, assignments);
  4859. });
  4860. def_optimize(AST_Definitions, function(self) {
  4861. if (self.definitions.length == 0)
  4862. return make_node(AST_EmptyStatement, self);
  4863. return self;
  4864. });
  4865. def_optimize(AST_VarDef, function(self) {
  4866. if (
  4867. self.name instanceof AST_SymbolLet
  4868. && self.value != null
  4869. && is_undefined(self.value)
  4870. ) {
  4871. self.value = null;
  4872. }
  4873. return self;
  4874. });
  4875. def_optimize(AST_Import, function(self) {
  4876. return self;
  4877. });
  4878. // TODO this only works with AST_Defun, shouldn't it work for other ways of defining functions?
  4879. function retain_top_func(fn, compressor) {
  4880. return compressor.top_retain
  4881. && fn instanceof AST_Defun
  4882. && has_flag(fn, TOP)
  4883. && fn.name
  4884. && compressor.top_retain(fn.name);
  4885. }
  4886. def_optimize(AST_Call, function(self, compressor) {
  4887. var exp = self.expression;
  4888. var fn = exp;
  4889. inline_array_like_spread(self.args);
  4890. var simple_args = self.args.every((arg) =>
  4891. !(arg instanceof AST_Expansion)
  4892. );
  4893. if (compressor.option("reduce_vars")
  4894. && fn instanceof AST_SymbolRef
  4895. && !has_annotation(self, _NOINLINE)
  4896. ) {
  4897. const fixed = fn.fixed_value();
  4898. if (!retain_top_func(fixed, compressor)) {
  4899. fn = fixed;
  4900. }
  4901. }
  4902. if (self.optional && is_nullish(fn)) {
  4903. return make_node(AST_Undefined, self);
  4904. }
  4905. var is_func = fn instanceof AST_Lambda;
  4906. if (is_func && fn.pinned()) return self;
  4907. if (compressor.option("unused")
  4908. && simple_args
  4909. && is_func
  4910. && !fn.uses_arguments) {
  4911. var pos = 0, last = 0;
  4912. for (var i = 0, len = self.args.length; i < len; i++) {
  4913. if (fn.argnames[i] instanceof AST_Expansion) {
  4914. if (has_flag(fn.argnames[i].expression, UNUSED)) while (i < len) {
  4915. var node = self.args[i++].drop_side_effect_free(compressor);
  4916. if (node) {
  4917. self.args[pos++] = node;
  4918. }
  4919. } else while (i < len) {
  4920. self.args[pos++] = self.args[i++];
  4921. }
  4922. last = pos;
  4923. break;
  4924. }
  4925. var trim = i >= fn.argnames.length;
  4926. if (trim || has_flag(fn.argnames[i], UNUSED)) {
  4927. var node = self.args[i].drop_side_effect_free(compressor);
  4928. if (node) {
  4929. self.args[pos++] = node;
  4930. } else if (!trim) {
  4931. self.args[pos++] = make_node(AST_Number, self.args[i], {
  4932. value: 0
  4933. });
  4934. continue;
  4935. }
  4936. } else {
  4937. self.args[pos++] = self.args[i];
  4938. }
  4939. last = pos;
  4940. }
  4941. self.args.length = last;
  4942. }
  4943. if (compressor.option("unsafe")) {
  4944. if (is_undeclared_ref(exp)) switch (exp.name) {
  4945. case "Array":
  4946. if (self.args.length != 1) {
  4947. return make_node(AST_Array, self, {
  4948. elements: self.args
  4949. }).optimize(compressor);
  4950. } else if (self.args[0] instanceof AST_Number && self.args[0].value <= 11) {
  4951. const elements = [];
  4952. for (let i = 0; i < self.args[0].value; i++) elements.push(new AST_Hole);
  4953. return new AST_Array({ elements });
  4954. }
  4955. break;
  4956. case "Object":
  4957. if (self.args.length == 0) {
  4958. return make_node(AST_Object, self, {
  4959. properties: []
  4960. });
  4961. }
  4962. break;
  4963. case "String":
  4964. if (self.args.length == 0) return make_node(AST_String, self, {
  4965. value: ""
  4966. });
  4967. if (self.args.length <= 1) return make_node(AST_Binary, self, {
  4968. left: self.args[0],
  4969. operator: "+",
  4970. right: make_node(AST_String, self, { value: "" })
  4971. }).optimize(compressor);
  4972. break;
  4973. case "Number":
  4974. if (self.args.length == 0) return make_node(AST_Number, self, {
  4975. value: 0
  4976. });
  4977. if (self.args.length == 1 && compressor.option("unsafe_math")) {
  4978. return make_node(AST_UnaryPrefix, self, {
  4979. expression: self.args[0],
  4980. operator: "+"
  4981. }).optimize(compressor);
  4982. }
  4983. break;
  4984. case "Symbol":
  4985. if (self.args.length == 1 && self.args[0] instanceof AST_String && compressor.option("unsafe_symbols"))
  4986. self.args.length = 0;
  4987. break;
  4988. case "Boolean":
  4989. if (self.args.length == 0) return make_node(AST_False, self);
  4990. if (self.args.length == 1) return make_node(AST_UnaryPrefix, self, {
  4991. expression: make_node(AST_UnaryPrefix, self, {
  4992. expression: self.args[0],
  4993. operator: "!"
  4994. }),
  4995. operator: "!"
  4996. }).optimize(compressor);
  4997. break;
  4998. case "RegExp":
  4999. var params = [];
  5000. if (self.args.length >= 1
  5001. && self.args.length <= 2
  5002. && self.args.every((arg) => {
  5003. var value = arg.evaluate(compressor);
  5004. params.push(value);
  5005. return arg !== value;
  5006. })
  5007. ) {
  5008. let [ source, flags ] = params;
  5009. source = regexp_source_fix(new RegExp(source).source);
  5010. const rx = make_node(AST_RegExp, self, {
  5011. value: { source, flags }
  5012. });
  5013. if (rx._eval(compressor) !== rx) {
  5014. return rx;
  5015. }
  5016. }
  5017. break;
  5018. } else if (exp instanceof AST_Dot) switch(exp.property) {
  5019. case "toString":
  5020. if (self.args.length == 0 && !exp.expression.may_throw_on_access(compressor)) {
  5021. return make_node(AST_Binary, self, {
  5022. left: make_node(AST_String, self, { value: "" }),
  5023. operator: "+",
  5024. right: exp.expression
  5025. }).optimize(compressor);
  5026. }
  5027. break;
  5028. case "join":
  5029. if (exp.expression instanceof AST_Array) EXIT: {
  5030. var separator;
  5031. if (self.args.length > 0) {
  5032. separator = self.args[0].evaluate(compressor);
  5033. if (separator === self.args[0]) break EXIT; // not a constant
  5034. }
  5035. var elements = [];
  5036. var consts = [];
  5037. for (var i = 0, len = exp.expression.elements.length; i < len; i++) {
  5038. var el = exp.expression.elements[i];
  5039. if (el instanceof AST_Expansion) break EXIT;
  5040. var value = el.evaluate(compressor);
  5041. if (value !== el) {
  5042. consts.push(value);
  5043. } else {
  5044. if (consts.length > 0) {
  5045. elements.push(make_node(AST_String, self, {
  5046. value: consts.join(separator)
  5047. }));
  5048. consts.length = 0;
  5049. }
  5050. elements.push(el);
  5051. }
  5052. }
  5053. if (consts.length > 0) {
  5054. elements.push(make_node(AST_String, self, {
  5055. value: consts.join(separator)
  5056. }));
  5057. }
  5058. if (elements.length == 0) return make_node(AST_String, self, { value: "" });
  5059. if (elements.length == 1) {
  5060. if (elements[0].is_string(compressor)) {
  5061. return elements[0];
  5062. }
  5063. return make_node(AST_Binary, elements[0], {
  5064. operator : "+",
  5065. left : make_node(AST_String, self, { value: "" }),
  5066. right : elements[0]
  5067. });
  5068. }
  5069. if (separator == "") {
  5070. var first;
  5071. if (elements[0].is_string(compressor)
  5072. || elements[1].is_string(compressor)) {
  5073. first = elements.shift();
  5074. } else {
  5075. first = make_node(AST_String, self, { value: "" });
  5076. }
  5077. return elements.reduce(function(prev, el) {
  5078. return make_node(AST_Binary, el, {
  5079. operator : "+",
  5080. left : prev,
  5081. right : el
  5082. });
  5083. }, first).optimize(compressor);
  5084. }
  5085. // need this awkward cloning to not affect original element
  5086. // best_of will decide which one to get through.
  5087. var node = self.clone();
  5088. node.expression = node.expression.clone();
  5089. node.expression.expression = node.expression.expression.clone();
  5090. node.expression.expression.elements = elements;
  5091. return best_of(compressor, self, node);
  5092. }
  5093. break;
  5094. case "charAt":
  5095. if (exp.expression.is_string(compressor)) {
  5096. var arg = self.args[0];
  5097. var index = arg ? arg.evaluate(compressor) : 0;
  5098. if (index !== arg) {
  5099. return make_node(AST_Sub, exp, {
  5100. expression: exp.expression,
  5101. property: make_node_from_constant(index | 0, arg || exp)
  5102. }).optimize(compressor);
  5103. }
  5104. }
  5105. break;
  5106. case "apply":
  5107. if (self.args.length == 2 && self.args[1] instanceof AST_Array) {
  5108. var args = self.args[1].elements.slice();
  5109. args.unshift(self.args[0]);
  5110. return make_node(AST_Call, self, {
  5111. expression: make_node(AST_Dot, exp, {
  5112. expression: exp.expression,
  5113. optional: false,
  5114. property: "call"
  5115. }),
  5116. args: args
  5117. }).optimize(compressor);
  5118. }
  5119. break;
  5120. case "call":
  5121. var func = exp.expression;
  5122. if (func instanceof AST_SymbolRef) {
  5123. func = func.fixed_value();
  5124. }
  5125. if (func instanceof AST_Lambda && !func.contains_this()) {
  5126. return (self.args.length ? make_sequence(this, [
  5127. self.args[0],
  5128. make_node(AST_Call, self, {
  5129. expression: exp.expression,
  5130. args: self.args.slice(1)
  5131. })
  5132. ]) : make_node(AST_Call, self, {
  5133. expression: exp.expression,
  5134. args: []
  5135. })).optimize(compressor);
  5136. }
  5137. break;
  5138. }
  5139. }
  5140. if (compressor.option("unsafe_Function")
  5141. && is_undeclared_ref(exp)
  5142. && exp.name == "Function") {
  5143. // new Function() => function(){}
  5144. if (self.args.length == 0) return make_node(AST_Function, self, {
  5145. argnames: [],
  5146. body: []
  5147. }).optimize(compressor);
  5148. if (self.args.every((x) => x instanceof AST_String)) {
  5149. // quite a corner-case, but we can handle it:
  5150. // https://github.com/mishoo/UglifyJS2/issues/203
  5151. // if the code argument is a constant, then we can minify it.
  5152. try {
  5153. var code = "n(function(" + self.args.slice(0, -1).map(function(arg) {
  5154. return arg.value;
  5155. }).join(",") + "){" + self.args[self.args.length - 1].value + "})";
  5156. var ast = parse(code);
  5157. var mangle = { ie8: compressor.option("ie8") };
  5158. ast.figure_out_scope(mangle);
  5159. var comp = new Compressor(compressor.options, {
  5160. mangle_options: compressor.mangle_options
  5161. });
  5162. ast = ast.transform(comp);
  5163. ast.figure_out_scope(mangle);
  5164. base54.reset();
  5165. ast.compute_char_frequency(mangle);
  5166. ast.mangle_names(mangle);
  5167. var fun;
  5168. walk(ast, node => {
  5169. if (is_func_expr(node)) {
  5170. fun = node;
  5171. return walk_abort;
  5172. }
  5173. });
  5174. var code = OutputStream();
  5175. AST_BlockStatement.prototype._codegen.call(fun, fun, code);
  5176. self.args = [
  5177. make_node(AST_String, self, {
  5178. value: fun.argnames.map(function(arg) {
  5179. return arg.print_to_string();
  5180. }).join(",")
  5181. }),
  5182. make_node(AST_String, self.args[self.args.length - 1], {
  5183. value: code.get().replace(/^{|}$/g, "")
  5184. })
  5185. ];
  5186. return self;
  5187. } catch (ex) {
  5188. if (!(ex instanceof JS_Parse_Error)) {
  5189. throw ex;
  5190. }
  5191. // Otherwise, it crashes at runtime. Or maybe it's nonstandard syntax.
  5192. }
  5193. }
  5194. }
  5195. var stat = is_func && fn.body[0];
  5196. var is_regular_func = is_func && !fn.is_generator && !fn.async;
  5197. var can_inline = is_regular_func && compressor.option("inline") && !self.is_callee_pure(compressor);
  5198. if (can_inline && stat instanceof AST_Return) {
  5199. let returned = stat.value;
  5200. if (!returned || returned.is_constant_expression()) {
  5201. if (returned) {
  5202. returned = returned.clone(true);
  5203. } else {
  5204. returned = make_node(AST_Undefined, self);
  5205. }
  5206. const args = self.args.concat(returned);
  5207. return make_sequence(self, args).optimize(compressor);
  5208. }
  5209. // optimize identity function
  5210. if (
  5211. fn.argnames.length === 1
  5212. && (fn.argnames[0] instanceof AST_SymbolFunarg)
  5213. && self.args.length < 2
  5214. && returned instanceof AST_SymbolRef
  5215. && returned.name === fn.argnames[0].name
  5216. ) {
  5217. const replacement =
  5218. (self.args[0] || make_node(AST_Undefined)).optimize(compressor);
  5219. let parent;
  5220. if (
  5221. replacement instanceof AST_PropAccess
  5222. && (parent = compressor.parent()) instanceof AST_Call
  5223. && parent.expression === self
  5224. ) {
  5225. // identity function was being used to remove `this`, like in
  5226. //
  5227. // id(bag.no_this)(...)
  5228. //
  5229. // Replace with a larger but more effish (0, bag.no_this) wrapper.
  5230. return make_sequence(self, [
  5231. make_node(AST_Number, self, { value: 0 }),
  5232. replacement
  5233. ]);
  5234. }
  5235. // replace call with first argument or undefined if none passed
  5236. return replacement;
  5237. }
  5238. }
  5239. if (can_inline) {
  5240. var scope, in_loop, level = -1;
  5241. let def;
  5242. let returned_value;
  5243. let nearest_scope;
  5244. if (simple_args
  5245. && !fn.uses_arguments
  5246. && !(compressor.parent() instanceof AST_Class)
  5247. && !(fn.name && fn instanceof AST_Function)
  5248. && (returned_value = can_flatten_body(stat))
  5249. && (exp === fn
  5250. || has_annotation(self, _INLINE)
  5251. || compressor.option("unused")
  5252. && (def = exp.definition()).references.length == 1
  5253. && !recursive_ref(compressor, def)
  5254. && fn.is_constant_expression(exp.scope))
  5255. && !has_annotation(self, _PURE | _NOINLINE)
  5256. && !fn.contains_this()
  5257. && can_inject_symbols()
  5258. && (nearest_scope = find_scope(compressor))
  5259. && !scope_encloses_variables_in_this_scope(nearest_scope, fn)
  5260. && !(function in_default_assign() {
  5261. // Due to the fact function parameters have their own scope
  5262. // which can't use `var something` in the function body within,
  5263. // we simply don't inline into DefaultAssign.
  5264. let i = 0;
  5265. let p;
  5266. while ((p = compressor.parent(i++))) {
  5267. if (p instanceof AST_DefaultAssign) return true;
  5268. if (p instanceof AST_Block) break;
  5269. }
  5270. return false;
  5271. })()
  5272. && !(scope instanceof AST_Class)
  5273. ) {
  5274. set_flag(fn, SQUEEZED);
  5275. nearest_scope.add_child_scope(fn);
  5276. return make_sequence(self, flatten_fn(returned_value)).optimize(compressor);
  5277. }
  5278. }
  5279. if (can_inline && has_annotation(self, _INLINE)) {
  5280. set_flag(fn, SQUEEZED);
  5281. fn = make_node(fn.CTOR === AST_Defun ? AST_Function : fn.CTOR, fn, fn);
  5282. fn.figure_out_scope({}, {
  5283. parent_scope: find_scope(compressor),
  5284. toplevel: compressor.get_toplevel()
  5285. });
  5286. return make_node(AST_Call, self, {
  5287. expression: fn,
  5288. args: self.args,
  5289. }).optimize(compressor);
  5290. }
  5291. const can_drop_this_call = is_regular_func && compressor.option("side_effects") && fn.body.every(is_empty);
  5292. if (can_drop_this_call) {
  5293. var args = self.args.concat(make_node(AST_Undefined, self));
  5294. return make_sequence(self, args).optimize(compressor);
  5295. }
  5296. if (compressor.option("negate_iife")
  5297. && compressor.parent() instanceof AST_SimpleStatement
  5298. && is_iife_call(self)) {
  5299. return self.negate(compressor, true);
  5300. }
  5301. var ev = self.evaluate(compressor);
  5302. if (ev !== self) {
  5303. ev = make_node_from_constant(ev, self).optimize(compressor);
  5304. return best_of(compressor, ev, self);
  5305. }
  5306. return self;
  5307. function return_value(stat) {
  5308. if (!stat) return make_node(AST_Undefined, self);
  5309. if (stat instanceof AST_Return) {
  5310. if (!stat.value) return make_node(AST_Undefined, self);
  5311. return stat.value.clone(true);
  5312. }
  5313. if (stat instanceof AST_SimpleStatement) {
  5314. return make_node(AST_UnaryPrefix, stat, {
  5315. operator: "void",
  5316. expression: stat.body.clone(true)
  5317. });
  5318. }
  5319. }
  5320. function can_flatten_body(stat) {
  5321. var body = fn.body;
  5322. var len = body.length;
  5323. if (compressor.option("inline") < 3) {
  5324. return len == 1 && return_value(stat);
  5325. }
  5326. stat = null;
  5327. for (var i = 0; i < len; i++) {
  5328. var line = body[i];
  5329. if (line instanceof AST_Var) {
  5330. if (stat && !line.definitions.every((var_def) =>
  5331. !var_def.value
  5332. )) {
  5333. return false;
  5334. }
  5335. } else if (stat) {
  5336. return false;
  5337. } else if (!(line instanceof AST_EmptyStatement)) {
  5338. stat = line;
  5339. }
  5340. }
  5341. return return_value(stat);
  5342. }
  5343. function can_inject_args(block_scoped, safe_to_inject) {
  5344. for (var i = 0, len = fn.argnames.length; i < len; i++) {
  5345. var arg = fn.argnames[i];
  5346. if (arg instanceof AST_DefaultAssign) {
  5347. if (has_flag(arg.left, UNUSED)) continue;
  5348. return false;
  5349. }
  5350. if (arg instanceof AST_Destructuring) return false;
  5351. if (arg instanceof AST_Expansion) {
  5352. if (has_flag(arg.expression, UNUSED)) continue;
  5353. return false;
  5354. }
  5355. if (has_flag(arg, UNUSED)) continue;
  5356. if (!safe_to_inject
  5357. || block_scoped.has(arg.name)
  5358. || identifier_atom.has(arg.name)
  5359. || scope.conflicting_def(arg.name)) {
  5360. return false;
  5361. }
  5362. if (in_loop) in_loop.push(arg.definition());
  5363. }
  5364. return true;
  5365. }
  5366. function can_inject_vars(block_scoped, safe_to_inject) {
  5367. var len = fn.body.length;
  5368. for (var i = 0; i < len; i++) {
  5369. var stat = fn.body[i];
  5370. if (!(stat instanceof AST_Var)) continue;
  5371. if (!safe_to_inject) return false;
  5372. for (var j = stat.definitions.length; --j >= 0;) {
  5373. var name = stat.definitions[j].name;
  5374. if (name instanceof AST_Destructuring
  5375. || block_scoped.has(name.name)
  5376. || identifier_atom.has(name.name)
  5377. || scope.conflicting_def(name.name)) {
  5378. return false;
  5379. }
  5380. if (in_loop) in_loop.push(name.definition());
  5381. }
  5382. }
  5383. return true;
  5384. }
  5385. function can_inject_symbols() {
  5386. var block_scoped = new Set();
  5387. do {
  5388. scope = compressor.parent(++level);
  5389. if (scope.is_block_scope() && scope.block_scope) {
  5390. // TODO this is sometimes undefined during compression.
  5391. // But it should always have a value!
  5392. scope.block_scope.variables.forEach(function (variable) {
  5393. block_scoped.add(variable.name);
  5394. });
  5395. }
  5396. if (scope instanceof AST_Catch) {
  5397. // TODO can we delete? AST_Catch is a block scope.
  5398. if (scope.argname) {
  5399. block_scoped.add(scope.argname.name);
  5400. }
  5401. } else if (scope instanceof AST_IterationStatement) {
  5402. in_loop = [];
  5403. } else if (scope instanceof AST_SymbolRef) {
  5404. if (scope.fixed_value() instanceof AST_Scope) return false;
  5405. }
  5406. } while (!(scope instanceof AST_Scope));
  5407. var safe_to_inject = !(scope instanceof AST_Toplevel) || compressor.toplevel.vars;
  5408. var inline = compressor.option("inline");
  5409. if (!can_inject_vars(block_scoped, inline >= 3 && safe_to_inject)) return false;
  5410. if (!can_inject_args(block_scoped, inline >= 2 && safe_to_inject)) return false;
  5411. return !in_loop || in_loop.length == 0 || !is_reachable(fn, in_loop);
  5412. }
  5413. function append_var(decls, expressions, name, value) {
  5414. var def = name.definition();
  5415. // Name already exists, only when a function argument had the same name
  5416. const already_appended = scope.variables.has(name.name);
  5417. if (!already_appended) {
  5418. scope.variables.set(name.name, def);
  5419. scope.enclosed.push(def);
  5420. decls.push(make_node(AST_VarDef, name, {
  5421. name: name,
  5422. value: null
  5423. }));
  5424. }
  5425. var sym = make_node(AST_SymbolRef, name, name);
  5426. def.references.push(sym);
  5427. if (value) expressions.push(make_node(AST_Assign, self, {
  5428. operator: "=",
  5429. logical: false,
  5430. left: sym,
  5431. right: value.clone()
  5432. }));
  5433. }
  5434. function flatten_args(decls, expressions) {
  5435. var len = fn.argnames.length;
  5436. for (var i = self.args.length; --i >= len;) {
  5437. expressions.push(self.args[i]);
  5438. }
  5439. for (i = len; --i >= 0;) {
  5440. var name = fn.argnames[i];
  5441. var value = self.args[i];
  5442. if (has_flag(name, UNUSED) || !name.name || scope.conflicting_def(name.name)) {
  5443. if (value) expressions.push(value);
  5444. } else {
  5445. var symbol = make_node(AST_SymbolVar, name, name);
  5446. name.definition().orig.push(symbol);
  5447. if (!value && in_loop) value = make_node(AST_Undefined, self);
  5448. append_var(decls, expressions, symbol, value);
  5449. }
  5450. }
  5451. decls.reverse();
  5452. expressions.reverse();
  5453. }
  5454. function flatten_vars(decls, expressions) {
  5455. var pos = expressions.length;
  5456. for (var i = 0, lines = fn.body.length; i < lines; i++) {
  5457. var stat = fn.body[i];
  5458. if (!(stat instanceof AST_Var)) continue;
  5459. for (var j = 0, defs = stat.definitions.length; j < defs; j++) {
  5460. var var_def = stat.definitions[j];
  5461. var name = var_def.name;
  5462. append_var(decls, expressions, name, var_def.value);
  5463. if (in_loop && fn.argnames.every((argname) =>
  5464. argname.name != name.name
  5465. )) {
  5466. var def = fn.variables.get(name.name);
  5467. var sym = make_node(AST_SymbolRef, name, name);
  5468. def.references.push(sym);
  5469. expressions.splice(pos++, 0, make_node(AST_Assign, var_def, {
  5470. operator: "=",
  5471. logical: false,
  5472. left: sym,
  5473. right: make_node(AST_Undefined, name)
  5474. }));
  5475. }
  5476. }
  5477. }
  5478. }
  5479. function flatten_fn(returned_value) {
  5480. var decls = [];
  5481. var expressions = [];
  5482. flatten_args(decls, expressions);
  5483. flatten_vars(decls, expressions);
  5484. expressions.push(returned_value);
  5485. if (decls.length) {
  5486. const i = scope.body.indexOf(compressor.parent(level - 1)) + 1;
  5487. scope.body.splice(i, 0, make_node(AST_Var, fn, {
  5488. definitions: decls
  5489. }));
  5490. }
  5491. return expressions.map(exp => exp.clone(true));
  5492. }
  5493. });
  5494. def_optimize(AST_New, function(self, compressor) {
  5495. if (
  5496. compressor.option("unsafe") &&
  5497. is_undeclared_ref(self.expression) &&
  5498. ["Object", "RegExp", "Function", "Error", "Array"].includes(self.expression.name)
  5499. ) return make_node(AST_Call, self, self).transform(compressor);
  5500. return self;
  5501. });
  5502. def_optimize(AST_Sequence, function(self, compressor) {
  5503. if (!compressor.option("side_effects")) return self;
  5504. var expressions = [];
  5505. filter_for_side_effects();
  5506. var end = expressions.length - 1;
  5507. trim_right_for_undefined();
  5508. if (end == 0) {
  5509. self = maintain_this_binding(compressor.parent(), compressor.self(), expressions[0]);
  5510. if (!(self instanceof AST_Sequence)) self = self.optimize(compressor);
  5511. return self;
  5512. }
  5513. self.expressions = expressions;
  5514. return self;
  5515. function filter_for_side_effects() {
  5516. var first = first_in_statement(compressor);
  5517. var last = self.expressions.length - 1;
  5518. self.expressions.forEach(function(expr, index) {
  5519. if (index < last) expr = expr.drop_side_effect_free(compressor, first);
  5520. if (expr) {
  5521. merge_sequence(expressions, expr);
  5522. first = false;
  5523. }
  5524. });
  5525. }
  5526. function trim_right_for_undefined() {
  5527. while (end > 0 && is_undefined(expressions[end], compressor)) end--;
  5528. if (end < expressions.length - 1) {
  5529. expressions[end] = make_node(AST_UnaryPrefix, self, {
  5530. operator : "void",
  5531. expression : expressions[end]
  5532. });
  5533. expressions.length = end + 1;
  5534. }
  5535. }
  5536. });
  5537. AST_Unary.DEFMETHOD("lift_sequences", function(compressor) {
  5538. if (compressor.option("sequences")) {
  5539. if (this.expression instanceof AST_Sequence) {
  5540. var x = this.expression.expressions.slice();
  5541. var e = this.clone();
  5542. e.expression = x.pop();
  5543. x.push(e);
  5544. return make_sequence(this, x).optimize(compressor);
  5545. }
  5546. }
  5547. return this;
  5548. });
  5549. def_optimize(AST_UnaryPostfix, function(self, compressor) {
  5550. return self.lift_sequences(compressor);
  5551. });
  5552. def_optimize(AST_UnaryPrefix, function(self, compressor) {
  5553. var e = self.expression;
  5554. if (self.operator == "delete"
  5555. && !(e instanceof AST_SymbolRef
  5556. || e instanceof AST_PropAccess
  5557. || is_identifier_atom(e))) {
  5558. if (e instanceof AST_Sequence) {
  5559. const exprs = e.expressions.slice();
  5560. exprs.push(make_node(AST_True, self));
  5561. return make_sequence(self, exprs).optimize(compressor);
  5562. }
  5563. return make_sequence(self, [ e, make_node(AST_True, self) ]).optimize(compressor);
  5564. }
  5565. var seq = self.lift_sequences(compressor);
  5566. if (seq !== self) {
  5567. return seq;
  5568. }
  5569. if (compressor.option("side_effects") && self.operator == "void") {
  5570. e = e.drop_side_effect_free(compressor);
  5571. if (e) {
  5572. self.expression = e;
  5573. return self;
  5574. } else {
  5575. return make_node(AST_Undefined, self).optimize(compressor);
  5576. }
  5577. }
  5578. if (compressor.in_boolean_context()) {
  5579. switch (self.operator) {
  5580. case "!":
  5581. if (e instanceof AST_UnaryPrefix && e.operator == "!") {
  5582. // !!foo ==> foo, if we're in boolean context
  5583. return e.expression;
  5584. }
  5585. if (e instanceof AST_Binary) {
  5586. self = best_of(compressor, self, e.negate(compressor, first_in_statement(compressor)));
  5587. }
  5588. break;
  5589. case "typeof":
  5590. // typeof always returns a non-empty string, thus it's
  5591. // always true in booleans
  5592. // And we don't need to check if it's undeclared, because in typeof, that's OK
  5593. return (e instanceof AST_SymbolRef ? make_node(AST_True, self) : make_sequence(self, [
  5594. e,
  5595. make_node(AST_True, self)
  5596. ])).optimize(compressor);
  5597. }
  5598. }
  5599. if (self.operator == "-" && e instanceof AST_Infinity) {
  5600. e = e.transform(compressor);
  5601. }
  5602. if (e instanceof AST_Binary
  5603. && (self.operator == "+" || self.operator == "-")
  5604. && (e.operator == "*" || e.operator == "/" || e.operator == "%")) {
  5605. return make_node(AST_Binary, self, {
  5606. operator: e.operator,
  5607. left: make_node(AST_UnaryPrefix, e.left, {
  5608. operator: self.operator,
  5609. expression: e.left
  5610. }),
  5611. right: e.right
  5612. });
  5613. }
  5614. // avoids infinite recursion of numerals
  5615. if (self.operator != "-"
  5616. || !(e instanceof AST_Number || e instanceof AST_Infinity || e instanceof AST_BigInt)) {
  5617. var ev = self.evaluate(compressor);
  5618. if (ev !== self) {
  5619. ev = make_node_from_constant(ev, self).optimize(compressor);
  5620. return best_of(compressor, ev, self);
  5621. }
  5622. }
  5623. return self;
  5624. });
  5625. AST_Binary.DEFMETHOD("lift_sequences", function(compressor) {
  5626. if (compressor.option("sequences")) {
  5627. if (this.left instanceof AST_Sequence) {
  5628. var x = this.left.expressions.slice();
  5629. var e = this.clone();
  5630. e.left = x.pop();
  5631. x.push(e);
  5632. return make_sequence(this, x).optimize(compressor);
  5633. }
  5634. if (this.right instanceof AST_Sequence && !this.left.has_side_effects(compressor)) {
  5635. var assign = this.operator == "=" && this.left instanceof AST_SymbolRef;
  5636. var x = this.right.expressions;
  5637. var last = x.length - 1;
  5638. for (var i = 0; i < last; i++) {
  5639. if (!assign && x[i].has_side_effects(compressor)) break;
  5640. }
  5641. if (i == last) {
  5642. x = x.slice();
  5643. var e = this.clone();
  5644. e.right = x.pop();
  5645. x.push(e);
  5646. return make_sequence(this, x).optimize(compressor);
  5647. } else if (i > 0) {
  5648. var e = this.clone();
  5649. e.right = make_sequence(this.right, x.slice(i));
  5650. x = x.slice(0, i);
  5651. x.push(e);
  5652. return make_sequence(this, x).optimize(compressor);
  5653. }
  5654. }
  5655. }
  5656. return this;
  5657. });
  5658. var commutativeOperators = makePredicate("== === != !== * & | ^");
  5659. function is_object(node) {
  5660. return node instanceof AST_Array
  5661. || node instanceof AST_Lambda
  5662. || node instanceof AST_Object
  5663. || node instanceof AST_Class;
  5664. }
  5665. def_optimize(AST_Binary, function(self, compressor) {
  5666. function reversible() {
  5667. return self.left.is_constant()
  5668. || self.right.is_constant()
  5669. || !self.left.has_side_effects(compressor)
  5670. && !self.right.has_side_effects(compressor);
  5671. }
  5672. function reverse(op) {
  5673. if (reversible()) {
  5674. if (op) self.operator = op;
  5675. var tmp = self.left;
  5676. self.left = self.right;
  5677. self.right = tmp;
  5678. }
  5679. }
  5680. if (commutativeOperators.has(self.operator)) {
  5681. if (self.right.is_constant()
  5682. && !self.left.is_constant()) {
  5683. // if right is a constant, whatever side effects the
  5684. // left side might have could not influence the
  5685. // result. hence, force switch.
  5686. if (!(self.left instanceof AST_Binary
  5687. && PRECEDENCE[self.left.operator] >= PRECEDENCE[self.operator])) {
  5688. reverse();
  5689. }
  5690. }
  5691. }
  5692. self = self.lift_sequences(compressor);
  5693. if (compressor.option("comparisons")) switch (self.operator) {
  5694. case "===":
  5695. case "!==":
  5696. var is_strict_comparison = true;
  5697. if ((self.left.is_string(compressor) && self.right.is_string(compressor)) ||
  5698. (self.left.is_number(compressor) && self.right.is_number(compressor)) ||
  5699. (self.left.is_boolean() && self.right.is_boolean()) ||
  5700. self.left.equivalent_to(self.right)) {
  5701. self.operator = self.operator.substr(0, 2);
  5702. }
  5703. // XXX: intentionally falling down to the next case
  5704. case "==":
  5705. case "!=":
  5706. // void 0 == x => null == x
  5707. if (!is_strict_comparison && is_undefined(self.left, compressor)) {
  5708. self.left = make_node(AST_Null, self.left);
  5709. } else if (compressor.option("typeofs")
  5710. // "undefined" == typeof x => undefined === x
  5711. && self.left instanceof AST_String
  5712. && self.left.value == "undefined"
  5713. && self.right instanceof AST_UnaryPrefix
  5714. && self.right.operator == "typeof") {
  5715. var expr = self.right.expression;
  5716. if (expr instanceof AST_SymbolRef ? expr.is_declared(compressor)
  5717. : !(expr instanceof AST_PropAccess && compressor.option("ie8"))) {
  5718. self.right = expr;
  5719. self.left = make_node(AST_Undefined, self.left).optimize(compressor);
  5720. if (self.operator.length == 2) self.operator += "=";
  5721. }
  5722. } else if (self.left instanceof AST_SymbolRef
  5723. // obj !== obj => false
  5724. && self.right instanceof AST_SymbolRef
  5725. && self.left.definition() === self.right.definition()
  5726. && is_object(self.left.fixed_value())) {
  5727. return make_node(self.operator[0] == "=" ? AST_True : AST_False, self);
  5728. }
  5729. break;
  5730. case "&&":
  5731. case "||":
  5732. var lhs = self.left;
  5733. if (lhs.operator == self.operator) {
  5734. lhs = lhs.right;
  5735. }
  5736. if (lhs instanceof AST_Binary
  5737. && lhs.operator == (self.operator == "&&" ? "!==" : "===")
  5738. && self.right instanceof AST_Binary
  5739. && lhs.operator == self.right.operator
  5740. && (is_undefined(lhs.left, compressor) && self.right.left instanceof AST_Null
  5741. || lhs.left instanceof AST_Null && is_undefined(self.right.left, compressor))
  5742. && !lhs.right.has_side_effects(compressor)
  5743. && lhs.right.equivalent_to(self.right.right)) {
  5744. var combined = make_node(AST_Binary, self, {
  5745. operator: lhs.operator.slice(0, -1),
  5746. left: make_node(AST_Null, self),
  5747. right: lhs.right
  5748. });
  5749. if (lhs !== self.left) {
  5750. combined = make_node(AST_Binary, self, {
  5751. operator: self.operator,
  5752. left: self.left.left,
  5753. right: combined
  5754. });
  5755. }
  5756. return combined;
  5757. }
  5758. break;
  5759. }
  5760. if (self.operator == "+" && compressor.in_boolean_context()) {
  5761. var ll = self.left.evaluate(compressor);
  5762. var rr = self.right.evaluate(compressor);
  5763. if (ll && typeof ll == "string") {
  5764. return make_sequence(self, [
  5765. self.right,
  5766. make_node(AST_True, self)
  5767. ]).optimize(compressor);
  5768. }
  5769. if (rr && typeof rr == "string") {
  5770. return make_sequence(self, [
  5771. self.left,
  5772. make_node(AST_True, self)
  5773. ]).optimize(compressor);
  5774. }
  5775. }
  5776. if (compressor.option("comparisons") && self.is_boolean()) {
  5777. if (!(compressor.parent() instanceof AST_Binary)
  5778. || compressor.parent() instanceof AST_Assign) {
  5779. var negated = make_node(AST_UnaryPrefix, self, {
  5780. operator: "!",
  5781. expression: self.negate(compressor, first_in_statement(compressor))
  5782. });
  5783. self = best_of(compressor, self, negated);
  5784. }
  5785. if (compressor.option("unsafe_comps")) {
  5786. switch (self.operator) {
  5787. case "<": reverse(">"); break;
  5788. case "<=": reverse(">="); break;
  5789. }
  5790. }
  5791. }
  5792. if (self.operator == "+") {
  5793. if (self.right instanceof AST_String
  5794. && self.right.getValue() == ""
  5795. && self.left.is_string(compressor)) {
  5796. return self.left;
  5797. }
  5798. if (self.left instanceof AST_String
  5799. && self.left.getValue() == ""
  5800. && self.right.is_string(compressor)) {
  5801. return self.right;
  5802. }
  5803. if (self.left instanceof AST_Binary
  5804. && self.left.operator == "+"
  5805. && self.left.left instanceof AST_String
  5806. && self.left.left.getValue() == ""
  5807. && self.right.is_string(compressor)) {
  5808. self.left = self.left.right;
  5809. return self;
  5810. }
  5811. }
  5812. if (compressor.option("evaluate")) {
  5813. switch (self.operator) {
  5814. case "&&":
  5815. var ll = has_flag(self.left, TRUTHY)
  5816. ? true
  5817. : has_flag(self.left, FALSY)
  5818. ? false
  5819. : self.left.evaluate(compressor);
  5820. if (!ll) {
  5821. return maintain_this_binding(compressor.parent(), compressor.self(), self.left).optimize(compressor);
  5822. } else if (!(ll instanceof AST_Node)) {
  5823. return make_sequence(self, [ self.left, self.right ]).optimize(compressor);
  5824. }
  5825. var rr = self.right.evaluate(compressor);
  5826. if (!rr) {
  5827. if (compressor.in_boolean_context()) {
  5828. return make_sequence(self, [
  5829. self.left,
  5830. make_node(AST_False, self)
  5831. ]).optimize(compressor);
  5832. } else {
  5833. set_flag(self, FALSY);
  5834. }
  5835. } else if (!(rr instanceof AST_Node)) {
  5836. var parent = compressor.parent();
  5837. if (parent.operator == "&&" && parent.left === compressor.self() || compressor.in_boolean_context()) {
  5838. return self.left.optimize(compressor);
  5839. }
  5840. }
  5841. // x || false && y ---> x ? y : false
  5842. if (self.left.operator == "||") {
  5843. var lr = self.left.right.evaluate(compressor);
  5844. if (!lr) return make_node(AST_Conditional, self, {
  5845. condition: self.left.left,
  5846. consequent: self.right,
  5847. alternative: self.left.right
  5848. }).optimize(compressor);
  5849. }
  5850. break;
  5851. case "||":
  5852. var ll = has_flag(self.left, TRUTHY)
  5853. ? true
  5854. : has_flag(self.left, FALSY)
  5855. ? false
  5856. : self.left.evaluate(compressor);
  5857. if (!ll) {
  5858. return make_sequence(self, [ self.left, self.right ]).optimize(compressor);
  5859. } else if (!(ll instanceof AST_Node)) {
  5860. return maintain_this_binding(compressor.parent(), compressor.self(), self.left).optimize(compressor);
  5861. }
  5862. var rr = self.right.evaluate(compressor);
  5863. if (!rr) {
  5864. var parent = compressor.parent();
  5865. if (parent.operator == "||" && parent.left === compressor.self() || compressor.in_boolean_context()) {
  5866. return self.left.optimize(compressor);
  5867. }
  5868. } else if (!(rr instanceof AST_Node)) {
  5869. if (compressor.in_boolean_context()) {
  5870. return make_sequence(self, [
  5871. self.left,
  5872. make_node(AST_True, self)
  5873. ]).optimize(compressor);
  5874. } else {
  5875. set_flag(self, TRUTHY);
  5876. }
  5877. }
  5878. if (self.left.operator == "&&") {
  5879. var lr = self.left.right.evaluate(compressor);
  5880. if (lr && !(lr instanceof AST_Node)) return make_node(AST_Conditional, self, {
  5881. condition: self.left.left,
  5882. consequent: self.left.right,
  5883. alternative: self.right
  5884. }).optimize(compressor);
  5885. }
  5886. break;
  5887. case "??":
  5888. if (is_nullish(self.left)) {
  5889. return self.right;
  5890. }
  5891. var ll = self.left.evaluate(compressor);
  5892. if (!(ll instanceof AST_Node)) {
  5893. // if we know the value for sure we can simply compute right away.
  5894. return ll == null ? self.right : self.left;
  5895. }
  5896. if (compressor.in_boolean_context()) {
  5897. const rr = self.right.evaluate(compressor);
  5898. if (!(rr instanceof AST_Node) && !rr) {
  5899. return self.left;
  5900. }
  5901. }
  5902. }
  5903. var associative = true;
  5904. switch (self.operator) {
  5905. case "+":
  5906. // (x + "foo") + "bar" => x + "foobar"
  5907. if (self.right instanceof AST_Constant
  5908. && self.left instanceof AST_Binary
  5909. && self.left.operator == "+"
  5910. && self.left.is_string(compressor)) {
  5911. var binary = make_node(AST_Binary, self, {
  5912. operator: "+",
  5913. left: self.left.right,
  5914. right: self.right,
  5915. });
  5916. var r = binary.optimize(compressor);
  5917. if (binary !== r) {
  5918. self = make_node(AST_Binary, self, {
  5919. operator: "+",
  5920. left: self.left.left,
  5921. right: r
  5922. });
  5923. }
  5924. }
  5925. // (x + "foo") + ("bar" + y) => (x + "foobar") + y
  5926. if (self.left instanceof AST_Binary
  5927. && self.left.operator == "+"
  5928. && self.left.is_string(compressor)
  5929. && self.right instanceof AST_Binary
  5930. && self.right.operator == "+"
  5931. && self.right.is_string(compressor)) {
  5932. var binary = make_node(AST_Binary, self, {
  5933. operator: "+",
  5934. left: self.left.right,
  5935. right: self.right.left,
  5936. });
  5937. var m = binary.optimize(compressor);
  5938. if (binary !== m) {
  5939. self = make_node(AST_Binary, self, {
  5940. operator: "+",
  5941. left: make_node(AST_Binary, self.left, {
  5942. operator: "+",
  5943. left: self.left.left,
  5944. right: m
  5945. }),
  5946. right: self.right.right
  5947. });
  5948. }
  5949. }
  5950. // a + -b => a - b
  5951. if (self.right instanceof AST_UnaryPrefix
  5952. && self.right.operator == "-"
  5953. && self.left.is_number(compressor)) {
  5954. self = make_node(AST_Binary, self, {
  5955. operator: "-",
  5956. left: self.left,
  5957. right: self.right.expression
  5958. });
  5959. break;
  5960. }
  5961. // -a + b => b - a
  5962. if (self.left instanceof AST_UnaryPrefix
  5963. && self.left.operator == "-"
  5964. && reversible()
  5965. && self.right.is_number(compressor)) {
  5966. self = make_node(AST_Binary, self, {
  5967. operator: "-",
  5968. left: self.right,
  5969. right: self.left.expression
  5970. });
  5971. break;
  5972. }
  5973. // `foo${bar}baz` + 1 => `foo${bar}baz1`
  5974. if (self.left instanceof AST_TemplateString) {
  5975. var l = self.left;
  5976. var r = self.right.evaluate(compressor);
  5977. if (r != self.right) {
  5978. l.segments[l.segments.length - 1].value += String(r);
  5979. return l;
  5980. }
  5981. }
  5982. // 1 + `foo${bar}baz` => `1foo${bar}baz`
  5983. if (self.right instanceof AST_TemplateString) {
  5984. var r = self.right;
  5985. var l = self.left.evaluate(compressor);
  5986. if (l != self.left) {
  5987. r.segments[0].value = String(l) + r.segments[0].value;
  5988. return r;
  5989. }
  5990. }
  5991. // `1${bar}2` + `foo${bar}baz` => `1${bar}2foo${bar}baz`
  5992. if (self.left instanceof AST_TemplateString
  5993. && self.right instanceof AST_TemplateString) {
  5994. var l = self.left;
  5995. var segments = l.segments;
  5996. var r = self.right;
  5997. segments[segments.length - 1].value += r.segments[0].value;
  5998. for (var i = 1; i < r.segments.length; i++) {
  5999. segments.push(r.segments[i]);
  6000. }
  6001. return l;
  6002. }
  6003. case "*":
  6004. associative = compressor.option("unsafe_math");
  6005. case "&":
  6006. case "|":
  6007. case "^":
  6008. // a + +b => +b + a
  6009. if (self.left.is_number(compressor)
  6010. && self.right.is_number(compressor)
  6011. && reversible()
  6012. && !(self.left instanceof AST_Binary
  6013. && self.left.operator != self.operator
  6014. && PRECEDENCE[self.left.operator] >= PRECEDENCE[self.operator])) {
  6015. var reversed = make_node(AST_Binary, self, {
  6016. operator: self.operator,
  6017. left: self.right,
  6018. right: self.left
  6019. });
  6020. if (self.right instanceof AST_Constant
  6021. && !(self.left instanceof AST_Constant)) {
  6022. self = best_of(compressor, reversed, self);
  6023. } else {
  6024. self = best_of(compressor, self, reversed);
  6025. }
  6026. }
  6027. if (associative && self.is_number(compressor)) {
  6028. // a + (b + c) => (a + b) + c
  6029. if (self.right instanceof AST_Binary
  6030. && self.right.operator == self.operator) {
  6031. self = make_node(AST_Binary, self, {
  6032. operator: self.operator,
  6033. left: make_node(AST_Binary, self.left, {
  6034. operator: self.operator,
  6035. left: self.left,
  6036. right: self.right.left,
  6037. start: self.left.start,
  6038. end: self.right.left.end
  6039. }),
  6040. right: self.right.right
  6041. });
  6042. }
  6043. // (n + 2) + 3 => 5 + n
  6044. // (2 * n) * 3 => 6 + n
  6045. if (self.right instanceof AST_Constant
  6046. && self.left instanceof AST_Binary
  6047. && self.left.operator == self.operator) {
  6048. if (self.left.left instanceof AST_Constant) {
  6049. self = make_node(AST_Binary, self, {
  6050. operator: self.operator,
  6051. left: make_node(AST_Binary, self.left, {
  6052. operator: self.operator,
  6053. left: self.left.left,
  6054. right: self.right,
  6055. start: self.left.left.start,
  6056. end: self.right.end
  6057. }),
  6058. right: self.left.right
  6059. });
  6060. } else if (self.left.right instanceof AST_Constant) {
  6061. self = make_node(AST_Binary, self, {
  6062. operator: self.operator,
  6063. left: make_node(AST_Binary, self.left, {
  6064. operator: self.operator,
  6065. left: self.left.right,
  6066. right: self.right,
  6067. start: self.left.right.start,
  6068. end: self.right.end
  6069. }),
  6070. right: self.left.left
  6071. });
  6072. }
  6073. }
  6074. // (a | 1) | (2 | d) => (3 | a) | b
  6075. if (self.left instanceof AST_Binary
  6076. && self.left.operator == self.operator
  6077. && self.left.right instanceof AST_Constant
  6078. && self.right instanceof AST_Binary
  6079. && self.right.operator == self.operator
  6080. && self.right.left instanceof AST_Constant) {
  6081. self = make_node(AST_Binary, self, {
  6082. operator: self.operator,
  6083. left: make_node(AST_Binary, self.left, {
  6084. operator: self.operator,
  6085. left: make_node(AST_Binary, self.left.left, {
  6086. operator: self.operator,
  6087. left: self.left.right,
  6088. right: self.right.left,
  6089. start: self.left.right.start,
  6090. end: self.right.left.end
  6091. }),
  6092. right: self.left.left
  6093. }),
  6094. right: self.right.right
  6095. });
  6096. }
  6097. }
  6098. }
  6099. }
  6100. // x && (y && z) ==> x && y && z
  6101. // x || (y || z) ==> x || y || z
  6102. // x + ("y" + z) ==> x + "y" + z
  6103. // "x" + (y + "z")==> "x" + y + "z"
  6104. if (self.right instanceof AST_Binary
  6105. && self.right.operator == self.operator
  6106. && (lazy_op.has(self.operator)
  6107. || (self.operator == "+"
  6108. && (self.right.left.is_string(compressor)
  6109. || (self.left.is_string(compressor)
  6110. && self.right.right.is_string(compressor)))))
  6111. ) {
  6112. self.left = make_node(AST_Binary, self.left, {
  6113. operator : self.operator,
  6114. left : self.left.transform(compressor),
  6115. right : self.right.left.transform(compressor)
  6116. });
  6117. self.right = self.right.right.transform(compressor);
  6118. return self.transform(compressor);
  6119. }
  6120. var ev = self.evaluate(compressor);
  6121. if (ev !== self) {
  6122. ev = make_node_from_constant(ev, self).optimize(compressor);
  6123. return best_of(compressor, ev, self);
  6124. }
  6125. return self;
  6126. });
  6127. def_optimize(AST_SymbolExport, function(self) {
  6128. return self;
  6129. });
  6130. function recursive_ref(compressor, def) {
  6131. var node;
  6132. for (var i = 0; node = compressor.parent(i); i++) {
  6133. if (
  6134. node instanceof AST_Lambda
  6135. || node instanceof AST_Class
  6136. ) {
  6137. var name = node.name;
  6138. if (name && name.definition() === def) break;
  6139. }
  6140. }
  6141. return node;
  6142. }
  6143. function within_array_or_object_literal(compressor) {
  6144. var node, level = 0;
  6145. while (node = compressor.parent(level++)) {
  6146. if (node instanceof AST_Statement) return false;
  6147. if (node instanceof AST_Array
  6148. || node instanceof AST_ObjectKeyVal
  6149. || node instanceof AST_Object) {
  6150. return true;
  6151. }
  6152. }
  6153. return false;
  6154. }
  6155. def_optimize(AST_SymbolRef, function(self, compressor) {
  6156. if (
  6157. !compressor.option("ie8")
  6158. && is_undeclared_ref(self)
  6159. && !compressor.find_parent(AST_With)
  6160. ) {
  6161. switch (self.name) {
  6162. case "undefined":
  6163. return make_node(AST_Undefined, self).optimize(compressor);
  6164. case "NaN":
  6165. return make_node(AST_NaN, self).optimize(compressor);
  6166. case "Infinity":
  6167. return make_node(AST_Infinity, self).optimize(compressor);
  6168. }
  6169. }
  6170. const parent = compressor.parent();
  6171. if (compressor.option("reduce_vars") && is_lhs(self, parent) !== self) {
  6172. const def = self.definition();
  6173. const nearest_scope = find_scope(compressor);
  6174. if (compressor.top_retain && def.global && compressor.top_retain(def)) {
  6175. def.fixed = false;
  6176. def.single_use = false;
  6177. return self;
  6178. }
  6179. let fixed = self.fixed_value();
  6180. let single_use = def.single_use
  6181. && !(parent instanceof AST_Call
  6182. && (parent.is_callee_pure(compressor))
  6183. || has_annotation(parent, _NOINLINE))
  6184. && !(parent instanceof AST_Export
  6185. && fixed instanceof AST_Lambda
  6186. && fixed.name);
  6187. if (single_use && fixed instanceof AST_Node) {
  6188. single_use =
  6189. !fixed.has_side_effects(compressor)
  6190. && !fixed.may_throw(compressor);
  6191. }
  6192. if (single_use && (fixed instanceof AST_Lambda || fixed instanceof AST_Class)) {
  6193. if (retain_top_func(fixed, compressor)) {
  6194. single_use = false;
  6195. } else if (def.scope !== self.scope
  6196. && (def.escaped == 1
  6197. || has_flag(fixed, INLINED)
  6198. || within_array_or_object_literal(compressor)
  6199. || !compressor.option("reduce_funcs"))) {
  6200. single_use = false;
  6201. } else if (recursive_ref(compressor, def)) {
  6202. single_use = false;
  6203. } else if (def.scope !== self.scope || def.orig[0] instanceof AST_SymbolFunarg) {
  6204. single_use = fixed.is_constant_expression(self.scope);
  6205. if (single_use == "f") {
  6206. var scope = self.scope;
  6207. do {
  6208. if (scope instanceof AST_Defun || is_func_expr(scope)) {
  6209. set_flag(scope, INLINED);
  6210. }
  6211. } while (scope = scope.parent_scope);
  6212. }
  6213. }
  6214. }
  6215. if (single_use && fixed instanceof AST_Lambda) {
  6216. single_use =
  6217. def.scope === self.scope
  6218. && !scope_encloses_variables_in_this_scope(nearest_scope, fixed)
  6219. || parent instanceof AST_Call
  6220. && parent.expression === self
  6221. && !scope_encloses_variables_in_this_scope(nearest_scope, fixed)
  6222. && !(fixed.name && fixed.name.definition().recursive_refs > 0);
  6223. }
  6224. if (single_use && fixed) {
  6225. if (fixed instanceof AST_DefClass) {
  6226. set_flag(fixed, SQUEEZED);
  6227. fixed = make_node(AST_ClassExpression, fixed, fixed);
  6228. }
  6229. if (fixed instanceof AST_Defun) {
  6230. set_flag(fixed, SQUEEZED);
  6231. fixed = make_node(AST_Function, fixed, fixed);
  6232. }
  6233. if (def.recursive_refs > 0 && fixed.name instanceof AST_SymbolDefun) {
  6234. const defun_def = fixed.name.definition();
  6235. let lambda_def = fixed.variables.get(fixed.name.name);
  6236. let name = lambda_def && lambda_def.orig[0];
  6237. if (!(name instanceof AST_SymbolLambda)) {
  6238. name = make_node(AST_SymbolLambda, fixed.name, fixed.name);
  6239. name.scope = fixed;
  6240. fixed.name = name;
  6241. lambda_def = fixed.def_function(name);
  6242. }
  6243. walk(fixed, node => {
  6244. if (node instanceof AST_SymbolRef && node.definition() === defun_def) {
  6245. node.thedef = lambda_def;
  6246. lambda_def.references.push(node);
  6247. }
  6248. });
  6249. }
  6250. if (
  6251. (fixed instanceof AST_Lambda || fixed instanceof AST_Class)
  6252. && fixed.parent_scope !== nearest_scope
  6253. ) {
  6254. fixed = fixed.clone(true, compressor.get_toplevel());
  6255. nearest_scope.add_child_scope(fixed);
  6256. }
  6257. return fixed.optimize(compressor);
  6258. }
  6259. // multiple uses
  6260. if (fixed) {
  6261. let replace;
  6262. if (fixed instanceof AST_This) {
  6263. if (!(def.orig[0] instanceof AST_SymbolFunarg)
  6264. && def.references.every((ref) =>
  6265. def.scope === ref.scope
  6266. )) {
  6267. replace = fixed;
  6268. }
  6269. } else {
  6270. var ev = fixed.evaluate(compressor);
  6271. if (
  6272. ev !== fixed
  6273. && (compressor.option("unsafe_regexp") || !(ev instanceof RegExp))
  6274. ) {
  6275. replace = make_node_from_constant(ev, fixed);
  6276. }
  6277. }
  6278. if (replace) {
  6279. const name_length = self.size(compressor);
  6280. const replace_size = replace.size(compressor);
  6281. let overhead = 0;
  6282. if (compressor.option("unused") && !compressor.exposed(def)) {
  6283. overhead =
  6284. (name_length + 2 + replace_size) /
  6285. (def.references.length - def.assignments);
  6286. }
  6287. if (replace_size <= name_length + overhead) {
  6288. return replace;
  6289. }
  6290. }
  6291. }
  6292. }
  6293. return self;
  6294. });
  6295. function scope_encloses_variables_in_this_scope(scope, pulled_scope) {
  6296. for (const enclosed of pulled_scope.enclosed) {
  6297. if (pulled_scope.variables.has(enclosed.name)) {
  6298. continue;
  6299. }
  6300. const looked_up = scope.find_variable(enclosed.name);
  6301. if (looked_up) {
  6302. if (looked_up === enclosed) continue;
  6303. return true;
  6304. }
  6305. }
  6306. return false;
  6307. }
  6308. function is_atomic(lhs, self) {
  6309. return lhs instanceof AST_SymbolRef || lhs.TYPE === self.TYPE;
  6310. }
  6311. def_optimize(AST_Undefined, function(self, compressor) {
  6312. if (compressor.option("unsafe_undefined")) {
  6313. var undef = find_variable(compressor, "undefined");
  6314. if (undef) {
  6315. var ref = make_node(AST_SymbolRef, self, {
  6316. name : "undefined",
  6317. scope : undef.scope,
  6318. thedef : undef
  6319. });
  6320. set_flag(ref, UNDEFINED);
  6321. return ref;
  6322. }
  6323. }
  6324. var lhs = is_lhs(compressor.self(), compressor.parent());
  6325. if (lhs && is_atomic(lhs, self)) return self;
  6326. return make_node(AST_UnaryPrefix, self, {
  6327. operator: "void",
  6328. expression: make_node(AST_Number, self, {
  6329. value: 0
  6330. })
  6331. });
  6332. });
  6333. def_optimize(AST_Infinity, function(self, compressor) {
  6334. var lhs = is_lhs(compressor.self(), compressor.parent());
  6335. if (lhs && is_atomic(lhs, self)) return self;
  6336. if (
  6337. compressor.option("keep_infinity")
  6338. && !(lhs && !is_atomic(lhs, self))
  6339. && !find_variable(compressor, "Infinity")
  6340. ) {
  6341. return self;
  6342. }
  6343. return make_node(AST_Binary, self, {
  6344. operator: "/",
  6345. left: make_node(AST_Number, self, {
  6346. value: 1
  6347. }),
  6348. right: make_node(AST_Number, self, {
  6349. value: 0
  6350. })
  6351. });
  6352. });
  6353. def_optimize(AST_NaN, function(self, compressor) {
  6354. var lhs = is_lhs(compressor.self(), compressor.parent());
  6355. if (lhs && !is_atomic(lhs, self)
  6356. || find_variable(compressor, "NaN")) {
  6357. return make_node(AST_Binary, self, {
  6358. operator: "/",
  6359. left: make_node(AST_Number, self, {
  6360. value: 0
  6361. }),
  6362. right: make_node(AST_Number, self, {
  6363. value: 0
  6364. })
  6365. });
  6366. }
  6367. return self;
  6368. });
  6369. function is_reachable(self, defs) {
  6370. const find_ref = node => {
  6371. if (node instanceof AST_SymbolRef && member(node.definition(), defs)) {
  6372. return walk_abort;
  6373. }
  6374. };
  6375. return walk_parent(self, (node, info) => {
  6376. if (node instanceof AST_Scope && node !== self) {
  6377. var parent = info.parent();
  6378. if (parent instanceof AST_Call && parent.expression === node) return;
  6379. if (walk(node, find_ref)) return walk_abort;
  6380. return true;
  6381. }
  6382. });
  6383. }
  6384. const ASSIGN_OPS = makePredicate("+ - / * % >> << >>> | ^ &");
  6385. const ASSIGN_OPS_COMMUTATIVE = makePredicate("* | ^ &");
  6386. def_optimize(AST_Assign, function(self, compressor) {
  6387. if (self.logical) {
  6388. return self.lift_sequences(compressor);
  6389. }
  6390. var def;
  6391. if (compressor.option("dead_code")
  6392. && self.left instanceof AST_SymbolRef
  6393. && (def = self.left.definition()).scope === compressor.find_parent(AST_Lambda)) {
  6394. var level = 0, node, parent = self;
  6395. do {
  6396. node = parent;
  6397. parent = compressor.parent(level++);
  6398. if (parent instanceof AST_Exit) {
  6399. if (in_try(level, parent)) break;
  6400. if (is_reachable(def.scope, [ def ])) break;
  6401. if (self.operator == "=") return self.right;
  6402. def.fixed = false;
  6403. return make_node(AST_Binary, self, {
  6404. operator: self.operator.slice(0, -1),
  6405. left: self.left,
  6406. right: self.right
  6407. }).optimize(compressor);
  6408. }
  6409. } while (parent instanceof AST_Binary && parent.right === node
  6410. || parent instanceof AST_Sequence && parent.tail_node() === node);
  6411. }
  6412. self = self.lift_sequences(compressor);
  6413. if (self.operator == "=" && self.left instanceof AST_SymbolRef && self.right instanceof AST_Binary) {
  6414. // x = expr1 OP expr2
  6415. if (self.right.left instanceof AST_SymbolRef
  6416. && self.right.left.name == self.left.name
  6417. && ASSIGN_OPS.has(self.right.operator)) {
  6418. // x = x - 2 ---> x -= 2
  6419. self.operator = self.right.operator + "=";
  6420. self.right = self.right.right;
  6421. } else if (self.right.right instanceof AST_SymbolRef
  6422. && self.right.right.name == self.left.name
  6423. && ASSIGN_OPS_COMMUTATIVE.has(self.right.operator)
  6424. && !self.right.left.has_side_effects(compressor)) {
  6425. // x = 2 & x ---> x &= 2
  6426. self.operator = self.right.operator + "=";
  6427. self.right = self.right.left;
  6428. }
  6429. }
  6430. return self;
  6431. function in_try(level, node) {
  6432. var right = self.right;
  6433. self.right = make_node(AST_Null, right);
  6434. var may_throw = node.may_throw(compressor);
  6435. self.right = right;
  6436. var scope = self.left.definition().scope;
  6437. var parent;
  6438. while ((parent = compressor.parent(level++)) !== scope) {
  6439. if (parent instanceof AST_Try) {
  6440. if (parent.bfinally) return true;
  6441. if (may_throw && parent.bcatch) return true;
  6442. }
  6443. }
  6444. }
  6445. });
  6446. def_optimize(AST_DefaultAssign, function(self, compressor) {
  6447. if (!compressor.option("evaluate")) {
  6448. return self;
  6449. }
  6450. var evaluateRight = self.right.evaluate(compressor);
  6451. // `[x = undefined] = foo` ---> `[x] = foo`
  6452. if (evaluateRight === undefined) {
  6453. self = self.left;
  6454. } else if (evaluateRight !== self.right) {
  6455. evaluateRight = make_node_from_constant(evaluateRight, self.right);
  6456. self.right = best_of_expression(evaluateRight, self.right);
  6457. }
  6458. return self;
  6459. });
  6460. function is_nullish(node) {
  6461. let fixed;
  6462. return (
  6463. node instanceof AST_Null
  6464. || is_undefined(node)
  6465. || (
  6466. node instanceof AST_SymbolRef
  6467. && (fixed = node.definition().fixed) instanceof AST_Node
  6468. && is_nullish(fixed)
  6469. )
  6470. // Recurse into those optional chains!
  6471. || node instanceof AST_PropAccess && node.optional && is_nullish(node.expression)
  6472. || node instanceof AST_Call && node.optional && is_nullish(node.expression)
  6473. || node instanceof AST_Chain && is_nullish(node.expression)
  6474. );
  6475. }
  6476. function is_nullish_check(check, check_subject, compressor) {
  6477. if (check_subject.may_throw(compressor)) return false;
  6478. let nullish_side;
  6479. // foo == null
  6480. if (
  6481. check instanceof AST_Binary
  6482. && check.operator === "=="
  6483. // which side is nullish?
  6484. && (
  6485. (nullish_side = is_nullish(check.left) && check.left)
  6486. || (nullish_side = is_nullish(check.right) && check.right)
  6487. )
  6488. // is the other side the same as the check_subject
  6489. && (
  6490. nullish_side === check.left
  6491. ? check.right
  6492. : check.left
  6493. ).equivalent_to(check_subject)
  6494. ) {
  6495. return true;
  6496. }
  6497. // foo === null || foo === undefined
  6498. if (check instanceof AST_Binary && check.operator === "||") {
  6499. let null_cmp;
  6500. let undefined_cmp;
  6501. const find_comparison = cmp => {
  6502. if (!(
  6503. cmp instanceof AST_Binary
  6504. && (cmp.operator === "===" || cmp.operator === "==")
  6505. )) {
  6506. return false;
  6507. }
  6508. let found = 0;
  6509. let defined_side;
  6510. if (cmp.left instanceof AST_Null) {
  6511. found++;
  6512. null_cmp = cmp;
  6513. defined_side = cmp.right;
  6514. }
  6515. if (cmp.right instanceof AST_Null) {
  6516. found++;
  6517. null_cmp = cmp;
  6518. defined_side = cmp.left;
  6519. }
  6520. if (is_undefined(cmp.left)) {
  6521. found++;
  6522. undefined_cmp = cmp;
  6523. defined_side = cmp.right;
  6524. }
  6525. if (is_undefined(cmp.right)) {
  6526. found++;
  6527. undefined_cmp = cmp;
  6528. defined_side = cmp.left;
  6529. }
  6530. if (found !== 1) {
  6531. return false;
  6532. }
  6533. if (!defined_side.equivalent_to(check_subject)) {
  6534. return false;
  6535. }
  6536. return true;
  6537. };
  6538. if (!find_comparison(check.left)) return false;
  6539. if (!find_comparison(check.right)) return false;
  6540. if (null_cmp && undefined_cmp && null_cmp !== undefined_cmp) {
  6541. return true;
  6542. }
  6543. }
  6544. return false;
  6545. }
  6546. def_optimize(AST_Conditional, function(self, compressor) {
  6547. if (!compressor.option("conditionals")) return self;
  6548. // This looks like lift_sequences(), should probably be under "sequences"
  6549. if (self.condition instanceof AST_Sequence) {
  6550. var expressions = self.condition.expressions.slice();
  6551. self.condition = expressions.pop();
  6552. expressions.push(self);
  6553. return make_sequence(self, expressions);
  6554. }
  6555. var cond = self.condition.evaluate(compressor);
  6556. if (cond !== self.condition) {
  6557. if (cond) {
  6558. return maintain_this_binding(compressor.parent(), compressor.self(), self.consequent);
  6559. } else {
  6560. return maintain_this_binding(compressor.parent(), compressor.self(), self.alternative);
  6561. }
  6562. }
  6563. var negated = cond.negate(compressor, first_in_statement(compressor));
  6564. if (best_of(compressor, cond, negated) === negated) {
  6565. self = make_node(AST_Conditional, self, {
  6566. condition: negated,
  6567. consequent: self.alternative,
  6568. alternative: self.consequent
  6569. });
  6570. }
  6571. var condition = self.condition;
  6572. var consequent = self.consequent;
  6573. var alternative = self.alternative;
  6574. // x?x:y --> x||y
  6575. if (condition instanceof AST_SymbolRef
  6576. && consequent instanceof AST_SymbolRef
  6577. && condition.definition() === consequent.definition()) {
  6578. return make_node(AST_Binary, self, {
  6579. operator: "||",
  6580. left: condition,
  6581. right: alternative
  6582. });
  6583. }
  6584. // if (foo) exp = something; else exp = something_else;
  6585. // |
  6586. // v
  6587. // exp = foo ? something : something_else;
  6588. if (
  6589. consequent instanceof AST_Assign
  6590. && alternative instanceof AST_Assign
  6591. && consequent.operator === alternative.operator
  6592. && consequent.logical === alternative.logical
  6593. && consequent.left.equivalent_to(alternative.left)
  6594. && (!self.condition.has_side_effects(compressor)
  6595. || consequent.operator == "="
  6596. && !consequent.left.has_side_effects(compressor))
  6597. ) {
  6598. return make_node(AST_Assign, self, {
  6599. operator: consequent.operator,
  6600. left: consequent.left,
  6601. logical: consequent.logical,
  6602. right: make_node(AST_Conditional, self, {
  6603. condition: self.condition,
  6604. consequent: consequent.right,
  6605. alternative: alternative.right
  6606. })
  6607. });
  6608. }
  6609. // x ? y(a) : y(b) --> y(x ? a : b)
  6610. var arg_index;
  6611. if (consequent instanceof AST_Call
  6612. && alternative.TYPE === consequent.TYPE
  6613. && consequent.args.length > 0
  6614. && consequent.args.length == alternative.args.length
  6615. && consequent.expression.equivalent_to(alternative.expression)
  6616. && !self.condition.has_side_effects(compressor)
  6617. && !consequent.expression.has_side_effects(compressor)
  6618. && typeof (arg_index = single_arg_diff()) == "number") {
  6619. var node = consequent.clone();
  6620. node.args[arg_index] = make_node(AST_Conditional, self, {
  6621. condition: self.condition,
  6622. consequent: consequent.args[arg_index],
  6623. alternative: alternative.args[arg_index]
  6624. });
  6625. return node;
  6626. }
  6627. // a ? b : c ? b : d --> (a || c) ? b : d
  6628. if (alternative instanceof AST_Conditional
  6629. && consequent.equivalent_to(alternative.consequent)) {
  6630. return make_node(AST_Conditional, self, {
  6631. condition: make_node(AST_Binary, self, {
  6632. operator: "||",
  6633. left: condition,
  6634. right: alternative.condition
  6635. }),
  6636. consequent: consequent,
  6637. alternative: alternative.alternative
  6638. }).optimize(compressor);
  6639. }
  6640. // a == null ? b : a -> a ?? b
  6641. if (
  6642. compressor.option("ecma") >= 2020 &&
  6643. is_nullish_check(condition, alternative, compressor)
  6644. ) {
  6645. return make_node(AST_Binary, self, {
  6646. operator: "??",
  6647. left: alternative,
  6648. right: consequent
  6649. }).optimize(compressor);
  6650. }
  6651. // a ? b : (c, b) --> (a || c), b
  6652. if (alternative instanceof AST_Sequence
  6653. && consequent.equivalent_to(alternative.expressions[alternative.expressions.length - 1])) {
  6654. return make_sequence(self, [
  6655. make_node(AST_Binary, self, {
  6656. operator: "||",
  6657. left: condition,
  6658. right: make_sequence(self, alternative.expressions.slice(0, -1))
  6659. }),
  6660. consequent
  6661. ]).optimize(compressor);
  6662. }
  6663. // a ? b : (c && b) --> (a || c) && b
  6664. if (alternative instanceof AST_Binary
  6665. && alternative.operator == "&&"
  6666. && consequent.equivalent_to(alternative.right)) {
  6667. return make_node(AST_Binary, self, {
  6668. operator: "&&",
  6669. left: make_node(AST_Binary, self, {
  6670. operator: "||",
  6671. left: condition,
  6672. right: alternative.left
  6673. }),
  6674. right: consequent
  6675. }).optimize(compressor);
  6676. }
  6677. // x?y?z:a:a --> x&&y?z:a
  6678. if (consequent instanceof AST_Conditional
  6679. && consequent.alternative.equivalent_to(alternative)) {
  6680. return make_node(AST_Conditional, self, {
  6681. condition: make_node(AST_Binary, self, {
  6682. left: self.condition,
  6683. operator: "&&",
  6684. right: consequent.condition
  6685. }),
  6686. consequent: consequent.consequent,
  6687. alternative: alternative
  6688. });
  6689. }
  6690. // x ? y : y --> x, y
  6691. if (consequent.equivalent_to(alternative)) {
  6692. return make_sequence(self, [
  6693. self.condition,
  6694. consequent
  6695. ]).optimize(compressor);
  6696. }
  6697. // x ? y || z : z --> x && y || z
  6698. if (consequent instanceof AST_Binary
  6699. && consequent.operator == "||"
  6700. && consequent.right.equivalent_to(alternative)) {
  6701. return make_node(AST_Binary, self, {
  6702. operator: "||",
  6703. left: make_node(AST_Binary, self, {
  6704. operator: "&&",
  6705. left: self.condition,
  6706. right: consequent.left
  6707. }),
  6708. right: alternative
  6709. }).optimize(compressor);
  6710. }
  6711. var in_bool = compressor.in_boolean_context();
  6712. if (is_true(self.consequent)) {
  6713. if (is_false(self.alternative)) {
  6714. // c ? true : false ---> !!c
  6715. return booleanize(self.condition);
  6716. }
  6717. // c ? true : x ---> !!c || x
  6718. return make_node(AST_Binary, self, {
  6719. operator: "||",
  6720. left: booleanize(self.condition),
  6721. right: self.alternative
  6722. });
  6723. }
  6724. if (is_false(self.consequent)) {
  6725. if (is_true(self.alternative)) {
  6726. // c ? false : true ---> !c
  6727. return booleanize(self.condition.negate(compressor));
  6728. }
  6729. // c ? false : x ---> !c && x
  6730. return make_node(AST_Binary, self, {
  6731. operator: "&&",
  6732. left: booleanize(self.condition.negate(compressor)),
  6733. right: self.alternative
  6734. });
  6735. }
  6736. if (is_true(self.alternative)) {
  6737. // c ? x : true ---> !c || x
  6738. return make_node(AST_Binary, self, {
  6739. operator: "||",
  6740. left: booleanize(self.condition.negate(compressor)),
  6741. right: self.consequent
  6742. });
  6743. }
  6744. if (is_false(self.alternative)) {
  6745. // c ? x : false ---> !!c && x
  6746. return make_node(AST_Binary, self, {
  6747. operator: "&&",
  6748. left: booleanize(self.condition),
  6749. right: self.consequent
  6750. });
  6751. }
  6752. return self;
  6753. function booleanize(node) {
  6754. if (node.is_boolean()) return node;
  6755. // !!expression
  6756. return make_node(AST_UnaryPrefix, node, {
  6757. operator: "!",
  6758. expression: node.negate(compressor)
  6759. });
  6760. }
  6761. // AST_True or !0
  6762. function is_true(node) {
  6763. return node instanceof AST_True
  6764. || in_bool
  6765. && node instanceof AST_Constant
  6766. && node.getValue()
  6767. || (node instanceof AST_UnaryPrefix
  6768. && node.operator == "!"
  6769. && node.expression instanceof AST_Constant
  6770. && !node.expression.getValue());
  6771. }
  6772. // AST_False or !1
  6773. function is_false(node) {
  6774. return node instanceof AST_False
  6775. || in_bool
  6776. && node instanceof AST_Constant
  6777. && !node.getValue()
  6778. || (node instanceof AST_UnaryPrefix
  6779. && node.operator == "!"
  6780. && node.expression instanceof AST_Constant
  6781. && node.expression.getValue());
  6782. }
  6783. function single_arg_diff() {
  6784. var a = consequent.args;
  6785. var b = alternative.args;
  6786. for (var i = 0, len = a.length; i < len; i++) {
  6787. if (a[i] instanceof AST_Expansion) return;
  6788. if (!a[i].equivalent_to(b[i])) {
  6789. if (b[i] instanceof AST_Expansion) return;
  6790. for (var j = i + 1; j < len; j++) {
  6791. if (a[j] instanceof AST_Expansion) return;
  6792. if (!a[j].equivalent_to(b[j])) return;
  6793. }
  6794. return i;
  6795. }
  6796. }
  6797. }
  6798. });
  6799. def_optimize(AST_Boolean, function(self, compressor) {
  6800. if (compressor.in_boolean_context()) return make_node(AST_Number, self, {
  6801. value: +self.value
  6802. });
  6803. var p = compressor.parent();
  6804. if (compressor.option("booleans_as_integers")) {
  6805. if (p instanceof AST_Binary && (p.operator == "===" || p.operator == "!==")) {
  6806. p.operator = p.operator.replace(/=$/, "");
  6807. }
  6808. return make_node(AST_Number, self, {
  6809. value: +self.value
  6810. });
  6811. }
  6812. if (compressor.option("booleans")) {
  6813. if (p instanceof AST_Binary && (p.operator == "=="
  6814. || p.operator == "!=")) {
  6815. return make_node(AST_Number, self, {
  6816. value: +self.value
  6817. });
  6818. }
  6819. return make_node(AST_UnaryPrefix, self, {
  6820. operator: "!",
  6821. expression: make_node(AST_Number, self, {
  6822. value: 1 - self.value
  6823. })
  6824. });
  6825. }
  6826. return self;
  6827. });
  6828. function safe_to_flatten(value, compressor) {
  6829. if (value instanceof AST_SymbolRef) {
  6830. value = value.fixed_value();
  6831. }
  6832. if (!value) return false;
  6833. if (!(value instanceof AST_Lambda || value instanceof AST_Class)) return true;
  6834. if (!(value instanceof AST_Lambda && value.contains_this())) return true;
  6835. return compressor.parent() instanceof AST_New;
  6836. }
  6837. AST_PropAccess.DEFMETHOD("flatten_object", function(key, compressor) {
  6838. if (!compressor.option("properties")) return;
  6839. if (key === "__proto__") return;
  6840. var arrows = compressor.option("unsafe_arrows") && compressor.option("ecma") >= 2015;
  6841. var expr = this.expression;
  6842. if (expr instanceof AST_Object) {
  6843. var props = expr.properties;
  6844. for (var i = props.length; --i >= 0;) {
  6845. var prop = props[i];
  6846. if ("" + (prop instanceof AST_ConciseMethod ? prop.key.name : prop.key) == key) {
  6847. const all_props_flattenable = props.every((p) =>
  6848. (p instanceof AST_ObjectKeyVal
  6849. || arrows && p instanceof AST_ConciseMethod && !p.is_generator
  6850. )
  6851. && !p.computed_key()
  6852. );
  6853. if (!all_props_flattenable) return;
  6854. if (!safe_to_flatten(prop.value, compressor)) return;
  6855. return make_node(AST_Sub, this, {
  6856. expression: make_node(AST_Array, expr, {
  6857. elements: props.map(function(prop) {
  6858. var v = prop.value;
  6859. if (v instanceof AST_Accessor) {
  6860. v = make_node(AST_Function, v, v);
  6861. }
  6862. var k = prop.key;
  6863. if (k instanceof AST_Node && !(k instanceof AST_SymbolMethod)) {
  6864. return make_sequence(prop, [ k, v ]);
  6865. }
  6866. return v;
  6867. })
  6868. }),
  6869. property: make_node(AST_Number, this, {
  6870. value: i
  6871. })
  6872. });
  6873. }
  6874. }
  6875. }
  6876. });
  6877. def_optimize(AST_Sub, function(self, compressor) {
  6878. var expr = self.expression;
  6879. var prop = self.property;
  6880. if (compressor.option("properties")) {
  6881. var key = prop.evaluate(compressor);
  6882. if (key !== prop) {
  6883. if (typeof key == "string") {
  6884. if (key == "undefined") {
  6885. key = undefined;
  6886. } else {
  6887. var value = parseFloat(key);
  6888. if (value.toString() == key) {
  6889. key = value;
  6890. }
  6891. }
  6892. }
  6893. prop = self.property = best_of_expression(prop, make_node_from_constant(key, prop).transform(compressor));
  6894. var property = "" + key;
  6895. if (is_basic_identifier_string(property)
  6896. && property.length <= prop.size() + 1) {
  6897. return make_node(AST_Dot, self, {
  6898. expression: expr,
  6899. optional: self.optional,
  6900. property: property,
  6901. quote: prop.quote,
  6902. }).optimize(compressor);
  6903. }
  6904. }
  6905. }
  6906. var fn;
  6907. OPT_ARGUMENTS: if (compressor.option("arguments")
  6908. && expr instanceof AST_SymbolRef
  6909. && expr.name == "arguments"
  6910. && expr.definition().orig.length == 1
  6911. && (fn = expr.scope) instanceof AST_Lambda
  6912. && fn.uses_arguments
  6913. && !(fn instanceof AST_Arrow)
  6914. && prop instanceof AST_Number) {
  6915. var index = prop.getValue();
  6916. var params = new Set();
  6917. var argnames = fn.argnames;
  6918. for (var n = 0; n < argnames.length; n++) {
  6919. if (!(argnames[n] instanceof AST_SymbolFunarg)) {
  6920. break OPT_ARGUMENTS; // destructuring parameter - bail
  6921. }
  6922. var param = argnames[n].name;
  6923. if (params.has(param)) {
  6924. break OPT_ARGUMENTS; // duplicate parameter - bail
  6925. }
  6926. params.add(param);
  6927. }
  6928. var argname = fn.argnames[index];
  6929. if (argname && compressor.has_directive("use strict")) {
  6930. var def = argname.definition();
  6931. if (!compressor.option("reduce_vars") || def.assignments || def.orig.length > 1) {
  6932. argname = null;
  6933. }
  6934. } else if (!argname && !compressor.option("keep_fargs") && index < fn.argnames.length + 5) {
  6935. while (index >= fn.argnames.length) {
  6936. argname = fn.create_symbol(AST_SymbolFunarg, {
  6937. source: fn,
  6938. scope: fn,
  6939. tentative_name: "argument_" + fn.argnames.length,
  6940. });
  6941. fn.argnames.push(argname);
  6942. }
  6943. }
  6944. if (argname) {
  6945. var sym = make_node(AST_SymbolRef, self, argname);
  6946. sym.reference({});
  6947. clear_flag(argname, UNUSED);
  6948. return sym;
  6949. }
  6950. }
  6951. if (is_lhs(self, compressor.parent())) return self;
  6952. if (key !== prop) {
  6953. var sub = self.flatten_object(property, compressor);
  6954. if (sub) {
  6955. expr = self.expression = sub.expression;
  6956. prop = self.property = sub.property;
  6957. }
  6958. }
  6959. if (compressor.option("properties") && compressor.option("side_effects")
  6960. && prop instanceof AST_Number && expr instanceof AST_Array) {
  6961. var index = prop.getValue();
  6962. var elements = expr.elements;
  6963. var retValue = elements[index];
  6964. FLATTEN: if (safe_to_flatten(retValue, compressor)) {
  6965. var flatten = true;
  6966. var values = [];
  6967. for (var i = elements.length; --i > index;) {
  6968. var value = elements[i].drop_side_effect_free(compressor);
  6969. if (value) {
  6970. values.unshift(value);
  6971. if (flatten && value.has_side_effects(compressor)) flatten = false;
  6972. }
  6973. }
  6974. if (retValue instanceof AST_Expansion) break FLATTEN;
  6975. retValue = retValue instanceof AST_Hole ? make_node(AST_Undefined, retValue) : retValue;
  6976. if (!flatten) values.unshift(retValue);
  6977. while (--i >= 0) {
  6978. var value = elements[i];
  6979. if (value instanceof AST_Expansion) break FLATTEN;
  6980. value = value.drop_side_effect_free(compressor);
  6981. if (value) values.unshift(value);
  6982. else index--;
  6983. }
  6984. if (flatten) {
  6985. values.push(retValue);
  6986. return make_sequence(self, values).optimize(compressor);
  6987. } else return make_node(AST_Sub, self, {
  6988. expression: make_node(AST_Array, expr, {
  6989. elements: values
  6990. }),
  6991. property: make_node(AST_Number, prop, {
  6992. value: index
  6993. })
  6994. });
  6995. }
  6996. }
  6997. var ev = self.evaluate(compressor);
  6998. if (ev !== self) {
  6999. ev = make_node_from_constant(ev, self).optimize(compressor);
  7000. return best_of(compressor, ev, self);
  7001. }
  7002. if (self.optional && is_nullish(self.expression)) {
  7003. return make_node(AST_Undefined, self);
  7004. }
  7005. return self;
  7006. });
  7007. def_optimize(AST_Chain, function (self, compressor) {
  7008. self.expression = self.expression.optimize(compressor);
  7009. return self;
  7010. });
  7011. AST_Lambda.DEFMETHOD("contains_this", function() {
  7012. return walk(this, node => {
  7013. if (node instanceof AST_This) return walk_abort;
  7014. if (
  7015. node !== this
  7016. && node instanceof AST_Scope
  7017. && !(node instanceof AST_Arrow)
  7018. ) {
  7019. return true;
  7020. }
  7021. });
  7022. });
  7023. def_optimize(AST_Dot, function(self, compressor) {
  7024. const parent = compressor.parent();
  7025. if (is_lhs(self, parent)) return self;
  7026. if (compressor.option("unsafe_proto")
  7027. && self.expression instanceof AST_Dot
  7028. && self.expression.property == "prototype") {
  7029. var exp = self.expression.expression;
  7030. if (is_undeclared_ref(exp)) switch (exp.name) {
  7031. case "Array":
  7032. self.expression = make_node(AST_Array, self.expression, {
  7033. elements: []
  7034. });
  7035. break;
  7036. case "Function":
  7037. self.expression = make_node(AST_Function, self.expression, {
  7038. argnames: [],
  7039. body: []
  7040. });
  7041. break;
  7042. case "Number":
  7043. self.expression = make_node(AST_Number, self.expression, {
  7044. value: 0
  7045. });
  7046. break;
  7047. case "Object":
  7048. self.expression = make_node(AST_Object, self.expression, {
  7049. properties: []
  7050. });
  7051. break;
  7052. case "RegExp":
  7053. self.expression = make_node(AST_RegExp, self.expression, {
  7054. value: { source: "t", flags: "" }
  7055. });
  7056. break;
  7057. case "String":
  7058. self.expression = make_node(AST_String, self.expression, {
  7059. value: ""
  7060. });
  7061. break;
  7062. }
  7063. }
  7064. if (!(parent instanceof AST_Call) || !has_annotation(parent, _NOINLINE)) {
  7065. const sub = self.flatten_object(self.property, compressor);
  7066. if (sub) return sub.optimize(compressor);
  7067. }
  7068. let ev = self.evaluate(compressor);
  7069. if (ev !== self) {
  7070. ev = make_node_from_constant(ev, self).optimize(compressor);
  7071. return best_of(compressor, ev, self);
  7072. }
  7073. if (self.optional && is_nullish(self.expression)) {
  7074. return make_node(AST_Undefined, self);
  7075. }
  7076. return self;
  7077. });
  7078. function literals_in_boolean_context(self, compressor) {
  7079. if (compressor.in_boolean_context()) {
  7080. return best_of(compressor, self, make_sequence(self, [
  7081. self,
  7082. make_node(AST_True, self)
  7083. ]).optimize(compressor));
  7084. }
  7085. return self;
  7086. }
  7087. function inline_array_like_spread(elements) {
  7088. for (var i = 0; i < elements.length; i++) {
  7089. var el = elements[i];
  7090. if (el instanceof AST_Expansion) {
  7091. var expr = el.expression;
  7092. if (
  7093. expr instanceof AST_Array
  7094. && !expr.elements.some(elm => elm instanceof AST_Hole)
  7095. ) {
  7096. elements.splice(i, 1, ...expr.elements);
  7097. // Step back one, as the element at i is now new.
  7098. i--;
  7099. }
  7100. // In array-like spread, spreading a non-iterable value is TypeError.
  7101. // We therefore can’t optimize anything else, unlike with object spread.
  7102. }
  7103. }
  7104. }
  7105. def_optimize(AST_Array, function(self, compressor) {
  7106. var optimized = literals_in_boolean_context(self, compressor);
  7107. if (optimized !== self) {
  7108. return optimized;
  7109. }
  7110. inline_array_like_spread(self.elements);
  7111. return self;
  7112. });
  7113. function inline_object_prop_spread(props) {
  7114. for (var i = 0; i < props.length; i++) {
  7115. var prop = props[i];
  7116. if (prop instanceof AST_Expansion) {
  7117. const expr = prop.expression;
  7118. if (
  7119. expr instanceof AST_Object
  7120. && expr.properties.every(prop => prop instanceof AST_ObjectKeyVal)
  7121. ) {
  7122. props.splice(i, 1, ...expr.properties);
  7123. // Step back one, as the property at i is now new.
  7124. i--;
  7125. } else if (expr instanceof AST_Constant
  7126. && !(expr instanceof AST_String)) {
  7127. // Unlike array-like spread, in object spread, spreading a
  7128. // non-iterable value silently does nothing; it is thus safe
  7129. // to remove. AST_String is the only iterable AST_Constant.
  7130. props.splice(i, 1);
  7131. }
  7132. }
  7133. }
  7134. }
  7135. def_optimize(AST_Object, function(self, compressor) {
  7136. var optimized = literals_in_boolean_context(self, compressor);
  7137. if (optimized !== self) {
  7138. return optimized;
  7139. }
  7140. inline_object_prop_spread(self.properties);
  7141. return self;
  7142. });
  7143. def_optimize(AST_RegExp, literals_in_boolean_context);
  7144. def_optimize(AST_Return, function(self, compressor) {
  7145. if (self.value && is_undefined(self.value, compressor)) {
  7146. self.value = null;
  7147. }
  7148. return self;
  7149. });
  7150. def_optimize(AST_Arrow, opt_AST_Lambda);
  7151. def_optimize(AST_Function, function(self, compressor) {
  7152. self = opt_AST_Lambda(self, compressor);
  7153. if (compressor.option("unsafe_arrows")
  7154. && compressor.option("ecma") >= 2015
  7155. && !self.name
  7156. && !self.is_generator
  7157. && !self.uses_arguments
  7158. && !self.pinned()) {
  7159. const uses_this = walk(self, node => {
  7160. if (node instanceof AST_This) return walk_abort;
  7161. });
  7162. if (!uses_this) return make_node(AST_Arrow, self, self).optimize(compressor);
  7163. }
  7164. return self;
  7165. });
  7166. def_optimize(AST_Class, function(self) {
  7167. // HACK to avoid compress failure.
  7168. // AST_Class is not really an AST_Scope/AST_Block as it lacks a body.
  7169. return self;
  7170. });
  7171. def_optimize(AST_Yield, function(self, compressor) {
  7172. if (self.expression && !self.is_star && is_undefined(self.expression, compressor)) {
  7173. self.expression = null;
  7174. }
  7175. return self;
  7176. });
  7177. def_optimize(AST_TemplateString, function(self, compressor) {
  7178. if (
  7179. !compressor.option("evaluate")
  7180. || compressor.parent() instanceof AST_PrefixedTemplateString
  7181. ) {
  7182. return self;
  7183. }
  7184. var segments = [];
  7185. for (var i = 0; i < self.segments.length; i++) {
  7186. var segment = self.segments[i];
  7187. if (segment instanceof AST_Node) {
  7188. var result = segment.evaluate(compressor);
  7189. // Evaluate to constant value
  7190. // Constant value shorter than ${segment}
  7191. if (result !== segment && (result + "").length <= segment.size() + "${}".length) {
  7192. // There should always be a previous and next segment if segment is a node
  7193. segments[segments.length - 1].value = segments[segments.length - 1].value + result + self.segments[++i].value;
  7194. continue;
  7195. }
  7196. // `before ${`innerBefore ${any} innerAfter`} after` => `before innerBefore ${any} innerAfter after`
  7197. // TODO:
  7198. // `before ${'test' + foo} after` => `before innerBefore ${any} innerAfter after`
  7199. // `before ${foo + 'test} after` => `before innerBefore ${any} innerAfter after`
  7200. if (segment instanceof AST_TemplateString) {
  7201. var inners = segment.segments;
  7202. segments[segments.length - 1].value += inners[0].value;
  7203. for (var j = 1; j < inners.length; j++) {
  7204. segment = inners[j];
  7205. segments.push(segment);
  7206. }
  7207. continue;
  7208. }
  7209. }
  7210. segments.push(segment);
  7211. }
  7212. self.segments = segments;
  7213. // `foo` => "foo"
  7214. if (segments.length == 1) {
  7215. return make_node(AST_String, self, segments[0]);
  7216. }
  7217. if (
  7218. segments.length === 3
  7219. && segments[1] instanceof AST_Node
  7220. && (
  7221. segments[1].is_string(compressor)
  7222. || segments[1].is_number(compressor)
  7223. || is_nullish(segments[1])
  7224. || compressor.option("unsafe")
  7225. )
  7226. ) {
  7227. // `foo${bar}` => "foo" + bar
  7228. if (segments[2].value === "") {
  7229. return make_node(AST_Binary, self, {
  7230. operator: "+",
  7231. left: make_node(AST_String, self, {
  7232. value: segments[0].value,
  7233. }),
  7234. right: segments[1],
  7235. });
  7236. }
  7237. // `${bar}baz` => bar + "baz"
  7238. if (segments[0].value === "") {
  7239. return make_node(AST_Binary, self, {
  7240. operator: "+",
  7241. left: segments[1],
  7242. right: make_node(AST_String, self, {
  7243. value: segments[2].value,
  7244. }),
  7245. });
  7246. }
  7247. }
  7248. return self;
  7249. });
  7250. def_optimize(AST_PrefixedTemplateString, function(self) {
  7251. return self;
  7252. });
  7253. // ["p"]:1 ---> p:1
  7254. // [42]:1 ---> 42:1
  7255. function lift_key(self, compressor) {
  7256. if (!compressor.option("computed_props")) return self;
  7257. // save a comparison in the typical case
  7258. if (!(self.key instanceof AST_Constant)) return self;
  7259. // allow certain acceptable props as not all AST_Constants are true constants
  7260. if (self.key instanceof AST_String || self.key instanceof AST_Number) {
  7261. if (self.key.value === "__proto__") return self;
  7262. if (self.key.value == "constructor"
  7263. && compressor.parent() instanceof AST_Class) return self;
  7264. if (self instanceof AST_ObjectKeyVal) {
  7265. self.key = self.key.value;
  7266. } else if (self instanceof AST_ClassProperty) {
  7267. self.key = make_node(AST_SymbolClassProperty, self.key, {
  7268. name: self.key.value
  7269. });
  7270. } else {
  7271. self.key = make_node(AST_SymbolMethod, self.key, {
  7272. name: self.key.value
  7273. });
  7274. }
  7275. }
  7276. return self;
  7277. }
  7278. def_optimize(AST_ObjectProperty, lift_key);
  7279. def_optimize(AST_ConciseMethod, function(self, compressor) {
  7280. lift_key(self, compressor);
  7281. // p(){return x;} ---> p:()=>x
  7282. if (compressor.option("arrows")
  7283. && compressor.parent() instanceof AST_Object
  7284. && !self.is_generator
  7285. && !self.value.uses_arguments
  7286. && !self.value.pinned()
  7287. && self.value.body.length == 1
  7288. && self.value.body[0] instanceof AST_Return
  7289. && self.value.body[0].value
  7290. && !self.value.contains_this()) {
  7291. var arrow = make_node(AST_Arrow, self.value, self.value);
  7292. arrow.async = self.async;
  7293. arrow.is_generator = self.is_generator;
  7294. return make_node(AST_ObjectKeyVal, self, {
  7295. key: self.key instanceof AST_SymbolMethod ? self.key.name : self.key,
  7296. value: arrow,
  7297. quote: self.quote,
  7298. });
  7299. }
  7300. return self;
  7301. });
  7302. def_optimize(AST_ObjectKeyVal, function(self, compressor) {
  7303. lift_key(self, compressor);
  7304. // p:function(){} ---> p(){}
  7305. // p:function*(){} ---> *p(){}
  7306. // p:async function(){} ---> async p(){}
  7307. // p:()=>{} ---> p(){}
  7308. // p:async()=>{} ---> async p(){}
  7309. var unsafe_methods = compressor.option("unsafe_methods");
  7310. if (unsafe_methods
  7311. && compressor.option("ecma") >= 2015
  7312. && (!(unsafe_methods instanceof RegExp) || unsafe_methods.test(self.key + ""))) {
  7313. var key = self.key;
  7314. var value = self.value;
  7315. var is_arrow_with_block = value instanceof AST_Arrow
  7316. && Array.isArray(value.body)
  7317. && !value.contains_this();
  7318. if ((is_arrow_with_block || value instanceof AST_Function) && !value.name) {
  7319. return make_node(AST_ConciseMethod, self, {
  7320. async: value.async,
  7321. is_generator: value.is_generator,
  7322. key: key instanceof AST_Node ? key : make_node(AST_SymbolMethod, self, {
  7323. name: key,
  7324. }),
  7325. value: make_node(AST_Accessor, value, value),
  7326. quote: self.quote,
  7327. });
  7328. }
  7329. }
  7330. return self;
  7331. });
  7332. def_optimize(AST_Destructuring, function(self, compressor) {
  7333. if (compressor.option("pure_getters") == true
  7334. && compressor.option("unused")
  7335. && !self.is_array
  7336. && Array.isArray(self.names)
  7337. && !is_destructuring_export_decl(compressor)
  7338. && !(self.names[self.names.length - 1] instanceof AST_Expansion)) {
  7339. var keep = [];
  7340. for (var i = 0; i < self.names.length; i++) {
  7341. var elem = self.names[i];
  7342. if (!(elem instanceof AST_ObjectKeyVal
  7343. && typeof elem.key == "string"
  7344. && elem.value instanceof AST_SymbolDeclaration
  7345. && !should_retain(compressor, elem.value.definition()))) {
  7346. keep.push(elem);
  7347. }
  7348. }
  7349. if (keep.length != self.names.length) {
  7350. self.names = keep;
  7351. }
  7352. }
  7353. return self;
  7354. function is_destructuring_export_decl(compressor) {
  7355. var ancestors = [/^VarDef$/, /^(Const|Let|Var)$/, /^Export$/];
  7356. for (var a = 0, p = 0, len = ancestors.length; a < len; p++) {
  7357. var parent = compressor.parent(p);
  7358. if (!parent) return false;
  7359. if (a === 0 && parent.TYPE == "Destructuring") continue;
  7360. if (!ancestors[a].test(parent.TYPE)) {
  7361. return false;
  7362. }
  7363. a++;
  7364. }
  7365. return true;
  7366. }
  7367. function should_retain(compressor, def) {
  7368. if (def.references.length) return true;
  7369. if (!def.global) return false;
  7370. if (compressor.toplevel.vars) {
  7371. if (compressor.top_retain) {
  7372. return compressor.top_retain(def);
  7373. }
  7374. return false;
  7375. }
  7376. return true;
  7377. }
  7378. });
  7379. export {
  7380. Compressor,
  7381. };