index.js 137 KB

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