compress.js 285 KB

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