index.js 149 KB

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