index.js 153 KB

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