index.js 147 KB

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