index.js 150 KB

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