index.js 153 KB

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