uglify.js 204 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805
  1. (function(global) {
  2. (function(/*! Stitch !*/) {
  3. if (!this.require) {
  4. var modules = {}, cache = {}, require = function(name, root) {
  5. var module = cache[name], path = expand(root, name), fn;
  6. if (module) {
  7. return module;
  8. } else if (fn = modules[path] || modules[path = expand(path, './index')]) {
  9. module = {id: name, exports: {}};
  10. try {
  11. cache[name] = module.exports;
  12. fn(module.exports, function(name) {
  13. return require(name, dirname(path));
  14. }, module);
  15. return cache[name] = module.exports;
  16. } catch (err) {
  17. delete cache[name];
  18. throw err;
  19. }
  20. } else {
  21. throw 'module \'' + name + '\' not found';
  22. }
  23. }, expand = function(root, name) {
  24. var results = [], parts, part;
  25. if (/^\.\.?(\/|$)/.test(name)) {
  26. parts = [root, name].join('/').split('/');
  27. } else {
  28. parts = name.split('/');
  29. }
  30. for (var i = 0, length = parts.length; i < length; i++) {
  31. part = parts[i];
  32. if (part == '..') {
  33. results.pop();
  34. } else if (part != '.' && part != '') {
  35. results.push(part);
  36. }
  37. }
  38. return results.join('/');
  39. }, dirname = function(path) {
  40. return path.split('/').slice(0, -1).join('/');
  41. };
  42. this.require = function(name) {
  43. return require(name, '');
  44. }
  45. this.require.define = function(bundle) {
  46. for (var key in bundle)
  47. modules[key] = bundle[key];
  48. };
  49. }
  50. return this.require.define;
  51. }).call(this)({"consolidator": function(exports, require, module) {/**
  52. * @preserve Copyright 2012 Robert Gust-Bardon <http://robert.gust-bardon.org/>.
  53. * All rights reserved.
  54. *
  55. * Redistribution and use in source and binary forms, with or without
  56. * modification, are permitted provided that the following conditions
  57. * are met:
  58. *
  59. * * Redistributions of source code must retain the above
  60. * copyright notice, this list of conditions and the following
  61. * disclaimer.
  62. *
  63. * * Redistributions in binary form must reproduce the above
  64. * copyright notice, this list of conditions and the following
  65. * disclaimer in the documentation and/or other materials
  66. * provided with the distribution.
  67. *
  68. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER "AS IS" AND ANY
  69. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  70. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  71. * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
  72. * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
  73. * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  74. * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  75. * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  76. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
  77. * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
  78. * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  79. * SUCH DAMAGE.
  80. */
  81. /**
  82. * @fileoverview Enhances <a href="https://github.com/mishoo/UglifyJS/"
  83. * >UglifyJS</a> with consolidation of null, Boolean, and String values.
  84. * <p>Also known as aliasing, this feature has been deprecated in <a href=
  85. * "http://closure-compiler.googlecode.com/">the Closure Compiler</a> since its
  86. * initial release, where it is unavailable from the <abbr title=
  87. * "command line interface">CLI</a>. The Closure Compiler allows one to log and
  88. * influence this process. In contrast, this implementation does not introduce
  89. * any variable declarations in global code and derives String values from
  90. * identifier names used as property accessors.</p>
  91. * <p>Consolidating literals may worsen the data compression ratio when an <a
  92. * href="http://tools.ietf.org/html/rfc2616#section-3.5">encoding
  93. * transformation</a> is applied. For instance, <a href=
  94. * "http://code.jquery.com/jquery-1.7.1.js">jQuery 1.7.1</a> takes 248235 bytes.
  95. * Building it with <a href="https://github.com/mishoo/UglifyJS/tarball/v1.2.5">
  96. * UglifyJS v1.2.5</a> results in 93647 bytes (37.73% of the original) which are
  97. * then compressed to 33154 bytes (13.36% of the original) using <a href=
  98. * "http://linux.die.net/man/1/gzip">gzip(1)</a>. Building it with the same
  99. * version of UglifyJS 1.2.5 patched with the implementation of consolidation
  100. * results in 80784 bytes (a decrease of 12863 bytes, i.e. 13.74%, in comparison
  101. * to the aforementioned 93647 bytes) which are then compressed to 34013 bytes
  102. * (an increase of 859 bytes, i.e. 2.59%, in comparison to the aforementioned
  103. * 33154 bytes).</p>
  104. * <p>Written in <a href="http://es5.github.com/#x4.2.2">the strict variant</a>
  105. * of <a href="http://es5.github.com/">ECMA-262 5.1 Edition</a>. Encoded in <a
  106. * href="http://tools.ietf.org/html/rfc3629">UTF-8</a>. Follows <a href=
  107. * "http://google-styleguide.googlecode.com/svn-history/r76/trunk/javascriptguide.xml"
  108. * >Revision 2.28 of the Google JavaScript Style Guide</a> (except for the
  109. * discouraged use of the {@code function} tag and the {@code namespace} tag).
  110. * 100% typed for the <a href=
  111. * "http://closure-compiler.googlecode.com/files/compiler-20120123.tar.gz"
  112. * >Closure Compiler Version 1741</a>.</p>
  113. * <p>Should you find this software useful, please consider <a href=
  114. * "https://paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=JZLW72X8FD4WG"
  115. * >a donation</a>.</p>
  116. * @author follow.me@RGustBardon (Robert Gust-Bardon)
  117. * @supported Tested with:
  118. * <ul>
  119. * <li><a href="http://nodejs.org/dist/v0.6.10/">Node v0.6.10</a>,</li>
  120. * <li><a href="https://github.com/mishoo/UglifyJS/tarball/v1.2.5">UglifyJS
  121. * v1.2.5</a>.</li>
  122. * </ul>
  123. */
  124. /*global console:false, exports:true, module:false, require:false */
  125. /*jshint sub:true */
  126. /**
  127. * Consolidates null, Boolean, and String values found inside an <abbr title=
  128. * "abstract syntax tree">AST</abbr>.
  129. * @param {!TSyntacticCodeUnit} oAbstractSyntaxTree An array-like object
  130. * representing an <abbr title="abstract syntax tree">AST</abbr>.
  131. * @return {!TSyntacticCodeUnit} An array-like object representing an <abbr
  132. * title="abstract syntax tree">AST</abbr> with its null, Boolean, and
  133. * String values consolidated.
  134. */
  135. // TODO(user) Consolidation of mathematical values found in numeric literals.
  136. // TODO(user) Unconsolidation.
  137. // TODO(user) Consolidation of ECMA-262 6th Edition programs.
  138. // TODO(user) Rewrite in ECMA-262 6th Edition.
  139. exports['ast_consolidate'] = function(oAbstractSyntaxTree) {
  140. 'use strict';
  141. /*jshint bitwise:true, curly:true, eqeqeq:true, forin:true, immed:true,
  142. latedef:true, newcap:true, noarge:true, noempty:true, nonew:true,
  143. onevar:true, plusplus:true, regexp:true, undef:true, strict:true,
  144. sub:false, trailing:true */
  145. var _,
  146. /**
  147. * A record consisting of data about one or more source elements.
  148. * @constructor
  149. * @nosideeffects
  150. */
  151. TSourceElementsData = function() {
  152. /**
  153. * The category of the elements.
  154. * @type {number}
  155. * @see ESourceElementCategories
  156. */
  157. this.nCategory = ESourceElementCategories.N_OTHER;
  158. /**
  159. * The number of occurrences (within the elements) of each primitive
  160. * value that could be consolidated.
  161. * @type {!Array.<!Object.<string, number>>}
  162. */
  163. this.aCount = [];
  164. this.aCount[EPrimaryExpressionCategories.N_IDENTIFIER_NAMES] = {};
  165. this.aCount[EPrimaryExpressionCategories.N_STRING_LITERALS] = {};
  166. this.aCount[EPrimaryExpressionCategories.N_NULL_AND_BOOLEAN_LITERALS] =
  167. {};
  168. /**
  169. * Identifier names found within the elements.
  170. * @type {!Array.<string>}
  171. */
  172. this.aIdentifiers = [];
  173. /**
  174. * Prefixed representation Strings of each primitive value that could be
  175. * consolidated within the elements.
  176. * @type {!Array.<string>}
  177. */
  178. this.aPrimitiveValues = [];
  179. },
  180. /**
  181. * A record consisting of data about a primitive value that could be
  182. * consolidated.
  183. * @constructor
  184. * @nosideeffects
  185. */
  186. TPrimitiveValue = function() {
  187. /**
  188. * The difference in the number of terminal symbols between the original
  189. * source text and the one with the primitive value consolidated. If the
  190. * difference is positive, the primitive value is considered worthwhile.
  191. * @type {number}
  192. */
  193. this.nSaving = 0;
  194. /**
  195. * An identifier name of the variable that will be declared and assigned
  196. * the primitive value if the primitive value is consolidated.
  197. * @type {string}
  198. */
  199. this.sName = '';
  200. },
  201. /**
  202. * A record consisting of data on what to consolidate within the range of
  203. * source elements that is currently being considered.
  204. * @constructor
  205. * @nosideeffects
  206. */
  207. TSolution = function() {
  208. /**
  209. * An object whose keys are prefixed representation Strings of each
  210. * primitive value that could be consolidated within the elements and
  211. * whose values are corresponding data about those primitive values.
  212. * @type {!Object.<string, {nSaving: number, sName: string}>}
  213. * @see TPrimitiveValue
  214. */
  215. this.oPrimitiveValues = {};
  216. /**
  217. * The difference in the number of terminal symbols between the original
  218. * source text and the one with all the worthwhile primitive values
  219. * consolidated.
  220. * @type {number}
  221. * @see TPrimitiveValue#nSaving
  222. */
  223. this.nSavings = 0;
  224. },
  225. /**
  226. * The processor of <abbr title="abstract syntax tree">AST</abbr>s found
  227. * in UglifyJS.
  228. * @namespace
  229. * @type {!TProcessor}
  230. */
  231. oProcessor = (/** @type {!TProcessor} */ require('./process')),
  232. /**
  233. * A record consisting of a number of constants that represent the
  234. * difference in the number of terminal symbols between a source text with
  235. * a modified syntactic code unit and the original one.
  236. * @namespace
  237. * @type {!Object.<string, number>}
  238. */
  239. oWeights = {
  240. /**
  241. * The difference in the number of punctuators required by the bracket
  242. * notation and the dot notation.
  243. * <p><code>'[]'.length - '.'.length</code></p>
  244. * @const
  245. * @type {number}
  246. */
  247. N_PROPERTY_ACCESSOR: 1,
  248. /**
  249. * The number of punctuators required by a variable declaration with an
  250. * initialiser.
  251. * <p><code>':'.length + ';'.length</code></p>
  252. * @const
  253. * @type {number}
  254. */
  255. N_VARIABLE_DECLARATION: 2,
  256. /**
  257. * The number of terminal symbols required to introduce a variable
  258. * statement (excluding its variable declaration list).
  259. * <p><code>'var '.length</code></p>
  260. * @const
  261. * @type {number}
  262. */
  263. N_VARIABLE_STATEMENT_AFFIXATION: 4,
  264. /**
  265. * The number of terminal symbols needed to enclose source elements
  266. * within a function call with no argument values to a function with an
  267. * empty parameter list.
  268. * <p><code>'(function(){}());'.length</code></p>
  269. * @const
  270. * @type {number}
  271. */
  272. N_CLOSURE: 17
  273. },
  274. /**
  275. * Categories of primary expressions from which primitive values that
  276. * could be consolidated are derivable.
  277. * @namespace
  278. * @enum {number}
  279. */
  280. EPrimaryExpressionCategories = {
  281. /**
  282. * Identifier names used as property accessors.
  283. * @type {number}
  284. */
  285. N_IDENTIFIER_NAMES: 0,
  286. /**
  287. * String literals.
  288. * @type {number}
  289. */
  290. N_STRING_LITERALS: 1,
  291. /**
  292. * Null and Boolean literals.
  293. * @type {number}
  294. */
  295. N_NULL_AND_BOOLEAN_LITERALS: 2
  296. },
  297. /**
  298. * Prefixes of primitive values that could be consolidated.
  299. * The String values of the prefixes must have same number of characters.
  300. * The prefixes must not be used in any properties defined in any version
  301. * of <a href=
  302. * "http://www.ecma-international.org/publications/standards/Ecma-262.htm"
  303. * >ECMA-262</a>.
  304. * @namespace
  305. * @enum {string}
  306. */
  307. EValuePrefixes = {
  308. /**
  309. * Identifies String values.
  310. * @type {string}
  311. */
  312. S_STRING: '#S',
  313. /**
  314. * Identifies null and Boolean values.
  315. * @type {string}
  316. */
  317. S_SYMBOLIC: '#O'
  318. },
  319. /**
  320. * Categories of source elements in terms of their appropriateness of
  321. * having their primitive values consolidated.
  322. * @namespace
  323. * @enum {number}
  324. */
  325. ESourceElementCategories = {
  326. /**
  327. * Identifies a source element that includes the <a href=
  328. * "http://es5.github.com/#x12.10">{@code with}</a> statement.
  329. * @type {number}
  330. */
  331. N_WITH: 0,
  332. /**
  333. * Identifies a source element that includes the <a href=
  334. * "http://es5.github.com/#x15.1.2.1">{@code eval}</a> identifier name.
  335. * @type {number}
  336. */
  337. N_EVAL: 1,
  338. /**
  339. * Identifies a source element that must be excluded from the process
  340. * unless its whole scope is examined.
  341. * @type {number}
  342. */
  343. N_EXCLUDABLE: 2,
  344. /**
  345. * Identifies source elements not posing any problems.
  346. * @type {number}
  347. */
  348. N_OTHER: 3
  349. },
  350. /**
  351. * The list of literals (other than the String ones) whose primitive
  352. * values can be consolidated.
  353. * @const
  354. * @type {!Array.<string>}
  355. */
  356. A_OTHER_SUBSTITUTABLE_LITERALS = [
  357. 'null', // The null literal.
  358. 'false', // The Boolean literal {@code false}.
  359. 'true' // The Boolean literal {@code true}.
  360. ];
  361. (/**
  362. * Consolidates all worthwhile primitive values in a syntactic code unit.
  363. * @param {!TSyntacticCodeUnit} oSyntacticCodeUnit An array-like object
  364. * representing the branch of the abstract syntax tree representing the
  365. * syntactic code unit along with its scope.
  366. * @see TPrimitiveValue#nSaving
  367. */
  368. function fExamineSyntacticCodeUnit(oSyntacticCodeUnit) {
  369. var _,
  370. /**
  371. * Indicates whether the syntactic code unit represents global code.
  372. * @type {boolean}
  373. */
  374. bIsGlobal = 'toplevel' === oSyntacticCodeUnit[0],
  375. /**
  376. * Indicates whether the whole scope is being examined.
  377. * @type {boolean}
  378. */
  379. bIsWhollyExaminable = !bIsGlobal,
  380. /**
  381. * An array-like object representing source elements that constitute a
  382. * syntactic code unit.
  383. * @type {!TSyntacticCodeUnit}
  384. */
  385. oSourceElements,
  386. /**
  387. * A record consisting of data about the source element that is
  388. * currently being examined.
  389. * @type {!TSourceElementsData}
  390. */
  391. oSourceElementData,
  392. /**
  393. * The scope of the syntactic code unit.
  394. * @type {!TScope}
  395. */
  396. oScope,
  397. /**
  398. * An instance of an object that allows the traversal of an <abbr
  399. * title="abstract syntax tree">AST</abbr>.
  400. * @type {!TWalker}
  401. */
  402. oWalker,
  403. /**
  404. * An object encompassing collections of functions used during the
  405. * traversal of an <abbr title="abstract syntax tree">AST</abbr>.
  406. * @namespace
  407. * @type {!Object.<string, !Object.<string, function(...[*])>>}
  408. */
  409. oWalkers = {
  410. /**
  411. * A collection of functions used during the surveyance of source
  412. * elements.
  413. * @namespace
  414. * @type {!Object.<string, function(...[*])>}
  415. */
  416. oSurveySourceElement: {
  417. /**#nocode+*/ // JsDoc Toolkit 2.4.0 hides some of the keys.
  418. /**
  419. * Classifies the source element as excludable if it does not
  420. * contain a {@code with} statement or the {@code eval} identifier
  421. * name. Adds the identifier of the function and its formal
  422. * parameters to the list of identifier names found.
  423. * @param {string} sIdentifier The identifier of the function.
  424. * @param {!Array.<string>} aFormalParameterList Formal parameters.
  425. * @param {!TSyntacticCodeUnit} oFunctionBody Function code.
  426. */
  427. 'defun': function(
  428. sIdentifier,
  429. aFormalParameterList,
  430. oFunctionBody) {
  431. fClassifyAsExcludable();
  432. fAddIdentifier(sIdentifier);
  433. aFormalParameterList.forEach(fAddIdentifier);
  434. },
  435. /**
  436. * Increments the count of the number of occurrences of the String
  437. * value that is equivalent to the sequence of terminal symbols
  438. * that constitute the encountered identifier name.
  439. * @param {!TSyntacticCodeUnit} oExpression The nonterminal
  440. * MemberExpression.
  441. * @param {string} sIdentifierName The identifier name used as the
  442. * property accessor.
  443. * @return {!Array} The encountered branch of an <abbr title=
  444. * "abstract syntax tree">AST</abbr> with its nonterminal
  445. * MemberExpression traversed.
  446. */
  447. 'dot': function(oExpression, sIdentifierName) {
  448. fCountPrimaryExpression(
  449. EPrimaryExpressionCategories.N_IDENTIFIER_NAMES,
  450. EValuePrefixes.S_STRING + sIdentifierName);
  451. return ['dot', oWalker.walk(oExpression), sIdentifierName];
  452. },
  453. /**
  454. * Adds the optional identifier of the function and its formal
  455. * parameters to the list of identifier names found.
  456. * @param {?string} sIdentifier The optional identifier of the
  457. * function.
  458. * @param {!Array.<string>} aFormalParameterList Formal parameters.
  459. * @param {!TSyntacticCodeUnit} oFunctionBody Function code.
  460. */
  461. 'function': function(
  462. sIdentifier,
  463. aFormalParameterList,
  464. oFunctionBody) {
  465. if ('string' === typeof sIdentifier) {
  466. fAddIdentifier(sIdentifier);
  467. }
  468. aFormalParameterList.forEach(fAddIdentifier);
  469. },
  470. /**
  471. * Either increments the count of the number of occurrences of the
  472. * encountered null or Boolean value or classifies a source element
  473. * as containing the {@code eval} identifier name.
  474. * @param {string} sIdentifier The identifier encountered.
  475. */
  476. 'name': function(sIdentifier) {
  477. if (-1 !== A_OTHER_SUBSTITUTABLE_LITERALS.indexOf(sIdentifier)) {
  478. fCountPrimaryExpression(
  479. EPrimaryExpressionCategories.N_NULL_AND_BOOLEAN_LITERALS,
  480. EValuePrefixes.S_SYMBOLIC + sIdentifier);
  481. } else {
  482. if ('eval' === sIdentifier) {
  483. oSourceElementData.nCategory =
  484. ESourceElementCategories.N_EVAL;
  485. }
  486. fAddIdentifier(sIdentifier);
  487. }
  488. },
  489. /**
  490. * Classifies the source element as excludable if it does not
  491. * contain a {@code with} statement or the {@code eval} identifier
  492. * name.
  493. * @param {TSyntacticCodeUnit} oExpression The expression whose
  494. * value is to be returned.
  495. */
  496. 'return': function(oExpression) {
  497. fClassifyAsExcludable();
  498. },
  499. /**
  500. * Increments the count of the number of occurrences of the
  501. * encountered String value.
  502. * @param {string} sStringValue The String value of the string
  503. * literal encountered.
  504. */
  505. 'string': function(sStringValue) {
  506. if (sStringValue.length > 0) {
  507. fCountPrimaryExpression(
  508. EPrimaryExpressionCategories.N_STRING_LITERALS,
  509. EValuePrefixes.S_STRING + sStringValue);
  510. }
  511. },
  512. /**
  513. * Adds the identifier reserved for an exception to the list of
  514. * identifier names found.
  515. * @param {!TSyntacticCodeUnit} oTry A block of code in which an
  516. * exception can occur.
  517. * @param {Array} aCatch The identifier reserved for an exception
  518. * and a block of code to handle the exception.
  519. * @param {TSyntacticCodeUnit} oFinally An optional block of code
  520. * to be evaluated regardless of whether an exception occurs.
  521. */
  522. 'try': function(oTry, aCatch, oFinally) {
  523. if (Array.isArray(aCatch)) {
  524. fAddIdentifier(aCatch[0]);
  525. }
  526. },
  527. /**
  528. * Classifies the source element as excludable if it does not
  529. * contain a {@code with} statement or the {@code eval} identifier
  530. * name. Adds the identifier of each declared variable to the list
  531. * of identifier names found.
  532. * @param {!Array.<!Array>} aVariableDeclarationList Variable
  533. * declarations.
  534. */
  535. 'var': function(aVariableDeclarationList) {
  536. fClassifyAsExcludable();
  537. aVariableDeclarationList.forEach(fAddVariable);
  538. },
  539. /**
  540. * Classifies a source element as containing the {@code with}
  541. * statement.
  542. * @param {!TSyntacticCodeUnit} oExpression An expression whose
  543. * value is to be converted to a value of type Object and
  544. * become the binding object of a new object environment
  545. * record of a new lexical environment in which the statement
  546. * is to be executed.
  547. * @param {!TSyntacticCodeUnit} oStatement The statement to be
  548. * executed in the augmented lexical environment.
  549. * @return {!Array} An empty array to stop the traversal.
  550. */
  551. 'with': function(oExpression, oStatement) {
  552. oSourceElementData.nCategory = ESourceElementCategories.N_WITH;
  553. return [];
  554. }
  555. /**#nocode-*/ // JsDoc Toolkit 2.4.0 hides some of the keys.
  556. },
  557. /**
  558. * A collection of functions used while looking for nested functions.
  559. * @namespace
  560. * @type {!Object.<string, function(...[*])>}
  561. */
  562. oExamineFunctions: {
  563. /**#nocode+*/ // JsDoc Toolkit 2.4.0 hides some of the keys.
  564. /**
  565. * Orders an examination of a nested function declaration.
  566. * @this {!TSyntacticCodeUnit} An array-like object representing
  567. * the branch of an <abbr title="abstract syntax tree"
  568. * >AST</abbr> representing the syntactic code unit along with
  569. * its scope.
  570. * @return {!Array} An empty array to stop the traversal.
  571. */
  572. 'defun': function() {
  573. fExamineSyntacticCodeUnit(this);
  574. return [];
  575. },
  576. /**
  577. * Orders an examination of a nested function expression.
  578. * @this {!TSyntacticCodeUnit} An array-like object representing
  579. * the branch of an <abbr title="abstract syntax tree"
  580. * >AST</abbr> representing the syntactic code unit along with
  581. * its scope.
  582. * @return {!Array} An empty array to stop the traversal.
  583. */
  584. 'function': function() {
  585. fExamineSyntacticCodeUnit(this);
  586. return [];
  587. }
  588. /**#nocode-*/ // JsDoc Toolkit 2.4.0 hides some of the keys.
  589. }
  590. },
  591. /**
  592. * Records containing data about source elements.
  593. * @type {Array.<TSourceElementsData>}
  594. */
  595. aSourceElementsData = [],
  596. /**
  597. * The index (in the source text order) of the source element
  598. * immediately following a <a href="http://es5.github.com/#x14.1"
  599. * >Directive Prologue</a>.
  600. * @type {number}
  601. */
  602. nAfterDirectivePrologue = 0,
  603. /**
  604. * The index (in the source text order) of the source element that is
  605. * currently being considered.
  606. * @type {number}
  607. */
  608. nPosition,
  609. /**
  610. * The index (in the source text order) of the source element that is
  611. * the last element of the range of source elements that is currently
  612. * being considered.
  613. * @type {(undefined|number)}
  614. */
  615. nTo,
  616. /**
  617. * Initiates the traversal of a source element.
  618. * @param {!TWalker} oWalker An instance of an object that allows the
  619. * traversal of an abstract syntax tree.
  620. * @param {!TSyntacticCodeUnit} oSourceElement A source element from
  621. * which the traversal should commence.
  622. * @return {function(): !TSyntacticCodeUnit} A function that is able to
  623. * initiate the traversal from a given source element.
  624. */
  625. cContext = function(oWalker, oSourceElement) {
  626. /**
  627. * @return {!TSyntacticCodeUnit} A function that is able to
  628. * initiate the traversal from a given source element.
  629. */
  630. var fLambda = function() {
  631. return oWalker.walk(oSourceElement);
  632. };
  633. return fLambda;
  634. },
  635. /**
  636. * Classifies the source element as excludable if it does not
  637. * contain a {@code with} statement or the {@code eval} identifier
  638. * name.
  639. */
  640. fClassifyAsExcludable = function() {
  641. if (oSourceElementData.nCategory ===
  642. ESourceElementCategories.N_OTHER) {
  643. oSourceElementData.nCategory =
  644. ESourceElementCategories.N_EXCLUDABLE;
  645. }
  646. },
  647. /**
  648. * Adds an identifier to the list of identifier names found.
  649. * @param {string} sIdentifier The identifier to be added.
  650. */
  651. fAddIdentifier = function(sIdentifier) {
  652. if (-1 === oSourceElementData.aIdentifiers.indexOf(sIdentifier)) {
  653. oSourceElementData.aIdentifiers.push(sIdentifier);
  654. }
  655. },
  656. /**
  657. * Adds the identifier of a variable to the list of identifier names
  658. * found.
  659. * @param {!Array} aVariableDeclaration A variable declaration.
  660. */
  661. fAddVariable = function(aVariableDeclaration) {
  662. fAddIdentifier(/** @type {string} */ aVariableDeclaration[0]);
  663. },
  664. /**
  665. * Increments the count of the number of occurrences of the prefixed
  666. * String representation attributed to the primary expression.
  667. * @param {number} nCategory The category of the primary expression.
  668. * @param {string} sName The prefixed String representation attributed
  669. * to the primary expression.
  670. */
  671. fCountPrimaryExpression = function(nCategory, sName) {
  672. if (!oSourceElementData.aCount[nCategory].hasOwnProperty(sName)) {
  673. oSourceElementData.aCount[nCategory][sName] = 0;
  674. if (-1 === oSourceElementData.aPrimitiveValues.indexOf(sName)) {
  675. oSourceElementData.aPrimitiveValues.push(sName);
  676. }
  677. }
  678. oSourceElementData.aCount[nCategory][sName] += 1;
  679. },
  680. /**
  681. * Consolidates all worthwhile primitive values in a range of source
  682. * elements.
  683. * @param {number} nFrom The index (in the source text order) of the
  684. * source element that is the first element of the range.
  685. * @param {number} nTo The index (in the source text order) of the
  686. * source element that is the last element of the range.
  687. * @param {boolean} bEnclose Indicates whether the range should be
  688. * enclosed within a function call with no argument values to a
  689. * function with an empty parameter list if any primitive values
  690. * are consolidated.
  691. * @see TPrimitiveValue#nSaving
  692. */
  693. fExamineSourceElements = function(nFrom, nTo, bEnclose) {
  694. var _,
  695. /**
  696. * The index of the last mangled name.
  697. * @type {number}
  698. */
  699. nIndex = oScope.cname,
  700. /**
  701. * The index of the source element that is currently being
  702. * considered.
  703. * @type {number}
  704. */
  705. nPosition,
  706. /**
  707. * A collection of functions used during the consolidation of
  708. * primitive values and identifier names used as property
  709. * accessors.
  710. * @namespace
  711. * @type {!Object.<string, function(...[*])>}
  712. */
  713. oWalkersTransformers = {
  714. /**
  715. * If the String value that is equivalent to the sequence of
  716. * terminal symbols that constitute the encountered identifier
  717. * name is worthwhile, a syntactic conversion from the dot
  718. * notation to the bracket notation ensues with that sequence
  719. * being substituted by an identifier name to which the value
  720. * is assigned.
  721. * Applies to property accessors that use the dot notation.
  722. * @param {!TSyntacticCodeUnit} oExpression The nonterminal
  723. * MemberExpression.
  724. * @param {string} sIdentifierName The identifier name used as
  725. * the property accessor.
  726. * @return {!Array} A syntactic code unit that is equivalent to
  727. * the one encountered.
  728. * @see TPrimitiveValue#nSaving
  729. */
  730. 'dot': function(oExpression, sIdentifierName) {
  731. /**
  732. * The prefixed String value that is equivalent to the
  733. * sequence of terminal symbols that constitute the
  734. * encountered identifier name.
  735. * @type {string}
  736. */
  737. var sPrefixed = EValuePrefixes.S_STRING + sIdentifierName;
  738. return oSolutionBest.oPrimitiveValues.hasOwnProperty(
  739. sPrefixed) &&
  740. oSolutionBest.oPrimitiveValues[sPrefixed].nSaving > 0 ?
  741. ['sub',
  742. oWalker.walk(oExpression),
  743. ['name',
  744. oSolutionBest.oPrimitiveValues[sPrefixed].sName]] :
  745. ['dot', oWalker.walk(oExpression), sIdentifierName];
  746. },
  747. /**
  748. * If the encountered identifier is a null or Boolean literal
  749. * and its value is worthwhile, the identifier is substituted
  750. * by an identifier name to which that value is assigned.
  751. * Applies to identifier names.
  752. * @param {string} sIdentifier The identifier encountered.
  753. * @return {!Array} A syntactic code unit that is equivalent to
  754. * the one encountered.
  755. * @see TPrimitiveValue#nSaving
  756. */
  757. 'name': function(sIdentifier) {
  758. /**
  759. * The prefixed representation String of the identifier.
  760. * @type {string}
  761. */
  762. var sPrefixed = EValuePrefixes.S_SYMBOLIC + sIdentifier;
  763. return [
  764. 'name',
  765. oSolutionBest.oPrimitiveValues.hasOwnProperty(sPrefixed) &&
  766. oSolutionBest.oPrimitiveValues[sPrefixed].nSaving > 0 ?
  767. oSolutionBest.oPrimitiveValues[sPrefixed].sName :
  768. sIdentifier
  769. ];
  770. },
  771. /**
  772. * If the encountered String value is worthwhile, it is
  773. * substituted by an identifier name to which that value is
  774. * assigned.
  775. * Applies to String values.
  776. * @param {string} sStringValue The String value of the string
  777. * literal encountered.
  778. * @return {!Array} A syntactic code unit that is equivalent to
  779. * the one encountered.
  780. * @see TPrimitiveValue#nSaving
  781. */
  782. 'string': function(sStringValue) {
  783. /**
  784. * The prefixed representation String of the primitive value
  785. * of the literal.
  786. * @type {string}
  787. */
  788. var sPrefixed =
  789. EValuePrefixes.S_STRING + sStringValue;
  790. return oSolutionBest.oPrimitiveValues.hasOwnProperty(
  791. sPrefixed) &&
  792. oSolutionBest.oPrimitiveValues[sPrefixed].nSaving > 0 ?
  793. ['name',
  794. oSolutionBest.oPrimitiveValues[sPrefixed].sName] :
  795. ['string', sStringValue];
  796. }
  797. },
  798. /**
  799. * Such data on what to consolidate within the range of source
  800. * elements that is currently being considered that lead to the
  801. * greatest known reduction of the number of the terminal symbols
  802. * in comparison to the original source text.
  803. * @type {!TSolution}
  804. */
  805. oSolutionBest = new TSolution(),
  806. /**
  807. * Data representing an ongoing attempt to find a better
  808. * reduction of the number of the terminal symbols in comparison
  809. * to the original source text than the best one that is
  810. * currently known.
  811. * @type {!TSolution}
  812. * @see oSolutionBest
  813. */
  814. oSolutionCandidate = new TSolution(),
  815. /**
  816. * A record consisting of data about the range of source elements
  817. * that is currently being examined.
  818. * @type {!TSourceElementsData}
  819. */
  820. oSourceElementsData = new TSourceElementsData(),
  821. /**
  822. * Variable declarations for each primitive value that is to be
  823. * consolidated within the elements.
  824. * @type {!Array.<!Array>}
  825. */
  826. aVariableDeclarations = [],
  827. /**
  828. * Augments a list with a prefixed representation String.
  829. * @param {!Array.<string>} aList A list that is to be augmented.
  830. * @return {function(string)} A function that augments a list
  831. * with a prefixed representation String.
  832. */
  833. cAugmentList = function(aList) {
  834. /**
  835. * @param {string} sPrefixed Prefixed representation String of
  836. * a primitive value that could be consolidated within the
  837. * elements.
  838. */
  839. var fLambda = function(sPrefixed) {
  840. if (-1 === aList.indexOf(sPrefixed)) {
  841. aList.push(sPrefixed);
  842. }
  843. };
  844. return fLambda;
  845. },
  846. /**
  847. * Adds the number of occurrences of a primitive value of a given
  848. * category that could be consolidated in the source element with
  849. * a given index to the count of occurrences of that primitive
  850. * value within the range of source elements that is currently
  851. * being considered.
  852. * @param {number} nPosition The index (in the source text order)
  853. * of a source element.
  854. * @param {number} nCategory The category of the primary
  855. * expression from which the primitive value is derived.
  856. * @return {function(string)} A function that performs the
  857. * addition.
  858. * @see cAddOccurrencesInCategory
  859. */
  860. cAddOccurrences = function(nPosition, nCategory) {
  861. /**
  862. * @param {string} sPrefixed The prefixed representation String
  863. * of a primitive value.
  864. */
  865. var fLambda = function(sPrefixed) {
  866. if (!oSourceElementsData.aCount[nCategory].hasOwnProperty(
  867. sPrefixed)) {
  868. oSourceElementsData.aCount[nCategory][sPrefixed] = 0;
  869. }
  870. oSourceElementsData.aCount[nCategory][sPrefixed] +=
  871. aSourceElementsData[nPosition].aCount[nCategory][
  872. sPrefixed];
  873. };
  874. return fLambda;
  875. },
  876. /**
  877. * Adds the number of occurrences of each primitive value of a
  878. * given category that could be consolidated in the source
  879. * element with a given index to the count of occurrences of that
  880. * primitive values within the range of source elements that is
  881. * currently being considered.
  882. * @param {number} nPosition The index (in the source text order)
  883. * of a source element.
  884. * @return {function(number)} A function that performs the
  885. * addition.
  886. * @see fAddOccurrences
  887. */
  888. cAddOccurrencesInCategory = function(nPosition) {
  889. /**
  890. * @param {number} nCategory The category of the primary
  891. * expression from which the primitive value is derived.
  892. */
  893. var fLambda = function(nCategory) {
  894. Object.keys(
  895. aSourceElementsData[nPosition].aCount[nCategory]
  896. ).forEach(cAddOccurrences(nPosition, nCategory));
  897. };
  898. return fLambda;
  899. },
  900. /**
  901. * Adds the number of occurrences of each primitive value that
  902. * could be consolidated in the source element with a given index
  903. * to the count of occurrences of that primitive values within
  904. * the range of source elements that is currently being
  905. * considered.
  906. * @param {number} nPosition The index (in the source text order)
  907. * of a source element.
  908. */
  909. fAddOccurrences = function(nPosition) {
  910. Object.keys(aSourceElementsData[nPosition].aCount).forEach(
  911. cAddOccurrencesInCategory(nPosition));
  912. },
  913. /**
  914. * Creates a variable declaration for a primitive value if that
  915. * primitive value is to be consolidated within the elements.
  916. * @param {string} sPrefixed Prefixed representation String of a
  917. * primitive value that could be consolidated within the
  918. * elements.
  919. * @see aVariableDeclarations
  920. */
  921. cAugmentVariableDeclarations = function(sPrefixed) {
  922. if (oSolutionBest.oPrimitiveValues[sPrefixed].nSaving > 0) {
  923. aVariableDeclarations.push([
  924. oSolutionBest.oPrimitiveValues[sPrefixed].sName,
  925. [0 === sPrefixed.indexOf(EValuePrefixes.S_SYMBOLIC) ?
  926. 'name' : 'string',
  927. sPrefixed.substring(EValuePrefixes.S_SYMBOLIC.length)]
  928. ]);
  929. }
  930. },
  931. /**
  932. * Sorts primitive values with regard to the difference in the
  933. * number of terminal symbols between the original source text
  934. * and the one with those primitive values consolidated.
  935. * @param {string} sPrefixed0 The prefixed representation String
  936. * of the first of the two primitive values that are being
  937. * compared.
  938. * @param {string} sPrefixed1 The prefixed representation String
  939. * of the second of the two primitive values that are being
  940. * compared.
  941. * @return {number}
  942. * <dl>
  943. * <dt>-1</dt>
  944. * <dd>if the first primitive value must be placed before
  945. * the other one,</dd>
  946. * <dt>0</dt>
  947. * <dd>if the first primitive value may be placed before
  948. * the other one,</dd>
  949. * <dt>1</dt>
  950. * <dd>if the first primitive value must not be placed
  951. * before the other one.</dd>
  952. * </dl>
  953. * @see TSolution.oPrimitiveValues
  954. */
  955. cSortPrimitiveValues = function(sPrefixed0, sPrefixed1) {
  956. /**
  957. * The difference between:
  958. * <ol>
  959. * <li>the difference in the number of terminal symbols
  960. * between the original source text and the one with the
  961. * first primitive value consolidated, and</li>
  962. * <li>the difference in the number of terminal symbols
  963. * between the original source text and the one with the
  964. * second primitive value consolidated.</li>
  965. * </ol>
  966. * @type {number}
  967. */
  968. var nDifference =
  969. oSolutionCandidate.oPrimitiveValues[sPrefixed0].nSaving -
  970. oSolutionCandidate.oPrimitiveValues[sPrefixed1].nSaving;
  971. return nDifference > 0 ? -1 : nDifference < 0 ? 1 : 0;
  972. },
  973. /**
  974. * Assigns an identifier name to a primitive value and calculates
  975. * whether instances of that primitive value are worth
  976. * consolidating.
  977. * @param {string} sPrefixed The prefixed representation String
  978. * of a primitive value that is being evaluated.
  979. */
  980. fEvaluatePrimitiveValue = function(sPrefixed) {
  981. var _,
  982. /**
  983. * The index of the last mangled name.
  984. * @type {number}
  985. */
  986. nIndex,
  987. /**
  988. * The representation String of the primitive value that is
  989. * being evaluated.
  990. * @type {string}
  991. */
  992. sName =
  993. sPrefixed.substring(EValuePrefixes.S_SYMBOLIC.length),
  994. /**
  995. * The number of source characters taken up by the
  996. * representation String of the primitive value that is
  997. * being evaluated.
  998. * @type {number}
  999. */
  1000. nLengthOriginal = sName.length,
  1001. /**
  1002. * The number of source characters taken up by the
  1003. * identifier name that could substitute the primitive
  1004. * value that is being evaluated.
  1005. * substituted.
  1006. * @type {number}
  1007. */
  1008. nLengthSubstitution,
  1009. /**
  1010. * The number of source characters taken up by by the
  1011. * representation String of the primitive value that is
  1012. * being evaluated when it is represented by a string
  1013. * literal.
  1014. * @type {number}
  1015. */
  1016. nLengthString = oProcessor.make_string(sName).length;
  1017. oSolutionCandidate.oPrimitiveValues[sPrefixed] =
  1018. new TPrimitiveValue();
  1019. do { // Find an identifier unused in this or any nested scope.
  1020. nIndex = oScope.cname;
  1021. oSolutionCandidate.oPrimitiveValues[sPrefixed].sName =
  1022. oScope.next_mangled();
  1023. } while (-1 !== oSourceElementsData.aIdentifiers.indexOf(
  1024. oSolutionCandidate.oPrimitiveValues[sPrefixed].sName));
  1025. nLengthSubstitution = oSolutionCandidate.oPrimitiveValues[
  1026. sPrefixed].sName.length;
  1027. if (0 === sPrefixed.indexOf(EValuePrefixes.S_SYMBOLIC)) {
  1028. // foo:null, or foo:null;
  1029. oSolutionCandidate.oPrimitiveValues[sPrefixed].nSaving -=
  1030. nLengthSubstitution + nLengthOriginal +
  1031. oWeights.N_VARIABLE_DECLARATION;
  1032. // null vs foo
  1033. oSolutionCandidate.oPrimitiveValues[sPrefixed].nSaving +=
  1034. oSourceElementsData.aCount[
  1035. EPrimaryExpressionCategories.
  1036. N_NULL_AND_BOOLEAN_LITERALS][sPrefixed] *
  1037. (nLengthOriginal - nLengthSubstitution);
  1038. } else {
  1039. // foo:'fromCharCode';
  1040. oSolutionCandidate.oPrimitiveValues[sPrefixed].nSaving -=
  1041. nLengthSubstitution + nLengthString +
  1042. oWeights.N_VARIABLE_DECLARATION;
  1043. // .fromCharCode vs [foo]
  1044. if (oSourceElementsData.aCount[
  1045. EPrimaryExpressionCategories.N_IDENTIFIER_NAMES
  1046. ].hasOwnProperty(sPrefixed)) {
  1047. oSolutionCandidate.oPrimitiveValues[sPrefixed].nSaving +=
  1048. oSourceElementsData.aCount[
  1049. EPrimaryExpressionCategories.N_IDENTIFIER_NAMES
  1050. ][sPrefixed] *
  1051. (nLengthOriginal - nLengthSubstitution -
  1052. oWeights.N_PROPERTY_ACCESSOR);
  1053. }
  1054. // 'fromCharCode' vs foo
  1055. if (oSourceElementsData.aCount[
  1056. EPrimaryExpressionCategories.N_STRING_LITERALS
  1057. ].hasOwnProperty(sPrefixed)) {
  1058. oSolutionCandidate.oPrimitiveValues[sPrefixed].nSaving +=
  1059. oSourceElementsData.aCount[
  1060. EPrimaryExpressionCategories.N_STRING_LITERALS
  1061. ][sPrefixed] *
  1062. (nLengthString - nLengthSubstitution);
  1063. }
  1064. }
  1065. if (oSolutionCandidate.oPrimitiveValues[sPrefixed].nSaving >
  1066. 0) {
  1067. oSolutionCandidate.nSavings +=
  1068. oSolutionCandidate.oPrimitiveValues[sPrefixed].nSaving;
  1069. } else {
  1070. oScope.cname = nIndex; // Free the identifier name.
  1071. }
  1072. },
  1073. /**
  1074. * Adds a variable declaration to an existing variable statement.
  1075. * @param {!Array} aVariableDeclaration A variable declaration
  1076. * with an initialiser.
  1077. */
  1078. cAddVariableDeclaration = function(aVariableDeclaration) {
  1079. (/** @type {!Array} */ oSourceElements[nFrom][1]).unshift(
  1080. aVariableDeclaration);
  1081. };
  1082. if (nFrom > nTo) {
  1083. return;
  1084. }
  1085. // If the range is a closure, reuse the closure.
  1086. if (nFrom === nTo &&
  1087. 'stat' === oSourceElements[nFrom][0] &&
  1088. 'call' === oSourceElements[nFrom][1][0] &&
  1089. 'function' === oSourceElements[nFrom][1][1][0]) {
  1090. fExamineSyntacticCodeUnit(oSourceElements[nFrom][1][1]);
  1091. return;
  1092. }
  1093. // Create a list of all derived primitive values within the range.
  1094. for (nPosition = nFrom; nPosition <= nTo; nPosition += 1) {
  1095. aSourceElementsData[nPosition].aPrimitiveValues.forEach(
  1096. cAugmentList(oSourceElementsData.aPrimitiveValues));
  1097. }
  1098. if (0 === oSourceElementsData.aPrimitiveValues.length) {
  1099. return;
  1100. }
  1101. for (nPosition = nFrom; nPosition <= nTo; nPosition += 1) {
  1102. // Add the number of occurrences to the total count.
  1103. fAddOccurrences(nPosition);
  1104. // Add identifiers of this or any nested scope to the list.
  1105. aSourceElementsData[nPosition].aIdentifiers.forEach(
  1106. cAugmentList(oSourceElementsData.aIdentifiers));
  1107. }
  1108. // Distribute identifier names among derived primitive values.
  1109. do { // If there was any progress, find a better distribution.
  1110. oSolutionBest = oSolutionCandidate;
  1111. if (Object.keys(oSolutionCandidate.oPrimitiveValues).length > 0) {
  1112. // Sort primitive values descending by their worthwhileness.
  1113. oSourceElementsData.aPrimitiveValues.sort(cSortPrimitiveValues);
  1114. }
  1115. oSolutionCandidate = new TSolution();
  1116. oSourceElementsData.aPrimitiveValues.forEach(
  1117. fEvaluatePrimitiveValue);
  1118. oScope.cname = nIndex;
  1119. } while (oSolutionCandidate.nSavings > oSolutionBest.nSavings);
  1120. // Take the necessity of adding a variable statement into account.
  1121. if ('var' !== oSourceElements[nFrom][0]) {
  1122. oSolutionBest.nSavings -= oWeights.N_VARIABLE_STATEMENT_AFFIXATION;
  1123. }
  1124. if (bEnclose) {
  1125. // Take the necessity of forming a closure into account.
  1126. oSolutionBest.nSavings -= oWeights.N_CLOSURE;
  1127. }
  1128. if (oSolutionBest.nSavings > 0) {
  1129. // Create variable declarations suitable for UglifyJS.
  1130. Object.keys(oSolutionBest.oPrimitiveValues).forEach(
  1131. cAugmentVariableDeclarations);
  1132. // Rewrite expressions that contain worthwhile primitive values.
  1133. for (nPosition = nFrom; nPosition <= nTo; nPosition += 1) {
  1134. oWalker = oProcessor.ast_walker();
  1135. oSourceElements[nPosition] =
  1136. oWalker.with_walkers(
  1137. oWalkersTransformers,
  1138. cContext(oWalker, oSourceElements[nPosition]));
  1139. }
  1140. if ('var' === oSourceElements[nFrom][0]) { // Reuse the statement.
  1141. (/** @type {!Array.<!Array>} */ aVariableDeclarations.reverse(
  1142. )).forEach(cAddVariableDeclaration);
  1143. } else { // Add a variable statement.
  1144. Array.prototype.splice.call(
  1145. oSourceElements,
  1146. nFrom,
  1147. 0,
  1148. ['var', aVariableDeclarations]);
  1149. nTo += 1;
  1150. }
  1151. if (bEnclose) {
  1152. // Add a closure.
  1153. Array.prototype.splice.call(
  1154. oSourceElements,
  1155. nFrom,
  1156. 0,
  1157. ['stat', ['call', ['function', null, [], []], []]]);
  1158. // Copy source elements into the closure.
  1159. for (nPosition = nTo + 1; nPosition > nFrom; nPosition -= 1) {
  1160. Array.prototype.unshift.call(
  1161. oSourceElements[nFrom][1][1][3],
  1162. oSourceElements[nPosition]);
  1163. }
  1164. // Remove source elements outside the closure.
  1165. Array.prototype.splice.call(
  1166. oSourceElements,
  1167. nFrom + 1,
  1168. nTo - nFrom + 1);
  1169. }
  1170. }
  1171. if (bEnclose) {
  1172. // Restore the availability of identifier names.
  1173. oScope.cname = nIndex;
  1174. }
  1175. };
  1176. oSourceElements = (/** @type {!TSyntacticCodeUnit} */
  1177. oSyntacticCodeUnit[bIsGlobal ? 1 : 3]);
  1178. if (0 === oSourceElements.length) {
  1179. return;
  1180. }
  1181. oScope = bIsGlobal ? oSyntacticCodeUnit.scope : oSourceElements.scope;
  1182. // Skip a Directive Prologue.
  1183. while (nAfterDirectivePrologue < oSourceElements.length &&
  1184. 'directive' === oSourceElements[nAfterDirectivePrologue][0]) {
  1185. nAfterDirectivePrologue += 1;
  1186. aSourceElementsData.push(null);
  1187. }
  1188. if (oSourceElements.length === nAfterDirectivePrologue) {
  1189. return;
  1190. }
  1191. for (nPosition = nAfterDirectivePrologue;
  1192. nPosition < oSourceElements.length;
  1193. nPosition += 1) {
  1194. oSourceElementData = new TSourceElementsData();
  1195. oWalker = oProcessor.ast_walker();
  1196. // Classify a source element.
  1197. // Find its derived primitive values and count their occurrences.
  1198. // Find all identifiers used (including nested scopes).
  1199. oWalker.with_walkers(
  1200. oWalkers.oSurveySourceElement,
  1201. cContext(oWalker, oSourceElements[nPosition]));
  1202. // Establish whether the scope is still wholly examinable.
  1203. bIsWhollyExaminable = bIsWhollyExaminable &&
  1204. ESourceElementCategories.N_WITH !== oSourceElementData.nCategory &&
  1205. ESourceElementCategories.N_EVAL !== oSourceElementData.nCategory;
  1206. aSourceElementsData.push(oSourceElementData);
  1207. }
  1208. if (bIsWhollyExaminable) { // Examine the whole scope.
  1209. fExamineSourceElements(
  1210. nAfterDirectivePrologue,
  1211. oSourceElements.length - 1,
  1212. false);
  1213. } else { // Examine unexcluded ranges of source elements.
  1214. for (nPosition = oSourceElements.length - 1;
  1215. nPosition >= nAfterDirectivePrologue;
  1216. nPosition -= 1) {
  1217. oSourceElementData = (/** @type {!TSourceElementsData} */
  1218. aSourceElementsData[nPosition]);
  1219. if (ESourceElementCategories.N_OTHER ===
  1220. oSourceElementData.nCategory) {
  1221. if ('undefined' === typeof nTo) {
  1222. nTo = nPosition; // Indicate the end of a range.
  1223. }
  1224. // Examine the range if it immediately follows a Directive Prologue.
  1225. if (nPosition === nAfterDirectivePrologue) {
  1226. fExamineSourceElements(nPosition, nTo, true);
  1227. }
  1228. } else {
  1229. if ('undefined' !== typeof nTo) {
  1230. // Examine the range that immediately follows this source element.
  1231. fExamineSourceElements(nPosition + 1, nTo, true);
  1232. nTo = void 0; // Obliterate the range.
  1233. }
  1234. // Examine nested functions.
  1235. oWalker = oProcessor.ast_walker();
  1236. oWalker.with_walkers(
  1237. oWalkers.oExamineFunctions,
  1238. cContext(oWalker, oSourceElements[nPosition]));
  1239. }
  1240. }
  1241. }
  1242. }(oAbstractSyntaxTree = oProcessor.ast_add_scope(oAbstractSyntaxTree)));
  1243. return oAbstractSyntaxTree;
  1244. };
  1245. /*jshint sub:false */
  1246. /* Local Variables: */
  1247. /* mode: js */
  1248. /* coding: utf-8 */
  1249. /* indent-tabs-mode: nil */
  1250. /* tab-width: 2 */
  1251. /* End: */
  1252. /* vim: set ft=javascript fenc=utf-8 et ts=2 sts=2 sw=2: */
  1253. /* :mode=javascript:noTabs=true:tabSize=2:indentSize=2:deepIndent=true: */
  1254. }, "parse-js": function(exports, require, module) {/***********************************************************************
  1255. A JavaScript tokenizer / parser / beautifier / compressor.
  1256. This version is suitable for Node.js. With minimal changes (the
  1257. exports stuff) it should work on any JS platform.
  1258. This file contains the tokenizer/parser. It is a port to JavaScript
  1259. of parse-js [1], a JavaScript parser library written in Common Lisp
  1260. by Marijn Haverbeke. Thank you Marijn!
  1261. [1] http://marijn.haverbeke.nl/parse-js/
  1262. Exported functions:
  1263. - tokenizer(code) -- returns a function. Call the returned
  1264. function to fetch the next token.
  1265. - parse(code) -- returns an AST of the given JavaScript code.
  1266. -------------------------------- (C) ---------------------------------
  1267. Author: Mihai Bazon
  1268. <mihai.bazon@gmail.com>
  1269. http://mihai.bazon.net/blog
  1270. Distributed under the BSD license:
  1271. Copyright 2010 (c) Mihai Bazon <mihai.bazon@gmail.com>
  1272. Based on parse-js (http://marijn.haverbeke.nl/parse-js/).
  1273. Redistribution and use in source and binary forms, with or without
  1274. modification, are permitted provided that the following conditions
  1275. are met:
  1276. * Redistributions of source code must retain the above
  1277. copyright notice, this list of conditions and the following
  1278. disclaimer.
  1279. * Redistributions in binary form must reproduce the above
  1280. copyright notice, this list of conditions and the following
  1281. disclaimer in the documentation and/or other materials
  1282. provided with the distribution.
  1283. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
  1284. EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  1285. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  1286. PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
  1287. LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
  1288. OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  1289. PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  1290. PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  1291. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
  1292. TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
  1293. THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  1294. SUCH DAMAGE.
  1295. ***********************************************************************/
  1296. /* -----[ Tokenizer (constants) ]----- */
  1297. var KEYWORDS = array_to_hash([
  1298. "break",
  1299. "case",
  1300. "catch",
  1301. "const",
  1302. "continue",
  1303. "debugger",
  1304. "default",
  1305. "delete",
  1306. "do",
  1307. "else",
  1308. "finally",
  1309. "for",
  1310. "function",
  1311. "if",
  1312. "in",
  1313. "instanceof",
  1314. "new",
  1315. "return",
  1316. "switch",
  1317. "throw",
  1318. "try",
  1319. "typeof",
  1320. "var",
  1321. "void",
  1322. "while",
  1323. "with"
  1324. ]);
  1325. var RESERVED_WORDS = array_to_hash([
  1326. "abstract",
  1327. "boolean",
  1328. "byte",
  1329. "char",
  1330. "class",
  1331. "double",
  1332. "enum",
  1333. "export",
  1334. "extends",
  1335. "final",
  1336. "float",
  1337. "goto",
  1338. "implements",
  1339. "import",
  1340. "int",
  1341. "interface",
  1342. "long",
  1343. "native",
  1344. "package",
  1345. "private",
  1346. "protected",
  1347. "public",
  1348. "short",
  1349. "static",
  1350. "super",
  1351. "synchronized",
  1352. "throws",
  1353. "transient",
  1354. "volatile"
  1355. ]);
  1356. var KEYWORDS_BEFORE_EXPRESSION = array_to_hash([
  1357. "return",
  1358. "new",
  1359. "delete",
  1360. "throw",
  1361. "else",
  1362. "case"
  1363. ]);
  1364. var KEYWORDS_ATOM = array_to_hash([
  1365. "false",
  1366. "null",
  1367. "true",
  1368. "undefined"
  1369. ]);
  1370. var OPERATOR_CHARS = array_to_hash(characters("+-*&%=<>!?|~^"));
  1371. var RE_HEX_NUMBER = /^0x[0-9a-f]+$/i;
  1372. var RE_OCT_NUMBER = /^0[0-7]+$/;
  1373. var RE_DEC_NUMBER = /^\d*\.?\d*(?:e[+-]?\d*(?:\d\.?|\.?\d)\d*)?$/i;
  1374. var OPERATORS = array_to_hash([
  1375. "in",
  1376. "instanceof",
  1377. "typeof",
  1378. "new",
  1379. "void",
  1380. "delete",
  1381. "++",
  1382. "--",
  1383. "+",
  1384. "-",
  1385. "!",
  1386. "~",
  1387. "&",
  1388. "|",
  1389. "^",
  1390. "*",
  1391. "/",
  1392. "%",
  1393. ">>",
  1394. "<<",
  1395. ">>>",
  1396. "<",
  1397. ">",
  1398. "<=",
  1399. ">=",
  1400. "==",
  1401. "===",
  1402. "!=",
  1403. "!==",
  1404. "?",
  1405. "=",
  1406. "+=",
  1407. "-=",
  1408. "/=",
  1409. "*=",
  1410. "%=",
  1411. ">>=",
  1412. "<<=",
  1413. ">>>=",
  1414. "|=",
  1415. "^=",
  1416. "&=",
  1417. "&&",
  1418. "||"
  1419. ]);
  1420. var WHITESPACE_CHARS = array_to_hash(characters(" \u00a0\n\r\t\f\u000b\u200b\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000"));
  1421. var PUNC_BEFORE_EXPRESSION = array_to_hash(characters("[{(,.;:"));
  1422. var PUNC_CHARS = array_to_hash(characters("[]{}(),;:"));
  1423. var REGEXP_MODIFIERS = array_to_hash(characters("gmsiy"));
  1424. /* -----[ Tokenizer ]----- */
  1425. var UNICODE = { // Unicode 6.1
  1426. letter: new RegExp("[\\u0041-\\u005A\\u0061-\\u007A\\u00AA\\u00B5\\u00BA\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02C1\\u02C6-\\u02D1\\u02E0-\\u02E4\\u02EC\\u02EE\\u0370-\\u0374\\u0376\\u0377\\u037A-\\u037D\\u0386\\u0388-\\u038A\\u038C\\u038E-\\u03A1\\u03A3-\\u03F5\\u03F7-\\u0481\\u048A-\\u0527\\u0531-\\u0556\\u0559\\u0561-\\u0587\\u05D0-\\u05EA\\u05F0-\\u05F2\\u0620-\\u064A\\u066E\\u066F\\u0671-\\u06D3\\u06D5\\u06E5\\u06E6\\u06EE\\u06EF\\u06FA-\\u06FC\\u06FF\\u0710\\u0712-\\u072F\\u074D-\\u07A5\\u07B1\\u07CA-\\u07EA\\u07F4\\u07F5\\u07FA\\u0800-\\u0815\\u081A\\u0824\\u0828\\u0840-\\u0858\\u08A0\\u08A2-\\u08AC\\u0904-\\u0939\\u093D\\u0950\\u0958-\\u0961\\u0971-\\u0977\\u0979-\\u097F\\u0985-\\u098C\\u098F\\u0990\\u0993-\\u09A8\\u09AA-\\u09B0\\u09B2\\u09B6-\\u09B9\\u09BD\\u09CE\\u09DC\\u09DD\\u09DF-\\u09E1\\u09F0\\u09F1\\u0A05-\\u0A0A\\u0A0F\\u0A10\\u0A13-\\u0A28\\u0A2A-\\u0A30\\u0A32\\u0A33\\u0A35\\u0A36\\u0A38\\u0A39\\u0A59-\\u0A5C\\u0A5E\\u0A72-\\u0A74\\u0A85-\\u0A8D\\u0A8F-\\u0A91\\u0A93-\\u0AA8\\u0AAA-\\u0AB0\\u0AB2\\u0AB3\\u0AB5-\\u0AB9\\u0ABD\\u0AD0\\u0AE0\\u0AE1\\u0B05-\\u0B0C\\u0B0F\\u0B10\\u0B13-\\u0B28\\u0B2A-\\u0B30\\u0B32\\u0B33\\u0B35-\\u0B39\\u0B3D\\u0B5C\\u0B5D\\u0B5F-\\u0B61\\u0B71\\u0B83\\u0B85-\\u0B8A\\u0B8E-\\u0B90\\u0B92-\\u0B95\\u0B99\\u0B9A\\u0B9C\\u0B9E\\u0B9F\\u0BA3\\u0BA4\\u0BA8-\\u0BAA\\u0BAE-\\u0BB9\\u0BD0\\u0C05-\\u0C0C\\u0C0E-\\u0C10\\u0C12-\\u0C28\\u0C2A-\\u0C33\\u0C35-\\u0C39\\u0C3D\\u0C58\\u0C59\\u0C60\\u0C61\\u0C85-\\u0C8C\\u0C8E-\\u0C90\\u0C92-\\u0CA8\\u0CAA-\\u0CB3\\u0CB5-\\u0CB9\\u0CBD\\u0CDE\\u0CE0\\u0CE1\\u0CF1\\u0CF2\\u0D05-\\u0D0C\\u0D0E-\\u0D10\\u0D12-\\u0D3A\\u0D3D\\u0D4E\\u0D60\\u0D61\\u0D7A-\\u0D7F\\u0D85-\\u0D96\\u0D9A-\\u0DB1\\u0DB3-\\u0DBB\\u0DBD\\u0DC0-\\u0DC6\\u0E01-\\u0E30\\u0E32\\u0E33\\u0E40-\\u0E46\\u0E81\\u0E82\\u0E84\\u0E87\\u0E88\\u0E8A\\u0E8D\\u0E94-\\u0E97\\u0E99-\\u0E9F\\u0EA1-\\u0EA3\\u0EA5\\u0EA7\\u0EAA\\u0EAB\\u0EAD-\\u0EB0\\u0EB2\\u0EB3\\u0EBD\\u0EC0-\\u0EC4\\u0EC6\\u0EDC-\\u0EDF\\u0F00\\u0F40-\\u0F47\\u0F49-\\u0F6C\\u0F88-\\u0F8C\\u1000-\\u102A\\u103F\\u1050-\\u1055\\u105A-\\u105D\\u1061\\u1065\\u1066\\u106E-\\u1070\\u1075-\\u1081\\u108E\\u10A0-\\u10C5\\u10C7\\u10CD\\u10D0-\\u10FA\\u10FC-\\u1248\\u124A-\\u124D\\u1250-\\u1256\\u1258\\u125A-\\u125D\\u1260-\\u1288\\u128A-\\u128D\\u1290-\\u12B0\\u12B2-\\u12B5\\u12B8-\\u12BE\\u12C0\\u12C2-\\u12C5\\u12C8-\\u12D6\\u12D8-\\u1310\\u1312-\\u1315\\u1318-\\u135A\\u1380-\\u138F\\u13A0-\\u13F4\\u1401-\\u166C\\u166F-\\u167F\\u1681-\\u169A\\u16A0-\\u16EA\\u16EE-\\u16F0\\u1700-\\u170C\\u170E-\\u1711\\u1720-\\u1731\\u1740-\\u1751\\u1760-\\u176C\\u176E-\\u1770\\u1780-\\u17B3\\u17D7\\u17DC\\u1820-\\u1877\\u1880-\\u18A8\\u18AA\\u18B0-\\u18F5\\u1900-\\u191C\\u1950-\\u196D\\u1970-\\u1974\\u1980-\\u19AB\\u19C1-\\u19C7\\u1A00-\\u1A16\\u1A20-\\u1A54\\u1AA7\\u1B05-\\u1B33\\u1B45-\\u1B4B\\u1B83-\\u1BA0\\u1BAE\\u1BAF\\u1BBA-\\u1BE5\\u1C00-\\u1C23\\u1C4D-\\u1C4F\\u1C5A-\\u1C7D\\u1CE9-\\u1CEC\\u1CEE-\\u1CF1\\u1CF5\\u1CF6\\u1D00-\\u1DBF\\u1E00-\\u1F15\\u1F18-\\u1F1D\\u1F20-\\u1F45\\u1F48-\\u1F4D\\u1F50-\\u1F57\\u1F59\\u1F5B\\u1F5D\\u1F5F-\\u1F7D\\u1F80-\\u1FB4\\u1FB6-\\u1FBC\\u1FBE\\u1FC2-\\u1FC4\\u1FC6-\\u1FCC\\u1FD0-\\u1FD3\\u1FD6-\\u1FDB\\u1FE0-\\u1FEC\\u1FF2-\\u1FF4\\u1FF6-\\u1FFC\\u2071\\u207F\\u2090-\\u209C\\u2102\\u2107\\u210A-\\u2113\\u2115\\u2119-\\u211D\\u2124\\u2126\\u2128\\u212A-\\u212D\\u212F-\\u2139\\u213C-\\u213F\\u2145-\\u2149\\u214E\\u2160-\\u2188\\u2C00-\\u2C2E\\u2C30-\\u2C5E\\u2C60-\\u2CE4\\u2CEB-\\u2CEE\\u2CF2\\u2CF3\\u2D00-\\u2D25\\u2D27\\u2D2D\\u2D30-\\u2D67\\u2D6F\\u2D80-\\u2D96\\u2DA0-\\u2DA6\\u2DA8-\\u2DAE\\u2DB0-\\u2DB6\\u2DB8-\\u2DBE\\u2DC0-\\u2DC6\\u2DC8-\\u2DCE\\u2DD0-\\u2DD6\\u2DD8-\\u2DDE\\u2E2F\\u3005-\\u3007\\u3021-\\u3029\\u3031-\\u3035\\u3038-\\u303C\\u3041-\\u3096\\u309D-\\u309F\\u30A1-\\u30FA\\u30FC-\\u30FF\\u3105-\\u312D\\u3131-\\u318E\\u31A0-\\u31BA\\u31F0-\\u31FF\\u3400-\\u4DB5\\u4E00-\\u9FCC\\uA000-\\uA48C\\uA4D0-\\uA4FD\\uA500-\\uA60C\\uA610-\\uA61F\\uA62A\\uA62B\\uA640-\\uA66E\\uA67F-\\uA697\\uA6A0-\\uA6EF\\uA717-\\uA71F\\uA722-\\uA788\\uA78B-\\uA78E\\uA790-\\uA793\\uA7A0-\\uA7AA\\uA7F8-\\uA801\\uA803-\\uA805\\uA807-\\uA80A\\uA80C-\\uA822\\uA840-\\uA873\\uA882-\\uA8B3\\uA8F2-\\uA8F7\\uA8FB\\uA90A-\\uA925\\uA930-\\uA946\\uA960-\\uA97C\\uA984-\\uA9B2\\uA9CF\\uAA00-\\uAA28\\uAA40-\\uAA42\\uAA44-\\uAA4B\\uAA60-\\uAA76\\uAA7A\\uAA80-\\uAAAF\\uAAB1\\uAAB5\\uAAB6\\uAAB9-\\uAABD\\uAAC0\\uAAC2\\uAADB-\\uAADD\\uAAE0-\\uAAEA\\uAAF2-\\uAAF4\\uAB01-\\uAB06\\uAB09-\\uAB0E\\uAB11-\\uAB16\\uAB20-\\uAB26\\uAB28-\\uAB2E\\uABC0-\\uABE2\\uAC00-\\uD7A3\\uD7B0-\\uD7C6\\uD7CB-\\uD7FB\\uF900-\\uFA6D\\uFA70-\\uFAD9\\uFB00-\\uFB06\\uFB13-\\uFB17\\uFB1D\\uFB1F-\\uFB28\\uFB2A-\\uFB36\\uFB38-\\uFB3C\\uFB3E\\uFB40\\uFB41\\uFB43\\uFB44\\uFB46-\\uFBB1\\uFBD3-\\uFD3D\\uFD50-\\uFD8F\\uFD92-\\uFDC7\\uFDF0-\\uFDFB\\uFE70-\\uFE74\\uFE76-\\uFEFC\\uFF21-\\uFF3A\\uFF41-\\uFF5A\\uFF66-\\uFFBE\\uFFC2-\\uFFC7\\uFFCA-\\uFFCF\\uFFD2-\\uFFD7\\uFFDA-\\uFFDC]"),
  1427. combining_mark: new RegExp("[\\u0300-\\u036F\\u0483-\\u0487\\u0591-\\u05BD\\u05BF\\u05C1\\u05C2\\u05C4\\u05C5\\u05C7\\u0610-\\u061A\\u064B-\\u065F\\u0670\\u06D6-\\u06DC\\u06DF-\\u06E4\\u06E7\\u06E8\\u06EA-\\u06ED\\u0711\\u0730-\\u074A\\u07A6-\\u07B0\\u07EB-\\u07F3\\u0816-\\u0819\\u081B-\\u0823\\u0825-\\u0827\\u0829-\\u082D\\u0859-\\u085B\\u08E4-\\u08FE\\u0900-\\u0903\\u093A-\\u093C\\u093E-\\u094F\\u0951-\\u0957\\u0962\\u0963\\u0981-\\u0983\\u09BC\\u09BE-\\u09C4\\u09C7\\u09C8\\u09CB-\\u09CD\\u09D7\\u09E2\\u09E3\\u0A01-\\u0A03\\u0A3C\\u0A3E-\\u0A42\\u0A47\\u0A48\\u0A4B-\\u0A4D\\u0A51\\u0A70\\u0A71\\u0A75\\u0A81-\\u0A83\\u0ABC\\u0ABE-\\u0AC5\\u0AC7-\\u0AC9\\u0ACB-\\u0ACD\\u0AE2\\u0AE3\\u0B01-\\u0B03\\u0B3C\\u0B3E-\\u0B44\\u0B47\\u0B48\\u0B4B-\\u0B4D\\u0B56\\u0B57\\u0B62\\u0B63\\u0B82\\u0BBE-\\u0BC2\\u0BC6-\\u0BC8\\u0BCA-\\u0BCD\\u0BD7\\u0C01-\\u0C03\\u0C3E-\\u0C44\\u0C46-\\u0C48\\u0C4A-\\u0C4D\\u0C55\\u0C56\\u0C62\\u0C63\\u0C82\\u0C83\\u0CBC\\u0CBE-\\u0CC4\\u0CC6-\\u0CC8\\u0CCA-\\u0CCD\\u0CD5\\u0CD6\\u0CE2\\u0CE3\\u0D02\\u0D03\\u0D3E-\\u0D44\\u0D46-\\u0D48\\u0D4A-\\u0D4D\\u0D57\\u0D62\\u0D63\\u0D82\\u0D83\\u0DCA\\u0DCF-\\u0DD4\\u0DD6\\u0DD8-\\u0DDF\\u0DF2\\u0DF3\\u0E31\\u0E34-\\u0E3A\\u0E47-\\u0E4E\\u0EB1\\u0EB4-\\u0EB9\\u0EBB\\u0EBC\\u0EC8-\\u0ECD\\u0F18\\u0F19\\u0F35\\u0F37\\u0F39\\u0F3E\\u0F3F\\u0F71-\\u0F84\\u0F86\\u0F87\\u0F8D-\\u0F97\\u0F99-\\u0FBC\\u0FC6\\u102B-\\u103E\\u1056-\\u1059\\u105E-\\u1060\\u1062-\\u1064\\u1067-\\u106D\\u1071-\\u1074\\u1082-\\u108D\\u108F\\u109A-\\u109D\\u135D-\\u135F\\u1712-\\u1714\\u1732-\\u1734\\u1752\\u1753\\u1772\\u1773\\u17B4-\\u17D3\\u17DD\\u180B-\\u180D\\u18A9\\u1920-\\u192B\\u1930-\\u193B\\u19B0-\\u19C0\\u19C8\\u19C9\\u1A17-\\u1A1B\\u1A55-\\u1A5E\\u1A60-\\u1A7C\\u1A7F\\u1B00-\\u1B04\\u1B34-\\u1B44\\u1B6B-\\u1B73\\u1B80-\\u1B82\\u1BA1-\\u1BAD\\u1BE6-\\u1BF3\\u1C24-\\u1C37\\u1CD0-\\u1CD2\\u1CD4-\\u1CE8\\u1CED\\u1CF2-\\u1CF4\\u1DC0-\\u1DE6\\u1DFC-\\u1DFF\\u20D0-\\u20DC\\u20E1\\u20E5-\\u20F0\\u2CEF-\\u2CF1\\u2D7F\\u2DE0-\\u2DFF\\u302A-\\u302F\\u3099\\u309A\\uA66F\\uA674-\\uA67D\\uA69F\\uA6F0\\uA6F1\\uA802\\uA806\\uA80B\\uA823-\\uA827\\uA880\\uA881\\uA8B4-\\uA8C4\\uA8E0-\\uA8F1\\uA926-\\uA92D\\uA947-\\uA953\\uA980-\\uA983\\uA9B3-\\uA9C0\\uAA29-\\uAA36\\uAA43\\uAA4C\\uAA4D\\uAA7B\\uAAB0\\uAAB2-\\uAAB4\\uAAB7\\uAAB8\\uAABE\\uAABF\\uAAC1\\uAAEB-\\uAAEF\\uAAF5\\uAAF6\\uABE3-\\uABEA\\uABEC\\uABED\\uFB1E\\uFE00-\\uFE0F\\uFE20-\\uFE26]"),
  1428. connector_punctuation: new RegExp("[\\u005F\\u203F\\u2040\\u2054\\uFE33\\uFE34\\uFE4D-\\uFE4F\\uFF3F]"),
  1429. digit: new RegExp("[\\u0030-\\u0039\\u0660-\\u0669\\u06F0-\\u06F9\\u07C0-\\u07C9\\u0966-\\u096F\\u09E6-\\u09EF\\u0A66-\\u0A6F\\u0AE6-\\u0AEF\\u0B66-\\u0B6F\\u0BE6-\\u0BEF\\u0C66-\\u0C6F\\u0CE6-\\u0CEF\\u0D66-\\u0D6F\\u0E50-\\u0E59\\u0ED0-\\u0ED9\\u0F20-\\u0F29\\u1040-\\u1049\\u1090-\\u1099\\u17E0-\\u17E9\\u1810-\\u1819\\u1946-\\u194F\\u19D0-\\u19D9\\u1A80-\\u1A89\\u1A90-\\u1A99\\u1B50-\\u1B59\\u1BB0-\\u1BB9\\u1C40-\\u1C49\\u1C50-\\u1C59\\uA620-\\uA629\\uA8D0-\\uA8D9\\uA900-\\uA909\\uA9D0-\\uA9D9\\uAA50-\\uAA59\\uABF0-\\uABF9\\uFF10-\\uFF19]")
  1430. };
  1431. function is_letter(ch) {
  1432. return UNICODE.letter.test(ch);
  1433. };
  1434. function is_digit(ch) {
  1435. ch = ch.charCodeAt(0);
  1436. return ch >= 48 && ch <= 57;
  1437. };
  1438. function is_unicode_digit(ch) {
  1439. return UNICODE.digit.test(ch);
  1440. }
  1441. function is_alphanumeric_char(ch) {
  1442. return is_digit(ch) || is_letter(ch);
  1443. };
  1444. function is_unicode_combining_mark(ch) {
  1445. return UNICODE.combining_mark.test(ch);
  1446. };
  1447. function is_unicode_connector_punctuation(ch) {
  1448. return UNICODE.connector_punctuation.test(ch);
  1449. };
  1450. function is_identifier_start(ch) {
  1451. return ch == "$" || ch == "_" || is_letter(ch);
  1452. };
  1453. function is_identifier_char(ch) {
  1454. return is_identifier_start(ch)
  1455. || is_unicode_combining_mark(ch)
  1456. || is_unicode_digit(ch)
  1457. || is_unicode_connector_punctuation(ch)
  1458. || ch == "\u200c" // zero-width non-joiner <ZWNJ>
  1459. || ch == "\u200d" // zero-width joiner <ZWJ> (in my ECMA-262 PDF, this is also 200c)
  1460. ;
  1461. };
  1462. function parse_js_number(num) {
  1463. if (RE_HEX_NUMBER.test(num)) {
  1464. return parseInt(num.substr(2), 16);
  1465. } else if (RE_OCT_NUMBER.test(num)) {
  1466. return parseInt(num.substr(1), 8);
  1467. } else if (RE_DEC_NUMBER.test(num)) {
  1468. return parseFloat(num);
  1469. }
  1470. };
  1471. function JS_Parse_Error(message, line, col, pos) {
  1472. this.message = message;
  1473. this.line = line + 1;
  1474. this.col = col + 1;
  1475. this.pos = pos + 1;
  1476. this.stack = new Error().stack;
  1477. };
  1478. JS_Parse_Error.prototype.toString = function() {
  1479. return this.message + " (line: " + this.line + ", col: " + this.col + ", pos: " + this.pos + ")" + "\n\n" + this.stack;
  1480. };
  1481. function js_error(message, line, col, pos) {
  1482. throw new JS_Parse_Error(message, line, col, pos);
  1483. };
  1484. function is_token(token, type, val) {
  1485. return token.type == type && (val == null || token.value == val);
  1486. };
  1487. var EX_EOF = {};
  1488. function tokenizer($TEXT) {
  1489. var S = {
  1490. text : $TEXT.replace(/\r\n?|[\n\u2028\u2029]/g, "\n").replace(/^\uFEFF/, ''),
  1491. pos : 0,
  1492. tokpos : 0,
  1493. line : 0,
  1494. tokline : 0,
  1495. col : 0,
  1496. tokcol : 0,
  1497. newline_before : false,
  1498. regex_allowed : false,
  1499. comments_before : []
  1500. };
  1501. function peek() { return S.text.charAt(S.pos); };
  1502. function next(signal_eof, in_string) {
  1503. var ch = S.text.charAt(S.pos++);
  1504. if (signal_eof && !ch)
  1505. throw EX_EOF;
  1506. if (ch == "\n") {
  1507. S.newline_before = S.newline_before || !in_string;
  1508. ++S.line;
  1509. S.col = 0;
  1510. } else {
  1511. ++S.col;
  1512. }
  1513. return ch;
  1514. };
  1515. function eof() {
  1516. return !S.peek();
  1517. };
  1518. function find(what, signal_eof) {
  1519. var pos = S.text.indexOf(what, S.pos);
  1520. if (signal_eof && pos == -1) throw EX_EOF;
  1521. return pos;
  1522. };
  1523. function start_token() {
  1524. S.tokline = S.line;
  1525. S.tokcol = S.col;
  1526. S.tokpos = S.pos;
  1527. };
  1528. function token(type, value, is_comment) {
  1529. S.regex_allowed = ((type == "operator" && !HOP(UNARY_POSTFIX, value)) ||
  1530. (type == "keyword" && HOP(KEYWORDS_BEFORE_EXPRESSION, value)) ||
  1531. (type == "punc" && HOP(PUNC_BEFORE_EXPRESSION, value)));
  1532. var ret = {
  1533. type : type,
  1534. value : value,
  1535. line : S.tokline,
  1536. col : S.tokcol,
  1537. pos : S.tokpos,
  1538. endpos : S.pos,
  1539. nlb : S.newline_before
  1540. };
  1541. if (!is_comment) {
  1542. ret.comments_before = S.comments_before;
  1543. S.comments_before = [];
  1544. // make note of any newlines in the comments that came before
  1545. for (var i = 0, len = ret.comments_before.length; i < len; i++) {
  1546. ret.nlb = ret.nlb || ret.comments_before[i].nlb;
  1547. }
  1548. }
  1549. S.newline_before = false;
  1550. return ret;
  1551. };
  1552. function skip_whitespace() {
  1553. while (HOP(WHITESPACE_CHARS, peek()))
  1554. next();
  1555. };
  1556. function read_while(pred) {
  1557. var ret = "", ch = peek(), i = 0;
  1558. while (ch && pred(ch, i++)) {
  1559. ret += next();
  1560. ch = peek();
  1561. }
  1562. return ret;
  1563. };
  1564. function parse_error(err) {
  1565. js_error(err, S.tokline, S.tokcol, S.tokpos);
  1566. };
  1567. function read_num(prefix) {
  1568. var has_e = false, after_e = false, has_x = false, has_dot = prefix == ".";
  1569. var num = read_while(function(ch, i){
  1570. if (ch == "x" || ch == "X") {
  1571. if (has_x) return false;
  1572. return has_x = true;
  1573. }
  1574. if (!has_x && (ch == "E" || ch == "e")) {
  1575. if (has_e) return false;
  1576. return has_e = after_e = true;
  1577. }
  1578. if (ch == "-") {
  1579. if (after_e || (i == 0 && !prefix)) return true;
  1580. return false;
  1581. }
  1582. if (ch == "+") return after_e;
  1583. after_e = false;
  1584. if (ch == ".") {
  1585. if (!has_dot && !has_x && !has_e)
  1586. return has_dot = true;
  1587. return false;
  1588. }
  1589. return is_alphanumeric_char(ch);
  1590. });
  1591. if (prefix)
  1592. num = prefix + num;
  1593. var valid = parse_js_number(num);
  1594. if (!isNaN(valid)) {
  1595. return token("num", valid);
  1596. } else {
  1597. parse_error("Invalid syntax: " + num);
  1598. }
  1599. };
  1600. function read_escaped_char(in_string) {
  1601. var ch = next(true, in_string);
  1602. switch (ch) {
  1603. case "n" : return "\n";
  1604. case "r" : return "\r";
  1605. case "t" : return "\t";
  1606. case "b" : return "\b";
  1607. case "v" : return "\u000b";
  1608. case "f" : return "\f";
  1609. case "0" : return "\0";
  1610. case "x" : return String.fromCharCode(hex_bytes(2));
  1611. case "u" : return String.fromCharCode(hex_bytes(4));
  1612. case "\n": return "";
  1613. default : return ch;
  1614. }
  1615. };
  1616. function hex_bytes(n) {
  1617. var num = 0;
  1618. for (; n > 0; --n) {
  1619. var digit = parseInt(next(true), 16);
  1620. if (isNaN(digit))
  1621. parse_error("Invalid hex-character pattern in string");
  1622. num = (num << 4) | digit;
  1623. }
  1624. return num;
  1625. };
  1626. function read_string() {
  1627. return with_eof_error("Unterminated string constant", function(){
  1628. var quote = next(), ret = "";
  1629. for (;;) {
  1630. var ch = next(true);
  1631. if (ch == "\\") {
  1632. // read OctalEscapeSequence (XXX: deprecated if "strict mode")
  1633. // https://github.com/mishoo/UglifyJS/issues/178
  1634. var octal_len = 0, first = null;
  1635. ch = read_while(function(ch){
  1636. if (ch >= "0" && ch <= "7") {
  1637. if (!first) {
  1638. first = ch;
  1639. return ++octal_len;
  1640. }
  1641. else if (first <= "3" && octal_len <= 2) return ++octal_len;
  1642. else if (first >= "4" && octal_len <= 1) return ++octal_len;
  1643. }
  1644. return false;
  1645. });
  1646. if (octal_len > 0) ch = String.fromCharCode(parseInt(ch, 8));
  1647. else ch = read_escaped_char(true);
  1648. }
  1649. else if (ch == quote) break;
  1650. ret += ch;
  1651. }
  1652. return token("string", ret);
  1653. });
  1654. };
  1655. function read_line_comment() {
  1656. next();
  1657. var i = find("\n"), ret;
  1658. if (i == -1) {
  1659. ret = S.text.substr(S.pos);
  1660. S.pos = S.text.length;
  1661. } else {
  1662. ret = S.text.substring(S.pos, i);
  1663. S.pos = i;
  1664. }
  1665. return token("comment1", ret, true);
  1666. };
  1667. function read_multiline_comment() {
  1668. next();
  1669. return with_eof_error("Unterminated multiline comment", function(){
  1670. var i = find("*/", true),
  1671. text = S.text.substring(S.pos, i);
  1672. S.pos = i + 2;
  1673. S.line += text.split("\n").length - 1;
  1674. S.newline_before = S.newline_before || text.indexOf("\n") >= 0;
  1675. // https://github.com/mishoo/UglifyJS/issues/#issue/100
  1676. if (/^@cc_on/i.test(text)) {
  1677. warn("WARNING: at line " + S.line);
  1678. warn("*** Found \"conditional comment\": " + text);
  1679. warn("*** UglifyJS DISCARDS ALL COMMENTS. This means your code might no longer work properly in Internet Explorer.");
  1680. }
  1681. return token("comment2", text, true);
  1682. });
  1683. };
  1684. function read_name() {
  1685. var backslash = false, name = "", ch, escaped = false, hex;
  1686. while ((ch = peek()) != null) {
  1687. if (!backslash) {
  1688. if (ch == "\\") escaped = backslash = true, next();
  1689. else if (is_identifier_char(ch)) name += next();
  1690. else break;
  1691. }
  1692. else {
  1693. if (ch != "u") parse_error("Expecting UnicodeEscapeSequence -- uXXXX");
  1694. ch = read_escaped_char();
  1695. if (!is_identifier_char(ch)) parse_error("Unicode char: " + ch.charCodeAt(0) + " is not valid in identifier");
  1696. name += ch;
  1697. backslash = false;
  1698. }
  1699. }
  1700. if (HOP(KEYWORDS, name) && escaped) {
  1701. hex = name.charCodeAt(0).toString(16).toUpperCase();
  1702. name = "\\u" + "0000".substr(hex.length) + hex + name.slice(1);
  1703. }
  1704. return name;
  1705. };
  1706. function read_regexp(regexp) {
  1707. return with_eof_error("Unterminated regular expression", function(){
  1708. var prev_backslash = false, ch, in_class = false;
  1709. while ((ch = next(true))) if (prev_backslash) {
  1710. regexp += "\\" + ch;
  1711. prev_backslash = false;
  1712. } else if (ch == "[") {
  1713. in_class = true;
  1714. regexp += ch;
  1715. } else if (ch == "]" && in_class) {
  1716. in_class = false;
  1717. regexp += ch;
  1718. } else if (ch == "/" && !in_class) {
  1719. break;
  1720. } else if (ch == "\\") {
  1721. prev_backslash = true;
  1722. } else {
  1723. regexp += ch;
  1724. }
  1725. var mods = read_name();
  1726. return token("regexp", [ regexp, mods ]);
  1727. });
  1728. };
  1729. function read_operator(prefix) {
  1730. function grow(op) {
  1731. if (!peek()) return op;
  1732. var bigger = op + peek();
  1733. if (HOP(OPERATORS, bigger)) {
  1734. next();
  1735. return grow(bigger);
  1736. } else {
  1737. return op;
  1738. }
  1739. };
  1740. return token("operator", grow(prefix || next()));
  1741. };
  1742. function handle_slash() {
  1743. next();
  1744. var regex_allowed = S.regex_allowed;
  1745. switch (peek()) {
  1746. case "/":
  1747. S.comments_before.push(read_line_comment());
  1748. S.regex_allowed = regex_allowed;
  1749. return next_token();
  1750. case "*":
  1751. S.comments_before.push(read_multiline_comment());
  1752. S.regex_allowed = regex_allowed;
  1753. return next_token();
  1754. }
  1755. return S.regex_allowed ? read_regexp("") : read_operator("/");
  1756. };
  1757. function handle_dot() {
  1758. next();
  1759. return is_digit(peek())
  1760. ? read_num(".")
  1761. : token("punc", ".");
  1762. };
  1763. function read_word() {
  1764. var word = read_name();
  1765. return !HOP(KEYWORDS, word)
  1766. ? token("name", word)
  1767. : HOP(OPERATORS, word)
  1768. ? token("operator", word)
  1769. : HOP(KEYWORDS_ATOM, word)
  1770. ? token("atom", word)
  1771. : token("keyword", word);
  1772. };
  1773. function with_eof_error(eof_error, cont) {
  1774. try {
  1775. return cont();
  1776. } catch(ex) {
  1777. if (ex === EX_EOF) parse_error(eof_error);
  1778. else throw ex;
  1779. }
  1780. };
  1781. function next_token(force_regexp) {
  1782. if (force_regexp != null)
  1783. return read_regexp(force_regexp);
  1784. skip_whitespace();
  1785. start_token();
  1786. var ch = peek();
  1787. if (!ch) return token("eof");
  1788. if (is_digit(ch)) return read_num();
  1789. if (ch == '"' || ch == "'") return read_string();
  1790. if (HOP(PUNC_CHARS, ch)) return token("punc", next());
  1791. if (ch == ".") return handle_dot();
  1792. if (ch == "/") return handle_slash();
  1793. if (HOP(OPERATOR_CHARS, ch)) return read_operator();
  1794. if (ch == "\\" || is_identifier_start(ch)) return read_word();
  1795. parse_error("Unexpected character '" + ch + "'");
  1796. };
  1797. next_token.context = function(nc) {
  1798. if (nc) S = nc;
  1799. return S;
  1800. };
  1801. return next_token;
  1802. };
  1803. /* -----[ Parser (constants) ]----- */
  1804. var UNARY_PREFIX = array_to_hash([
  1805. "typeof",
  1806. "void",
  1807. "delete",
  1808. "--",
  1809. "++",
  1810. "!",
  1811. "~",
  1812. "-",
  1813. "+"
  1814. ]);
  1815. var UNARY_POSTFIX = array_to_hash([ "--", "++" ]);
  1816. var ASSIGNMENT = (function(a, ret, i){
  1817. while (i < a.length) {
  1818. ret[a[i]] = a[i].substr(0, a[i].length - 1);
  1819. i++;
  1820. }
  1821. return ret;
  1822. })(
  1823. ["+=", "-=", "/=", "*=", "%=", ">>=", "<<=", ">>>=", "|=", "^=", "&="],
  1824. { "=": true },
  1825. 0
  1826. );
  1827. var PRECEDENCE = (function(a, ret){
  1828. for (var i = 0, n = 1; i < a.length; ++i, ++n) {
  1829. var b = a[i];
  1830. for (var j = 0; j < b.length; ++j) {
  1831. ret[b[j]] = n;
  1832. }
  1833. }
  1834. return ret;
  1835. })(
  1836. [
  1837. ["||"],
  1838. ["&&"],
  1839. ["|"],
  1840. ["^"],
  1841. ["&"],
  1842. ["==", "===", "!=", "!=="],
  1843. ["<", ">", "<=", ">=", "in", "instanceof"],
  1844. [">>", "<<", ">>>"],
  1845. ["+", "-"],
  1846. ["*", "/", "%"]
  1847. ],
  1848. {}
  1849. );
  1850. var STATEMENTS_WITH_LABELS = array_to_hash([ "for", "do", "while", "switch" ]);
  1851. var ATOMIC_START_TOKEN = array_to_hash([ "atom", "num", "string", "regexp", "name" ]);
  1852. /* -----[ Parser ]----- */
  1853. function NodeWithToken(str, start, end) {
  1854. this.name = str;
  1855. this.start = start;
  1856. this.end = end;
  1857. };
  1858. NodeWithToken.prototype.toString = function() { return this.name; };
  1859. function parse($TEXT, exigent_mode, embed_tokens) {
  1860. var S = {
  1861. input : typeof $TEXT == "string" ? tokenizer($TEXT, true) : $TEXT,
  1862. token : null,
  1863. prev : null,
  1864. peeked : null,
  1865. in_function : 0,
  1866. in_directives : true,
  1867. in_loop : 0,
  1868. labels : []
  1869. };
  1870. S.token = next();
  1871. function is(type, value) {
  1872. return is_token(S.token, type, value);
  1873. };
  1874. function peek() { return S.peeked || (S.peeked = S.input()); };
  1875. function next() {
  1876. S.prev = S.token;
  1877. if (S.peeked) {
  1878. S.token = S.peeked;
  1879. S.peeked = null;
  1880. } else {
  1881. S.token = S.input();
  1882. }
  1883. S.in_directives = S.in_directives && (
  1884. S.token.type == "string" || is("punc", ";")
  1885. );
  1886. return S.token;
  1887. };
  1888. function prev() {
  1889. return S.prev;
  1890. };
  1891. function croak(msg, line, col, pos) {
  1892. var ctx = S.input.context();
  1893. js_error(msg,
  1894. line != null ? line : ctx.tokline,
  1895. col != null ? col : ctx.tokcol,
  1896. pos != null ? pos : ctx.tokpos);
  1897. };
  1898. function token_error(token, msg) {
  1899. croak(msg, token.line, token.col);
  1900. };
  1901. function unexpected(token) {
  1902. if (token == null)
  1903. token = S.token;
  1904. token_error(token, "Unexpected token: " + token.type + " (" + token.value + ")");
  1905. };
  1906. function expect_token(type, val) {
  1907. if (is(type, val)) {
  1908. return next();
  1909. }
  1910. token_error(S.token, "Unexpected token " + S.token.type + ", expected " + type);
  1911. };
  1912. function expect(punc) { return expect_token("punc", punc); };
  1913. function can_insert_semicolon() {
  1914. return !exigent_mode && (
  1915. S.token.nlb || is("eof") || is("punc", "}")
  1916. );
  1917. };
  1918. function semicolon() {
  1919. if (is("punc", ";")) next();
  1920. else if (!can_insert_semicolon()) unexpected();
  1921. };
  1922. function as() {
  1923. return slice(arguments);
  1924. };
  1925. function parenthesised() {
  1926. expect("(");
  1927. var ex = expression();
  1928. expect(")");
  1929. return ex;
  1930. };
  1931. function add_tokens(str, start, end) {
  1932. return str instanceof NodeWithToken ? str : new NodeWithToken(str, start, end);
  1933. };
  1934. function maybe_embed_tokens(parser) {
  1935. if (embed_tokens) return function() {
  1936. var start = S.token;
  1937. var ast = parser.apply(this, arguments);
  1938. ast[0] = add_tokens(ast[0], start, prev());
  1939. return ast;
  1940. };
  1941. else return parser;
  1942. };
  1943. var statement = maybe_embed_tokens(function() {
  1944. if (is("operator", "/") || is("operator", "/=")) {
  1945. S.peeked = null;
  1946. S.token = S.input(S.token.value.substr(1)); // force regexp
  1947. }
  1948. switch (S.token.type) {
  1949. case "string":
  1950. var dir = S.in_directives, stat = simple_statement();
  1951. if (dir && stat[1][0] == "string" && !is("punc", ","))
  1952. return as("directive", stat[1][1]);
  1953. return stat;
  1954. case "num":
  1955. case "regexp":
  1956. case "operator":
  1957. case "atom":
  1958. return simple_statement();
  1959. case "name":
  1960. return is_token(peek(), "punc", ":")
  1961. ? labeled_statement(prog1(S.token.value, next, next))
  1962. : simple_statement();
  1963. case "punc":
  1964. switch (S.token.value) {
  1965. case "{":
  1966. return as("block", block_());
  1967. case "[":
  1968. case "(":
  1969. return simple_statement();
  1970. case ";":
  1971. next();
  1972. return as("block");
  1973. default:
  1974. unexpected();
  1975. }
  1976. case "keyword":
  1977. switch (prog1(S.token.value, next)) {
  1978. case "break":
  1979. return break_cont("break");
  1980. case "continue":
  1981. return break_cont("continue");
  1982. case "debugger":
  1983. semicolon();
  1984. return as("debugger");
  1985. case "do":
  1986. return (function(body){
  1987. expect_token("keyword", "while");
  1988. return as("do", prog1(parenthesised, semicolon), body);
  1989. })(in_loop(statement));
  1990. case "for":
  1991. return for_();
  1992. case "function":
  1993. return function_(true);
  1994. case "if":
  1995. return if_();
  1996. case "return":
  1997. if (S.in_function == 0)
  1998. croak("'return' outside of function");
  1999. return as("return",
  2000. is("punc", ";")
  2001. ? (next(), null)
  2002. : can_insert_semicolon()
  2003. ? null
  2004. : prog1(expression, semicolon));
  2005. case "switch":
  2006. return as("switch", parenthesised(), switch_block_());
  2007. case "throw":
  2008. if (S.token.nlb)
  2009. croak("Illegal newline after 'throw'");
  2010. return as("throw", prog1(expression, semicolon));
  2011. case "try":
  2012. return try_();
  2013. case "var":
  2014. return prog1(var_, semicolon);
  2015. case "const":
  2016. return prog1(const_, semicolon);
  2017. case "while":
  2018. return as("while", parenthesised(), in_loop(statement));
  2019. case "with":
  2020. return as("with", parenthesised(), statement());
  2021. default:
  2022. unexpected();
  2023. }
  2024. }
  2025. });
  2026. function labeled_statement(label) {
  2027. S.labels.push(label);
  2028. var start = S.token, stat = statement();
  2029. if (exigent_mode && !HOP(STATEMENTS_WITH_LABELS, stat[0]))
  2030. unexpected(start);
  2031. S.labels.pop();
  2032. return as("label", label, stat);
  2033. };
  2034. function simple_statement() {
  2035. return as("stat", prog1(expression, semicolon));
  2036. };
  2037. function break_cont(type) {
  2038. var name;
  2039. if (!can_insert_semicolon()) {
  2040. name = is("name") ? S.token.value : null;
  2041. }
  2042. if (name != null) {
  2043. next();
  2044. if (!member(name, S.labels))
  2045. croak("Label " + name + " without matching loop or statement");
  2046. }
  2047. else if (S.in_loop == 0)
  2048. croak(type + " not inside a loop or switch");
  2049. semicolon();
  2050. return as(type, name);
  2051. };
  2052. function for_() {
  2053. expect("(");
  2054. var init = null;
  2055. if (!is("punc", ";")) {
  2056. init = is("keyword", "var")
  2057. ? (next(), var_(true))
  2058. : expression(true, true);
  2059. if (is("operator", "in")) {
  2060. if (init[0] == "var" && init[1].length > 1)
  2061. croak("Only one variable declaration allowed in for..in loop");
  2062. return for_in(init);
  2063. }
  2064. }
  2065. return regular_for(init);
  2066. };
  2067. function regular_for(init) {
  2068. expect(";");
  2069. var test = is("punc", ";") ? null : expression();
  2070. expect(";");
  2071. var step = is("punc", ")") ? null : expression();
  2072. expect(")");
  2073. return as("for", init, test, step, in_loop(statement));
  2074. };
  2075. function for_in(init) {
  2076. var lhs = init[0] == "var" ? as("name", init[1][0]) : init;
  2077. next();
  2078. var obj = expression();
  2079. expect(")");
  2080. return as("for-in", init, lhs, obj, in_loop(statement));
  2081. };
  2082. var function_ = function(in_statement) {
  2083. var name = is("name") ? prog1(S.token.value, next) : null;
  2084. if (in_statement && !name)
  2085. unexpected();
  2086. expect("(");
  2087. return as(in_statement ? "defun" : "function",
  2088. name,
  2089. // arguments
  2090. (function(first, a){
  2091. while (!is("punc", ")")) {
  2092. if (first) first = false; else expect(",");
  2093. if (!is("name")) unexpected();
  2094. a.push(S.token.value);
  2095. next();
  2096. }
  2097. next();
  2098. return a;
  2099. })(true, []),
  2100. // body
  2101. (function(){
  2102. ++S.in_function;
  2103. var loop = S.in_loop;
  2104. S.in_directives = true;
  2105. S.in_loop = 0;
  2106. var a = block_();
  2107. --S.in_function;
  2108. S.in_loop = loop;
  2109. return a;
  2110. })());
  2111. };
  2112. function if_() {
  2113. var cond = parenthesised(), body = statement(), belse;
  2114. if (is("keyword", "else")) {
  2115. next();
  2116. belse = statement();
  2117. }
  2118. return as("if", cond, body, belse);
  2119. };
  2120. function block_() {
  2121. expect("{");
  2122. var a = [];
  2123. while (!is("punc", "}")) {
  2124. if (is("eof")) unexpected();
  2125. a.push(statement());
  2126. }
  2127. next();
  2128. return a;
  2129. };
  2130. var switch_block_ = curry(in_loop, function(){
  2131. expect("{");
  2132. var a = [], cur = null;
  2133. while (!is("punc", "}")) {
  2134. if (is("eof")) unexpected();
  2135. if (is("keyword", "case")) {
  2136. next();
  2137. cur = [];
  2138. a.push([ expression(), cur ]);
  2139. expect(":");
  2140. }
  2141. else if (is("keyword", "default")) {
  2142. next();
  2143. expect(":");
  2144. cur = [];
  2145. a.push([ null, cur ]);
  2146. }
  2147. else {
  2148. if (!cur) unexpected();
  2149. cur.push(statement());
  2150. }
  2151. }
  2152. next();
  2153. return a;
  2154. });
  2155. function try_() {
  2156. var body = block_(), bcatch, bfinally;
  2157. if (is("keyword", "catch")) {
  2158. next();
  2159. expect("(");
  2160. if (!is("name"))
  2161. croak("Name expected");
  2162. var name = S.token.value;
  2163. next();
  2164. expect(")");
  2165. bcatch = [ name, block_() ];
  2166. }
  2167. if (is("keyword", "finally")) {
  2168. next();
  2169. bfinally = block_();
  2170. }
  2171. if (!bcatch && !bfinally)
  2172. croak("Missing catch/finally blocks");
  2173. return as("try", body, bcatch, bfinally);
  2174. };
  2175. function vardefs(no_in) {
  2176. var a = [];
  2177. for (;;) {
  2178. if (!is("name"))
  2179. unexpected();
  2180. var name = S.token.value;
  2181. next();
  2182. if (is("operator", "=")) {
  2183. next();
  2184. a.push([ name, expression(false, no_in) ]);
  2185. } else {
  2186. a.push([ name ]);
  2187. }
  2188. if (!is("punc", ","))
  2189. break;
  2190. next();
  2191. }
  2192. return a;
  2193. };
  2194. function var_(no_in) {
  2195. return as("var", vardefs(no_in));
  2196. };
  2197. function const_() {
  2198. return as("const", vardefs());
  2199. };
  2200. function new_() {
  2201. var newexp = expr_atom(false), args;
  2202. if (is("punc", "(")) {
  2203. next();
  2204. args = expr_list(")");
  2205. } else {
  2206. args = [];
  2207. }
  2208. return subscripts(as("new", newexp, args), true);
  2209. };
  2210. var expr_atom = maybe_embed_tokens(function(allow_calls) {
  2211. if (is("operator", "new")) {
  2212. next();
  2213. return new_();
  2214. }
  2215. if (is("punc")) {
  2216. switch (S.token.value) {
  2217. case "(":
  2218. next();
  2219. return subscripts(prog1(expression, curry(expect, ")")), allow_calls);
  2220. case "[":
  2221. next();
  2222. return subscripts(array_(), allow_calls);
  2223. case "{":
  2224. next();
  2225. return subscripts(object_(), allow_calls);
  2226. }
  2227. unexpected();
  2228. }
  2229. if (is("keyword", "function")) {
  2230. next();
  2231. return subscripts(function_(false), allow_calls);
  2232. }
  2233. if (HOP(ATOMIC_START_TOKEN, S.token.type)) {
  2234. var atom = S.token.type == "regexp"
  2235. ? as("regexp", S.token.value[0], S.token.value[1])
  2236. : as(S.token.type, S.token.value);
  2237. return subscripts(prog1(atom, next), allow_calls);
  2238. }
  2239. unexpected();
  2240. });
  2241. function expr_list(closing, allow_trailing_comma, allow_empty) {
  2242. var first = true, a = [];
  2243. while (!is("punc", closing)) {
  2244. if (first) first = false; else expect(",");
  2245. if (allow_trailing_comma && is("punc", closing)) break;
  2246. if (is("punc", ",") && allow_empty) {
  2247. a.push([ "atom", "undefined" ]);
  2248. } else {
  2249. a.push(expression(false));
  2250. }
  2251. }
  2252. next();
  2253. return a;
  2254. };
  2255. function array_() {
  2256. return as("array", expr_list("]", !exigent_mode, true));
  2257. };
  2258. function object_() {
  2259. var first = true, a = [];
  2260. while (!is("punc", "}")) {
  2261. if (first) first = false; else expect(",");
  2262. if (!exigent_mode && is("punc", "}"))
  2263. // allow trailing comma
  2264. break;
  2265. var type = S.token.type;
  2266. var name = as_property_name();
  2267. if (type == "name" && (name == "get" || name == "set") && !is("punc", ":")) {
  2268. a.push([ as_name(), function_(false), name ]);
  2269. } else {
  2270. expect(":");
  2271. a.push([ name, expression(false) ]);
  2272. }
  2273. }
  2274. next();
  2275. return as("object", a);
  2276. };
  2277. function as_property_name() {
  2278. switch (S.token.type) {
  2279. case "num":
  2280. case "string":
  2281. return prog1(S.token.value, next);
  2282. }
  2283. return as_name();
  2284. };
  2285. function as_name() {
  2286. switch (S.token.type) {
  2287. case "name":
  2288. case "operator":
  2289. case "keyword":
  2290. case "atom":
  2291. return prog1(S.token.value, next);
  2292. default:
  2293. unexpected();
  2294. }
  2295. };
  2296. function subscripts(expr, allow_calls) {
  2297. if (is("punc", ".")) {
  2298. next();
  2299. return subscripts(as("dot", expr, as_name()), allow_calls);
  2300. }
  2301. if (is("punc", "[")) {
  2302. next();
  2303. return subscripts(as("sub", expr, prog1(expression, curry(expect, "]"))), allow_calls);
  2304. }
  2305. if (allow_calls && is("punc", "(")) {
  2306. next();
  2307. return subscripts(as("call", expr, expr_list(")")), true);
  2308. }
  2309. return expr;
  2310. };
  2311. function maybe_unary(allow_calls) {
  2312. if (is("operator") && HOP(UNARY_PREFIX, S.token.value)) {
  2313. return make_unary("unary-prefix",
  2314. prog1(S.token.value, next),
  2315. maybe_unary(allow_calls));
  2316. }
  2317. var val = expr_atom(allow_calls);
  2318. while (is("operator") && HOP(UNARY_POSTFIX, S.token.value) && !S.token.nlb) {
  2319. val = make_unary("unary-postfix", S.token.value, val);
  2320. next();
  2321. }
  2322. return val;
  2323. };
  2324. function make_unary(tag, op, expr) {
  2325. if ((op == "++" || op == "--") && !is_assignable(expr))
  2326. croak("Invalid use of " + op + " operator");
  2327. return as(tag, op, expr);
  2328. };
  2329. function expr_op(left, min_prec, no_in) {
  2330. var op = is("operator") ? S.token.value : null;
  2331. if (op && op == "in" && no_in) op = null;
  2332. var prec = op != null ? PRECEDENCE[op] : null;
  2333. if (prec != null && prec > min_prec) {
  2334. next();
  2335. var right = expr_op(maybe_unary(true), prec, no_in);
  2336. return expr_op(as("binary", op, left, right), min_prec, no_in);
  2337. }
  2338. return left;
  2339. };
  2340. function expr_ops(no_in) {
  2341. return expr_op(maybe_unary(true), 0, no_in);
  2342. };
  2343. function maybe_conditional(no_in) {
  2344. var expr = expr_ops(no_in);
  2345. if (is("operator", "?")) {
  2346. next();
  2347. var yes = expression(false);
  2348. expect(":");
  2349. return as("conditional", expr, yes, expression(false, no_in));
  2350. }
  2351. return expr;
  2352. };
  2353. function is_assignable(expr) {
  2354. if (!exigent_mode) return true;
  2355. switch (expr[0]+"") {
  2356. case "dot":
  2357. case "sub":
  2358. case "new":
  2359. case "call":
  2360. return true;
  2361. case "name":
  2362. return expr[1] != "this";
  2363. }
  2364. };
  2365. function maybe_assign(no_in) {
  2366. var left = maybe_conditional(no_in), val = S.token.value;
  2367. if (is("operator") && HOP(ASSIGNMENT, val)) {
  2368. if (is_assignable(left)) {
  2369. next();
  2370. return as("assign", ASSIGNMENT[val], left, maybe_assign(no_in));
  2371. }
  2372. croak("Invalid assignment");
  2373. }
  2374. return left;
  2375. };
  2376. var expression = maybe_embed_tokens(function(commas, no_in) {
  2377. if (arguments.length == 0)
  2378. commas = true;
  2379. var expr = maybe_assign(no_in);
  2380. if (commas && is("punc", ",")) {
  2381. next();
  2382. return as("seq", expr, expression(true, no_in));
  2383. }
  2384. return expr;
  2385. });
  2386. function in_loop(cont) {
  2387. try {
  2388. ++S.in_loop;
  2389. return cont();
  2390. } finally {
  2391. --S.in_loop;
  2392. }
  2393. };
  2394. return as("toplevel", (function(a){
  2395. while (!is("eof"))
  2396. a.push(statement());
  2397. return a;
  2398. })([]));
  2399. };
  2400. /* -----[ Utilities ]----- */
  2401. function curry(f) {
  2402. var args = slice(arguments, 1);
  2403. return function() { return f.apply(this, args.concat(slice(arguments))); };
  2404. };
  2405. function prog1(ret) {
  2406. if (ret instanceof Function)
  2407. ret = ret();
  2408. for (var i = 1, n = arguments.length; --n > 0; ++i)
  2409. arguments[i]();
  2410. return ret;
  2411. };
  2412. function array_to_hash(a) {
  2413. var ret = {};
  2414. for (var i = 0; i < a.length; ++i)
  2415. ret[a[i]] = true;
  2416. return ret;
  2417. };
  2418. function slice(a, start) {
  2419. return Array.prototype.slice.call(a, start || 0);
  2420. };
  2421. function characters(str) {
  2422. return str.split("");
  2423. };
  2424. function member(name, array) {
  2425. for (var i = array.length; --i >= 0;)
  2426. if (array[i] == name)
  2427. return true;
  2428. return false;
  2429. };
  2430. function HOP(obj, prop) {
  2431. return Object.prototype.hasOwnProperty.call(obj, prop);
  2432. };
  2433. var warn = function() {};
  2434. /* -----[ Exports ]----- */
  2435. exports.tokenizer = tokenizer;
  2436. exports.parse = parse;
  2437. exports.slice = slice;
  2438. exports.curry = curry;
  2439. exports.member = member;
  2440. exports.array_to_hash = array_to_hash;
  2441. exports.PRECEDENCE = PRECEDENCE;
  2442. exports.KEYWORDS_ATOM = KEYWORDS_ATOM;
  2443. exports.RESERVED_WORDS = RESERVED_WORDS;
  2444. exports.KEYWORDS = KEYWORDS;
  2445. exports.ATOMIC_START_TOKEN = ATOMIC_START_TOKEN;
  2446. exports.OPERATORS = OPERATORS;
  2447. exports.is_alphanumeric_char = is_alphanumeric_char;
  2448. exports.is_identifier_start = is_identifier_start;
  2449. exports.is_identifier_char = is_identifier_char;
  2450. exports.set_logger = function(logger) {
  2451. warn = logger;
  2452. };
  2453. }, "process": function(exports, require, module) {/***********************************************************************
  2454. A JavaScript tokenizer / parser / beautifier / compressor.
  2455. This version is suitable for Node.js. With minimal changes (the
  2456. exports stuff) it should work on any JS platform.
  2457. This file implements some AST processors. They work on data built
  2458. by parse-js.
  2459. Exported functions:
  2460. - ast_mangle(ast, options) -- mangles the variable/function names
  2461. in the AST. Returns an AST.
  2462. - ast_squeeze(ast) -- employs various optimizations to make the
  2463. final generated code even smaller. Returns an AST.
  2464. - gen_code(ast, options) -- generates JS code from the AST. Pass
  2465. true (or an object, see the code for some options) as second
  2466. argument to get "pretty" (indented) code.
  2467. -------------------------------- (C) ---------------------------------
  2468. Author: Mihai Bazon
  2469. <mihai.bazon@gmail.com>
  2470. http://mihai.bazon.net/blog
  2471. Distributed under the BSD license:
  2472. Copyright 2010 (c) Mihai Bazon <mihai.bazon@gmail.com>
  2473. Redistribution and use in source and binary forms, with or without
  2474. modification, are permitted provided that the following conditions
  2475. are met:
  2476. * Redistributions of source code must retain the above
  2477. copyright notice, this list of conditions and the following
  2478. disclaimer.
  2479. * Redistributions in binary form must reproduce the above
  2480. copyright notice, this list of conditions and the following
  2481. disclaimer in the documentation and/or other materials
  2482. provided with the distribution.
  2483. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
  2484. EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  2485. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  2486. PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
  2487. LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
  2488. OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  2489. PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  2490. PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  2491. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
  2492. TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
  2493. THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  2494. SUCH DAMAGE.
  2495. ***********************************************************************/
  2496. var jsp = require("./parse-js"),
  2497. slice = jsp.slice,
  2498. member = jsp.member,
  2499. is_identifier_char = jsp.is_identifier_char,
  2500. PRECEDENCE = jsp.PRECEDENCE,
  2501. OPERATORS = jsp.OPERATORS;
  2502. /* -----[ helper for AST traversal ]----- */
  2503. function ast_walker() {
  2504. function _vardefs(defs) {
  2505. return [ this[0], MAP(defs, function(def){
  2506. var a = [ def[0] ];
  2507. if (def.length > 1)
  2508. a[1] = walk(def[1]);
  2509. return a;
  2510. }) ];
  2511. };
  2512. function _block(statements) {
  2513. var out = [ this[0] ];
  2514. if (statements != null)
  2515. out.push(MAP(statements, walk));
  2516. return out;
  2517. };
  2518. var walkers = {
  2519. "string": function(str) {
  2520. return [ this[0], str ];
  2521. },
  2522. "num": function(num) {
  2523. return [ this[0], num ];
  2524. },
  2525. "name": function(name) {
  2526. return [ this[0], name ];
  2527. },
  2528. "toplevel": function(statements) {
  2529. return [ this[0], MAP(statements, walk) ];
  2530. },
  2531. "block": _block,
  2532. "splice": _block,
  2533. "var": _vardefs,
  2534. "const": _vardefs,
  2535. "try": function(t, c, f) {
  2536. return [
  2537. this[0],
  2538. MAP(t, walk),
  2539. c != null ? [ c[0], MAP(c[1], walk) ] : null,
  2540. f != null ? MAP(f, walk) : null
  2541. ];
  2542. },
  2543. "throw": function(expr) {
  2544. return [ this[0], walk(expr) ];
  2545. },
  2546. "new": function(ctor, args) {
  2547. return [ this[0], walk(ctor), MAP(args, walk) ];
  2548. },
  2549. "switch": function(expr, body) {
  2550. return [ this[0], walk(expr), MAP(body, function(branch){
  2551. return [ branch[0] ? walk(branch[0]) : null,
  2552. MAP(branch[1], walk) ];
  2553. }) ];
  2554. },
  2555. "break": function(label) {
  2556. return [ this[0], label ];
  2557. },
  2558. "continue": function(label) {
  2559. return [ this[0], label ];
  2560. },
  2561. "conditional": function(cond, t, e) {
  2562. return [ this[0], walk(cond), walk(t), walk(e) ];
  2563. },
  2564. "assign": function(op, lvalue, rvalue) {
  2565. return [ this[0], op, walk(lvalue), walk(rvalue) ];
  2566. },
  2567. "dot": function(expr) {
  2568. return [ this[0], walk(expr) ].concat(slice(arguments, 1));
  2569. },
  2570. "call": function(expr, args) {
  2571. return [ this[0], walk(expr), MAP(args, walk) ];
  2572. },
  2573. "function": function(name, args, body) {
  2574. return [ this[0], name, args.slice(), MAP(body, walk) ];
  2575. },
  2576. "debugger": function() {
  2577. return [ this[0] ];
  2578. },
  2579. "defun": function(name, args, body) {
  2580. return [ this[0], name, args.slice(), MAP(body, walk) ];
  2581. },
  2582. "if": function(conditional, t, e) {
  2583. return [ this[0], walk(conditional), walk(t), walk(e) ];
  2584. },
  2585. "for": function(init, cond, step, block) {
  2586. return [ this[0], walk(init), walk(cond), walk(step), walk(block) ];
  2587. },
  2588. "for-in": function(vvar, key, hash, block) {
  2589. return [ this[0], walk(vvar), walk(key), walk(hash), walk(block) ];
  2590. },
  2591. "while": function(cond, block) {
  2592. return [ this[0], walk(cond), walk(block) ];
  2593. },
  2594. "do": function(cond, block) {
  2595. return [ this[0], walk(cond), walk(block) ];
  2596. },
  2597. "return": function(expr) {
  2598. return [ this[0], walk(expr) ];
  2599. },
  2600. "binary": function(op, left, right) {
  2601. return [ this[0], op, walk(left), walk(right) ];
  2602. },
  2603. "unary-prefix": function(op, expr) {
  2604. return [ this[0], op, walk(expr) ];
  2605. },
  2606. "unary-postfix": function(op, expr) {
  2607. return [ this[0], op, walk(expr) ];
  2608. },
  2609. "sub": function(expr, subscript) {
  2610. return [ this[0], walk(expr), walk(subscript) ];
  2611. },
  2612. "object": function(props) {
  2613. return [ this[0], MAP(props, function(p){
  2614. return p.length == 2
  2615. ? [ p[0], walk(p[1]) ]
  2616. : [ p[0], walk(p[1]), p[2] ]; // get/set-ter
  2617. }) ];
  2618. },
  2619. "regexp": function(rx, mods) {
  2620. return [ this[0], rx, mods ];
  2621. },
  2622. "array": function(elements) {
  2623. return [ this[0], MAP(elements, walk) ];
  2624. },
  2625. "stat": function(stat) {
  2626. return [ this[0], walk(stat) ];
  2627. },
  2628. "seq": function() {
  2629. return [ this[0] ].concat(MAP(slice(arguments), walk));
  2630. },
  2631. "label": function(name, block) {
  2632. return [ this[0], name, walk(block) ];
  2633. },
  2634. "with": function(expr, block) {
  2635. return [ this[0], walk(expr), walk(block) ];
  2636. },
  2637. "atom": function(name) {
  2638. return [ this[0], name ];
  2639. },
  2640. "directive": function(dir) {
  2641. return [ this[0], dir ];
  2642. }
  2643. };
  2644. var user = {};
  2645. var stack = [];
  2646. function walk(ast) {
  2647. if (ast == null)
  2648. return null;
  2649. try {
  2650. stack.push(ast);
  2651. var type = ast[0];
  2652. var gen = user[type];
  2653. if (gen) {
  2654. var ret = gen.apply(ast, ast.slice(1));
  2655. if (ret != null)
  2656. return ret;
  2657. }
  2658. gen = walkers[type];
  2659. return gen.apply(ast, ast.slice(1));
  2660. } finally {
  2661. stack.pop();
  2662. }
  2663. };
  2664. function dive(ast) {
  2665. if (ast == null)
  2666. return null;
  2667. try {
  2668. stack.push(ast);
  2669. return walkers[ast[0]].apply(ast, ast.slice(1));
  2670. } finally {
  2671. stack.pop();
  2672. }
  2673. };
  2674. function with_walkers(walkers, cont){
  2675. var save = {}, i;
  2676. for (i in walkers) if (HOP(walkers, i)) {
  2677. save[i] = user[i];
  2678. user[i] = walkers[i];
  2679. }
  2680. var ret = cont();
  2681. for (i in save) if (HOP(save, i)) {
  2682. if (!save[i]) delete user[i];
  2683. else user[i] = save[i];
  2684. }
  2685. return ret;
  2686. };
  2687. return {
  2688. walk: walk,
  2689. dive: dive,
  2690. with_walkers: with_walkers,
  2691. parent: function() {
  2692. return stack[stack.length - 2]; // last one is current node
  2693. },
  2694. stack: function() {
  2695. return stack;
  2696. }
  2697. };
  2698. };
  2699. /* -----[ Scope and mangling ]----- */
  2700. function Scope(parent) {
  2701. this.names = {}; // names defined in this scope
  2702. this.mangled = {}; // mangled names (orig.name => mangled)
  2703. this.rev_mangled = {}; // reverse lookup (mangled => orig.name)
  2704. this.cname = -1; // current mangled name
  2705. this.refs = {}; // names referenced from this scope
  2706. this.uses_with = false; // will become TRUE if with() is detected in this or any subscopes
  2707. this.uses_eval = false; // will become TRUE if eval() is detected in this or any subscopes
  2708. this.directives = []; // directives activated from this scope
  2709. this.parent = parent; // parent scope
  2710. this.children = []; // sub-scopes
  2711. if (parent) {
  2712. this.level = parent.level + 1;
  2713. parent.children.push(this);
  2714. } else {
  2715. this.level = 0;
  2716. }
  2717. };
  2718. function base54_digits() {
  2719. if (typeof DIGITS_OVERRIDE_FOR_TESTING != "undefined")
  2720. return DIGITS_OVERRIDE_FOR_TESTING;
  2721. else
  2722. return "etnrisouaflchpdvmgybwESxTNCkLAOM_DPHBjFIqRUzWXV$JKQGYZ0516372984";
  2723. }
  2724. var base54 = (function(){
  2725. var DIGITS = base54_digits();
  2726. return function(num) {
  2727. var ret = "", base = 54;
  2728. do {
  2729. ret += DIGITS.charAt(num % base);
  2730. num = Math.floor(num / base);
  2731. base = 64;
  2732. } while (num > 0);
  2733. return ret;
  2734. };
  2735. })();
  2736. Scope.prototype = {
  2737. has: function(name) {
  2738. for (var s = this; s; s = s.parent)
  2739. if (HOP(s.names, name))
  2740. return s;
  2741. },
  2742. has_mangled: function(mname) {
  2743. for (var s = this; s; s = s.parent)
  2744. if (HOP(s.rev_mangled, mname))
  2745. return s;
  2746. },
  2747. toJSON: function() {
  2748. return {
  2749. names: this.names,
  2750. uses_eval: this.uses_eval,
  2751. uses_with: this.uses_with
  2752. };
  2753. },
  2754. next_mangled: function() {
  2755. // we must be careful that the new mangled name:
  2756. //
  2757. // 1. doesn't shadow a mangled name from a parent
  2758. // scope, unless we don't reference the original
  2759. // name from this scope OR from any sub-scopes!
  2760. // This will get slow.
  2761. //
  2762. // 2. doesn't shadow an original name from a parent
  2763. // scope, in the event that the name is not mangled
  2764. // in the parent scope and we reference that name
  2765. // here OR IN ANY SUBSCOPES!
  2766. //
  2767. // 3. doesn't shadow a name that is referenced but not
  2768. // defined (possibly global defined elsewhere).
  2769. for (;;) {
  2770. var m = base54(++this.cname), prior;
  2771. // case 1.
  2772. prior = this.has_mangled(m);
  2773. if (prior && this.refs[prior.rev_mangled[m]] === prior)
  2774. continue;
  2775. // case 2.
  2776. prior = this.has(m);
  2777. if (prior && prior !== this && this.refs[m] === prior && !prior.has_mangled(m))
  2778. continue;
  2779. // case 3.
  2780. if (HOP(this.refs, m) && this.refs[m] == null)
  2781. continue;
  2782. // I got "do" once. :-/
  2783. if (!is_identifier(m))
  2784. continue;
  2785. return m;
  2786. }
  2787. },
  2788. set_mangle: function(name, m) {
  2789. this.rev_mangled[m] = name;
  2790. return this.mangled[name] = m;
  2791. },
  2792. get_mangled: function(name, newMangle) {
  2793. if (this.uses_eval || this.uses_with) return name; // no mangle if eval or with is in use
  2794. var s = this.has(name);
  2795. if (!s) return name; // not in visible scope, no mangle
  2796. if (HOP(s.mangled, name)) return s.mangled[name]; // already mangled in this scope
  2797. if (!newMangle) return name; // not found and no mangling requested
  2798. return s.set_mangle(name, s.next_mangled());
  2799. },
  2800. references: function(name) {
  2801. return name && !this.parent || this.uses_with || this.uses_eval || this.refs[name];
  2802. },
  2803. define: function(name, type) {
  2804. if (name != null) {
  2805. if (type == "var" || !HOP(this.names, name))
  2806. this.names[name] = type || "var";
  2807. return name;
  2808. }
  2809. },
  2810. active: function(dir) {
  2811. return member(dir, this.directives) || this.parent && this.parent.active(dir);
  2812. }
  2813. };
  2814. function ast_add_scope(ast) {
  2815. var current_scope = null;
  2816. var w = ast_walker(), walk = w.walk;
  2817. var having_eval = [];
  2818. function with_new_scope(cont) {
  2819. current_scope = new Scope(current_scope);
  2820. current_scope.labels = new Scope();
  2821. var ret = current_scope.body = cont();
  2822. ret.scope = current_scope;
  2823. current_scope = current_scope.parent;
  2824. return ret;
  2825. };
  2826. function define(name, type) {
  2827. return current_scope.define(name, type);
  2828. };
  2829. function reference(name) {
  2830. current_scope.refs[name] = true;
  2831. };
  2832. function _lambda(name, args, body) {
  2833. var is_defun = this[0] == "defun";
  2834. return [ this[0], is_defun ? define(name, "defun") : name, args, with_new_scope(function(){
  2835. if (!is_defun) define(name, "lambda");
  2836. MAP(args, function(name){ define(name, "arg") });
  2837. return MAP(body, walk);
  2838. })];
  2839. };
  2840. function _vardefs(type) {
  2841. return function(defs) {
  2842. MAP(defs, function(d){
  2843. define(d[0], type);
  2844. if (d[1]) reference(d[0]);
  2845. });
  2846. };
  2847. };
  2848. function _breacont(label) {
  2849. if (label)
  2850. current_scope.labels.refs[label] = true;
  2851. };
  2852. return with_new_scope(function(){
  2853. // process AST
  2854. var ret = w.with_walkers({
  2855. "function": _lambda,
  2856. "defun": _lambda,
  2857. "label": function(name, stat) { current_scope.labels.define(name) },
  2858. "break": _breacont,
  2859. "continue": _breacont,
  2860. "with": function(expr, block) {
  2861. for (var s = current_scope; s; s = s.parent)
  2862. s.uses_with = true;
  2863. },
  2864. "var": _vardefs("var"),
  2865. "const": _vardefs("const"),
  2866. "try": function(t, c, f) {
  2867. if (c != null) return [
  2868. this[0],
  2869. MAP(t, walk),
  2870. [ define(c[0], "catch"), MAP(c[1], walk) ],
  2871. f != null ? MAP(f, walk) : null
  2872. ];
  2873. },
  2874. "name": function(name) {
  2875. if (name == "eval")
  2876. having_eval.push(current_scope);
  2877. reference(name);
  2878. }
  2879. }, function(){
  2880. return walk(ast);
  2881. });
  2882. // the reason why we need an additional pass here is
  2883. // that names can be used prior to their definition.
  2884. // scopes where eval was detected and their parents
  2885. // are marked with uses_eval, unless they define the
  2886. // "eval" name.
  2887. MAP(having_eval, function(scope){
  2888. if (!scope.has("eval")) while (scope) {
  2889. scope.uses_eval = true;
  2890. scope = scope.parent;
  2891. }
  2892. });
  2893. // for referenced names it might be useful to know
  2894. // their origin scope. current_scope here is the
  2895. // toplevel one.
  2896. function fixrefs(scope, i) {
  2897. // do children first; order shouldn't matter
  2898. for (i = scope.children.length; --i >= 0;)
  2899. fixrefs(scope.children[i]);
  2900. for (i in scope.refs) if (HOP(scope.refs, i)) {
  2901. // find origin scope and propagate the reference to origin
  2902. for (var origin = scope.has(i), s = scope; s; s = s.parent) {
  2903. s.refs[i] = origin;
  2904. if (s === origin) break;
  2905. }
  2906. }
  2907. };
  2908. fixrefs(current_scope);
  2909. return ret;
  2910. });
  2911. };
  2912. /* -----[ mangle names ]----- */
  2913. function ast_mangle(ast, options) {
  2914. var w = ast_walker(), walk = w.walk, scope;
  2915. options = defaults(options, {
  2916. mangle : true,
  2917. toplevel : false,
  2918. defines : null,
  2919. except : null,
  2920. no_functions : false
  2921. });
  2922. function get_mangled(name, newMangle) {
  2923. if (!options.mangle) return name;
  2924. if (!options.toplevel && !scope.parent) return name; // don't mangle toplevel
  2925. if (options.except && member(name, options.except))
  2926. return name;
  2927. if (options.no_functions && HOP(scope.names, name) &&
  2928. (scope.names[name] == 'defun' || scope.names[name] == 'lambda'))
  2929. return name;
  2930. return scope.get_mangled(name, newMangle);
  2931. };
  2932. function get_define(name) {
  2933. if (options.defines) {
  2934. // we always lookup a defined symbol for the current scope FIRST, so declared
  2935. // vars trump a DEFINE symbol, but if no such var is found, then match a DEFINE value
  2936. if (!scope.has(name)) {
  2937. if (HOP(options.defines, name)) {
  2938. return options.defines[name];
  2939. }
  2940. }
  2941. return null;
  2942. }
  2943. };
  2944. function _lambda(name, args, body) {
  2945. if (!options.no_functions && options.mangle) {
  2946. var is_defun = this[0] == "defun", extra;
  2947. if (name) {
  2948. if (is_defun) name = get_mangled(name);
  2949. else if (body.scope.references(name)) {
  2950. extra = {};
  2951. if (!(scope.uses_eval || scope.uses_with))
  2952. name = extra[name] = scope.next_mangled();
  2953. else
  2954. extra[name] = name;
  2955. }
  2956. else name = null;
  2957. }
  2958. }
  2959. body = with_scope(body.scope, function(){
  2960. args = MAP(args, function(name){ return get_mangled(name) });
  2961. return MAP(body, walk);
  2962. }, extra);
  2963. return [ this[0], name, args, body ];
  2964. };
  2965. function with_scope(s, cont, extra) {
  2966. var _scope = scope;
  2967. scope = s;
  2968. if (extra) for (var i in extra) if (HOP(extra, i)) {
  2969. s.set_mangle(i, extra[i]);
  2970. }
  2971. for (var i in s.names) if (HOP(s.names, i)) {
  2972. get_mangled(i, true);
  2973. }
  2974. var ret = cont();
  2975. ret.scope = s;
  2976. scope = _scope;
  2977. return ret;
  2978. };
  2979. function _vardefs(defs) {
  2980. return [ this[0], MAP(defs, function(d){
  2981. return [ get_mangled(d[0]), walk(d[1]) ];
  2982. }) ];
  2983. };
  2984. function _breacont(label) {
  2985. if (label) return [ this[0], scope.labels.get_mangled(label) ];
  2986. };
  2987. return w.with_walkers({
  2988. "function": _lambda,
  2989. "defun": function() {
  2990. // move function declarations to the top when
  2991. // they are not in some block.
  2992. var ast = _lambda.apply(this, arguments);
  2993. switch (w.parent()[0]) {
  2994. case "toplevel":
  2995. case "function":
  2996. case "defun":
  2997. return MAP.at_top(ast);
  2998. }
  2999. return ast;
  3000. },
  3001. "label": function(label, stat) {
  3002. if (scope.labels.refs[label]) return [
  3003. this[0],
  3004. scope.labels.get_mangled(label, true),
  3005. walk(stat)
  3006. ];
  3007. return walk(stat);
  3008. },
  3009. "break": _breacont,
  3010. "continue": _breacont,
  3011. "var": _vardefs,
  3012. "const": _vardefs,
  3013. "name": function(name) {
  3014. return get_define(name) || [ this[0], get_mangled(name) ];
  3015. },
  3016. "try": function(t, c, f) {
  3017. return [ this[0],
  3018. MAP(t, walk),
  3019. c != null ? [ get_mangled(c[0]), MAP(c[1], walk) ] : null,
  3020. f != null ? MAP(f, walk) : null ];
  3021. },
  3022. "toplevel": function(body) {
  3023. var self = this;
  3024. return with_scope(self.scope, function(){
  3025. return [ self[0], MAP(body, walk) ];
  3026. });
  3027. },
  3028. "directive": function() {
  3029. return MAP.at_top(this);
  3030. }
  3031. }, function() {
  3032. return walk(ast_add_scope(ast));
  3033. });
  3034. };
  3035. /* -----[
  3036. - compress foo["bar"] into foo.bar,
  3037. - remove block brackets {} where possible
  3038. - join consecutive var declarations
  3039. - various optimizations for IFs:
  3040. - if (cond) foo(); else bar(); ==> cond?foo():bar();
  3041. - if (cond) foo(); ==> cond&&foo();
  3042. - if (foo) return bar(); else return baz(); ==> return foo?bar():baz(); // also for throw
  3043. - if (foo) return bar(); else something(); ==> {if(foo)return bar();something()}
  3044. ]----- */
  3045. var warn = function(){};
  3046. function best_of(ast1, ast2) {
  3047. return gen_code(ast1).length > gen_code(ast2[0] == "stat" ? ast2[1] : ast2).length ? ast2 : ast1;
  3048. };
  3049. function last_stat(b) {
  3050. if (b[0] == "block" && b[1] && b[1].length > 0)
  3051. return b[1][b[1].length - 1];
  3052. return b;
  3053. }
  3054. function aborts(t) {
  3055. if (t) switch (last_stat(t)[0]) {
  3056. case "return":
  3057. case "break":
  3058. case "continue":
  3059. case "throw":
  3060. return true;
  3061. }
  3062. };
  3063. function boolean_expr(expr) {
  3064. return ( (expr[0] == "unary-prefix"
  3065. && member(expr[1], [ "!", "delete" ])) ||
  3066. (expr[0] == "binary"
  3067. && member(expr[1], [ "in", "instanceof", "==", "!=", "===", "!==", "<", "<=", ">=", ">" ])) ||
  3068. (expr[0] == "binary"
  3069. && member(expr[1], [ "&&", "||" ])
  3070. && boolean_expr(expr[2])
  3071. && boolean_expr(expr[3])) ||
  3072. (expr[0] == "conditional"
  3073. && boolean_expr(expr[2])
  3074. && boolean_expr(expr[3])) ||
  3075. (expr[0] == "assign"
  3076. && expr[1] === true
  3077. && boolean_expr(expr[3])) ||
  3078. (expr[0] == "seq"
  3079. && boolean_expr(expr[expr.length - 1]))
  3080. );
  3081. };
  3082. function empty(b) {
  3083. return !b || (b[0] == "block" && (!b[1] || b[1].length == 0));
  3084. };
  3085. function is_string(node) {
  3086. return (node[0] == "string" ||
  3087. node[0] == "unary-prefix" && node[1] == "typeof" ||
  3088. node[0] == "binary" && node[1] == "+" &&
  3089. (is_string(node[2]) || is_string(node[3])));
  3090. };
  3091. var when_constant = (function(){
  3092. var $NOT_CONSTANT = {};
  3093. // this can only evaluate constant expressions. If it finds anything
  3094. // not constant, it throws $NOT_CONSTANT.
  3095. function evaluate(expr) {
  3096. switch (expr[0]) {
  3097. case "string":
  3098. case "num":
  3099. return expr[1];
  3100. case "name":
  3101. case "atom":
  3102. switch (expr[1]) {
  3103. case "true": return true;
  3104. case "false": return false;
  3105. case "null": return null;
  3106. }
  3107. break;
  3108. case "unary-prefix":
  3109. switch (expr[1]) {
  3110. case "!": return !evaluate(expr[2]);
  3111. case "typeof": return typeof evaluate(expr[2]);
  3112. case "~": return ~evaluate(expr[2]);
  3113. case "-": return -evaluate(expr[2]);
  3114. case "+": return +evaluate(expr[2]);
  3115. }
  3116. break;
  3117. case "binary":
  3118. var left = expr[2], right = expr[3];
  3119. switch (expr[1]) {
  3120. case "&&" : return evaluate(left) && evaluate(right);
  3121. case "||" : return evaluate(left) || evaluate(right);
  3122. case "|" : return evaluate(left) | evaluate(right);
  3123. case "&" : return evaluate(left) & evaluate(right);
  3124. case "^" : return evaluate(left) ^ evaluate(right);
  3125. case "+" : return evaluate(left) + evaluate(right);
  3126. case "*" : return evaluate(left) * evaluate(right);
  3127. case "/" : return evaluate(left) / evaluate(right);
  3128. case "%" : return evaluate(left) % evaluate(right);
  3129. case "-" : return evaluate(left) - evaluate(right);
  3130. case "<<" : return evaluate(left) << evaluate(right);
  3131. case ">>" : return evaluate(left) >> evaluate(right);
  3132. case ">>>" : return evaluate(left) >>> evaluate(right);
  3133. case "==" : return evaluate(left) == evaluate(right);
  3134. case "===" : return evaluate(left) === evaluate(right);
  3135. case "!=" : return evaluate(left) != evaluate(right);
  3136. case "!==" : return evaluate(left) !== evaluate(right);
  3137. case "<" : return evaluate(left) < evaluate(right);
  3138. case "<=" : return evaluate(left) <= evaluate(right);
  3139. case ">" : return evaluate(left) > evaluate(right);
  3140. case ">=" : return evaluate(left) >= evaluate(right);
  3141. case "in" : return evaluate(left) in evaluate(right);
  3142. case "instanceof" : return evaluate(left) instanceof evaluate(right);
  3143. }
  3144. }
  3145. throw $NOT_CONSTANT;
  3146. };
  3147. return function(expr, yes, no) {
  3148. try {
  3149. var val = evaluate(expr), ast;
  3150. switch (typeof val) {
  3151. case "string": ast = [ "string", val ]; break;
  3152. case "number": ast = [ "num", val ]; break;
  3153. case "boolean": ast = [ "name", String(val) ]; break;
  3154. default:
  3155. if (val === null) { ast = [ "atom", "null" ]; break; }
  3156. throw new Error("Can't handle constant of type: " + (typeof val));
  3157. }
  3158. return yes.call(expr, ast, val);
  3159. } catch(ex) {
  3160. if (ex === $NOT_CONSTANT) {
  3161. if (expr[0] == "binary"
  3162. && (expr[1] == "===" || expr[1] == "!==")
  3163. && ((is_string(expr[2]) && is_string(expr[3]))
  3164. || (boolean_expr(expr[2]) && boolean_expr(expr[3])))) {
  3165. expr[1] = expr[1].substr(0, 2);
  3166. }
  3167. else if (no && expr[0] == "binary"
  3168. && (expr[1] == "||" || expr[1] == "&&")) {
  3169. // the whole expression is not constant but the lval may be...
  3170. try {
  3171. var lval = evaluate(expr[2]);
  3172. expr = ((expr[1] == "&&" && (lval ? expr[3] : lval)) ||
  3173. (expr[1] == "||" && (lval ? lval : expr[3])) ||
  3174. expr);
  3175. } catch(ex2) {
  3176. // IGNORE... lval is not constant
  3177. }
  3178. }
  3179. return no ? no.call(expr, expr) : null;
  3180. }
  3181. else throw ex;
  3182. }
  3183. };
  3184. })();
  3185. function warn_unreachable(ast) {
  3186. if (!empty(ast))
  3187. warn("Dropping unreachable code: " + gen_code(ast, true));
  3188. };
  3189. function prepare_ifs(ast) {
  3190. var w = ast_walker(), walk = w.walk;
  3191. // In this first pass, we rewrite ifs which abort with no else with an
  3192. // if-else. For example:
  3193. //
  3194. // if (x) {
  3195. // blah();
  3196. // return y;
  3197. // }
  3198. // foobar();
  3199. //
  3200. // is rewritten into:
  3201. //
  3202. // if (x) {
  3203. // blah();
  3204. // return y;
  3205. // } else {
  3206. // foobar();
  3207. // }
  3208. function redo_if(statements) {
  3209. statements = MAP(statements, walk);
  3210. for (var i = 0; i < statements.length; ++i) {
  3211. var fi = statements[i];
  3212. if (fi[0] != "if") continue;
  3213. if (fi[3] && walk(fi[3])) continue;
  3214. var t = walk(fi[2]);
  3215. if (!aborts(t)) continue;
  3216. var conditional = walk(fi[1]);
  3217. var e_body = redo_if(statements.slice(i + 1));
  3218. var e = e_body.length == 1 ? e_body[0] : [ "block", e_body ];
  3219. return statements.slice(0, i).concat([ [
  3220. fi[0], // "if"
  3221. conditional, // conditional
  3222. t, // then
  3223. e // else
  3224. ] ]);
  3225. }
  3226. return statements;
  3227. };
  3228. function redo_if_lambda(name, args, body) {
  3229. body = redo_if(body);
  3230. return [ this[0], name, args, body ];
  3231. };
  3232. function redo_if_block(statements) {
  3233. return [ this[0], statements != null ? redo_if(statements) : null ];
  3234. };
  3235. return w.with_walkers({
  3236. "defun": redo_if_lambda,
  3237. "function": redo_if_lambda,
  3238. "block": redo_if_block,
  3239. "splice": redo_if_block,
  3240. "toplevel": function(statements) {
  3241. return [ this[0], redo_if(statements) ];
  3242. },
  3243. "try": function(t, c, f) {
  3244. return [
  3245. this[0],
  3246. redo_if(t),
  3247. c != null ? [ c[0], redo_if(c[1]) ] : null,
  3248. f != null ? redo_if(f) : null
  3249. ];
  3250. }
  3251. }, function() {
  3252. return walk(ast);
  3253. });
  3254. };
  3255. function for_side_effects(ast, handler) {
  3256. var w = ast_walker(), walk = w.walk;
  3257. var $stop = {}, $restart = {};
  3258. function stop() { throw $stop };
  3259. function restart() { throw $restart };
  3260. function found(){ return handler.call(this, this, w, stop, restart) };
  3261. function unary(op) {
  3262. if (op == "++" || op == "--")
  3263. return found.apply(this, arguments);
  3264. };
  3265. return w.with_walkers({
  3266. "try": found,
  3267. "throw": found,
  3268. "return": found,
  3269. "new": found,
  3270. "switch": found,
  3271. "break": found,
  3272. "continue": found,
  3273. "assign": found,
  3274. "call": found,
  3275. "if": found,
  3276. "for": found,
  3277. "for-in": found,
  3278. "while": found,
  3279. "do": found,
  3280. "return": found,
  3281. "unary-prefix": unary,
  3282. "unary-postfix": unary,
  3283. "defun": found
  3284. }, function(){
  3285. while (true) try {
  3286. walk(ast);
  3287. break;
  3288. } catch(ex) {
  3289. if (ex === $stop) break;
  3290. if (ex === $restart) continue;
  3291. throw ex;
  3292. }
  3293. });
  3294. };
  3295. function ast_lift_variables(ast) {
  3296. var w = ast_walker(), walk = w.walk, scope;
  3297. function do_body(body, env) {
  3298. var _scope = scope;
  3299. scope = env;
  3300. body = MAP(body, walk);
  3301. var hash = {}, names = MAP(env.names, function(type, name){
  3302. if (type != "var") return MAP.skip;
  3303. if (!env.references(name)) return MAP.skip;
  3304. hash[name] = true;
  3305. return [ name ];
  3306. });
  3307. if (names.length > 0) {
  3308. // looking for assignments to any of these variables.
  3309. // we can save considerable space by moving the definitions
  3310. // in the var declaration.
  3311. for_side_effects([ "block", body ], function(ast, walker, stop, restart) {
  3312. if (ast[0] == "assign"
  3313. && ast[1] === true
  3314. && ast[2][0] == "name"
  3315. && HOP(hash, ast[2][1])) {
  3316. // insert the definition into the var declaration
  3317. for (var i = names.length; --i >= 0;) {
  3318. if (names[i][0] == ast[2][1]) {
  3319. if (names[i][1]) // this name already defined, we must stop
  3320. stop();
  3321. names[i][1] = ast[3]; // definition
  3322. names.push(names.splice(i, 1)[0]);
  3323. break;
  3324. }
  3325. }
  3326. // remove this assignment from the AST.
  3327. var p = walker.parent();
  3328. if (p[0] == "seq") {
  3329. var a = p[2];
  3330. a.unshift(0, p.length);
  3331. p.splice.apply(p, a);
  3332. }
  3333. else if (p[0] == "stat") {
  3334. p.splice(0, p.length, "block"); // empty statement
  3335. }
  3336. else {
  3337. stop();
  3338. }
  3339. restart();
  3340. }
  3341. stop();
  3342. });
  3343. body.unshift([ "var", names ]);
  3344. }
  3345. scope = _scope;
  3346. return body;
  3347. };
  3348. function _vardefs(defs) {
  3349. var ret = null;
  3350. for (var i = defs.length; --i >= 0;) {
  3351. var d = defs[i];
  3352. if (!d[1]) continue;
  3353. d = [ "assign", true, [ "name", d[0] ], d[1] ];
  3354. if (ret == null) ret = d;
  3355. else ret = [ "seq", d, ret ];
  3356. }
  3357. if (ret == null) {
  3358. if (w.parent()[0] == "for-in")
  3359. return [ "name", defs[0][0] ];
  3360. return MAP.skip;
  3361. }
  3362. return [ "stat", ret ];
  3363. };
  3364. function _toplevel(body) {
  3365. return [ this[0], do_body(body, this.scope) ];
  3366. };
  3367. return w.with_walkers({
  3368. "function": function(name, args, body){
  3369. for (var i = args.length; --i >= 0 && !body.scope.references(args[i]);)
  3370. args.pop();
  3371. if (!body.scope.references(name)) name = null;
  3372. return [ this[0], name, args, do_body(body, body.scope) ];
  3373. },
  3374. "defun": function(name, args, body){
  3375. if (!scope.references(name)) return MAP.skip;
  3376. for (var i = args.length; --i >= 0 && !body.scope.references(args[i]);)
  3377. args.pop();
  3378. return [ this[0], name, args, do_body(body, body.scope) ];
  3379. },
  3380. "var": _vardefs,
  3381. "toplevel": _toplevel
  3382. }, function(){
  3383. return walk(ast_add_scope(ast));
  3384. });
  3385. };
  3386. function ast_squeeze(ast, options) {
  3387. options = defaults(options, {
  3388. make_seqs : true,
  3389. dead_code : true,
  3390. no_warnings : false,
  3391. keep_comps : true,
  3392. unsafe : false
  3393. });
  3394. var w = ast_walker(), walk = w.walk, scope;
  3395. function negate(c) {
  3396. var not_c = [ "unary-prefix", "!", c ];
  3397. switch (c[0]) {
  3398. case "unary-prefix":
  3399. return c[1] == "!" && boolean_expr(c[2]) ? c[2] : not_c;
  3400. case "seq":
  3401. c = slice(c);
  3402. c[c.length - 1] = negate(c[c.length - 1]);
  3403. return c;
  3404. case "conditional":
  3405. return best_of(not_c, [ "conditional", c[1], negate(c[2]), negate(c[3]) ]);
  3406. case "binary":
  3407. var op = c[1], left = c[2], right = c[3];
  3408. if (!options.keep_comps) switch (op) {
  3409. case "<=" : return [ "binary", ">", left, right ];
  3410. case "<" : return [ "binary", ">=", left, right ];
  3411. case ">=" : return [ "binary", "<", left, right ];
  3412. case ">" : return [ "binary", "<=", left, right ];
  3413. }
  3414. switch (op) {
  3415. case "==" : return [ "binary", "!=", left, right ];
  3416. case "!=" : return [ "binary", "==", left, right ];
  3417. case "===" : return [ "binary", "!==", left, right ];
  3418. case "!==" : return [ "binary", "===", left, right ];
  3419. case "&&" : return best_of(not_c, [ "binary", "||", negate(left), negate(right) ]);
  3420. case "||" : return best_of(not_c, [ "binary", "&&", negate(left), negate(right) ]);
  3421. }
  3422. break;
  3423. }
  3424. return not_c;
  3425. };
  3426. function make_conditional(c, t, e) {
  3427. var make_real_conditional = function() {
  3428. if (c[0] == "unary-prefix" && c[1] == "!") {
  3429. return e ? [ "conditional", c[2], e, t ] : [ "binary", "||", c[2], t ];
  3430. } else {
  3431. return e ? best_of(
  3432. [ "conditional", c, t, e ],
  3433. [ "conditional", negate(c), e, t ]
  3434. ) : [ "binary", "&&", c, t ];
  3435. }
  3436. };
  3437. // shortcut the conditional if the expression has a constant value
  3438. return when_constant(c, function(ast, val){
  3439. warn_unreachable(val ? e : t);
  3440. return (val ? t : e);
  3441. }, make_real_conditional);
  3442. };
  3443. function rmblock(block) {
  3444. if (block != null && block[0] == "block" && block[1]) {
  3445. if (block[1].length == 1)
  3446. block = block[1][0];
  3447. else if (block[1].length == 0)
  3448. block = [ "block" ];
  3449. }
  3450. return block;
  3451. };
  3452. function _lambda(name, args, body) {
  3453. return [ this[0], name, args, with_scope(body.scope, function() {
  3454. return tighten(body, "lambda");
  3455. }) ];
  3456. };
  3457. function with_scope(s, cont) {
  3458. var _scope = scope;
  3459. scope = s;
  3460. var ret = cont();
  3461. scope = _scope;
  3462. return ret;
  3463. };
  3464. // this function does a few things:
  3465. // 1. discard useless blocks
  3466. // 2. join consecutive var declarations
  3467. // 3. remove obviously dead code
  3468. // 4. transform consecutive statements using the comma operator
  3469. // 5. if block_type == "lambda" and it detects constructs like if(foo) return ... - rewrite like if (!foo) { ... }
  3470. function tighten(statements, block_type) {
  3471. statements = MAP(statements, walk);
  3472. statements = statements.reduce(function(a, stat){
  3473. if (stat[0] == "block") {
  3474. if (stat[1]) {
  3475. a.push.apply(a, stat[1]);
  3476. }
  3477. } else {
  3478. a.push(stat);
  3479. }
  3480. return a;
  3481. }, []);
  3482. statements = (function(a, prev){
  3483. statements.forEach(function(cur){
  3484. if (prev && ((cur[0] == "var" && prev[0] == "var") ||
  3485. (cur[0] == "const" && prev[0] == "const"))) {
  3486. prev[1] = prev[1].concat(cur[1]);
  3487. } else {
  3488. a.push(cur);
  3489. prev = cur;
  3490. }
  3491. });
  3492. return a;
  3493. })([]);
  3494. if (options.dead_code) statements = (function(a, has_quit){
  3495. statements.forEach(function(st){
  3496. if (has_quit) {
  3497. if (st[0] == "function" || st[0] == "defun") {
  3498. a.push(st);
  3499. }
  3500. else if (st[0] == "var" || st[0] == "const") {
  3501. if (!options.no_warnings)
  3502. warn("Variables declared in unreachable code");
  3503. st[1] = MAP(st[1], function(def){
  3504. if (def[1] && !options.no_warnings)
  3505. warn_unreachable([ "assign", true, [ "name", def[0] ], def[1] ]);
  3506. return [ def[0] ];
  3507. });
  3508. a.push(st);
  3509. }
  3510. else if (!options.no_warnings)
  3511. warn_unreachable(st);
  3512. }
  3513. else {
  3514. a.push(st);
  3515. if (member(st[0], [ "return", "throw", "break", "continue" ]))
  3516. has_quit = true;
  3517. }
  3518. });
  3519. return a;
  3520. })([]);
  3521. if (options.make_seqs) statements = (function(a, prev) {
  3522. statements.forEach(function(cur){
  3523. if (prev && prev[0] == "stat" && cur[0] == "stat") {
  3524. prev[1] = [ "seq", prev[1], cur[1] ];
  3525. } else {
  3526. a.push(cur);
  3527. prev = cur;
  3528. }
  3529. });
  3530. if (a.length >= 2
  3531. && a[a.length-2][0] == "stat"
  3532. && (a[a.length-1][0] == "return" || a[a.length-1][0] == "throw")
  3533. && a[a.length-1][1])
  3534. {
  3535. a.splice(a.length - 2, 2,
  3536. [ a[a.length-1][0],
  3537. [ "seq", a[a.length-2][1], a[a.length-1][1] ]]);
  3538. }
  3539. return a;
  3540. })([]);
  3541. // this increases jQuery by 1K. Probably not such a good idea after all..
  3542. // part of this is done in prepare_ifs anyway.
  3543. // if (block_type == "lambda") statements = (function(i, a, stat){
  3544. // while (i < statements.length) {
  3545. // stat = statements[i++];
  3546. // if (stat[0] == "if" && !stat[3]) {
  3547. // if (stat[2][0] == "return" && stat[2][1] == null) {
  3548. // a.push(make_if(negate(stat[1]), [ "block", statements.slice(i) ]));
  3549. // break;
  3550. // }
  3551. // var last = last_stat(stat[2]);
  3552. // if (last[0] == "return" && last[1] == null) {
  3553. // a.push(make_if(stat[1], [ "block", stat[2][1].slice(0, -1) ], [ "block", statements.slice(i) ]));
  3554. // break;
  3555. // }
  3556. // }
  3557. // a.push(stat);
  3558. // }
  3559. // return a;
  3560. // })(0, []);
  3561. return statements;
  3562. };
  3563. function make_if(c, t, e) {
  3564. return when_constant(c, function(ast, val){
  3565. if (val) {
  3566. t = walk(t);
  3567. warn_unreachable(e);
  3568. return t || [ "block" ];
  3569. } else {
  3570. e = walk(e);
  3571. warn_unreachable(t);
  3572. return e || [ "block" ];
  3573. }
  3574. }, function() {
  3575. return make_real_if(c, t, e);
  3576. });
  3577. };
  3578. function abort_else(c, t, e) {
  3579. var ret = [ [ "if", negate(c), e ] ];
  3580. if (t[0] == "block") {
  3581. if (t[1]) ret = ret.concat(t[1]);
  3582. } else {
  3583. ret.push(t);
  3584. }
  3585. return walk([ "block", ret ]);
  3586. };
  3587. function make_real_if(c, t, e) {
  3588. c = walk(c);
  3589. t = walk(t);
  3590. e = walk(e);
  3591. if (empty(e) && empty(t))
  3592. return [ "stat", c ];
  3593. if (empty(t)) {
  3594. c = negate(c);
  3595. t = e;
  3596. e = null;
  3597. } else if (empty(e)) {
  3598. e = null;
  3599. } else {
  3600. // if we have both else and then, maybe it makes sense to switch them?
  3601. (function(){
  3602. var a = gen_code(c);
  3603. var n = negate(c);
  3604. var b = gen_code(n);
  3605. if (b.length < a.length) {
  3606. var tmp = t;
  3607. t = e;
  3608. e = tmp;
  3609. c = n;
  3610. }
  3611. })();
  3612. }
  3613. var ret = [ "if", c, t, e ];
  3614. if (t[0] == "if" && empty(t[3]) && empty(e)) {
  3615. ret = best_of(ret, walk([ "if", [ "binary", "&&", c, t[1] ], t[2] ]));
  3616. }
  3617. else if (t[0] == "stat") {
  3618. if (e) {
  3619. if (e[0] == "stat")
  3620. ret = best_of(ret, [ "stat", make_conditional(c, t[1], e[1]) ]);
  3621. else if (aborts(e))
  3622. ret = abort_else(c, t, e);
  3623. }
  3624. else {
  3625. ret = best_of(ret, [ "stat", make_conditional(c, t[1]) ]);
  3626. }
  3627. }
  3628. else if (e && t[0] == e[0] && (t[0] == "return" || t[0] == "throw") && t[1] && e[1]) {
  3629. ret = best_of(ret, [ t[0], make_conditional(c, t[1], e[1] ) ]);
  3630. }
  3631. else if (e && aborts(t)) {
  3632. ret = [ [ "if", c, t ] ];
  3633. if (e[0] == "block") {
  3634. if (e[1]) ret = ret.concat(e[1]);
  3635. }
  3636. else {
  3637. ret.push(e);
  3638. }
  3639. ret = walk([ "block", ret ]);
  3640. }
  3641. else if (t && aborts(e)) {
  3642. ret = abort_else(c, t, e);
  3643. }
  3644. return ret;
  3645. };
  3646. function _do_while(cond, body) {
  3647. return when_constant(cond, function(cond, val){
  3648. if (!val) {
  3649. warn_unreachable(body);
  3650. return [ "block" ];
  3651. } else {
  3652. return [ "for", null, null, null, walk(body) ];
  3653. }
  3654. });
  3655. };
  3656. return w.with_walkers({
  3657. "sub": function(expr, subscript) {
  3658. if (subscript[0] == "string") {
  3659. var name = subscript[1];
  3660. if (is_identifier(name))
  3661. return [ "dot", walk(expr), name ];
  3662. else if (/^[1-9][0-9]*$/.test(name) || name === "0")
  3663. return [ "sub", walk(expr), [ "num", parseInt(name, 10) ] ];
  3664. }
  3665. },
  3666. "if": make_if,
  3667. "toplevel": function(body) {
  3668. return with_scope(this.scope, function() {
  3669. return [ "toplevel", tighten(body) ];
  3670. });
  3671. },
  3672. "switch": function(expr, body) {
  3673. var last = body.length - 1;
  3674. return [ "switch", walk(expr), MAP(body, function(branch, i){
  3675. var block = tighten(branch[1]);
  3676. if (i == last && block.length > 0) {
  3677. var node = block[block.length - 1];
  3678. if (node[0] == "break" && !node[1])
  3679. block.pop();
  3680. }
  3681. return [ branch[0] ? walk(branch[0]) : null, block ];
  3682. }) ];
  3683. },
  3684. "function": _lambda,
  3685. "defun": _lambda,
  3686. "block": function(body) {
  3687. if (body) return rmblock([ "block", tighten(body) ]);
  3688. },
  3689. "binary": function(op, left, right) {
  3690. return when_constant([ "binary", op, walk(left), walk(right) ], function yes(c){
  3691. return best_of(walk(c), this);
  3692. }, function no() {
  3693. return function(){
  3694. if(op != "==" && op != "!=") return;
  3695. var l = walk(left), r = walk(right);
  3696. if(l && l[0] == "unary-prefix" && l[1] == "!" && l[2][0] == "num")
  3697. left = ['num', +!l[2][1]];
  3698. else if (r && r[0] == "unary-prefix" && r[1] == "!" && r[2][0] == "num")
  3699. right = ['num', +!r[2][1]];
  3700. return ["binary", op, left, right];
  3701. }() || this;
  3702. });
  3703. },
  3704. "conditional": function(c, t, e) {
  3705. return make_conditional(walk(c), walk(t), walk(e));
  3706. },
  3707. "try": function(t, c, f) {
  3708. return [
  3709. "try",
  3710. tighten(t),
  3711. c != null ? [ c[0], tighten(c[1]) ] : null,
  3712. f != null ? tighten(f) : null
  3713. ];
  3714. },
  3715. "unary-prefix": function(op, expr) {
  3716. expr = walk(expr);
  3717. var ret = [ "unary-prefix", op, expr ];
  3718. if (op == "!")
  3719. ret = best_of(ret, negate(expr));
  3720. return when_constant(ret, function(ast, val){
  3721. return walk(ast); // it's either true or false, so minifies to !0 or !1
  3722. }, function() { return ret });
  3723. },
  3724. "name": function(name) {
  3725. switch (name) {
  3726. case "true": return [ "unary-prefix", "!", [ "num", 0 ]];
  3727. case "false": return [ "unary-prefix", "!", [ "num", 1 ]];
  3728. }
  3729. },
  3730. "while": _do_while,
  3731. "assign": function(op, lvalue, rvalue) {
  3732. lvalue = walk(lvalue);
  3733. rvalue = walk(rvalue);
  3734. var okOps = [ '+', '-', '/', '*', '%', '>>', '<<', '>>>', '|', '^', '&' ];
  3735. if (op === true && lvalue[0] === "name" && rvalue[0] === "binary" &&
  3736. ~okOps.indexOf(rvalue[1]) && rvalue[2][0] === "name" &&
  3737. rvalue[2][1] === lvalue[1]) {
  3738. return [ this[0], rvalue[1], lvalue, rvalue[3] ]
  3739. }
  3740. return [ this[0], op, lvalue, rvalue ];
  3741. },
  3742. "directive": function(dir) {
  3743. if (scope.active(dir))
  3744. return [ "block" ];
  3745. scope.directives.push(dir);
  3746. return [ this[0], dir ];
  3747. },
  3748. "call": function(expr, args) {
  3749. expr = walk(expr);
  3750. if (options.unsafe && expr[0] == "dot" && expr[1][0] == "string" && expr[2] == "toString") {
  3751. return expr[1];
  3752. }
  3753. return [ this[0], expr, MAP(args, walk) ];
  3754. },
  3755. "num": function (num) {
  3756. if (!isFinite(num))
  3757. return [ "binary", "/", num === 1 / 0
  3758. ? [ "num", 1 ] : num === -1 / 0
  3759. ? [ "unary-prefix", "-", [ "num", 1 ] ]
  3760. : [ "num", 0 ], [ "num", 0 ] ];
  3761. return [ this[0], num ];
  3762. }
  3763. }, function() {
  3764. for (var i = 0; i < 2; ++i) {
  3765. ast = prepare_ifs(ast);
  3766. ast = walk(ast_add_scope(ast));
  3767. }
  3768. return ast;
  3769. });
  3770. };
  3771. /* -----[ re-generate code from the AST ]----- */
  3772. var DOT_CALL_NO_PARENS = jsp.array_to_hash([
  3773. "name",
  3774. "array",
  3775. "object",
  3776. "string",
  3777. "dot",
  3778. "sub",
  3779. "call",
  3780. "regexp",
  3781. "defun"
  3782. ]);
  3783. function make_string(str, ascii_only) {
  3784. var dq = 0, sq = 0;
  3785. str = str.replace(/[\\\b\f\n\r\t\x22\x27\u2028\u2029\0]/g, function(s){
  3786. switch (s) {
  3787. case "\\": return "\\\\";
  3788. case "\b": return "\\b";
  3789. case "\f": return "\\f";
  3790. case "\n": return "\\n";
  3791. case "\r": return "\\r";
  3792. case "\u2028": return "\\u2028";
  3793. case "\u2029": return "\\u2029";
  3794. case '"': ++dq; return '"';
  3795. case "'": ++sq; return "'";
  3796. case "\0": return "\\0";
  3797. }
  3798. return s;
  3799. });
  3800. if (ascii_only) str = to_ascii(str);
  3801. if (dq > sq) return "'" + str.replace(/\x27/g, "\\'") + "'";
  3802. else return '"' + str.replace(/\x22/g, '\\"') + '"';
  3803. };
  3804. function to_ascii(str) {
  3805. return str.replace(/[\u0080-\uffff]/g, function(ch) {
  3806. var code = ch.charCodeAt(0).toString(16);
  3807. while (code.length < 4) code = "0" + code;
  3808. return "\\u" + code;
  3809. });
  3810. };
  3811. var SPLICE_NEEDS_BRACKETS = jsp.array_to_hash([ "if", "while", "do", "for", "for-in", "with" ]);
  3812. function gen_code(ast, options) {
  3813. options = defaults(options, {
  3814. indent_start : 0,
  3815. indent_level : 4,
  3816. quote_keys : false,
  3817. space_colon : false,
  3818. beautify : false,
  3819. ascii_only : false,
  3820. inline_script: false
  3821. });
  3822. var beautify = !!options.beautify;
  3823. var indentation = 0,
  3824. newline = beautify ? "\n" : "",
  3825. space = beautify ? " " : "";
  3826. function encode_string(str) {
  3827. var ret = make_string(str, options.ascii_only);
  3828. if (options.inline_script)
  3829. ret = ret.replace(/<\x2fscript([>\/\t\n\f\r ])/gi, "<\\/script$1");
  3830. return ret;
  3831. };
  3832. function make_name(name) {
  3833. name = name.toString();
  3834. if (options.ascii_only)
  3835. name = to_ascii(name);
  3836. return name;
  3837. };
  3838. function indent(line) {
  3839. if (line == null)
  3840. line = "";
  3841. if (beautify)
  3842. line = repeat_string(" ", options.indent_start + indentation * options.indent_level) + line;
  3843. return line;
  3844. };
  3845. function with_indent(cont, incr) {
  3846. if (incr == null) incr = 1;
  3847. indentation += incr;
  3848. try { return cont.apply(null, slice(arguments, 1)); }
  3849. finally { indentation -= incr; }
  3850. };
  3851. function last_char(str) {
  3852. str = str.toString();
  3853. return str.charAt(str.length - 1);
  3854. };
  3855. function first_char(str) {
  3856. return str.toString().charAt(0);
  3857. };
  3858. function add_spaces(a) {
  3859. if (beautify)
  3860. return a.join(" ");
  3861. var b = [];
  3862. for (var i = 0; i < a.length; ++i) {
  3863. var next = a[i + 1];
  3864. b.push(a[i]);
  3865. if (next &&
  3866. ((is_identifier_char(last_char(a[i])) && (is_identifier_char(first_char(next))
  3867. || first_char(next) == "\\")) ||
  3868. (/[\+\-]$/.test(a[i].toString()) && /^[\+\-]/.test(next.toString())))) {
  3869. b.push(" ");
  3870. }
  3871. }
  3872. return b.join("");
  3873. };
  3874. function add_commas(a) {
  3875. return a.join("," + space);
  3876. };
  3877. function parenthesize(expr) {
  3878. var gen = make(expr);
  3879. for (var i = 1; i < arguments.length; ++i) {
  3880. var el = arguments[i];
  3881. if ((el instanceof Function && el(expr)) || expr[0] == el)
  3882. return "(" + gen + ")";
  3883. }
  3884. return gen;
  3885. };
  3886. function best_of(a) {
  3887. if (a.length == 1) {
  3888. return a[0];
  3889. }
  3890. if (a.length == 2) {
  3891. var b = a[1];
  3892. a = a[0];
  3893. return a.length <= b.length ? a : b;
  3894. }
  3895. return best_of([ a[0], best_of(a.slice(1)) ]);
  3896. };
  3897. function needs_parens(expr) {
  3898. if (expr[0] == "function" || expr[0] == "object") {
  3899. // dot/call on a literal function requires the
  3900. // function literal itself to be parenthesized
  3901. // only if it's the first "thing" in a
  3902. // statement. This means that the parent is
  3903. // "stat", but it could also be a "seq" and
  3904. // we're the first in this "seq" and the
  3905. // parent is "stat", and so on. Messy stuff,
  3906. // but it worths the trouble.
  3907. var a = slice(w.stack()), self = a.pop(), p = a.pop();
  3908. while (p) {
  3909. if (p[0] == "stat") return true;
  3910. if (((p[0] == "seq" || p[0] == "call" || p[0] == "dot" || p[0] == "sub" || p[0] == "conditional") && p[1] === self) ||
  3911. ((p[0] == "binary" || p[0] == "assign" || p[0] == "unary-postfix") && p[2] === self)) {
  3912. self = p;
  3913. p = a.pop();
  3914. } else {
  3915. return false;
  3916. }
  3917. }
  3918. }
  3919. return !HOP(DOT_CALL_NO_PARENS, expr[0]);
  3920. };
  3921. function make_num(num) {
  3922. var str = num.toString(10), a = [ str.replace(/^0\./, ".").replace('e+', 'e') ], m;
  3923. if (Math.floor(num) === num) {
  3924. if (num >= 0) {
  3925. a.push("0x" + num.toString(16).toLowerCase(), // probably pointless
  3926. "0" + num.toString(8)); // same.
  3927. } else {
  3928. a.push("-0x" + (-num).toString(16).toLowerCase(), // probably pointless
  3929. "-0" + (-num).toString(8)); // same.
  3930. }
  3931. if ((m = /^(.*?)(0+)$/.exec(num))) {
  3932. a.push(m[1] + "e" + m[2].length);
  3933. }
  3934. } else if ((m = /^0?\.(0+)(.*)$/.exec(num))) {
  3935. a.push(m[2] + "e-" + (m[1].length + m[2].length),
  3936. str.substr(str.indexOf(".")));
  3937. }
  3938. return best_of(a);
  3939. };
  3940. var w = ast_walker();
  3941. var make = w.walk;
  3942. return w.with_walkers({
  3943. "string": encode_string,
  3944. "num": make_num,
  3945. "name": make_name,
  3946. "debugger": function(){ return "debugger;" },
  3947. "toplevel": function(statements) {
  3948. return make_block_statements(statements)
  3949. .join(newline + newline);
  3950. },
  3951. "splice": function(statements) {
  3952. var parent = w.parent();
  3953. if (HOP(SPLICE_NEEDS_BRACKETS, parent)) {
  3954. // we need block brackets in this case
  3955. return make_block.apply(this, arguments);
  3956. } else {
  3957. return MAP(make_block_statements(statements, true),
  3958. function(line, i) {
  3959. // the first line is already indented
  3960. return i > 0 ? indent(line) : line;
  3961. }).join(newline);
  3962. }
  3963. },
  3964. "block": make_block,
  3965. "var": function(defs) {
  3966. return "var " + add_commas(MAP(defs, make_1vardef)) + ";";
  3967. },
  3968. "const": function(defs) {
  3969. return "const " + add_commas(MAP(defs, make_1vardef)) + ";";
  3970. },
  3971. "try": function(tr, ca, fi) {
  3972. var out = [ "try", make_block(tr) ];
  3973. if (ca) out.push("catch", "(" + ca[0] + ")", make_block(ca[1]));
  3974. if (fi) out.push("finally", make_block(fi));
  3975. return add_spaces(out);
  3976. },
  3977. "throw": function(expr) {
  3978. return add_spaces([ "throw", make(expr) ]) + ";";
  3979. },
  3980. "new": function(ctor, args) {
  3981. args = args.length > 0 ? "(" + add_commas(MAP(args, function(expr){
  3982. return parenthesize(expr, "seq");
  3983. })) + ")" : "";
  3984. return add_spaces([ "new", parenthesize(ctor, "seq", "binary", "conditional", "assign", function(expr){
  3985. var w = ast_walker(), has_call = {};
  3986. try {
  3987. w.with_walkers({
  3988. "call": function() { throw has_call },
  3989. "function": function() { return this }
  3990. }, function(){
  3991. w.walk(expr);
  3992. });
  3993. } catch(ex) {
  3994. if (ex === has_call)
  3995. return true;
  3996. throw ex;
  3997. }
  3998. }) + args ]);
  3999. },
  4000. "switch": function(expr, body) {
  4001. return add_spaces([ "switch", "(" + make(expr) + ")", make_switch_block(body) ]);
  4002. },
  4003. "break": function(label) {
  4004. var out = "break";
  4005. if (label != null)
  4006. out += " " + make_name(label);
  4007. return out + ";";
  4008. },
  4009. "continue": function(label) {
  4010. var out = "continue";
  4011. if (label != null)
  4012. out += " " + make_name(label);
  4013. return out + ";";
  4014. },
  4015. "conditional": function(co, th, el) {
  4016. return add_spaces([ parenthesize(co, "assign", "seq", "conditional"), "?",
  4017. parenthesize(th, "seq"), ":",
  4018. parenthesize(el, "seq") ]);
  4019. },
  4020. "assign": function(op, lvalue, rvalue) {
  4021. if (op && op !== true) op += "=";
  4022. else op = "=";
  4023. return add_spaces([ make(lvalue), op, parenthesize(rvalue, "seq") ]);
  4024. },
  4025. "dot": function(expr) {
  4026. var out = make(expr), i = 1;
  4027. if (expr[0] == "num") {
  4028. if (!/[a-f.]/i.test(out))
  4029. out += ".";
  4030. } else if (expr[0] != "function" && needs_parens(expr))
  4031. out = "(" + out + ")";
  4032. while (i < arguments.length)
  4033. out += "." + make_name(arguments[i++]);
  4034. return out;
  4035. },
  4036. "call": function(func, args) {
  4037. var f = make(func);
  4038. if (f.charAt(0) != "(" && needs_parens(func))
  4039. f = "(" + f + ")";
  4040. return f + "(" + add_commas(MAP(args, function(expr){
  4041. return parenthesize(expr, "seq");
  4042. })) + ")";
  4043. },
  4044. "function": make_function,
  4045. "defun": make_function,
  4046. "if": function(co, th, el) {
  4047. var out = [ "if", "(" + make(co) + ")", el ? make_then(th) : make(th) ];
  4048. if (el) {
  4049. out.push("else", make(el));
  4050. }
  4051. return add_spaces(out);
  4052. },
  4053. "for": function(init, cond, step, block) {
  4054. var out = [ "for" ];
  4055. init = (init != null ? make(init) : "").replace(/;*\s*$/, ";" + space);
  4056. cond = (cond != null ? make(cond) : "").replace(/;*\s*$/, ";" + space);
  4057. step = (step != null ? make(step) : "").replace(/;*\s*$/, "");
  4058. var args = init + cond + step;
  4059. if (args == "; ; ") args = ";;";
  4060. out.push("(" + args + ")", make(block));
  4061. return add_spaces(out);
  4062. },
  4063. "for-in": function(vvar, key, hash, block) {
  4064. return add_spaces([ "for", "(" +
  4065. (vvar ? make(vvar).replace(/;+$/, "") : make(key)),
  4066. "in",
  4067. make(hash) + ")", make(block) ]);
  4068. },
  4069. "while": function(condition, block) {
  4070. return add_spaces([ "while", "(" + make(condition) + ")", make(block) ]);
  4071. },
  4072. "do": function(condition, block) {
  4073. return add_spaces([ "do", make(block), "while", "(" + make(condition) + ")" ]) + ";";
  4074. },
  4075. "return": function(expr) {
  4076. var out = [ "return" ];
  4077. if (expr != null) out.push(make(expr));
  4078. return add_spaces(out) + ";";
  4079. },
  4080. "binary": function(operator, lvalue, rvalue) {
  4081. var left = make(lvalue), right = make(rvalue);
  4082. // XXX: I'm pretty sure other cases will bite here.
  4083. // we need to be smarter.
  4084. // adding parens all the time is the safest bet.
  4085. if (member(lvalue[0], [ "assign", "conditional", "seq" ]) ||
  4086. lvalue[0] == "binary" && PRECEDENCE[operator] > PRECEDENCE[lvalue[1]] ||
  4087. lvalue[0] == "function" && needs_parens(this)) {
  4088. left = "(" + left + ")";
  4089. }
  4090. if (member(rvalue[0], [ "assign", "conditional", "seq" ]) ||
  4091. rvalue[0] == "binary" && PRECEDENCE[operator] >= PRECEDENCE[rvalue[1]] &&
  4092. !(rvalue[1] == operator && member(operator, [ "&&", "||", "*" ]))) {
  4093. right = "(" + right + ")";
  4094. }
  4095. else if (!beautify && options.inline_script && (operator == "<" || operator == "<<")
  4096. && rvalue[0] == "regexp" && /^script/i.test(rvalue[1])) {
  4097. right = " " + right;
  4098. }
  4099. return add_spaces([ left, operator, right ]);
  4100. },
  4101. "unary-prefix": function(operator, expr) {
  4102. var val = make(expr);
  4103. if (!(expr[0] == "num" || (expr[0] == "unary-prefix" && !HOP(OPERATORS, operator + expr[1])) || !needs_parens(expr)))
  4104. val = "(" + val + ")";
  4105. return operator + (jsp.is_alphanumeric_char(operator.charAt(0)) ? " " : "") + val;
  4106. },
  4107. "unary-postfix": function(operator, expr) {
  4108. var val = make(expr);
  4109. if (!(expr[0] == "num" || (expr[0] == "unary-postfix" && !HOP(OPERATORS, operator + expr[1])) || !needs_parens(expr)))
  4110. val = "(" + val + ")";
  4111. return val + operator;
  4112. },
  4113. "sub": function(expr, subscript) {
  4114. var hash = make(expr);
  4115. if (needs_parens(expr))
  4116. hash = "(" + hash + ")";
  4117. return hash + "[" + make(subscript) + "]";
  4118. },
  4119. "object": function(props) {
  4120. var obj_needs_parens = needs_parens(this);
  4121. if (props.length == 0)
  4122. return obj_needs_parens ? "({})" : "{}";
  4123. var out = "{" + newline + with_indent(function(){
  4124. return MAP(props, function(p){
  4125. if (p.length == 3) {
  4126. // getter/setter. The name is in p[0], the arg.list in p[1][2], the
  4127. // body in p[1][3] and type ("get" / "set") in p[2].
  4128. return indent(make_function(p[0], p[1][2], p[1][3], p[2], true));
  4129. }
  4130. var key = p[0], val = parenthesize(p[1], "seq");
  4131. if (options.quote_keys) {
  4132. key = encode_string(key);
  4133. } else if ((typeof key == "number" || !beautify && +key + "" == key)
  4134. && parseFloat(key) >= 0) {
  4135. key = make_num(+key);
  4136. } else if (!is_identifier(key)) {
  4137. key = encode_string(key);
  4138. }
  4139. return indent(add_spaces(beautify && options.space_colon
  4140. ? [ key, ":", val ]
  4141. : [ key + ":", val ]));
  4142. }).join("," + newline);
  4143. }) + newline + indent("}");
  4144. return obj_needs_parens ? "(" + out + ")" : out;
  4145. },
  4146. "regexp": function(rx, mods) {
  4147. if (options.ascii_only) rx = to_ascii(rx);
  4148. return "/" + rx + "/" + mods;
  4149. },
  4150. "array": function(elements) {
  4151. if (elements.length == 0) return "[]";
  4152. return add_spaces([ "[", add_commas(MAP(elements, function(el, i){
  4153. if (!beautify && el[0] == "atom" && el[1] == "undefined") return i === elements.length - 1 ? "," : "";
  4154. return parenthesize(el, "seq");
  4155. })), "]" ]);
  4156. },
  4157. "stat": function(stmt) {
  4158. return make(stmt).replace(/;*\s*$/, ";");
  4159. },
  4160. "seq": function() {
  4161. return add_commas(MAP(slice(arguments), make));
  4162. },
  4163. "label": function(name, block) {
  4164. return add_spaces([ make_name(name), ":", make(block) ]);
  4165. },
  4166. "with": function(expr, block) {
  4167. return add_spaces([ "with", "(" + make(expr) + ")", make(block) ]);
  4168. },
  4169. "atom": function(name) {
  4170. return make_name(name);
  4171. },
  4172. "directive": function(dir) {
  4173. return make_string(dir) + ";";
  4174. }
  4175. }, function(){ return make(ast) });
  4176. // The squeezer replaces "block"-s that contain only a single
  4177. // statement with the statement itself; technically, the AST
  4178. // is correct, but this can create problems when we output an
  4179. // IF having an ELSE clause where the THEN clause ends in an
  4180. // IF *without* an ELSE block (then the outer ELSE would refer
  4181. // to the inner IF). This function checks for this case and
  4182. // adds the block brackets if needed.
  4183. function make_then(th) {
  4184. if (th == null) return ";";
  4185. if (th[0] == "do") {
  4186. // https://github.com/mishoo/UglifyJS/issues/#issue/57
  4187. // IE croaks with "syntax error" on code like this:
  4188. // if (foo) do ... while(cond); else ...
  4189. // we need block brackets around do/while
  4190. return make_block([ th ]);
  4191. }
  4192. var b = th;
  4193. while (true) {
  4194. var type = b[0];
  4195. if (type == "if") {
  4196. if (!b[3])
  4197. // no else, we must add the block
  4198. return make([ "block", [ th ]]);
  4199. b = b[3];
  4200. }
  4201. else if (type == "while" || type == "do") b = b[2];
  4202. else if (type == "for" || type == "for-in") b = b[4];
  4203. else break;
  4204. }
  4205. return make(th);
  4206. };
  4207. function make_function(name, args, body, keyword, no_parens) {
  4208. var out = keyword || "function";
  4209. if (name) {
  4210. out += " " + make_name(name);
  4211. }
  4212. out += "(" + add_commas(MAP(args, make_name)) + ")";
  4213. out = add_spaces([ out, make_block(body) ]);
  4214. return (!no_parens && needs_parens(this)) ? "(" + out + ")" : out;
  4215. };
  4216. function must_has_semicolon(node) {
  4217. switch (node[0]) {
  4218. case "with":
  4219. case "while":
  4220. return empty(node[2]) || must_has_semicolon(node[2]);
  4221. case "for":
  4222. case "for-in":
  4223. return empty(node[4]) || must_has_semicolon(node[4]);
  4224. case "if":
  4225. if (empty(node[2]) && !node[3]) return true; // `if' with empty `then' and no `else'
  4226. if (node[3]) {
  4227. if (empty(node[3])) return true; // `else' present but empty
  4228. return must_has_semicolon(node[3]); // dive into the `else' branch
  4229. }
  4230. return must_has_semicolon(node[2]); // dive into the `then' branch
  4231. case "directive":
  4232. return true;
  4233. }
  4234. };
  4235. function make_block_statements(statements, noindent) {
  4236. for (var a = [], last = statements.length - 1, i = 0; i <= last; ++i) {
  4237. var stat = statements[i];
  4238. var code = make(stat);
  4239. if (code != ";") {
  4240. if (!beautify && i == last && !must_has_semicolon(stat)) {
  4241. code = code.replace(/;+\s*$/, "");
  4242. }
  4243. a.push(code);
  4244. }
  4245. }
  4246. return noindent ? a : MAP(a, indent);
  4247. };
  4248. function make_switch_block(body) {
  4249. var n = body.length;
  4250. if (n == 0) return "{}";
  4251. return "{" + newline + MAP(body, function(branch, i){
  4252. var has_body = branch[1].length > 0, code = with_indent(function(){
  4253. return indent(branch[0]
  4254. ? add_spaces([ "case", make(branch[0]) + ":" ])
  4255. : "default:");
  4256. }, 0.5) + (has_body ? newline + with_indent(function(){
  4257. return make_block_statements(branch[1]).join(newline);
  4258. }) : "");
  4259. if (!beautify && has_body && i < n - 1)
  4260. code += ";";
  4261. return code;
  4262. }).join(newline) + newline + indent("}");
  4263. };
  4264. function make_block(statements) {
  4265. if (!statements) return ";";
  4266. if (statements.length == 0) return "{}";
  4267. return "{" + newline + with_indent(function(){
  4268. return make_block_statements(statements).join(newline);
  4269. }) + newline + indent("}");
  4270. };
  4271. function make_1vardef(def) {
  4272. var name = def[0], val = def[1];
  4273. if (val != null)
  4274. name = add_spaces([ make_name(name), "=", parenthesize(val, "seq") ]);
  4275. return name;
  4276. };
  4277. };
  4278. function split_lines(code, max_line_length) {
  4279. var splits = [ 0 ];
  4280. jsp.parse(function(){
  4281. var next_token = jsp.tokenizer(code);
  4282. var last_split = 0;
  4283. var prev_token;
  4284. function current_length(tok) {
  4285. return tok.pos - last_split;
  4286. };
  4287. function split_here(tok) {
  4288. last_split = tok.pos;
  4289. splits.push(last_split);
  4290. };
  4291. function custom(){
  4292. var tok = next_token.apply(this, arguments);
  4293. out: {
  4294. if (prev_token) {
  4295. if (prev_token.type == "keyword") break out;
  4296. }
  4297. if (current_length(tok) > max_line_length) {
  4298. switch (tok.type) {
  4299. case "keyword":
  4300. case "atom":
  4301. case "name":
  4302. case "punc":
  4303. split_here(tok);
  4304. break out;
  4305. }
  4306. }
  4307. }
  4308. prev_token = tok;
  4309. return tok;
  4310. };
  4311. custom.context = function() {
  4312. return next_token.context.apply(this, arguments);
  4313. };
  4314. return custom;
  4315. }());
  4316. return splits.map(function(pos, i){
  4317. return code.substring(pos, splits[i + 1] || code.length);
  4318. }).join("\n");
  4319. };
  4320. /* -----[ Utilities ]----- */
  4321. function repeat_string(str, i) {
  4322. if (i <= 0) return "";
  4323. if (i == 1) return str;
  4324. var d = repeat_string(str, i >> 1);
  4325. d += d;
  4326. if (i & 1) d += str;
  4327. return d;
  4328. };
  4329. function defaults(args, defs) {
  4330. var ret = {};
  4331. if (args === true)
  4332. args = {};
  4333. for (var i in defs) if (HOP(defs, i)) {
  4334. ret[i] = (args && HOP(args, i)) ? args[i] : defs[i];
  4335. }
  4336. return ret;
  4337. };
  4338. function is_identifier(name) {
  4339. return /^[a-z_$][a-z0-9_$]*$/i.test(name)
  4340. && name != "this"
  4341. && !HOP(jsp.KEYWORDS_ATOM, name)
  4342. && !HOP(jsp.RESERVED_WORDS, name)
  4343. && !HOP(jsp.KEYWORDS, name);
  4344. };
  4345. function HOP(obj, prop) {
  4346. return Object.prototype.hasOwnProperty.call(obj, prop);
  4347. };
  4348. // some utilities
  4349. var MAP;
  4350. (function(){
  4351. MAP = function(a, f, o) {
  4352. var ret = [], top = [], i;
  4353. function doit() {
  4354. var val = f.call(o, a[i], i);
  4355. if (val instanceof AtTop) {
  4356. val = val.v;
  4357. if (val instanceof Splice) {
  4358. top.push.apply(top, val.v);
  4359. } else {
  4360. top.push(val);
  4361. }
  4362. }
  4363. else if (val != skip) {
  4364. if (val instanceof Splice) {
  4365. ret.push.apply(ret, val.v);
  4366. } else {
  4367. ret.push(val);
  4368. }
  4369. }
  4370. };
  4371. if (a instanceof Array) for (i = 0; i < a.length; ++i) doit();
  4372. else for (i in a) if (HOP(a, i)) doit();
  4373. return top.concat(ret);
  4374. };
  4375. MAP.at_top = function(val) { return new AtTop(val) };
  4376. MAP.splice = function(val) { return new Splice(val) };
  4377. var skip = MAP.skip = {};
  4378. function AtTop(val) { this.v = val };
  4379. function Splice(val) { this.v = val };
  4380. })();
  4381. /* -----[ Exports ]----- */
  4382. exports.ast_walker = ast_walker;
  4383. exports.ast_mangle = ast_mangle;
  4384. exports.ast_squeeze = ast_squeeze;
  4385. exports.ast_lift_variables = ast_lift_variables;
  4386. exports.gen_code = gen_code;
  4387. exports.ast_add_scope = ast_add_scope;
  4388. exports.set_logger = function(logger) { warn = logger };
  4389. exports.make_string = make_string;
  4390. exports.split_lines = split_lines;
  4391. exports.MAP = MAP;
  4392. // keep this last!
  4393. exports.ast_squeeze_more = require("./squeeze-more").ast_squeeze_more;
  4394. }, "squeeze-more": function(exports, require, module) {var jsp = require("./parse-js"),
  4395. pro = require("./process"),
  4396. slice = jsp.slice,
  4397. member = jsp.member,
  4398. curry = jsp.curry,
  4399. MAP = pro.MAP,
  4400. PRECEDENCE = jsp.PRECEDENCE,
  4401. OPERATORS = jsp.OPERATORS;
  4402. function ast_squeeze_more(ast) {
  4403. var w = pro.ast_walker(), walk = w.walk, scope;
  4404. function with_scope(s, cont) {
  4405. var save = scope, ret;
  4406. scope = s;
  4407. ret = cont();
  4408. scope = save;
  4409. return ret;
  4410. };
  4411. function _lambda(name, args, body) {
  4412. return [ this[0], name, args, with_scope(body.scope, curry(MAP, body, walk)) ];
  4413. };
  4414. return w.with_walkers({
  4415. "toplevel": function(body) {
  4416. return [ this[0], with_scope(this.scope, curry(MAP, body, walk)) ];
  4417. },
  4418. "function": _lambda,
  4419. "defun": _lambda,
  4420. "new": function(ctor, args) {
  4421. if (ctor[0] == "name") {
  4422. if (ctor[1] == "Array" && !scope.has("Array")) {
  4423. if (args.length != 1) {
  4424. return [ "array", args ];
  4425. } else {
  4426. return walk([ "call", [ "name", "Array" ], args ]);
  4427. }
  4428. } else if (ctor[1] == "Object" && !scope.has("Object")) {
  4429. if (!args.length) {
  4430. return [ "object", [] ];
  4431. } else {
  4432. return walk([ "call", [ "name", "Object" ], args ]);
  4433. }
  4434. } else if ((ctor[1] == "RegExp" || ctor[1] == "Function" || ctor[1] == "Error") && !scope.has(ctor[1])) {
  4435. return walk([ "call", [ "name", ctor[1] ], args]);
  4436. }
  4437. }
  4438. },
  4439. "call": function(expr, args) {
  4440. if (expr[0] == "dot" && expr[1][0] == "string" && args.length == 1
  4441. && (args[0][1] > 0 && expr[2] == "substring" || expr[2] == "substr")) {
  4442. return [ "call", [ "dot", expr[1], "slice"], args];
  4443. }
  4444. if (expr[0] == "dot" && expr[2] == "toString" && args.length == 0) {
  4445. // foo.toString() ==> foo+""
  4446. if (expr[1][0] == "string") return expr[1];
  4447. return [ "binary", "+", expr[1], [ "string", "" ]];
  4448. }
  4449. if (expr[0] == "name") {
  4450. if (expr[1] == "Array" && args.length != 1 && !scope.has("Array")) {
  4451. return [ "array", args ];
  4452. }
  4453. if (expr[1] == "Object" && !args.length && !scope.has("Object")) {
  4454. return [ "object", [] ];
  4455. }
  4456. if (expr[1] == "String" && !scope.has("String")) {
  4457. return [ "binary", "+", args[0], [ "string", "" ]];
  4458. }
  4459. }
  4460. }
  4461. }, function() {
  4462. return walk(pro.ast_add_scope(ast));
  4463. });
  4464. };
  4465. exports.ast_squeeze_more = ast_squeeze_more;
  4466. }});
  4467. ;
  4468. global.UglifyJS = {};
  4469. global.UglifyJS.parser = this.require('parse-js');
  4470. global.UglifyJS.uglify = this.require('process');
  4471. }).call({}, this);