index.js 150 KB

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