index.js 137 KB

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