compress.js 267 KB

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