index.js 172 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667
  1. /***********************************************************************
  2. A JavaScript tokenizer / parser / beautifier / compressor.
  3. https://github.com/mishoo/UglifyJS2
  4. -------------------------------- (C) ---------------------------------
  5. Author: Mihai Bazon
  6. <mihai.bazon@gmail.com>
  7. http://mihai.bazon.net/blog
  8. Distributed under the BSD license:
  9. Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com>
  10. Redistribution and use in source and binary forms, with or without
  11. modification, are permitted provided that the following conditions
  12. are met:
  13. * Redistributions of source code must retain the above
  14. copyright notice, this list of conditions and the following
  15. disclaimer.
  16. * Redistributions in binary form must reproduce the above
  17. copyright notice, this list of conditions and the following
  18. disclaimer in the documentation and/or other materials
  19. provided with the distribution.
  20. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
  21. EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  22. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  23. PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
  24. LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
  25. OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  26. PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  27. PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  28. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
  29. TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
  30. THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  31. SUCH DAMAGE.
  32. ***********************************************************************/
  33. import {
  34. AST_Accessor,
  35. AST_Array,
  36. AST_Arrow,
  37. AST_Assign,
  38. AST_BigInt,
  39. AST_Binary,
  40. AST_Block,
  41. AST_BlockStatement,
  42. AST_Boolean,
  43. AST_Break,
  44. AST_Call,
  45. AST_Catch,
  46. AST_Chain,
  47. AST_Class,
  48. AST_ClassExpression,
  49. AST_ClassProperty,
  50. AST_ConciseMethod,
  51. AST_Conditional,
  52. AST_Const,
  53. AST_Constant,
  54. AST_Debugger,
  55. AST_Default,
  56. AST_DefaultAssign,
  57. AST_DefClass,
  58. AST_Definitions,
  59. AST_Defun,
  60. AST_Destructuring,
  61. AST_Directive,
  62. AST_Do,
  63. AST_Dot,
  64. AST_DWLoop,
  65. AST_EmptyStatement,
  66. AST_Exit,
  67. AST_Expansion,
  68. AST_Export,
  69. AST_False,
  70. AST_For,
  71. AST_ForIn,
  72. AST_Function,
  73. AST_Hole,
  74. AST_If,
  75. AST_Import,
  76. AST_Infinity,
  77. AST_IterationStatement,
  78. AST_LabeledStatement,
  79. AST_Lambda,
  80. AST_Let,
  81. AST_NaN,
  82. AST_New,
  83. AST_Node,
  84. AST_Null,
  85. AST_Number,
  86. AST_Object,
  87. AST_ObjectKeyVal,
  88. AST_ObjectProperty,
  89. AST_PrefixedTemplateString,
  90. AST_PropAccess,
  91. AST_RegExp,
  92. AST_Return,
  93. AST_Scope,
  94. AST_Sequence,
  95. AST_SimpleStatement,
  96. AST_Statement,
  97. AST_String,
  98. AST_Sub,
  99. AST_Switch,
  100. AST_SwitchBranch,
  101. AST_Symbol,
  102. AST_SymbolBlockDeclaration,
  103. AST_SymbolCatch,
  104. AST_SymbolClassProperty,
  105. AST_SymbolDeclaration,
  106. AST_SymbolDefun,
  107. AST_SymbolExport,
  108. AST_SymbolFunarg,
  109. AST_SymbolLambda,
  110. AST_SymbolLet,
  111. AST_SymbolMethod,
  112. AST_SymbolRef,
  113. AST_SymbolVar,
  114. AST_TemplateString,
  115. AST_This,
  116. AST_Toplevel,
  117. AST_True,
  118. AST_Try,
  119. AST_Unary,
  120. AST_UnaryPostfix,
  121. AST_UnaryPrefix,
  122. AST_Undefined,
  123. AST_Var,
  124. AST_VarDef,
  125. AST_While,
  126. AST_With,
  127. AST_Yield,
  128. TreeTransformer,
  129. TreeWalker,
  130. walk,
  131. walk_abort,
  132. walk_parent,
  133. _INLINE,
  134. _NOINLINE,
  135. _PURE
  136. } from "../ast.js";
  137. import {
  138. defaults,
  139. HOP,
  140. keep_name,
  141. make_node,
  142. makePredicate,
  143. map_add,
  144. MAP,
  145. member,
  146. remove,
  147. return_false,
  148. return_true,
  149. regexp_source_fix,
  150. has_annotation
  151. } from "../utils/index.js";
  152. import { first_in_statement } from "../utils/first_in_statement.js";
  153. import { equivalent_to } from "../equivalent-to.js";
  154. import {
  155. is_basic_identifier_string,
  156. JS_Parse_Error,
  157. parse,
  158. PRECEDENCE,
  159. } from "../parse.js";
  160. import { OutputStream } from "../output.js";
  161. import {
  162. base54,
  163. SymbolDef,
  164. } from "../scope.js";
  165. import "../size.js";
  166. import "./evaluate.js";
  167. import "./drop-side-effect-free.js";
  168. import "./reduce-vars.js";
  169. import {
  170. is_undeclared_ref,
  171. lazy_op,
  172. is_nullish,
  173. is_undefined,
  174. is_lhs,
  175. aborts,
  176. } from "./inference.js";
  177. import {
  178. SQUEEZED,
  179. OPTIMIZED,
  180. INLINED,
  181. CLEAR_BETWEEN_PASSES,
  182. TOP,
  183. WRITE_ONLY,
  184. UNDEFINED,
  185. UNUSED,
  186. TRUTHY,
  187. FALSY,
  188. has_flag,
  189. set_flag,
  190. clear_flag,
  191. } from "./compressor-flags.js";
  192. import {
  193. make_sequence,
  194. best_of,
  195. best_of_expression,
  196. make_node_from_constant,
  197. merge_sequence,
  198. get_simple_key,
  199. has_break_or_continue,
  200. maintain_this_binding,
  201. identifier_atom,
  202. is_identifier_atom,
  203. is_func_expr,
  204. is_ref_of,
  205. can_be_evicted_from_block,
  206. as_statement_array,
  207. is_iife_call,
  208. is_recursive_ref
  209. } from "./common.js";
  210. import { tighten_body, trim_unreachable_code } from "./tighten-body.js";
  211. class Compressor extends TreeWalker {
  212. constructor(options, { false_by_default = false, mangle_options = false }) {
  213. super();
  214. if (options.defaults !== undefined && !options.defaults) false_by_default = true;
  215. this.options = defaults(options, {
  216. arguments : false,
  217. arrows : !false_by_default,
  218. booleans : !false_by_default,
  219. booleans_as_integers : false,
  220. collapse_vars : !false_by_default,
  221. comparisons : !false_by_default,
  222. computed_props: !false_by_default,
  223. conditionals : !false_by_default,
  224. dead_code : !false_by_default,
  225. defaults : true,
  226. directives : !false_by_default,
  227. drop_console : false,
  228. drop_debugger : !false_by_default,
  229. ecma : 5,
  230. evaluate : !false_by_default,
  231. expression : false,
  232. global_defs : false,
  233. hoist_funs : false,
  234. hoist_props : !false_by_default,
  235. hoist_vars : false,
  236. ie8 : false,
  237. if_return : !false_by_default,
  238. inline : !false_by_default,
  239. join_vars : !false_by_default,
  240. keep_classnames: false,
  241. keep_fargs : true,
  242. keep_fnames : false,
  243. keep_infinity : false,
  244. loops : !false_by_default,
  245. module : false,
  246. negate_iife : !false_by_default,
  247. passes : 1,
  248. properties : !false_by_default,
  249. pure_getters : !false_by_default && "strict",
  250. pure_funcs : null,
  251. reduce_funcs : !false_by_default,
  252. reduce_vars : !false_by_default,
  253. sequences : !false_by_default,
  254. side_effects : !false_by_default,
  255. switches : !false_by_default,
  256. top_retain : null,
  257. toplevel : !!(options && options["top_retain"]),
  258. typeofs : !false_by_default,
  259. unsafe : false,
  260. unsafe_arrows : false,
  261. unsafe_comps : false,
  262. unsafe_Function: false,
  263. unsafe_math : false,
  264. unsafe_symbols: false,
  265. unsafe_methods: false,
  266. unsafe_proto : false,
  267. unsafe_regexp : false,
  268. unsafe_undefined: false,
  269. unused : !false_by_default,
  270. warnings : false // legacy
  271. }, true);
  272. var global_defs = this.options["global_defs"];
  273. if (typeof global_defs == "object") for (var key in global_defs) {
  274. if (key[0] === "@" && HOP(global_defs, key)) {
  275. global_defs[key.slice(1)] = parse(global_defs[key], {
  276. expression: true
  277. });
  278. }
  279. }
  280. if (this.options["inline"] === true) this.options["inline"] = 3;
  281. var pure_funcs = this.options["pure_funcs"];
  282. if (typeof pure_funcs == "function") {
  283. this.pure_funcs = pure_funcs;
  284. } else {
  285. this.pure_funcs = pure_funcs ? function(node) {
  286. return !pure_funcs.includes(node.expression.print_to_string());
  287. } : return_true;
  288. }
  289. var top_retain = this.options["top_retain"];
  290. if (top_retain instanceof RegExp) {
  291. this.top_retain = function(def) {
  292. return top_retain.test(def.name);
  293. };
  294. } else if (typeof top_retain == "function") {
  295. this.top_retain = top_retain;
  296. } else if (top_retain) {
  297. if (typeof top_retain == "string") {
  298. top_retain = top_retain.split(/,/);
  299. }
  300. this.top_retain = function(def) {
  301. return top_retain.includes(def.name);
  302. };
  303. }
  304. if (this.options["module"]) {
  305. this.directives["use strict"] = true;
  306. this.options["toplevel"] = true;
  307. }
  308. var toplevel = this.options["toplevel"];
  309. this.toplevel = typeof toplevel == "string" ? {
  310. funcs: /funcs/.test(toplevel),
  311. vars: /vars/.test(toplevel)
  312. } : {
  313. funcs: toplevel,
  314. vars: toplevel
  315. };
  316. var sequences = this.options["sequences"];
  317. this.sequences_limit = sequences == 1 ? 800 : sequences | 0;
  318. this.evaluated_regexps = new Map();
  319. this._toplevel = undefined;
  320. this.mangle_options = mangle_options;
  321. }
  322. option(key) {
  323. return this.options[key];
  324. }
  325. exposed(def) {
  326. if (def.export) return true;
  327. if (def.global) for (var i = 0, len = def.orig.length; i < len; i++)
  328. if (!this.toplevel[def.orig[i] instanceof AST_SymbolDefun ? "funcs" : "vars"])
  329. return true;
  330. return false;
  331. }
  332. in_boolean_context() {
  333. if (!this.option("booleans")) return false;
  334. var self = this.self();
  335. for (var i = 0, p; p = this.parent(i); i++) {
  336. if (p instanceof AST_SimpleStatement
  337. || p instanceof AST_Conditional && p.condition === self
  338. || p instanceof AST_DWLoop && p.condition === self
  339. || p instanceof AST_For && p.condition === self
  340. || p instanceof AST_If && p.condition === self
  341. || p instanceof AST_UnaryPrefix && p.operator == "!" && p.expression === self) {
  342. return true;
  343. }
  344. if (
  345. p instanceof AST_Binary
  346. && (
  347. p.operator == "&&"
  348. || p.operator == "||"
  349. || p.operator == "??"
  350. )
  351. || p instanceof AST_Conditional
  352. || p.tail_node() === self
  353. ) {
  354. self = p;
  355. } else {
  356. return false;
  357. }
  358. }
  359. }
  360. get_toplevel() {
  361. return this._toplevel;
  362. }
  363. compress(toplevel) {
  364. toplevel = toplevel.resolve_defines(this);
  365. this._toplevel = toplevel;
  366. if (this.option("expression")) {
  367. this._toplevel.process_expression(true);
  368. }
  369. var passes = +this.options.passes || 1;
  370. var min_count = 1 / 0;
  371. var stopping = false;
  372. var nth_identifier = this.mangle_options && this.mangle_options.nth_identifier || base54;
  373. var mangle = { ie8: this.option("ie8"), nth_identifier: nth_identifier };
  374. for (var pass = 0; pass < passes; pass++) {
  375. this._toplevel.figure_out_scope(mangle);
  376. if (pass === 0 && this.option("drop_console")) {
  377. // must be run before reduce_vars and compress pass
  378. this._toplevel = this._toplevel.drop_console();
  379. }
  380. if (pass > 0 || this.option("reduce_vars")) {
  381. this._toplevel.reset_opt_flags(this);
  382. }
  383. this._toplevel = this._toplevel.transform(this);
  384. if (passes > 1) {
  385. let count = 0;
  386. walk(this._toplevel, () => { count++; });
  387. if (count < min_count) {
  388. min_count = count;
  389. stopping = false;
  390. } else if (stopping) {
  391. break;
  392. } else {
  393. stopping = true;
  394. }
  395. }
  396. }
  397. if (this.option("expression")) {
  398. this._toplevel.process_expression(false);
  399. }
  400. toplevel = this._toplevel;
  401. this._toplevel = undefined;
  402. return toplevel;
  403. }
  404. before(node, descend) {
  405. if (has_flag(node, SQUEEZED)) return node;
  406. var was_scope = false;
  407. if (node instanceof AST_Scope) {
  408. node = node.hoist_properties(this);
  409. node = node.hoist_declarations(this);
  410. was_scope = true;
  411. }
  412. // Before https://github.com/mishoo/UglifyJS2/pull/1602 AST_Node.optimize()
  413. // would call AST_Node.transform() if a different instance of AST_Node is
  414. // produced after def_optimize().
  415. // This corrupts TreeWalker.stack, which cause AST look-ups to malfunction.
  416. // Migrate and defer all children's AST_Node.transform() to below, which
  417. // will now happen after this parent AST_Node has been properly substituted
  418. // thus gives a consistent AST snapshot.
  419. descend(node, this);
  420. // Existing code relies on how AST_Node.optimize() worked, and omitting the
  421. // following replacement call would result in degraded efficiency of both
  422. // output and performance.
  423. descend(node, this);
  424. var opt = node.optimize(this);
  425. if (was_scope && opt instanceof AST_Scope) {
  426. opt.drop_unused(this);
  427. descend(opt, this);
  428. }
  429. if (opt === node) set_flag(opt, SQUEEZED);
  430. return opt;
  431. }
  432. }
  433. function def_optimize(node, optimizer) {
  434. node.DEFMETHOD("optimize", function(compressor) {
  435. var self = this;
  436. if (has_flag(self, OPTIMIZED)) return self;
  437. if (compressor.has_directive("use asm")) return self;
  438. var opt = optimizer(self, compressor);
  439. set_flag(opt, OPTIMIZED);
  440. return opt;
  441. });
  442. }
  443. def_optimize(AST_Node, function(self) {
  444. return self;
  445. });
  446. AST_Toplevel.DEFMETHOD("drop_console", function() {
  447. return this.transform(new TreeTransformer(function(self) {
  448. if (self.TYPE == "Call") {
  449. var exp = self.expression;
  450. if (exp instanceof AST_PropAccess) {
  451. var name = exp.expression;
  452. while (name.expression) {
  453. name = name.expression;
  454. }
  455. if (is_undeclared_ref(name) && name.name == "console") {
  456. return make_node(AST_Undefined, self);
  457. }
  458. }
  459. }
  460. }));
  461. });
  462. AST_Node.DEFMETHOD("equivalent_to", function(node) {
  463. return equivalent_to(this, node);
  464. });
  465. AST_Scope.DEFMETHOD("process_expression", function(insert, compressor) {
  466. var self = this;
  467. var tt = new TreeTransformer(function(node) {
  468. if (insert && node instanceof AST_SimpleStatement) {
  469. return make_node(AST_Return, node, {
  470. value: node.body
  471. });
  472. }
  473. if (!insert && node instanceof AST_Return) {
  474. if (compressor) {
  475. var value = node.value && node.value.drop_side_effect_free(compressor, true);
  476. return value
  477. ? make_node(AST_SimpleStatement, node, { body: value })
  478. : make_node(AST_EmptyStatement, node);
  479. }
  480. return make_node(AST_SimpleStatement, node, {
  481. body: node.value || make_node(AST_UnaryPrefix, node, {
  482. operator: "void",
  483. expression: make_node(AST_Number, node, {
  484. value: 0
  485. })
  486. })
  487. });
  488. }
  489. if (node instanceof AST_Class || node instanceof AST_Lambda && node !== self) {
  490. return node;
  491. }
  492. if (node instanceof AST_Block) {
  493. var index = node.body.length - 1;
  494. if (index >= 0) {
  495. node.body[index] = node.body[index].transform(tt);
  496. }
  497. } else if (node instanceof AST_If) {
  498. node.body = node.body.transform(tt);
  499. if (node.alternative) {
  500. node.alternative = node.alternative.transform(tt);
  501. }
  502. } else if (node instanceof AST_With) {
  503. node.body = node.body.transform(tt);
  504. }
  505. return node;
  506. });
  507. self.transform(tt);
  508. });
  509. AST_Toplevel.DEFMETHOD("reset_opt_flags", function(compressor) {
  510. const self = this;
  511. const reduce_vars = compressor.option("reduce_vars");
  512. const preparation = new TreeWalker(function(node, descend) {
  513. clear_flag(node, CLEAR_BETWEEN_PASSES);
  514. if (reduce_vars) {
  515. if (compressor.top_retain
  516. && node instanceof AST_Defun // Only functions are retained
  517. && preparation.parent() === self
  518. ) {
  519. set_flag(node, TOP);
  520. }
  521. return node.reduce_vars(preparation, descend, compressor);
  522. }
  523. });
  524. // Stack of look-up tables to keep track of whether a `SymbolDef` has been
  525. // properly assigned before use:
  526. // - `push()` & `pop()` when visiting conditional branches
  527. preparation.safe_ids = Object.create(null);
  528. preparation.in_loop = null;
  529. preparation.loop_ids = new Map();
  530. preparation.defs_to_safe_ids = new Map();
  531. self.walk(preparation);
  532. });
  533. AST_Symbol.DEFMETHOD("fixed_value", function() {
  534. var fixed = this.thedef.fixed;
  535. if (!fixed || fixed instanceof AST_Node) return fixed;
  536. return fixed();
  537. });
  538. AST_SymbolRef.DEFMETHOD("is_immutable", function() {
  539. var orig = this.definition().orig;
  540. return orig.length == 1 && orig[0] instanceof AST_SymbolLambda;
  541. });
  542. function find_scope(tw) {
  543. for (let i = 0;;i++) {
  544. const p = tw.parent(i);
  545. if (p instanceof AST_Toplevel) return p;
  546. if (p instanceof AST_Lambda) return p;
  547. if (p.block_scope) return p.block_scope;
  548. }
  549. }
  550. function find_variable(compressor, name) {
  551. var scope, i = 0;
  552. while (scope = compressor.parent(i++)) {
  553. if (scope instanceof AST_Scope) break;
  554. if (scope instanceof AST_Catch && scope.argname) {
  555. scope = scope.argname.definition().scope;
  556. break;
  557. }
  558. }
  559. return scope.find_variable(name);
  560. }
  561. function is_empty(thing) {
  562. if (thing === null) return true;
  563. if (thing instanceof AST_EmptyStatement) return true;
  564. if (thing instanceof AST_BlockStatement) return thing.body.length == 0;
  565. return false;
  566. }
  567. var global_names = makePredicate("Array Boolean clearInterval clearTimeout console Date decodeURI decodeURIComponent encodeURI encodeURIComponent Error escape eval EvalError Function isFinite isNaN JSON Math Number parseFloat parseInt RangeError ReferenceError RegExp Object setInterval setTimeout String SyntaxError TypeError unescape URIError");
  568. AST_SymbolRef.DEFMETHOD("is_declared", function(compressor) {
  569. return !this.definition().undeclared
  570. || compressor.option("unsafe") && global_names.has(this.name);
  571. });
  572. /* -----[ optimizers ]----- */
  573. var directives = new Set(["use asm", "use strict"]);
  574. def_optimize(AST_Directive, function(self, compressor) {
  575. if (compressor.option("directives")
  576. && (!directives.has(self.value) || compressor.has_directive(self.value) !== self)) {
  577. return make_node(AST_EmptyStatement, self);
  578. }
  579. return self;
  580. });
  581. def_optimize(AST_Debugger, function(self, compressor) {
  582. if (compressor.option("drop_debugger"))
  583. return make_node(AST_EmptyStatement, self);
  584. return self;
  585. });
  586. def_optimize(AST_LabeledStatement, function(self, compressor) {
  587. if (self.body instanceof AST_Break
  588. && compressor.loopcontrol_target(self.body) === self.body) {
  589. return make_node(AST_EmptyStatement, self);
  590. }
  591. return self.label.references.length == 0 ? self.body : self;
  592. });
  593. def_optimize(AST_Block, function(self, compressor) {
  594. tighten_body(self.body, compressor);
  595. return self;
  596. });
  597. function can_be_extracted_from_if_block(node) {
  598. return !(
  599. node instanceof AST_Const
  600. || node instanceof AST_Let
  601. || node instanceof AST_Class
  602. );
  603. }
  604. def_optimize(AST_BlockStatement, function(self, compressor) {
  605. tighten_body(self.body, compressor);
  606. switch (self.body.length) {
  607. case 1:
  608. if (!compressor.has_directive("use strict")
  609. && compressor.parent() instanceof AST_If
  610. && can_be_extracted_from_if_block(self.body[0])
  611. || can_be_evicted_from_block(self.body[0])) {
  612. return self.body[0];
  613. }
  614. break;
  615. case 0: return make_node(AST_EmptyStatement, self);
  616. }
  617. return self;
  618. });
  619. function opt_AST_Lambda(self, compressor) {
  620. tighten_body(self.body, compressor);
  621. if (compressor.option("side_effects")
  622. && self.body.length == 1
  623. && self.body[0] === compressor.has_directive("use strict")) {
  624. self.body.length = 0;
  625. }
  626. return self;
  627. }
  628. def_optimize(AST_Lambda, opt_AST_Lambda);
  629. const r_keep_assign = /keep_assign/;
  630. AST_Scope.DEFMETHOD("drop_unused", function(compressor) {
  631. if (!compressor.option("unused")) return;
  632. if (compressor.has_directive("use asm")) return;
  633. var self = this;
  634. if (self.pinned()) return;
  635. var drop_funcs = !(self instanceof AST_Toplevel) || compressor.toplevel.funcs;
  636. var drop_vars = !(self instanceof AST_Toplevel) || compressor.toplevel.vars;
  637. const assign_as_unused = r_keep_assign.test(compressor.option("unused")) ? return_false : function(node) {
  638. if (node instanceof AST_Assign
  639. && !node.logical
  640. && (has_flag(node, WRITE_ONLY) || node.operator == "=")
  641. ) {
  642. return node.left;
  643. }
  644. if (node instanceof AST_Unary && has_flag(node, WRITE_ONLY)) {
  645. return node.expression;
  646. }
  647. };
  648. var in_use_ids = new Map();
  649. var fixed_ids = new Map();
  650. if (self instanceof AST_Toplevel && compressor.top_retain) {
  651. self.variables.forEach(function(def) {
  652. if (compressor.top_retain(def) && !in_use_ids.has(def.id)) {
  653. in_use_ids.set(def.id, def);
  654. }
  655. });
  656. }
  657. var var_defs_by_id = new Map();
  658. var initializations = new Map();
  659. // pass 1: find out which symbols are directly used in
  660. // this scope (not in nested scopes).
  661. var scope = this;
  662. var tw = new TreeWalker(function(node, descend) {
  663. if (node instanceof AST_Lambda && node.uses_arguments && !tw.has_directive("use strict")) {
  664. node.argnames.forEach(function(argname) {
  665. if (!(argname instanceof AST_SymbolDeclaration)) return;
  666. var def = argname.definition();
  667. if (!in_use_ids.has(def.id)) {
  668. in_use_ids.set(def.id, def);
  669. }
  670. });
  671. }
  672. if (node === self) return;
  673. if (node instanceof AST_Defun || node instanceof AST_DefClass) {
  674. var node_def = node.name.definition();
  675. const in_export = tw.parent() instanceof AST_Export;
  676. if (in_export || !drop_funcs && scope === self) {
  677. if (node_def.global && !in_use_ids.has(node_def.id)) {
  678. in_use_ids.set(node_def.id, node_def);
  679. }
  680. }
  681. if (node instanceof AST_DefClass) {
  682. if (
  683. node.extends
  684. && (node.extends.has_side_effects(compressor)
  685. || node.extends.may_throw(compressor))
  686. ) {
  687. node.extends.walk(tw);
  688. }
  689. for (const prop of node.properties) {
  690. if (
  691. prop.has_side_effects(compressor) ||
  692. prop.may_throw(compressor)
  693. ) {
  694. prop.walk(tw);
  695. }
  696. }
  697. }
  698. map_add(initializations, node_def.id, node);
  699. return true; // don't go in nested scopes
  700. }
  701. if (node instanceof AST_SymbolFunarg && scope === self) {
  702. map_add(var_defs_by_id, node.definition().id, node);
  703. }
  704. if (node instanceof AST_Definitions && scope === self) {
  705. const in_export = tw.parent() instanceof AST_Export;
  706. node.definitions.forEach(function(def) {
  707. if (def.name instanceof AST_SymbolVar) {
  708. map_add(var_defs_by_id, def.name.definition().id, def);
  709. }
  710. if (in_export || !drop_vars) {
  711. walk(def.name, node => {
  712. if (node instanceof AST_SymbolDeclaration) {
  713. const def = node.definition();
  714. if (
  715. (in_export || def.global)
  716. && !in_use_ids.has(def.id)
  717. ) {
  718. in_use_ids.set(def.id, def);
  719. }
  720. }
  721. });
  722. }
  723. if (def.value) {
  724. if (def.name instanceof AST_Destructuring) {
  725. def.walk(tw);
  726. } else {
  727. var node_def = def.name.definition();
  728. map_add(initializations, node_def.id, def.value);
  729. if (!node_def.chained && def.name.fixed_value() === def.value) {
  730. fixed_ids.set(node_def.id, def);
  731. }
  732. }
  733. if (def.value.has_side_effects(compressor)) {
  734. def.value.walk(tw);
  735. }
  736. }
  737. });
  738. return true;
  739. }
  740. return scan_ref_scoped(node, descend);
  741. });
  742. self.walk(tw);
  743. // pass 2: for every used symbol we need to walk its
  744. // initialization code to figure out if it uses other
  745. // symbols (that may not be in_use).
  746. tw = new TreeWalker(scan_ref_scoped);
  747. in_use_ids.forEach(function (def) {
  748. var init = initializations.get(def.id);
  749. if (init) init.forEach(function(init) {
  750. init.walk(tw);
  751. });
  752. });
  753. // pass 3: we should drop declarations not in_use
  754. var tt = new TreeTransformer(
  755. function before(node, descend, in_list) {
  756. var parent = tt.parent();
  757. if (drop_vars) {
  758. const sym = assign_as_unused(node);
  759. if (sym instanceof AST_SymbolRef) {
  760. var def = sym.definition();
  761. var in_use = in_use_ids.has(def.id);
  762. if (node instanceof AST_Assign) {
  763. if (!in_use || fixed_ids.has(def.id) && fixed_ids.get(def.id) !== node) {
  764. return maintain_this_binding(parent, node, node.right.transform(tt));
  765. }
  766. } else if (!in_use) return in_list ? MAP.skip : make_node(AST_Number, node, {
  767. value: 0
  768. });
  769. }
  770. }
  771. if (scope !== self) return;
  772. var def;
  773. if (node.name
  774. && (node instanceof AST_ClassExpression
  775. && !keep_name(compressor.option("keep_classnames"), (def = node.name.definition()).name)
  776. || node instanceof AST_Function
  777. && !keep_name(compressor.option("keep_fnames"), (def = node.name.definition()).name))) {
  778. // any declarations with same name will overshadow
  779. // name of this anonymous function and can therefore
  780. // never be used anywhere
  781. if (!in_use_ids.has(def.id) || def.orig.length > 1) node.name = null;
  782. }
  783. if (node instanceof AST_Lambda && !(node instanceof AST_Accessor)) {
  784. var trim = !compressor.option("keep_fargs");
  785. for (var a = node.argnames, i = a.length; --i >= 0;) {
  786. var sym = a[i];
  787. if (sym instanceof AST_Expansion) {
  788. sym = sym.expression;
  789. }
  790. if (sym instanceof AST_DefaultAssign) {
  791. sym = sym.left;
  792. }
  793. // Do not drop destructuring arguments.
  794. // They constitute a type assertion, so dropping
  795. // them would stop that TypeError which would happen
  796. // if someone called it with an incorrectly formatted
  797. // parameter.
  798. if (!(sym instanceof AST_Destructuring) && !in_use_ids.has(sym.definition().id)) {
  799. set_flag(sym, UNUSED);
  800. if (trim) {
  801. a.pop();
  802. }
  803. } else {
  804. trim = false;
  805. }
  806. }
  807. }
  808. if ((node instanceof AST_Defun || node instanceof AST_DefClass) && node !== self) {
  809. const def = node.name.definition();
  810. let keep = def.global && !drop_funcs || in_use_ids.has(def.id);
  811. if (!keep) {
  812. def.eliminated++;
  813. if (node instanceof AST_DefClass) {
  814. // Classes might have extends with side effects
  815. const side_effects = node.drop_side_effect_free(compressor);
  816. if (side_effects) {
  817. return make_node(AST_SimpleStatement, node, {
  818. body: side_effects
  819. });
  820. }
  821. }
  822. return in_list ? MAP.skip : make_node(AST_EmptyStatement, node);
  823. }
  824. }
  825. if (node instanceof AST_Definitions && !(parent instanceof AST_ForIn && parent.init === node)) {
  826. var drop_block = !(parent instanceof AST_Toplevel) && !(node instanceof AST_Var);
  827. // place uninitialized names at the start
  828. var body = [], head = [], tail = [];
  829. // for unused names whose initialization has
  830. // side effects, we can cascade the init. code
  831. // into the next one, or next statement.
  832. var side_effects = [];
  833. node.definitions.forEach(function(def) {
  834. if (def.value) def.value = def.value.transform(tt);
  835. var is_destructure = def.name instanceof AST_Destructuring;
  836. var sym = is_destructure
  837. ? new SymbolDef(null, { name: "<destructure>" }) /* fake SymbolDef */
  838. : def.name.definition();
  839. if (drop_block && sym.global) return tail.push(def);
  840. if (!(drop_vars || drop_block)
  841. || is_destructure
  842. && (def.name.names.length
  843. || def.name.is_array
  844. || compressor.option("pure_getters") != true)
  845. || in_use_ids.has(sym.id)
  846. ) {
  847. if (def.value && fixed_ids.has(sym.id) && fixed_ids.get(sym.id) !== def) {
  848. def.value = def.value.drop_side_effect_free(compressor);
  849. }
  850. if (def.name instanceof AST_SymbolVar) {
  851. var var_defs = var_defs_by_id.get(sym.id);
  852. if (var_defs.length > 1 && (!def.value || sym.orig.indexOf(def.name) > sym.eliminated)) {
  853. if (def.value) {
  854. var ref = make_node(AST_SymbolRef, def.name, def.name);
  855. sym.references.push(ref);
  856. var assign = make_node(AST_Assign, def, {
  857. operator: "=",
  858. logical: false,
  859. left: ref,
  860. right: def.value
  861. });
  862. if (fixed_ids.get(sym.id) === def) {
  863. fixed_ids.set(sym.id, assign);
  864. }
  865. side_effects.push(assign.transform(tt));
  866. }
  867. remove(var_defs, def);
  868. sym.eliminated++;
  869. return;
  870. }
  871. }
  872. if (def.value) {
  873. if (side_effects.length > 0) {
  874. if (tail.length > 0) {
  875. side_effects.push(def.value);
  876. def.value = make_sequence(def.value, side_effects);
  877. } else {
  878. body.push(make_node(AST_SimpleStatement, node, {
  879. body: make_sequence(node, side_effects)
  880. }));
  881. }
  882. side_effects = [];
  883. }
  884. tail.push(def);
  885. } else {
  886. head.push(def);
  887. }
  888. } else if (sym.orig[0] instanceof AST_SymbolCatch) {
  889. var value = def.value && def.value.drop_side_effect_free(compressor);
  890. if (value) side_effects.push(value);
  891. def.value = null;
  892. head.push(def);
  893. } else {
  894. var value = def.value && def.value.drop_side_effect_free(compressor);
  895. if (value) {
  896. side_effects.push(value);
  897. }
  898. sym.eliminated++;
  899. }
  900. });
  901. if (head.length > 0 || tail.length > 0) {
  902. node.definitions = head.concat(tail);
  903. body.push(node);
  904. }
  905. if (side_effects.length > 0) {
  906. body.push(make_node(AST_SimpleStatement, node, {
  907. body: make_sequence(node, side_effects)
  908. }));
  909. }
  910. switch (body.length) {
  911. case 0:
  912. return in_list ? MAP.skip : make_node(AST_EmptyStatement, node);
  913. case 1:
  914. return body[0];
  915. default:
  916. return in_list ? MAP.splice(body) : make_node(AST_BlockStatement, node, {
  917. body: body
  918. });
  919. }
  920. }
  921. // certain combination of unused name + side effect leads to:
  922. // https://github.com/mishoo/UglifyJS2/issues/44
  923. // https://github.com/mishoo/UglifyJS2/issues/1830
  924. // https://github.com/mishoo/UglifyJS2/issues/1838
  925. // that's an invalid AST.
  926. // We fix it at this stage by moving the `var` outside the `for`.
  927. if (node instanceof AST_For) {
  928. descend(node, this);
  929. var block;
  930. if (node.init instanceof AST_BlockStatement) {
  931. block = node.init;
  932. node.init = block.body.pop();
  933. block.body.push(node);
  934. }
  935. if (node.init instanceof AST_SimpleStatement) {
  936. node.init = node.init.body;
  937. } else if (is_empty(node.init)) {
  938. node.init = null;
  939. }
  940. return !block ? node : in_list ? MAP.splice(block.body) : block;
  941. }
  942. if (node instanceof AST_LabeledStatement
  943. && node.body instanceof AST_For
  944. ) {
  945. descend(node, this);
  946. if (node.body instanceof AST_BlockStatement) {
  947. var block = node.body;
  948. node.body = block.body.pop();
  949. block.body.push(node);
  950. return in_list ? MAP.splice(block.body) : block;
  951. }
  952. return node;
  953. }
  954. if (node instanceof AST_BlockStatement) {
  955. descend(node, this);
  956. if (in_list && node.body.every(can_be_evicted_from_block)) {
  957. return MAP.splice(node.body);
  958. }
  959. return node;
  960. }
  961. if (node instanceof AST_Scope) {
  962. const save_scope = scope;
  963. scope = node;
  964. descend(node, this);
  965. scope = save_scope;
  966. return node;
  967. }
  968. }
  969. );
  970. self.transform(tt);
  971. function scan_ref_scoped(node, descend) {
  972. var node_def;
  973. const sym = assign_as_unused(node);
  974. if (sym instanceof AST_SymbolRef
  975. && !is_ref_of(node.left, AST_SymbolBlockDeclaration)
  976. && self.variables.get(sym.name) === (node_def = sym.definition())
  977. ) {
  978. if (node instanceof AST_Assign) {
  979. node.right.walk(tw);
  980. if (!node_def.chained && node.left.fixed_value() === node.right) {
  981. fixed_ids.set(node_def.id, node);
  982. }
  983. }
  984. return true;
  985. }
  986. if (node instanceof AST_SymbolRef) {
  987. node_def = node.definition();
  988. if (!in_use_ids.has(node_def.id)) {
  989. in_use_ids.set(node_def.id, node_def);
  990. if (node_def.orig[0] instanceof AST_SymbolCatch) {
  991. const redef = node_def.scope.is_block_scope()
  992. && node_def.scope.get_defun_scope().variables.get(node_def.name);
  993. if (redef) in_use_ids.set(redef.id, redef);
  994. }
  995. }
  996. return true;
  997. }
  998. if (node instanceof AST_Scope) {
  999. var save_scope = scope;
  1000. scope = node;
  1001. descend();
  1002. scope = save_scope;
  1003. return true;
  1004. }
  1005. }
  1006. });
  1007. AST_Scope.DEFMETHOD("hoist_declarations", function(compressor) {
  1008. var self = this;
  1009. if (compressor.has_directive("use asm")) return self;
  1010. // Hoisting makes no sense in an arrow func
  1011. if (!Array.isArray(self.body)) return self;
  1012. var hoist_funs = compressor.option("hoist_funs");
  1013. var hoist_vars = compressor.option("hoist_vars");
  1014. if (hoist_funs || hoist_vars) {
  1015. var dirs = [];
  1016. var hoisted = [];
  1017. var vars = new Map(), vars_found = 0, var_decl = 0;
  1018. // let's count var_decl first, we seem to waste a lot of
  1019. // space if we hoist `var` when there's only one.
  1020. walk(self, node => {
  1021. if (node instanceof AST_Scope && node !== self)
  1022. return true;
  1023. if (node instanceof AST_Var) {
  1024. ++var_decl;
  1025. return true;
  1026. }
  1027. });
  1028. hoist_vars = hoist_vars && var_decl > 1;
  1029. var tt = new TreeTransformer(
  1030. function before(node) {
  1031. if (node !== self) {
  1032. if (node instanceof AST_Directive) {
  1033. dirs.push(node);
  1034. return make_node(AST_EmptyStatement, node);
  1035. }
  1036. if (hoist_funs && node instanceof AST_Defun
  1037. && !(tt.parent() instanceof AST_Export)
  1038. && tt.parent() === self) {
  1039. hoisted.push(node);
  1040. return make_node(AST_EmptyStatement, node);
  1041. }
  1042. if (
  1043. hoist_vars
  1044. && node instanceof AST_Var
  1045. && !node.definitions.some(def => def.name instanceof AST_Destructuring)
  1046. ) {
  1047. node.definitions.forEach(function(def) {
  1048. vars.set(def.name.name, def);
  1049. ++vars_found;
  1050. });
  1051. var seq = node.to_assignments(compressor);
  1052. var p = tt.parent();
  1053. if (p instanceof AST_ForIn && p.init === node) {
  1054. if (seq == null) {
  1055. var def = node.definitions[0].name;
  1056. return make_node(AST_SymbolRef, def, def);
  1057. }
  1058. return seq;
  1059. }
  1060. if (p instanceof AST_For && p.init === node) {
  1061. return seq;
  1062. }
  1063. if (!seq) return make_node(AST_EmptyStatement, node);
  1064. return make_node(AST_SimpleStatement, node, {
  1065. body: seq
  1066. });
  1067. }
  1068. if (node instanceof AST_Scope)
  1069. return node; // to avoid descending in nested scopes
  1070. }
  1071. }
  1072. );
  1073. self = self.transform(tt);
  1074. if (vars_found > 0) {
  1075. // collect only vars which don't show up in self's arguments list
  1076. var defs = [];
  1077. const is_lambda = self instanceof AST_Lambda;
  1078. const args_as_names = is_lambda ? self.args_as_names() : null;
  1079. vars.forEach((def, name) => {
  1080. if (is_lambda && args_as_names.some((x) => x.name === def.name.name)) {
  1081. vars.delete(name);
  1082. } else {
  1083. def = def.clone();
  1084. def.value = null;
  1085. defs.push(def);
  1086. vars.set(name, def);
  1087. }
  1088. });
  1089. if (defs.length > 0) {
  1090. // try to merge in assignments
  1091. for (var i = 0; i < self.body.length;) {
  1092. if (self.body[i] instanceof AST_SimpleStatement) {
  1093. var expr = self.body[i].body, sym, assign;
  1094. if (expr instanceof AST_Assign
  1095. && expr.operator == "="
  1096. && (sym = expr.left) instanceof AST_Symbol
  1097. && vars.has(sym.name)
  1098. ) {
  1099. var def = vars.get(sym.name);
  1100. if (def.value) break;
  1101. def.value = expr.right;
  1102. remove(defs, def);
  1103. defs.push(def);
  1104. self.body.splice(i, 1);
  1105. continue;
  1106. }
  1107. if (expr instanceof AST_Sequence
  1108. && (assign = expr.expressions[0]) instanceof AST_Assign
  1109. && assign.operator == "="
  1110. && (sym = assign.left) instanceof AST_Symbol
  1111. && vars.has(sym.name)
  1112. ) {
  1113. var def = vars.get(sym.name);
  1114. if (def.value) break;
  1115. def.value = assign.right;
  1116. remove(defs, def);
  1117. defs.push(def);
  1118. self.body[i].body = make_sequence(expr, expr.expressions.slice(1));
  1119. continue;
  1120. }
  1121. }
  1122. if (self.body[i] instanceof AST_EmptyStatement) {
  1123. self.body.splice(i, 1);
  1124. continue;
  1125. }
  1126. if (self.body[i] instanceof AST_BlockStatement) {
  1127. self.body.splice(i, 1, ...self.body[i].body);
  1128. continue;
  1129. }
  1130. break;
  1131. }
  1132. defs = make_node(AST_Var, self, {
  1133. definitions: defs
  1134. });
  1135. hoisted.push(defs);
  1136. }
  1137. }
  1138. self.body = dirs.concat(hoisted, self.body);
  1139. }
  1140. return self;
  1141. });
  1142. AST_Scope.DEFMETHOD("hoist_properties", function(compressor) {
  1143. var self = this;
  1144. if (!compressor.option("hoist_props") || compressor.has_directive("use asm")) return self;
  1145. var top_retain = self instanceof AST_Toplevel && compressor.top_retain || return_false;
  1146. var defs_by_id = new Map();
  1147. var hoister = new TreeTransformer(function(node, descend) {
  1148. if (node instanceof AST_Definitions
  1149. && hoister.parent() instanceof AST_Export) return node;
  1150. if (node instanceof AST_VarDef) {
  1151. const sym = node.name;
  1152. let def;
  1153. let value;
  1154. if (sym.scope === self
  1155. && (def = sym.definition()).escaped != 1
  1156. && !def.assignments
  1157. && !def.direct_access
  1158. && !def.single_use
  1159. && !compressor.exposed(def)
  1160. && !top_retain(def)
  1161. && (value = sym.fixed_value()) === node.value
  1162. && value instanceof AST_Object
  1163. && !value.properties.some(prop =>
  1164. prop instanceof AST_Expansion || prop.computed_key()
  1165. )
  1166. ) {
  1167. descend(node, this);
  1168. const defs = new Map();
  1169. const assignments = [];
  1170. value.properties.forEach(({ key, value }) => {
  1171. const scope = find_scope(hoister);
  1172. const symbol = self.create_symbol(sym.CTOR, {
  1173. source: sym,
  1174. scope,
  1175. conflict_scopes: new Set([
  1176. scope,
  1177. ...sym.definition().references.map(ref => ref.scope)
  1178. ]),
  1179. tentative_name: sym.name + "_" + key
  1180. });
  1181. defs.set(String(key), symbol.definition());
  1182. assignments.push(make_node(AST_VarDef, node, {
  1183. name: symbol,
  1184. value
  1185. }));
  1186. });
  1187. defs_by_id.set(def.id, defs);
  1188. return MAP.splice(assignments);
  1189. }
  1190. } else if (node instanceof AST_PropAccess
  1191. && node.expression instanceof AST_SymbolRef
  1192. ) {
  1193. const defs = defs_by_id.get(node.expression.definition().id);
  1194. if (defs) {
  1195. const def = defs.get(String(get_simple_key(node.property)));
  1196. const sym = make_node(AST_SymbolRef, node, {
  1197. name: def.name,
  1198. scope: node.expression.scope,
  1199. thedef: def
  1200. });
  1201. sym.reference({});
  1202. return sym;
  1203. }
  1204. }
  1205. });
  1206. return self.transform(hoister);
  1207. });
  1208. def_optimize(AST_SimpleStatement, function(self, compressor) {
  1209. if (compressor.option("side_effects")) {
  1210. var body = self.body;
  1211. var node = body.drop_side_effect_free(compressor, true);
  1212. if (!node) {
  1213. return make_node(AST_EmptyStatement, self);
  1214. }
  1215. if (node !== body) {
  1216. return make_node(AST_SimpleStatement, self, { body: node });
  1217. }
  1218. }
  1219. return self;
  1220. });
  1221. def_optimize(AST_While, function(self, compressor) {
  1222. return compressor.option("loops") ? make_node(AST_For, self, self).optimize(compressor) : self;
  1223. });
  1224. def_optimize(AST_Do, function(self, compressor) {
  1225. if (!compressor.option("loops")) return self;
  1226. var cond = self.condition.tail_node().evaluate(compressor);
  1227. if (!(cond instanceof AST_Node)) {
  1228. if (cond) return make_node(AST_For, self, {
  1229. body: make_node(AST_BlockStatement, self.body, {
  1230. body: [
  1231. self.body,
  1232. make_node(AST_SimpleStatement, self.condition, {
  1233. body: self.condition
  1234. })
  1235. ]
  1236. })
  1237. }).optimize(compressor);
  1238. if (!has_break_or_continue(self, compressor.parent())) {
  1239. return make_node(AST_BlockStatement, self.body, {
  1240. body: [
  1241. self.body,
  1242. make_node(AST_SimpleStatement, self.condition, {
  1243. body: self.condition
  1244. })
  1245. ]
  1246. }).optimize(compressor);
  1247. }
  1248. }
  1249. return self;
  1250. });
  1251. function if_break_in_loop(self, compressor) {
  1252. var first = self.body instanceof AST_BlockStatement ? self.body.body[0] : self.body;
  1253. if (compressor.option("dead_code") && is_break(first)) {
  1254. var body = [];
  1255. if (self.init instanceof AST_Statement) {
  1256. body.push(self.init);
  1257. } else if (self.init) {
  1258. body.push(make_node(AST_SimpleStatement, self.init, {
  1259. body: self.init
  1260. }));
  1261. }
  1262. if (self.condition) {
  1263. body.push(make_node(AST_SimpleStatement, self.condition, {
  1264. body: self.condition
  1265. }));
  1266. }
  1267. trim_unreachable_code(compressor, self.body, body);
  1268. return make_node(AST_BlockStatement, self, {
  1269. body: body
  1270. });
  1271. }
  1272. if (first instanceof AST_If) {
  1273. if (is_break(first.body)) {
  1274. if (self.condition) {
  1275. self.condition = make_node(AST_Binary, self.condition, {
  1276. left: self.condition,
  1277. operator: "&&",
  1278. right: first.condition.negate(compressor),
  1279. });
  1280. } else {
  1281. self.condition = first.condition.negate(compressor);
  1282. }
  1283. drop_it(first.alternative);
  1284. } else if (is_break(first.alternative)) {
  1285. if (self.condition) {
  1286. self.condition = make_node(AST_Binary, self.condition, {
  1287. left: self.condition,
  1288. operator: "&&",
  1289. right: first.condition,
  1290. });
  1291. } else {
  1292. self.condition = first.condition;
  1293. }
  1294. drop_it(first.body);
  1295. }
  1296. }
  1297. return self;
  1298. function is_break(node) {
  1299. return node instanceof AST_Break
  1300. && compressor.loopcontrol_target(node) === compressor.self();
  1301. }
  1302. function drop_it(rest) {
  1303. rest = as_statement_array(rest);
  1304. if (self.body instanceof AST_BlockStatement) {
  1305. self.body = self.body.clone();
  1306. self.body.body = rest.concat(self.body.body.slice(1));
  1307. self.body = self.body.transform(compressor);
  1308. } else {
  1309. self.body = make_node(AST_BlockStatement, self.body, {
  1310. body: rest
  1311. }).transform(compressor);
  1312. }
  1313. self = if_break_in_loop(self, compressor);
  1314. }
  1315. }
  1316. def_optimize(AST_For, function(self, compressor) {
  1317. if (!compressor.option("loops")) return self;
  1318. if (compressor.option("side_effects") && self.init) {
  1319. self.init = self.init.drop_side_effect_free(compressor);
  1320. }
  1321. if (self.condition) {
  1322. var cond = self.condition.evaluate(compressor);
  1323. if (!(cond instanceof AST_Node)) {
  1324. if (cond) self.condition = null;
  1325. else if (!compressor.option("dead_code")) {
  1326. var orig = self.condition;
  1327. self.condition = make_node_from_constant(cond, self.condition);
  1328. self.condition = best_of_expression(self.condition.transform(compressor), orig);
  1329. }
  1330. }
  1331. if (compressor.option("dead_code")) {
  1332. if (cond instanceof AST_Node) cond = self.condition.tail_node().evaluate(compressor);
  1333. if (!cond) {
  1334. var body = [];
  1335. trim_unreachable_code(compressor, self.body, body);
  1336. if (self.init instanceof AST_Statement) {
  1337. body.push(self.init);
  1338. } else if (self.init) {
  1339. body.push(make_node(AST_SimpleStatement, self.init, {
  1340. body: self.init
  1341. }));
  1342. }
  1343. body.push(make_node(AST_SimpleStatement, self.condition, {
  1344. body: self.condition
  1345. }));
  1346. return make_node(AST_BlockStatement, self, { body: body }).optimize(compressor);
  1347. }
  1348. }
  1349. }
  1350. return if_break_in_loop(self, compressor);
  1351. });
  1352. def_optimize(AST_If, function(self, compressor) {
  1353. if (is_empty(self.alternative)) self.alternative = null;
  1354. if (!compressor.option("conditionals")) return self;
  1355. // if condition can be statically determined, drop
  1356. // one of the blocks. note, statically determined implies
  1357. // “has no side effects”; also it doesn't work for cases like
  1358. // `x && true`, though it probably should.
  1359. var cond = self.condition.evaluate(compressor);
  1360. if (!compressor.option("dead_code") && !(cond instanceof AST_Node)) {
  1361. var orig = self.condition;
  1362. self.condition = make_node_from_constant(cond, orig);
  1363. self.condition = best_of_expression(self.condition.transform(compressor), orig);
  1364. }
  1365. if (compressor.option("dead_code")) {
  1366. if (cond instanceof AST_Node) cond = self.condition.tail_node().evaluate(compressor);
  1367. if (!cond) {
  1368. var body = [];
  1369. trim_unreachable_code(compressor, self.body, body);
  1370. body.push(make_node(AST_SimpleStatement, self.condition, {
  1371. body: self.condition
  1372. }));
  1373. if (self.alternative) body.push(self.alternative);
  1374. return make_node(AST_BlockStatement, self, { body: body }).optimize(compressor);
  1375. } else if (!(cond instanceof AST_Node)) {
  1376. var body = [];
  1377. body.push(make_node(AST_SimpleStatement, self.condition, {
  1378. body: self.condition
  1379. }));
  1380. body.push(self.body);
  1381. if (self.alternative) {
  1382. trim_unreachable_code(compressor, self.alternative, body);
  1383. }
  1384. return make_node(AST_BlockStatement, self, { body: body }).optimize(compressor);
  1385. }
  1386. }
  1387. var negated = self.condition.negate(compressor);
  1388. var self_condition_length = self.condition.size();
  1389. var negated_length = negated.size();
  1390. var negated_is_best = negated_length < self_condition_length;
  1391. if (self.alternative && negated_is_best) {
  1392. negated_is_best = false; // because we already do the switch here.
  1393. // no need to swap values of self_condition_length and negated_length
  1394. // here because they are only used in an equality comparison later on.
  1395. self.condition = negated;
  1396. var tmp = self.body;
  1397. self.body = self.alternative || make_node(AST_EmptyStatement, self);
  1398. self.alternative = tmp;
  1399. }
  1400. if (is_empty(self.body) && is_empty(self.alternative)) {
  1401. return make_node(AST_SimpleStatement, self.condition, {
  1402. body: self.condition.clone()
  1403. }).optimize(compressor);
  1404. }
  1405. if (self.body instanceof AST_SimpleStatement
  1406. && self.alternative instanceof AST_SimpleStatement) {
  1407. return make_node(AST_SimpleStatement, self, {
  1408. body: make_node(AST_Conditional, self, {
  1409. condition : self.condition,
  1410. consequent : self.body.body,
  1411. alternative : self.alternative.body
  1412. })
  1413. }).optimize(compressor);
  1414. }
  1415. if (is_empty(self.alternative) && self.body instanceof AST_SimpleStatement) {
  1416. if (self_condition_length === negated_length && !negated_is_best
  1417. && self.condition instanceof AST_Binary && self.condition.operator == "||") {
  1418. // although the code length of self.condition and negated are the same,
  1419. // negated does not require additional surrounding parentheses.
  1420. // see https://github.com/mishoo/UglifyJS2/issues/979
  1421. negated_is_best = true;
  1422. }
  1423. if (negated_is_best) return make_node(AST_SimpleStatement, self, {
  1424. body: make_node(AST_Binary, self, {
  1425. operator : "||",
  1426. left : negated,
  1427. right : self.body.body
  1428. })
  1429. }).optimize(compressor);
  1430. return make_node(AST_SimpleStatement, self, {
  1431. body: make_node(AST_Binary, self, {
  1432. operator : "&&",
  1433. left : self.condition,
  1434. right : self.body.body
  1435. })
  1436. }).optimize(compressor);
  1437. }
  1438. if (self.body instanceof AST_EmptyStatement
  1439. && self.alternative instanceof AST_SimpleStatement) {
  1440. return make_node(AST_SimpleStatement, self, {
  1441. body: make_node(AST_Binary, self, {
  1442. operator : "||",
  1443. left : self.condition,
  1444. right : self.alternative.body
  1445. })
  1446. }).optimize(compressor);
  1447. }
  1448. if (self.body instanceof AST_Exit
  1449. && self.alternative instanceof AST_Exit
  1450. && self.body.TYPE == self.alternative.TYPE) {
  1451. return make_node(self.body.CTOR, self, {
  1452. value: make_node(AST_Conditional, self, {
  1453. condition : self.condition,
  1454. consequent : self.body.value || make_node(AST_Undefined, self.body),
  1455. alternative : self.alternative.value || make_node(AST_Undefined, self.alternative)
  1456. }).transform(compressor)
  1457. }).optimize(compressor);
  1458. }
  1459. if (self.body instanceof AST_If
  1460. && !self.body.alternative
  1461. && !self.alternative) {
  1462. self = make_node(AST_If, self, {
  1463. condition: make_node(AST_Binary, self.condition, {
  1464. operator: "&&",
  1465. left: self.condition,
  1466. right: self.body.condition
  1467. }),
  1468. body: self.body.body,
  1469. alternative: null
  1470. });
  1471. }
  1472. if (aborts(self.body)) {
  1473. if (self.alternative) {
  1474. var alt = self.alternative;
  1475. self.alternative = null;
  1476. return make_node(AST_BlockStatement, self, {
  1477. body: [ self, alt ]
  1478. }).optimize(compressor);
  1479. }
  1480. }
  1481. if (aborts(self.alternative)) {
  1482. var body = self.body;
  1483. self.body = self.alternative;
  1484. self.condition = negated_is_best ? negated : self.condition.negate(compressor);
  1485. self.alternative = null;
  1486. return make_node(AST_BlockStatement, self, {
  1487. body: [ self, body ]
  1488. }).optimize(compressor);
  1489. }
  1490. return self;
  1491. });
  1492. def_optimize(AST_Switch, function(self, compressor) {
  1493. if (!compressor.option("switches")) return self;
  1494. var branch;
  1495. var value = self.expression.evaluate(compressor);
  1496. if (!(value instanceof AST_Node)) {
  1497. var orig = self.expression;
  1498. self.expression = make_node_from_constant(value, orig);
  1499. self.expression = best_of_expression(self.expression.transform(compressor), orig);
  1500. }
  1501. if (!compressor.option("dead_code")) return self;
  1502. if (value instanceof AST_Node) {
  1503. value = self.expression.tail_node().evaluate(compressor);
  1504. }
  1505. var decl = [];
  1506. var body = [];
  1507. var default_branch;
  1508. var exact_match;
  1509. for (var i = 0, len = self.body.length; i < len && !exact_match; i++) {
  1510. branch = self.body[i];
  1511. if (branch instanceof AST_Default) {
  1512. if (!default_branch) {
  1513. default_branch = branch;
  1514. } else {
  1515. eliminate_branch(branch, body[body.length - 1]);
  1516. }
  1517. } else if (!(value instanceof AST_Node)) {
  1518. var exp = branch.expression.evaluate(compressor);
  1519. if (!(exp instanceof AST_Node) && exp !== value) {
  1520. eliminate_branch(branch, body[body.length - 1]);
  1521. continue;
  1522. }
  1523. if (exp instanceof AST_Node) exp = branch.expression.tail_node().evaluate(compressor);
  1524. if (exp === value) {
  1525. exact_match = branch;
  1526. if (default_branch) {
  1527. var default_index = body.indexOf(default_branch);
  1528. body.splice(default_index, 1);
  1529. eliminate_branch(default_branch, body[default_index - 1]);
  1530. default_branch = null;
  1531. }
  1532. }
  1533. }
  1534. body.push(branch);
  1535. }
  1536. while (i < len) eliminate_branch(self.body[i++], body[body.length - 1]);
  1537. self.body = body;
  1538. let default_or_exact = default_branch || exact_match;
  1539. default_branch = null;
  1540. exact_match = null;
  1541. // group equivalent branches so they will be located next to each other,
  1542. // that way the next micro-optimization will merge them.
  1543. // ** bail micro-optimization if not a simple switch case with breaks
  1544. if (body.every((branch, i) =>
  1545. (branch === default_or_exact || branch.expression instanceof AST_Constant)
  1546. && (branch.body.length === 0 || aborts(branch) || body.length - 1 === i))
  1547. ) {
  1548. for (let i = 0; i < body.length; i++) {
  1549. const branch = body[i];
  1550. for (let j = i + 1; j < body.length; j++) {
  1551. const next = body[j];
  1552. if (next.body.length === 0) continue;
  1553. const last_branch = j === (body.length - 1);
  1554. const equivalentBranch = branches_equivalent(next, branch, false);
  1555. if (equivalentBranch || (last_branch && branches_equivalent(next, branch, true))) {
  1556. if (!equivalentBranch && last_branch) {
  1557. next.body.push(make_node(AST_Break));
  1558. }
  1559. // let's find previous siblings with inert fallthrough...
  1560. let x = j - 1;
  1561. let fallthroughDepth = 0;
  1562. while (x > i) {
  1563. if (is_inert_body(body[x--])) {
  1564. fallthroughDepth++;
  1565. } else {
  1566. break;
  1567. }
  1568. }
  1569. const plucked = body.splice(j - fallthroughDepth, 1 + fallthroughDepth);
  1570. body.splice(i + 1, 0, ...plucked);
  1571. i += plucked.length;
  1572. }
  1573. }
  1574. }
  1575. }
  1576. // merge equivalent branches in a row
  1577. for (let i = 0; i < body.length; i++) {
  1578. let branch = body[i];
  1579. if (branch.body.length === 0) continue;
  1580. if (!aborts(branch)) continue;
  1581. for (let j = i + 1; j < body.length; i++, j++) {
  1582. let next = body[j];
  1583. if (next.body.length === 0) continue;
  1584. if (
  1585. branches_equivalent(next, branch, false)
  1586. || (j === body.length - 1 && branches_equivalent(next, branch, true))
  1587. ) {
  1588. branch.body = [];
  1589. branch = next;
  1590. continue;
  1591. }
  1592. break;
  1593. }
  1594. }
  1595. // Prune any empty branches at the end of the switch statement.
  1596. {
  1597. let i = body.length - 1;
  1598. for (; i >= 0; i--) {
  1599. let bbody = body[i].body;
  1600. if (is_break(bbody[bbody.length - 1], compressor)) bbody.pop();
  1601. if (!is_inert_body(body[i])) break;
  1602. }
  1603. // i now points to the index of a branch that contains a body. By incrementing, it's
  1604. // pointing to the first branch that's empty.
  1605. i++;
  1606. if (!default_or_exact || body.indexOf(default_or_exact) >= i) {
  1607. // The default behavior is to do nothing. We can take advantage of that to
  1608. // remove all case expressions that are side-effect free that also do
  1609. // nothing, since they'll default to doing nothing. But we can't remove any
  1610. // case expressions before one that would side-effect, since they may cause
  1611. // the side-effect to be skipped.
  1612. for (let j = body.length - 1; j >= i; j--) {
  1613. let branch = body[j];
  1614. if (branch === default_or_exact) {
  1615. default_or_exact = null;
  1616. body.pop();
  1617. } else if (!branch.expression.has_side_effects(compressor)) {
  1618. body.pop();
  1619. } else {
  1620. break;
  1621. }
  1622. }
  1623. }
  1624. }
  1625. // Prune side-effect free branches that fall into default.
  1626. DEFAULT: if (default_or_exact) {
  1627. let default_index = body.indexOf(default_or_exact);
  1628. let default_body_index = default_index;
  1629. for (; default_body_index < body.length - 1; default_body_index++) {
  1630. if (!is_inert_body(body[default_body_index])) break;
  1631. }
  1632. if (default_body_index < body.length - 1) {
  1633. break DEFAULT;
  1634. }
  1635. let side_effect_index = body.length - 1;
  1636. for (; side_effect_index >= 0; side_effect_index--) {
  1637. let branch = body[side_effect_index];
  1638. if (branch === default_or_exact) continue;
  1639. if (branch.expression.has_side_effects(compressor)) break;
  1640. }
  1641. // If the default behavior comes after any side-effect case expressions,
  1642. // then we can fold all side-effect free cases into the default branch.
  1643. // If the side-effect case is after the default, then any side-effect
  1644. // free cases could prevent the side-effect from occurring.
  1645. if (default_body_index > side_effect_index) {
  1646. let prev_body_index = default_index - 1;
  1647. for (; prev_body_index >= 0; prev_body_index--) {
  1648. if (!is_inert_body(body[prev_body_index])) break;
  1649. }
  1650. let before = Math.max(side_effect_index, prev_body_index) + 1;
  1651. let after = default_index;
  1652. if (side_effect_index > default_index) {
  1653. // If the default falls into the same body as a side-effect
  1654. // case, then we need preserve that case and only prune the
  1655. // cases after it.
  1656. after = side_effect_index;
  1657. body[side_effect_index].body = body[default_body_index].body;
  1658. } else {
  1659. // The default will be the last branch.
  1660. default_or_exact.body = body[default_body_index].body;
  1661. }
  1662. // Prune everything after the default (or last side-effect case)
  1663. // until the next case with a body.
  1664. body.splice(after + 1, default_body_index - after);
  1665. // Prune everything before the default that falls into it.
  1666. body.splice(before, default_index - before);
  1667. }
  1668. }
  1669. // See if we can remove the switch entirely if all cases (the default) fall into the same case body.
  1670. DEFAULT: if (default_or_exact) {
  1671. let i = body.findIndex(branch => !is_inert_body(branch));
  1672. let caseBody;
  1673. // `i` is equal to one of the following:
  1674. // - `-1`, there is no body in the switch statement.
  1675. // - `body.length - 1`, all cases fall into the same body.
  1676. // - anything else, there are multiple bodies in the switch.
  1677. if (i === body.length - 1) {
  1678. // All cases fall into the case body.
  1679. let branch = body[i];
  1680. if (has_nested_break(self)) break DEFAULT;
  1681. // This is the last case body, and we've already pruned any breaks, so it's
  1682. // safe to hoist.
  1683. caseBody = make_node(AST_BlockStatement, branch, {
  1684. body: branch.body
  1685. });
  1686. branch.body = [];
  1687. } else if (i !== -1) {
  1688. // If there are multiple bodies, then we cannot optimize anything.
  1689. break DEFAULT;
  1690. }
  1691. let sideEffect = body.find(branch => {
  1692. return (
  1693. branch !== default_or_exact
  1694. && branch.expression.has_side_effects(compressor)
  1695. );
  1696. });
  1697. // If no cases cause a side-effect, we can eliminate the switch entirely.
  1698. if (!sideEffect) {
  1699. return make_node(AST_BlockStatement, self, {
  1700. body: decl.concat(
  1701. statement(self.expression),
  1702. default_or_exact.expression ? statement(default_or_exact.expression) : [],
  1703. caseBody || []
  1704. )
  1705. }).optimize(compressor);
  1706. }
  1707. // If we're this far, either there was no body or all cases fell into the same body.
  1708. // If there was no body, then we don't need a default branch (because the default is
  1709. // do nothing). If there was a body, we'll extract it to after the switch, so the
  1710. // switch's new default is to do nothing and we can still prune it.
  1711. const default_index = body.indexOf(default_or_exact);
  1712. body.splice(default_index, 1);
  1713. default_or_exact = null;
  1714. if (caseBody) {
  1715. // Recurse into switch statement one more time so that we can append the case body
  1716. // outside of the switch. This recursion will only happen once since we've pruned
  1717. // the default case.
  1718. return make_node(AST_BlockStatement, self, {
  1719. body: decl.concat(self, caseBody)
  1720. }).optimize(compressor);
  1721. }
  1722. // If we fall here, there is a default branch somewhere, there are no case bodies,
  1723. // and there's a side-effect somewhere. Just let the below paths take care of it.
  1724. }
  1725. if (body.length > 0) {
  1726. body[0].body = decl.concat(body[0].body);
  1727. }
  1728. if (body.length == 0) {
  1729. return make_node(AST_BlockStatement, self, {
  1730. body: decl.concat(statement(self.expression))
  1731. }).optimize(compressor);
  1732. }
  1733. if (body.length == 1 && !has_nested_break(self)) {
  1734. // This is the last case body, and we've already pruned any breaks, so it's
  1735. // safe to hoist.
  1736. let branch = body[0];
  1737. return make_node(AST_If, self, {
  1738. condition: make_node(AST_Binary, self, {
  1739. operator: "===",
  1740. left: self.expression,
  1741. right: branch.expression,
  1742. }),
  1743. body: make_node(AST_BlockStatement, branch, {
  1744. body: branch.body
  1745. }),
  1746. alternative: null
  1747. }).optimize(compressor);
  1748. }
  1749. if (body.length === 2 && default_or_exact && !has_nested_break(self)) {
  1750. let branch = body[0] === default_or_exact ? body[1] : body[0];
  1751. let exact_exp = default_or_exact.expression && statement(default_or_exact.expression);
  1752. if (aborts(body[0])) {
  1753. // Only the first branch body could have a break (at the last statement)
  1754. let first = body[0];
  1755. if (is_break(first.body[first.body.length - 1], compressor)) {
  1756. first.body.pop();
  1757. }
  1758. return make_node(AST_If, self, {
  1759. condition: make_node(AST_Binary, self, {
  1760. operator: "===",
  1761. left: self.expression,
  1762. right: branch.expression,
  1763. }),
  1764. body: make_node(AST_BlockStatement, branch, {
  1765. body: branch.body
  1766. }),
  1767. alternative: make_node(AST_BlockStatement, default_or_exact, {
  1768. body: [].concat(
  1769. exact_exp || [],
  1770. default_or_exact.body
  1771. )
  1772. })
  1773. }).optimize(compressor);
  1774. }
  1775. let operator = "===";
  1776. let consequent = make_node(AST_BlockStatement, branch, {
  1777. body: branch.body,
  1778. });
  1779. let always = make_node(AST_BlockStatement, default_or_exact, {
  1780. body: [].concat(
  1781. exact_exp || [],
  1782. default_or_exact.body
  1783. )
  1784. });
  1785. if (body[0] === default_or_exact) {
  1786. operator = "!==";
  1787. let tmp = always;
  1788. always = consequent;
  1789. consequent = tmp;
  1790. }
  1791. return make_node(AST_BlockStatement, self, {
  1792. body: [
  1793. make_node(AST_If, self, {
  1794. condition: make_node(AST_Binary, self, {
  1795. operator: operator,
  1796. left: self.expression,
  1797. right: branch.expression,
  1798. }),
  1799. body: consequent,
  1800. alternative: null
  1801. })
  1802. ].concat(always)
  1803. }).optimize(compressor);
  1804. }
  1805. return self;
  1806. function eliminate_branch(branch, prev) {
  1807. if (prev && !aborts(prev)) {
  1808. prev.body = prev.body.concat(branch.body);
  1809. } else {
  1810. trim_unreachable_code(compressor, branch, decl);
  1811. }
  1812. }
  1813. function branches_equivalent(branch, prev, insertBreak) {
  1814. let bbody = branch.body;
  1815. let pbody = prev.body;
  1816. if (insertBreak) {
  1817. bbody = bbody.concat(make_node(AST_Break));
  1818. }
  1819. if (bbody.length !== pbody.length) return false;
  1820. let bblock = make_node(AST_BlockStatement, branch, { body: bbody });
  1821. let pblock = make_node(AST_BlockStatement, prev, { body: pbody });
  1822. return bblock.equivalent_to(pblock);
  1823. }
  1824. function statement(expression) {
  1825. return make_node(AST_SimpleStatement, expression, {
  1826. body: expression
  1827. });
  1828. }
  1829. function has_nested_break(root) {
  1830. let has_break = false;
  1831. let tw = new TreeWalker(node => {
  1832. if (has_break) return true;
  1833. if (node instanceof AST_Lambda) return true;
  1834. if (node instanceof AST_SimpleStatement) return true;
  1835. if (!is_break(node, tw)) return;
  1836. let parent = tw.parent();
  1837. if (
  1838. parent instanceof AST_SwitchBranch
  1839. && parent.body[parent.body.length - 1] === node
  1840. ) {
  1841. return;
  1842. }
  1843. has_break = true;
  1844. });
  1845. root.walk(tw);
  1846. return has_break;
  1847. }
  1848. function is_break(node, stack) {
  1849. return node instanceof AST_Break
  1850. && stack.loopcontrol_target(node) === self;
  1851. }
  1852. function is_inert_body(branch) {
  1853. return !aborts(branch) && !make_node(AST_BlockStatement, branch, {
  1854. body: branch.body
  1855. }).has_side_effects(compressor);
  1856. }
  1857. });
  1858. def_optimize(AST_Try, function(self, compressor) {
  1859. tighten_body(self.body, compressor);
  1860. if (self.bcatch && self.bfinally && self.bfinally.body.every(is_empty)) self.bfinally = null;
  1861. if (compressor.option("dead_code") && self.body.every(is_empty)) {
  1862. var body = [];
  1863. if (self.bcatch) {
  1864. trim_unreachable_code(compressor, self.bcatch, body);
  1865. }
  1866. if (self.bfinally) body.push(...self.bfinally.body);
  1867. return make_node(AST_BlockStatement, self, {
  1868. body: body
  1869. }).optimize(compressor);
  1870. }
  1871. return self;
  1872. });
  1873. AST_Definitions.DEFMETHOD("remove_initializers", function() {
  1874. var decls = [];
  1875. this.definitions.forEach(function(def) {
  1876. if (def.name instanceof AST_SymbolDeclaration) {
  1877. def.value = null;
  1878. decls.push(def);
  1879. } else {
  1880. walk(def.name, node => {
  1881. if (node instanceof AST_SymbolDeclaration) {
  1882. decls.push(make_node(AST_VarDef, def, {
  1883. name: node,
  1884. value: null
  1885. }));
  1886. }
  1887. });
  1888. }
  1889. });
  1890. this.definitions = decls;
  1891. });
  1892. AST_Definitions.DEFMETHOD("to_assignments", function(compressor) {
  1893. var reduce_vars = compressor.option("reduce_vars");
  1894. var assignments = [];
  1895. for (const def of this.definitions) {
  1896. if (def.value) {
  1897. var name = make_node(AST_SymbolRef, def.name, def.name);
  1898. assignments.push(make_node(AST_Assign, def, {
  1899. operator : "=",
  1900. logical: false,
  1901. left : name,
  1902. right : def.value
  1903. }));
  1904. if (reduce_vars) name.definition().fixed = false;
  1905. } else if (def.value) {
  1906. // Because it's a destructuring, do not turn into an assignment.
  1907. var varDef = make_node(AST_VarDef, def, {
  1908. name: def.name,
  1909. value: def.value
  1910. });
  1911. var var_ = make_node(AST_Var, def, {
  1912. definitions: [ varDef ]
  1913. });
  1914. assignments.push(var_);
  1915. }
  1916. const thedef = def.name.definition();
  1917. thedef.eliminated++;
  1918. thedef.replaced--;
  1919. }
  1920. if (assignments.length == 0) return null;
  1921. return make_sequence(this, assignments);
  1922. });
  1923. def_optimize(AST_Definitions, function(self) {
  1924. if (self.definitions.length == 0)
  1925. return make_node(AST_EmptyStatement, self);
  1926. return self;
  1927. });
  1928. def_optimize(AST_VarDef, function(self, compressor) {
  1929. if (
  1930. self.name instanceof AST_SymbolLet
  1931. && self.value != null
  1932. && is_undefined(self.value, compressor)
  1933. ) {
  1934. self.value = null;
  1935. }
  1936. return self;
  1937. });
  1938. def_optimize(AST_Import, function(self) {
  1939. return self;
  1940. });
  1941. // TODO this only works with AST_Defun, shouldn't it work for other ways of defining functions?
  1942. function retain_top_func(fn, compressor) {
  1943. return compressor.top_retain
  1944. && fn instanceof AST_Defun
  1945. && has_flag(fn, TOP)
  1946. && fn.name
  1947. && compressor.top_retain(fn.name);
  1948. }
  1949. def_optimize(AST_Call, function(self, compressor) {
  1950. var exp = self.expression;
  1951. var fn = exp;
  1952. inline_array_like_spread(self.args);
  1953. var simple_args = self.args.every((arg) =>
  1954. !(arg instanceof AST_Expansion)
  1955. );
  1956. if (compressor.option("reduce_vars")
  1957. && fn instanceof AST_SymbolRef
  1958. && !has_annotation(self, _NOINLINE)
  1959. ) {
  1960. const fixed = fn.fixed_value();
  1961. if (!retain_top_func(fixed, compressor)) {
  1962. fn = fixed;
  1963. }
  1964. }
  1965. var is_func = fn instanceof AST_Lambda;
  1966. if (is_func && fn.pinned()) return self;
  1967. if (compressor.option("unused")
  1968. && simple_args
  1969. && is_func
  1970. && !fn.uses_arguments) {
  1971. var pos = 0, last = 0;
  1972. for (var i = 0, len = self.args.length; i < len; i++) {
  1973. if (fn.argnames[i] instanceof AST_Expansion) {
  1974. if (has_flag(fn.argnames[i].expression, UNUSED)) while (i < len) {
  1975. var node = self.args[i++].drop_side_effect_free(compressor);
  1976. if (node) {
  1977. self.args[pos++] = node;
  1978. }
  1979. } else while (i < len) {
  1980. self.args[pos++] = self.args[i++];
  1981. }
  1982. last = pos;
  1983. break;
  1984. }
  1985. var trim = i >= fn.argnames.length;
  1986. if (trim || has_flag(fn.argnames[i], UNUSED)) {
  1987. var node = self.args[i].drop_side_effect_free(compressor);
  1988. if (node) {
  1989. self.args[pos++] = node;
  1990. } else if (!trim) {
  1991. self.args[pos++] = make_node(AST_Number, self.args[i], {
  1992. value: 0
  1993. });
  1994. continue;
  1995. }
  1996. } else {
  1997. self.args[pos++] = self.args[i];
  1998. }
  1999. last = pos;
  2000. }
  2001. self.args.length = last;
  2002. }
  2003. if (compressor.option("unsafe")) {
  2004. if (exp instanceof AST_Dot && exp.start.value === "Array" && exp.property === "from" && self.args.length === 1) {
  2005. const [argument] = self.args;
  2006. if (argument instanceof AST_Array) {
  2007. return make_node(AST_Array, argument, {
  2008. elements: argument.elements
  2009. }).optimize(compressor);
  2010. }
  2011. }
  2012. if (is_undeclared_ref(exp)) switch (exp.name) {
  2013. case "Array":
  2014. if (self.args.length != 1) {
  2015. return make_node(AST_Array, self, {
  2016. elements: self.args
  2017. }).optimize(compressor);
  2018. } else if (self.args[0] instanceof AST_Number && self.args[0].value <= 11) {
  2019. const elements = [];
  2020. for (let i = 0; i < self.args[0].value; i++) elements.push(new AST_Hole);
  2021. return new AST_Array({ elements });
  2022. }
  2023. break;
  2024. case "Object":
  2025. if (self.args.length == 0) {
  2026. return make_node(AST_Object, self, {
  2027. properties: []
  2028. });
  2029. }
  2030. break;
  2031. case "String":
  2032. if (self.args.length == 0) return make_node(AST_String, self, {
  2033. value: ""
  2034. });
  2035. if (self.args.length <= 1) return make_node(AST_Binary, self, {
  2036. left: self.args[0],
  2037. operator: "+",
  2038. right: make_node(AST_String, self, { value: "" })
  2039. }).optimize(compressor);
  2040. break;
  2041. case "Number":
  2042. if (self.args.length == 0) return make_node(AST_Number, self, {
  2043. value: 0
  2044. });
  2045. if (self.args.length == 1 && compressor.option("unsafe_math")) {
  2046. return make_node(AST_UnaryPrefix, self, {
  2047. expression: self.args[0],
  2048. operator: "+"
  2049. }).optimize(compressor);
  2050. }
  2051. break;
  2052. case "Symbol":
  2053. if (self.args.length == 1 && self.args[0] instanceof AST_String && compressor.option("unsafe_symbols"))
  2054. self.args.length = 0;
  2055. break;
  2056. case "Boolean":
  2057. if (self.args.length == 0) return make_node(AST_False, self);
  2058. if (self.args.length == 1) return make_node(AST_UnaryPrefix, self, {
  2059. expression: make_node(AST_UnaryPrefix, self, {
  2060. expression: self.args[0],
  2061. operator: "!"
  2062. }),
  2063. operator: "!"
  2064. }).optimize(compressor);
  2065. break;
  2066. case "RegExp":
  2067. var params = [];
  2068. if (self.args.length >= 1
  2069. && self.args.length <= 2
  2070. && self.args.every((arg) => {
  2071. var value = arg.evaluate(compressor);
  2072. params.push(value);
  2073. return arg !== value;
  2074. })
  2075. ) {
  2076. let [ source, flags ] = params;
  2077. source = regexp_source_fix(new RegExp(source).source);
  2078. const rx = make_node(AST_RegExp, self, {
  2079. value: { source, flags }
  2080. });
  2081. if (rx._eval(compressor) !== rx) {
  2082. return rx;
  2083. }
  2084. }
  2085. break;
  2086. } else if (exp instanceof AST_Dot) switch(exp.property) {
  2087. case "toString":
  2088. if (self.args.length == 0 && !exp.expression.may_throw_on_access(compressor)) {
  2089. return make_node(AST_Binary, self, {
  2090. left: make_node(AST_String, self, { value: "" }),
  2091. operator: "+",
  2092. right: exp.expression
  2093. }).optimize(compressor);
  2094. }
  2095. break;
  2096. case "join":
  2097. if (exp.expression instanceof AST_Array) EXIT: {
  2098. var separator;
  2099. if (self.args.length > 0) {
  2100. separator = self.args[0].evaluate(compressor);
  2101. if (separator === self.args[0]) break EXIT; // not a constant
  2102. }
  2103. var elements = [];
  2104. var consts = [];
  2105. for (var i = 0, len = exp.expression.elements.length; i < len; i++) {
  2106. var el = exp.expression.elements[i];
  2107. if (el instanceof AST_Expansion) break EXIT;
  2108. var value = el.evaluate(compressor);
  2109. if (value !== el) {
  2110. consts.push(value);
  2111. } else {
  2112. if (consts.length > 0) {
  2113. elements.push(make_node(AST_String, self, {
  2114. value: consts.join(separator)
  2115. }));
  2116. consts.length = 0;
  2117. }
  2118. elements.push(el);
  2119. }
  2120. }
  2121. if (consts.length > 0) {
  2122. elements.push(make_node(AST_String, self, {
  2123. value: consts.join(separator)
  2124. }));
  2125. }
  2126. if (elements.length == 0) return make_node(AST_String, self, { value: "" });
  2127. if (elements.length == 1) {
  2128. if (elements[0].is_string(compressor)) {
  2129. return elements[0];
  2130. }
  2131. return make_node(AST_Binary, elements[0], {
  2132. operator : "+",
  2133. left : make_node(AST_String, self, { value: "" }),
  2134. right : elements[0]
  2135. });
  2136. }
  2137. if (separator == "") {
  2138. var first;
  2139. if (elements[0].is_string(compressor)
  2140. || elements[1].is_string(compressor)) {
  2141. first = elements.shift();
  2142. } else {
  2143. first = make_node(AST_String, self, { value: "" });
  2144. }
  2145. return elements.reduce(function(prev, el) {
  2146. return make_node(AST_Binary, el, {
  2147. operator : "+",
  2148. left : prev,
  2149. right : el
  2150. });
  2151. }, first).optimize(compressor);
  2152. }
  2153. // need this awkward cloning to not affect original element
  2154. // best_of will decide which one to get through.
  2155. var node = self.clone();
  2156. node.expression = node.expression.clone();
  2157. node.expression.expression = node.expression.expression.clone();
  2158. node.expression.expression.elements = elements;
  2159. return best_of(compressor, self, node);
  2160. }
  2161. break;
  2162. case "charAt":
  2163. if (exp.expression.is_string(compressor)) {
  2164. var arg = self.args[0];
  2165. var index = arg ? arg.evaluate(compressor) : 0;
  2166. if (index !== arg) {
  2167. return make_node(AST_Sub, exp, {
  2168. expression: exp.expression,
  2169. property: make_node_from_constant(index | 0, arg || exp)
  2170. }).optimize(compressor);
  2171. }
  2172. }
  2173. break;
  2174. case "apply":
  2175. if (self.args.length == 2 && self.args[1] instanceof AST_Array) {
  2176. var args = self.args[1].elements.slice();
  2177. args.unshift(self.args[0]);
  2178. return make_node(AST_Call, self, {
  2179. expression: make_node(AST_Dot, exp, {
  2180. expression: exp.expression,
  2181. optional: false,
  2182. property: "call"
  2183. }),
  2184. args: args
  2185. }).optimize(compressor);
  2186. }
  2187. break;
  2188. case "call":
  2189. var func = exp.expression;
  2190. if (func instanceof AST_SymbolRef) {
  2191. func = func.fixed_value();
  2192. }
  2193. if (func instanceof AST_Lambda && !func.contains_this()) {
  2194. return (self.args.length ? make_sequence(this, [
  2195. self.args[0],
  2196. make_node(AST_Call, self, {
  2197. expression: exp.expression,
  2198. args: self.args.slice(1)
  2199. })
  2200. ]) : make_node(AST_Call, self, {
  2201. expression: exp.expression,
  2202. args: []
  2203. })).optimize(compressor);
  2204. }
  2205. break;
  2206. }
  2207. }
  2208. if (compressor.option("unsafe_Function")
  2209. && is_undeclared_ref(exp)
  2210. && exp.name == "Function") {
  2211. // new Function() => function(){}
  2212. if (self.args.length == 0) return make_node(AST_Function, self, {
  2213. argnames: [],
  2214. body: []
  2215. }).optimize(compressor);
  2216. var nth_identifier = compressor.mangle_options && compressor.mangle_options.nth_identifier || base54;
  2217. if (self.args.every((x) => x instanceof AST_String)) {
  2218. // quite a corner-case, but we can handle it:
  2219. // https://github.com/mishoo/UglifyJS2/issues/203
  2220. // if the code argument is a constant, then we can minify it.
  2221. try {
  2222. var code = "n(function(" + self.args.slice(0, -1).map(function(arg) {
  2223. return arg.value;
  2224. }).join(",") + "){" + self.args[self.args.length - 1].value + "})";
  2225. var ast = parse(code);
  2226. var mangle = { ie8: compressor.option("ie8"), nth_identifier: nth_identifier };
  2227. ast.figure_out_scope(mangle);
  2228. var comp = new Compressor(compressor.options, {
  2229. mangle_options: compressor.mangle_options
  2230. });
  2231. ast = ast.transform(comp);
  2232. ast.figure_out_scope(mangle);
  2233. ast.compute_char_frequency(mangle);
  2234. ast.mangle_names(mangle);
  2235. var fun;
  2236. walk(ast, node => {
  2237. if (is_func_expr(node)) {
  2238. fun = node;
  2239. return walk_abort;
  2240. }
  2241. });
  2242. var code = OutputStream();
  2243. AST_BlockStatement.prototype._codegen.call(fun, fun, code);
  2244. self.args = [
  2245. make_node(AST_String, self, {
  2246. value: fun.argnames.map(function(arg) {
  2247. return arg.print_to_string();
  2248. }).join(",")
  2249. }),
  2250. make_node(AST_String, self.args[self.args.length - 1], {
  2251. value: code.get().replace(/^{|}$/g, "")
  2252. })
  2253. ];
  2254. return self;
  2255. } catch (ex) {
  2256. if (!(ex instanceof JS_Parse_Error)) {
  2257. throw ex;
  2258. }
  2259. // Otherwise, it crashes at runtime. Or maybe it's nonstandard syntax.
  2260. }
  2261. }
  2262. }
  2263. var stat = is_func && fn.body[0];
  2264. var is_regular_func = is_func && !fn.is_generator && !fn.async;
  2265. var can_inline = is_regular_func && compressor.option("inline") && !self.is_callee_pure(compressor);
  2266. if (can_inline && stat instanceof AST_Return) {
  2267. let returned = stat.value;
  2268. if (!returned || returned.is_constant_expression()) {
  2269. if (returned) {
  2270. returned = returned.clone(true);
  2271. } else {
  2272. returned = make_node(AST_Undefined, self);
  2273. }
  2274. const args = self.args.concat(returned);
  2275. return make_sequence(self, args).optimize(compressor);
  2276. }
  2277. // optimize identity function
  2278. if (
  2279. fn.argnames.length === 1
  2280. && (fn.argnames[0] instanceof AST_SymbolFunarg)
  2281. && self.args.length < 2
  2282. && returned instanceof AST_SymbolRef
  2283. && returned.name === fn.argnames[0].name
  2284. ) {
  2285. const replacement =
  2286. (self.args[0] || make_node(AST_Undefined)).optimize(compressor);
  2287. let parent;
  2288. if (
  2289. replacement instanceof AST_PropAccess
  2290. && (parent = compressor.parent()) instanceof AST_Call
  2291. && parent.expression === self
  2292. ) {
  2293. // identity function was being used to remove `this`, like in
  2294. //
  2295. // id(bag.no_this)(...)
  2296. //
  2297. // Replace with a larger but more effish (0, bag.no_this) wrapper.
  2298. return make_sequence(self, [
  2299. make_node(AST_Number, self, { value: 0 }),
  2300. replacement
  2301. ]);
  2302. }
  2303. // replace call with first argument or undefined if none passed
  2304. return replacement;
  2305. }
  2306. }
  2307. if (can_inline) {
  2308. var scope, in_loop, level = -1;
  2309. let def;
  2310. let returned_value;
  2311. let nearest_scope;
  2312. if (simple_args
  2313. && !fn.uses_arguments
  2314. && !(compressor.parent() instanceof AST_Class)
  2315. && !(fn.name && fn instanceof AST_Function)
  2316. && (returned_value = can_flatten_body(stat))
  2317. && (exp === fn
  2318. || has_annotation(self, _INLINE)
  2319. || compressor.option("unused")
  2320. && (def = exp.definition()).references.length == 1
  2321. && !is_recursive_ref(compressor, def)
  2322. && fn.is_constant_expression(exp.scope))
  2323. && !has_annotation(self, _PURE | _NOINLINE)
  2324. && !fn.contains_this()
  2325. && can_inject_symbols()
  2326. && (nearest_scope = find_scope(compressor))
  2327. && !scope_encloses_variables_in_this_scope(nearest_scope, fn)
  2328. && !(function in_default_assign() {
  2329. // Due to the fact function parameters have their own scope
  2330. // which can't use `var something` in the function body within,
  2331. // we simply don't inline into DefaultAssign.
  2332. let i = 0;
  2333. let p;
  2334. while ((p = compressor.parent(i++))) {
  2335. if (p instanceof AST_DefaultAssign) return true;
  2336. if (p instanceof AST_Block) break;
  2337. }
  2338. return false;
  2339. })()
  2340. && !(scope instanceof AST_Class)
  2341. ) {
  2342. set_flag(fn, SQUEEZED);
  2343. nearest_scope.add_child_scope(fn);
  2344. return make_sequence(self, flatten_fn(returned_value)).optimize(compressor);
  2345. }
  2346. }
  2347. if (can_inline && has_annotation(self, _INLINE)) {
  2348. set_flag(fn, SQUEEZED);
  2349. fn = make_node(fn.CTOR === AST_Defun ? AST_Function : fn.CTOR, fn, fn);
  2350. fn = fn.clone(true);
  2351. fn.figure_out_scope({}, {
  2352. parent_scope: find_scope(compressor),
  2353. toplevel: compressor.get_toplevel()
  2354. });
  2355. return make_node(AST_Call, self, {
  2356. expression: fn,
  2357. args: self.args,
  2358. }).optimize(compressor);
  2359. }
  2360. const can_drop_this_call = is_regular_func && compressor.option("side_effects") && fn.body.every(is_empty);
  2361. if (can_drop_this_call) {
  2362. var args = self.args.concat(make_node(AST_Undefined, self));
  2363. return make_sequence(self, args).optimize(compressor);
  2364. }
  2365. if (compressor.option("negate_iife")
  2366. && compressor.parent() instanceof AST_SimpleStatement
  2367. && is_iife_call(self)) {
  2368. return self.negate(compressor, true);
  2369. }
  2370. var ev = self.evaluate(compressor);
  2371. if (ev !== self) {
  2372. ev = make_node_from_constant(ev, self).optimize(compressor);
  2373. return best_of(compressor, ev, self);
  2374. }
  2375. return self;
  2376. function return_value(stat) {
  2377. if (!stat) return make_node(AST_Undefined, self);
  2378. if (stat instanceof AST_Return) {
  2379. if (!stat.value) return make_node(AST_Undefined, self);
  2380. return stat.value.clone(true);
  2381. }
  2382. if (stat instanceof AST_SimpleStatement) {
  2383. return make_node(AST_UnaryPrefix, stat, {
  2384. operator: "void",
  2385. expression: stat.body.clone(true)
  2386. });
  2387. }
  2388. }
  2389. function can_flatten_body(stat) {
  2390. var body = fn.body;
  2391. var len = body.length;
  2392. if (compressor.option("inline") < 3) {
  2393. return len == 1 && return_value(stat);
  2394. }
  2395. stat = null;
  2396. for (var i = 0; i < len; i++) {
  2397. var line = body[i];
  2398. if (line instanceof AST_Var) {
  2399. if (stat && !line.definitions.every((var_def) =>
  2400. !var_def.value
  2401. )) {
  2402. return false;
  2403. }
  2404. } else if (stat) {
  2405. return false;
  2406. } else if (!(line instanceof AST_EmptyStatement)) {
  2407. stat = line;
  2408. }
  2409. }
  2410. return return_value(stat);
  2411. }
  2412. function can_inject_args(block_scoped, safe_to_inject) {
  2413. for (var i = 0, len = fn.argnames.length; i < len; i++) {
  2414. var arg = fn.argnames[i];
  2415. if (arg instanceof AST_DefaultAssign) {
  2416. if (has_flag(arg.left, UNUSED)) continue;
  2417. return false;
  2418. }
  2419. if (arg instanceof AST_Destructuring) return false;
  2420. if (arg instanceof AST_Expansion) {
  2421. if (has_flag(arg.expression, UNUSED)) continue;
  2422. return false;
  2423. }
  2424. if (has_flag(arg, UNUSED)) continue;
  2425. if (!safe_to_inject
  2426. || block_scoped.has(arg.name)
  2427. || identifier_atom.has(arg.name)
  2428. || scope.conflicting_def(arg.name)) {
  2429. return false;
  2430. }
  2431. if (in_loop) in_loop.push(arg.definition());
  2432. }
  2433. return true;
  2434. }
  2435. function can_inject_vars(block_scoped, safe_to_inject) {
  2436. var len = fn.body.length;
  2437. for (var i = 0; i < len; i++) {
  2438. var stat = fn.body[i];
  2439. if (!(stat instanceof AST_Var)) continue;
  2440. if (!safe_to_inject) return false;
  2441. for (var j = stat.definitions.length; --j >= 0;) {
  2442. var name = stat.definitions[j].name;
  2443. if (name instanceof AST_Destructuring
  2444. || block_scoped.has(name.name)
  2445. || identifier_atom.has(name.name)
  2446. || scope.conflicting_def(name.name)) {
  2447. return false;
  2448. }
  2449. if (in_loop) in_loop.push(name.definition());
  2450. }
  2451. }
  2452. return true;
  2453. }
  2454. function can_inject_symbols() {
  2455. var block_scoped = new Set();
  2456. do {
  2457. scope = compressor.parent(++level);
  2458. if (scope.is_block_scope() && scope.block_scope) {
  2459. // TODO this is sometimes undefined during compression.
  2460. // But it should always have a value!
  2461. scope.block_scope.variables.forEach(function (variable) {
  2462. block_scoped.add(variable.name);
  2463. });
  2464. }
  2465. if (scope instanceof AST_Catch) {
  2466. // TODO can we delete? AST_Catch is a block scope.
  2467. if (scope.argname) {
  2468. block_scoped.add(scope.argname.name);
  2469. }
  2470. } else if (scope instanceof AST_IterationStatement) {
  2471. in_loop = [];
  2472. } else if (scope instanceof AST_SymbolRef) {
  2473. if (scope.fixed_value() instanceof AST_Scope) return false;
  2474. }
  2475. } while (!(scope instanceof AST_Scope));
  2476. var safe_to_inject = !(scope instanceof AST_Toplevel) || compressor.toplevel.vars;
  2477. var inline = compressor.option("inline");
  2478. if (!can_inject_vars(block_scoped, inline >= 3 && safe_to_inject)) return false;
  2479. if (!can_inject_args(block_scoped, inline >= 2 && safe_to_inject)) return false;
  2480. return !in_loop || in_loop.length == 0 || !is_reachable(fn, in_loop);
  2481. }
  2482. function append_var(decls, expressions, name, value) {
  2483. var def = name.definition();
  2484. // Name already exists, only when a function argument had the same name
  2485. const already_appended = scope.variables.has(name.name);
  2486. if (!already_appended) {
  2487. scope.variables.set(name.name, def);
  2488. scope.enclosed.push(def);
  2489. decls.push(make_node(AST_VarDef, name, {
  2490. name: name,
  2491. value: null
  2492. }));
  2493. }
  2494. var sym = make_node(AST_SymbolRef, name, name);
  2495. def.references.push(sym);
  2496. if (value) expressions.push(make_node(AST_Assign, self, {
  2497. operator: "=",
  2498. logical: false,
  2499. left: sym,
  2500. right: value.clone()
  2501. }));
  2502. }
  2503. function flatten_args(decls, expressions) {
  2504. var len = fn.argnames.length;
  2505. for (var i = self.args.length; --i >= len;) {
  2506. expressions.push(self.args[i]);
  2507. }
  2508. for (i = len; --i >= 0;) {
  2509. var name = fn.argnames[i];
  2510. var value = self.args[i];
  2511. if (has_flag(name, UNUSED) || !name.name || scope.conflicting_def(name.name)) {
  2512. if (value) expressions.push(value);
  2513. } else {
  2514. var symbol = make_node(AST_SymbolVar, name, name);
  2515. name.definition().orig.push(symbol);
  2516. if (!value && in_loop) value = make_node(AST_Undefined, self);
  2517. append_var(decls, expressions, symbol, value);
  2518. }
  2519. }
  2520. decls.reverse();
  2521. expressions.reverse();
  2522. }
  2523. function flatten_vars(decls, expressions) {
  2524. var pos = expressions.length;
  2525. for (var i = 0, lines = fn.body.length; i < lines; i++) {
  2526. var stat = fn.body[i];
  2527. if (!(stat instanceof AST_Var)) continue;
  2528. for (var j = 0, defs = stat.definitions.length; j < defs; j++) {
  2529. var var_def = stat.definitions[j];
  2530. var name = var_def.name;
  2531. append_var(decls, expressions, name, var_def.value);
  2532. if (in_loop && fn.argnames.every((argname) =>
  2533. argname.name != name.name
  2534. )) {
  2535. var def = fn.variables.get(name.name);
  2536. var sym = make_node(AST_SymbolRef, name, name);
  2537. def.references.push(sym);
  2538. expressions.splice(pos++, 0, make_node(AST_Assign, var_def, {
  2539. operator: "=",
  2540. logical: false,
  2541. left: sym,
  2542. right: make_node(AST_Undefined, name)
  2543. }));
  2544. }
  2545. }
  2546. }
  2547. }
  2548. function flatten_fn(returned_value) {
  2549. var decls = [];
  2550. var expressions = [];
  2551. flatten_args(decls, expressions);
  2552. flatten_vars(decls, expressions);
  2553. expressions.push(returned_value);
  2554. if (decls.length) {
  2555. const i = scope.body.indexOf(compressor.parent(level - 1)) + 1;
  2556. scope.body.splice(i, 0, make_node(AST_Var, fn, {
  2557. definitions: decls
  2558. }));
  2559. }
  2560. return expressions.map(exp => exp.clone(true));
  2561. }
  2562. });
  2563. def_optimize(AST_New, function(self, compressor) {
  2564. if (
  2565. compressor.option("unsafe") &&
  2566. is_undeclared_ref(self.expression) &&
  2567. ["Object", "RegExp", "Function", "Error", "Array"].includes(self.expression.name)
  2568. ) return make_node(AST_Call, self, self).transform(compressor);
  2569. return self;
  2570. });
  2571. def_optimize(AST_Sequence, function(self, compressor) {
  2572. if (!compressor.option("side_effects")) return self;
  2573. var expressions = [];
  2574. filter_for_side_effects();
  2575. var end = expressions.length - 1;
  2576. trim_right_for_undefined();
  2577. if (end == 0) {
  2578. self = maintain_this_binding(compressor.parent(), compressor.self(), expressions[0]);
  2579. if (!(self instanceof AST_Sequence)) self = self.optimize(compressor);
  2580. return self;
  2581. }
  2582. self.expressions = expressions;
  2583. return self;
  2584. function filter_for_side_effects() {
  2585. var first = first_in_statement(compressor);
  2586. var last = self.expressions.length - 1;
  2587. self.expressions.forEach(function(expr, index) {
  2588. if (index < last) expr = expr.drop_side_effect_free(compressor, first);
  2589. if (expr) {
  2590. merge_sequence(expressions, expr);
  2591. first = false;
  2592. }
  2593. });
  2594. }
  2595. function trim_right_for_undefined() {
  2596. while (end > 0 && is_undefined(expressions[end], compressor)) end--;
  2597. if (end < expressions.length - 1) {
  2598. expressions[end] = make_node(AST_UnaryPrefix, self, {
  2599. operator : "void",
  2600. expression : expressions[end]
  2601. });
  2602. expressions.length = end + 1;
  2603. }
  2604. }
  2605. });
  2606. AST_Unary.DEFMETHOD("lift_sequences", function(compressor) {
  2607. if (compressor.option("sequences")) {
  2608. if (this.expression instanceof AST_Sequence) {
  2609. var x = this.expression.expressions.slice();
  2610. var e = this.clone();
  2611. e.expression = x.pop();
  2612. x.push(e);
  2613. return make_sequence(this, x).optimize(compressor);
  2614. }
  2615. }
  2616. return this;
  2617. });
  2618. def_optimize(AST_UnaryPostfix, function(self, compressor) {
  2619. return self.lift_sequences(compressor);
  2620. });
  2621. def_optimize(AST_UnaryPrefix, function(self, compressor) {
  2622. var e = self.expression;
  2623. if (
  2624. self.operator == "delete" &&
  2625. !(
  2626. e instanceof AST_SymbolRef ||
  2627. e instanceof AST_PropAccess ||
  2628. e instanceof AST_Chain ||
  2629. is_identifier_atom(e)
  2630. )
  2631. ) {
  2632. return make_sequence(self, [e, make_node(AST_True, self)]).optimize(compressor);
  2633. }
  2634. var seq = self.lift_sequences(compressor);
  2635. if (seq !== self) {
  2636. return seq;
  2637. }
  2638. if (compressor.option("side_effects") && self.operator == "void") {
  2639. e = e.drop_side_effect_free(compressor);
  2640. if (e) {
  2641. self.expression = e;
  2642. return self;
  2643. } else {
  2644. return make_node(AST_Undefined, self).optimize(compressor);
  2645. }
  2646. }
  2647. if (compressor.in_boolean_context()) {
  2648. switch (self.operator) {
  2649. case "!":
  2650. if (e instanceof AST_UnaryPrefix && e.operator == "!") {
  2651. // !!foo ==> foo, if we're in boolean context
  2652. return e.expression;
  2653. }
  2654. if (e instanceof AST_Binary) {
  2655. self = best_of(compressor, self, e.negate(compressor, first_in_statement(compressor)));
  2656. }
  2657. break;
  2658. case "typeof":
  2659. // typeof always returns a non-empty string, thus it's
  2660. // always true in booleans
  2661. // And we don't need to check if it's undeclared, because in typeof, that's OK
  2662. return (e instanceof AST_SymbolRef ? make_node(AST_True, self) : make_sequence(self, [
  2663. e,
  2664. make_node(AST_True, self)
  2665. ])).optimize(compressor);
  2666. }
  2667. }
  2668. if (self.operator == "-" && e instanceof AST_Infinity) {
  2669. e = e.transform(compressor);
  2670. }
  2671. if (e instanceof AST_Binary
  2672. && (self.operator == "+" || self.operator == "-")
  2673. && (e.operator == "*" || e.operator == "/" || e.operator == "%")) {
  2674. return make_node(AST_Binary, self, {
  2675. operator: e.operator,
  2676. left: make_node(AST_UnaryPrefix, e.left, {
  2677. operator: self.operator,
  2678. expression: e.left
  2679. }),
  2680. right: e.right
  2681. });
  2682. }
  2683. // avoids infinite recursion of numerals
  2684. if (self.operator != "-"
  2685. || !(e instanceof AST_Number || e instanceof AST_Infinity || e instanceof AST_BigInt)) {
  2686. var ev = self.evaluate(compressor);
  2687. if (ev !== self) {
  2688. ev = make_node_from_constant(ev, self).optimize(compressor);
  2689. return best_of(compressor, ev, self);
  2690. }
  2691. }
  2692. return self;
  2693. });
  2694. AST_Binary.DEFMETHOD("lift_sequences", function(compressor) {
  2695. if (compressor.option("sequences")) {
  2696. if (this.left instanceof AST_Sequence) {
  2697. var x = this.left.expressions.slice();
  2698. var e = this.clone();
  2699. e.left = x.pop();
  2700. x.push(e);
  2701. return make_sequence(this, x).optimize(compressor);
  2702. }
  2703. if (this.right instanceof AST_Sequence && !this.left.has_side_effects(compressor)) {
  2704. var assign = this.operator == "=" && this.left instanceof AST_SymbolRef;
  2705. var x = this.right.expressions;
  2706. var last = x.length - 1;
  2707. for (var i = 0; i < last; i++) {
  2708. if (!assign && x[i].has_side_effects(compressor)) break;
  2709. }
  2710. if (i == last) {
  2711. x = x.slice();
  2712. var e = this.clone();
  2713. e.right = x.pop();
  2714. x.push(e);
  2715. return make_sequence(this, x).optimize(compressor);
  2716. } else if (i > 0) {
  2717. var e = this.clone();
  2718. e.right = make_sequence(this.right, x.slice(i));
  2719. x = x.slice(0, i);
  2720. x.push(e);
  2721. return make_sequence(this, x).optimize(compressor);
  2722. }
  2723. }
  2724. }
  2725. return this;
  2726. });
  2727. var commutativeOperators = makePredicate("== === != !== * & | ^");
  2728. function is_object(node) {
  2729. return node instanceof AST_Array
  2730. || node instanceof AST_Lambda
  2731. || node instanceof AST_Object
  2732. || node instanceof AST_Class;
  2733. }
  2734. def_optimize(AST_Binary, function(self, compressor) {
  2735. function reversible() {
  2736. return self.left.is_constant()
  2737. || self.right.is_constant()
  2738. || !self.left.has_side_effects(compressor)
  2739. && !self.right.has_side_effects(compressor);
  2740. }
  2741. function reverse(op) {
  2742. if (reversible()) {
  2743. if (op) self.operator = op;
  2744. var tmp = self.left;
  2745. self.left = self.right;
  2746. self.right = tmp;
  2747. }
  2748. }
  2749. if (commutativeOperators.has(self.operator)) {
  2750. if (self.right.is_constant()
  2751. && !self.left.is_constant()) {
  2752. // if right is a constant, whatever side effects the
  2753. // left side might have could not influence the
  2754. // result. hence, force switch.
  2755. if (!(self.left instanceof AST_Binary
  2756. && PRECEDENCE[self.left.operator] >= PRECEDENCE[self.operator])) {
  2757. reverse();
  2758. }
  2759. }
  2760. }
  2761. self = self.lift_sequences(compressor);
  2762. if (compressor.option("comparisons")) switch (self.operator) {
  2763. case "===":
  2764. case "!==":
  2765. var is_strict_comparison = true;
  2766. if ((self.left.is_string(compressor) && self.right.is_string(compressor)) ||
  2767. (self.left.is_number(compressor) && self.right.is_number(compressor)) ||
  2768. (self.left.is_boolean() && self.right.is_boolean()) ||
  2769. self.left.equivalent_to(self.right)) {
  2770. self.operator = self.operator.substr(0, 2);
  2771. }
  2772. // XXX: intentionally falling down to the next case
  2773. case "==":
  2774. case "!=":
  2775. // void 0 == x => null == x
  2776. if (!is_strict_comparison && is_undefined(self.left, compressor)) {
  2777. self.left = make_node(AST_Null, self.left);
  2778. } else if (compressor.option("typeofs")
  2779. // "undefined" == typeof x => undefined === x
  2780. && self.left instanceof AST_String
  2781. && self.left.value == "undefined"
  2782. && self.right instanceof AST_UnaryPrefix
  2783. && self.right.operator == "typeof") {
  2784. var expr = self.right.expression;
  2785. if (expr instanceof AST_SymbolRef ? expr.is_declared(compressor)
  2786. : !(expr instanceof AST_PropAccess && compressor.option("ie8"))) {
  2787. self.right = expr;
  2788. self.left = make_node(AST_Undefined, self.left).optimize(compressor);
  2789. if (self.operator.length == 2) self.operator += "=";
  2790. }
  2791. } else if (self.left instanceof AST_SymbolRef
  2792. // obj !== obj => false
  2793. && self.right instanceof AST_SymbolRef
  2794. && self.left.definition() === self.right.definition()
  2795. && is_object(self.left.fixed_value())) {
  2796. return make_node(self.operator[0] == "=" ? AST_True : AST_False, self);
  2797. }
  2798. break;
  2799. case "&&":
  2800. case "||":
  2801. var lhs = self.left;
  2802. if (lhs.operator == self.operator) {
  2803. lhs = lhs.right;
  2804. }
  2805. if (lhs instanceof AST_Binary
  2806. && lhs.operator == (self.operator == "&&" ? "!==" : "===")
  2807. && self.right instanceof AST_Binary
  2808. && lhs.operator == self.right.operator
  2809. && (is_undefined(lhs.left, compressor) && self.right.left instanceof AST_Null
  2810. || lhs.left instanceof AST_Null && is_undefined(self.right.left, compressor))
  2811. && !lhs.right.has_side_effects(compressor)
  2812. && lhs.right.equivalent_to(self.right.right)) {
  2813. var combined = make_node(AST_Binary, self, {
  2814. operator: lhs.operator.slice(0, -1),
  2815. left: make_node(AST_Null, self),
  2816. right: lhs.right
  2817. });
  2818. if (lhs !== self.left) {
  2819. combined = make_node(AST_Binary, self, {
  2820. operator: self.operator,
  2821. left: self.left.left,
  2822. right: combined
  2823. });
  2824. }
  2825. return combined;
  2826. }
  2827. break;
  2828. }
  2829. if (self.operator == "+" && compressor.in_boolean_context()) {
  2830. var ll = self.left.evaluate(compressor);
  2831. var rr = self.right.evaluate(compressor);
  2832. if (ll && typeof ll == "string") {
  2833. return make_sequence(self, [
  2834. self.right,
  2835. make_node(AST_True, self)
  2836. ]).optimize(compressor);
  2837. }
  2838. if (rr && typeof rr == "string") {
  2839. return make_sequence(self, [
  2840. self.left,
  2841. make_node(AST_True, self)
  2842. ]).optimize(compressor);
  2843. }
  2844. }
  2845. if (compressor.option("comparisons") && self.is_boolean()) {
  2846. if (!(compressor.parent() instanceof AST_Binary)
  2847. || compressor.parent() instanceof AST_Assign) {
  2848. var negated = make_node(AST_UnaryPrefix, self, {
  2849. operator: "!",
  2850. expression: self.negate(compressor, first_in_statement(compressor))
  2851. });
  2852. self = best_of(compressor, self, negated);
  2853. }
  2854. if (compressor.option("unsafe_comps")) {
  2855. switch (self.operator) {
  2856. case "<": reverse(">"); break;
  2857. case "<=": reverse(">="); break;
  2858. }
  2859. }
  2860. }
  2861. if (self.operator == "+") {
  2862. if (self.right instanceof AST_String
  2863. && self.right.getValue() == ""
  2864. && self.left.is_string(compressor)) {
  2865. return self.left;
  2866. }
  2867. if (self.left instanceof AST_String
  2868. && self.left.getValue() == ""
  2869. && self.right.is_string(compressor)) {
  2870. return self.right;
  2871. }
  2872. if (self.left instanceof AST_Binary
  2873. && self.left.operator == "+"
  2874. && self.left.left instanceof AST_String
  2875. && self.left.left.getValue() == ""
  2876. && self.right.is_string(compressor)) {
  2877. self.left = self.left.right;
  2878. return self;
  2879. }
  2880. }
  2881. if (compressor.option("evaluate")) {
  2882. switch (self.operator) {
  2883. case "&&":
  2884. var ll = has_flag(self.left, TRUTHY)
  2885. ? true
  2886. : has_flag(self.left, FALSY)
  2887. ? false
  2888. : self.left.evaluate(compressor);
  2889. if (!ll) {
  2890. return maintain_this_binding(compressor.parent(), compressor.self(), self.left).optimize(compressor);
  2891. } else if (!(ll instanceof AST_Node)) {
  2892. return make_sequence(self, [ self.left, self.right ]).optimize(compressor);
  2893. }
  2894. var rr = self.right.evaluate(compressor);
  2895. if (!rr) {
  2896. if (compressor.in_boolean_context()) {
  2897. return make_sequence(self, [
  2898. self.left,
  2899. make_node(AST_False, self)
  2900. ]).optimize(compressor);
  2901. } else {
  2902. set_flag(self, FALSY);
  2903. }
  2904. } else if (!(rr instanceof AST_Node)) {
  2905. var parent = compressor.parent();
  2906. if (parent.operator == "&&" && parent.left === compressor.self() || compressor.in_boolean_context()) {
  2907. return self.left.optimize(compressor);
  2908. }
  2909. }
  2910. // x || false && y ---> x ? y : false
  2911. if (self.left.operator == "||") {
  2912. var lr = self.left.right.evaluate(compressor);
  2913. if (!lr) return make_node(AST_Conditional, self, {
  2914. condition: self.left.left,
  2915. consequent: self.right,
  2916. alternative: self.left.right
  2917. }).optimize(compressor);
  2918. }
  2919. break;
  2920. case "||":
  2921. var ll = has_flag(self.left, TRUTHY)
  2922. ? true
  2923. : has_flag(self.left, FALSY)
  2924. ? false
  2925. : self.left.evaluate(compressor);
  2926. if (!ll) {
  2927. return make_sequence(self, [ self.left, self.right ]).optimize(compressor);
  2928. } else if (!(ll instanceof AST_Node)) {
  2929. return maintain_this_binding(compressor.parent(), compressor.self(), self.left).optimize(compressor);
  2930. }
  2931. var rr = self.right.evaluate(compressor);
  2932. if (!rr) {
  2933. var parent = compressor.parent();
  2934. if (parent.operator == "||" && parent.left === compressor.self() || compressor.in_boolean_context()) {
  2935. return self.left.optimize(compressor);
  2936. }
  2937. } else if (!(rr instanceof AST_Node)) {
  2938. if (compressor.in_boolean_context()) {
  2939. return make_sequence(self, [
  2940. self.left,
  2941. make_node(AST_True, self)
  2942. ]).optimize(compressor);
  2943. } else {
  2944. set_flag(self, TRUTHY);
  2945. }
  2946. }
  2947. if (self.left.operator == "&&") {
  2948. var lr = self.left.right.evaluate(compressor);
  2949. if (lr && !(lr instanceof AST_Node)) return make_node(AST_Conditional, self, {
  2950. condition: self.left.left,
  2951. consequent: self.left.right,
  2952. alternative: self.right
  2953. }).optimize(compressor);
  2954. }
  2955. break;
  2956. case "??":
  2957. if (is_nullish(self.left, compressor)) {
  2958. return self.right;
  2959. }
  2960. var ll = self.left.evaluate(compressor);
  2961. if (!(ll instanceof AST_Node)) {
  2962. // if we know the value for sure we can simply compute right away.
  2963. return ll == null ? self.right : self.left;
  2964. }
  2965. if (compressor.in_boolean_context()) {
  2966. const rr = self.right.evaluate(compressor);
  2967. if (!(rr instanceof AST_Node) && !rr) {
  2968. return self.left;
  2969. }
  2970. }
  2971. }
  2972. var associative = true;
  2973. switch (self.operator) {
  2974. case "+":
  2975. // (x + "foo") + "bar" => x + "foobar"
  2976. if (self.right instanceof AST_Constant
  2977. && self.left instanceof AST_Binary
  2978. && self.left.operator == "+"
  2979. && self.left.is_string(compressor)) {
  2980. var binary = make_node(AST_Binary, self, {
  2981. operator: "+",
  2982. left: self.left.right,
  2983. right: self.right,
  2984. });
  2985. var r = binary.optimize(compressor);
  2986. if (binary !== r) {
  2987. self = make_node(AST_Binary, self, {
  2988. operator: "+",
  2989. left: self.left.left,
  2990. right: r
  2991. });
  2992. }
  2993. }
  2994. // (x + "foo") + ("bar" + y) => (x + "foobar") + y
  2995. if (self.left instanceof AST_Binary
  2996. && self.left.operator == "+"
  2997. && self.left.is_string(compressor)
  2998. && self.right instanceof AST_Binary
  2999. && self.right.operator == "+"
  3000. && self.right.is_string(compressor)) {
  3001. var binary = make_node(AST_Binary, self, {
  3002. operator: "+",
  3003. left: self.left.right,
  3004. right: self.right.left,
  3005. });
  3006. var m = binary.optimize(compressor);
  3007. if (binary !== m) {
  3008. self = make_node(AST_Binary, self, {
  3009. operator: "+",
  3010. left: make_node(AST_Binary, self.left, {
  3011. operator: "+",
  3012. left: self.left.left,
  3013. right: m
  3014. }),
  3015. right: self.right.right
  3016. });
  3017. }
  3018. }
  3019. // a + -b => a - b
  3020. if (self.right instanceof AST_UnaryPrefix
  3021. && self.right.operator == "-"
  3022. && self.left.is_number(compressor)) {
  3023. self = make_node(AST_Binary, self, {
  3024. operator: "-",
  3025. left: self.left,
  3026. right: self.right.expression
  3027. });
  3028. break;
  3029. }
  3030. // -a + b => b - a
  3031. if (self.left instanceof AST_UnaryPrefix
  3032. && self.left.operator == "-"
  3033. && reversible()
  3034. && self.right.is_number(compressor)) {
  3035. self = make_node(AST_Binary, self, {
  3036. operator: "-",
  3037. left: self.right,
  3038. right: self.left.expression
  3039. });
  3040. break;
  3041. }
  3042. // `foo${bar}baz` + 1 => `foo${bar}baz1`
  3043. if (self.left instanceof AST_TemplateString) {
  3044. var l = self.left;
  3045. var r = self.right.evaluate(compressor);
  3046. if (r != self.right) {
  3047. l.segments[l.segments.length - 1].value += String(r);
  3048. return l;
  3049. }
  3050. }
  3051. // 1 + `foo${bar}baz` => `1foo${bar}baz`
  3052. if (self.right instanceof AST_TemplateString) {
  3053. var r = self.right;
  3054. var l = self.left.evaluate(compressor);
  3055. if (l != self.left) {
  3056. r.segments[0].value = String(l) + r.segments[0].value;
  3057. return r;
  3058. }
  3059. }
  3060. // `1${bar}2` + `foo${bar}baz` => `1${bar}2foo${bar}baz`
  3061. if (self.left instanceof AST_TemplateString
  3062. && self.right instanceof AST_TemplateString) {
  3063. var l = self.left;
  3064. var segments = l.segments;
  3065. var r = self.right;
  3066. segments[segments.length - 1].value += r.segments[0].value;
  3067. for (var i = 1; i < r.segments.length; i++) {
  3068. segments.push(r.segments[i]);
  3069. }
  3070. return l;
  3071. }
  3072. case "*":
  3073. associative = compressor.option("unsafe_math");
  3074. case "&":
  3075. case "|":
  3076. case "^":
  3077. // a + +b => +b + a
  3078. if (self.left.is_number(compressor)
  3079. && self.right.is_number(compressor)
  3080. && reversible()
  3081. && !(self.left instanceof AST_Binary
  3082. && self.left.operator != self.operator
  3083. && PRECEDENCE[self.left.operator] >= PRECEDENCE[self.operator])) {
  3084. var reversed = make_node(AST_Binary, self, {
  3085. operator: self.operator,
  3086. left: self.right,
  3087. right: self.left
  3088. });
  3089. if (self.right instanceof AST_Constant
  3090. && !(self.left instanceof AST_Constant)) {
  3091. self = best_of(compressor, reversed, self);
  3092. } else {
  3093. self = best_of(compressor, self, reversed);
  3094. }
  3095. }
  3096. if (associative && self.is_number(compressor)) {
  3097. // a + (b + c) => (a + b) + c
  3098. if (self.right instanceof AST_Binary
  3099. && self.right.operator == self.operator) {
  3100. self = make_node(AST_Binary, self, {
  3101. operator: self.operator,
  3102. left: make_node(AST_Binary, self.left, {
  3103. operator: self.operator,
  3104. left: self.left,
  3105. right: self.right.left,
  3106. start: self.left.start,
  3107. end: self.right.left.end
  3108. }),
  3109. right: self.right.right
  3110. });
  3111. }
  3112. // (n + 2) + 3 => 5 + n
  3113. // (2 * n) * 3 => 6 + n
  3114. if (self.right instanceof AST_Constant
  3115. && self.left instanceof AST_Binary
  3116. && self.left.operator == self.operator) {
  3117. if (self.left.left instanceof AST_Constant) {
  3118. self = make_node(AST_Binary, self, {
  3119. operator: self.operator,
  3120. left: make_node(AST_Binary, self.left, {
  3121. operator: self.operator,
  3122. left: self.left.left,
  3123. right: self.right,
  3124. start: self.left.left.start,
  3125. end: self.right.end
  3126. }),
  3127. right: self.left.right
  3128. });
  3129. } else if (self.left.right instanceof AST_Constant) {
  3130. self = make_node(AST_Binary, self, {
  3131. operator: self.operator,
  3132. left: make_node(AST_Binary, self.left, {
  3133. operator: self.operator,
  3134. left: self.left.right,
  3135. right: self.right,
  3136. start: self.left.right.start,
  3137. end: self.right.end
  3138. }),
  3139. right: self.left.left
  3140. });
  3141. }
  3142. }
  3143. // (a | 1) | (2 | d) => (3 | a) | b
  3144. if (self.left instanceof AST_Binary
  3145. && self.left.operator == self.operator
  3146. && self.left.right instanceof AST_Constant
  3147. && self.right instanceof AST_Binary
  3148. && self.right.operator == self.operator
  3149. && self.right.left instanceof AST_Constant) {
  3150. self = make_node(AST_Binary, self, {
  3151. operator: self.operator,
  3152. left: make_node(AST_Binary, self.left, {
  3153. operator: self.operator,
  3154. left: make_node(AST_Binary, self.left.left, {
  3155. operator: self.operator,
  3156. left: self.left.right,
  3157. right: self.right.left,
  3158. start: self.left.right.start,
  3159. end: self.right.left.end
  3160. }),
  3161. right: self.left.left
  3162. }),
  3163. right: self.right.right
  3164. });
  3165. }
  3166. }
  3167. }
  3168. }
  3169. // x && (y && z) ==> x && y && z
  3170. // x || (y || z) ==> x || y || z
  3171. // x + ("y" + z) ==> x + "y" + z
  3172. // "x" + (y + "z")==> "x" + y + "z"
  3173. if (self.right instanceof AST_Binary
  3174. && self.right.operator == self.operator
  3175. && (lazy_op.has(self.operator)
  3176. || (self.operator == "+"
  3177. && (self.right.left.is_string(compressor)
  3178. || (self.left.is_string(compressor)
  3179. && self.right.right.is_string(compressor)))))
  3180. ) {
  3181. self.left = make_node(AST_Binary, self.left, {
  3182. operator : self.operator,
  3183. left : self.left.transform(compressor),
  3184. right : self.right.left.transform(compressor)
  3185. });
  3186. self.right = self.right.right.transform(compressor);
  3187. return self.transform(compressor);
  3188. }
  3189. var ev = self.evaluate(compressor);
  3190. if (ev !== self) {
  3191. ev = make_node_from_constant(ev, self).optimize(compressor);
  3192. return best_of(compressor, ev, self);
  3193. }
  3194. return self;
  3195. });
  3196. def_optimize(AST_SymbolExport, function(self) {
  3197. return self;
  3198. });
  3199. function within_array_or_object_literal(compressor) {
  3200. var node, level = 0;
  3201. while (node = compressor.parent(level++)) {
  3202. if (node instanceof AST_Statement) return false;
  3203. if (node instanceof AST_Array
  3204. || node instanceof AST_ObjectKeyVal
  3205. || node instanceof AST_Object) {
  3206. return true;
  3207. }
  3208. }
  3209. return false;
  3210. }
  3211. def_optimize(AST_SymbolRef, function(self, compressor) {
  3212. if (
  3213. !compressor.option("ie8")
  3214. && is_undeclared_ref(self)
  3215. && !compressor.find_parent(AST_With)
  3216. ) {
  3217. switch (self.name) {
  3218. case "undefined":
  3219. return make_node(AST_Undefined, self).optimize(compressor);
  3220. case "NaN":
  3221. return make_node(AST_NaN, self).optimize(compressor);
  3222. case "Infinity":
  3223. return make_node(AST_Infinity, self).optimize(compressor);
  3224. }
  3225. }
  3226. const parent = compressor.parent();
  3227. if (compressor.option("reduce_vars") && is_lhs(self, parent) !== self) {
  3228. const def = self.definition();
  3229. const nearest_scope = find_scope(compressor);
  3230. if (compressor.top_retain && def.global && compressor.top_retain(def)) {
  3231. def.fixed = false;
  3232. def.single_use = false;
  3233. return self;
  3234. }
  3235. let fixed = self.fixed_value();
  3236. let single_use = def.single_use
  3237. && !(parent instanceof AST_Call
  3238. && (parent.is_callee_pure(compressor))
  3239. || has_annotation(parent, _NOINLINE))
  3240. && !(parent instanceof AST_Export
  3241. && fixed instanceof AST_Lambda
  3242. && fixed.name);
  3243. if (single_use && fixed instanceof AST_Node) {
  3244. single_use =
  3245. !fixed.has_side_effects(compressor)
  3246. && !fixed.may_throw(compressor);
  3247. }
  3248. if (single_use && (fixed instanceof AST_Lambda || fixed instanceof AST_Class)) {
  3249. if (retain_top_func(fixed, compressor)) {
  3250. single_use = false;
  3251. } else if (def.scope !== self.scope
  3252. && (def.escaped == 1
  3253. || has_flag(fixed, INLINED)
  3254. || within_array_or_object_literal(compressor)
  3255. || !compressor.option("reduce_funcs"))) {
  3256. single_use = false;
  3257. } else if (is_recursive_ref(compressor, def)) {
  3258. single_use = false;
  3259. } else if (def.scope !== self.scope || def.orig[0] instanceof AST_SymbolFunarg) {
  3260. single_use = fixed.is_constant_expression(self.scope);
  3261. if (single_use == "f") {
  3262. var scope = self.scope;
  3263. do {
  3264. if (scope instanceof AST_Defun || is_func_expr(scope)) {
  3265. set_flag(scope, INLINED);
  3266. }
  3267. } while (scope = scope.parent_scope);
  3268. }
  3269. }
  3270. }
  3271. if (single_use && fixed instanceof AST_Lambda) {
  3272. single_use =
  3273. def.scope === self.scope
  3274. && !scope_encloses_variables_in_this_scope(nearest_scope, fixed)
  3275. || parent instanceof AST_Call
  3276. && parent.expression === self
  3277. && !scope_encloses_variables_in_this_scope(nearest_scope, fixed)
  3278. && !(fixed.name && fixed.name.definition().recursive_refs > 0);
  3279. }
  3280. if (single_use && fixed) {
  3281. if (fixed instanceof AST_DefClass) {
  3282. set_flag(fixed, SQUEEZED);
  3283. fixed = make_node(AST_ClassExpression, fixed, fixed);
  3284. }
  3285. if (fixed instanceof AST_Defun) {
  3286. set_flag(fixed, SQUEEZED);
  3287. fixed = make_node(AST_Function, fixed, fixed);
  3288. }
  3289. if (def.recursive_refs > 0 && fixed.name instanceof AST_SymbolDefun) {
  3290. const defun_def = fixed.name.definition();
  3291. let lambda_def = fixed.variables.get(fixed.name.name);
  3292. let name = lambda_def && lambda_def.orig[0];
  3293. if (!(name instanceof AST_SymbolLambda)) {
  3294. name = make_node(AST_SymbolLambda, fixed.name, fixed.name);
  3295. name.scope = fixed;
  3296. fixed.name = name;
  3297. lambda_def = fixed.def_function(name);
  3298. }
  3299. walk(fixed, node => {
  3300. if (node instanceof AST_SymbolRef && node.definition() === defun_def) {
  3301. node.thedef = lambda_def;
  3302. lambda_def.references.push(node);
  3303. }
  3304. });
  3305. }
  3306. if (
  3307. (fixed instanceof AST_Lambda || fixed instanceof AST_Class)
  3308. && fixed.parent_scope !== nearest_scope
  3309. ) {
  3310. fixed = fixed.clone(true, compressor.get_toplevel());
  3311. nearest_scope.add_child_scope(fixed);
  3312. }
  3313. return fixed.optimize(compressor);
  3314. }
  3315. // multiple uses
  3316. if (fixed) {
  3317. let replace;
  3318. if (fixed instanceof AST_This) {
  3319. if (!(def.orig[0] instanceof AST_SymbolFunarg)
  3320. && def.references.every((ref) =>
  3321. def.scope === ref.scope
  3322. )) {
  3323. replace = fixed;
  3324. }
  3325. } else {
  3326. var ev = fixed.evaluate(compressor);
  3327. if (
  3328. ev !== fixed
  3329. && (compressor.option("unsafe_regexp") || !(ev instanceof RegExp))
  3330. ) {
  3331. replace = make_node_from_constant(ev, fixed);
  3332. }
  3333. }
  3334. if (replace) {
  3335. const name_length = self.size(compressor);
  3336. const replace_size = replace.size(compressor);
  3337. let overhead = 0;
  3338. if (compressor.option("unused") && !compressor.exposed(def)) {
  3339. overhead =
  3340. (name_length + 2 + replace_size) /
  3341. (def.references.length - def.assignments);
  3342. }
  3343. if (replace_size <= name_length + overhead) {
  3344. return replace;
  3345. }
  3346. }
  3347. }
  3348. }
  3349. return self;
  3350. });
  3351. function scope_encloses_variables_in_this_scope(scope, pulled_scope) {
  3352. for (const enclosed of pulled_scope.enclosed) {
  3353. if (pulled_scope.variables.has(enclosed.name)) {
  3354. continue;
  3355. }
  3356. const looked_up = scope.find_variable(enclosed.name);
  3357. if (looked_up) {
  3358. if (looked_up === enclosed) continue;
  3359. return true;
  3360. }
  3361. }
  3362. return false;
  3363. }
  3364. function is_atomic(lhs, self) {
  3365. return lhs instanceof AST_SymbolRef || lhs.TYPE === self.TYPE;
  3366. }
  3367. def_optimize(AST_Undefined, function(self, compressor) {
  3368. if (compressor.option("unsafe_undefined")) {
  3369. var undef = find_variable(compressor, "undefined");
  3370. if (undef) {
  3371. var ref = make_node(AST_SymbolRef, self, {
  3372. name : "undefined",
  3373. scope : undef.scope,
  3374. thedef : undef
  3375. });
  3376. set_flag(ref, UNDEFINED);
  3377. return ref;
  3378. }
  3379. }
  3380. var lhs = is_lhs(compressor.self(), compressor.parent());
  3381. if (lhs && is_atomic(lhs, self)) return self;
  3382. return make_node(AST_UnaryPrefix, self, {
  3383. operator: "void",
  3384. expression: make_node(AST_Number, self, {
  3385. value: 0
  3386. })
  3387. });
  3388. });
  3389. def_optimize(AST_Infinity, function(self, compressor) {
  3390. var lhs = is_lhs(compressor.self(), compressor.parent());
  3391. if (lhs && is_atomic(lhs, self)) return self;
  3392. if (
  3393. compressor.option("keep_infinity")
  3394. && !(lhs && !is_atomic(lhs, self))
  3395. && !find_variable(compressor, "Infinity")
  3396. ) {
  3397. return self;
  3398. }
  3399. return make_node(AST_Binary, self, {
  3400. operator: "/",
  3401. left: make_node(AST_Number, self, {
  3402. value: 1
  3403. }),
  3404. right: make_node(AST_Number, self, {
  3405. value: 0
  3406. })
  3407. });
  3408. });
  3409. def_optimize(AST_NaN, function(self, compressor) {
  3410. var lhs = is_lhs(compressor.self(), compressor.parent());
  3411. if (lhs && !is_atomic(lhs, self)
  3412. || find_variable(compressor, "NaN")) {
  3413. return make_node(AST_Binary, self, {
  3414. operator: "/",
  3415. left: make_node(AST_Number, self, {
  3416. value: 0
  3417. }),
  3418. right: make_node(AST_Number, self, {
  3419. value: 0
  3420. })
  3421. });
  3422. }
  3423. return self;
  3424. });
  3425. function is_reachable(self, defs) {
  3426. const find_ref = node => {
  3427. if (node instanceof AST_SymbolRef && member(node.definition(), defs)) {
  3428. return walk_abort;
  3429. }
  3430. };
  3431. return walk_parent(self, (node, info) => {
  3432. if (node instanceof AST_Scope && node !== self) {
  3433. var parent = info.parent();
  3434. if (
  3435. parent instanceof AST_Call
  3436. && parent.expression === node
  3437. // Async/Generators aren't guaranteed to sync evaluate all of
  3438. // their body steps, so it's possible they close over the variable.
  3439. && !(node.async || node.is_generator)
  3440. ) {
  3441. return;
  3442. }
  3443. if (walk(node, find_ref)) return walk_abort;
  3444. return true;
  3445. }
  3446. });
  3447. }
  3448. const ASSIGN_OPS = makePredicate("+ - / * % >> << >>> | ^ &");
  3449. const ASSIGN_OPS_COMMUTATIVE = makePredicate("* | ^ &");
  3450. def_optimize(AST_Assign, function(self, compressor) {
  3451. if (self.logical) {
  3452. return self.lift_sequences(compressor);
  3453. }
  3454. var def;
  3455. if (compressor.option("dead_code")
  3456. && self.left instanceof AST_SymbolRef
  3457. && (def = self.left.definition()).scope === compressor.find_parent(AST_Lambda)) {
  3458. var level = 0, node, parent = self;
  3459. do {
  3460. node = parent;
  3461. parent = compressor.parent(level++);
  3462. if (parent instanceof AST_Exit) {
  3463. if (in_try(level, parent)) break;
  3464. if (is_reachable(def.scope, [ def ])) break;
  3465. if (self.operator == "=") return self.right;
  3466. def.fixed = false;
  3467. return make_node(AST_Binary, self, {
  3468. operator: self.operator.slice(0, -1),
  3469. left: self.left,
  3470. right: self.right
  3471. }).optimize(compressor);
  3472. }
  3473. } while (parent instanceof AST_Binary && parent.right === node
  3474. || parent instanceof AST_Sequence && parent.tail_node() === node);
  3475. }
  3476. self = self.lift_sequences(compressor);
  3477. if (self.operator == "=" && self.left instanceof AST_SymbolRef && self.right instanceof AST_Binary) {
  3478. // x = expr1 OP expr2
  3479. if (self.right.left instanceof AST_SymbolRef
  3480. && self.right.left.name == self.left.name
  3481. && ASSIGN_OPS.has(self.right.operator)) {
  3482. // x = x - 2 ---> x -= 2
  3483. self.operator = self.right.operator + "=";
  3484. self.right = self.right.right;
  3485. } else if (self.right.right instanceof AST_SymbolRef
  3486. && self.right.right.name == self.left.name
  3487. && ASSIGN_OPS_COMMUTATIVE.has(self.right.operator)
  3488. && !self.right.left.has_side_effects(compressor)) {
  3489. // x = 2 & x ---> x &= 2
  3490. self.operator = self.right.operator + "=";
  3491. self.right = self.right.left;
  3492. }
  3493. }
  3494. return self;
  3495. function in_try(level, node) {
  3496. var right = self.right;
  3497. self.right = make_node(AST_Null, right);
  3498. var may_throw = node.may_throw(compressor);
  3499. self.right = right;
  3500. var scope = self.left.definition().scope;
  3501. var parent;
  3502. while ((parent = compressor.parent(level++)) !== scope) {
  3503. if (parent instanceof AST_Try) {
  3504. if (parent.bfinally) return true;
  3505. if (may_throw && parent.bcatch) return true;
  3506. }
  3507. }
  3508. }
  3509. });
  3510. def_optimize(AST_DefaultAssign, function(self, compressor) {
  3511. if (!compressor.option("evaluate")) {
  3512. return self;
  3513. }
  3514. var evaluateRight = self.right.evaluate(compressor);
  3515. // `[x = undefined] = foo` ---> `[x] = foo`
  3516. if (evaluateRight === undefined) {
  3517. self = self.left;
  3518. } else if (evaluateRight !== self.right) {
  3519. evaluateRight = make_node_from_constant(evaluateRight, self.right);
  3520. self.right = best_of_expression(evaluateRight, self.right);
  3521. }
  3522. return self;
  3523. });
  3524. function is_nullish_check(check, check_subject, compressor) {
  3525. if (check_subject.may_throw(compressor)) return false;
  3526. let nullish_side;
  3527. // foo == null
  3528. if (
  3529. check instanceof AST_Binary
  3530. && check.operator === "=="
  3531. // which side is nullish?
  3532. && (
  3533. (nullish_side = is_nullish(check.left, compressor) && check.left)
  3534. || (nullish_side = is_nullish(check.right, compressor) && check.right)
  3535. )
  3536. // is the other side the same as the check_subject
  3537. && (
  3538. nullish_side === check.left
  3539. ? check.right
  3540. : check.left
  3541. ).equivalent_to(check_subject)
  3542. ) {
  3543. return true;
  3544. }
  3545. // foo === null || foo === undefined
  3546. if (check instanceof AST_Binary && check.operator === "||") {
  3547. let null_cmp;
  3548. let undefined_cmp;
  3549. const find_comparison = cmp => {
  3550. if (!(
  3551. cmp instanceof AST_Binary
  3552. && (cmp.operator === "===" || cmp.operator === "==")
  3553. )) {
  3554. return false;
  3555. }
  3556. let found = 0;
  3557. let defined_side;
  3558. if (cmp.left instanceof AST_Null) {
  3559. found++;
  3560. null_cmp = cmp;
  3561. defined_side = cmp.right;
  3562. }
  3563. if (cmp.right instanceof AST_Null) {
  3564. found++;
  3565. null_cmp = cmp;
  3566. defined_side = cmp.left;
  3567. }
  3568. if (is_undefined(cmp.left, compressor)) {
  3569. found++;
  3570. undefined_cmp = cmp;
  3571. defined_side = cmp.right;
  3572. }
  3573. if (is_undefined(cmp.right, compressor)) {
  3574. found++;
  3575. undefined_cmp = cmp;
  3576. defined_side = cmp.left;
  3577. }
  3578. if (found !== 1) {
  3579. return false;
  3580. }
  3581. if (!defined_side.equivalent_to(check_subject)) {
  3582. return false;
  3583. }
  3584. return true;
  3585. };
  3586. if (!find_comparison(check.left)) return false;
  3587. if (!find_comparison(check.right)) return false;
  3588. if (null_cmp && undefined_cmp && null_cmp !== undefined_cmp) {
  3589. return true;
  3590. }
  3591. }
  3592. return false;
  3593. }
  3594. def_optimize(AST_Conditional, function(self, compressor) {
  3595. if (!compressor.option("conditionals")) return self;
  3596. // This looks like lift_sequences(), should probably be under "sequences"
  3597. if (self.condition instanceof AST_Sequence) {
  3598. var expressions = self.condition.expressions.slice();
  3599. self.condition = expressions.pop();
  3600. expressions.push(self);
  3601. return make_sequence(self, expressions);
  3602. }
  3603. var cond = self.condition.evaluate(compressor);
  3604. if (cond !== self.condition) {
  3605. if (cond) {
  3606. return maintain_this_binding(compressor.parent(), compressor.self(), self.consequent);
  3607. } else {
  3608. return maintain_this_binding(compressor.parent(), compressor.self(), self.alternative);
  3609. }
  3610. }
  3611. var negated = cond.negate(compressor, first_in_statement(compressor));
  3612. if (best_of(compressor, cond, negated) === negated) {
  3613. self = make_node(AST_Conditional, self, {
  3614. condition: negated,
  3615. consequent: self.alternative,
  3616. alternative: self.consequent
  3617. });
  3618. }
  3619. var condition = self.condition;
  3620. var consequent = self.consequent;
  3621. var alternative = self.alternative;
  3622. // x?x:y --> x||y
  3623. if (condition instanceof AST_SymbolRef
  3624. && consequent instanceof AST_SymbolRef
  3625. && condition.definition() === consequent.definition()) {
  3626. return make_node(AST_Binary, self, {
  3627. operator: "||",
  3628. left: condition,
  3629. right: alternative
  3630. });
  3631. }
  3632. // if (foo) exp = something; else exp = something_else;
  3633. // |
  3634. // v
  3635. // exp = foo ? something : something_else;
  3636. if (
  3637. consequent instanceof AST_Assign
  3638. && alternative instanceof AST_Assign
  3639. && consequent.operator === alternative.operator
  3640. && consequent.logical === alternative.logical
  3641. && consequent.left.equivalent_to(alternative.left)
  3642. && (!self.condition.has_side_effects(compressor)
  3643. || consequent.operator == "="
  3644. && !consequent.left.has_side_effects(compressor))
  3645. ) {
  3646. return make_node(AST_Assign, self, {
  3647. operator: consequent.operator,
  3648. left: consequent.left,
  3649. logical: consequent.logical,
  3650. right: make_node(AST_Conditional, self, {
  3651. condition: self.condition,
  3652. consequent: consequent.right,
  3653. alternative: alternative.right
  3654. })
  3655. });
  3656. }
  3657. // x ? y(a) : y(b) --> y(x ? a : b)
  3658. var arg_index;
  3659. if (consequent instanceof AST_Call
  3660. && alternative.TYPE === consequent.TYPE
  3661. && consequent.args.length > 0
  3662. && consequent.args.length == alternative.args.length
  3663. && consequent.expression.equivalent_to(alternative.expression)
  3664. && !self.condition.has_side_effects(compressor)
  3665. && !consequent.expression.has_side_effects(compressor)
  3666. && typeof (arg_index = single_arg_diff()) == "number") {
  3667. var node = consequent.clone();
  3668. node.args[arg_index] = make_node(AST_Conditional, self, {
  3669. condition: self.condition,
  3670. consequent: consequent.args[arg_index],
  3671. alternative: alternative.args[arg_index]
  3672. });
  3673. return node;
  3674. }
  3675. // a ? b : c ? b : d --> (a || c) ? b : d
  3676. if (alternative instanceof AST_Conditional
  3677. && consequent.equivalent_to(alternative.consequent)) {
  3678. return make_node(AST_Conditional, self, {
  3679. condition: make_node(AST_Binary, self, {
  3680. operator: "||",
  3681. left: condition,
  3682. right: alternative.condition
  3683. }),
  3684. consequent: consequent,
  3685. alternative: alternative.alternative
  3686. }).optimize(compressor);
  3687. }
  3688. // a == null ? b : a -> a ?? b
  3689. if (
  3690. compressor.option("ecma") >= 2020 &&
  3691. is_nullish_check(condition, alternative, compressor)
  3692. ) {
  3693. return make_node(AST_Binary, self, {
  3694. operator: "??",
  3695. left: alternative,
  3696. right: consequent
  3697. }).optimize(compressor);
  3698. }
  3699. // a ? b : (c, b) --> (a || c), b
  3700. if (alternative instanceof AST_Sequence
  3701. && consequent.equivalent_to(alternative.expressions[alternative.expressions.length - 1])) {
  3702. return make_sequence(self, [
  3703. make_node(AST_Binary, self, {
  3704. operator: "||",
  3705. left: condition,
  3706. right: make_sequence(self, alternative.expressions.slice(0, -1))
  3707. }),
  3708. consequent
  3709. ]).optimize(compressor);
  3710. }
  3711. // a ? b : (c && b) --> (a || c) && b
  3712. if (alternative instanceof AST_Binary
  3713. && alternative.operator == "&&"
  3714. && consequent.equivalent_to(alternative.right)) {
  3715. return make_node(AST_Binary, self, {
  3716. operator: "&&",
  3717. left: make_node(AST_Binary, self, {
  3718. operator: "||",
  3719. left: condition,
  3720. right: alternative.left
  3721. }),
  3722. right: consequent
  3723. }).optimize(compressor);
  3724. }
  3725. // x?y?z:a:a --> x&&y?z:a
  3726. if (consequent instanceof AST_Conditional
  3727. && consequent.alternative.equivalent_to(alternative)) {
  3728. return make_node(AST_Conditional, self, {
  3729. condition: make_node(AST_Binary, self, {
  3730. left: self.condition,
  3731. operator: "&&",
  3732. right: consequent.condition
  3733. }),
  3734. consequent: consequent.consequent,
  3735. alternative: alternative
  3736. });
  3737. }
  3738. // x ? y : y --> x, y
  3739. if (consequent.equivalent_to(alternative)) {
  3740. return make_sequence(self, [
  3741. self.condition,
  3742. consequent
  3743. ]).optimize(compressor);
  3744. }
  3745. // x ? y || z : z --> x && y || z
  3746. if (consequent instanceof AST_Binary
  3747. && consequent.operator == "||"
  3748. && consequent.right.equivalent_to(alternative)) {
  3749. return make_node(AST_Binary, self, {
  3750. operator: "||",
  3751. left: make_node(AST_Binary, self, {
  3752. operator: "&&",
  3753. left: self.condition,
  3754. right: consequent.left
  3755. }),
  3756. right: alternative
  3757. }).optimize(compressor);
  3758. }
  3759. const in_bool = compressor.in_boolean_context();
  3760. if (is_true(self.consequent)) {
  3761. if (is_false(self.alternative)) {
  3762. // c ? true : false ---> !!c
  3763. return booleanize(self.condition);
  3764. }
  3765. // c ? true : x ---> !!c || x
  3766. return make_node(AST_Binary, self, {
  3767. operator: "||",
  3768. left: booleanize(self.condition),
  3769. right: self.alternative
  3770. });
  3771. }
  3772. if (is_false(self.consequent)) {
  3773. if (is_true(self.alternative)) {
  3774. // c ? false : true ---> !c
  3775. return booleanize(self.condition.negate(compressor));
  3776. }
  3777. // c ? false : x ---> !c && x
  3778. return make_node(AST_Binary, self, {
  3779. operator: "&&",
  3780. left: booleanize(self.condition.negate(compressor)),
  3781. right: self.alternative
  3782. });
  3783. }
  3784. if (is_true(self.alternative)) {
  3785. // c ? x : true ---> !c || x
  3786. return make_node(AST_Binary, self, {
  3787. operator: "||",
  3788. left: booleanize(self.condition.negate(compressor)),
  3789. right: self.consequent
  3790. });
  3791. }
  3792. if (is_false(self.alternative)) {
  3793. // c ? x : false ---> !!c && x
  3794. return make_node(AST_Binary, self, {
  3795. operator: "&&",
  3796. left: booleanize(self.condition),
  3797. right: self.consequent
  3798. });
  3799. }
  3800. return self;
  3801. function booleanize(node) {
  3802. if (node.is_boolean()) return node;
  3803. // !!expression
  3804. return make_node(AST_UnaryPrefix, node, {
  3805. operator: "!",
  3806. expression: node.negate(compressor)
  3807. });
  3808. }
  3809. // AST_True or !0
  3810. function is_true(node) {
  3811. return node instanceof AST_True
  3812. || in_bool
  3813. && node instanceof AST_Constant
  3814. && node.getValue()
  3815. || (node instanceof AST_UnaryPrefix
  3816. && node.operator == "!"
  3817. && node.expression instanceof AST_Constant
  3818. && !node.expression.getValue());
  3819. }
  3820. // AST_False or !1
  3821. function is_false(node) {
  3822. return node instanceof AST_False
  3823. || in_bool
  3824. && node instanceof AST_Constant
  3825. && !node.getValue()
  3826. || (node instanceof AST_UnaryPrefix
  3827. && node.operator == "!"
  3828. && node.expression instanceof AST_Constant
  3829. && node.expression.getValue());
  3830. }
  3831. function single_arg_diff() {
  3832. var a = consequent.args;
  3833. var b = alternative.args;
  3834. for (var i = 0, len = a.length; i < len; i++) {
  3835. if (a[i] instanceof AST_Expansion) return;
  3836. if (!a[i].equivalent_to(b[i])) {
  3837. if (b[i] instanceof AST_Expansion) return;
  3838. for (var j = i + 1; j < len; j++) {
  3839. if (a[j] instanceof AST_Expansion) return;
  3840. if (!a[j].equivalent_to(b[j])) return;
  3841. }
  3842. return i;
  3843. }
  3844. }
  3845. }
  3846. });
  3847. def_optimize(AST_Boolean, function(self, compressor) {
  3848. if (compressor.in_boolean_context()) return make_node(AST_Number, self, {
  3849. value: +self.value
  3850. });
  3851. var p = compressor.parent();
  3852. if (compressor.option("booleans_as_integers")) {
  3853. if (p instanceof AST_Binary && (p.operator == "===" || p.operator == "!==")) {
  3854. p.operator = p.operator.replace(/=$/, "");
  3855. }
  3856. return make_node(AST_Number, self, {
  3857. value: +self.value
  3858. });
  3859. }
  3860. if (compressor.option("booleans")) {
  3861. if (p instanceof AST_Binary && (p.operator == "=="
  3862. || p.operator == "!=")) {
  3863. return make_node(AST_Number, self, {
  3864. value: +self.value
  3865. });
  3866. }
  3867. return make_node(AST_UnaryPrefix, self, {
  3868. operator: "!",
  3869. expression: make_node(AST_Number, self, {
  3870. value: 1 - self.value
  3871. })
  3872. });
  3873. }
  3874. return self;
  3875. });
  3876. function safe_to_flatten(value, compressor) {
  3877. if (value instanceof AST_SymbolRef) {
  3878. value = value.fixed_value();
  3879. }
  3880. if (!value) return false;
  3881. if (!(value instanceof AST_Lambda || value instanceof AST_Class)) return true;
  3882. if (!(value instanceof AST_Lambda && value.contains_this())) return true;
  3883. return compressor.parent() instanceof AST_New;
  3884. }
  3885. AST_PropAccess.DEFMETHOD("flatten_object", function(key, compressor) {
  3886. if (!compressor.option("properties")) return;
  3887. if (key === "__proto__") return;
  3888. var arrows = compressor.option("unsafe_arrows") && compressor.option("ecma") >= 2015;
  3889. var expr = this.expression;
  3890. if (expr instanceof AST_Object) {
  3891. var props = expr.properties;
  3892. for (var i = props.length; --i >= 0;) {
  3893. var prop = props[i];
  3894. if ("" + (prop instanceof AST_ConciseMethod ? prop.key.name : prop.key) == key) {
  3895. const all_props_flattenable = props.every((p) =>
  3896. (p instanceof AST_ObjectKeyVal
  3897. || arrows && p instanceof AST_ConciseMethod && !p.is_generator
  3898. )
  3899. && !p.computed_key()
  3900. );
  3901. if (!all_props_flattenable) return;
  3902. if (!safe_to_flatten(prop.value, compressor)) return;
  3903. return make_node(AST_Sub, this, {
  3904. expression: make_node(AST_Array, expr, {
  3905. elements: props.map(function(prop) {
  3906. var v = prop.value;
  3907. if (v instanceof AST_Accessor) {
  3908. v = make_node(AST_Function, v, v);
  3909. }
  3910. var k = prop.key;
  3911. if (k instanceof AST_Node && !(k instanceof AST_SymbolMethod)) {
  3912. return make_sequence(prop, [ k, v ]);
  3913. }
  3914. return v;
  3915. })
  3916. }),
  3917. property: make_node(AST_Number, this, {
  3918. value: i
  3919. })
  3920. });
  3921. }
  3922. }
  3923. }
  3924. });
  3925. def_optimize(AST_Sub, function(self, compressor) {
  3926. var expr = self.expression;
  3927. var prop = self.property;
  3928. if (compressor.option("properties")) {
  3929. var key = prop.evaluate(compressor);
  3930. if (key !== prop) {
  3931. if (typeof key == "string") {
  3932. if (key == "undefined") {
  3933. key = undefined;
  3934. } else {
  3935. var value = parseFloat(key);
  3936. if (value.toString() == key) {
  3937. key = value;
  3938. }
  3939. }
  3940. }
  3941. prop = self.property = best_of_expression(prop, make_node_from_constant(key, prop).transform(compressor));
  3942. var property = "" + key;
  3943. if (is_basic_identifier_string(property)
  3944. && property.length <= prop.size() + 1) {
  3945. return make_node(AST_Dot, self, {
  3946. expression: expr,
  3947. optional: self.optional,
  3948. property: property,
  3949. quote: prop.quote,
  3950. }).optimize(compressor);
  3951. }
  3952. }
  3953. }
  3954. var fn;
  3955. OPT_ARGUMENTS: if (compressor.option("arguments")
  3956. && expr instanceof AST_SymbolRef
  3957. && expr.name == "arguments"
  3958. && expr.definition().orig.length == 1
  3959. && (fn = expr.scope) instanceof AST_Lambda
  3960. && fn.uses_arguments
  3961. && !(fn instanceof AST_Arrow)
  3962. && prop instanceof AST_Number) {
  3963. var index = prop.getValue();
  3964. var params = new Set();
  3965. var argnames = fn.argnames;
  3966. for (var n = 0; n < argnames.length; n++) {
  3967. if (!(argnames[n] instanceof AST_SymbolFunarg)) {
  3968. break OPT_ARGUMENTS; // destructuring parameter - bail
  3969. }
  3970. var param = argnames[n].name;
  3971. if (params.has(param)) {
  3972. break OPT_ARGUMENTS; // duplicate parameter - bail
  3973. }
  3974. params.add(param);
  3975. }
  3976. var argname = fn.argnames[index];
  3977. if (argname && compressor.has_directive("use strict")) {
  3978. var def = argname.definition();
  3979. if (!compressor.option("reduce_vars") || def.assignments || def.orig.length > 1) {
  3980. argname = null;
  3981. }
  3982. } else if (!argname && !compressor.option("keep_fargs") && index < fn.argnames.length + 5) {
  3983. while (index >= fn.argnames.length) {
  3984. argname = fn.create_symbol(AST_SymbolFunarg, {
  3985. source: fn,
  3986. scope: fn,
  3987. tentative_name: "argument_" + fn.argnames.length,
  3988. });
  3989. fn.argnames.push(argname);
  3990. }
  3991. }
  3992. if (argname) {
  3993. var sym = make_node(AST_SymbolRef, self, argname);
  3994. sym.reference({});
  3995. clear_flag(argname, UNUSED);
  3996. return sym;
  3997. }
  3998. }
  3999. if (is_lhs(self, compressor.parent())) return self;
  4000. if (key !== prop) {
  4001. var sub = self.flatten_object(property, compressor);
  4002. if (sub) {
  4003. expr = self.expression = sub.expression;
  4004. prop = self.property = sub.property;
  4005. }
  4006. }
  4007. if (compressor.option("properties") && compressor.option("side_effects")
  4008. && prop instanceof AST_Number && expr instanceof AST_Array) {
  4009. var index = prop.getValue();
  4010. var elements = expr.elements;
  4011. var retValue = elements[index];
  4012. FLATTEN: if (safe_to_flatten(retValue, compressor)) {
  4013. var flatten = true;
  4014. var values = [];
  4015. for (var i = elements.length; --i > index;) {
  4016. var value = elements[i].drop_side_effect_free(compressor);
  4017. if (value) {
  4018. values.unshift(value);
  4019. if (flatten && value.has_side_effects(compressor)) flatten = false;
  4020. }
  4021. }
  4022. if (retValue instanceof AST_Expansion) break FLATTEN;
  4023. retValue = retValue instanceof AST_Hole ? make_node(AST_Undefined, retValue) : retValue;
  4024. if (!flatten) values.unshift(retValue);
  4025. while (--i >= 0) {
  4026. var value = elements[i];
  4027. if (value instanceof AST_Expansion) break FLATTEN;
  4028. value = value.drop_side_effect_free(compressor);
  4029. if (value) values.unshift(value);
  4030. else index--;
  4031. }
  4032. if (flatten) {
  4033. values.push(retValue);
  4034. return make_sequence(self, values).optimize(compressor);
  4035. } else return make_node(AST_Sub, self, {
  4036. expression: make_node(AST_Array, expr, {
  4037. elements: values
  4038. }),
  4039. property: make_node(AST_Number, prop, {
  4040. value: index
  4041. })
  4042. });
  4043. }
  4044. }
  4045. var ev = self.evaluate(compressor);
  4046. if (ev !== self) {
  4047. ev = make_node_from_constant(ev, self).optimize(compressor);
  4048. return best_of(compressor, ev, self);
  4049. }
  4050. return self;
  4051. });
  4052. def_optimize(AST_Chain, function (self, compressor) {
  4053. if (is_nullish(self.expression, compressor)) {
  4054. let parent = compressor.parent();
  4055. // It's valid to delete a nullish optional chain, but if we optimized
  4056. // this to `delete undefined` then it would appear to be a syntax error
  4057. // when we try to optimize the delete. Thankfully, `delete 0` is fine.
  4058. if (parent instanceof AST_UnaryPrefix && parent.operator === "delete") {
  4059. return make_node_from_constant(0, self);
  4060. }
  4061. return make_node(AST_Undefined, self);
  4062. }
  4063. return self;
  4064. });
  4065. AST_Lambda.DEFMETHOD("contains_this", function() {
  4066. return walk(this, node => {
  4067. if (node instanceof AST_This) return walk_abort;
  4068. if (
  4069. node !== this
  4070. && node instanceof AST_Scope
  4071. && !(node instanceof AST_Arrow)
  4072. ) {
  4073. return true;
  4074. }
  4075. });
  4076. });
  4077. def_optimize(AST_Dot, function(self, compressor) {
  4078. const parent = compressor.parent();
  4079. if (is_lhs(self, parent)) return self;
  4080. if (compressor.option("unsafe_proto")
  4081. && self.expression instanceof AST_Dot
  4082. && self.expression.property == "prototype") {
  4083. var exp = self.expression.expression;
  4084. if (is_undeclared_ref(exp)) switch (exp.name) {
  4085. case "Array":
  4086. self.expression = make_node(AST_Array, self.expression, {
  4087. elements: []
  4088. });
  4089. break;
  4090. case "Function":
  4091. self.expression = make_node(AST_Function, self.expression, {
  4092. argnames: [],
  4093. body: []
  4094. });
  4095. break;
  4096. case "Number":
  4097. self.expression = make_node(AST_Number, self.expression, {
  4098. value: 0
  4099. });
  4100. break;
  4101. case "Object":
  4102. self.expression = make_node(AST_Object, self.expression, {
  4103. properties: []
  4104. });
  4105. break;
  4106. case "RegExp":
  4107. self.expression = make_node(AST_RegExp, self.expression, {
  4108. value: { source: "t", flags: "" }
  4109. });
  4110. break;
  4111. case "String":
  4112. self.expression = make_node(AST_String, self.expression, {
  4113. value: ""
  4114. });
  4115. break;
  4116. }
  4117. }
  4118. if (!(parent instanceof AST_Call) || !has_annotation(parent, _NOINLINE)) {
  4119. const sub = self.flatten_object(self.property, compressor);
  4120. if (sub) return sub.optimize(compressor);
  4121. }
  4122. let ev = self.evaluate(compressor);
  4123. if (ev !== self) {
  4124. ev = make_node_from_constant(ev, self).optimize(compressor);
  4125. return best_of(compressor, ev, self);
  4126. }
  4127. return self;
  4128. });
  4129. function literals_in_boolean_context(self, compressor) {
  4130. if (compressor.in_boolean_context()) {
  4131. return best_of(compressor, self, make_sequence(self, [
  4132. self,
  4133. make_node(AST_True, self)
  4134. ]).optimize(compressor));
  4135. }
  4136. return self;
  4137. }
  4138. function inline_array_like_spread(elements) {
  4139. for (var i = 0; i < elements.length; i++) {
  4140. var el = elements[i];
  4141. if (el instanceof AST_Expansion) {
  4142. var expr = el.expression;
  4143. if (
  4144. expr instanceof AST_Array
  4145. && !expr.elements.some(elm => elm instanceof AST_Hole)
  4146. ) {
  4147. elements.splice(i, 1, ...expr.elements);
  4148. // Step back one, as the element at i is now new.
  4149. i--;
  4150. }
  4151. // In array-like spread, spreading a non-iterable value is TypeError.
  4152. // We therefore can’t optimize anything else, unlike with object spread.
  4153. }
  4154. }
  4155. }
  4156. def_optimize(AST_Array, function(self, compressor) {
  4157. var optimized = literals_in_boolean_context(self, compressor);
  4158. if (optimized !== self) {
  4159. return optimized;
  4160. }
  4161. inline_array_like_spread(self.elements);
  4162. return self;
  4163. });
  4164. function inline_object_prop_spread(props, compressor) {
  4165. for (var i = 0; i < props.length; i++) {
  4166. var prop = props[i];
  4167. if (prop instanceof AST_Expansion) {
  4168. const expr = prop.expression;
  4169. if (
  4170. expr instanceof AST_Object
  4171. && expr.properties.every(prop => prop instanceof AST_ObjectKeyVal)
  4172. ) {
  4173. props.splice(i, 1, ...expr.properties);
  4174. // Step back one, as the property at i is now new.
  4175. i--;
  4176. } else if (expr instanceof AST_Constant
  4177. && !(expr instanceof AST_String)) {
  4178. // Unlike array-like spread, in object spread, spreading a
  4179. // non-iterable value silently does nothing; it is thus safe
  4180. // to remove. AST_String is the only iterable AST_Constant.
  4181. props.splice(i, 1);
  4182. i--;
  4183. } else if (is_nullish(expr, compressor)) {
  4184. // Likewise, null and undefined can be silently removed.
  4185. props.splice(i, 1);
  4186. i--;
  4187. }
  4188. }
  4189. }
  4190. }
  4191. def_optimize(AST_Object, function(self, compressor) {
  4192. var optimized = literals_in_boolean_context(self, compressor);
  4193. if (optimized !== self) {
  4194. return optimized;
  4195. }
  4196. inline_object_prop_spread(self.properties, compressor);
  4197. return self;
  4198. });
  4199. def_optimize(AST_RegExp, literals_in_boolean_context);
  4200. def_optimize(AST_Return, function(self, compressor) {
  4201. if (self.value && is_undefined(self.value, compressor)) {
  4202. self.value = null;
  4203. }
  4204. return self;
  4205. });
  4206. def_optimize(AST_Arrow, opt_AST_Lambda);
  4207. def_optimize(AST_Function, function(self, compressor) {
  4208. self = opt_AST_Lambda(self, compressor);
  4209. if (compressor.option("unsafe_arrows")
  4210. && compressor.option("ecma") >= 2015
  4211. && !self.name
  4212. && !self.is_generator
  4213. && !self.uses_arguments
  4214. && !self.pinned()) {
  4215. const uses_this = walk(self, node => {
  4216. if (node instanceof AST_This) return walk_abort;
  4217. });
  4218. if (!uses_this) return make_node(AST_Arrow, self, self).optimize(compressor);
  4219. }
  4220. return self;
  4221. });
  4222. def_optimize(AST_Class, function(self) {
  4223. // HACK to avoid compress failure.
  4224. // AST_Class is not really an AST_Scope/AST_Block as it lacks a body.
  4225. return self;
  4226. });
  4227. def_optimize(AST_Yield, function(self, compressor) {
  4228. if (self.expression && !self.is_star && is_undefined(self.expression, compressor)) {
  4229. self.expression = null;
  4230. }
  4231. return self;
  4232. });
  4233. def_optimize(AST_TemplateString, function(self, compressor) {
  4234. if (
  4235. !compressor.option("evaluate")
  4236. || compressor.parent() instanceof AST_PrefixedTemplateString
  4237. ) {
  4238. return self;
  4239. }
  4240. var segments = [];
  4241. for (var i = 0; i < self.segments.length; i++) {
  4242. var segment = self.segments[i];
  4243. if (segment instanceof AST_Node) {
  4244. var result = segment.evaluate(compressor);
  4245. // Evaluate to constant value
  4246. // Constant value shorter than ${segment}
  4247. if (result !== segment && (result + "").length <= segment.size() + "${}".length) {
  4248. // There should always be a previous and next segment if segment is a node
  4249. segments[segments.length - 1].value = segments[segments.length - 1].value + result + self.segments[++i].value;
  4250. continue;
  4251. }
  4252. // `before ${`innerBefore ${any} innerAfter`} after` => `before innerBefore ${any} innerAfter after`
  4253. // TODO:
  4254. // `before ${'test' + foo} after` => `before innerBefore ${any} innerAfter after`
  4255. // `before ${foo + 'test} after` => `before innerBefore ${any} innerAfter after`
  4256. if (segment instanceof AST_TemplateString) {
  4257. var inners = segment.segments;
  4258. segments[segments.length - 1].value += inners[0].value;
  4259. for (var j = 1; j < inners.length; j++) {
  4260. segment = inners[j];
  4261. segments.push(segment);
  4262. }
  4263. continue;
  4264. }
  4265. }
  4266. segments.push(segment);
  4267. }
  4268. self.segments = segments;
  4269. // `foo` => "foo"
  4270. if (segments.length == 1) {
  4271. return make_node(AST_String, self, segments[0]);
  4272. }
  4273. if (
  4274. segments.length === 3
  4275. && segments[1] instanceof AST_Node
  4276. && (
  4277. segments[1].is_string(compressor)
  4278. || segments[1].is_number(compressor)
  4279. || is_nullish(segments[1], compressor)
  4280. || compressor.option("unsafe")
  4281. )
  4282. ) {
  4283. // `foo${bar}` => "foo" + bar
  4284. if (segments[2].value === "") {
  4285. return make_node(AST_Binary, self, {
  4286. operator: "+",
  4287. left: make_node(AST_String, self, {
  4288. value: segments[0].value,
  4289. }),
  4290. right: segments[1],
  4291. });
  4292. }
  4293. // `${bar}baz` => bar + "baz"
  4294. if (segments[0].value === "") {
  4295. return make_node(AST_Binary, self, {
  4296. operator: "+",
  4297. left: segments[1],
  4298. right: make_node(AST_String, self, {
  4299. value: segments[2].value,
  4300. }),
  4301. });
  4302. }
  4303. }
  4304. return self;
  4305. });
  4306. def_optimize(AST_PrefixedTemplateString, function(self) {
  4307. return self;
  4308. });
  4309. // ["p"]:1 ---> p:1
  4310. // [42]:1 ---> 42:1
  4311. function lift_key(self, compressor) {
  4312. if (!compressor.option("computed_props")) return self;
  4313. // save a comparison in the typical case
  4314. if (!(self.key instanceof AST_Constant)) return self;
  4315. // allow certain acceptable props as not all AST_Constants are true constants
  4316. if (self.key instanceof AST_String || self.key instanceof AST_Number) {
  4317. if (self.key.value === "__proto__") return self;
  4318. if (self.key.value == "constructor"
  4319. && compressor.parent() instanceof AST_Class) return self;
  4320. if (self instanceof AST_ObjectKeyVal) {
  4321. self.quote = self.key.quote;
  4322. self.key = self.key.value;
  4323. } else if (self instanceof AST_ClassProperty) {
  4324. self.quote = self.key.quote;
  4325. self.key = make_node(AST_SymbolClassProperty, self.key, {
  4326. name: self.key.value
  4327. });
  4328. } else {
  4329. self.quote = self.key.quote;
  4330. self.key = make_node(AST_SymbolMethod, self.key, {
  4331. name: self.key.value
  4332. });
  4333. }
  4334. }
  4335. return self;
  4336. }
  4337. def_optimize(AST_ObjectProperty, lift_key);
  4338. def_optimize(AST_ConciseMethod, function(self, compressor) {
  4339. lift_key(self, compressor);
  4340. // p(){return x;} ---> p:()=>x
  4341. if (compressor.option("arrows")
  4342. && compressor.parent() instanceof AST_Object
  4343. && !self.is_generator
  4344. && !self.value.uses_arguments
  4345. && !self.value.pinned()
  4346. && self.value.body.length == 1
  4347. && self.value.body[0] instanceof AST_Return
  4348. && self.value.body[0].value
  4349. && !self.value.contains_this()) {
  4350. var arrow = make_node(AST_Arrow, self.value, self.value);
  4351. arrow.async = self.async;
  4352. arrow.is_generator = self.is_generator;
  4353. return make_node(AST_ObjectKeyVal, self, {
  4354. key: self.key instanceof AST_SymbolMethod ? self.key.name : self.key,
  4355. value: arrow,
  4356. quote: self.quote,
  4357. });
  4358. }
  4359. return self;
  4360. });
  4361. def_optimize(AST_ObjectKeyVal, function(self, compressor) {
  4362. lift_key(self, compressor);
  4363. // p:function(){} ---> p(){}
  4364. // p:function*(){} ---> *p(){}
  4365. // p:async function(){} ---> async p(){}
  4366. // p:()=>{} ---> p(){}
  4367. // p:async()=>{} ---> async p(){}
  4368. var unsafe_methods = compressor.option("unsafe_methods");
  4369. if (unsafe_methods
  4370. && compressor.option("ecma") >= 2015
  4371. && (!(unsafe_methods instanceof RegExp) || unsafe_methods.test(self.key + ""))) {
  4372. var key = self.key;
  4373. var value = self.value;
  4374. var is_arrow_with_block = value instanceof AST_Arrow
  4375. && Array.isArray(value.body)
  4376. && !value.contains_this();
  4377. if ((is_arrow_with_block || value instanceof AST_Function) && !value.name) {
  4378. return make_node(AST_ConciseMethod, self, {
  4379. async: value.async,
  4380. is_generator: value.is_generator,
  4381. key: key instanceof AST_Node ? key : make_node(AST_SymbolMethod, self, {
  4382. name: key,
  4383. }),
  4384. value: make_node(AST_Accessor, value, value),
  4385. quote: self.quote,
  4386. });
  4387. }
  4388. }
  4389. return self;
  4390. });
  4391. def_optimize(AST_Destructuring, function(self, compressor) {
  4392. if (compressor.option("pure_getters") == true
  4393. && compressor.option("unused")
  4394. && !self.is_array
  4395. && Array.isArray(self.names)
  4396. && !is_destructuring_export_decl(compressor)
  4397. && !(self.names[self.names.length - 1] instanceof AST_Expansion)) {
  4398. var keep = [];
  4399. for (var i = 0; i < self.names.length; i++) {
  4400. var elem = self.names[i];
  4401. if (!(elem instanceof AST_ObjectKeyVal
  4402. && typeof elem.key == "string"
  4403. && elem.value instanceof AST_SymbolDeclaration
  4404. && !should_retain(compressor, elem.value.definition()))) {
  4405. keep.push(elem);
  4406. }
  4407. }
  4408. if (keep.length != self.names.length) {
  4409. self.names = keep;
  4410. }
  4411. }
  4412. return self;
  4413. function is_destructuring_export_decl(compressor) {
  4414. var ancestors = [/^VarDef$/, /^(Const|Let|Var)$/, /^Export$/];
  4415. for (var a = 0, p = 0, len = ancestors.length; a < len; p++) {
  4416. var parent = compressor.parent(p);
  4417. if (!parent) return false;
  4418. if (a === 0 && parent.TYPE == "Destructuring") continue;
  4419. if (!ancestors[a].test(parent.TYPE)) {
  4420. return false;
  4421. }
  4422. a++;
  4423. }
  4424. return true;
  4425. }
  4426. function should_retain(compressor, def) {
  4427. if (def.references.length) return true;
  4428. if (!def.global) return false;
  4429. if (compressor.toplevel.vars) {
  4430. if (compressor.top_retain) {
  4431. return compressor.top_retain(def);
  4432. }
  4433. return false;
  4434. }
  4435. return true;
  4436. }
  4437. });
  4438. export {
  4439. Compressor,
  4440. };