compress.js 264 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306
  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. function Compressor(options, false_by_default) {
  35. if (!(this instanceof Compressor))
  36. return new Compressor(options, false_by_default);
  37. TreeTransformer.call(this, this.before, this.after);
  38. this.options = defaults(options, {
  39. arrows : !false_by_default,
  40. booleans : !false_by_default,
  41. collapse_vars : !false_by_default,
  42. comparisons : !false_by_default,
  43. computed_props: !false_by_default,
  44. conditionals : !false_by_default,
  45. dead_code : !false_by_default,
  46. drop_console : false,
  47. drop_debugger : !false_by_default,
  48. ecma : 5,
  49. evaluate : !false_by_default,
  50. expression : false,
  51. global_defs : {},
  52. hoist_funs : false,
  53. hoist_props : !false_by_default,
  54. hoist_vars : false,
  55. ie8 : false,
  56. if_return : !false_by_default,
  57. inline : !false_by_default,
  58. join_vars : !false_by_default,
  59. keep_classnames: false,
  60. keep_fargs : true,
  61. keep_fnames : false,
  62. keep_infinity : false,
  63. loops : !false_by_default,
  64. negate_iife : !false_by_default,
  65. passes : 1,
  66. properties : !false_by_default,
  67. pure_getters : !false_by_default && "strict",
  68. pure_funcs : null,
  69. reduce_funcs : !false_by_default,
  70. reduce_vars : !false_by_default,
  71. sequences : !false_by_default,
  72. side_effects : !false_by_default,
  73. switches : !false_by_default,
  74. top_retain : null,
  75. toplevel : !!(options && options["top_retain"]),
  76. typeofs : !false_by_default,
  77. unsafe : false,
  78. unsafe_arrows : false,
  79. unsafe_comps : false,
  80. unsafe_Function: false,
  81. unsafe_math : false,
  82. unsafe_methods: false,
  83. unsafe_proto : false,
  84. unsafe_regexp : false,
  85. unsafe_undefined: false,
  86. unused : !false_by_default,
  87. warnings : false,
  88. }, true);
  89. var global_defs = this.options["global_defs"];
  90. if (typeof global_defs == "object") for (var key in global_defs) {
  91. if (/^@/.test(key) && HOP(global_defs, key)) {
  92. global_defs[key.slice(1)] = parse(global_defs[key], {
  93. expression: true
  94. });
  95. }
  96. }
  97. if (this.options["inline"] === true) this.options["inline"] = 3;
  98. var pure_funcs = this.options["pure_funcs"];
  99. if (typeof pure_funcs == "function") {
  100. this.pure_funcs = pure_funcs;
  101. } else {
  102. this.pure_funcs = pure_funcs ? function(node) {
  103. return pure_funcs.indexOf(node.expression.print_to_string()) < 0;
  104. } : return_true;
  105. }
  106. var top_retain = this.options["top_retain"];
  107. if (top_retain instanceof RegExp) {
  108. this.top_retain = function(def) {
  109. return top_retain.test(def.name);
  110. };
  111. } else if (typeof top_retain == "function") {
  112. this.top_retain = top_retain;
  113. } else if (top_retain) {
  114. if (typeof top_retain == "string") {
  115. top_retain = top_retain.split(/,/);
  116. }
  117. this.top_retain = function(def) {
  118. return top_retain.indexOf(def.name) >= 0;
  119. };
  120. }
  121. var toplevel = this.options["toplevel"];
  122. this.toplevel = typeof toplevel == "string" ? {
  123. funcs: /funcs/.test(toplevel),
  124. vars: /vars/.test(toplevel)
  125. } : {
  126. funcs: toplevel,
  127. vars: toplevel
  128. };
  129. var sequences = this.options["sequences"];
  130. this.sequences_limit = sequences == 1 ? 800 : sequences | 0;
  131. this.warnings_produced = {};
  132. };
  133. Compressor.prototype = new TreeTransformer;
  134. merge(Compressor.prototype, {
  135. option: function(key) { return this.options[key] },
  136. exposed: function(def) {
  137. if (def.export) return true;
  138. if (def.global) for (var i = 0, len = def.orig.length; i < len; i++)
  139. if (!this.toplevel[def.orig[i] instanceof AST_SymbolDefun ? "funcs" : "vars"])
  140. return true;
  141. return false;
  142. },
  143. in_boolean_context: function() {
  144. if (!this.option("booleans")) return false;
  145. var self = this.self();
  146. for (var i = 0, p; p = this.parent(i); i++) {
  147. if (p instanceof AST_SimpleStatement
  148. || p instanceof AST_Conditional && p.condition === self
  149. || p instanceof AST_DWLoop && p.condition === self
  150. || p instanceof AST_For && p.condition === self
  151. || p instanceof AST_If && p.condition === self
  152. || p instanceof AST_UnaryPrefix && p.operator == "!" && p.expression === self) {
  153. return true;
  154. }
  155. if (p instanceof AST_Binary && (p.operator == "&&" || p.operator == "||")
  156. || p instanceof AST_Conditional
  157. || p.tail_node() === self) {
  158. self = p;
  159. } else {
  160. return false;
  161. }
  162. }
  163. },
  164. compress: function(node) {
  165. if (this.option("expression")) {
  166. node.process_expression(true);
  167. }
  168. var passes = +this.options.passes || 1;
  169. var min_count = 1 / 0;
  170. var stopping = false;
  171. var mangle = { ie8: this.option("ie8") };
  172. for (var pass = 0; pass < passes; pass++) {
  173. node.figure_out_scope(mangle);
  174. if (pass > 0 || this.option("reduce_vars"))
  175. node.reset_opt_flags(this);
  176. node = node.transform(this);
  177. if (passes > 1) {
  178. var count = 0;
  179. node.walk(new TreeWalker(function() {
  180. count++;
  181. }));
  182. this.info("pass " + pass + ": last_count: " + min_count + ", count: " + count);
  183. if (count < min_count) {
  184. min_count = count;
  185. stopping = false;
  186. } else if (stopping) {
  187. break;
  188. } else {
  189. stopping = true;
  190. }
  191. }
  192. }
  193. if (this.option("expression")) {
  194. node.process_expression(false);
  195. }
  196. return node;
  197. },
  198. info: function() {
  199. if (this.options.warnings == "verbose") {
  200. AST_Node.warn.apply(AST_Node, arguments);
  201. }
  202. },
  203. warn: function(text, props) {
  204. if (this.options.warnings) {
  205. // only emit unique warnings
  206. var message = string_template(text, props);
  207. if (!(message in this.warnings_produced)) {
  208. this.warnings_produced[message] = true;
  209. AST_Node.warn.apply(AST_Node, arguments);
  210. }
  211. }
  212. },
  213. clear_warnings: function() {
  214. this.warnings_produced = {};
  215. },
  216. before: function(node, descend, in_list) {
  217. if (node._squeezed) return node;
  218. var was_scope = false;
  219. if (node instanceof AST_Scope) {
  220. node = node.hoist_properties(this);
  221. node = node.hoist_declarations(this);
  222. was_scope = true;
  223. }
  224. // Before https://github.com/mishoo/UglifyJS2/pull/1602 AST_Node.optimize()
  225. // would call AST_Node.transform() if a different instance of AST_Node is
  226. // produced after OPT().
  227. // This corrupts TreeWalker.stack, which cause AST look-ups to malfunction.
  228. // Migrate and defer all children's AST_Node.transform() to below, which
  229. // will now happen after this parent AST_Node has been properly substituted
  230. // thus gives a consistent AST snapshot.
  231. descend(node, this);
  232. // Existing code relies on how AST_Node.optimize() worked, and omitting the
  233. // following replacement call would result in degraded efficiency of both
  234. // output and performance.
  235. descend(node, this);
  236. var opt = node.optimize(this);
  237. if (was_scope && opt instanceof AST_Scope) {
  238. opt.drop_unused(this);
  239. descend(opt, this);
  240. }
  241. if (opt === node) opt._squeezed = true;
  242. return opt;
  243. }
  244. });
  245. (function(){
  246. function OPT(node, optimizer) {
  247. node.DEFMETHOD("optimize", function(compressor){
  248. var self = this;
  249. if (self._optimized) return self;
  250. if (compressor.has_directive("use asm")) return self;
  251. var opt = optimizer(self, compressor);
  252. opt._optimized = true;
  253. return opt;
  254. });
  255. };
  256. OPT(AST_Node, function(self, compressor){
  257. return self;
  258. });
  259. AST_Node.DEFMETHOD("equivalent_to", function(node){
  260. return this.TYPE == node.TYPE && this.print_to_string() == node.print_to_string();
  261. });
  262. AST_Scope.DEFMETHOD("process_expression", function(insert, compressor) {
  263. var self = this;
  264. var tt = new TreeTransformer(function(node) {
  265. if (insert && node instanceof AST_SimpleStatement) {
  266. return make_node(AST_Return, node, {
  267. value: node.body
  268. });
  269. }
  270. if (!insert && node instanceof AST_Return) {
  271. if (compressor) {
  272. var value = node.value && node.value.drop_side_effect_free(compressor, true);
  273. return value ? make_node(AST_SimpleStatement, node, {
  274. body: value
  275. }) : make_node(AST_EmptyStatement, node);
  276. }
  277. return make_node(AST_SimpleStatement, node, {
  278. body: node.value || make_node(AST_UnaryPrefix, node, {
  279. operator: "void",
  280. expression: make_node(AST_Number, node, {
  281. value: 0
  282. })
  283. })
  284. });
  285. }
  286. if (node instanceof AST_Class || node instanceof AST_Lambda && node !== self) {
  287. return node;
  288. }
  289. if (node instanceof AST_Block) {
  290. var index = node.body.length - 1;
  291. if (index >= 0) {
  292. node.body[index] = node.body[index].transform(tt);
  293. }
  294. } else if (node instanceof AST_If) {
  295. node.body = node.body.transform(tt);
  296. if (node.alternative) {
  297. node.alternative = node.alternative.transform(tt);
  298. }
  299. } else if (node instanceof AST_With) {
  300. node.body = node.body.transform(tt);
  301. }
  302. return node;
  303. });
  304. self.transform(tt);
  305. });
  306. (function(def){
  307. def(AST_Node, noop);
  308. function reset_def(compressor, def) {
  309. def.assignments = 0;
  310. def.direct_access = false;
  311. def.escaped = false;
  312. if (def.scope.uses_eval || def.scope.uses_with) {
  313. def.fixed = false;
  314. } else if (def.orig[0] instanceof AST_SymbolConst || !compressor.exposed(def)) {
  315. def.fixed = def.init;
  316. } else {
  317. def.fixed = false;
  318. }
  319. def.recursive_refs = 0;
  320. def.references = [];
  321. def.should_replace = undefined;
  322. def.single_use = undefined;
  323. }
  324. function reset_variables(tw, compressor, node) {
  325. node.variables.each(function(def) {
  326. reset_def(compressor, def);
  327. if (def.fixed === null) {
  328. def.safe_ids = tw.safe_ids;
  329. mark(tw, def, true);
  330. } else if (def.fixed) {
  331. tw.loop_ids[def.id] = tw.in_loop;
  332. mark(tw, def, true);
  333. }
  334. });
  335. }
  336. function reset_block_variables(compressor, node) {
  337. if (node.block_scope) node.block_scope.variables.each(function(def) {
  338. reset_def(compressor, def);
  339. });
  340. }
  341. function push(tw) {
  342. tw.safe_ids = Object.create(tw.safe_ids);
  343. }
  344. function pop(tw) {
  345. tw.safe_ids = Object.getPrototypeOf(tw.safe_ids);
  346. }
  347. function mark(tw, def, safe) {
  348. tw.safe_ids[def.id] = safe;
  349. }
  350. function safe_to_read(tw, def) {
  351. if (tw.safe_ids[def.id]) {
  352. if (def.fixed == null) {
  353. var orig = def.orig[0];
  354. if (orig instanceof AST_SymbolFunarg || orig.name == "arguments") return false;
  355. def.fixed = make_node(AST_Undefined, orig);
  356. }
  357. return true;
  358. }
  359. return def.fixed instanceof AST_Defun;
  360. }
  361. function safe_to_assign(tw, def, value) {
  362. if (def.fixed === undefined) return true;
  363. if (def.fixed === null && def.safe_ids) {
  364. def.safe_ids[def.id] = false;
  365. delete def.safe_ids;
  366. return true;
  367. }
  368. if (!HOP(tw.safe_ids, def.id)) return false;
  369. if (!safe_to_read(tw, def)) return false;
  370. if (def.fixed === false) return false;
  371. if (def.fixed != null && (!value || def.references.length > def.assignments)) return false;
  372. return all(def.orig, function(sym) {
  373. return !(sym instanceof AST_SymbolConst
  374. || sym instanceof AST_SymbolDefun
  375. || sym instanceof AST_SymbolLambda);
  376. });
  377. }
  378. function ref_once(tw, compressor, def) {
  379. return compressor.option("unused")
  380. && !def.scope.uses_eval
  381. && !def.scope.uses_with
  382. && def.references.length - def.recursive_refs == 1
  383. && tw.loop_ids[def.id] === tw.in_loop;
  384. }
  385. function is_immutable(value) {
  386. if (!value) return false;
  387. return value.is_constant()
  388. || value instanceof AST_Lambda
  389. || value instanceof AST_This;
  390. }
  391. function read_property(obj, key) {
  392. key = get_value(key);
  393. if (key instanceof AST_Node) return;
  394. var value;
  395. if (obj instanceof AST_Array) {
  396. var elements = obj.elements;
  397. if (key == "length") return make_node_from_constant(elements.length, obj);
  398. if (typeof key == "number" && key in elements) value = elements[key];
  399. } else if (obj instanceof AST_Object) {
  400. key = "" + key;
  401. var props = obj.properties;
  402. for (var i = props.length; --i >= 0;) {
  403. var prop = props[i];
  404. if (!(prop instanceof AST_ObjectKeyVal)) return;
  405. if (!value && props[i].key === key) value = props[i].value;
  406. }
  407. }
  408. return value instanceof AST_SymbolRef && value.fixed_value() || value;
  409. }
  410. function is_modified(tw, node, value, level, immutable) {
  411. var parent = tw.parent(level);
  412. if (is_lhs(node, parent)
  413. || !immutable
  414. && parent instanceof AST_Call
  415. && parent.expression === node
  416. && !(value instanceof AST_Arrow)
  417. && !(value instanceof AST_Class)
  418. && (!(value instanceof AST_Function)
  419. || !(parent instanceof AST_New) && value.contains_this())) {
  420. return true;
  421. } else if (parent instanceof AST_Array) {
  422. return is_modified(tw, parent, parent, level + 1);
  423. } else if (parent instanceof AST_ObjectKeyVal && node === parent.value) {
  424. var obj = tw.parent(level + 1);
  425. return is_modified(tw, obj, obj, level + 2);
  426. } else if (parent instanceof AST_PropAccess && parent.expression === node) {
  427. return !immutable && is_modified(tw, parent, read_property(value, parent.property), level + 1);
  428. }
  429. }
  430. function mark_escaped(tw, d, scope, node, value, level, depth) {
  431. var parent = tw.parent(level);
  432. if (value) {
  433. if (value.is_constant()) return;
  434. if (value instanceof AST_ClassExpression) return;
  435. }
  436. if (parent instanceof AST_Assign && parent.operator == "=" && node === parent.right
  437. || parent instanceof AST_Call && node !== parent.expression
  438. || parent instanceof AST_Exit && node === parent.value && node.scope !== d.scope
  439. || parent instanceof AST_VarDef && node === parent.value
  440. || parent instanceof AST_Yield && node === parent.value && node.scope !== d.scope) {
  441. if (depth > 1 && !(value && value.is_constant_expression(scope))) depth = 1;
  442. if (!d.escaped || d.escaped > depth) d.escaped = depth;
  443. return;
  444. } else if (parent instanceof AST_Array
  445. || parent instanceof AST_Await
  446. || parent instanceof AST_Binary && lazy_op(parent.operator)
  447. || parent instanceof AST_Conditional && node !== parent.condition
  448. || parent instanceof AST_Expansion
  449. || parent instanceof AST_Sequence && node === parent.tail_node()) {
  450. mark_escaped(tw, d, scope, parent, parent, level + 1, depth);
  451. } else if (parent instanceof AST_ObjectKeyVal && node === parent.value) {
  452. var obj = tw.parent(level + 1);
  453. mark_escaped(tw, d, scope, obj, obj, level + 2, depth);
  454. } else if (parent instanceof AST_PropAccess && node === parent.expression) {
  455. value = read_property(value, parent.property);
  456. mark_escaped(tw, d, scope, parent, value, level + 1, depth + 1);
  457. if (value) return;
  458. }
  459. if (level == 0) d.direct_access = true;
  460. }
  461. var suppressor = new TreeWalker(function(node) {
  462. if (!(node instanceof AST_Symbol)) return;
  463. var d = node.definition();
  464. if (!d) return;
  465. if (node instanceof AST_SymbolRef) d.references.push(node);
  466. d.fixed = false;
  467. });
  468. def(AST_Accessor, function(tw, descend, compressor) {
  469. push(tw);
  470. reset_variables(tw, compressor, this);
  471. descend();
  472. pop(tw);
  473. return true;
  474. });
  475. def(AST_Arrow, mark_func_expr);
  476. def(AST_Assign, function(tw) {
  477. var node = this;
  478. if (node.left instanceof AST_Destructuring) {
  479. node.left.walk(suppressor);
  480. return;
  481. }
  482. if (node.operator != "=" || !(node.left instanceof AST_SymbolRef)) return;
  483. var d = node.left.definition();
  484. if (safe_to_assign(tw, d, node.right)) {
  485. d.references.push(node.left);
  486. d.assignments++;
  487. d.fixed = function() {
  488. return node.right;
  489. };
  490. mark(tw, d, false);
  491. node.right.walk(tw);
  492. mark(tw, d, true);
  493. return true;
  494. }
  495. });
  496. def(AST_Binary, function(tw) {
  497. if (!lazy_op(this.operator)) return;
  498. this.left.walk(tw);
  499. push(tw);
  500. this.right.walk(tw);
  501. pop(tw);
  502. return true;
  503. });
  504. def(AST_Block, function(tw, descend, compressor) {
  505. reset_block_variables(compressor, this);
  506. });
  507. def(AST_ClassExpression, function(tw, descend) {
  508. this.inlined = false;
  509. push(tw);
  510. descend();
  511. pop(tw);
  512. return true;
  513. })
  514. def(AST_Conditional, function(tw) {
  515. this.condition.walk(tw);
  516. push(tw);
  517. this.consequent.walk(tw);
  518. pop(tw);
  519. push(tw);
  520. this.alternative.walk(tw);
  521. pop(tw);
  522. return true;
  523. });
  524. function mark_def_node(tw, descend, compressor) {
  525. this.inlined = false;
  526. var save_ids = tw.safe_ids;
  527. tw.safe_ids = Object.create(null);
  528. reset_variables(tw, compressor, this);
  529. descend();
  530. tw.safe_ids = save_ids;
  531. return true;
  532. }
  533. def(AST_DefClass, mark_def_node);
  534. def(AST_Defun, mark_def_node);
  535. def(AST_Do, function(tw, descend, compressor) {
  536. reset_block_variables(compressor, this);
  537. var saved_loop = tw.in_loop;
  538. tw.in_loop = this;
  539. push(tw);
  540. this.body.walk(tw);
  541. this.condition.walk(tw);
  542. pop(tw);
  543. tw.in_loop = saved_loop;
  544. return true;
  545. });
  546. def(AST_For, function(tw, descend, compressor) {
  547. reset_block_variables(compressor, this);
  548. if (this.init) this.init.walk(tw);
  549. var saved_loop = tw.in_loop;
  550. tw.in_loop = this;
  551. if (this.condition) {
  552. push(tw);
  553. this.condition.walk(tw);
  554. pop(tw);
  555. }
  556. push(tw);
  557. this.body.walk(tw);
  558. pop(tw);
  559. if (this.step) {
  560. push(tw);
  561. this.step.walk(tw);
  562. pop(tw);
  563. }
  564. tw.in_loop = saved_loop;
  565. return true;
  566. });
  567. def(AST_ForIn, function(tw, descend, compressor) {
  568. reset_block_variables(compressor, this);
  569. this.init.walk(suppressor);
  570. this.object.walk(tw);
  571. var saved_loop = tw.in_loop;
  572. tw.in_loop = this;
  573. push(tw);
  574. this.body.walk(tw);
  575. pop(tw);
  576. tw.in_loop = saved_loop;
  577. return true;
  578. });
  579. function mark_func_expr(tw, descend, compressor) {
  580. var node = this;
  581. node.inlined = false;
  582. push(tw);
  583. reset_variables(tw, compressor, node);
  584. var iife;
  585. if (!node.name
  586. && (iife = tw.parent()) instanceof AST_Call
  587. && iife.expression === node) {
  588. // Virtually turn IIFE parameters into variable definitions:
  589. // (function(a,b) {...})(c,d) => (function() {var a=c,b=d; ...})()
  590. // So existing transformation rules can work on them.
  591. node.argnames.forEach(function(arg, i) {
  592. if (!arg.definition) return;
  593. var d = arg.definition();
  594. if (!node.uses_arguments && d.fixed === undefined) {
  595. d.fixed = function() {
  596. return iife.args[i] || make_node(AST_Undefined, iife);
  597. };
  598. tw.loop_ids[d.id] = tw.in_loop;
  599. mark(tw, d, true);
  600. } else {
  601. d.fixed = false;
  602. }
  603. });
  604. }
  605. descend();
  606. pop(tw);
  607. return true;
  608. }
  609. def(AST_Function, mark_func_expr);
  610. def(AST_If, function(tw) {
  611. this.condition.walk(tw);
  612. push(tw);
  613. this.body.walk(tw);
  614. pop(tw);
  615. if (this.alternative) {
  616. push(tw);
  617. this.alternative.walk(tw);
  618. pop(tw);
  619. }
  620. return true;
  621. });
  622. def(AST_LabeledStatement, function(tw) {
  623. push(tw);
  624. this.body.walk(tw);
  625. pop(tw);
  626. return true;
  627. });
  628. def(AST_SwitchBranch, function(tw, descend) {
  629. push(tw);
  630. descend();
  631. pop(tw);
  632. return true;
  633. });
  634. def(AST_SymbolCatch, function() {
  635. this.definition().fixed = false;
  636. });
  637. def(AST_SymbolRef, function(tw, descend, compressor) {
  638. var d = this.definition();
  639. d.references.push(this);
  640. if (d.references.length == 1
  641. && !d.fixed
  642. && d.orig[0] instanceof AST_SymbolDefun) {
  643. tw.loop_ids[d.id] = tw.in_loop;
  644. }
  645. var value;
  646. if (d.fixed === undefined || !safe_to_read(tw, d) || d.single_use == "m") {
  647. d.fixed = false;
  648. } else if (d.fixed) {
  649. value = this.fixed_value();
  650. if (value instanceof AST_Lambda && recursive_ref(tw, d)) {
  651. d.recursive_refs++;
  652. } else if (value && !compressor.exposed(d) && ref_once(tw, compressor, d)) {
  653. d.single_use = value instanceof AST_Lambda
  654. || value instanceof AST_Class
  655. || d.scope === this.scope && value.is_constant_expression();
  656. } else {
  657. d.single_use = false;
  658. }
  659. if (is_modified(tw, this, value, 0, is_immutable(value))) {
  660. if (d.single_use) {
  661. d.single_use = "m";
  662. } else {
  663. d.fixed = false;
  664. }
  665. }
  666. }
  667. mark_escaped(tw, d, this.scope, this, value, 0, 1);
  668. });
  669. def(AST_Toplevel, function(tw, descend, compressor) {
  670. this.globals.each(function(def) {
  671. reset_def(compressor, def);
  672. });
  673. reset_variables(tw, compressor, this);
  674. });
  675. def(AST_Try, function(tw, descend, compressor) {
  676. reset_block_variables(compressor, this);
  677. push(tw);
  678. walk_body(this, tw);
  679. pop(tw);
  680. if (this.bcatch) {
  681. push(tw);
  682. this.bcatch.walk(tw);
  683. pop(tw);
  684. }
  685. if (this.bfinally) this.bfinally.walk(tw);
  686. return true;
  687. });
  688. def(AST_VarDef, function(tw, descend) {
  689. var node = this;
  690. if (node.name instanceof AST_Destructuring) {
  691. node.name.walk(suppressor);
  692. return;
  693. }
  694. var d = node.name.definition();
  695. if (safe_to_assign(tw, d, node.value)) {
  696. if (node.value) {
  697. d.fixed = function() {
  698. return node.value;
  699. };
  700. tw.loop_ids[d.id] = tw.in_loop;
  701. mark(tw, d, false);
  702. descend();
  703. }
  704. mark(tw, d, true);
  705. return true;
  706. } else if (node.value) {
  707. d.fixed = false;
  708. }
  709. });
  710. def(AST_While, function(tw, descend, compressor) {
  711. reset_block_variables(compressor, this);
  712. var saved_loop = tw.in_loop;
  713. tw.in_loop = this;
  714. push(tw);
  715. this.condition.walk(tw);
  716. this.body.walk(tw);
  717. pop(tw);
  718. tw.in_loop = saved_loop;
  719. return true;
  720. });
  721. })(function(node, func){
  722. node.DEFMETHOD("reduce_vars", func);
  723. });
  724. AST_Toplevel.DEFMETHOD("reset_opt_flags", function(compressor) {
  725. var reduce_vars = compressor.option("reduce_vars");
  726. var tw = new TreeWalker(function(node, descend) {
  727. node._squeezed = false;
  728. node._optimized = false;
  729. if (reduce_vars) return node.reduce_vars(tw, descend, compressor);
  730. });
  731. // Stack of look-up tables to keep track of whether a `SymbolDef` has been
  732. // properly assigned before use:
  733. // - `push()` & `pop()` when visiting conditional branches
  734. // - backup & restore via `save_ids` when visiting out-of-order sections
  735. tw.safe_ids = Object.create(null);
  736. tw.in_loop = null;
  737. tw.loop_ids = Object.create(null);
  738. this.walk(tw);
  739. });
  740. AST_Symbol.DEFMETHOD("fixed_value", function() {
  741. var fixed = this.definition().fixed;
  742. if (!fixed || fixed instanceof AST_Node) return fixed;
  743. return fixed();
  744. });
  745. AST_SymbolRef.DEFMETHOD("is_immutable", function() {
  746. var orig = this.definition().orig;
  747. return orig.length == 1 && orig[0] instanceof AST_SymbolLambda;
  748. });
  749. function is_func_expr(node) {
  750. return node instanceof AST_Arrow || node instanceof AST_Function;
  751. }
  752. function is_lhs_read_only(lhs) {
  753. if (lhs instanceof AST_This) return true;
  754. if (lhs instanceof AST_SymbolRef) return lhs.definition().orig[0] instanceof AST_SymbolLambda;
  755. if (lhs instanceof AST_PropAccess) {
  756. lhs = lhs.expression;
  757. if (lhs instanceof AST_SymbolRef) {
  758. if (lhs.is_immutable()) return false;
  759. lhs = lhs.fixed_value();
  760. }
  761. if (!lhs) return true;
  762. if (lhs instanceof AST_RegExp) return false;
  763. if (lhs instanceof AST_Constant) return true;
  764. return is_lhs_read_only(lhs);
  765. }
  766. return false;
  767. }
  768. function is_ref_of(ref, type) {
  769. if (!(ref instanceof AST_SymbolRef)) return false;
  770. var orig = ref.definition().orig;
  771. for (var i = orig.length; --i >= 0;) {
  772. if (orig[i] instanceof type) return true;
  773. }
  774. }
  775. function find_variable(compressor, name) {
  776. var scope, i = 0;
  777. while (scope = compressor.parent(i++)) {
  778. if (scope instanceof AST_Scope) break;
  779. if (scope instanceof AST_Catch) {
  780. scope = scope.argname.definition().scope;
  781. break;
  782. }
  783. }
  784. return scope.find_variable(name);
  785. }
  786. function make_node(ctor, orig, props) {
  787. if (!props) props = {};
  788. if (orig) {
  789. if (!props.start) props.start = orig.start;
  790. if (!props.end) props.end = orig.end;
  791. }
  792. return new ctor(props);
  793. };
  794. function make_sequence(orig, expressions) {
  795. if (expressions.length == 1) return expressions[0];
  796. return make_node(AST_Sequence, orig, {
  797. expressions: expressions.reduce(merge_sequence, [])
  798. });
  799. }
  800. function make_node_from_constant(val, orig) {
  801. switch (typeof val) {
  802. case "string":
  803. return make_node(AST_String, orig, {
  804. value: val
  805. });
  806. case "number":
  807. if (isNaN(val)) return make_node(AST_NaN, orig);
  808. if (isFinite(val)) {
  809. return 1 / val < 0 ? make_node(AST_UnaryPrefix, orig, {
  810. operator: "-",
  811. expression: make_node(AST_Number, orig, { value: -val })
  812. }) : make_node(AST_Number, orig, { value: val });
  813. }
  814. return val < 0 ? make_node(AST_UnaryPrefix, orig, {
  815. operator: "-",
  816. expression: make_node(AST_Infinity, orig)
  817. }) : make_node(AST_Infinity, orig);
  818. case "boolean":
  819. return make_node(val ? AST_True : AST_False, orig);
  820. case "undefined":
  821. return make_node(AST_Undefined, orig);
  822. default:
  823. if (val === null) {
  824. return make_node(AST_Null, orig, { value: null });
  825. }
  826. if (val instanceof RegExp) {
  827. return make_node(AST_RegExp, orig, { value: val });
  828. }
  829. throw new Error(string_template("Can't handle constant of type: {type}", {
  830. type: typeof val
  831. }));
  832. }
  833. };
  834. // we shouldn't compress (1,func)(something) to
  835. // func(something) because that changes the meaning of
  836. // the func (becomes lexical instead of global).
  837. function maintain_this_binding(parent, orig, val) {
  838. if (parent instanceof AST_UnaryPrefix && parent.operator == "delete"
  839. || parent instanceof AST_Call && parent.expression === orig
  840. && (val instanceof AST_PropAccess || val instanceof AST_SymbolRef && val.name == "eval")) {
  841. return make_sequence(orig, [ make_node(AST_Number, orig, { value: 0 }), val ]);
  842. }
  843. return val;
  844. }
  845. function merge_sequence(array, node) {
  846. if (node instanceof AST_Sequence) {
  847. array.push.apply(array, node.expressions);
  848. } else {
  849. array.push(node);
  850. }
  851. return array;
  852. }
  853. function as_statement_array(thing) {
  854. if (thing === null) return [];
  855. if (thing instanceof AST_BlockStatement) return thing.body;
  856. if (thing instanceof AST_EmptyStatement) return [];
  857. if (thing instanceof AST_Statement) return [ thing ];
  858. throw new Error("Can't convert thing to statement array");
  859. };
  860. function is_empty(thing) {
  861. if (thing === null) return true;
  862. if (thing instanceof AST_EmptyStatement) return true;
  863. if (thing instanceof AST_BlockStatement) return thing.body.length == 0;
  864. return false;
  865. };
  866. function can_be_evicted_from_block(node) {
  867. return !(
  868. node instanceof AST_DefClass ||
  869. node instanceof AST_Defun ||
  870. node instanceof AST_Let ||
  871. node instanceof AST_Const ||
  872. node instanceof AST_Export ||
  873. node instanceof AST_Import
  874. );
  875. }
  876. function loop_body(x) {
  877. if (x instanceof AST_IterationStatement) {
  878. return x.body instanceof AST_BlockStatement ? x.body : x;
  879. }
  880. return x;
  881. };
  882. function is_iife_call(node) {
  883. if (node.TYPE != "Call") return false;
  884. return node.expression instanceof AST_Function || is_iife_call(node.expression);
  885. }
  886. function is_undeclared_ref(node) {
  887. return node instanceof AST_SymbolRef && node.definition().undeclared;
  888. }
  889. 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");
  890. AST_SymbolRef.DEFMETHOD("is_declared", function(compressor) {
  891. return !this.definition().undeclared
  892. || compressor.option("unsafe") && global_names(this.name);
  893. });
  894. var identifier_atom = makePredicate("Infinity NaN undefined");
  895. function is_identifier_atom(node) {
  896. return node instanceof AST_Infinity
  897. || node instanceof AST_NaN
  898. || node instanceof AST_Undefined;
  899. }
  900. function tighten_body(statements, compressor) {
  901. var scope = compressor.find_parent(AST_Scope).get_defun_scope();
  902. var CHANGED, max_iter = 10;
  903. do {
  904. CHANGED = false;
  905. eliminate_spurious_blocks(statements);
  906. if (compressor.option("dead_code")) {
  907. eliminate_dead_code(statements, compressor);
  908. }
  909. if (compressor.option("if_return")) {
  910. handle_if_return(statements, compressor);
  911. }
  912. if (compressor.sequences_limit > 0) {
  913. sequencesize(statements, compressor);
  914. sequencesize_2(statements, compressor);
  915. }
  916. if (compressor.option("join_vars")) {
  917. join_consecutive_vars(statements);
  918. }
  919. if (compressor.option("collapse_vars")) {
  920. collapse(statements, compressor);
  921. }
  922. } while (CHANGED && max_iter-- > 0);
  923. // Search from right to left for assignment-like expressions:
  924. // - `var a = x;`
  925. // - `a = x;`
  926. // - `++a`
  927. // For each candidate, scan from left to right for first usage, then try
  928. // to fold assignment into the site for compression.
  929. // Will not attempt to collapse assignments into or past code blocks
  930. // which are not sequentially executed, e.g. loops and conditionals.
  931. function collapse(statements, compressor) {
  932. if (scope.uses_eval || scope.uses_with) return statements;
  933. var args;
  934. var candidates = [];
  935. var in_try = compressor.self() instanceof AST_Try;
  936. var stat_index = statements.length;
  937. var scanner = new TreeTransformer(function(node, descend) {
  938. if (abort) return node;
  939. // Scan case expressions first in a switch statement
  940. if (node instanceof AST_Switch) {
  941. if (!hit) {
  942. if (node !== hit_stack[hit_index]) return node;
  943. hit_index++;
  944. }
  945. node.expression = node.expression.transform(scanner);
  946. for (var i = 0, len = node.body.length; !abort && i < len; i++) {
  947. var branch = node.body[i];
  948. if (branch instanceof AST_Case) {
  949. if (!hit) {
  950. if (branch !== hit_stack[hit_index]) continue;
  951. hit_index++;
  952. }
  953. branch.expression = branch.expression.transform(scanner);
  954. if (side_effects || !replace_all) break;
  955. }
  956. }
  957. abort = true;
  958. return node;
  959. }
  960. // Skip nodes before `candidate` as quickly as possible
  961. if (!hit) {
  962. if (node !== hit_stack[hit_index]) return node;
  963. hit_index++;
  964. if (hit_index < hit_stack.length) return;
  965. hit = true;
  966. stop_after = find_stop(node, 0);
  967. if (stop_after === node) abort = true;
  968. return node;
  969. }
  970. // Stop immediately if these node types are encountered
  971. var parent = scanner.parent();
  972. if (node instanceof AST_Assign && node.operator != "=" && lhs.equivalent_to(node.left)
  973. || node instanceof AST_Await
  974. || node instanceof AST_Call && lhs instanceof AST_PropAccess && lhs.equivalent_to(node.expression)
  975. || node instanceof AST_Debugger
  976. || node instanceof AST_Destructuring
  977. || node instanceof AST_IterationStatement && !(node instanceof AST_For)
  978. || node instanceof AST_Try
  979. || node instanceof AST_With
  980. || parent instanceof AST_For && node !== parent.init
  981. || (side_effects || !replace_all)
  982. && (node instanceof AST_SymbolRef && !node.is_declared(compressor))) {
  983. abort = true;
  984. return node;
  985. }
  986. // Replace variable with assignment when found
  987. if (can_replace
  988. && !(node instanceof AST_SymbolDeclaration)
  989. && lhs.equivalent_to(node)) {
  990. if (is_lhs(node, parent)) {
  991. if (value_def) replaced++;
  992. return node;
  993. }
  994. CHANGED = abort = true;
  995. replaced++;
  996. compressor.info("Collapsing {name} [{file}:{line},{col}]", {
  997. name: node.print_to_string(),
  998. file: node.start.file,
  999. line: node.start.line,
  1000. col: node.start.col
  1001. });
  1002. if (candidate instanceof AST_UnaryPostfix) {
  1003. return make_node(AST_UnaryPrefix, candidate, candidate);
  1004. }
  1005. if (candidate instanceof AST_VarDef) {
  1006. if (value_def) {
  1007. abort = false;
  1008. return node;
  1009. }
  1010. var def = candidate.name.definition();
  1011. var value = candidate.value;
  1012. if (def.references.length - def.replaced == 1 && !compressor.exposed(def)) {
  1013. def.replaced++;
  1014. if (funarg && is_identifier_atom(value)) {
  1015. return value.transform(compressor);
  1016. } else {
  1017. return maintain_this_binding(parent, node, value);
  1018. }
  1019. }
  1020. return make_node(AST_Assign, candidate, {
  1021. operator: "=",
  1022. left: make_node(AST_SymbolRef, candidate.name, candidate.name),
  1023. right: value
  1024. });
  1025. }
  1026. candidate.write_only = false;
  1027. return candidate;
  1028. }
  1029. // These node types have child nodes that execute sequentially,
  1030. // but are otherwise not safe to scan into or beyond them.
  1031. var sym;
  1032. if (node instanceof AST_Call
  1033. || node instanceof AST_Exit
  1034. || node instanceof AST_PropAccess
  1035. && (side_effects || node.expression.may_throw_on_access(compressor))
  1036. || node instanceof AST_SymbolRef
  1037. && (lvalues[node.name]
  1038. || side_effects && !references_in_scope(node.definition()))
  1039. || (sym = lhs_or_def(node))
  1040. && (sym instanceof AST_PropAccess || sym.name in lvalues)
  1041. || may_throw
  1042. && (in_try ? node.has_side_effects(compressor) : side_effects_external(node))
  1043. || (side_effects || !replace_all)
  1044. && (parent instanceof AST_Binary && lazy_op(parent.operator)
  1045. || parent instanceof AST_Conditional
  1046. || parent instanceof AST_If)) {
  1047. stop_after = node;
  1048. if (node instanceof AST_Scope) abort = true;
  1049. }
  1050. // Skip (non-executed) functions
  1051. if (node instanceof AST_Scope) return node;
  1052. }, function(node) {
  1053. if (!abort && stop_after === node) abort = true;
  1054. });
  1055. var multi_replacer = new TreeTransformer(function(node) {
  1056. if (abort) return node;
  1057. // Skip nodes before `candidate` as quickly as possible
  1058. if (!hit) {
  1059. if (node !== hit_stack[hit_index]) return node;
  1060. hit_index++;
  1061. if (hit_index < hit_stack.length) return;
  1062. hit = true;
  1063. return node;
  1064. }
  1065. // Replace variable when found
  1066. if (node instanceof AST_SymbolRef
  1067. && node.name == def.name) {
  1068. if (!--replaced) abort = true;
  1069. if (is_lhs(node, multi_replacer.parent())) return node;
  1070. def.replaced++;
  1071. value_def.replaced--;
  1072. return candidate.value;
  1073. }
  1074. // Skip (non-executed) functions and (leading) default case in switch statements
  1075. if (node instanceof AST_Default || node instanceof AST_Scope) return node;
  1076. });
  1077. while (--stat_index >= 0) {
  1078. // Treat parameters as collapsible in IIFE, i.e.
  1079. // function(a, b){ ... }(x());
  1080. // would be translated into equivalent assignments:
  1081. // var a = x(), b = undefined;
  1082. if (stat_index == 0 && compressor.option("unused")) extract_args();
  1083. // Find collapsible assignments
  1084. var hit_stack = [];
  1085. extract_candidates(statements[stat_index]);
  1086. while (candidates.length > 0) {
  1087. hit_stack = candidates.pop();
  1088. var hit_index = 0;
  1089. var candidate = hit_stack[hit_stack.length - 1];
  1090. var value_def = null;
  1091. var stop_after = null;
  1092. var lhs = get_lhs(candidate);
  1093. if (!lhs || is_lhs_read_only(lhs) || lhs.has_side_effects(compressor)) continue;
  1094. // Locate symbols which may execute code outside of scanning range
  1095. var lvalues = get_lvalues(candidate);
  1096. if (lhs instanceof AST_SymbolRef) lvalues[lhs.name] = false;
  1097. var replace_all = value_def;
  1098. if (!replace_all && lhs instanceof AST_SymbolRef) {
  1099. var def = lhs.definition();
  1100. if (def.references.length - def.replaced == (candidate instanceof AST_VarDef ? 1 : 2)) {
  1101. replace_all = true;
  1102. }
  1103. }
  1104. var side_effects = value_has_side_effects(candidate);
  1105. var may_throw = candidate.may_throw(compressor);
  1106. var funarg = candidate.name instanceof AST_SymbolFunarg;
  1107. var hit = funarg;
  1108. var abort = false, replaced = 0, can_replace = !args || !hit;
  1109. if (!can_replace) {
  1110. for (var j = compressor.self().argnames.lastIndexOf(candidate.name) + 1; !abort && j < args.length; j++) {
  1111. args[j].transform(scanner);
  1112. }
  1113. can_replace = true;
  1114. }
  1115. for (var i = stat_index; !abort && i < statements.length; i++) {
  1116. statements[i].transform(scanner);
  1117. }
  1118. if (value_def) {
  1119. var def = candidate.name.definition();
  1120. if (abort && def.references.length - def.replaced > replaced) replaced = false;
  1121. else {
  1122. abort = false;
  1123. hit_index = 0;
  1124. hit = funarg;
  1125. for (var i = stat_index; !abort && i < statements.length; i++) {
  1126. statements[i].transform(multi_replacer);
  1127. }
  1128. value_def.single_use = false;
  1129. }
  1130. }
  1131. if (replaced && !remove_candidate(candidate)) statements.splice(stat_index, 1);
  1132. }
  1133. }
  1134. function has_overlapping_symbol(fn, arg, fn_strict) {
  1135. var found = false, scan_this = !(fn instanceof AST_Arrow);
  1136. arg.walk(new TreeWalker(function(node, descend) {
  1137. if (found) return true;
  1138. if (node instanceof AST_SymbolRef && fn.variables.has(node.name)) {
  1139. var s = node.definition().scope;
  1140. if (s !== scope) while (s = s.parent_scope) {
  1141. if (s === scope) return true;
  1142. }
  1143. return found = true;
  1144. }
  1145. if ((fn_strict || scan_this) && node instanceof AST_This) {
  1146. return found = true;
  1147. }
  1148. if (node instanceof AST_Scope && !(node instanceof AST_Arrow)) {
  1149. var prev = scan_this;
  1150. scan_this = false;
  1151. descend();
  1152. scan_this = prev;
  1153. return true;
  1154. }
  1155. }));
  1156. return found;
  1157. }
  1158. function extract_args() {
  1159. var iife, fn = compressor.self();
  1160. if (is_func_expr(fn)
  1161. && !fn.name
  1162. && !fn.uses_arguments
  1163. && !fn.uses_eval
  1164. && (iife = compressor.parent()) instanceof AST_Call
  1165. && iife.expression === fn
  1166. && all(iife.args, function(arg) {
  1167. return !(arg instanceof AST_Expansion);
  1168. })) {
  1169. var fn_strict = compressor.has_directive("use strict");
  1170. if (fn_strict && !member(fn_strict, fn.body)) fn_strict = false;
  1171. var len = fn.argnames.length;
  1172. args = iife.args.slice(len);
  1173. var names = Object.create(null);
  1174. for (var i = len; --i >= 0;) {
  1175. var sym = fn.argnames[i];
  1176. var arg = iife.args[i];
  1177. args.unshift(make_node(AST_VarDef, sym, {
  1178. name: sym,
  1179. value: arg
  1180. }));
  1181. if (sym.name in names) continue;
  1182. names[sym.name] = true;
  1183. if (sym instanceof AST_Expansion) {
  1184. var elements = iife.args.slice(i);
  1185. if (all(elements, function(arg) {
  1186. return !has_overlapping_symbol(fn, arg, fn_strict);
  1187. })) {
  1188. candidates.unshift([ make_node(AST_VarDef, sym, {
  1189. name: sym.expression,
  1190. value: make_node(AST_Array, iife, {
  1191. elements: elements
  1192. })
  1193. }) ]);
  1194. }
  1195. } else {
  1196. if (!arg) arg = make_node(AST_Undefined, sym).transform(compressor);
  1197. else if (has_overlapping_symbol(fn, arg, fn_strict)) arg = null;
  1198. if (arg) candidates.unshift([ make_node(AST_VarDef, sym, {
  1199. name: sym,
  1200. value: arg
  1201. }) ]);
  1202. }
  1203. }
  1204. }
  1205. }
  1206. function extract_candidates(expr) {
  1207. hit_stack.push(expr);
  1208. if (expr instanceof AST_Assign) {
  1209. if (!expr.left.has_side_effects(compressor)) {
  1210. candidates.push(hit_stack.slice());
  1211. }
  1212. extract_candidates(expr.right);
  1213. } else if (expr instanceof AST_Binary) {
  1214. extract_candidates(expr.left);
  1215. extract_candidates(expr.right);
  1216. } else if (expr instanceof AST_Call) {
  1217. extract_candidates(expr.expression);
  1218. expr.args.forEach(extract_candidates);
  1219. } else if (expr instanceof AST_Case) {
  1220. extract_candidates(expr.expression);
  1221. } else if (expr instanceof AST_Conditional) {
  1222. extract_candidates(expr.condition);
  1223. extract_candidates(expr.consequent);
  1224. extract_candidates(expr.alternative);
  1225. } else if (expr instanceof AST_Definitions
  1226. && (compressor.option("unused") || !(expr instanceof AST_Const))) {
  1227. expr.definitions.forEach(extract_candidates);
  1228. } else if (expr instanceof AST_DWLoop) {
  1229. extract_candidates(expr.condition);
  1230. if (!(expr.body instanceof AST_Block)) {
  1231. extract_candidates(expr.body);
  1232. }
  1233. } else if (expr instanceof AST_Exit) {
  1234. if (expr.value) extract_candidates(expr.value);
  1235. } else if (expr instanceof AST_For) {
  1236. if (expr.init) extract_candidates(expr.init);
  1237. if (expr.condition) extract_candidates(expr.condition);
  1238. if (expr.step) extract_candidates(expr.step);
  1239. if (!(expr.body instanceof AST_Block)) {
  1240. extract_candidates(expr.body);
  1241. }
  1242. } else if (expr instanceof AST_ForIn) {
  1243. extract_candidates(expr.object);
  1244. if (!(expr.body instanceof AST_Block)) {
  1245. extract_candidates(expr.body);
  1246. }
  1247. } else if (expr instanceof AST_If) {
  1248. extract_candidates(expr.condition);
  1249. if (!(expr.body instanceof AST_Block)) {
  1250. extract_candidates(expr.body);
  1251. }
  1252. if (expr.alternative && !(expr.alternative instanceof AST_Block)) {
  1253. extract_candidates(expr.alternative);
  1254. }
  1255. } else if (expr instanceof AST_Sequence) {
  1256. expr.expressions.forEach(extract_candidates);
  1257. } else if (expr instanceof AST_SimpleStatement) {
  1258. extract_candidates(expr.body);
  1259. } else if (expr instanceof AST_Switch) {
  1260. extract_candidates(expr.expression);
  1261. expr.body.forEach(extract_candidates);
  1262. } else if (expr instanceof AST_Unary) {
  1263. if (expr.operator == "++" || expr.operator == "--") {
  1264. candidates.push(hit_stack.slice());
  1265. }
  1266. } else if (expr instanceof AST_VarDef) {
  1267. if (expr.value) {
  1268. candidates.push(hit_stack.slice());
  1269. extract_candidates(expr.value);
  1270. }
  1271. }
  1272. hit_stack.pop();
  1273. }
  1274. function find_stop(node, level) {
  1275. var parent = scanner.parent(level);
  1276. if (parent instanceof AST_Binary) return node;
  1277. if (parent instanceof AST_Call) return node;
  1278. if (parent instanceof AST_Case) return node;
  1279. if (parent instanceof AST_Conditional) return node;
  1280. if (parent instanceof AST_Definitions) return find_stop(parent, level + 1);
  1281. if (parent instanceof AST_Exit) return node;
  1282. if (parent instanceof AST_If) return node;
  1283. if (parent instanceof AST_IterationStatement) return node;
  1284. if (parent instanceof AST_Sequence) return find_stop(parent, level + 1);
  1285. if (parent instanceof AST_SimpleStatement) return find_stop(parent, level + 1);
  1286. if (parent instanceof AST_Switch) return node;
  1287. if (parent instanceof AST_VarDef) return node;
  1288. return null;
  1289. }
  1290. function mangleable_var(var_def) {
  1291. var value = var_def.value;
  1292. if (!(value instanceof AST_SymbolRef)) return;
  1293. if (value.name == "arguments") return;
  1294. var def = value.definition();
  1295. if (def.undeclared) return;
  1296. return value_def = def;
  1297. }
  1298. function get_lhs(expr) {
  1299. if (expr instanceof AST_VarDef && expr.name instanceof AST_SymbolDeclaration) {
  1300. var def = expr.name.definition();
  1301. if (!member(expr.name, def.orig)) return;
  1302. var declared = def.orig.length - def.eliminated;
  1303. var referenced = def.references.length - def.replaced;
  1304. if (declared > 1 && !(expr.name instanceof AST_SymbolFunarg)
  1305. || (referenced > 1 ? mangleable_var(expr) : !compressor.exposed(def))) {
  1306. return make_node(AST_SymbolRef, expr.name, expr.name);
  1307. }
  1308. } else {
  1309. var lhs = expr[expr instanceof AST_Assign ? "left" : "expression"];
  1310. return !is_ref_of(lhs, AST_SymbolConst) && lhs;
  1311. }
  1312. }
  1313. function get_rvalue(expr) {
  1314. return expr[expr instanceof AST_Assign ? "right" : "value"];
  1315. }
  1316. function get_lvalues(expr) {
  1317. var lvalues = Object.create(null);
  1318. if (expr instanceof AST_Unary) return lvalues;
  1319. var tw = new TreeWalker(function(node, descend) {
  1320. var sym = node;
  1321. while (sym instanceof AST_PropAccess) sym = sym.expression;
  1322. if (sym instanceof AST_SymbolRef || sym instanceof AST_This) {
  1323. lvalues[sym.name] = lvalues[sym.name] || is_lhs(node, tw.parent());
  1324. }
  1325. });
  1326. get_rvalue(expr).walk(tw);
  1327. return lvalues;
  1328. }
  1329. function lhs_or_def(node) {
  1330. if (node instanceof AST_VarDef) return node.value && node.name;
  1331. return is_lhs(node.left, node);
  1332. }
  1333. function remove_candidate(expr) {
  1334. if (expr.name instanceof AST_SymbolFunarg) {
  1335. var iife = compressor.parent(), argnames = compressor.self().argnames;
  1336. var index = argnames.indexOf(expr.name);
  1337. if (index < 0) {
  1338. iife.args.length = Math.min(iife.args.length, argnames.length - 1);
  1339. } else {
  1340. var args = iife.args;
  1341. if (args[index]) args[index] = make_node(AST_Number, args[index], {
  1342. value: 0
  1343. });
  1344. }
  1345. return true;
  1346. }
  1347. var found = false;
  1348. return statements[stat_index].transform(new TreeTransformer(function(node, descend, in_list) {
  1349. if (found) return node;
  1350. if (node === expr || node.body === expr) {
  1351. found = true;
  1352. if (node instanceof AST_VarDef) {
  1353. node.value = null;
  1354. return node;
  1355. }
  1356. return in_list ? MAP.skip : null;
  1357. }
  1358. }, function(node) {
  1359. if (node instanceof AST_Sequence) switch (node.expressions.length) {
  1360. case 0: return null;
  1361. case 1: return node.expressions[0];
  1362. }
  1363. }));
  1364. }
  1365. function value_has_side_effects(expr) {
  1366. if (expr instanceof AST_Unary) return false;
  1367. return get_rvalue(expr).has_side_effects(compressor);
  1368. }
  1369. function references_in_scope(def) {
  1370. if (def.orig.length == 1 && def.orig[0] instanceof AST_SymbolDefun) return true;
  1371. if (def.scope.get_defun_scope() !== scope) return false;
  1372. return def.references.every(function(ref) {
  1373. return ref.scope.get_defun_scope() === scope;
  1374. });
  1375. }
  1376. function side_effects_external(node, lhs) {
  1377. if (node instanceof AST_Assign) {
  1378. return side_effects_external(node.left, true)
  1379. || side_effects_external(node.right);
  1380. }
  1381. if (node instanceof AST_Definitions) return false;
  1382. if (node instanceof AST_Unary) return side_effects_external(node.expression, true);
  1383. if (node instanceof AST_VarDef) return node.value && side_effects_external(node.value);
  1384. if (lhs) {
  1385. if (node instanceof AST_Dot) return side_effects_external(node.expression, true);
  1386. if (node instanceof AST_Sub) {
  1387. return side_effects_external(node.expression, true)
  1388. || side_effects_external(node.property);
  1389. }
  1390. if (node instanceof AST_SymbolRef) return node.definition().scope !== scope;
  1391. }
  1392. return node.has_side_effects(compressor);
  1393. }
  1394. }
  1395. function eliminate_spurious_blocks(statements) {
  1396. var seen_dirs = [];
  1397. for (var i = 0; i < statements.length;) {
  1398. var stat = statements[i];
  1399. if (stat instanceof AST_BlockStatement && all(stat.body, can_be_evicted_from_block)) {
  1400. CHANGED = true;
  1401. eliminate_spurious_blocks(stat.body);
  1402. [].splice.apply(statements, [i, 1].concat(stat.body));
  1403. i += stat.body.length;
  1404. } else if (stat instanceof AST_EmptyStatement) {
  1405. CHANGED = true;
  1406. statements.splice(i, 1);
  1407. } else if (stat instanceof AST_Directive) {
  1408. if (seen_dirs.indexOf(stat.value) < 0) {
  1409. i++;
  1410. seen_dirs.push(stat.value);
  1411. } else {
  1412. CHANGED = true;
  1413. statements.splice(i, 1);
  1414. }
  1415. } else i++;
  1416. }
  1417. }
  1418. function handle_if_return(statements, compressor) {
  1419. var self = compressor.self();
  1420. var multiple_if_returns = has_multiple_if_returns(statements);
  1421. var in_lambda = self instanceof AST_Lambda;
  1422. for (var i = statements.length; --i >= 0;) {
  1423. var stat = statements[i];
  1424. var j = next_index(i);
  1425. var next = statements[j];
  1426. if (in_lambda && !next && stat instanceof AST_Return) {
  1427. if (!stat.value) {
  1428. CHANGED = true;
  1429. statements.splice(i, 1);
  1430. continue;
  1431. }
  1432. if (stat.value instanceof AST_UnaryPrefix && stat.value.operator == "void") {
  1433. CHANGED = true;
  1434. statements[i] = make_node(AST_SimpleStatement, stat, {
  1435. body: stat.value.expression
  1436. });
  1437. continue;
  1438. }
  1439. }
  1440. if (stat instanceof AST_If) {
  1441. var ab = aborts(stat.body);
  1442. if (can_merge_flow(ab)) {
  1443. if (ab.label) {
  1444. remove(ab.label.thedef.references, ab);
  1445. }
  1446. CHANGED = true;
  1447. stat = stat.clone();
  1448. stat.condition = stat.condition.negate(compressor);
  1449. var body = as_statement_array_with_return(stat.body, ab);
  1450. stat.body = make_node(AST_BlockStatement, stat, {
  1451. body: as_statement_array(stat.alternative).concat(extract_functions())
  1452. });
  1453. stat.alternative = make_node(AST_BlockStatement, stat, {
  1454. body: body
  1455. });
  1456. statements[i] = stat.transform(compressor);
  1457. continue;
  1458. }
  1459. var ab = aborts(stat.alternative);
  1460. if (can_merge_flow(ab)) {
  1461. if (ab.label) {
  1462. remove(ab.label.thedef.references, ab);
  1463. }
  1464. CHANGED = true;
  1465. stat = stat.clone();
  1466. stat.body = make_node(AST_BlockStatement, stat.body, {
  1467. body: as_statement_array(stat.body).concat(extract_functions())
  1468. });
  1469. var body = as_statement_array_with_return(stat.alternative, ab);
  1470. stat.alternative = make_node(AST_BlockStatement, stat.alternative, {
  1471. body: body
  1472. });
  1473. statements[i] = stat.transform(compressor);
  1474. continue;
  1475. }
  1476. }
  1477. if (stat instanceof AST_If && stat.body instanceof AST_Return) {
  1478. var value = stat.body.value;
  1479. //---
  1480. // pretty silly case, but:
  1481. // if (foo()) return; return; ==> foo(); return;
  1482. if (!value && !stat.alternative
  1483. && (in_lambda && !next || next instanceof AST_Return && !next.value)) {
  1484. CHANGED = true;
  1485. statements[i] = make_node(AST_SimpleStatement, stat.condition, {
  1486. body: stat.condition
  1487. });
  1488. continue;
  1489. }
  1490. //---
  1491. // if (foo()) return x; return y; ==> return foo() ? x : y;
  1492. if (value && !stat.alternative && next instanceof AST_Return && next.value) {
  1493. CHANGED = true;
  1494. stat = stat.clone();
  1495. stat.alternative = next;
  1496. statements.splice(i, 1, stat.transform(compressor));
  1497. statements.splice(j, 1);
  1498. continue;
  1499. }
  1500. //---
  1501. // if (foo()) return x; [ return ; ] ==> return foo() ? x : undefined;
  1502. if (value && !stat.alternative
  1503. && (!next && in_lambda && multiple_if_returns
  1504. || next instanceof AST_Return)) {
  1505. CHANGED = true;
  1506. stat = stat.clone();
  1507. stat.alternative = next || make_node(AST_Return, stat, {
  1508. value: null
  1509. });
  1510. statements.splice(i, 1, stat.transform(compressor));
  1511. if (next) statements.splice(j, 1);
  1512. continue;
  1513. }
  1514. //---
  1515. // if (a) return b; if (c) return d; e; ==> return a ? b : c ? d : void e;
  1516. //
  1517. // if sequences is not enabled, this can lead to an endless loop (issue #866).
  1518. // however, with sequences on this helps producing slightly better output for
  1519. // the example code.
  1520. var prev = statements[prev_index(i)];
  1521. if (compressor.option("sequences") && in_lambda && !stat.alternative
  1522. && prev instanceof AST_If && prev.body instanceof AST_Return
  1523. && next_index(j) == statements.length && next instanceof AST_SimpleStatement) {
  1524. CHANGED = true;
  1525. stat = stat.clone();
  1526. stat.alternative = make_node(AST_BlockStatement, next, {
  1527. body: [
  1528. next,
  1529. make_node(AST_Return, next, {
  1530. value: null
  1531. })
  1532. ]
  1533. });
  1534. statements.splice(i, 1, stat.transform(compressor));
  1535. statements.splice(j, 1);
  1536. continue;
  1537. }
  1538. }
  1539. }
  1540. function has_multiple_if_returns(statements) {
  1541. var n = 0;
  1542. for (var i = statements.length; --i >= 0;) {
  1543. var stat = statements[i];
  1544. if (stat instanceof AST_If && stat.body instanceof AST_Return) {
  1545. if (++n > 1) return true;
  1546. }
  1547. }
  1548. return false;
  1549. }
  1550. function is_return_void(value) {
  1551. return !value || value instanceof AST_UnaryPrefix && value.operator == "void";
  1552. }
  1553. function can_merge_flow(ab) {
  1554. if (!ab) return false;
  1555. for (var j = i + 1, len = statements.length; j < len; j++) {
  1556. var stat = statements[j];
  1557. if (stat instanceof AST_Const || stat instanceof AST_Let) return false;
  1558. }
  1559. var lct = ab instanceof AST_LoopControl ? compressor.loopcontrol_target(ab) : null;
  1560. return ab instanceof AST_Return && in_lambda && is_return_void(ab.value)
  1561. || ab instanceof AST_Continue && self === loop_body(lct)
  1562. || ab instanceof AST_Break && lct instanceof AST_BlockStatement && self === lct;
  1563. }
  1564. function extract_functions() {
  1565. var tail = statements.slice(i + 1);
  1566. statements.length = i + 1;
  1567. return tail.filter(function(stat) {
  1568. if (stat instanceof AST_Defun) {
  1569. statements.push(stat);
  1570. return false;
  1571. }
  1572. return true;
  1573. });
  1574. }
  1575. function as_statement_array_with_return(node, ab) {
  1576. var body = as_statement_array(node).slice(0, -1);
  1577. if (ab.value) {
  1578. body.push(make_node(AST_SimpleStatement, ab.value, {
  1579. body: ab.value.expression
  1580. }));
  1581. }
  1582. return body;
  1583. }
  1584. function next_index(i) {
  1585. for (var j = i + 1, len = statements.length; j < len; j++) {
  1586. var stat = statements[j];
  1587. if (!(stat instanceof AST_Var && declarations_only(stat))) {
  1588. break;
  1589. }
  1590. }
  1591. return j;
  1592. }
  1593. function prev_index(i) {
  1594. for (var j = i; --j >= 0;) {
  1595. var stat = statements[j];
  1596. if (!(stat instanceof AST_Var && declarations_only(stat))) {
  1597. break;
  1598. }
  1599. }
  1600. return j;
  1601. }
  1602. }
  1603. function eliminate_dead_code(statements, compressor) {
  1604. var has_quit;
  1605. var self = compressor.self();
  1606. for (var i = 0, n = 0, len = statements.length; i < len; i++) {
  1607. var stat = statements[i];
  1608. if (stat instanceof AST_LoopControl) {
  1609. var lct = compressor.loopcontrol_target(stat);
  1610. if (stat instanceof AST_Break
  1611. && !(lct instanceof AST_IterationStatement)
  1612. && loop_body(lct) === self
  1613. || stat instanceof AST_Continue
  1614. && loop_body(lct) === self) {
  1615. if (stat.label) {
  1616. remove(stat.label.thedef.references, stat);
  1617. }
  1618. } else {
  1619. statements[n++] = stat;
  1620. }
  1621. } else {
  1622. statements[n++] = stat;
  1623. }
  1624. if (aborts(stat)) {
  1625. has_quit = statements.slice(i + 1);
  1626. break;
  1627. }
  1628. }
  1629. statements.length = n;
  1630. CHANGED = n != len;
  1631. if (has_quit) has_quit.forEach(function(stat) {
  1632. extract_declarations_from_unreachable_code(compressor, stat, statements);
  1633. });
  1634. }
  1635. function declarations_only(node) {
  1636. return all(node.definitions, function(var_def) {
  1637. return !var_def.value;
  1638. });
  1639. }
  1640. function sequencesize(statements, compressor) {
  1641. if (statements.length < 2) return;
  1642. var seq = [], n = 0;
  1643. function push_seq() {
  1644. if (!seq.length) return;
  1645. var body = make_sequence(seq[0], seq);
  1646. statements[n++] = make_node(AST_SimpleStatement, body, { body: body });
  1647. seq = [];
  1648. }
  1649. for (var i = 0, len = statements.length; i < len; i++) {
  1650. var stat = statements[i];
  1651. if (stat instanceof AST_SimpleStatement) {
  1652. if (seq.length >= compressor.sequences_limit) push_seq();
  1653. var body = stat.body;
  1654. if (seq.length > 0) body = body.drop_side_effect_free(compressor);
  1655. if (body) merge_sequence(seq, body);
  1656. } else if (stat instanceof AST_Definitions && declarations_only(stat)
  1657. || stat instanceof AST_Defun) {
  1658. statements[n++] = stat;
  1659. } else {
  1660. push_seq();
  1661. statements[n++] = stat;
  1662. }
  1663. }
  1664. push_seq();
  1665. statements.length = n;
  1666. if (n != len) CHANGED = true;
  1667. }
  1668. function to_simple_statement(block, decls) {
  1669. if (!(block instanceof AST_BlockStatement)) return block;
  1670. var stat = null;
  1671. for (var i = 0, len = block.body.length; i < len; i++) {
  1672. var line = block.body[i];
  1673. if (line instanceof AST_Var && declarations_only(line)) {
  1674. decls.push(line);
  1675. } else if (stat) {
  1676. return false;
  1677. } else {
  1678. stat = line;
  1679. }
  1680. }
  1681. return stat;
  1682. }
  1683. function sequencesize_2(statements, compressor) {
  1684. function cons_seq(right) {
  1685. n--;
  1686. CHANGED = true;
  1687. var left = prev.body;
  1688. return make_sequence(left, [ left, right ]).transform(compressor);
  1689. };
  1690. var n = 0, prev;
  1691. for (var i = 0; i < statements.length; i++) {
  1692. var stat = statements[i];
  1693. if (prev) {
  1694. if (stat instanceof AST_Exit) {
  1695. stat.value = cons_seq(stat.value || make_node(AST_Undefined, stat).transform(compressor));
  1696. } else if (stat instanceof AST_For) {
  1697. if (!(stat.init instanceof AST_Definitions)) {
  1698. var abort = false;
  1699. prev.body.walk(new TreeWalker(function(node) {
  1700. if (abort || node instanceof AST_Scope) return true;
  1701. if (node instanceof AST_Binary && node.operator == "in") {
  1702. abort = true;
  1703. return true;
  1704. }
  1705. }));
  1706. if (!abort) {
  1707. if (stat.init) stat.init = cons_seq(stat.init);
  1708. else {
  1709. stat.init = prev.body;
  1710. n--;
  1711. CHANGED = true;
  1712. }
  1713. }
  1714. }
  1715. } else if (stat instanceof AST_ForIn) {
  1716. if (!(stat.init instanceof AST_Const) && !(stat.init instanceof AST_Let)) {
  1717. stat.object = cons_seq(stat.object);
  1718. }
  1719. } else if (stat instanceof AST_If) {
  1720. stat.condition = cons_seq(stat.condition);
  1721. } else if (stat instanceof AST_Switch) {
  1722. stat.expression = cons_seq(stat.expression);
  1723. } else if (stat instanceof AST_With) {
  1724. stat.expression = cons_seq(stat.expression);
  1725. }
  1726. }
  1727. if (compressor.option("conditionals") && stat instanceof AST_If) {
  1728. var decls = [];
  1729. var body = to_simple_statement(stat.body, decls);
  1730. var alt = to_simple_statement(stat.alternative, decls);
  1731. if (body !== false && alt !== false && decls.length > 0) {
  1732. var len = decls.length;
  1733. decls.push(make_node(AST_If, stat, {
  1734. condition: stat.condition,
  1735. body: body || make_node(AST_EmptyStatement, stat.body),
  1736. alternative: alt
  1737. }));
  1738. decls.unshift(n, 1);
  1739. [].splice.apply(statements, decls);
  1740. i += len;
  1741. n += len + 1;
  1742. prev = null;
  1743. CHANGED = true;
  1744. continue;
  1745. }
  1746. }
  1747. statements[n++] = stat;
  1748. prev = stat instanceof AST_SimpleStatement ? stat : null;
  1749. }
  1750. statements.length = n;
  1751. }
  1752. function join_object_assignments(defn, body) {
  1753. if (!(defn instanceof AST_Definitions)) return;
  1754. var def = defn.definitions[defn.definitions.length - 1];
  1755. if (!(def.value instanceof AST_Object)) return;
  1756. var exprs;
  1757. if (body instanceof AST_Assign) {
  1758. exprs = [ body ];
  1759. } else if (body instanceof AST_Sequence) {
  1760. exprs = body.expressions.slice();
  1761. }
  1762. if (!exprs) return;
  1763. var trimmed = false;
  1764. do {
  1765. var node = exprs[0];
  1766. if (!(node instanceof AST_Assign)) break;
  1767. if (node.operator != "=") break;
  1768. if (!(node.left instanceof AST_PropAccess)) break;
  1769. var sym = node.left.expression;
  1770. if (!(sym instanceof AST_SymbolRef)) break;
  1771. if (def.name.name != sym.name) break;
  1772. if (!node.right.is_constant_expression(scope)) break;
  1773. var prop = node.left.property;
  1774. if (prop instanceof AST_Node) {
  1775. prop = prop.evaluate(compressor);
  1776. }
  1777. if (prop instanceof AST_Node) break;
  1778. prop = "" + prop;
  1779. if (compressor.option("ecma") < 6 && compressor.has_directive("use strict")) {
  1780. if (!all(def.value.properties, function(node) {
  1781. return node.key != prop && node.key.name != prop;
  1782. })) break;
  1783. }
  1784. def.value.properties.push(make_node(AST_ObjectKeyVal, node, {
  1785. key: prop,
  1786. value: node.right
  1787. }));
  1788. exprs.shift();
  1789. trimmed = true;
  1790. } while (exprs.length);
  1791. return trimmed && exprs;
  1792. }
  1793. function join_consecutive_vars(statements) {
  1794. var defs;
  1795. for (var i = 0, j = -1, len = statements.length; i < len; i++) {
  1796. var stat = statements[i];
  1797. var prev = statements[j];
  1798. if (stat instanceof AST_Definitions) {
  1799. if (prev && prev.TYPE == stat.TYPE) {
  1800. prev.definitions = prev.definitions.concat(stat.definitions);
  1801. CHANGED = true;
  1802. } else if (defs && defs.TYPE == stat.TYPE && declarations_only(stat)) {
  1803. defs.definitions = defs.definitions.concat(stat.definitions);
  1804. CHANGED = true;
  1805. } else {
  1806. statements[++j] = stat;
  1807. defs = stat;
  1808. }
  1809. } else if (stat instanceof AST_Exit) {
  1810. stat.value = extract_object_assignments(stat.value);
  1811. } else if (stat instanceof AST_For) {
  1812. var exprs = join_object_assignments(prev, stat.init);
  1813. if (exprs) {
  1814. CHANGED = true;
  1815. stat.init = exprs.length ? make_sequence(stat.init, exprs) : null;
  1816. statements[++j] = stat;
  1817. } else if (prev instanceof AST_Var && (!stat.init || stat.init.TYPE == prev.TYPE)) {
  1818. if (stat.init) {
  1819. prev.definitions = prev.definitions.concat(stat.init.definitions);
  1820. }
  1821. stat.init = prev;
  1822. statements[j] = stat;
  1823. CHANGED = true;
  1824. } else if (defs && stat.init && defs.TYPE == stat.init.TYPE && declarations_only(stat.init)) {
  1825. defs.definitions = defs.definitions.concat(stat.init.definitions);
  1826. stat.init = null;
  1827. statements[++j] = stat;
  1828. CHANGED = true;
  1829. } else {
  1830. statements[++j] = stat;
  1831. }
  1832. } else if (stat instanceof AST_ForIn) {
  1833. stat.object = extract_object_assignments(stat.object);
  1834. } else if (stat instanceof AST_If) {
  1835. stat.condition = extract_object_assignments(stat.condition);
  1836. } else if (stat instanceof AST_SimpleStatement) {
  1837. var exprs = join_object_assignments(prev, stat.body);
  1838. if (exprs) {
  1839. CHANGED = true;
  1840. if (!exprs.length) continue;
  1841. stat.body = make_sequence(stat.body, exprs);
  1842. }
  1843. statements[++j] = stat;
  1844. } else if (stat instanceof AST_Switch) {
  1845. stat.expression = extract_object_assignments(stat.expression);
  1846. } else if (stat instanceof AST_With) {
  1847. stat.expression = extract_object_assignments(stat.expression);
  1848. } else {
  1849. statements[++j] = stat;
  1850. }
  1851. }
  1852. statements.length = j + 1;
  1853. function extract_object_assignments(value) {
  1854. statements[++j] = stat;
  1855. var exprs = join_object_assignments(prev, value);
  1856. if (exprs) {
  1857. CHANGED = true;
  1858. if (exprs.length) {
  1859. return make_sequence(value, exprs);
  1860. } else if (value instanceof AST_Sequence) {
  1861. return value.tail_node().left;
  1862. } else {
  1863. return value.left;
  1864. }
  1865. }
  1866. return value;
  1867. }
  1868. }
  1869. }
  1870. function extract_declarations_from_unreachable_code(compressor, stat, target) {
  1871. if (!(stat instanceof AST_Defun)) {
  1872. compressor.warn("Dropping unreachable code [{file}:{line},{col}]", stat.start);
  1873. }
  1874. stat.walk(new TreeWalker(function(node){
  1875. if (node instanceof AST_Var) {
  1876. compressor.warn("Declarations in unreachable code! [{file}:{line},{col}]", node.start);
  1877. node.remove_initializers();
  1878. target.push(node);
  1879. return true;
  1880. }
  1881. if (node instanceof AST_Defun && (node === stat || !compressor.has_directive("use strict"))) {
  1882. target.push(node === stat ? node : make_node(AST_Var, node, {
  1883. definitions: [
  1884. make_node(AST_VarDef, node, {
  1885. name: make_node(AST_SymbolVar, node.name, node.name),
  1886. value: null
  1887. })
  1888. ]
  1889. }));
  1890. return true;
  1891. }
  1892. if (node instanceof AST_Scope) {
  1893. return true;
  1894. }
  1895. }));
  1896. };
  1897. function get_value(key) {
  1898. if (key instanceof AST_Constant) {
  1899. return key.getValue();
  1900. }
  1901. if (key instanceof AST_UnaryPrefix
  1902. && key.operator == "void"
  1903. && key.expression instanceof AST_Constant) {
  1904. return;
  1905. }
  1906. return key;
  1907. }
  1908. function is_undefined(node, compressor) {
  1909. return node.is_undefined
  1910. || node instanceof AST_Undefined
  1911. || node instanceof AST_UnaryPrefix
  1912. && node.operator == "void"
  1913. && !node.expression.has_side_effects(compressor);
  1914. }
  1915. // may_throw_on_access()
  1916. // returns true if this node may be null, undefined or contain `AST_Accessor`
  1917. (function(def) {
  1918. AST_Node.DEFMETHOD("may_throw_on_access", function(compressor) {
  1919. return !compressor.option("pure_getters")
  1920. || this._dot_throw(compressor);
  1921. });
  1922. function is_strict(compressor) {
  1923. return /strict/.test(compressor.option("pure_getters"));
  1924. }
  1925. def(AST_Node, is_strict);
  1926. def(AST_Null, return_true);
  1927. def(AST_Undefined, return_true);
  1928. def(AST_Constant, return_false);
  1929. def(AST_Array, return_false);
  1930. def(AST_Object, function(compressor) {
  1931. if (!is_strict(compressor)) return false;
  1932. for (var i = this.properties.length; --i >=0;)
  1933. if (this.properties[i]._dot_throw(compressor)) return true;
  1934. return false;
  1935. });
  1936. def(AST_ObjectProperty, return_false);
  1937. def(AST_ObjectGetter, return_true);
  1938. def(AST_Expansion, function(compressor) {
  1939. return this.expression._dot_throw(compressor);
  1940. });
  1941. def(AST_Function, return_false);
  1942. def(AST_Arrow, return_false);
  1943. def(AST_UnaryPostfix, return_false);
  1944. def(AST_UnaryPrefix, function() {
  1945. return this.operator == "void";
  1946. });
  1947. def(AST_Binary, function(compressor) {
  1948. return (this.operator == "&&" || this.operator == "||")
  1949. && (this.left._dot_throw(compressor) || this.right._dot_throw(compressor));
  1950. })
  1951. def(AST_Assign, function(compressor) {
  1952. return this.operator == "="
  1953. && this.right._dot_throw(compressor);
  1954. })
  1955. def(AST_Conditional, function(compressor) {
  1956. return this.consequent._dot_throw(compressor)
  1957. || this.alternative._dot_throw(compressor);
  1958. })
  1959. def(AST_Dot, function(compressor) {
  1960. if (!is_strict(compressor)) return false;
  1961. if (this.expression instanceof AST_Function && this.property == "prototype") return false;
  1962. return true;
  1963. });
  1964. def(AST_Sequence, function(compressor) {
  1965. return this.tail_node()._dot_throw(compressor);
  1966. });
  1967. def(AST_SymbolRef, function(compressor) {
  1968. if (this.is_undefined) return true;
  1969. if (!is_strict(compressor)) return false;
  1970. if (is_undeclared_ref(this) && this.is_declared(compressor)) return false;
  1971. if (this.is_immutable()) return false;
  1972. var fixed = this.fixed_value();
  1973. return !fixed || fixed._dot_throw(compressor);
  1974. });
  1975. })(function(node, func) {
  1976. node.DEFMETHOD("_dot_throw", func);
  1977. });
  1978. /* -----[ boolean/negation helpers ]----- */
  1979. // methods to determine whether an expression has a boolean result type
  1980. (function(def){
  1981. var unary_bool = [ "!", "delete" ];
  1982. var binary_bool = [ "in", "instanceof", "==", "!=", "===", "!==", "<", "<=", ">=", ">" ];
  1983. def(AST_Node, return_false);
  1984. def(AST_UnaryPrefix, function(){
  1985. return member(this.operator, unary_bool);
  1986. });
  1987. def(AST_Binary, function(){
  1988. return member(this.operator, binary_bool)
  1989. || lazy_op(this.operator)
  1990. && this.left.is_boolean()
  1991. && this.right.is_boolean();
  1992. });
  1993. def(AST_Conditional, function(){
  1994. return this.consequent.is_boolean() && this.alternative.is_boolean();
  1995. });
  1996. def(AST_Assign, function(){
  1997. return this.operator == "=" && this.right.is_boolean();
  1998. });
  1999. def(AST_Sequence, function(){
  2000. return this.tail_node().is_boolean();
  2001. });
  2002. def(AST_True, return_true);
  2003. def(AST_False, return_true);
  2004. })(function(node, func){
  2005. node.DEFMETHOD("is_boolean", func);
  2006. });
  2007. // methods to determine if an expression has a numeric result type
  2008. (function(def){
  2009. def(AST_Node, return_false);
  2010. def(AST_Number, return_true);
  2011. var unary = makePredicate("+ - ~ ++ --");
  2012. def(AST_Unary, function(){
  2013. return unary(this.operator);
  2014. });
  2015. var binary = makePredicate("- * / % & | ^ << >> >>>");
  2016. def(AST_Binary, function(compressor){
  2017. return binary(this.operator) || this.operator == "+"
  2018. && this.left.is_number(compressor)
  2019. && this.right.is_number(compressor);
  2020. });
  2021. def(AST_Assign, function(compressor){
  2022. return binary(this.operator.slice(0, -1))
  2023. || this.operator == "=" && this.right.is_number(compressor);
  2024. });
  2025. def(AST_Sequence, function(compressor){
  2026. return this.tail_node().is_number(compressor);
  2027. });
  2028. def(AST_Conditional, function(compressor){
  2029. return this.consequent.is_number(compressor) && this.alternative.is_number(compressor);
  2030. });
  2031. })(function(node, func){
  2032. node.DEFMETHOD("is_number", func);
  2033. });
  2034. // methods to determine if an expression has a string result type
  2035. (function(def){
  2036. def(AST_Node, return_false);
  2037. def(AST_String, return_true);
  2038. def(AST_TemplateString, function(){
  2039. return this.segments.length === 1;
  2040. });
  2041. def(AST_UnaryPrefix, function(){
  2042. return this.operator == "typeof";
  2043. });
  2044. def(AST_Binary, function(compressor){
  2045. return this.operator == "+" &&
  2046. (this.left.is_string(compressor) || this.right.is_string(compressor));
  2047. });
  2048. def(AST_Assign, function(compressor){
  2049. return (this.operator == "=" || this.operator == "+=") && this.right.is_string(compressor);
  2050. });
  2051. def(AST_Sequence, function(compressor){
  2052. return this.tail_node().is_string(compressor);
  2053. });
  2054. def(AST_Conditional, function(compressor){
  2055. return this.consequent.is_string(compressor) && this.alternative.is_string(compressor);
  2056. });
  2057. })(function(node, func){
  2058. node.DEFMETHOD("is_string", func);
  2059. });
  2060. var lazy_op = makePredicate("&& ||");
  2061. var unary_side_effects = makePredicate("delete ++ --");
  2062. function is_lhs(node, parent) {
  2063. if (parent instanceof AST_Unary && unary_side_effects(parent.operator)) return parent.expression;
  2064. if (parent instanceof AST_Assign && parent.left === node) return node;
  2065. }
  2066. (function(def){
  2067. AST_Node.DEFMETHOD("resolve_defines", function(compressor) {
  2068. if (!compressor.option("global_defs")) return;
  2069. var def = this._find_defs(compressor, "");
  2070. if (def) {
  2071. var node, parent = this, level = 0;
  2072. do {
  2073. node = parent;
  2074. parent = compressor.parent(level++);
  2075. } while (parent instanceof AST_PropAccess && parent.expression === node);
  2076. if (is_lhs(node, parent)) {
  2077. compressor.warn('global_defs ' + this.print_to_string() + ' redefined [{file}:{line},{col}]', this.start);
  2078. } else {
  2079. return def;
  2080. }
  2081. }
  2082. });
  2083. function to_node(value, orig) {
  2084. if (value instanceof AST_Node) return make_node(value.CTOR, orig, value);
  2085. if (Array.isArray(value)) return make_node(AST_Array, orig, {
  2086. elements: value.map(function(value) {
  2087. return to_node(value, orig);
  2088. })
  2089. });
  2090. if (value && typeof value == "object") {
  2091. var props = [];
  2092. for (var key in value) if (HOP(value, key)) {
  2093. props.push(make_node(AST_ObjectKeyVal, orig, {
  2094. key: key,
  2095. value: to_node(value[key], orig)
  2096. }));
  2097. }
  2098. return make_node(AST_Object, orig, {
  2099. properties: props
  2100. });
  2101. }
  2102. return make_node_from_constant(value, orig);
  2103. }
  2104. def(AST_Node, noop);
  2105. def(AST_Dot, function(compressor, suffix){
  2106. return this.expression._find_defs(compressor, "." + this.property + suffix);
  2107. });
  2108. def(AST_SymbolRef, function(compressor, suffix){
  2109. if (!this.global()) return;
  2110. var name;
  2111. var defines = compressor.option("global_defs");
  2112. if (defines && HOP(defines, (name = this.name + suffix))) {
  2113. var node = to_node(defines[name], this);
  2114. var top = compressor.find_parent(AST_Toplevel);
  2115. node.walk(new TreeWalker(function(node) {
  2116. if (node instanceof AST_SymbolRef) {
  2117. node.scope = top;
  2118. node.thedef = top.def_global(node);
  2119. }
  2120. }));
  2121. return node;
  2122. }
  2123. });
  2124. })(function(node, func){
  2125. node.DEFMETHOD("_find_defs", func);
  2126. });
  2127. function best_of_expression(ast1, ast2) {
  2128. return ast1.print_to_string().length >
  2129. ast2.print_to_string().length
  2130. ? ast2 : ast1;
  2131. }
  2132. function best_of_statement(ast1, ast2) {
  2133. return best_of_expression(make_node(AST_SimpleStatement, ast1, {
  2134. body: ast1
  2135. }), make_node(AST_SimpleStatement, ast2, {
  2136. body: ast2
  2137. })).body;
  2138. }
  2139. function best_of(compressor, ast1, ast2) {
  2140. return (first_in_statement(compressor) ? best_of_statement : best_of_expression)(ast1, ast2);
  2141. }
  2142. function convert_to_predicate(obj) {
  2143. for (var key in obj) {
  2144. obj[key] = makePredicate(obj[key]);
  2145. }
  2146. }
  2147. var object_fns = [
  2148. "constructor",
  2149. "toString",
  2150. "valueOf",
  2151. ];
  2152. var native_fns = {
  2153. Array: [
  2154. "indexOf",
  2155. "join",
  2156. "lastIndexOf",
  2157. "slice",
  2158. ].concat(object_fns),
  2159. Boolean: object_fns,
  2160. Number: [
  2161. "toExponential",
  2162. "toFixed",
  2163. "toPrecision",
  2164. ].concat(object_fns),
  2165. Object: object_fns,
  2166. RegExp: [
  2167. "test",
  2168. ].concat(object_fns),
  2169. String: [
  2170. "charAt",
  2171. "charCodeAt",
  2172. "concat",
  2173. "indexOf",
  2174. "italics",
  2175. "lastIndexOf",
  2176. "match",
  2177. "replace",
  2178. "search",
  2179. "slice",
  2180. "split",
  2181. "substr",
  2182. "substring",
  2183. "trim",
  2184. ].concat(object_fns),
  2185. };
  2186. convert_to_predicate(native_fns);
  2187. var static_fns = {
  2188. Array: [
  2189. "isArray",
  2190. ],
  2191. Math: [
  2192. "abs",
  2193. "acos",
  2194. "asin",
  2195. "atan",
  2196. "ceil",
  2197. "cos",
  2198. "exp",
  2199. "floor",
  2200. "log",
  2201. "round",
  2202. "sin",
  2203. "sqrt",
  2204. "tan",
  2205. "atan2",
  2206. "pow",
  2207. "max",
  2208. "min",
  2209. ],
  2210. Number: [
  2211. "isFinite",
  2212. "isNaN",
  2213. ],
  2214. Object: [
  2215. "create",
  2216. "getOwnPropertyDescriptor",
  2217. "getOwnPropertyNames",
  2218. "getPrototypeOf",
  2219. "isExtensible",
  2220. "isFrozen",
  2221. "isSealed",
  2222. "keys",
  2223. ],
  2224. String: [
  2225. "fromCharCode",
  2226. ],
  2227. };
  2228. convert_to_predicate(static_fns);
  2229. // methods to evaluate a constant expression
  2230. (function(def){
  2231. // If the node has been successfully reduced to a constant,
  2232. // then its value is returned; otherwise the element itself
  2233. // is returned.
  2234. // They can be distinguished as constant value is never a
  2235. // descendant of AST_Node.
  2236. AST_Node.DEFMETHOD("evaluate", function(compressor){
  2237. if (!compressor.option("evaluate")) return this;
  2238. var val = this._eval(compressor, 1);
  2239. return !val || val instanceof RegExp || typeof val != "object" ? val : this;
  2240. });
  2241. var unaryPrefix = makePredicate("! ~ - + void");
  2242. AST_Node.DEFMETHOD("is_constant", function(){
  2243. // Accomodate when compress option evaluate=false
  2244. // as well as the common constant expressions !0 and -1
  2245. if (this instanceof AST_Constant) {
  2246. return !(this instanceof AST_RegExp);
  2247. } else {
  2248. return this instanceof AST_UnaryPrefix
  2249. && this.expression instanceof AST_Constant
  2250. && unaryPrefix(this.operator);
  2251. }
  2252. });
  2253. def(AST_Statement, function(){
  2254. throw new Error(string_template("Cannot evaluate a statement [{file}:{line},{col}]", this.start));
  2255. });
  2256. def(AST_Lambda, return_this);
  2257. def(AST_Class, return_this);
  2258. def(AST_Node, return_this);
  2259. def(AST_Constant, function(){
  2260. return this.getValue();
  2261. });
  2262. def(AST_TemplateString, function() {
  2263. if (this.segments.length !== 1) return this;
  2264. return this.segments[0].value;
  2265. });
  2266. def(AST_Array, function(compressor, depth) {
  2267. if (compressor.option("unsafe")) {
  2268. var elements = [];
  2269. for (var i = 0, len = this.elements.length; i < len; i++) {
  2270. var element = this.elements[i];
  2271. if (element instanceof AST_Function) {
  2272. elements.push(element);
  2273. continue;
  2274. }
  2275. var value = element._eval(compressor, depth);
  2276. if (element === value) return this;
  2277. elements.push(value);
  2278. }
  2279. return elements;
  2280. }
  2281. return this;
  2282. });
  2283. def(AST_Object, function(compressor, depth) {
  2284. if (compressor.option("unsafe")) {
  2285. var val = {};
  2286. for (var i = 0, len = this.properties.length; i < len; i++) {
  2287. var prop = this.properties[i];
  2288. if (prop instanceof AST_Expansion) return this;
  2289. var key = prop.key;
  2290. if (key instanceof AST_Symbol) {
  2291. key = key.name;
  2292. } else if (key instanceof AST_Node) {
  2293. key = key._eval(compressor, depth);
  2294. if (key === prop.key) return this;
  2295. }
  2296. if (typeof Object.prototype[key] === 'function') {
  2297. return this;
  2298. }
  2299. if (prop.value instanceof AST_Function) continue;
  2300. val[key] = prop.value._eval(compressor, depth);
  2301. if (val[key] === prop.value) return this;
  2302. }
  2303. return val;
  2304. }
  2305. return this;
  2306. });
  2307. def(AST_UnaryPrefix, function(compressor, depth) {
  2308. var e = this.expression;
  2309. // Function would be evaluated to an array and so typeof would
  2310. // incorrectly return 'object'. Hence making is a special case.
  2311. if (compressor.option("typeofs")
  2312. && this.operator == "typeof"
  2313. && (e instanceof AST_Lambda
  2314. || e instanceof AST_SymbolRef
  2315. && e.fixed_value() instanceof AST_Lambda)) {
  2316. return typeof function(){};
  2317. }
  2318. e = e._eval(compressor, depth);
  2319. if (e === this.expression) return this;
  2320. switch (this.operator) {
  2321. case "!": return !e;
  2322. case "typeof":
  2323. // typeof <RegExp> returns "object" or "function" on different platforms
  2324. // so cannot evaluate reliably
  2325. if (e instanceof RegExp) return this;
  2326. return typeof e;
  2327. case "void": return void e;
  2328. case "~": return ~e;
  2329. case "-": return -e;
  2330. case "+": return +e;
  2331. }
  2332. return this;
  2333. });
  2334. def(AST_Binary, function(compressor, depth) {
  2335. var left = this.left._eval(compressor, depth);
  2336. if (left === this.left) return this;
  2337. var right = this.right._eval(compressor, depth);
  2338. if (right === this.right) return this;
  2339. var result;
  2340. switch (this.operator) {
  2341. case "&&" : result = left && right; break;
  2342. case "||" : result = left || right; break;
  2343. case "|" : result = left | right; break;
  2344. case "&" : result = left & right; break;
  2345. case "^" : result = left ^ right; break;
  2346. case "+" : result = left + right; break;
  2347. case "*" : result = left * right; break;
  2348. case "**" : result = Math.pow(left, right); break;
  2349. case "/" : result = left / right; break;
  2350. case "%" : result = left % right; break;
  2351. case "-" : result = left - right; break;
  2352. case "<<" : result = left << right; break;
  2353. case ">>" : result = left >> right; break;
  2354. case ">>>" : result = left >>> right; break;
  2355. case "==" : result = left == right; break;
  2356. case "===" : result = left === right; break;
  2357. case "!=" : result = left != right; break;
  2358. case "!==" : result = left !== right; break;
  2359. case "<" : result = left < right; break;
  2360. case "<=" : result = left <= right; break;
  2361. case ">" : result = left > right; break;
  2362. case ">=" : result = left >= right; break;
  2363. default:
  2364. return this;
  2365. }
  2366. if (isNaN(result) && compressor.find_parent(AST_With)) {
  2367. // leave original expression as is
  2368. return this;
  2369. }
  2370. return result;
  2371. });
  2372. def(AST_Conditional, function(compressor, depth) {
  2373. var condition = this.condition._eval(compressor, depth);
  2374. if (condition === this.condition) return this;
  2375. var node = condition ? this.consequent : this.alternative;
  2376. var value = node._eval(compressor, depth);
  2377. return value === node ? this : value;
  2378. });
  2379. def(AST_SymbolRef, function(compressor, depth) {
  2380. var fixed = this.fixed_value();
  2381. if (!fixed) return this;
  2382. var value;
  2383. if (HOP(fixed, "_eval")) {
  2384. value = fixed._eval();
  2385. } else {
  2386. this._eval = return_this;
  2387. value = fixed._eval(compressor, depth);
  2388. delete this._eval;
  2389. if (value === fixed) return this;
  2390. fixed._eval = function() {
  2391. return value;
  2392. };
  2393. }
  2394. if (value && typeof value == "object") {
  2395. var escaped = this.definition().escaped;
  2396. if (escaped && depth > escaped) return this;
  2397. }
  2398. return value;
  2399. });
  2400. var global_objs = {
  2401. Array: Array,
  2402. Math: Math,
  2403. Number: Number,
  2404. Object: Object,
  2405. String: String,
  2406. };
  2407. var static_values = {
  2408. Math: [
  2409. "E",
  2410. "LN10",
  2411. "LN2",
  2412. "LOG2E",
  2413. "LOG10E",
  2414. "PI",
  2415. "SQRT1_2",
  2416. "SQRT2",
  2417. ],
  2418. Number: [
  2419. "MAX_VALUE",
  2420. "MIN_VALUE",
  2421. "NaN",
  2422. "NEGATIVE_INFINITY",
  2423. "POSITIVE_INFINITY",
  2424. ],
  2425. };
  2426. convert_to_predicate(static_values);
  2427. def(AST_PropAccess, function(compressor, depth) {
  2428. if (compressor.option("unsafe")) {
  2429. var key = this.property;
  2430. if (key instanceof AST_Node) {
  2431. key = key._eval(compressor, depth);
  2432. if (key === this.property) return this;
  2433. }
  2434. var exp = this.expression;
  2435. var val;
  2436. if (is_undeclared_ref(exp)) {
  2437. if (!(static_values[exp.name] || return_false)(key)) return this;
  2438. val = global_objs[exp.name];
  2439. } else {
  2440. val = exp._eval(compressor, depth + 1);
  2441. if (!val || val === exp || !HOP(val, key)) return this;
  2442. }
  2443. return val[key];
  2444. }
  2445. return this;
  2446. });
  2447. def(AST_Call, function(compressor, depth) {
  2448. var exp = this.expression;
  2449. if (compressor.option("unsafe") && exp instanceof AST_PropAccess) {
  2450. var key = exp.property;
  2451. if (key instanceof AST_Node) {
  2452. key = key._eval(compressor, depth);
  2453. if (key === exp.property) return this;
  2454. }
  2455. var val;
  2456. var e = exp.expression;
  2457. if (is_undeclared_ref(e)) {
  2458. if (!(static_fns[e.name] || return_false)(key)) return this;
  2459. val = global_objs[e.name];
  2460. } else {
  2461. val = e._eval(compressor, depth + 1);
  2462. if (val === e || !(val && native_fns[val.constructor.name] || return_false)(key)) return this;
  2463. }
  2464. var args = [];
  2465. for (var i = 0, len = this.args.length; i < len; i++) {
  2466. var arg = this.args[i];
  2467. var value = arg._eval(compressor, depth);
  2468. if (arg === value) return this;
  2469. args.push(value);
  2470. }
  2471. try {
  2472. return val[key].apply(val, args);
  2473. } catch (ex) {
  2474. compressor.warn("Error evaluating {code} [{file}:{line},{col}]", {
  2475. code: this.print_to_string(),
  2476. file: this.start.file,
  2477. line: this.start.line,
  2478. col: this.start.col
  2479. });
  2480. }
  2481. }
  2482. return this;
  2483. });
  2484. def(AST_New, return_this);
  2485. })(function(node, func){
  2486. node.DEFMETHOD("_eval", func);
  2487. });
  2488. // method to negate an expression
  2489. (function(def){
  2490. function basic_negation(exp) {
  2491. return make_node(AST_UnaryPrefix, exp, {
  2492. operator: "!",
  2493. expression: exp
  2494. });
  2495. }
  2496. function best(orig, alt, first_in_statement) {
  2497. var negated = basic_negation(orig);
  2498. if (first_in_statement) {
  2499. var stat = make_node(AST_SimpleStatement, alt, {
  2500. body: alt
  2501. });
  2502. return best_of_expression(negated, stat) === stat ? alt : negated;
  2503. }
  2504. return best_of_expression(negated, alt);
  2505. }
  2506. def(AST_Node, function(){
  2507. return basic_negation(this);
  2508. });
  2509. def(AST_Statement, function(){
  2510. throw new Error("Cannot negate a statement");
  2511. });
  2512. def(AST_Function, function(){
  2513. return basic_negation(this);
  2514. });
  2515. def(AST_Arrow, function(){
  2516. return basic_negation(this);
  2517. });
  2518. def(AST_UnaryPrefix, function(){
  2519. if (this.operator == "!")
  2520. return this.expression;
  2521. return basic_negation(this);
  2522. });
  2523. def(AST_Sequence, function(compressor){
  2524. var expressions = this.expressions.slice();
  2525. expressions.push(expressions.pop().negate(compressor));
  2526. return make_sequence(this, expressions);
  2527. });
  2528. def(AST_Conditional, function(compressor, first_in_statement){
  2529. var self = this.clone();
  2530. self.consequent = self.consequent.negate(compressor);
  2531. self.alternative = self.alternative.negate(compressor);
  2532. return best(this, self, first_in_statement);
  2533. });
  2534. def(AST_Binary, function(compressor, first_in_statement){
  2535. var self = this.clone(), op = this.operator;
  2536. if (compressor.option("unsafe_comps")) {
  2537. switch (op) {
  2538. case "<=" : self.operator = ">" ; return self;
  2539. case "<" : self.operator = ">=" ; return self;
  2540. case ">=" : self.operator = "<" ; return self;
  2541. case ">" : self.operator = "<=" ; return self;
  2542. }
  2543. }
  2544. switch (op) {
  2545. case "==" : self.operator = "!="; return self;
  2546. case "!=" : self.operator = "=="; return self;
  2547. case "===": self.operator = "!=="; return self;
  2548. case "!==": self.operator = "==="; return self;
  2549. case "&&":
  2550. self.operator = "||";
  2551. self.left = self.left.negate(compressor, first_in_statement);
  2552. self.right = self.right.negate(compressor);
  2553. return best(this, self, first_in_statement);
  2554. case "||":
  2555. self.operator = "&&";
  2556. self.left = self.left.negate(compressor, first_in_statement);
  2557. self.right = self.right.negate(compressor);
  2558. return best(this, self, first_in_statement);
  2559. }
  2560. return basic_negation(this);
  2561. });
  2562. })(function(node, func){
  2563. node.DEFMETHOD("negate", function(compressor, first_in_statement){
  2564. return func.call(this, compressor, first_in_statement);
  2565. });
  2566. });
  2567. 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");
  2568. AST_Call.DEFMETHOD("is_expr_pure", function(compressor) {
  2569. if (compressor.option("unsafe")) {
  2570. var expr = this.expression;
  2571. if (is_undeclared_ref(expr) && global_pure_fns(expr.name)) return true;
  2572. if (expr instanceof AST_Dot
  2573. && is_undeclared_ref(expr.expression)
  2574. && (static_fns[expr.expression.name] || return_false)(expr.property)) {
  2575. return true;
  2576. }
  2577. }
  2578. return this.pure || !compressor.pure_funcs(this);
  2579. });
  2580. AST_Node.DEFMETHOD("is_call_pure", return_false);
  2581. AST_Dot.DEFMETHOD("is_call_pure", function(compressor) {
  2582. if (!compressor.option("unsafe")) return;
  2583. var expr = this.expression;
  2584. var fns = return_false;
  2585. if (expr instanceof AST_Array) {
  2586. fns = native_fns.Array;
  2587. } else if (expr.is_boolean()) {
  2588. fns = native_fns.Boolean;
  2589. } else if (expr.is_number(compressor)) {
  2590. fns = native_fns.Number;
  2591. } else if (expr instanceof AST_RegExp) {
  2592. fns = native_fns.RegExp;
  2593. } else if (expr.is_string(compressor)) {
  2594. fns = native_fns.String;
  2595. } else if (!this.may_throw_on_access(compressor)) {
  2596. fns = native_fns.Object;
  2597. }
  2598. return fns(this.property);
  2599. });
  2600. // determine if expression has side effects
  2601. (function(def){
  2602. def(AST_Node, return_true);
  2603. def(AST_EmptyStatement, return_false);
  2604. def(AST_Constant, return_false);
  2605. def(AST_This, return_false);
  2606. function any(list, compressor) {
  2607. for (var i = list.length; --i >= 0;)
  2608. if (list[i].has_side_effects(compressor))
  2609. return true;
  2610. return false;
  2611. }
  2612. def(AST_Block, function(compressor){
  2613. return any(this.body, compressor);
  2614. });
  2615. def(AST_Call, function(compressor){
  2616. if (!this.is_expr_pure(compressor)
  2617. && (!this.expression.is_call_pure(compressor)
  2618. || this.expression.has_side_effects(compressor))) {
  2619. return true;
  2620. }
  2621. return any(this.args, compressor);
  2622. });
  2623. def(AST_Switch, function(compressor){
  2624. return this.expression.has_side_effects(compressor)
  2625. || any(this.body, compressor);
  2626. });
  2627. def(AST_Case, function(compressor){
  2628. return this.expression.has_side_effects(compressor)
  2629. || any(this.body, compressor);
  2630. });
  2631. def(AST_Try, function(compressor){
  2632. return any(this.body, compressor)
  2633. || this.bcatch && this.bcatch.has_side_effects(compressor)
  2634. || this.bfinally && this.bfinally.has_side_effects(compressor);
  2635. });
  2636. def(AST_If, function(compressor){
  2637. return this.condition.has_side_effects(compressor)
  2638. || this.body && this.body.has_side_effects(compressor)
  2639. || this.alternative && this.alternative.has_side_effects(compressor);
  2640. });
  2641. def(AST_LabeledStatement, function(compressor){
  2642. return this.body.has_side_effects(compressor);
  2643. });
  2644. def(AST_SimpleStatement, function(compressor){
  2645. return this.body.has_side_effects(compressor);
  2646. });
  2647. def(AST_Lambda, return_false);
  2648. def(AST_Class, return_false);
  2649. def(AST_DefClass, return_true);
  2650. def(AST_Binary, function(compressor){
  2651. return this.left.has_side_effects(compressor)
  2652. || this.right.has_side_effects(compressor);
  2653. });
  2654. def(AST_Assign, return_true);
  2655. def(AST_Conditional, function(compressor){
  2656. return this.condition.has_side_effects(compressor)
  2657. || this.consequent.has_side_effects(compressor)
  2658. || this.alternative.has_side_effects(compressor);
  2659. });
  2660. def(AST_Unary, function(compressor){
  2661. return unary_side_effects(this.operator)
  2662. || this.expression.has_side_effects(compressor);
  2663. });
  2664. def(AST_SymbolRef, function(compressor){
  2665. return !this.is_declared(compressor);
  2666. });
  2667. def(AST_SymbolDeclaration, return_false);
  2668. def(AST_Object, function(compressor){
  2669. return any(this.properties, compressor);
  2670. });
  2671. def(AST_ObjectProperty, function(compressor){
  2672. if (this.key instanceof AST_ObjectKeyVal &&
  2673. this.key.has_side_effects(compressor))
  2674. return true;
  2675. return this.value.has_side_effects(compressor);
  2676. });
  2677. def(AST_Array, function(compressor){
  2678. return any(this.elements, compressor);
  2679. });
  2680. def(AST_Dot, function(compressor){
  2681. return this.expression.may_throw_on_access(compressor)
  2682. || this.expression.has_side_effects(compressor);
  2683. });
  2684. def(AST_Sub, function(compressor){
  2685. return this.expression.may_throw_on_access(compressor)
  2686. || this.expression.has_side_effects(compressor)
  2687. || this.property.has_side_effects(compressor);
  2688. });
  2689. def(AST_Sequence, function(compressor){
  2690. return any(this.expressions, compressor);
  2691. });
  2692. def(AST_Definitions, function(compressor){
  2693. return any(this.definitions, compressor);
  2694. });
  2695. def(AST_VarDef, function(compressor){
  2696. return this.value;
  2697. });
  2698. def(AST_TemplateSegment, return_false);
  2699. def(AST_TemplateString, function(compressor){
  2700. return any(this.segments, compressor);
  2701. });
  2702. })(function(node, func){
  2703. node.DEFMETHOD("has_side_effects", func);
  2704. });
  2705. // determine if expression may throw
  2706. (function(def){
  2707. def(AST_Node, return_true);
  2708. def(AST_Class, return_false);
  2709. def(AST_Constant, return_false);
  2710. def(AST_EmptyStatement, return_false);
  2711. def(AST_Lambda, return_false);
  2712. def(AST_SymbolDeclaration, return_false);
  2713. def(AST_This, return_false);
  2714. function any(list, compressor) {
  2715. for (var i = list.length; --i >= 0;)
  2716. if (list[i].may_throw(compressor))
  2717. return true;
  2718. return false;
  2719. }
  2720. def(AST_Array, function(compressor){
  2721. return any(this.elements, compressor);
  2722. });
  2723. def(AST_Assign, function(compressor){
  2724. return this.operator != "=" && this.left.may_throw(compressor)
  2725. || this.right.may_throw(compressor);
  2726. });
  2727. def(AST_Binary, function(compressor){
  2728. return this.left.may_throw(compressor)
  2729. || this.right.may_throw(compressor);
  2730. });
  2731. def(AST_Block, function(compressor){
  2732. return any(this.body, compressor);
  2733. });
  2734. def(AST_Call, function(compressor){
  2735. if (any(this.args, compressor)) return true;
  2736. if (this.is_expr_pure(compressor)) return false;
  2737. if (this.expression.may_throw(compressor)) return true;
  2738. return !(this.expression instanceof AST_Lambda)
  2739. || any(this.expression.body, compressor);
  2740. });
  2741. def(AST_Case, function(compressor){
  2742. return this.expression.may_throw(compressor)
  2743. || any(this.body, compressor);
  2744. });
  2745. def(AST_Conditional, function(compressor){
  2746. return this.condition.may_throw(compressor)
  2747. || this.consequent.may_throw(compressor)
  2748. || this.alternative.may_throw(compressor);
  2749. });
  2750. def(AST_Definitions, function(compressor){
  2751. return any(this.definitions, compressor);
  2752. });
  2753. def(AST_Dot, function(compressor){
  2754. return this.expression.may_throw_on_access(compressor)
  2755. || this.expression.may_throw(compressor);
  2756. });
  2757. def(AST_If, function(compressor){
  2758. return this.condition.may_throw(compressor)
  2759. || this.body && this.body.may_throw(compressor)
  2760. || this.alternative && this.alternative.may_throw(compressor);
  2761. });
  2762. def(AST_LabeledStatement, function(compressor){
  2763. return this.body.may_throw(compressor);
  2764. });
  2765. def(AST_Object, function(compressor){
  2766. return any(this.properties, compressor);
  2767. });
  2768. def(AST_ObjectProperty, function(compressor){
  2769. return this.value.may_throw(compressor);
  2770. });
  2771. def(AST_Sequence, function(compressor){
  2772. return any(this.expressions, compressor);
  2773. });
  2774. def(AST_SimpleStatement, function(compressor){
  2775. return this.body.may_throw(compressor);
  2776. });
  2777. def(AST_Sub, function(compressor){
  2778. return this.expression.may_throw_on_access(compressor)
  2779. || this.expression.may_throw(compressor)
  2780. || this.property.may_throw(compressor);
  2781. });
  2782. def(AST_Switch, function(compressor){
  2783. return this.expression.may_throw(compressor)
  2784. || any(this.body, compressor);
  2785. });
  2786. def(AST_SymbolRef, function(compressor){
  2787. return !this.is_declared(compressor);
  2788. });
  2789. def(AST_Try, function(compressor){
  2790. return any(this.body, compressor)
  2791. || this.bcatch && this.bcatch.may_throw(compressor)
  2792. || this.bfinally && this.bfinally.may_throw(compressor);
  2793. });
  2794. def(AST_Unary, function(compressor){
  2795. if (this.operator == "typeof" && this.expression instanceof AST_SymbolRef)
  2796. return false;
  2797. return this.expression.may_throw(compressor);
  2798. });
  2799. def(AST_VarDef, function(compressor){
  2800. if (!this.value) return false;
  2801. return this.value.may_throw(compressor);
  2802. });
  2803. })(function(node, func){
  2804. node.DEFMETHOD("may_throw", func);
  2805. });
  2806. // determine if expression is constant
  2807. (function(def){
  2808. function all(list) {
  2809. for (var i = list.length; --i >= 0;)
  2810. if (!list[i].is_constant_expression())
  2811. return false;
  2812. return true;
  2813. }
  2814. function all_refs_local(scope) {
  2815. var self = this;
  2816. var result = true;
  2817. self.walk(new TreeWalker(function(node) {
  2818. if (!result) return true;
  2819. if (node instanceof AST_SymbolRef) {
  2820. if (self.inlined) {
  2821. result = false;
  2822. return true;
  2823. }
  2824. var def = node.definition();
  2825. if (member(def, self.enclosed)
  2826. && !self.variables.has(def.name)) {
  2827. if (scope) {
  2828. var scope_def = scope.find_variable(node);
  2829. if (def.undeclared ? !scope_def : scope_def === def) {
  2830. result = "f";
  2831. return true;
  2832. }
  2833. }
  2834. result = false;
  2835. }
  2836. return true;
  2837. }
  2838. if (node instanceof AST_This && self instanceof AST_Arrow) {
  2839. result = false;
  2840. return true;
  2841. }
  2842. }));
  2843. return result;
  2844. }
  2845. def(AST_Node, return_false);
  2846. def(AST_Constant, return_true);
  2847. def(AST_Class, all_refs_local);
  2848. def(AST_Lambda, all_refs_local);
  2849. def(AST_Unary, function(){
  2850. return this.expression.is_constant_expression();
  2851. });
  2852. def(AST_Binary, function(){
  2853. return this.left.is_constant_expression() && this.right.is_constant_expression();
  2854. });
  2855. def(AST_Array, function(){
  2856. return all(this.elements);
  2857. });
  2858. def(AST_Object, function(){
  2859. return all(this.properties);
  2860. });
  2861. def(AST_ObjectProperty, function(){
  2862. return !(this.key instanceof AST_Node) && this.value.is_constant_expression();
  2863. });
  2864. })(function(node, func){
  2865. node.DEFMETHOD("is_constant_expression", func);
  2866. });
  2867. // tell me if a statement aborts
  2868. function aborts(thing) {
  2869. return thing && thing.aborts();
  2870. };
  2871. (function(def){
  2872. def(AST_Statement, return_null);
  2873. def(AST_Jump, return_this);
  2874. function block_aborts(){
  2875. var n = this.body.length;
  2876. return n > 0 && aborts(this.body[n - 1]);
  2877. };
  2878. def(AST_Import, function(){ return null; });
  2879. def(AST_BlockStatement, block_aborts);
  2880. def(AST_SwitchBranch, block_aborts);
  2881. def(AST_If, function(){
  2882. return this.alternative && aborts(this.body) && aborts(this.alternative) && this;
  2883. });
  2884. })(function(node, func){
  2885. node.DEFMETHOD("aborts", func);
  2886. });
  2887. /* -----[ optimizers ]----- */
  2888. OPT(AST_Directive, function(self, compressor){
  2889. if (compressor.has_directive(self.value) !== self) {
  2890. return make_node(AST_EmptyStatement, self);
  2891. }
  2892. return self;
  2893. });
  2894. OPT(AST_Debugger, function(self, compressor){
  2895. if (compressor.option("drop_debugger"))
  2896. return make_node(AST_EmptyStatement, self);
  2897. return self;
  2898. });
  2899. OPT(AST_LabeledStatement, function(self, compressor){
  2900. if (self.body instanceof AST_Break
  2901. && compressor.loopcontrol_target(self.body) === self.body) {
  2902. return make_node(AST_EmptyStatement, self);
  2903. }
  2904. return self.label.references.length == 0 ? self.body : self;
  2905. });
  2906. OPT(AST_Block, function(self, compressor){
  2907. tighten_body(self.body, compressor);
  2908. return self;
  2909. });
  2910. OPT(AST_BlockStatement, function(self, compressor){
  2911. tighten_body(self.body, compressor);
  2912. switch (self.body.length) {
  2913. case 1:
  2914. if (!compressor.has_directive("use strict") && compressor.parent() instanceof AST_If
  2915. || can_be_evicted_from_block(self.body[0])) {
  2916. return self.body[0];
  2917. }
  2918. break;
  2919. case 0: return make_node(AST_EmptyStatement, self);
  2920. }
  2921. return self;
  2922. });
  2923. AST_Scope.DEFMETHOD("drop_unused", function(compressor){
  2924. if (!compressor.option("unused")) return;
  2925. if (compressor.has_directive("use asm")) return;
  2926. var self = this;
  2927. if (self.uses_eval || self.uses_with) return;
  2928. var drop_funcs = !(self instanceof AST_Toplevel) || compressor.toplevel.funcs;
  2929. var drop_vars = !(self instanceof AST_Toplevel) || compressor.toplevel.vars;
  2930. var assign_as_unused = /keep_assign/.test(compressor.option("unused")) ? return_false : function(node) {
  2931. if (node instanceof AST_Assign && (node.write_only || node.operator == "=")) {
  2932. return node.left;
  2933. }
  2934. if (node instanceof AST_Unary && node.write_only) return node.expression;
  2935. };
  2936. var in_use = [];
  2937. var in_use_ids = Object.create(null); // avoid expensive linear scans of in_use
  2938. var fixed_ids = Object.create(null);
  2939. if (self instanceof AST_Toplevel && compressor.top_retain) {
  2940. self.variables.each(function(def) {
  2941. if (compressor.top_retain(def) && !(def.id in in_use_ids)) {
  2942. in_use_ids[def.id] = true;
  2943. in_use.push(def);
  2944. }
  2945. });
  2946. }
  2947. var var_defs_by_id = new Dictionary();
  2948. var initializations = new Dictionary();
  2949. var destructuring_value = null;
  2950. // pass 1: find out which symbols are directly used in
  2951. // this scope (not in nested scopes).
  2952. var scope = this;
  2953. var tw = new TreeWalker(function(node, descend){
  2954. if (node === self) return;
  2955. if (node instanceof AST_Defun || node instanceof AST_DefClass) {
  2956. var node_def = node.name.definition();
  2957. var in_export = tw.parent() instanceof AST_Export;
  2958. if (in_export || !drop_funcs && scope === self) {
  2959. if (node_def.global && !(node_def.id in in_use_ids)) {
  2960. in_use_ids[node_def.id] = true;
  2961. in_use.push(node_def);
  2962. }
  2963. }
  2964. initializations.add(node_def.id, node);
  2965. return true; // don't go in nested scopes
  2966. }
  2967. if (node instanceof AST_SymbolFunarg && scope === self) {
  2968. var_defs_by_id.add(node.definition().id, node);
  2969. }
  2970. if (node instanceof AST_Definitions && scope === self) {
  2971. var in_export = tw.parent() instanceof AST_Export;
  2972. node.definitions.forEach(function(def){
  2973. if (def.name instanceof AST_SymbolVar) {
  2974. var_defs_by_id.add(def.name.definition().id, def);
  2975. }
  2976. if (in_export || !drop_vars) {
  2977. def.name.walk(new TreeWalker(function(node) {
  2978. if (node instanceof AST_SymbolDeclaration) {
  2979. var def = node.definition();
  2980. if ((in_export || def.global) && !(def.id in in_use_ids)) {
  2981. in_use_ids[def.id] = true;
  2982. in_use.push(def);
  2983. }
  2984. }
  2985. }));
  2986. }
  2987. if (def.value) {
  2988. if (def.name instanceof AST_Destructuring) {
  2989. var destructuring_cache = destructuring_value;
  2990. destructuring_value = def.value;
  2991. def.walk(tw);
  2992. destructuring_value = destructuring_cache;
  2993. } else {
  2994. var node_def = def.name.definition();;
  2995. initializations.add(node_def.id, def.value);
  2996. if (def.name.fixed_value() === def.value) {
  2997. fixed_ids[node_def.id] = def;
  2998. }
  2999. }
  3000. if (def.value.has_side_effects(compressor)) {
  3001. def.value.walk(tw);
  3002. }
  3003. }
  3004. });
  3005. return true;
  3006. }
  3007. if (node.destructuring && destructuring_value) {
  3008. initializations.add(node.name, destructuring_value);
  3009. }
  3010. return scan_ref_scoped(node, descend);
  3011. });
  3012. self.walk(tw);
  3013. // pass 2: for every used symbol we need to walk its
  3014. // initialization code to figure out if it uses other
  3015. // symbols (that may not be in_use).
  3016. tw = new TreeWalker(scan_ref_scoped);
  3017. for (var i = 0; i < in_use.length; i++) {
  3018. var init = initializations.get(in_use[i].id);
  3019. if (init) init.forEach(function(init) {
  3020. init.walk(tw);
  3021. });
  3022. }
  3023. // pass 3: we should drop declarations not in_use
  3024. var tt = new TreeTransformer(
  3025. function before(node, descend, in_list) {
  3026. var parent = tt.parent();
  3027. if (drop_vars) {
  3028. var sym = assign_as_unused(node);
  3029. if (sym instanceof AST_SymbolRef) {
  3030. var def = sym.definition();
  3031. var in_use = def.id in in_use_ids;
  3032. if (node instanceof AST_Assign) {
  3033. if (!in_use || def.id in fixed_ids && fixed_ids[def.id] !== node) {
  3034. return maintain_this_binding(parent, node, node.right.transform(tt));
  3035. }
  3036. } else if (!in_use) return make_node(AST_Number, node, {
  3037. value: 0
  3038. });
  3039. }
  3040. }
  3041. if (scope !== self) return;
  3042. if (node.name
  3043. && (!compressor.option("keep_classnames") && node instanceof AST_ClassExpression
  3044. || !compressor.option("keep_fnames") && node instanceof AST_Function)) {
  3045. var def = node.name.definition();
  3046. // any declarations with same name will overshadow
  3047. // name of this anonymous function and can therefore
  3048. // never be used anywhere
  3049. if (!(def.id in in_use_ids) || def.orig.length > 1)
  3050. node.name = null;
  3051. }
  3052. if (node instanceof AST_Lambda && !(node instanceof AST_Accessor)) {
  3053. var trim = !compressor.option("keep_fargs");
  3054. for (var a = node.argnames, i = a.length; --i >= 0;) {
  3055. var sym = a[i];
  3056. if (sym instanceof AST_Expansion) {
  3057. sym = sym.expression;
  3058. }
  3059. if (sym instanceof AST_DefaultAssign) {
  3060. sym = sym.left;
  3061. }
  3062. // Do not drop destructuring arguments.
  3063. // They constitute a type assertion, so dropping
  3064. // them would stop that TypeError which would happen
  3065. // if someone called it with an incorrectly formatted
  3066. // parameter.
  3067. if (!(sym instanceof AST_Destructuring) && !(sym.definition().id in in_use_ids)) {
  3068. sym.__unused = true;
  3069. if (trim) {
  3070. a.pop();
  3071. compressor[sym.unreferenced() ? "warn" : "info"]("Dropping unused function argument {name} [{file}:{line},{col}]", template(sym));
  3072. }
  3073. }
  3074. else {
  3075. trim = false;
  3076. }
  3077. }
  3078. }
  3079. if ((node instanceof AST_Defun || node instanceof AST_DefClass) && node !== self) {
  3080. var def = node.name.definition();
  3081. var keep = (def.id in in_use_ids) || !drop_funcs && def.global;
  3082. if (!keep) {
  3083. compressor[node.name.unreferenced() ? "warn" : "info"]("Dropping unused function {name} [{file}:{line},{col}]", template(node.name));
  3084. def.eliminated++;
  3085. return make_node(AST_EmptyStatement, node);
  3086. }
  3087. }
  3088. if (node instanceof AST_Definitions && !(parent instanceof AST_ForIn && parent.init === node)) {
  3089. var drop_block = !(parent instanceof AST_Toplevel) && !(node instanceof AST_Var);
  3090. // place uninitialized names at the start
  3091. var body = [], head = [], tail = [];
  3092. // for unused names whose initialization has
  3093. // side effects, we can cascade the init. code
  3094. // into the next one, or next statement.
  3095. var side_effects = [];
  3096. node.definitions.forEach(function(def) {
  3097. if (def.value) def.value = def.value.transform(tt);
  3098. if (def.name instanceof AST_Destructuring) return tail.push(def);
  3099. var sym = def.name.definition();
  3100. if (drop_block && sym.global) return tail.push(def);
  3101. if (!(drop_vars || drop_block) || sym.id in in_use_ids) {
  3102. if (def.value && sym.id in fixed_ids && fixed_ids[sym.id] !== def) {
  3103. def.value = def.value.drop_side_effect_free(compressor);
  3104. }
  3105. if (def.name instanceof AST_SymbolVar) {
  3106. var var_defs = var_defs_by_id.get(sym.id);
  3107. if (var_defs.length > 1 && (!def.value || sym.orig.indexOf(def.name) > sym.eliminated)) {
  3108. compressor.warn("Dropping duplicated definition of variable {name} [{file}:{line},{col}]", template(def.name));
  3109. if (def.value) {
  3110. var ref = make_node(AST_SymbolRef, def.name, def.name);
  3111. sym.references.push(ref);
  3112. var assign = make_node(AST_Assign, def, {
  3113. operator: "=",
  3114. left: ref,
  3115. right: def.value
  3116. });
  3117. if (fixed_ids[sym.id] === def) {
  3118. fixed_ids[sym.id] = assign;
  3119. }
  3120. side_effects.push(assign.transform(tt));
  3121. }
  3122. remove(var_defs, def);
  3123. sym.eliminated++;
  3124. return;
  3125. }
  3126. }
  3127. if (def.value) {
  3128. if (side_effects.length > 0) {
  3129. if (tail.length > 0) {
  3130. side_effects.push(def.value);
  3131. def.value = make_sequence(def.value, side_effects);
  3132. } else {
  3133. body.push(make_node(AST_SimpleStatement, node, {
  3134. body: make_sequence(node, side_effects)
  3135. }));
  3136. }
  3137. side_effects = [];
  3138. }
  3139. tail.push(def);
  3140. } else {
  3141. head.push(def);
  3142. }
  3143. } else if (sym.orig[0] instanceof AST_SymbolCatch) {
  3144. var value = def.value && def.value.drop_side_effect_free(compressor);
  3145. if (value) side_effects.push(value);
  3146. def.value = null;
  3147. head.push(def);
  3148. } else {
  3149. var value = def.value && def.value.drop_side_effect_free(compressor);
  3150. if (value) {
  3151. compressor.warn("Side effects in initialization of unused variable {name} [{file}:{line},{col}]", template(def.name));
  3152. side_effects.push(value);
  3153. } else {
  3154. compressor[def.name.unreferenced() ? "warn" : "info"]("Dropping unused variable {name} [{file}:{line},{col}]", template(def.name));
  3155. }
  3156. sym.eliminated++;
  3157. }
  3158. });
  3159. if (head.length > 0 || tail.length > 0) {
  3160. node.definitions = head.concat(tail);
  3161. body.push(node);
  3162. }
  3163. if (side_effects.length > 0) {
  3164. body.push(make_node(AST_SimpleStatement, node, {
  3165. body: make_sequence(node, side_effects)
  3166. }));
  3167. }
  3168. switch (body.length) {
  3169. case 0:
  3170. return in_list ? MAP.skip : make_node(AST_EmptyStatement, node);
  3171. case 1:
  3172. return body[0];
  3173. default:
  3174. return in_list ? MAP.splice(body) : make_node(AST_BlockStatement, node, {
  3175. body: body
  3176. });
  3177. }
  3178. }
  3179. // certain combination of unused name + side effect leads to:
  3180. // https://github.com/mishoo/UglifyJS2/issues/44
  3181. // https://github.com/mishoo/UglifyJS2/issues/1830
  3182. // https://github.com/mishoo/UglifyJS2/issues/1838
  3183. // that's an invalid AST.
  3184. // We fix it at this stage by moving the `var` outside the `for`.
  3185. if (node instanceof AST_For) {
  3186. descend(node, this);
  3187. var block;
  3188. if (node.init instanceof AST_BlockStatement) {
  3189. block = node.init;
  3190. node.init = block.body.pop();
  3191. block.body.push(node);
  3192. }
  3193. if (node.init instanceof AST_SimpleStatement) {
  3194. node.init = node.init.body;
  3195. } else if (is_empty(node.init)) {
  3196. node.init = null;
  3197. }
  3198. return !block ? node : in_list ? MAP.splice(block.body) : block;
  3199. }
  3200. if (node instanceof AST_LabeledStatement && node.body instanceof AST_For) {
  3201. descend(node, this);
  3202. if (node.body instanceof AST_BlockStatement) {
  3203. var block = node.body;
  3204. node.body = block.body.pop();
  3205. block.body.push(node);
  3206. return in_list ? MAP.splice(block.body) : block;
  3207. }
  3208. return node;
  3209. }
  3210. if (node instanceof AST_BlockStatement) {
  3211. descend(node, this);
  3212. if (in_list && all(node.body, can_be_evicted_from_block)) {
  3213. return MAP.splice(node.body);
  3214. }
  3215. return node;
  3216. }
  3217. if (node instanceof AST_Scope) {
  3218. var save_scope = scope;
  3219. scope = node;
  3220. descend(node, this);
  3221. scope = save_scope;
  3222. return node;
  3223. }
  3224. function template(sym) {
  3225. return {
  3226. name : sym.name,
  3227. file : sym.start.file,
  3228. line : sym.start.line,
  3229. col : sym.start.col
  3230. };
  3231. }
  3232. }
  3233. );
  3234. self.transform(tt);
  3235. function scan_ref_scoped(node, descend) {
  3236. var node_def, sym = assign_as_unused(node);
  3237. if (sym instanceof AST_SymbolRef
  3238. && !is_ref_of(node.left, AST_SymbolBlockDeclaration)
  3239. && self.variables.get(sym.name) === (node_def = sym.definition())) {
  3240. if (node instanceof AST_Assign) {
  3241. node.right.walk(tw);
  3242. if (node.left.fixed_value() === node.right) {
  3243. fixed_ids[node_def.id] = node;
  3244. }
  3245. }
  3246. return true;
  3247. }
  3248. if (node instanceof AST_SymbolRef) {
  3249. node_def = node.definition();
  3250. if (!(node_def.id in in_use_ids)) {
  3251. in_use_ids[node_def.id] = true;
  3252. in_use.push(node_def);
  3253. if (node_def = node_def.redefined()) {
  3254. in_use_ids[node_def.id] = true;
  3255. in_use.push(node_def);
  3256. }
  3257. }
  3258. return true;
  3259. }
  3260. if (node instanceof AST_Scope) {
  3261. var save_scope = scope;
  3262. scope = node;
  3263. descend();
  3264. scope = save_scope;
  3265. return true;
  3266. }
  3267. }
  3268. });
  3269. AST_Scope.DEFMETHOD("hoist_declarations", function(compressor){
  3270. var self = this;
  3271. if (compressor.has_directive("use asm")) return self;
  3272. // Hoisting makes no sense in an arrow func
  3273. if (!Array.isArray(self.body)) return self;
  3274. var hoist_funs = compressor.option("hoist_funs");
  3275. var hoist_vars = compressor.option("hoist_vars");
  3276. if (hoist_funs || hoist_vars) {
  3277. var dirs = [];
  3278. var hoisted = [];
  3279. var vars = new Dictionary(), vars_found = 0, var_decl = 0;
  3280. // let's count var_decl first, we seem to waste a lot of
  3281. // space if we hoist `var` when there's only one.
  3282. self.walk(new TreeWalker(function(node){
  3283. if (node instanceof AST_Scope && node !== self)
  3284. return true;
  3285. if (node instanceof AST_Var) {
  3286. ++var_decl;
  3287. return true;
  3288. }
  3289. }));
  3290. hoist_vars = hoist_vars && var_decl > 1;
  3291. var tt = new TreeTransformer(
  3292. function before(node) {
  3293. if (node !== self) {
  3294. if (node instanceof AST_Directive) {
  3295. dirs.push(node);
  3296. return make_node(AST_EmptyStatement, node);
  3297. }
  3298. if (hoist_funs && node instanceof AST_Defun
  3299. && !(tt.parent() instanceof AST_Export)
  3300. && tt.parent() === self) {
  3301. hoisted.push(node);
  3302. return make_node(AST_EmptyStatement, node);
  3303. }
  3304. if (hoist_vars && node instanceof AST_Var) {
  3305. node.definitions.forEach(function(def){
  3306. if (def.name instanceof AST_Destructuring) return;
  3307. vars.set(def.name.name, def);
  3308. ++vars_found;
  3309. });
  3310. var seq = node.to_assignments(compressor);
  3311. var p = tt.parent();
  3312. if (p instanceof AST_ForIn && p.init === node) {
  3313. if (seq == null) {
  3314. var def = node.definitions[0].name;
  3315. return make_node(AST_SymbolRef, def, def);
  3316. }
  3317. return seq;
  3318. }
  3319. if (p instanceof AST_For && p.init === node) {
  3320. return seq;
  3321. }
  3322. if (!seq) return make_node(AST_EmptyStatement, node);
  3323. return make_node(AST_SimpleStatement, node, {
  3324. body: seq
  3325. });
  3326. }
  3327. if (node instanceof AST_Scope)
  3328. return node; // to avoid descending in nested scopes
  3329. }
  3330. }
  3331. );
  3332. self = self.transform(tt);
  3333. if (vars_found > 0) {
  3334. // collect only vars which don't show up in self's arguments list
  3335. var defs = [];
  3336. vars.each(function(def, name){
  3337. if (self instanceof AST_Lambda
  3338. && find_if(function(x){ return x.name == def.name.name },
  3339. self.args_as_names())) {
  3340. vars.del(name);
  3341. } else {
  3342. def = def.clone();
  3343. def.value = null;
  3344. defs.push(def);
  3345. vars.set(name, def);
  3346. }
  3347. });
  3348. if (defs.length > 0) {
  3349. // try to merge in assignments
  3350. for (var i = 0; i < self.body.length;) {
  3351. if (self.body[i] instanceof AST_SimpleStatement) {
  3352. var expr = self.body[i].body, sym, assign;
  3353. if (expr instanceof AST_Assign
  3354. && expr.operator == "="
  3355. && (sym = expr.left) instanceof AST_Symbol
  3356. && vars.has(sym.name))
  3357. {
  3358. var def = vars.get(sym.name);
  3359. if (def.value) break;
  3360. def.value = expr.right;
  3361. remove(defs, def);
  3362. defs.push(def);
  3363. self.body.splice(i, 1);
  3364. continue;
  3365. }
  3366. if (expr instanceof AST_Sequence
  3367. && (assign = expr.expressions[0]) instanceof AST_Assign
  3368. && assign.operator == "="
  3369. && (sym = assign.left) instanceof AST_Symbol
  3370. && vars.has(sym.name))
  3371. {
  3372. var def = vars.get(sym.name);
  3373. if (def.value) break;
  3374. def.value = assign.right;
  3375. remove(defs, def);
  3376. defs.push(def);
  3377. self.body[i].body = make_sequence(expr, expr.expressions.slice(1));
  3378. continue;
  3379. }
  3380. }
  3381. if (self.body[i] instanceof AST_EmptyStatement) {
  3382. self.body.splice(i, 1);
  3383. continue;
  3384. }
  3385. if (self.body[i] instanceof AST_BlockStatement) {
  3386. var tmp = [ i, 1 ].concat(self.body[i].body);
  3387. self.body.splice.apply(self.body, tmp);
  3388. continue;
  3389. }
  3390. break;
  3391. }
  3392. defs = make_node(AST_Var, self, {
  3393. definitions: defs
  3394. });
  3395. hoisted.push(defs);
  3396. };
  3397. }
  3398. self.body = dirs.concat(hoisted, self.body);
  3399. }
  3400. return self;
  3401. });
  3402. AST_Scope.DEFMETHOD("var_names", function() {
  3403. var var_names = this._var_names;
  3404. if (!var_names) {
  3405. this._var_names = var_names = Object.create(null);
  3406. this.enclosed.forEach(function(def) {
  3407. var_names[def.name] = true;
  3408. });
  3409. this.variables.each(function(def, name) {
  3410. var_names[name] = true;
  3411. });
  3412. }
  3413. return var_names;
  3414. });
  3415. AST_Scope.DEFMETHOD("make_var_name", function(prefix) {
  3416. var var_names = this.var_names();
  3417. prefix = prefix.replace(/[^a-z_$]+/ig, "_");
  3418. var name = prefix;
  3419. for (var i = 0; var_names[name]; i++) name = prefix + "$" + i;
  3420. var_names[name] = true;
  3421. return name;
  3422. });
  3423. AST_Scope.DEFMETHOD("hoist_properties", function(compressor){
  3424. var self = this;
  3425. if (!compressor.option("hoist_props") || compressor.has_directive("use asm")) return self;
  3426. var top_retain = self instanceof AST_Toplevel && compressor.top_retain || return_false;
  3427. var defs_by_id = Object.create(null);
  3428. var tt = new TreeTransformer(function(node, descend) {
  3429. if (node instanceof AST_Definitions && tt.parent() instanceof AST_Export) return node;
  3430. if (node instanceof AST_VarDef) {
  3431. var sym = node.name, def, value;
  3432. if (sym.scope === self
  3433. && (def = sym.definition()).escaped != 1
  3434. && !def.single_use
  3435. && !def.direct_access
  3436. && !compressor.exposed(def)
  3437. && !top_retain(def)
  3438. && (value = sym.fixed_value()) === node.value
  3439. && value instanceof AST_Object) {
  3440. descend(node, this);
  3441. var defs = new Dictionary();
  3442. var assignments = [];
  3443. value.properties.forEach(function(prop) {
  3444. assignments.push(make_node(AST_VarDef, node, {
  3445. name: make_sym(prop.key),
  3446. value: prop.value
  3447. }));
  3448. });
  3449. defs_by_id[def.id] = defs;
  3450. return MAP.splice(assignments);
  3451. }
  3452. }
  3453. if (node instanceof AST_PropAccess && node.expression instanceof AST_SymbolRef) {
  3454. var defs = defs_by_id[node.expression.definition().id];
  3455. if (defs) {
  3456. var def = defs.get(get_value(node.property));
  3457. var sym = make_node(AST_SymbolRef, node, {
  3458. name: def.name,
  3459. scope: node.expression.scope,
  3460. thedef: def
  3461. });
  3462. sym.reference({});
  3463. return sym;
  3464. }
  3465. }
  3466. function make_sym(key) {
  3467. var new_var = make_node(sym.CTOR, sym, {
  3468. name: self.make_var_name(sym.name + "_" + key),
  3469. scope: self
  3470. });
  3471. var def = self.def_variable(new_var);
  3472. defs.set(key, def);
  3473. self.enclosed.push(def);
  3474. return new_var;
  3475. }
  3476. });
  3477. return self.transform(tt);
  3478. });
  3479. // drop_side_effect_free()
  3480. // remove side-effect-free parts which only affects return value
  3481. (function(def){
  3482. // Drop side-effect-free elements from an array of expressions.
  3483. // Returns an array of expressions with side-effects or null
  3484. // if all elements were dropped. Note: original array may be
  3485. // returned if nothing changed.
  3486. function trim(nodes, compressor, first_in_statement) {
  3487. var len = nodes.length;
  3488. if (!len) return null;
  3489. var ret = [], changed = false;
  3490. for (var i = 0; i < len; i++) {
  3491. var node = nodes[i].drop_side_effect_free(compressor, first_in_statement);
  3492. changed |= node !== nodes[i];
  3493. if (node) {
  3494. ret.push(node);
  3495. first_in_statement = false;
  3496. }
  3497. }
  3498. return changed ? ret.length ? ret : null : nodes;
  3499. }
  3500. def(AST_Node, return_this);
  3501. def(AST_Constant, return_null);
  3502. def(AST_This, return_null);
  3503. def(AST_Call, function(compressor, first_in_statement){
  3504. if (!this.is_expr_pure(compressor)) {
  3505. if (this.expression.is_call_pure(compressor)) {
  3506. var exprs = this.args.slice();
  3507. exprs.unshift(this.expression.expression);
  3508. exprs = trim(exprs, compressor, first_in_statement);
  3509. return exprs && make_sequence(this, exprs);
  3510. }
  3511. if (is_func_expr(this.expression)
  3512. && (!this.expression.name || !this.expression.name.definition().references.length)) {
  3513. var node = this.clone();
  3514. node.expression.process_expression(false, compressor);
  3515. return node;
  3516. }
  3517. return this;
  3518. }
  3519. if (this.pure) {
  3520. compressor.warn("Dropping __PURE__ call [{file}:{line},{col}]", this.start);
  3521. }
  3522. var args = trim(this.args, compressor, first_in_statement);
  3523. return args && make_sequence(this, args);
  3524. });
  3525. def(AST_Accessor, return_null);
  3526. def(AST_Function, return_null);
  3527. def(AST_Arrow, return_null);
  3528. def(AST_ClassExpression, return_null);
  3529. def(AST_Binary, function(compressor, first_in_statement){
  3530. var right = this.right.drop_side_effect_free(compressor);
  3531. if (!right) return this.left.drop_side_effect_free(compressor, first_in_statement);
  3532. if (lazy_op(this.operator)) {
  3533. if (right === this.right) return this;
  3534. var node = this.clone();
  3535. node.right = right;
  3536. return node;
  3537. } else {
  3538. var left = this.left.drop_side_effect_free(compressor, first_in_statement);
  3539. if (!left) return this.right.drop_side_effect_free(compressor, first_in_statement);
  3540. return make_sequence(this, [ left, right ]);
  3541. }
  3542. });
  3543. def(AST_Assign, function(compressor){
  3544. var left = this.left;
  3545. if (left.has_side_effects(compressor)
  3546. || compressor.has_directive("use strict")
  3547. && left instanceof AST_PropAccess
  3548. && left.expression.is_constant()) {
  3549. return this;
  3550. }
  3551. this.write_only = true;
  3552. while (left instanceof AST_PropAccess) {
  3553. left = left.expression;
  3554. }
  3555. if (left.is_constant_expression(compressor.find_parent(AST_Scope))) {
  3556. return this.right.drop_side_effect_free(compressor);
  3557. }
  3558. return this;
  3559. });
  3560. def(AST_Conditional, function(compressor){
  3561. var consequent = this.consequent.drop_side_effect_free(compressor);
  3562. var alternative = this.alternative.drop_side_effect_free(compressor);
  3563. if (consequent === this.consequent && alternative === this.alternative) return this;
  3564. if (!consequent) return alternative ? make_node(AST_Binary, this, {
  3565. operator: "||",
  3566. left: this.condition,
  3567. right: alternative
  3568. }) : this.condition.drop_side_effect_free(compressor);
  3569. if (!alternative) return make_node(AST_Binary, this, {
  3570. operator: "&&",
  3571. left: this.condition,
  3572. right: consequent
  3573. });
  3574. var node = this.clone();
  3575. node.consequent = consequent;
  3576. node.alternative = alternative;
  3577. return node;
  3578. });
  3579. def(AST_Unary, function(compressor, first_in_statement){
  3580. if (unary_side_effects(this.operator)) {
  3581. this.write_only = !this.expression.has_side_effects(compressor);
  3582. return this;
  3583. }
  3584. if (this.operator == "typeof" && this.expression instanceof AST_SymbolRef) return null;
  3585. var expression = this.expression.drop_side_effect_free(compressor, first_in_statement);
  3586. if (first_in_statement && expression && is_iife_call(expression)) {
  3587. if (expression === this.expression && this.operator == "!") return this;
  3588. return expression.negate(compressor, first_in_statement);
  3589. }
  3590. return expression;
  3591. });
  3592. def(AST_SymbolRef, function(compressor) {
  3593. return this.is_declared(compressor) ? null : this;
  3594. });
  3595. def(AST_Object, function(compressor, first_in_statement){
  3596. var values = trim(this.properties, compressor, first_in_statement);
  3597. return values && make_sequence(this, values);
  3598. });
  3599. def(AST_ObjectProperty, function(compressor, first_in_statement){
  3600. return this.value.drop_side_effect_free(compressor, first_in_statement);
  3601. });
  3602. def(AST_Array, function(compressor, first_in_statement){
  3603. var values = trim(this.elements, compressor, first_in_statement);
  3604. return values && make_sequence(this, values);
  3605. });
  3606. def(AST_Dot, function(compressor, first_in_statement){
  3607. if (this.expression.may_throw_on_access(compressor)) return this;
  3608. return this.expression.drop_side_effect_free(compressor, first_in_statement);
  3609. });
  3610. def(AST_Sub, function(compressor, first_in_statement){
  3611. if (this.expression.may_throw_on_access(compressor)) return this;
  3612. var expression = this.expression.drop_side_effect_free(compressor, first_in_statement);
  3613. if (!expression) return this.property.drop_side_effect_free(compressor, first_in_statement);
  3614. var property = this.property.drop_side_effect_free(compressor);
  3615. if (!property) return expression;
  3616. return make_sequence(this, [ expression, property ]);
  3617. });
  3618. def(AST_Sequence, function(compressor){
  3619. var last = this.tail_node();
  3620. var expr = last.drop_side_effect_free(compressor);
  3621. if (expr === last) return this;
  3622. var expressions = this.expressions.slice(0, -1);
  3623. if (expr) expressions.push(expr);
  3624. return make_sequence(this, expressions);
  3625. });
  3626. def(AST_Expansion, function(compressor, first_in_statement){
  3627. return this.expression.drop_side_effect_free(compressor, first_in_statement);
  3628. });
  3629. def(AST_TemplateSegment, return_null);
  3630. def(AST_TemplateString, function(compressor){
  3631. var values = trim(this.segments, compressor, first_in_statement);
  3632. return values && make_sequence(this, values);
  3633. });
  3634. })(function(node, func){
  3635. node.DEFMETHOD("drop_side_effect_free", func);
  3636. });
  3637. OPT(AST_SimpleStatement, function(self, compressor){
  3638. if (compressor.option("side_effects")) {
  3639. var body = self.body;
  3640. var node = body.drop_side_effect_free(compressor, true);
  3641. if (!node) {
  3642. compressor.warn("Dropping side-effect-free statement [{file}:{line},{col}]", self.start);
  3643. return make_node(AST_EmptyStatement, self);
  3644. }
  3645. if (node !== body) {
  3646. return make_node(AST_SimpleStatement, self, { body: node });
  3647. }
  3648. }
  3649. return self;
  3650. });
  3651. OPT(AST_While, function(self, compressor){
  3652. return compressor.option("loops") ? make_node(AST_For, self, self).optimize(compressor) : self;
  3653. });
  3654. OPT(AST_Do, function(self, compressor){
  3655. if (!compressor.option("loops")) return self;
  3656. var cond = self.condition.tail_node().evaluate(compressor);
  3657. if (!(cond instanceof AST_Node)) {
  3658. if (cond) return make_node(AST_For, self, {
  3659. body: make_node(AST_BlockStatement, self.body, {
  3660. body: [
  3661. self.body,
  3662. make_node(AST_SimpleStatement, self.condition, {
  3663. body: self.condition
  3664. })
  3665. ]
  3666. })
  3667. }).optimize(compressor);
  3668. var has_loop_control = false;
  3669. var tw = new TreeWalker(function(node) {
  3670. if (node instanceof AST_Scope || has_loop_control) return true;
  3671. if (node instanceof AST_LoopControl && tw.loopcontrol_target(node) === self)
  3672. return has_loop_control = true;
  3673. });
  3674. var parent = compressor.parent();
  3675. (parent instanceof AST_LabeledStatement ? parent : self).walk(tw);
  3676. if (!has_loop_control) return make_node(AST_BlockStatement, self.body, {
  3677. body: [
  3678. self.body,
  3679. make_node(AST_SimpleStatement, self.condition, {
  3680. body: self.condition
  3681. })
  3682. ]
  3683. }).optimize(compressor);
  3684. }
  3685. return self;
  3686. });
  3687. function if_break_in_loop(self, compressor) {
  3688. var first = self.body instanceof AST_BlockStatement ? self.body.body[0] : self.body;
  3689. if (compressor.option("dead_code") && is_break(first)) {
  3690. var body = [];
  3691. if (self.init instanceof AST_Statement) {
  3692. body.push(self.init);
  3693. } else if (self.init) {
  3694. body.push(make_node(AST_SimpleStatement, self.init, {
  3695. body: self.init
  3696. }));
  3697. }
  3698. if (self.condition) {
  3699. body.push(make_node(AST_SimpleStatement, self.condition, {
  3700. body: self.condition
  3701. }));
  3702. }
  3703. extract_declarations_from_unreachable_code(compressor, self.body, body);
  3704. return make_node(AST_BlockStatement, self, {
  3705. body: body
  3706. });
  3707. }
  3708. if (first instanceof AST_If) {
  3709. if (is_break(first.body)) {
  3710. if (self.condition) {
  3711. self.condition = make_node(AST_Binary, self.condition, {
  3712. left: self.condition,
  3713. operator: "&&",
  3714. right: first.condition.negate(compressor),
  3715. });
  3716. } else {
  3717. self.condition = first.condition.negate(compressor);
  3718. }
  3719. drop_it(first.alternative);
  3720. } else if (is_break(first.alternative)) {
  3721. if (self.condition) {
  3722. self.condition = make_node(AST_Binary, self.condition, {
  3723. left: self.condition,
  3724. operator: "&&",
  3725. right: first.condition,
  3726. });
  3727. } else {
  3728. self.condition = first.condition;
  3729. }
  3730. drop_it(first.body);
  3731. }
  3732. }
  3733. return self;
  3734. function is_break(node) {
  3735. return node instanceof AST_Break
  3736. && compressor.loopcontrol_target(node) === compressor.self();
  3737. }
  3738. function drop_it(rest) {
  3739. rest = as_statement_array(rest);
  3740. if (self.body instanceof AST_BlockStatement) {
  3741. self.body = self.body.clone();
  3742. self.body.body = rest.concat(self.body.body.slice(1));
  3743. self.body = self.body.transform(compressor);
  3744. } else {
  3745. self.body = make_node(AST_BlockStatement, self.body, {
  3746. body: rest
  3747. }).transform(compressor);
  3748. }
  3749. self = if_break_in_loop(self, compressor);
  3750. }
  3751. }
  3752. OPT(AST_For, function(self, compressor){
  3753. if (!compressor.option("loops")) return self;
  3754. if (compressor.option("side_effects") && self.init) {
  3755. self.init = self.init.drop_side_effect_free(compressor);
  3756. }
  3757. if (self.condition) {
  3758. var cond = self.condition.evaluate(compressor);
  3759. if (!(cond instanceof AST_Node)) {
  3760. if (cond) self.condition = null;
  3761. else if (!compressor.option("dead_code")) {
  3762. var orig = self.condition;
  3763. self.condition = make_node_from_constant(cond, self.condition);
  3764. self.condition = best_of_expression(self.condition.transform(compressor), orig);
  3765. }
  3766. }
  3767. if (compressor.option("dead_code")) {
  3768. if (cond instanceof AST_Node) cond = self.condition.tail_node().evaluate(compressor);
  3769. if (!cond) {
  3770. var body = [];
  3771. extract_declarations_from_unreachable_code(compressor, self.body, body);
  3772. if (self.init instanceof AST_Statement) {
  3773. body.push(self.init);
  3774. } else if (self.init) {
  3775. body.push(make_node(AST_SimpleStatement, self.init, {
  3776. body: self.init
  3777. }));
  3778. }
  3779. body.push(make_node(AST_SimpleStatement, self.condition, {
  3780. body: self.condition
  3781. }));
  3782. return make_node(AST_BlockStatement, self, { body: body }).optimize(compressor);
  3783. }
  3784. }
  3785. }
  3786. return if_break_in_loop(self, compressor);
  3787. });
  3788. OPT(AST_If, function(self, compressor){
  3789. if (is_empty(self.alternative)) self.alternative = null;
  3790. if (!compressor.option("conditionals")) return self;
  3791. // if condition can be statically determined, warn and drop
  3792. // one of the blocks. note, statically determined implies
  3793. // “has no side effects”; also it doesn't work for cases like
  3794. // `x && true`, though it probably should.
  3795. var cond = self.condition.evaluate(compressor);
  3796. if (!compressor.option("dead_code") && !(cond instanceof AST_Node)) {
  3797. var orig = self.condition;
  3798. self.condition = make_node_from_constant(cond, orig);
  3799. self.condition = best_of_expression(self.condition.transform(compressor), orig);
  3800. }
  3801. if (compressor.option("dead_code")) {
  3802. if (cond instanceof AST_Node) cond = self.condition.tail_node().evaluate(compressor);
  3803. if (!cond) {
  3804. compressor.warn("Condition always false [{file}:{line},{col}]", self.condition.start);
  3805. var body = [];
  3806. extract_declarations_from_unreachable_code(compressor, self.body, body);
  3807. body.push(make_node(AST_SimpleStatement, self.condition, {
  3808. body: self.condition
  3809. }));
  3810. if (self.alternative) body.push(self.alternative);
  3811. return make_node(AST_BlockStatement, self, { body: body }).optimize(compressor);
  3812. } else if (!(cond instanceof AST_Node)) {
  3813. compressor.warn("Condition always true [{file}:{line},{col}]", self.condition.start);
  3814. var body = [];
  3815. if (self.alternative) {
  3816. extract_declarations_from_unreachable_code(compressor, self.alternative, body);
  3817. }
  3818. body.push(make_node(AST_SimpleStatement, self.condition, {
  3819. body: self.condition
  3820. }));
  3821. body.push(self.body);
  3822. return make_node(AST_BlockStatement, self, { body: body }).optimize(compressor);
  3823. }
  3824. }
  3825. var negated = self.condition.negate(compressor);
  3826. var self_condition_length = self.condition.print_to_string().length;
  3827. var negated_length = negated.print_to_string().length;
  3828. var negated_is_best = negated_length < self_condition_length;
  3829. if (self.alternative && negated_is_best) {
  3830. negated_is_best = false; // because we already do the switch here.
  3831. // no need to swap values of self_condition_length and negated_length
  3832. // here because they are only used in an equality comparison later on.
  3833. self.condition = negated;
  3834. var tmp = self.body;
  3835. self.body = self.alternative || make_node(AST_EmptyStatement, self);
  3836. self.alternative = tmp;
  3837. }
  3838. if (is_empty(self.body) && is_empty(self.alternative)) {
  3839. return make_node(AST_SimpleStatement, self.condition, {
  3840. body: self.condition.clone()
  3841. }).optimize(compressor);
  3842. }
  3843. if (self.body instanceof AST_SimpleStatement
  3844. && self.alternative instanceof AST_SimpleStatement) {
  3845. return make_node(AST_SimpleStatement, self, {
  3846. body: make_node(AST_Conditional, self, {
  3847. condition : self.condition,
  3848. consequent : self.body.body,
  3849. alternative : self.alternative.body
  3850. })
  3851. }).optimize(compressor);
  3852. }
  3853. if (is_empty(self.alternative) && self.body instanceof AST_SimpleStatement) {
  3854. if (self_condition_length === negated_length && !negated_is_best
  3855. && self.condition instanceof AST_Binary && self.condition.operator == "||") {
  3856. // although the code length of self.condition and negated are the same,
  3857. // negated does not require additional surrounding parentheses.
  3858. // see https://github.com/mishoo/UglifyJS2/issues/979
  3859. negated_is_best = true;
  3860. }
  3861. if (negated_is_best) return make_node(AST_SimpleStatement, self, {
  3862. body: make_node(AST_Binary, self, {
  3863. operator : "||",
  3864. left : negated,
  3865. right : self.body.body
  3866. })
  3867. }).optimize(compressor);
  3868. return make_node(AST_SimpleStatement, self, {
  3869. body: make_node(AST_Binary, self, {
  3870. operator : "&&",
  3871. left : self.condition,
  3872. right : self.body.body
  3873. })
  3874. }).optimize(compressor);
  3875. }
  3876. if (self.body instanceof AST_EmptyStatement
  3877. && self.alternative instanceof AST_SimpleStatement) {
  3878. return make_node(AST_SimpleStatement, self, {
  3879. body: make_node(AST_Binary, self, {
  3880. operator : "||",
  3881. left : self.condition,
  3882. right : self.alternative.body
  3883. })
  3884. }).optimize(compressor);
  3885. }
  3886. if (self.body instanceof AST_Exit
  3887. && self.alternative instanceof AST_Exit
  3888. && self.body.TYPE == self.alternative.TYPE) {
  3889. return make_node(self.body.CTOR, self, {
  3890. value: make_node(AST_Conditional, self, {
  3891. condition : self.condition,
  3892. consequent : self.body.value || make_node(AST_Undefined, self.body),
  3893. alternative : self.alternative.value || make_node(AST_Undefined, self.alternative)
  3894. }).transform(compressor)
  3895. }).optimize(compressor);
  3896. }
  3897. if (self.body instanceof AST_If
  3898. && !self.body.alternative
  3899. && !self.alternative) {
  3900. self = make_node(AST_If, self, {
  3901. condition: make_node(AST_Binary, self.condition, {
  3902. operator: "&&",
  3903. left: self.condition,
  3904. right: self.body.condition
  3905. }),
  3906. body: self.body.body,
  3907. alternative: null
  3908. });
  3909. }
  3910. if (aborts(self.body)) {
  3911. if (self.alternative) {
  3912. var alt = self.alternative;
  3913. self.alternative = null;
  3914. return make_node(AST_BlockStatement, self, {
  3915. body: [ self, alt ]
  3916. }).optimize(compressor);
  3917. }
  3918. }
  3919. if (aborts(self.alternative)) {
  3920. var body = self.body;
  3921. self.body = self.alternative;
  3922. self.condition = negated_is_best ? negated : self.condition.negate(compressor);
  3923. self.alternative = null;
  3924. return make_node(AST_BlockStatement, self, {
  3925. body: [ self, body ]
  3926. }).optimize(compressor);
  3927. }
  3928. return self;
  3929. });
  3930. OPT(AST_Switch, function(self, compressor){
  3931. if (!compressor.option("switches")) return self;
  3932. var branch;
  3933. var value = self.expression.evaluate(compressor);
  3934. if (!(value instanceof AST_Node)) {
  3935. var orig = self.expression;
  3936. self.expression = make_node_from_constant(value, orig);
  3937. self.expression = best_of_expression(self.expression.transform(compressor), orig);
  3938. }
  3939. if (!compressor.option("dead_code")) return self;
  3940. if (value instanceof AST_Node) {
  3941. value = self.expression.tail_node().evaluate(compressor);
  3942. }
  3943. var decl = [];
  3944. var body = [];
  3945. var default_branch;
  3946. var exact_match;
  3947. for (var i = 0, len = self.body.length; i < len && !exact_match; i++) {
  3948. branch = self.body[i];
  3949. if (branch instanceof AST_Default) {
  3950. if (!default_branch) {
  3951. default_branch = branch;
  3952. } else {
  3953. eliminate_branch(branch, body[body.length - 1]);
  3954. }
  3955. } else if (!(value instanceof AST_Node)) {
  3956. var exp = branch.expression.evaluate(compressor);
  3957. if (!(exp instanceof AST_Node) && exp !== value) {
  3958. eliminate_branch(branch, body[body.length - 1]);
  3959. continue;
  3960. }
  3961. if (exp instanceof AST_Node) exp = branch.expression.tail_node().evaluate(compressor);
  3962. if (exp === value) {
  3963. exact_match = branch;
  3964. if (default_branch) {
  3965. var default_index = body.indexOf(default_branch);
  3966. body.splice(default_index, 1);
  3967. eliminate_branch(default_branch, body[default_index - 1]);
  3968. default_branch = null;
  3969. }
  3970. }
  3971. }
  3972. if (aborts(branch)) {
  3973. var prev = body[body.length - 1];
  3974. if (aborts(prev) && prev.body.length == branch.body.length
  3975. && make_node(AST_BlockStatement, prev, prev).equivalent_to(make_node(AST_BlockStatement, branch, branch))) {
  3976. prev.body = [];
  3977. }
  3978. }
  3979. body.push(branch);
  3980. }
  3981. while (i < len) eliminate_branch(self.body[i++], body[body.length - 1]);
  3982. if (body.length > 0) {
  3983. body[0].body = decl.concat(body[0].body);
  3984. }
  3985. self.body = body;
  3986. while (branch = body[body.length - 1]) {
  3987. var stat = branch.body[branch.body.length - 1];
  3988. if (stat instanceof AST_Break && compressor.loopcontrol_target(stat) === self)
  3989. branch.body.pop();
  3990. if (branch.body.length || branch instanceof AST_Case
  3991. && (default_branch || branch.expression.has_side_effects(compressor))) break;
  3992. if (body.pop() === default_branch) default_branch = null;
  3993. }
  3994. if (body.length == 0) {
  3995. return make_node(AST_BlockStatement, self, {
  3996. body: decl.concat(make_node(AST_SimpleStatement, self.expression, {
  3997. body: self.expression
  3998. }))
  3999. }).optimize(compressor);
  4000. }
  4001. if (body.length == 1 && (body[0] === exact_match || body[0] === default_branch)) {
  4002. var has_break = false;
  4003. var tw = new TreeWalker(function(node) {
  4004. if (has_break
  4005. || node instanceof AST_Lambda
  4006. || node instanceof AST_SimpleStatement) return true;
  4007. if (node instanceof AST_Break && tw.loopcontrol_target(node) === self)
  4008. has_break = true;
  4009. });
  4010. self.walk(tw);
  4011. if (!has_break) {
  4012. var statements = body[0].body.slice();
  4013. var exp = body[0].expression;
  4014. if (exp) statements.unshift(make_node(AST_SimpleStatement, exp, {
  4015. body: exp
  4016. }));
  4017. statements.unshift(make_node(AST_SimpleStatement, self.expression, {
  4018. body:self.expression
  4019. }));
  4020. return make_node(AST_BlockStatement, self, {
  4021. body: statements
  4022. }).optimize(compressor);
  4023. }
  4024. }
  4025. return self;
  4026. function eliminate_branch(branch, prev) {
  4027. if (prev && !aborts(prev)) {
  4028. prev.body = prev.body.concat(branch.body);
  4029. } else {
  4030. extract_declarations_from_unreachable_code(compressor, branch, decl);
  4031. }
  4032. }
  4033. });
  4034. OPT(AST_Try, function(self, compressor){
  4035. tighten_body(self.body, compressor);
  4036. if (self.bcatch && self.bfinally && all(self.bfinally.body, is_empty)) self.bfinally = null;
  4037. if (compressor.option("dead_code") && all(self.body, is_empty)) {
  4038. var body = [];
  4039. if (self.bcatch) {
  4040. extract_declarations_from_unreachable_code(compressor, self.bcatch, body);
  4041. body.forEach(function(stat) {
  4042. if (!(stat instanceof AST_Definitions)) return;
  4043. stat.definitions.forEach(function(var_def) {
  4044. var def = var_def.name.definition().redefined();
  4045. if (!def) return;
  4046. var_def.name = var_def.name.clone();
  4047. var_def.name.thedef = def;
  4048. });
  4049. });
  4050. }
  4051. if (self.bfinally) body = body.concat(self.bfinally.body);
  4052. return make_node(AST_BlockStatement, self, {
  4053. body: body
  4054. }).optimize(compressor);
  4055. }
  4056. return self;
  4057. });
  4058. AST_Definitions.DEFMETHOD("remove_initializers", function(){
  4059. var decls = [];
  4060. this.definitions.forEach(function(def) {
  4061. if (def.name instanceof AST_SymbolDeclaration) {
  4062. def.value = null;
  4063. decls.push(def);
  4064. } else def.name.walk(new TreeWalker(function(node) {
  4065. if (node instanceof AST_SymbolDeclaration) {
  4066. decls.push(make_node(AST_VarDef, def, {
  4067. name: node,
  4068. value: null
  4069. }));
  4070. }
  4071. }));
  4072. });
  4073. this.definitions = decls;
  4074. });
  4075. AST_Definitions.DEFMETHOD("to_assignments", function(compressor){
  4076. var reduce_vars = compressor.option("reduce_vars");
  4077. var assignments = this.definitions.reduce(function(a, def){
  4078. if (def.value && !(def.name instanceof AST_Destructuring)) {
  4079. var name = make_node(AST_SymbolRef, def.name, def.name);
  4080. a.push(make_node(AST_Assign, def, {
  4081. operator : "=",
  4082. left : name,
  4083. right : def.value
  4084. }));
  4085. if (reduce_vars) name.definition().fixed = false;
  4086. } else if (def.value) {
  4087. // Because it's a destructuring, do not turn into an assignment.
  4088. var varDef = make_node(AST_VarDef, def, {
  4089. name: def.name,
  4090. value: def.value
  4091. });
  4092. var var_ = make_node(AST_Var, def, {
  4093. definitions: [ varDef ]
  4094. });
  4095. a.push(var_);
  4096. }
  4097. def = def.name.definition();
  4098. def.eliminated++;
  4099. def.replaced--;
  4100. return a;
  4101. }, []);
  4102. if (assignments.length == 0) return null;
  4103. return make_sequence(this, assignments);
  4104. });
  4105. OPT(AST_Definitions, function(self, compressor){
  4106. if (self.definitions.length == 0)
  4107. return make_node(AST_EmptyStatement, self);
  4108. return self;
  4109. });
  4110. OPT(AST_Import, function(self, compressor) {
  4111. return self;
  4112. });
  4113. OPT(AST_Call, function(self, compressor){
  4114. var exp = self.expression;
  4115. var fn = exp;
  4116. var simple_args = all(self.args, function(arg) {
  4117. return !(arg instanceof AST_Expansion);
  4118. });
  4119. if (compressor.option("reduce_vars") && fn instanceof AST_SymbolRef) {
  4120. fn = fn.fixed_value();
  4121. }
  4122. var is_func = fn instanceof AST_Lambda;
  4123. if (compressor.option("unused")
  4124. && simple_args
  4125. && is_func
  4126. && !fn.uses_arguments
  4127. && !fn.uses_eval) {
  4128. var pos = 0, last = 0;
  4129. for (var i = 0, len = self.args.length; i < len; i++) {
  4130. if (fn.argnames[i] instanceof AST_Expansion) {
  4131. if (fn.argnames[i].expression.__unused) while (i < len) {
  4132. var node = self.args[i++].drop_side_effect_free(compressor);
  4133. if (node) {
  4134. self.args[pos++] = node;
  4135. }
  4136. } else while (i < len) {
  4137. self.args[pos++] = self.args[i++];
  4138. }
  4139. last = pos;
  4140. break;
  4141. }
  4142. var trim = i >= fn.argnames.length;
  4143. if (trim || fn.argnames[i].__unused) {
  4144. var node = self.args[i].drop_side_effect_free(compressor);
  4145. if (node) {
  4146. self.args[pos++] = node;
  4147. } else if (!trim) {
  4148. self.args[pos++] = make_node(AST_Number, self.args[i], {
  4149. value: 0
  4150. });
  4151. continue;
  4152. }
  4153. } else {
  4154. self.args[pos++] = self.args[i];
  4155. }
  4156. last = pos;
  4157. }
  4158. self.args.length = last;
  4159. }
  4160. if (compressor.option("unsafe")) {
  4161. if (is_undeclared_ref(exp)) switch (exp.name) {
  4162. case "Array":
  4163. if (self.args.length != 1) {
  4164. return make_node(AST_Array, self, {
  4165. elements: self.args
  4166. }).optimize(compressor);
  4167. }
  4168. break;
  4169. case "Object":
  4170. if (self.args.length == 0) {
  4171. return make_node(AST_Object, self, {
  4172. properties: []
  4173. });
  4174. }
  4175. break;
  4176. case "String":
  4177. if (self.args.length == 0) return make_node(AST_String, self, {
  4178. value: ""
  4179. });
  4180. if (self.args.length <= 1) return make_node(AST_Binary, self, {
  4181. left: self.args[0],
  4182. operator: "+",
  4183. right: make_node(AST_String, self, { value: "" })
  4184. }).optimize(compressor);
  4185. break;
  4186. case "Number":
  4187. if (self.args.length == 0) return make_node(AST_Number, self, {
  4188. value: 0
  4189. });
  4190. if (self.args.length == 1) return make_node(AST_UnaryPrefix, self, {
  4191. expression: self.args[0],
  4192. operator: "+"
  4193. }).optimize(compressor);
  4194. case "Boolean":
  4195. if (self.args.length == 0) return make_node(AST_False, self);
  4196. if (self.args.length == 1) return make_node(AST_UnaryPrefix, self, {
  4197. expression: make_node(AST_UnaryPrefix, self, {
  4198. expression: self.args[0],
  4199. operator: "!"
  4200. }),
  4201. operator: "!"
  4202. }).optimize(compressor);
  4203. break;
  4204. case "RegExp":
  4205. var params = [];
  4206. if (all(self.args, function(arg) {
  4207. var value = arg.evaluate(compressor);
  4208. params.unshift(value);
  4209. return arg !== value;
  4210. })) {
  4211. try {
  4212. return best_of(compressor, self, make_node(AST_RegExp, self, {
  4213. value: RegExp.apply(RegExp, params),
  4214. }));
  4215. } catch (ex) {
  4216. compressor.warn("Error converting {expr} [{file}:{line},{col}]", {
  4217. expr: self.print_to_string(),
  4218. file: self.start.file,
  4219. line: self.start.line,
  4220. col: self.start.col
  4221. });
  4222. }
  4223. }
  4224. break;
  4225. case "Symbol":
  4226. // Symbol's argument is only used for debugging.
  4227. self.args = [];
  4228. return self;
  4229. } else if (exp instanceof AST_Dot) switch(exp.property) {
  4230. case "toString":
  4231. if (self.args.length == 0 && !exp.expression.may_throw_on_access(compressor)) {
  4232. return make_node(AST_Binary, self, {
  4233. left: make_node(AST_String, self, { value: "" }),
  4234. operator: "+",
  4235. right: exp.expression
  4236. }).optimize(compressor);
  4237. }
  4238. break;
  4239. case "join":
  4240. if (exp.expression instanceof AST_Array) EXIT: {
  4241. var separator;
  4242. if (self.args.length > 0) {
  4243. separator = self.args[0].evaluate(compressor);
  4244. if (separator === self.args[0]) break EXIT; // not a constant
  4245. }
  4246. var elements = [];
  4247. var consts = [];
  4248. for (var i = 0, len = exp.expression.elements.length; i < len; i++) {
  4249. var el = exp.expression.elements[i];
  4250. if (el instanceof AST_Expansion) break EXIT;
  4251. var value = el.evaluate(compressor);
  4252. if (value !== el) {
  4253. consts.push(value);
  4254. } else {
  4255. if (consts.length > 0) {
  4256. elements.push(make_node(AST_String, self, {
  4257. value: consts.join(separator)
  4258. }));
  4259. consts.length = 0;
  4260. }
  4261. elements.push(el);
  4262. }
  4263. }
  4264. if (consts.length > 0) {
  4265. elements.push(make_node(AST_String, self, {
  4266. value: consts.join(separator)
  4267. }));
  4268. }
  4269. if (elements.length == 0) return make_node(AST_String, self, { value: "" });
  4270. if (elements.length == 1) {
  4271. if (elements[0].is_string(compressor)) {
  4272. return elements[0];
  4273. }
  4274. return make_node(AST_Binary, elements[0], {
  4275. operator : "+",
  4276. left : make_node(AST_String, self, { value: "" }),
  4277. right : elements[0]
  4278. });
  4279. }
  4280. if (separator == "") {
  4281. var first;
  4282. if (elements[0].is_string(compressor)
  4283. || elements[1].is_string(compressor)) {
  4284. first = elements.shift();
  4285. } else {
  4286. first = make_node(AST_String, self, { value: "" });
  4287. }
  4288. return elements.reduce(function(prev, el){
  4289. return make_node(AST_Binary, el, {
  4290. operator : "+",
  4291. left : prev,
  4292. right : el
  4293. });
  4294. }, first).optimize(compressor);
  4295. }
  4296. // need this awkward cloning to not affect original element
  4297. // best_of will decide which one to get through.
  4298. var node = self.clone();
  4299. node.expression = node.expression.clone();
  4300. node.expression.expression = node.expression.expression.clone();
  4301. node.expression.expression.elements = elements;
  4302. return best_of(compressor, self, node);
  4303. }
  4304. break;
  4305. case "charAt":
  4306. if (exp.expression.is_string(compressor)) {
  4307. var arg = self.args[0];
  4308. var index = arg ? arg.evaluate(compressor) : 0;
  4309. if (index !== arg) {
  4310. return make_node(AST_Sub, exp, {
  4311. expression: exp.expression,
  4312. property: make_node_from_constant(index | 0, arg || exp)
  4313. }).optimize(compressor);
  4314. }
  4315. }
  4316. break;
  4317. case "apply":
  4318. if (self.args.length == 2 && self.args[1] instanceof AST_Array) {
  4319. var args = self.args[1].elements.slice();
  4320. args.unshift(self.args[0]);
  4321. return make_node(AST_Call, self, {
  4322. expression: make_node(AST_Dot, exp, {
  4323. expression: exp.expression,
  4324. property: "call"
  4325. }),
  4326. args: args
  4327. }).optimize(compressor);
  4328. }
  4329. break;
  4330. case "call":
  4331. var func = exp.expression;
  4332. if (func instanceof AST_SymbolRef) {
  4333. func = func.fixed_value();
  4334. }
  4335. if (func instanceof AST_Lambda && !func.contains_this()) {
  4336. return make_sequence(this, [
  4337. self.args[0],
  4338. make_node(AST_Call, self, {
  4339. expression: exp.expression,
  4340. args: self.args.slice(1)
  4341. })
  4342. ]).optimize(compressor);
  4343. }
  4344. break;
  4345. }
  4346. }
  4347. if (compressor.option("unsafe_Function")
  4348. && is_undeclared_ref(exp)
  4349. && exp.name == "Function") {
  4350. // new Function() => function(){}
  4351. if (self.args.length == 0) return make_node(AST_Function, self, {
  4352. argnames: [],
  4353. body: []
  4354. }).optimize(compressor);
  4355. if (all(self.args, function(x) {
  4356. return x instanceof AST_String;
  4357. })) {
  4358. // quite a corner-case, but we can handle it:
  4359. // https://github.com/mishoo/UglifyJS2/issues/203
  4360. // if the code argument is a constant, then we can minify it.
  4361. try {
  4362. var code = "n(function(" + self.args.slice(0, -1).map(function(arg) {
  4363. return arg.value;
  4364. }).join(",") + "){" + self.args[self.args.length - 1].value + "})";
  4365. var ast = parse(code);
  4366. var mangle = { ie8: compressor.option("ie8") };
  4367. ast.figure_out_scope(mangle);
  4368. var comp = new Compressor(compressor.options);
  4369. ast = ast.transform(comp);
  4370. ast.figure_out_scope(mangle);
  4371. base54.reset();
  4372. ast.compute_char_frequency(mangle);
  4373. ast.mangle_names(mangle);
  4374. var fun;
  4375. ast.walk(new TreeWalker(function(node) {
  4376. if (fun) return true;
  4377. if (is_func_expr(node)) {
  4378. fun = node;
  4379. return true;
  4380. }
  4381. }));
  4382. if (fun.body instanceof AST_Node) {
  4383. fun.body = [
  4384. make_node(AST_Return, fun.body, {
  4385. value: fun.body
  4386. })
  4387. ];
  4388. }
  4389. var code = OutputStream();
  4390. AST_BlockStatement.prototype._codegen.call(fun, fun, code);
  4391. self.args = [
  4392. make_node(AST_String, self, {
  4393. value: fun.argnames.map(function(arg) {
  4394. return arg.print_to_string();
  4395. }).join(",")
  4396. }),
  4397. make_node(AST_String, self.args[self.args.length - 1], {
  4398. value: code.get().replace(/^\{|\}$/g, "")
  4399. })
  4400. ];
  4401. return self;
  4402. } catch (ex) {
  4403. if (ex instanceof JS_Parse_Error) {
  4404. compressor.warn("Error parsing code passed to new Function [{file}:{line},{col}]", self.args[self.args.length - 1].start);
  4405. compressor.warn(ex.toString());
  4406. } else {
  4407. throw ex;
  4408. }
  4409. }
  4410. }
  4411. }
  4412. var stat = is_func && fn.body;
  4413. if (stat instanceof AST_Node) {
  4414. stat = make_node(AST_Return, stat, {
  4415. value: stat
  4416. });
  4417. } else if (stat) {
  4418. stat = stat[0];
  4419. }
  4420. if (compressor.option("inline") && stat instanceof AST_Return) {
  4421. var value = stat.value;
  4422. if (!value || value.is_constant_expression()) {
  4423. var args = self.args.concat(value || make_node(AST_Undefined, self));
  4424. return make_sequence(self, args).optimize(compressor);
  4425. }
  4426. }
  4427. if (is_func && !fn.is_generator && !fn.async) {
  4428. var def, value, scope, in_loop, level = -1;
  4429. if (compressor.option("inline")
  4430. && simple_args
  4431. && !fn.uses_arguments
  4432. && !fn.uses_eval
  4433. && !(fn.name && fn instanceof AST_Function)
  4434. && (value = can_flatten_body(stat))
  4435. && (exp === fn
  4436. || compressor.option("unused")
  4437. && (def = exp.definition()).references.length == 1
  4438. && !recursive_ref(compressor, def)
  4439. && fn.is_constant_expression(exp.scope))
  4440. && !self.pure
  4441. && !fn.contains_this()
  4442. && can_inject_symbols()) {
  4443. return make_sequence(self, flatten_fn()).optimize(compressor);
  4444. }
  4445. if (compressor.option("side_effects") && !(fn.body instanceof AST_Node) && all(fn.body, is_empty)) {
  4446. var args = self.args.concat(make_node(AST_Undefined, self));
  4447. return make_sequence(self, args).optimize(compressor);
  4448. }
  4449. }
  4450. if (compressor.option("drop_console")) {
  4451. if (exp instanceof AST_PropAccess) {
  4452. var name = exp.expression;
  4453. while (name.expression) {
  4454. name = name.expression;
  4455. }
  4456. if (is_undeclared_ref(name) && name.name == "console") {
  4457. return make_node(AST_Undefined, self).optimize(compressor);
  4458. }
  4459. }
  4460. }
  4461. if (compressor.option("negate_iife")
  4462. && compressor.parent() instanceof AST_SimpleStatement
  4463. && is_iife_call(self)) {
  4464. return self.negate(compressor, true);
  4465. }
  4466. var ev = self.evaluate(compressor);
  4467. if (ev !== self) {
  4468. ev = make_node_from_constant(ev, self).optimize(compressor);
  4469. return best_of(compressor, ev, self);
  4470. }
  4471. return self;
  4472. function return_value(stat) {
  4473. if (!stat) return make_node(AST_Undefined, self);
  4474. if (stat instanceof AST_Return) {
  4475. if (!stat.value) return make_node(AST_Undefined, self);
  4476. return stat.value.clone(true);
  4477. }
  4478. if (stat instanceof AST_SimpleStatement) {
  4479. return make_node(AST_UnaryPrefix, stat, {
  4480. operator: "void",
  4481. expression: stat.body.clone(true)
  4482. });
  4483. }
  4484. }
  4485. function can_flatten_body(stat) {
  4486. var body = fn.body instanceof AST_Node ? [ fn.body ] : fn.body;
  4487. var len = body.length;
  4488. if (compressor.option("inline") < 3) {
  4489. return len == 1 && return_value(stat);
  4490. }
  4491. stat = null;
  4492. for (var i = 0; i < len; i++) {
  4493. var line = body[i];
  4494. if (line instanceof AST_Var) {
  4495. if (stat && !all(line.definitions, function(var_def) {
  4496. return !var_def.value;
  4497. })) {
  4498. return false;
  4499. }
  4500. } else if (stat) {
  4501. return false;
  4502. } else {
  4503. stat = line;
  4504. }
  4505. }
  4506. return return_value(stat);
  4507. }
  4508. function can_inject_args(catches, safe_to_inject) {
  4509. for (var i = 0, len = fn.argnames.length; i < len; i++) {
  4510. var arg = fn.argnames[i];
  4511. if (arg instanceof AST_DefaultAssign) {
  4512. if (arg.left.__unused) continue;
  4513. return false;
  4514. }
  4515. if (arg instanceof AST_Destructuring) return false;
  4516. if (arg instanceof AST_Expansion) {
  4517. if (arg.expression.__unused) continue;
  4518. return false;
  4519. }
  4520. if (arg.__unused) continue;
  4521. if (!safe_to_inject
  4522. || catches[arg.name]
  4523. || identifier_atom(arg.name)
  4524. || scope.var_names()[arg.name]) {
  4525. return false;
  4526. }
  4527. if (in_loop) in_loop.push(arg.definition());
  4528. }
  4529. return true;
  4530. }
  4531. function can_inject_vars(catches, safe_to_inject) {
  4532. var len = fn.body.length;
  4533. for (var i = 0; i < len; i++) {
  4534. var stat = fn.body[i];
  4535. if (!(stat instanceof AST_Var)) continue;
  4536. if (!safe_to_inject) return false;
  4537. for (var j = stat.definitions.length; --j >= 0;) {
  4538. var name = stat.definitions[j].name;
  4539. if (catches[name.name]
  4540. || identifier_atom(name.name)
  4541. || scope.var_names()[name.name]) {
  4542. return false;
  4543. }
  4544. if (in_loop) in_loop.push(name.definition());
  4545. }
  4546. }
  4547. return true;
  4548. }
  4549. function can_inject_symbols() {
  4550. var catches = Object.create(null);
  4551. do {
  4552. scope = compressor.parent(++level);
  4553. if (scope instanceof AST_Catch) {
  4554. catches[scope.argname.name] = true;
  4555. } else if (scope instanceof AST_IterationStatement) {
  4556. in_loop = [];
  4557. } else if (scope instanceof AST_SymbolRef) {
  4558. if (scope.fixed_value() instanceof AST_Scope) return false;
  4559. }
  4560. } while (!(scope instanceof AST_Scope) || scope instanceof AST_Arrow);
  4561. var safe_to_inject = !(scope instanceof AST_Toplevel) || compressor.toplevel.vars;
  4562. var inline = compressor.option("inline");
  4563. if (!can_inject_vars(catches, inline >= 3 && safe_to_inject)) return false;
  4564. if (!can_inject_args(catches, inline >= 2 && safe_to_inject)) return false;
  4565. return !in_loop || in_loop.length == 0 || !is_reachable(fn, in_loop);
  4566. }
  4567. function append_var(decls, expressions, name, value) {
  4568. var def = name.definition();
  4569. scope.variables.set(name.name, def);
  4570. scope.enclosed.push(def);
  4571. if (!scope.var_names()[name.name]) {
  4572. scope.var_names()[name.name] = true;
  4573. decls.push(make_node(AST_VarDef, name, {
  4574. name: name,
  4575. value: null
  4576. }));
  4577. }
  4578. var sym = make_node(AST_SymbolRef, name, name);
  4579. def.references.push(sym);
  4580. if (value) expressions.push(make_node(AST_Assign, self, {
  4581. operator: "=",
  4582. left: sym,
  4583. right: value
  4584. }));
  4585. }
  4586. function flatten_args(decls, expressions) {
  4587. var len = fn.argnames.length;
  4588. for (var i = self.args.length; --i >= len;) {
  4589. expressions.push(self.args[i]);
  4590. }
  4591. for (i = len; --i >= 0;) {
  4592. var name = fn.argnames[i];
  4593. var value = self.args[i];
  4594. if (name.__unused || !name.name || scope.var_names()[name.name]) {
  4595. if (value) expressions.push(value);
  4596. } else {
  4597. var symbol = make_node(AST_SymbolVar, name, name);
  4598. name.definition().orig.push(symbol);
  4599. if (!value && in_loop) value = make_node(AST_Undefined, self);
  4600. append_var(decls, expressions, symbol, value);
  4601. }
  4602. }
  4603. decls.reverse();
  4604. expressions.reverse();
  4605. }
  4606. function flatten_vars(decls, expressions) {
  4607. var pos = expressions.length;
  4608. for (var i = 0, lines = fn.body.length; i < lines; i++) {
  4609. var stat = fn.body[i];
  4610. if (!(stat instanceof AST_Var)) continue;
  4611. for (var j = 0, defs = stat.definitions.length; j < defs; j++) {
  4612. var var_def = stat.definitions[j];
  4613. var name = var_def.name;
  4614. append_var(decls, expressions, name, var_def.value);
  4615. if (in_loop) {
  4616. var def = name.definition();
  4617. var sym = make_node(AST_SymbolRef, name, name);
  4618. def.references.push(sym);
  4619. expressions.splice(pos++, 0, make_node(AST_Assign, var_def, {
  4620. operator: "=",
  4621. left: sym,
  4622. right: make_node(AST_Undefined, name)
  4623. }));
  4624. }
  4625. }
  4626. }
  4627. }
  4628. function flatten_fn() {
  4629. var decls = [];
  4630. var expressions = [];
  4631. flatten_args(decls, expressions);
  4632. flatten_vars(decls, expressions);
  4633. expressions.push(value);
  4634. if (decls.length) {
  4635. i = scope.body.indexOf(compressor.parent(level - 1)) + 1;
  4636. scope.body.splice(i, 0, make_node(AST_Var, fn, {
  4637. definitions: decls
  4638. }));
  4639. }
  4640. return expressions;
  4641. }
  4642. });
  4643. OPT(AST_New, function(self, compressor){
  4644. if (compressor.option("unsafe")) {
  4645. var exp = self.expression;
  4646. if (is_undeclared_ref(exp)) {
  4647. switch (exp.name) {
  4648. case "Object":
  4649. case "RegExp":
  4650. case "Function":
  4651. case "Error":
  4652. case "Array":
  4653. return make_node(AST_Call, self, self).transform(compressor);
  4654. }
  4655. }
  4656. }
  4657. return self;
  4658. });
  4659. OPT(AST_Sequence, function(self, compressor){
  4660. if (!compressor.option("side_effects")) return self;
  4661. var expressions = [];
  4662. filter_for_side_effects();
  4663. var end = expressions.length - 1;
  4664. trim_right_for_undefined();
  4665. if (end == 0) {
  4666. self = maintain_this_binding(compressor.parent(), compressor.self(), expressions[0]);
  4667. if (!(self instanceof AST_Sequence)) self = self.optimize(compressor);
  4668. return self;
  4669. }
  4670. self.expressions = expressions;
  4671. return self;
  4672. function filter_for_side_effects() {
  4673. var first = first_in_statement(compressor);
  4674. var last = self.expressions.length - 1;
  4675. self.expressions.forEach(function(expr, index) {
  4676. if (index < last) expr = expr.drop_side_effect_free(compressor, first);
  4677. if (expr) {
  4678. merge_sequence(expressions, expr);
  4679. first = false;
  4680. }
  4681. });
  4682. }
  4683. function trim_right_for_undefined() {
  4684. while (end > 0 && is_undefined(expressions[end], compressor)) end--;
  4685. if (end < expressions.length - 1) {
  4686. expressions[end] = make_node(AST_UnaryPrefix, self, {
  4687. operator : "void",
  4688. expression : expressions[end]
  4689. });
  4690. expressions.length = end + 1;
  4691. }
  4692. }
  4693. });
  4694. AST_Unary.DEFMETHOD("lift_sequences", function(compressor){
  4695. if (compressor.option("sequences")) {
  4696. if (this.expression instanceof AST_Sequence) {
  4697. var x = this.expression.expressions.slice();
  4698. var e = this.clone();
  4699. e.expression = x.pop();
  4700. x.push(e);
  4701. return make_sequence(this, x).optimize(compressor);
  4702. }
  4703. }
  4704. return this;
  4705. });
  4706. OPT(AST_UnaryPostfix, function(self, compressor){
  4707. return self.lift_sequences(compressor);
  4708. });
  4709. OPT(AST_UnaryPrefix, function(self, compressor){
  4710. var e = self.expression;
  4711. if (self.operator == "delete"
  4712. && !(e instanceof AST_SymbolRef
  4713. || e instanceof AST_PropAccess
  4714. || is_identifier_atom(e))) {
  4715. if (e instanceof AST_Sequence) {
  4716. e = e.expressions.slice();
  4717. e.push(make_node(AST_True, self));
  4718. return make_sequence(self, e).optimize(compressor);
  4719. }
  4720. return make_sequence(self, [ e, make_node(AST_True, self) ]).optimize(compressor);
  4721. }
  4722. var seq = self.lift_sequences(compressor);
  4723. if (seq !== self) {
  4724. return seq;
  4725. }
  4726. if (compressor.option("side_effects") && self.operator == "void") {
  4727. e = e.drop_side_effect_free(compressor);
  4728. if (e) {
  4729. self.expression = e;
  4730. return self;
  4731. } else {
  4732. return make_node(AST_Undefined, self).optimize(compressor);
  4733. }
  4734. }
  4735. if (compressor.in_boolean_context()) {
  4736. switch (self.operator) {
  4737. case "!":
  4738. if (e instanceof AST_UnaryPrefix && e.operator == "!") {
  4739. // !!foo ==> foo, if we're in boolean context
  4740. return e.expression;
  4741. }
  4742. if (e instanceof AST_Binary) {
  4743. self = best_of(compressor, self, e.negate(compressor, first_in_statement(compressor)));
  4744. }
  4745. break;
  4746. case "typeof":
  4747. // typeof always returns a non-empty string, thus it's
  4748. // always true in booleans
  4749. compressor.warn("Boolean expression always true [{file}:{line},{col}]", self.start);
  4750. return (e instanceof AST_SymbolRef ? make_node(AST_True, self) : make_sequence(self, [
  4751. e,
  4752. make_node(AST_True, self)
  4753. ])).optimize(compressor);
  4754. }
  4755. }
  4756. if (self.operator == "-" && e instanceof AST_Infinity) {
  4757. e = e.transform(compressor);
  4758. }
  4759. if (e instanceof AST_Binary
  4760. && (self.operator == "+" || self.operator == "-")
  4761. && (e.operator == "*" || e.operator == "/" || e.operator == "%")) {
  4762. return make_node(AST_Binary, self, {
  4763. operator: e.operator,
  4764. left: make_node(AST_UnaryPrefix, e.left, {
  4765. operator: self.operator,
  4766. expression: e.left
  4767. }),
  4768. right: e.right
  4769. });
  4770. }
  4771. // avoids infinite recursion of numerals
  4772. if (self.operator != "-"
  4773. || !(e instanceof AST_Number || e instanceof AST_Infinity)) {
  4774. var ev = self.evaluate(compressor);
  4775. if (ev !== self) {
  4776. ev = make_node_from_constant(ev, self).optimize(compressor);
  4777. return best_of(compressor, ev, self);
  4778. }
  4779. }
  4780. return self;
  4781. });
  4782. AST_Binary.DEFMETHOD("lift_sequences", function(compressor){
  4783. if (compressor.option("sequences")) {
  4784. if (this.left instanceof AST_Sequence) {
  4785. var x = this.left.expressions.slice();
  4786. var e = this.clone();
  4787. e.left = x.pop();
  4788. x.push(e);
  4789. return make_sequence(this, x).optimize(compressor);
  4790. }
  4791. if (this.right instanceof AST_Sequence && !this.left.has_side_effects(compressor)) {
  4792. var assign = this.operator == "=" && this.left instanceof AST_SymbolRef;
  4793. var x = this.right.expressions;
  4794. var last = x.length - 1;
  4795. for (var i = 0; i < last; i++) {
  4796. if (!assign && x[i].has_side_effects(compressor)) break;
  4797. }
  4798. if (i == last) {
  4799. x = x.slice();
  4800. var e = this.clone();
  4801. e.right = x.pop();
  4802. x.push(e);
  4803. return make_sequence(this, x).optimize(compressor);
  4804. } else if (i > 0) {
  4805. var e = this.clone();
  4806. e.right = make_sequence(this.right, x.slice(i));
  4807. x = x.slice(0, i);
  4808. x.push(e);
  4809. return make_sequence(this, x).optimize(compressor);
  4810. }
  4811. }
  4812. }
  4813. return this;
  4814. });
  4815. var commutativeOperators = makePredicate("== === != !== * & | ^");
  4816. function is_object(node) {
  4817. return node instanceof AST_Array
  4818. || node instanceof AST_Lambda
  4819. || node instanceof AST_Object
  4820. || node instanceof AST_Class;
  4821. }
  4822. OPT(AST_Binary, function(self, compressor){
  4823. function reversible() {
  4824. return self.left.is_constant()
  4825. || self.right.is_constant()
  4826. || !self.left.has_side_effects(compressor)
  4827. && !self.right.has_side_effects(compressor);
  4828. }
  4829. function reverse(op) {
  4830. if (reversible()) {
  4831. if (op) self.operator = op;
  4832. var tmp = self.left;
  4833. self.left = self.right;
  4834. self.right = tmp;
  4835. }
  4836. }
  4837. if (commutativeOperators(self.operator)) {
  4838. if (self.right.is_constant()
  4839. && !self.left.is_constant()) {
  4840. // if right is a constant, whatever side effects the
  4841. // left side might have could not influence the
  4842. // result. hence, force switch.
  4843. if (!(self.left instanceof AST_Binary
  4844. && PRECEDENCE[self.left.operator] >= PRECEDENCE[self.operator])) {
  4845. reverse();
  4846. }
  4847. }
  4848. }
  4849. self = self.lift_sequences(compressor);
  4850. if (compressor.option("comparisons")) switch (self.operator) {
  4851. case "===":
  4852. case "!==":
  4853. if ((self.left.is_string(compressor) && self.right.is_string(compressor)) ||
  4854. (self.left.is_number(compressor) && self.right.is_number(compressor)) ||
  4855. (self.left.is_boolean() && self.right.is_boolean()) ||
  4856. self.left.equivalent_to(self.right)) {
  4857. self.operator = self.operator.substr(0, 2);
  4858. }
  4859. // XXX: intentionally falling down to the next case
  4860. case "==":
  4861. case "!=":
  4862. // "undefined" == typeof x => undefined === x
  4863. if (compressor.option("typeofs")
  4864. && self.left instanceof AST_String
  4865. && self.left.value == "undefined"
  4866. && self.right instanceof AST_UnaryPrefix
  4867. && self.right.operator == "typeof") {
  4868. var expr = self.right.expression;
  4869. if (expr instanceof AST_SymbolRef ? expr.is_declared(compressor)
  4870. : !(expr instanceof AST_PropAccess && compressor.option("ie8"))) {
  4871. self.right = expr;
  4872. self.left = make_node(AST_Undefined, self.left).optimize(compressor);
  4873. if (self.operator.length == 2) self.operator += "=";
  4874. }
  4875. }
  4876. // obj !== obj => false
  4877. else if (self.left instanceof AST_SymbolRef
  4878. && self.right instanceof AST_SymbolRef
  4879. && self.left.definition() === self.right.definition()
  4880. && is_object(self.left.fixed_value())) {
  4881. return make_node(self.operator[0] == "=" ? AST_True : AST_False, self);
  4882. }
  4883. break;
  4884. }
  4885. if (self.operator == "+" && compressor.in_boolean_context()) {
  4886. var ll = self.left.evaluate(compressor);
  4887. var rr = self.right.evaluate(compressor);
  4888. if (ll && typeof ll == "string") {
  4889. compressor.warn("+ in boolean context always true [{file}:{line},{col}]", self.start);
  4890. return make_sequence(self, [
  4891. self.right,
  4892. make_node(AST_True, self)
  4893. ]).optimize(compressor);
  4894. }
  4895. if (rr && typeof rr == "string") {
  4896. compressor.warn("+ in boolean context always true [{file}:{line},{col}]", self.start);
  4897. return make_sequence(self, [
  4898. self.left,
  4899. make_node(AST_True, self)
  4900. ]).optimize(compressor);
  4901. }
  4902. }
  4903. if (compressor.option("comparisons") && self.is_boolean()) {
  4904. if (!(compressor.parent() instanceof AST_Binary)
  4905. || compressor.parent() instanceof AST_Assign) {
  4906. var negated = make_node(AST_UnaryPrefix, self, {
  4907. operator: "!",
  4908. expression: self.negate(compressor, first_in_statement(compressor))
  4909. });
  4910. self = best_of(compressor, self, negated);
  4911. }
  4912. if (compressor.option("unsafe_comps")) {
  4913. switch (self.operator) {
  4914. case "<": reverse(">"); break;
  4915. case "<=": reverse(">="); break;
  4916. }
  4917. }
  4918. }
  4919. if (self.operator == "+") {
  4920. if (self.right instanceof AST_String
  4921. && self.right.getValue() == ""
  4922. && self.left.is_string(compressor)) {
  4923. return self.left;
  4924. }
  4925. if (self.left instanceof AST_String
  4926. && self.left.getValue() == ""
  4927. && self.right.is_string(compressor)) {
  4928. return self.right;
  4929. }
  4930. if (self.left instanceof AST_Binary
  4931. && self.left.operator == "+"
  4932. && self.left.left instanceof AST_String
  4933. && self.left.left.getValue() == ""
  4934. && self.right.is_string(compressor)) {
  4935. self.left = self.left.right;
  4936. return self.transform(compressor);
  4937. }
  4938. }
  4939. if (compressor.option("evaluate")) {
  4940. switch (self.operator) {
  4941. case "&&":
  4942. var ll = self.left.truthy ? true : self.left.falsy ? false : self.left.evaluate(compressor);
  4943. if (!ll) {
  4944. compressor.warn("Condition left of && always false [{file}:{line},{col}]", self.start);
  4945. return maintain_this_binding(compressor.parent(), compressor.self(), self.left).optimize(compressor);
  4946. } else if (!(ll instanceof AST_Node)) {
  4947. compressor.warn("Condition left of && always true [{file}:{line},{col}]", self.start);
  4948. return make_sequence(self, [ self.left, self.right ]).optimize(compressor);
  4949. }
  4950. var rr = self.right.evaluate(compressor);
  4951. if (!rr) {
  4952. if (compressor.in_boolean_context()) {
  4953. compressor.warn("Boolean && always false [{file}:{line},{col}]", self.start);
  4954. return make_sequence(self, [
  4955. self.left,
  4956. make_node(AST_False, self)
  4957. ]).optimize(compressor);
  4958. } else self.falsy = true;
  4959. } else if (!(rr instanceof AST_Node)) {
  4960. var parent = compressor.parent();
  4961. if (parent.operator == "&&" && parent.left === compressor.self() || compressor.in_boolean_context()) {
  4962. compressor.warn("Dropping side-effect-free && [{file}:{line},{col}]", self.start);
  4963. return self.left.optimize(compressor);
  4964. }
  4965. }
  4966. // x || false && y ---> x ? y : false
  4967. if (self.left.operator == "||") {
  4968. var lr = self.left.right.evaluate(compressor);
  4969. if (!lr) return make_node(AST_Conditional, self, {
  4970. condition: self.left.left,
  4971. consequent: self.right,
  4972. alternative: self.left.right
  4973. }).optimize(compressor);
  4974. }
  4975. break;
  4976. case "||":
  4977. var ll = self.left.truthy ? true : self.left.falsy ? false : self.left.evaluate(compressor);
  4978. if (!ll) {
  4979. compressor.warn("Condition left of || always false [{file}:{line},{col}]", self.start);
  4980. return make_sequence(self, [ self.left, self.right ]).optimize(compressor);
  4981. } else if (!(ll instanceof AST_Node)) {
  4982. compressor.warn("Condition left of || always true [{file}:{line},{col}]", self.start);
  4983. return maintain_this_binding(compressor.parent(), compressor.self(), self.left).optimize(compressor);
  4984. }
  4985. var rr = self.right.evaluate(compressor);
  4986. if (!rr) {
  4987. var parent = compressor.parent();
  4988. if (parent.operator == "||" && parent.left === compressor.self() || compressor.in_boolean_context()) {
  4989. compressor.warn("Dropping side-effect-free || [{file}:{line},{col}]", self.start);
  4990. return self.left.optimize(compressor);
  4991. }
  4992. } else if (!(rr instanceof AST_Node)) {
  4993. if (compressor.in_boolean_context()) {
  4994. compressor.warn("Boolean || always true [{file}:{line},{col}]", self.start);
  4995. return make_sequence(self, [
  4996. self.left,
  4997. make_node(AST_True, self)
  4998. ]).optimize(compressor);
  4999. } else self.truthy = true;
  5000. }
  5001. if (self.left.operator == "&&") {
  5002. var lr = self.left.right.evaluate(compressor);
  5003. if (lr && !(lr instanceof AST_Node)) return make_node(AST_Conditional, self, {
  5004. condition: self.left.left,
  5005. consequent: self.left.right,
  5006. alternative: self.right
  5007. }).optimize(compressor);
  5008. }
  5009. break;
  5010. }
  5011. var associative = true;
  5012. switch (self.operator) {
  5013. case "+":
  5014. // "foo" + ("bar" + x) => "foobar" + x
  5015. if (self.left instanceof AST_Constant
  5016. && self.right instanceof AST_Binary
  5017. && self.right.operator == "+"
  5018. && self.right.left instanceof AST_Constant
  5019. && self.right.is_string(compressor)) {
  5020. self = make_node(AST_Binary, self, {
  5021. operator: "+",
  5022. left: make_node(AST_String, self.left, {
  5023. value: "" + self.left.getValue() + self.right.left.getValue(),
  5024. start: self.left.start,
  5025. end: self.right.left.end
  5026. }),
  5027. right: self.right.right
  5028. });
  5029. }
  5030. // (x + "foo") + "bar" => x + "foobar"
  5031. if (self.right instanceof AST_Constant
  5032. && self.left instanceof AST_Binary
  5033. && self.left.operator == "+"
  5034. && self.left.right instanceof AST_Constant
  5035. && self.left.is_string(compressor)) {
  5036. self = make_node(AST_Binary, self, {
  5037. operator: "+",
  5038. left: self.left.left,
  5039. right: make_node(AST_String, self.right, {
  5040. value: "" + self.left.right.getValue() + self.right.getValue(),
  5041. start: self.left.right.start,
  5042. end: self.right.end
  5043. })
  5044. });
  5045. }
  5046. // (x + "foo") + ("bar" + y) => (x + "foobar") + y
  5047. if (self.left instanceof AST_Binary
  5048. && self.left.operator == "+"
  5049. && self.left.is_string(compressor)
  5050. && self.left.right instanceof AST_Constant
  5051. && self.right instanceof AST_Binary
  5052. && self.right.operator == "+"
  5053. && self.right.left instanceof AST_Constant
  5054. && self.right.is_string(compressor)) {
  5055. self = make_node(AST_Binary, self, {
  5056. operator: "+",
  5057. left: make_node(AST_Binary, self.left, {
  5058. operator: "+",
  5059. left: self.left.left,
  5060. right: make_node(AST_String, self.left.right, {
  5061. value: "" + self.left.right.getValue() + self.right.left.getValue(),
  5062. start: self.left.right.start,
  5063. end: self.right.left.end
  5064. })
  5065. }),
  5066. right: self.right.right
  5067. });
  5068. }
  5069. // a + -b => a - b
  5070. if (self.right instanceof AST_UnaryPrefix
  5071. && self.right.operator == "-"
  5072. && self.left.is_number(compressor)) {
  5073. self = make_node(AST_Binary, self, {
  5074. operator: "-",
  5075. left: self.left,
  5076. right: self.right.expression
  5077. });
  5078. break;
  5079. }
  5080. // -a + b => b - a
  5081. if (self.left instanceof AST_UnaryPrefix
  5082. && self.left.operator == "-"
  5083. && reversible()
  5084. && self.right.is_number(compressor)) {
  5085. self = make_node(AST_Binary, self, {
  5086. operator: "-",
  5087. left: self.right,
  5088. right: self.left.expression
  5089. });
  5090. break;
  5091. }
  5092. case "*":
  5093. associative = compressor.option("unsafe_math");
  5094. case "&":
  5095. case "|":
  5096. case "^":
  5097. // a + +b => +b + a
  5098. if (self.left.is_number(compressor)
  5099. && self.right.is_number(compressor)
  5100. && reversible()
  5101. && !(self.left instanceof AST_Binary
  5102. && self.left.operator != self.operator
  5103. && PRECEDENCE[self.left.operator] >= PRECEDENCE[self.operator])) {
  5104. var reversed = make_node(AST_Binary, self, {
  5105. operator: self.operator,
  5106. left: self.right,
  5107. right: self.left
  5108. });
  5109. if (self.right instanceof AST_Constant
  5110. && !(self.left instanceof AST_Constant)) {
  5111. self = best_of(compressor, reversed, self);
  5112. } else {
  5113. self = best_of(compressor, self, reversed);
  5114. }
  5115. }
  5116. if (associative && self.is_number(compressor)) {
  5117. // a + (b + c) => (a + b) + c
  5118. if (self.right instanceof AST_Binary
  5119. && self.right.operator == self.operator) {
  5120. self = make_node(AST_Binary, self, {
  5121. operator: self.operator,
  5122. left: make_node(AST_Binary, self.left, {
  5123. operator: self.operator,
  5124. left: self.left,
  5125. right: self.right.left,
  5126. start: self.left.start,
  5127. end: self.right.left.end
  5128. }),
  5129. right: self.right.right
  5130. });
  5131. }
  5132. // (n + 2) + 3 => 5 + n
  5133. // (2 * n) * 3 => 6 + n
  5134. if (self.right instanceof AST_Constant
  5135. && self.left instanceof AST_Binary
  5136. && self.left.operator == self.operator) {
  5137. if (self.left.left instanceof AST_Constant) {
  5138. self = make_node(AST_Binary, self, {
  5139. operator: self.operator,
  5140. left: make_node(AST_Binary, self.left, {
  5141. operator: self.operator,
  5142. left: self.left.left,
  5143. right: self.right,
  5144. start: self.left.left.start,
  5145. end: self.right.end
  5146. }),
  5147. right: self.left.right
  5148. });
  5149. } else if (self.left.right instanceof AST_Constant) {
  5150. self = make_node(AST_Binary, self, {
  5151. operator: self.operator,
  5152. left: make_node(AST_Binary, self.left, {
  5153. operator: self.operator,
  5154. left: self.left.right,
  5155. right: self.right,
  5156. start: self.left.right.start,
  5157. end: self.right.end
  5158. }),
  5159. right: self.left.left
  5160. });
  5161. }
  5162. }
  5163. // (a | 1) | (2 | d) => (3 | a) | b
  5164. if (self.left instanceof AST_Binary
  5165. && self.left.operator == self.operator
  5166. && self.left.right instanceof AST_Constant
  5167. && self.right instanceof AST_Binary
  5168. && self.right.operator == self.operator
  5169. && self.right.left instanceof AST_Constant) {
  5170. self = make_node(AST_Binary, self, {
  5171. operator: self.operator,
  5172. left: make_node(AST_Binary, self.left, {
  5173. operator: self.operator,
  5174. left: make_node(AST_Binary, self.left.left, {
  5175. operator: self.operator,
  5176. left: self.left.right,
  5177. right: self.right.left,
  5178. start: self.left.right.start,
  5179. end: self.right.left.end
  5180. }),
  5181. right: self.left.left
  5182. }),
  5183. right: self.right.right
  5184. });
  5185. }
  5186. }
  5187. }
  5188. }
  5189. // x && (y && z) ==> x && y && z
  5190. // x || (y || z) ==> x || y || z
  5191. // x + ("y" + z) ==> x + "y" + z
  5192. // "x" + (y + "z")==> "x" + y + "z"
  5193. if (self.right instanceof AST_Binary
  5194. && self.right.operator == self.operator
  5195. && (lazy_op(self.operator)
  5196. || (self.operator == "+"
  5197. && (self.right.left.is_string(compressor)
  5198. || (self.left.is_string(compressor)
  5199. && self.right.right.is_string(compressor))))))
  5200. {
  5201. self.left = make_node(AST_Binary, self.left, {
  5202. operator : self.operator,
  5203. left : self.left,
  5204. right : self.right.left
  5205. });
  5206. self.right = self.right.right;
  5207. return self.transform(compressor);
  5208. }
  5209. var ev = self.evaluate(compressor);
  5210. if (ev !== self) {
  5211. ev = make_node_from_constant(ev, self).optimize(compressor);
  5212. return best_of(compressor, ev, self);
  5213. }
  5214. return self;
  5215. });
  5216. OPT(AST_SymbolExport, function(self, compressor){
  5217. return self;
  5218. });
  5219. function recursive_ref(compressor, def) {
  5220. var node;
  5221. for (var i = 0; node = compressor.parent(i); i++) {
  5222. if (node instanceof AST_Lambda) {
  5223. var name = node.name;
  5224. if (name && name.definition() === def) break;
  5225. }
  5226. }
  5227. return node;
  5228. }
  5229. OPT(AST_SymbolRef, function(self, compressor){
  5230. var def = self.resolve_defines(compressor);
  5231. if (def) {
  5232. return def.optimize(compressor);
  5233. }
  5234. // testing against !self.scope.uses_with first is an optimization
  5235. if (!compressor.option("ie8")
  5236. && is_undeclared_ref(self)
  5237. && (!self.scope.uses_with || !compressor.find_parent(AST_With))) {
  5238. switch (self.name) {
  5239. case "undefined":
  5240. return make_node(AST_Undefined, self).optimize(compressor);
  5241. case "NaN":
  5242. return make_node(AST_NaN, self).optimize(compressor);
  5243. case "Infinity":
  5244. return make_node(AST_Infinity, self).optimize(compressor);
  5245. }
  5246. }
  5247. if (compressor.option("reduce_vars")
  5248. && is_lhs(self, compressor.parent()) !== self) {
  5249. var d = self.definition();
  5250. var fixed = self.fixed_value();
  5251. var single_use = d.single_use;
  5252. if (single_use && (fixed instanceof AST_Lambda || fixed instanceof AST_Class)) {
  5253. if (d.scope !== self.scope
  5254. && (!compressor.option("reduce_funcs") && fixed instanceof AST_Lambda
  5255. || d.escaped == 1
  5256. || fixed.inlined)) {
  5257. single_use = false;
  5258. } else if (recursive_ref(compressor, d)) {
  5259. single_use = false;
  5260. } else if (d.scope !== self.scope || d.orig[0] instanceof AST_SymbolFunarg) {
  5261. single_use = fixed.is_constant_expression(self.scope);
  5262. if (single_use == "f") {
  5263. var scope = self.scope;
  5264. do {
  5265. if (scope instanceof AST_Defun || is_func_expr(scope)) {
  5266. scope.inlined = true;
  5267. }
  5268. } while (scope = scope.parent_scope);
  5269. }
  5270. }
  5271. }
  5272. if (single_use && fixed) {
  5273. if (fixed instanceof AST_DefClass) {
  5274. fixed = make_node(AST_ClassExpression, fixed, fixed);
  5275. }
  5276. if (fixed instanceof AST_Defun) {
  5277. fixed._squeezed = true;
  5278. fixed = make_node(AST_Function, fixed, fixed);
  5279. }
  5280. var value;
  5281. if (d.recursive_refs > 0 && fixed.name instanceof AST_SymbolDefun) {
  5282. value = fixed.clone(true);
  5283. var defun_def = value.name.definition();
  5284. var lambda_def = value.variables.get(value.name.name);
  5285. var name = lambda_def && lambda_def.orig[0];
  5286. if (!(name instanceof AST_SymbolLambda)) {
  5287. name = make_node(AST_SymbolLambda, value.name, value.name);
  5288. name.scope = value;
  5289. value.name = name;
  5290. lambda_def = value.def_function(name);
  5291. }
  5292. value.walk(new TreeWalker(function(node) {
  5293. if (node instanceof AST_SymbolRef && node.definition() === defun_def) {
  5294. node.thedef = lambda_def;
  5295. lambda_def.references.push(node);
  5296. }
  5297. }));
  5298. } else {
  5299. value = fixed.optimize(compressor);
  5300. if (value === fixed) value = fixed.clone(true);
  5301. }
  5302. return value;
  5303. }
  5304. if (fixed && d.should_replace === undefined) {
  5305. var init;
  5306. if (fixed instanceof AST_This) {
  5307. if (!(d.orig[0] instanceof AST_SymbolFunarg)
  5308. && all(d.references, function(ref) {
  5309. return d.scope === ref.scope;
  5310. })) {
  5311. init = fixed;
  5312. }
  5313. } else {
  5314. var ev = fixed.evaluate(compressor);
  5315. if (ev !== fixed && (compressor.option("unsafe_regexp") || !(ev instanceof RegExp))) {
  5316. init = make_node_from_constant(ev, fixed);
  5317. }
  5318. }
  5319. if (init) {
  5320. var value_length = init.optimize(compressor).print_to_string().length;
  5321. var fn;
  5322. if (has_symbol_ref(fixed)) {
  5323. fn = function() {
  5324. var result = init.optimize(compressor);
  5325. return result === init ? result.clone(true) : result;
  5326. };
  5327. } else {
  5328. value_length = Math.min(value_length, fixed.print_to_string().length);
  5329. fn = function() {
  5330. var result = best_of_expression(init.optimize(compressor), fixed);
  5331. return result === init || result === fixed ? result.clone(true) : result;
  5332. };
  5333. }
  5334. var name_length = d.name.length;
  5335. var overhead = 0;
  5336. if (compressor.option("unused") && !compressor.exposed(d)) {
  5337. overhead = (name_length + 2 + value_length) / d.references.length;
  5338. }
  5339. d.should_replace = value_length <= name_length + overhead ? fn : false;
  5340. } else {
  5341. d.should_replace = false;
  5342. }
  5343. }
  5344. if (d.should_replace) {
  5345. return d.should_replace();
  5346. }
  5347. }
  5348. return self;
  5349. function has_symbol_ref(value) {
  5350. var found;
  5351. value.walk(new TreeWalker(function(node) {
  5352. if (node instanceof AST_SymbolRef) found = true;
  5353. if (found) return true;
  5354. }));
  5355. return found;
  5356. }
  5357. });
  5358. function is_atomic(lhs, self) {
  5359. return lhs instanceof AST_SymbolRef || lhs.TYPE === self.TYPE;
  5360. }
  5361. OPT(AST_Undefined, function(self, compressor){
  5362. if (compressor.option("unsafe_undefined")) {
  5363. var undef = find_variable(compressor, "undefined");
  5364. if (undef) {
  5365. var ref = make_node(AST_SymbolRef, self, {
  5366. name : "undefined",
  5367. scope : undef.scope,
  5368. thedef : undef
  5369. });
  5370. ref.is_undefined = true;
  5371. return ref;
  5372. }
  5373. }
  5374. var lhs = is_lhs(compressor.self(), compressor.parent());
  5375. if (lhs && is_atomic(lhs, self)) return self;
  5376. return make_node(AST_UnaryPrefix, self, {
  5377. operator: "void",
  5378. expression: make_node(AST_Number, self, {
  5379. value: 0
  5380. })
  5381. });
  5382. });
  5383. OPT(AST_Infinity, function(self, compressor){
  5384. var lhs = is_lhs(compressor.self(), compressor.parent());
  5385. if (lhs && is_atomic(lhs, self)) return self;
  5386. if (compressor.option("keep_infinity")
  5387. && !(lhs && !is_atomic(lhs, self))
  5388. && !find_variable(compressor, "Infinity"))
  5389. return self;
  5390. return make_node(AST_Binary, self, {
  5391. operator: "/",
  5392. left: make_node(AST_Number, self, {
  5393. value: 1
  5394. }),
  5395. right: make_node(AST_Number, self, {
  5396. value: 0
  5397. })
  5398. });
  5399. });
  5400. OPT(AST_NaN, function(self, compressor){
  5401. var lhs = is_lhs(compressor.self(), compressor.parent());
  5402. if (lhs && !is_atomic(lhs, self)
  5403. || find_variable(compressor, "NaN")) {
  5404. return make_node(AST_Binary, self, {
  5405. operator: "/",
  5406. left: make_node(AST_Number, self, {
  5407. value: 0
  5408. }),
  5409. right: make_node(AST_Number, self, {
  5410. value: 0
  5411. })
  5412. });
  5413. }
  5414. return self;
  5415. });
  5416. function is_reachable(self, defs) {
  5417. var reachable = false;
  5418. var find_ref = new TreeWalker(function(node) {
  5419. if (reachable) return true;
  5420. if (node instanceof AST_SymbolRef && member(node.definition(), defs)) {
  5421. return reachable = true;
  5422. }
  5423. });
  5424. var scan_scope = new TreeWalker(function(node) {
  5425. if (reachable) return true;
  5426. if (node instanceof AST_Scope && node !== self) {
  5427. var parent = scan_scope.parent();
  5428. if (parent instanceof AST_Call && parent.expression === node) return;
  5429. node.walk(find_ref);
  5430. return true;
  5431. }
  5432. });
  5433. self.walk(scan_scope);
  5434. return reachable;
  5435. }
  5436. var ASSIGN_OPS = [ '+', '-', '/', '*', '%', '>>', '<<', '>>>', '|', '^', '&' ];
  5437. var ASSIGN_OPS_COMMUTATIVE = [ '*', '|', '^', '&' ];
  5438. OPT(AST_Assign, function(self, compressor){
  5439. var def;
  5440. if (compressor.option("dead_code")
  5441. && self.left instanceof AST_SymbolRef
  5442. && (def = self.left.definition()).scope === compressor.find_parent(AST_Lambda)) {
  5443. var level = 0, node, parent = self;
  5444. do {
  5445. node = parent;
  5446. parent = compressor.parent(level++);
  5447. if (parent instanceof AST_Exit) {
  5448. if (in_try(level, parent instanceof AST_Throw)) break;
  5449. if (is_reachable(def.scope, [ def ])) break;
  5450. if (self.operator == "=") return self.right;
  5451. return make_node(AST_Binary, self, {
  5452. operator: self.operator.slice(0, -1),
  5453. left: self.left,
  5454. right: self.right
  5455. }).optimize(compressor);
  5456. }
  5457. } while (parent instanceof AST_Binary && parent.right === node
  5458. || parent instanceof AST_Sequence && parent.tail_node() === node);
  5459. }
  5460. self = self.lift_sequences(compressor);
  5461. if (self.operator == "=" && self.left instanceof AST_SymbolRef && self.right instanceof AST_Binary) {
  5462. // x = expr1 OP expr2
  5463. if (self.right.left instanceof AST_SymbolRef
  5464. && self.right.left.name == self.left.name
  5465. && member(self.right.operator, ASSIGN_OPS)) {
  5466. // x = x - 2 ---> x -= 2
  5467. self.operator = self.right.operator + "=";
  5468. self.right = self.right.right;
  5469. }
  5470. else if (self.right.right instanceof AST_SymbolRef
  5471. && self.right.right.name == self.left.name
  5472. && member(self.right.operator, ASSIGN_OPS_COMMUTATIVE)
  5473. && !self.right.left.has_side_effects(compressor)) {
  5474. // x = 2 & x ---> x &= 2
  5475. self.operator = self.right.operator + "=";
  5476. self.right = self.right.left;
  5477. }
  5478. }
  5479. return self;
  5480. function in_try(level, no_catch) {
  5481. var scope = self.left.definition().scope;
  5482. var parent;
  5483. while ((parent = compressor.parent(level++)) !== scope) {
  5484. if (parent instanceof AST_Try) {
  5485. if (parent.bfinally) return true;
  5486. if (no_catch && parent.bcatch) return true;
  5487. }
  5488. }
  5489. }
  5490. });
  5491. OPT(AST_DefaultAssign, function(self, compressor){
  5492. if (!compressor.option("evaluate")) {
  5493. return self;
  5494. }
  5495. var evaluateRight = self.right.evaluate(compressor);
  5496. // `[x = undefined] = foo` ---> `[x] = foo`
  5497. if (evaluateRight === undefined) {
  5498. self = self.left;
  5499. } else if (evaluateRight !== self.right) {
  5500. evaluateRight = make_node_from_constant(evaluateRight, self.right);
  5501. self.right = best_of_expression(evaluateRight, self.right);
  5502. }
  5503. return self;
  5504. });
  5505. OPT(AST_Conditional, function(self, compressor){
  5506. if (!compressor.option("conditionals")) return self;
  5507. // This looks like lift_sequences(), should probably be under "sequences"
  5508. if (self.condition instanceof AST_Sequence) {
  5509. var expressions = self.condition.expressions.slice();
  5510. self.condition = expressions.pop();
  5511. expressions.push(self);
  5512. return make_sequence(self, expressions);
  5513. }
  5514. var cond = self.condition.evaluate(compressor);
  5515. if (cond !== self.condition) {
  5516. if (cond) {
  5517. compressor.warn("Condition always true [{file}:{line},{col}]", self.start);
  5518. return maintain_this_binding(compressor.parent(), compressor.self(), self.consequent);
  5519. } else {
  5520. compressor.warn("Condition always false [{file}:{line},{col}]", self.start);
  5521. return maintain_this_binding(compressor.parent(), compressor.self(), self.alternative);
  5522. }
  5523. }
  5524. var negated = cond.negate(compressor, first_in_statement(compressor));
  5525. if (best_of(compressor, cond, negated) === negated) {
  5526. self = make_node(AST_Conditional, self, {
  5527. condition: negated,
  5528. consequent: self.alternative,
  5529. alternative: self.consequent
  5530. });
  5531. }
  5532. var condition = self.condition;
  5533. var consequent = self.consequent;
  5534. var alternative = self.alternative;
  5535. // x?x:y --> x||y
  5536. if (condition instanceof AST_SymbolRef
  5537. && consequent instanceof AST_SymbolRef
  5538. && condition.definition() === consequent.definition()) {
  5539. return make_node(AST_Binary, self, {
  5540. operator: "||",
  5541. left: condition,
  5542. right: alternative
  5543. });
  5544. }
  5545. // if (foo) exp = something; else exp = something_else;
  5546. // |
  5547. // v
  5548. // exp = foo ? something : something_else;
  5549. if (consequent instanceof AST_Assign
  5550. && alternative instanceof AST_Assign
  5551. && consequent.operator == alternative.operator
  5552. && consequent.left.equivalent_to(alternative.left)
  5553. && (!self.condition.has_side_effects(compressor)
  5554. || consequent.operator == "="
  5555. && !consequent.left.has_side_effects(compressor))) {
  5556. return make_node(AST_Assign, self, {
  5557. operator: consequent.operator,
  5558. left: consequent.left,
  5559. right: make_node(AST_Conditional, self, {
  5560. condition: self.condition,
  5561. consequent: consequent.right,
  5562. alternative: alternative.right
  5563. })
  5564. });
  5565. }
  5566. // x ? y(a) : y(b) --> y(x ? a : b)
  5567. var arg_index;
  5568. if (consequent instanceof AST_Call
  5569. && alternative.TYPE === consequent.TYPE
  5570. && consequent.args.length > 0
  5571. && consequent.args.length == alternative.args.length
  5572. && consequent.expression.equivalent_to(alternative.expression)
  5573. && !self.condition.has_side_effects(compressor)
  5574. && !consequent.expression.has_side_effects(compressor)
  5575. && typeof (arg_index = single_arg_diff()) == "number") {
  5576. var node = consequent.clone();
  5577. node.args[arg_index] = make_node(AST_Conditional, self, {
  5578. condition: self.condition,
  5579. consequent: consequent.args[arg_index],
  5580. alternative: alternative.args[arg_index]
  5581. });
  5582. return node;
  5583. }
  5584. // x?y?z:a:a --> x&&y?z:a
  5585. if (consequent instanceof AST_Conditional
  5586. && consequent.alternative.equivalent_to(alternative)) {
  5587. return make_node(AST_Conditional, self, {
  5588. condition: make_node(AST_Binary, self, {
  5589. left: self.condition,
  5590. operator: "&&",
  5591. right: consequent.condition
  5592. }),
  5593. consequent: consequent.consequent,
  5594. alternative: alternative
  5595. });
  5596. }
  5597. // x ? y : y --> x, y
  5598. if (consequent.equivalent_to(alternative)) {
  5599. return make_sequence(self, [
  5600. self.condition,
  5601. consequent
  5602. ]).optimize(compressor);
  5603. }
  5604. // x ? y || z : z --> x && y || z
  5605. if (consequent instanceof AST_Binary
  5606. && consequent.operator == "||"
  5607. && consequent.right.equivalent_to(alternative)) {
  5608. return make_node(AST_Binary, self, {
  5609. operator: "||",
  5610. left: make_node(AST_Binary, self, {
  5611. operator: "&&",
  5612. left: self.condition,
  5613. right: consequent.left
  5614. }),
  5615. right: alternative
  5616. }).optimize(compressor);
  5617. }
  5618. var in_bool = compressor.in_boolean_context();
  5619. if (is_true(self.consequent)) {
  5620. if (is_false(self.alternative)) {
  5621. // c ? true : false ---> !!c
  5622. return booleanize(self.condition);
  5623. }
  5624. // c ? true : x ---> !!c || x
  5625. return make_node(AST_Binary, self, {
  5626. operator: "||",
  5627. left: booleanize(self.condition),
  5628. right: self.alternative
  5629. });
  5630. }
  5631. if (is_false(self.consequent)) {
  5632. if (is_true(self.alternative)) {
  5633. // c ? false : true ---> !c
  5634. return booleanize(self.condition.negate(compressor));
  5635. }
  5636. // c ? false : x ---> !c && x
  5637. return make_node(AST_Binary, self, {
  5638. operator: "&&",
  5639. left: booleanize(self.condition.negate(compressor)),
  5640. right: self.alternative
  5641. });
  5642. }
  5643. if (is_true(self.alternative)) {
  5644. // c ? x : true ---> !c || x
  5645. return make_node(AST_Binary, self, {
  5646. operator: "||",
  5647. left: booleanize(self.condition.negate(compressor)),
  5648. right: self.consequent
  5649. });
  5650. }
  5651. if (is_false(self.alternative)) {
  5652. // c ? x : false ---> !!c && x
  5653. return make_node(AST_Binary, self, {
  5654. operator: "&&",
  5655. left: booleanize(self.condition),
  5656. right: self.consequent
  5657. });
  5658. }
  5659. return self;
  5660. function booleanize(node) {
  5661. if (node.is_boolean()) return node;
  5662. // !!expression
  5663. return make_node(AST_UnaryPrefix, node, {
  5664. operator: "!",
  5665. expression: node.negate(compressor)
  5666. });
  5667. }
  5668. // AST_True or !0
  5669. function is_true(node) {
  5670. return node instanceof AST_True
  5671. || in_bool
  5672. && node instanceof AST_Constant
  5673. && node.getValue()
  5674. || (node instanceof AST_UnaryPrefix
  5675. && node.operator == "!"
  5676. && node.expression instanceof AST_Constant
  5677. && !node.expression.getValue());
  5678. }
  5679. // AST_False or !1
  5680. function is_false(node) {
  5681. return node instanceof AST_False
  5682. || in_bool
  5683. && node instanceof AST_Constant
  5684. && !node.getValue()
  5685. || (node instanceof AST_UnaryPrefix
  5686. && node.operator == "!"
  5687. && node.expression instanceof AST_Constant
  5688. && node.expression.getValue());
  5689. }
  5690. function single_arg_diff() {
  5691. var a = consequent.args;
  5692. var b = alternative.args;
  5693. for (var i = 0, len = a.length; i < len; i++) {
  5694. if (a[i] instanceof AST_Expansion) return;
  5695. if (!a[i].equivalent_to(b[i])) {
  5696. if (b[i] instanceof AST_Expansion) return;
  5697. for (var j = i + 1; j < len; j++) {
  5698. if (a[j] instanceof AST_Expansion) return;
  5699. if (!a[j].equivalent_to(b[j])) return;
  5700. }
  5701. return i;
  5702. }
  5703. }
  5704. }
  5705. });
  5706. OPT(AST_Boolean, function(self, compressor){
  5707. if (compressor.in_boolean_context()) return make_node(AST_Number, self, {
  5708. value: +self.value
  5709. });
  5710. if (compressor.option("booleans")) {
  5711. var p = compressor.parent();
  5712. if (p instanceof AST_Binary && (p.operator == "=="
  5713. || p.operator == "!=")) {
  5714. compressor.warn("Non-strict equality against boolean: {operator} {value} [{file}:{line},{col}]", {
  5715. operator : p.operator,
  5716. value : self.value,
  5717. file : p.start.file,
  5718. line : p.start.line,
  5719. col : p.start.col,
  5720. });
  5721. return make_node(AST_Number, self, {
  5722. value: +self.value
  5723. });
  5724. }
  5725. return make_node(AST_UnaryPrefix, self, {
  5726. operator: "!",
  5727. expression: make_node(AST_Number, self, {
  5728. value: 1 - self.value
  5729. })
  5730. });
  5731. }
  5732. return self;
  5733. });
  5734. OPT(AST_Sub, function(self, compressor){
  5735. var expr = self.expression;
  5736. var prop = self.property;
  5737. if (compressor.option("properties")) {
  5738. var key = prop.evaluate(compressor);
  5739. if (key !== prop) {
  5740. if (typeof key == "string") {
  5741. if (key == "undefined") {
  5742. key = undefined;
  5743. } else {
  5744. var value = parseFloat(key);
  5745. if (value.toString() == key) {
  5746. key = value;
  5747. }
  5748. }
  5749. }
  5750. prop = self.property = best_of_expression(prop, make_node_from_constant(key, prop).transform(compressor));
  5751. var property = "" + key;
  5752. if (is_identifier_string(property)
  5753. && property.length <= prop.print_to_string().length + 1) {
  5754. return make_node(AST_Dot, self, {
  5755. expression: expr,
  5756. property: property
  5757. }).optimize(compressor);
  5758. }
  5759. }
  5760. }
  5761. if (is_lhs(self, compressor.parent())) return self;
  5762. if (key !== prop) {
  5763. var sub = self.flatten_object(property, compressor);
  5764. if (sub) {
  5765. expr = self.expression = sub.expression;
  5766. prop = self.property = sub.property;
  5767. }
  5768. }
  5769. if (compressor.option("properties") && compressor.option("side_effects")
  5770. && prop instanceof AST_Number && expr instanceof AST_Array) {
  5771. var index = prop.getValue();
  5772. var elements = expr.elements;
  5773. FLATTEN: if (index in elements) {
  5774. var flatten = true;
  5775. var values = [];
  5776. for (var i = elements.length; --i > index;) {
  5777. var value = elements[i].drop_side_effect_free(compressor);
  5778. if (value) {
  5779. values.unshift(value);
  5780. if (flatten && value.has_side_effects(compressor)) flatten = false;
  5781. }
  5782. }
  5783. var retValue = elements[index];
  5784. if (retValue instanceof AST_Expansion) break FLATTEN;
  5785. retValue = retValue instanceof AST_Hole ? make_node(AST_Undefined, retValue) : retValue;
  5786. if (!flatten) values.unshift(retValue);
  5787. while (--i >= 0) {
  5788. var value = elements[i];
  5789. if (value instanceof AST_Expansion) break FLATTEN;
  5790. value = value.drop_side_effect_free(compressor);
  5791. if (value) values.unshift(value);
  5792. else index--;
  5793. }
  5794. if (flatten) {
  5795. values.push(retValue);
  5796. return make_sequence(self, values).optimize(compressor);
  5797. } else return make_node(AST_Sub, self, {
  5798. expression: make_node(AST_Array, expr, {
  5799. elements: values
  5800. }),
  5801. property: make_node(AST_Number, prop, {
  5802. value: index
  5803. })
  5804. });
  5805. }
  5806. }
  5807. var ev = self.evaluate(compressor);
  5808. if (ev !== self) {
  5809. ev = make_node_from_constant(ev, self).optimize(compressor);
  5810. return best_of(compressor, ev, self);
  5811. }
  5812. return self;
  5813. });
  5814. AST_Lambda.DEFMETHOD("contains_this", function() {
  5815. var result;
  5816. var self = this;
  5817. self.walk(new TreeWalker(function(node) {
  5818. if (result) return true;
  5819. if (node instanceof AST_This) return result = true;
  5820. if (node !== self && node instanceof AST_Scope && !(node instanceof AST_Arrow)) return true;
  5821. }));
  5822. return result;
  5823. });
  5824. AST_PropAccess.DEFMETHOD("flatten_object", function(key, compressor) {
  5825. if (!compressor.option("properties")) return;
  5826. var arrows = compressor.option("unsafe_arrows") && compressor.option("ecma") >= 6;
  5827. var expr = this.expression;
  5828. if (expr instanceof AST_Object) {
  5829. var props = expr.properties;
  5830. for (var i = props.length; --i >= 0;) {
  5831. var prop = props[i];
  5832. if ("" + (prop instanceof AST_ConciseMethod ? prop.key.name : prop.key) == key) {
  5833. if (!all(props, function(prop) {
  5834. return prop instanceof AST_ObjectKeyVal
  5835. || arrows && prop instanceof AST_ConciseMethod && !prop.is_generator;
  5836. })) break;
  5837. var value = prop.value;
  5838. if ((value instanceof AST_Accessor || value instanceof AST_Function)
  5839. && !(compressor.parent() instanceof AST_New)
  5840. && value.contains_this()) break;
  5841. return make_node(AST_Sub, this, {
  5842. expression: make_node(AST_Array, expr, {
  5843. elements: props.map(function(prop) {
  5844. var v = prop.value;
  5845. if (v instanceof AST_Accessor) v = make_node(AST_Function, v, v);
  5846. var k = prop.key;
  5847. if (k instanceof AST_Node && !(k instanceof AST_SymbolMethod)) {
  5848. return make_sequence(prop, [ k, v ]);
  5849. }
  5850. return v;
  5851. })
  5852. }),
  5853. property: make_node(AST_Number, this, {
  5854. value: i
  5855. })
  5856. });
  5857. }
  5858. }
  5859. }
  5860. });
  5861. OPT(AST_Dot, function(self, compressor){
  5862. if (self.property == "arguments" || self.property == "caller") {
  5863. compressor.warn("Function.protoype.{prop} not supported [{file}:{line},{col}]", {
  5864. prop: self.property,
  5865. file: self.start.file,
  5866. line: self.start.line,
  5867. col: self.start.col
  5868. });
  5869. }
  5870. var def = self.resolve_defines(compressor);
  5871. if (def) {
  5872. return def.optimize(compressor);
  5873. }
  5874. if (is_lhs(self, compressor.parent())) return self;
  5875. if (compressor.option("unsafe_proto")
  5876. && self.expression instanceof AST_Dot
  5877. && self.expression.property == "prototype") {
  5878. var exp = self.expression.expression;
  5879. if (is_undeclared_ref(exp)) switch (exp.name) {
  5880. case "Array":
  5881. self.expression = make_node(AST_Array, self.expression, {
  5882. elements: []
  5883. });
  5884. break;
  5885. case "Function":
  5886. self.expression = make_node(AST_Function, self.expression, {
  5887. argnames: [],
  5888. body: []
  5889. });
  5890. break;
  5891. case "Number":
  5892. self.expression = make_node(AST_Number, self.expression, {
  5893. value: 0
  5894. });
  5895. break;
  5896. case "Object":
  5897. self.expression = make_node(AST_Object, self.expression, {
  5898. properties: []
  5899. });
  5900. break;
  5901. case "RegExp":
  5902. self.expression = make_node(AST_RegExp, self.expression, {
  5903. value: /t/
  5904. });
  5905. break;
  5906. case "String":
  5907. self.expression = make_node(AST_String, self.expression, {
  5908. value: ""
  5909. });
  5910. break;
  5911. }
  5912. }
  5913. var sub = self.flatten_object(self.property, compressor);
  5914. if (sub) return sub.optimize(compressor);
  5915. var ev = self.evaluate(compressor);
  5916. if (ev !== self) {
  5917. ev = make_node_from_constant(ev, self).optimize(compressor);
  5918. return best_of(compressor, ev, self);
  5919. }
  5920. return self;
  5921. });
  5922. function literals_in_boolean_context(self, compressor) {
  5923. if (compressor.in_boolean_context()) {
  5924. return best_of(compressor, self, make_sequence(self, [
  5925. self,
  5926. make_node(AST_True, self)
  5927. ]).optimize(compressor));
  5928. }
  5929. return self;
  5930. };
  5931. OPT(AST_Array, literals_in_boolean_context);
  5932. OPT(AST_Object, literals_in_boolean_context);
  5933. OPT(AST_RegExp, literals_in_boolean_context);
  5934. OPT(AST_Return, function(self, compressor){
  5935. if (self.value && is_undefined(self.value, compressor)) {
  5936. self.value = null;
  5937. }
  5938. return self;
  5939. });
  5940. OPT(AST_Arrow, function(self, compressor){
  5941. if (!(self.body instanceof AST_Node)) tighten_body(self.body, compressor);
  5942. if (compressor.option("arrows")
  5943. && self.body.length == 1
  5944. && self.body[0] instanceof AST_Return) {
  5945. var value = self.body[0].value;
  5946. self.body = value ? value : [];
  5947. }
  5948. return self;
  5949. });
  5950. OPT(AST_Function, function(self, compressor){
  5951. tighten_body(self.body, compressor);
  5952. if (compressor.option("unsafe_arrows")
  5953. && compressor.option("ecma") >= 6
  5954. && !self.name
  5955. && !self.is_generator
  5956. && !self.uses_arguments
  5957. && !self.uses_eval) {
  5958. var has_special_symbol = false;
  5959. self.walk(new TreeWalker(function(node) {
  5960. if (has_special_symbol) return true;
  5961. if (node instanceof AST_This) {
  5962. has_special_symbol = true;
  5963. return true;
  5964. }
  5965. }));
  5966. if (!has_special_symbol) return make_node(AST_Arrow, self, self).optimize(compressor);
  5967. }
  5968. return self;
  5969. });
  5970. OPT(AST_Class, function(self, compressor){
  5971. // HACK to avoid compress failure.
  5972. // AST_Class is not really an AST_Scope/AST_Block as it lacks a body.
  5973. return self;
  5974. });
  5975. OPT(AST_Yield, function(self, compressor){
  5976. if (self.expression && !self.is_star && is_undefined(self.expression, compressor)) {
  5977. self.expression = null;
  5978. }
  5979. return self;
  5980. });
  5981. OPT(AST_VarDef, function(self, compressor){
  5982. var defines = compressor.option("global_defs");
  5983. if (defines && HOP(defines, self.name.name)) {
  5984. compressor.warn('global_defs ' + self.name.name + ' redefined [{file}:{line},{col}]', self.start);
  5985. }
  5986. return self;
  5987. });
  5988. OPT(AST_TemplateString, function(self, compressor){
  5989. if (!compressor.option("evaluate")
  5990. || compressor.parent() instanceof AST_PrefixedTemplateString)
  5991. return self;
  5992. var segments = [];
  5993. for (var i = 0; i < self.segments.length; i++) {
  5994. var segment = self.segments[i];
  5995. if (segment instanceof AST_Node) {
  5996. var result = segment.evaluate(compressor);
  5997. // Evaluate to constant value
  5998. // Constant value shorter than ${segment}
  5999. if (result !== segment && (result + "").length <= segment.print_to_string().length + "${}".length) {
  6000. // There should always be a previous and next segment if segment is a node
  6001. segments[segments.length - 1].value = segments[segments.length - 1].value + result + self.segments[++i].value;
  6002. continue;
  6003. }
  6004. }
  6005. segments.push(segment);
  6006. }
  6007. self.segments = segments;
  6008. return segments.length == 1 ? make_node(AST_String, self, segments[0]) : self;
  6009. });
  6010. OPT(AST_PrefixedTemplateString, function(self, compressor){
  6011. return self;
  6012. });
  6013. // ["p"]:1 ---> p:1
  6014. // [42]:1 ---> 42:1
  6015. function lift_key(self, compressor) {
  6016. if (!compressor.option("computed_props")) return self;
  6017. // save a comparison in the typical case
  6018. if (!(self.key instanceof AST_Constant)) return self;
  6019. // whitelist acceptable props as not all AST_Constants are true constants
  6020. if (self.key instanceof AST_String || self.key instanceof AST_Number) {
  6021. if (self.key.value == "constructor"
  6022. && compressor.parent() instanceof AST_Class) return self;
  6023. if (self instanceof AST_ObjectKeyVal) {
  6024. self.key = self.key.value;
  6025. } else {
  6026. self.key = make_node(AST_SymbolMethod, self.key, {
  6027. name: self.key.value
  6028. });
  6029. }
  6030. }
  6031. return self;
  6032. }
  6033. OPT(AST_ObjectProperty, lift_key);
  6034. OPT(AST_ConciseMethod, function(self, compressor){
  6035. lift_key(self, compressor);
  6036. // p(){return x;} ---> p:()=>x
  6037. if (compressor.option("arrows")
  6038. && compressor.parent() instanceof AST_Object
  6039. && !self.value.uses_arguments
  6040. && !self.value.uses_eval
  6041. && self.value.body.length == 1
  6042. && self.value.body[0] instanceof AST_Return
  6043. && self.value.body[0].value
  6044. && !self.value.contains_this()) {
  6045. var arrow = make_node(AST_Arrow, self.value, self.value);
  6046. arrow.async = self.async;
  6047. arrow.is_generator = self.is_generator;
  6048. return make_node(AST_ObjectKeyVal, self, {
  6049. key: self.key instanceof AST_SymbolMethod ? self.key.name : self.key,
  6050. value: arrow,
  6051. quote: self.quote,
  6052. });
  6053. }
  6054. return self;
  6055. });
  6056. OPT(AST_ObjectKeyVal, function(self, compressor){
  6057. lift_key(self, compressor);
  6058. // p:function(){} ---> p(){}
  6059. // p:function*(){} ---> *p(){}
  6060. // p:async function(){} ---> async p(){}
  6061. // p:()=>{} ---> p(){}
  6062. // p:async()=>{} ---> async p(){}
  6063. var unsafe_methods = compressor.option("unsafe_methods");
  6064. if (unsafe_methods
  6065. && compressor.option("ecma") >= 6
  6066. && (!(unsafe_methods instanceof RegExp) || unsafe_methods.test(self.key + ""))) {
  6067. var key = self.key;
  6068. var value = self.value;
  6069. var is_arrow_with_block = value instanceof AST_Arrow
  6070. && Array.isArray(value.body)
  6071. && !value.contains_this();
  6072. if ((is_arrow_with_block || value instanceof AST_Function) && !value.name) {
  6073. return make_node(AST_ConciseMethod, self, {
  6074. async: value.async,
  6075. is_generator: value.is_generator,
  6076. key: key instanceof AST_Node ? key : make_node(AST_SymbolMethod, self, {
  6077. name: key,
  6078. }),
  6079. value: make_node(AST_Accessor, value, value),
  6080. quote: self.quote,
  6081. });
  6082. }
  6083. }
  6084. return self;
  6085. });
  6086. })();