a zip code crypto-currency system good for red ONLY

compress.js 230KB

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