You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

compress.js 363KB

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