compress.js 287 KB

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