index.js 137 KB

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