index.js 154 KB

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