compress.js 286 KB

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