compress.js 269 KB

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