index.js 147 KB

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