index.js 136 KB

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