compress.js 124 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903
  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. "use strict";
  34. function Compressor(options, false_by_default) {
  35. if (!(this instanceof Compressor))
  36. return new Compressor(options, false_by_default);
  37. TreeTransformer.call(this, this.before, this.after);
  38. this.options = defaults(options, {
  39. sequences : !false_by_default,
  40. properties : !false_by_default,
  41. dead_code : !false_by_default,
  42. drop_debugger : !false_by_default,
  43. unsafe : false,
  44. unsafe_comps : false,
  45. conditionals : !false_by_default,
  46. comparisons : !false_by_default,
  47. evaluate : !false_by_default,
  48. booleans : !false_by_default,
  49. loops : !false_by_default,
  50. unused : !false_by_default,
  51. hoist_funs : !false_by_default,
  52. keep_fargs : true,
  53. keep_fnames : false,
  54. hoist_vars : false,
  55. if_return : !false_by_default,
  56. join_vars : !false_by_default,
  57. collapse_vars : false,
  58. cascade : !false_by_default,
  59. side_effects : !false_by_default,
  60. pure_getters : false,
  61. pure_funcs : null,
  62. negate_iife : !false_by_default,
  63. screw_ie8 : false,
  64. drop_console : false,
  65. angular : false,
  66. warnings : true,
  67. global_defs : {},
  68. passes : 1,
  69. }, true);
  70. this.warnings_produced = {};
  71. };
  72. Compressor.prototype = new TreeTransformer;
  73. merge(Compressor.prototype, {
  74. option: function(key) { return this.options[key] },
  75. compress: function(node) {
  76. var passes = +this.options.passes || 1;
  77. for (var pass = 0; pass < passes && pass < 3; ++pass) {
  78. if (pass > 0) node.clear_opt_flags();
  79. node = node.transform(this);
  80. }
  81. return node;
  82. },
  83. warn: function(text, props) {
  84. if (this.options.warnings) {
  85. // only emit unique warnings
  86. var message = string_template(text, props);
  87. if (!(message in this.warnings_produced)) {
  88. this.warnings_produced[message] = true;
  89. AST_Node.warn.apply(AST_Node, arguments);
  90. }
  91. }
  92. },
  93. clear_warnings: function() {
  94. this.warnings_produced = {};
  95. },
  96. before: function(node, descend, in_list) {
  97. if (node._squeezed) return node;
  98. var was_scope = false;
  99. if (node instanceof AST_Scope) {
  100. node = node.hoist_declarations(this);
  101. was_scope = true;
  102. }
  103. descend(node, this);
  104. node = node.optimize(this);
  105. if (was_scope && node instanceof AST_Scope) {
  106. node.drop_unused(this);
  107. descend(node, this);
  108. }
  109. node._squeezed = true;
  110. return node;
  111. }
  112. });
  113. (function(){
  114. function OPT(node, optimizer) {
  115. node.DEFMETHOD("optimize", function(compressor){
  116. var self = this;
  117. if (self._optimized) return self;
  118. if (compressor.has_directive("use asm")) return self;
  119. var opt = optimizer(self, compressor);
  120. opt._optimized = true;
  121. if (opt === self) return opt;
  122. return opt.transform(compressor);
  123. });
  124. };
  125. OPT(AST_Node, function(self, compressor){
  126. return self;
  127. });
  128. AST_Node.DEFMETHOD("equivalent_to", function(node){
  129. // XXX: this is a rather expensive way to test two node's equivalence:
  130. return this.print_to_string() == node.print_to_string();
  131. });
  132. AST_Node.DEFMETHOD("clear_opt_flags", function(){
  133. this.walk(new TreeWalker(function(node){
  134. if (!(node instanceof AST_Directive || node instanceof AST_Constant)) {
  135. node._squeezed = false;
  136. node._optimized = false;
  137. }
  138. }));
  139. });
  140. function make_node(ctor, orig, props) {
  141. if (!props) props = {};
  142. if (orig) {
  143. if (!props.start) props.start = orig.start;
  144. if (!props.end) props.end = orig.end;
  145. }
  146. return new ctor(props);
  147. };
  148. function make_node_from_constant(compressor, val, orig) {
  149. // XXX: WIP.
  150. // if (val instanceof AST_Node) return val.transform(new TreeTransformer(null, function(node){
  151. // if (node instanceof AST_SymbolRef) {
  152. // var scope = compressor.find_parent(AST_Scope);
  153. // var def = scope.find_variable(node);
  154. // node.thedef = def;
  155. // return node;
  156. // }
  157. // })).transform(compressor);
  158. if (val instanceof AST_Node) return val.transform(compressor);
  159. switch (typeof val) {
  160. case "string":
  161. return make_node(AST_String, orig, {
  162. value: val
  163. }).optimize(compressor);
  164. case "number":
  165. if (isNaN(val)) {
  166. return make_node(AST_NaN, orig);
  167. }
  168. if ((1 / val) < 0) {
  169. return make_node(AST_UnaryPrefix, orig, {
  170. operator: "-",
  171. expression: make_node(AST_Number, null, { value: -val })
  172. });
  173. }
  174. return make_node(AST_Number, orig, { value: val }).optimize(compressor);
  175. case "boolean":
  176. return make_node(val ? AST_True : AST_False, orig).optimize(compressor);
  177. case "undefined":
  178. return make_node(AST_Undefined, orig).optimize(compressor);
  179. default:
  180. if (val === null) {
  181. return make_node(AST_Null, orig, { value: null }).optimize(compressor);
  182. }
  183. if (val instanceof RegExp) {
  184. return make_node(AST_RegExp, orig, { value: val }).optimize(compressor);
  185. }
  186. throw new Error(string_template("Can't handle constant of type: {type}", {
  187. type: typeof val
  188. }));
  189. }
  190. };
  191. // we shouldn't compress (1,func)(something) to
  192. // func(something) because that changes the meaning of
  193. // the func (becomes lexical instead of global).
  194. function maintain_this_binding(parent, orig, val) {
  195. if (parent instanceof AST_Call && parent.expression === orig) {
  196. if (val instanceof AST_PropAccess || val instanceof AST_SymbolRef && val.name === "eval") {
  197. return make_node(AST_Seq, orig, {
  198. car: make_node(AST_Number, orig, {
  199. value: 0
  200. }),
  201. cdr: val
  202. });
  203. }
  204. }
  205. return val;
  206. }
  207. function as_statement_array(thing) {
  208. if (thing === null) return [];
  209. if (thing instanceof AST_BlockStatement) return thing.body;
  210. if (thing instanceof AST_EmptyStatement) return [];
  211. if (thing instanceof AST_Statement) return [ thing ];
  212. throw new Error("Can't convert thing to statement array");
  213. };
  214. function is_empty(thing) {
  215. if (thing === null) return true;
  216. if (thing instanceof AST_EmptyStatement) return true;
  217. if (thing instanceof AST_BlockStatement) return thing.body.length == 0;
  218. return false;
  219. };
  220. function loop_body(x) {
  221. if (x instanceof AST_Switch) return x;
  222. if (x instanceof AST_For || x instanceof AST_ForIn || x instanceof AST_DWLoop) {
  223. return (x.body instanceof AST_BlockStatement ? x.body : x);
  224. }
  225. return x;
  226. };
  227. function tighten_body(statements, compressor) {
  228. var CHANGED, max_iter = 10;
  229. do {
  230. CHANGED = false;
  231. if (compressor.option("angular")) {
  232. statements = process_for_angular(statements);
  233. }
  234. statements = eliminate_spurious_blocks(statements);
  235. if (compressor.option("dead_code")) {
  236. statements = eliminate_dead_code(statements, compressor);
  237. }
  238. if (compressor.option("if_return")) {
  239. statements = handle_if_return(statements, compressor);
  240. }
  241. if (compressor.option("sequences")) {
  242. statements = sequencesize(statements, compressor);
  243. }
  244. if (compressor.option("join_vars")) {
  245. statements = join_consecutive_vars(statements, compressor);
  246. }
  247. if (compressor.option("collapse_vars")) {
  248. statements = collapse_single_use_vars(statements, compressor);
  249. }
  250. } while (CHANGED && max_iter-- > 0);
  251. if (compressor.option("negate_iife")) {
  252. negate_iifes(statements, compressor);
  253. }
  254. return statements;
  255. function collapse_single_use_vars(statements, compressor) {
  256. // Iterate statements backwards looking for a statement with a var/const
  257. // declaration immediately preceding it. Grab the rightmost var definition
  258. // and if it has exactly one reference then attempt to replace its reference
  259. // in the statement with the var value and then erase the var definition.
  260. var self = compressor.self();
  261. var var_defs_removed = false;
  262. for (var stat_index = statements.length; --stat_index >= 0;) {
  263. var stat = statements[stat_index];
  264. if (stat instanceof AST_Definitions) continue;
  265. // Process child blocks of statement if present.
  266. [stat, stat.body, stat.alternative, stat.bcatch, stat.bfinally].forEach(function(node) {
  267. node && node.body && collapse_single_use_vars(node.body, compressor);
  268. });
  269. // The variable definition must precede a statement.
  270. if (stat_index <= 0) break;
  271. var prev_stat_index = stat_index - 1;
  272. var prev_stat = statements[prev_stat_index];
  273. if (!(prev_stat instanceof AST_Definitions)) continue;
  274. var var_defs = prev_stat.definitions;
  275. if (var_defs == null) continue;
  276. var var_names_seen = {};
  277. var side_effects_encountered = false;
  278. var lvalues_encountered = false;
  279. var lvalues = {};
  280. // Scan variable definitions from right to left.
  281. for (var var_defs_index = var_defs.length; --var_defs_index >= 0;) {
  282. // Obtain var declaration and var name with basic sanity check.
  283. var var_decl = var_defs[var_defs_index];
  284. if (var_decl.value == null) break;
  285. var var_name = var_decl.name.name;
  286. if (!var_name || !var_name.length) break;
  287. // Bail if we've seen a var definition of same name before.
  288. if (var_name in var_names_seen) break;
  289. var_names_seen[var_name] = true;
  290. // Only interested in cases with just one reference to the variable.
  291. var def = self.find_variable && self.find_variable(var_name);
  292. if (!def || !def.references || def.references.length !== 1 || var_name == "arguments") {
  293. side_effects_encountered = true;
  294. continue;
  295. }
  296. var ref = def.references[0];
  297. // Don't replace ref if eval() or with statement in scope.
  298. if (ref.scope.uses_eval || ref.scope.uses_with) break;
  299. // Constant single use vars can be replaced in any scope.
  300. if (!(var_decl.value instanceof AST_RegExp) && var_decl.value.is_constant(compressor)) {
  301. var ctt = new TreeTransformer(function(node) {
  302. if (node === ref)
  303. return replace_var(node, ctt.parent(), true);
  304. });
  305. stat.transform(ctt);
  306. continue;
  307. }
  308. // Restrict var replacement to constants if side effects encountered.
  309. if (side_effects_encountered |= lvalues_encountered) continue;
  310. // Non-constant single use vars can only be replaced in same scope.
  311. if (ref.scope !== self) {
  312. side_effects_encountered |= var_decl.value.has_side_effects(compressor);
  313. continue;
  314. }
  315. // Detect lvalues in var value.
  316. var tw = new TreeWalker(function(node){
  317. if (node instanceof AST_SymbolRef && is_lvalue(node, tw.parent())) {
  318. lvalues[node.name] = lvalues_encountered = true;
  319. }
  320. });
  321. var_decl.value.walk(tw);
  322. // Replace the non-constant single use var in statement if side effect free.
  323. var unwind = false;
  324. var tt = new TreeTransformer(
  325. function preorder(node) {
  326. if (unwind) return node;
  327. var parent = tt.parent();
  328. if (node instanceof AST_Lambda
  329. || node instanceof AST_Try
  330. || node instanceof AST_With
  331. || node instanceof AST_Case
  332. || node instanceof AST_IterationStatement
  333. || (parent instanceof AST_If && node !== parent.condition)
  334. || (parent instanceof AST_Conditional && node !== parent.condition)
  335. || (parent instanceof AST_Binary
  336. && (parent.operator == "&&" || parent.operator == "||")
  337. && node === parent.right)
  338. || (parent instanceof AST_Switch && node !== parent.expression)) {
  339. return side_effects_encountered = unwind = true, node;
  340. }
  341. },
  342. function postorder(node) {
  343. if (unwind) return node;
  344. if (node === ref)
  345. return unwind = true, replace_var(node, tt.parent(), false);
  346. if (side_effects_encountered |= node.has_side_effects(compressor))
  347. return unwind = true, node;
  348. if (lvalues_encountered && node instanceof AST_SymbolRef && node.name in lvalues) {
  349. side_effects_encountered = true;
  350. return unwind = true, node;
  351. }
  352. }
  353. );
  354. stat.transform(tt);
  355. }
  356. }
  357. // Remove extraneous empty statments in block after removing var definitions.
  358. // Leave at least one statement in `statements`.
  359. if (var_defs_removed) for (var i = statements.length; --i >= 0;) {
  360. if (statements.length > 1 && statements[i] instanceof AST_EmptyStatement)
  361. statements.splice(i, 1);
  362. }
  363. return statements;
  364. function is_lvalue(node, parent) {
  365. return node instanceof AST_SymbolRef && (
  366. (parent instanceof AST_Assign && node === parent.left)
  367. || (parent instanceof AST_Unary && parent.expression === node
  368. && (parent.operator == "++" || parent.operator == "--")));
  369. }
  370. function replace_var(node, parent, is_constant) {
  371. if (is_lvalue(node, parent)) return node;
  372. // Remove var definition and return its value to the TreeTransformer to replace.
  373. var value = maintain_this_binding(parent, node, var_decl.value);
  374. var_decl.value = null;
  375. var_defs.splice(var_defs_index, 1);
  376. if (var_defs.length === 0) {
  377. statements[prev_stat_index] = make_node(AST_EmptyStatement, self);
  378. var_defs_removed = true;
  379. }
  380. // Further optimize statement after substitution.
  381. stat.clear_opt_flags();
  382. compressor.warn("Replacing " + (is_constant ? "constant" : "variable") +
  383. " " + var_name + " [{file}:{line},{col}]", node.start);
  384. CHANGED = true;
  385. return value;
  386. }
  387. }
  388. function process_for_angular(statements) {
  389. function has_inject(comment) {
  390. return /@ngInject/.test(comment.value);
  391. }
  392. function make_arguments_names_list(func) {
  393. return func.argnames.map(function(sym){
  394. return make_node(AST_String, sym, { value: sym.name });
  395. });
  396. }
  397. function make_array(orig, elements) {
  398. return make_node(AST_Array, orig, { elements: elements });
  399. }
  400. function make_injector(func, name) {
  401. return make_node(AST_SimpleStatement, func, {
  402. body: make_node(AST_Assign, func, {
  403. operator: "=",
  404. left: make_node(AST_Dot, name, {
  405. expression: make_node(AST_SymbolRef, name, name),
  406. property: "$inject"
  407. }),
  408. right: make_array(func, make_arguments_names_list(func))
  409. })
  410. });
  411. }
  412. function check_expression(body) {
  413. if (body && body.args) {
  414. // if this is a function call check all of arguments passed
  415. body.args.forEach(function(argument, index, array) {
  416. var comments = argument.start.comments_before;
  417. // if the argument is function preceded by @ngInject
  418. if (argument instanceof AST_Lambda && comments.length && has_inject(comments[0])) {
  419. // replace the function with an array of names of its parameters and function at the end
  420. array[index] = make_array(argument, make_arguments_names_list(argument).concat(argument));
  421. }
  422. });
  423. // if this is chained call check previous one recursively
  424. if (body.expression && body.expression.expression) {
  425. check_expression(body.expression.expression);
  426. }
  427. }
  428. }
  429. return statements.reduce(function(a, stat){
  430. a.push(stat);
  431. if (stat.body && stat.body.args) {
  432. check_expression(stat.body);
  433. } else {
  434. var token = stat.start;
  435. var comments = token.comments_before;
  436. if (comments && comments.length > 0) {
  437. var last = comments.pop();
  438. if (has_inject(last)) {
  439. // case 1: defun
  440. if (stat instanceof AST_Defun) {
  441. a.push(make_injector(stat, stat.name));
  442. }
  443. else if (stat instanceof AST_Definitions) {
  444. stat.definitions.forEach(function(def) {
  445. if (def.value && def.value instanceof AST_Lambda) {
  446. a.push(make_injector(def.value, def.name));
  447. }
  448. });
  449. }
  450. else {
  451. compressor.warn("Unknown statement marked with @ngInject [{file}:{line},{col}]", token);
  452. }
  453. }
  454. }
  455. }
  456. return a;
  457. }, []);
  458. }
  459. function eliminate_spurious_blocks(statements) {
  460. var seen_dirs = [];
  461. return statements.reduce(function(a, stat){
  462. if (stat instanceof AST_BlockStatement) {
  463. CHANGED = true;
  464. a.push.apply(a, eliminate_spurious_blocks(stat.body));
  465. } else if (stat instanceof AST_EmptyStatement) {
  466. CHANGED = true;
  467. } else if (stat instanceof AST_Directive) {
  468. if (seen_dirs.indexOf(stat.value) < 0) {
  469. a.push(stat);
  470. seen_dirs.push(stat.value);
  471. } else {
  472. CHANGED = true;
  473. }
  474. } else {
  475. a.push(stat);
  476. }
  477. return a;
  478. }, []);
  479. };
  480. function handle_if_return(statements, compressor) {
  481. var self = compressor.self();
  482. var multiple_if_returns = has_multiple_if_returns(statements);
  483. var in_lambda = self instanceof AST_Lambda;
  484. var ret = [];
  485. loop: for (var i = statements.length; --i >= 0;) {
  486. var stat = statements[i];
  487. switch (true) {
  488. case (in_lambda && stat instanceof AST_Return && !stat.value && ret.length == 0):
  489. CHANGED = true;
  490. // note, ret.length is probably always zero
  491. // because we drop unreachable code before this
  492. // step. nevertheless, it's good to check.
  493. continue loop;
  494. case stat instanceof AST_If:
  495. if (stat.body instanceof AST_Return) {
  496. //---
  497. // pretty silly case, but:
  498. // if (foo()) return; return; ==> foo(); return;
  499. if (((in_lambda && ret.length == 0)
  500. || (ret[0] instanceof AST_Return && !ret[0].value))
  501. && !stat.body.value && !stat.alternative) {
  502. CHANGED = true;
  503. var cond = make_node(AST_SimpleStatement, stat.condition, {
  504. body: stat.condition
  505. });
  506. ret.unshift(cond);
  507. continue loop;
  508. }
  509. //---
  510. // if (foo()) return x; return y; ==> return foo() ? x : y;
  511. if (ret[0] instanceof AST_Return && stat.body.value && ret[0].value && !stat.alternative) {
  512. CHANGED = true;
  513. stat = stat.clone();
  514. stat.alternative = ret[0];
  515. ret[0] = stat.transform(compressor);
  516. continue loop;
  517. }
  518. //---
  519. // if (foo()) return x; [ return ; ] ==> return foo() ? x : undefined;
  520. if (multiple_if_returns && (ret.length == 0 || ret[0] instanceof AST_Return)
  521. && stat.body.value && !stat.alternative && in_lambda) {
  522. CHANGED = true;
  523. stat = stat.clone();
  524. stat.alternative = ret[0] || make_node(AST_Return, stat, {
  525. value: make_node(AST_Undefined, stat)
  526. });
  527. ret[0] = stat.transform(compressor);
  528. continue loop;
  529. }
  530. //---
  531. // if (foo()) return; [ else x... ]; y... ==> if (!foo()) { x...; y... }
  532. if (!stat.body.value && in_lambda) {
  533. CHANGED = true;
  534. stat = stat.clone();
  535. stat.condition = stat.condition.negate(compressor);
  536. var body = as_statement_array(stat.alternative).concat(ret);
  537. var funs = extract_functions_from_statement_array(body);
  538. stat.body = make_node(AST_BlockStatement, stat, {
  539. body: body
  540. });
  541. stat.alternative = null;
  542. ret = funs.concat([ stat.transform(compressor) ]);
  543. continue loop;
  544. }
  545. //---
  546. // XXX: what was the intention of this case?
  547. // if sequences is not enabled, this can lead to an endless loop (issue #866).
  548. // however, with sequences on this helps producing slightly better output for
  549. // the example code.
  550. if (compressor.option("sequences")
  551. && ret.length == 1 && in_lambda && ret[0] instanceof AST_SimpleStatement
  552. && (!stat.alternative || stat.alternative instanceof AST_SimpleStatement)) {
  553. CHANGED = true;
  554. ret.push(make_node(AST_Return, ret[0], {
  555. value: make_node(AST_Undefined, ret[0])
  556. }).transform(compressor));
  557. ret = as_statement_array(stat.alternative).concat(ret);
  558. ret.unshift(stat);
  559. continue loop;
  560. }
  561. }
  562. var ab = aborts(stat.body);
  563. var lct = ab instanceof AST_LoopControl ? compressor.loopcontrol_target(ab.label) : null;
  564. if (ab && ((ab instanceof AST_Return && !ab.value && in_lambda)
  565. || (ab instanceof AST_Continue && self === loop_body(lct))
  566. || (ab instanceof AST_Break && lct instanceof AST_BlockStatement && self === lct))) {
  567. if (ab.label) {
  568. remove(ab.label.thedef.references, ab);
  569. }
  570. CHANGED = true;
  571. var body = as_statement_array(stat.body).slice(0, -1);
  572. stat = stat.clone();
  573. stat.condition = stat.condition.negate(compressor);
  574. stat.body = make_node(AST_BlockStatement, stat, {
  575. body: as_statement_array(stat.alternative).concat(ret)
  576. });
  577. stat.alternative = make_node(AST_BlockStatement, stat, {
  578. body: body
  579. });
  580. ret = [ stat.transform(compressor) ];
  581. continue loop;
  582. }
  583. var ab = aborts(stat.alternative);
  584. var lct = ab instanceof AST_LoopControl ? compressor.loopcontrol_target(ab.label) : null;
  585. if (ab && ((ab instanceof AST_Return && !ab.value && in_lambda)
  586. || (ab instanceof AST_Continue && self === loop_body(lct))
  587. || (ab instanceof AST_Break && lct instanceof AST_BlockStatement && self === lct))) {
  588. if (ab.label) {
  589. remove(ab.label.thedef.references, ab);
  590. }
  591. CHANGED = true;
  592. stat = stat.clone();
  593. stat.body = make_node(AST_BlockStatement, stat.body, {
  594. body: as_statement_array(stat.body).concat(ret)
  595. });
  596. stat.alternative = make_node(AST_BlockStatement, stat.alternative, {
  597. body: as_statement_array(stat.alternative).slice(0, -1)
  598. });
  599. ret = [ stat.transform(compressor) ];
  600. continue loop;
  601. }
  602. ret.unshift(stat);
  603. break;
  604. default:
  605. ret.unshift(stat);
  606. break;
  607. }
  608. }
  609. return ret;
  610. function has_multiple_if_returns(statements) {
  611. var n = 0;
  612. for (var i = statements.length; --i >= 0;) {
  613. var stat = statements[i];
  614. if (stat instanceof AST_If && stat.body instanceof AST_Return) {
  615. if (++n > 1) return true;
  616. }
  617. }
  618. return false;
  619. }
  620. };
  621. function eliminate_dead_code(statements, compressor) {
  622. var has_quit = false;
  623. var orig = statements.length;
  624. var self = compressor.self();
  625. statements = statements.reduce(function(a, stat){
  626. if (has_quit) {
  627. extract_declarations_from_unreachable_code(compressor, stat, a);
  628. } else {
  629. if (stat instanceof AST_LoopControl) {
  630. var lct = compressor.loopcontrol_target(stat.label);
  631. if ((stat instanceof AST_Break
  632. && lct instanceof AST_BlockStatement
  633. && loop_body(lct) === self) || (stat instanceof AST_Continue
  634. && loop_body(lct) === self)) {
  635. if (stat.label) {
  636. remove(stat.label.thedef.references, stat);
  637. }
  638. } else {
  639. a.push(stat);
  640. }
  641. } else {
  642. a.push(stat);
  643. }
  644. if (aborts(stat)) has_quit = true;
  645. }
  646. return a;
  647. }, []);
  648. CHANGED = statements.length != orig;
  649. return statements;
  650. };
  651. function sequencesize(statements, compressor) {
  652. if (statements.length < 2) return statements;
  653. var seq = [], ret = [];
  654. function push_seq() {
  655. seq = AST_Seq.from_array(seq);
  656. if (seq) ret.push(make_node(AST_SimpleStatement, seq, {
  657. body: seq
  658. }));
  659. seq = [];
  660. };
  661. statements.forEach(function(stat){
  662. if (stat instanceof AST_SimpleStatement && seqLength(seq) < 2000) {
  663. seq.push(stat.body);
  664. } else {
  665. push_seq();
  666. ret.push(stat);
  667. }
  668. });
  669. push_seq();
  670. ret = sequencesize_2(ret, compressor);
  671. CHANGED = ret.length != statements.length;
  672. return ret;
  673. };
  674. function seqLength(a) {
  675. for (var len = 0, i = 0; i < a.length; ++i) {
  676. var stat = a[i];
  677. if (stat instanceof AST_Seq) {
  678. len += stat.len();
  679. } else {
  680. len++;
  681. }
  682. }
  683. return len;
  684. };
  685. function sequencesize_2(statements, compressor) {
  686. function cons_seq(right) {
  687. ret.pop();
  688. var left = prev.body;
  689. if (left instanceof AST_Seq) {
  690. left.add(right);
  691. } else {
  692. left = AST_Seq.cons(left, right);
  693. }
  694. return left.transform(compressor);
  695. };
  696. var ret = [], prev = null;
  697. statements.forEach(function(stat){
  698. if (prev) {
  699. if (stat instanceof AST_For) {
  700. var opera = {};
  701. try {
  702. prev.body.walk(new TreeWalker(function(node){
  703. if (node instanceof AST_Binary && node.operator == "in")
  704. throw opera;
  705. }));
  706. if (stat.init && !(stat.init instanceof AST_Definitions)) {
  707. stat.init = cons_seq(stat.init);
  708. }
  709. else if (!stat.init) {
  710. stat.init = prev.body;
  711. ret.pop();
  712. }
  713. } catch(ex) {
  714. if (ex !== opera) throw ex;
  715. }
  716. }
  717. else if (stat instanceof AST_If) {
  718. stat.condition = cons_seq(stat.condition);
  719. }
  720. else if (stat instanceof AST_With) {
  721. stat.expression = cons_seq(stat.expression);
  722. }
  723. else if (stat instanceof AST_Exit && stat.value) {
  724. stat.value = cons_seq(stat.value);
  725. }
  726. else if (stat instanceof AST_Exit) {
  727. stat.value = cons_seq(make_node(AST_Undefined, stat));
  728. }
  729. else if (stat instanceof AST_Switch) {
  730. stat.expression = cons_seq(stat.expression);
  731. }
  732. }
  733. ret.push(stat);
  734. prev = stat instanceof AST_SimpleStatement ? stat : null;
  735. });
  736. return ret;
  737. };
  738. function join_consecutive_vars(statements, compressor) {
  739. var prev = null;
  740. return statements.reduce(function(a, stat){
  741. if (stat instanceof AST_Definitions && prev && prev.TYPE == stat.TYPE) {
  742. prev.definitions = prev.definitions.concat(stat.definitions);
  743. CHANGED = true;
  744. }
  745. else if (stat instanceof AST_For
  746. && prev instanceof AST_Definitions
  747. && (!stat.init || stat.init.TYPE == prev.TYPE)) {
  748. CHANGED = true;
  749. a.pop();
  750. if (stat.init) {
  751. stat.init.definitions = prev.definitions.concat(stat.init.definitions);
  752. } else {
  753. stat.init = prev;
  754. }
  755. a.push(stat);
  756. prev = stat;
  757. }
  758. else {
  759. prev = stat;
  760. a.push(stat);
  761. }
  762. return a;
  763. }, []);
  764. };
  765. function negate_iifes(statements, compressor) {
  766. statements.forEach(function(stat){
  767. if (stat instanceof AST_SimpleStatement) {
  768. stat.body = (function transform(thing) {
  769. return thing.transform(new TreeTransformer(function(node){
  770. if (node instanceof AST_New) {
  771. return node;
  772. }
  773. if (node instanceof AST_Call && node.expression instanceof AST_Function) {
  774. return make_node(AST_UnaryPrefix, node, {
  775. operator: "!",
  776. expression: node
  777. });
  778. }
  779. else if (node instanceof AST_Call) {
  780. node.expression = transform(node.expression);
  781. }
  782. else if (node instanceof AST_Seq) {
  783. node.car = transform(node.car);
  784. }
  785. else if (node instanceof AST_Conditional) {
  786. var expr = transform(node.condition);
  787. if (expr !== node.condition) {
  788. // it has been negated, reverse
  789. node.condition = expr;
  790. var tmp = node.consequent;
  791. node.consequent = node.alternative;
  792. node.alternative = tmp;
  793. }
  794. }
  795. return node;
  796. }));
  797. })(stat.body);
  798. }
  799. });
  800. };
  801. };
  802. function extract_functions_from_statement_array(statements) {
  803. var funs = [];
  804. for (var i = statements.length - 1; i >= 0; --i) {
  805. var stat = statements[i];
  806. if (stat instanceof AST_Defun) {
  807. statements.splice(i, 1);
  808. funs.unshift(stat);
  809. }
  810. }
  811. return funs;
  812. }
  813. function extract_declarations_from_unreachable_code(compressor, stat, target) {
  814. if (!(stat instanceof AST_Defun)) {
  815. compressor.warn("Dropping unreachable code [{file}:{line},{col}]", stat.start);
  816. }
  817. stat.walk(new TreeWalker(function(node){
  818. if (node instanceof AST_Definitions) {
  819. compressor.warn("Declarations in unreachable code! [{file}:{line},{col}]", node.start);
  820. node.remove_initializers();
  821. target.push(node);
  822. return true;
  823. }
  824. if (node instanceof AST_Defun) {
  825. target.push(node);
  826. return true;
  827. }
  828. if (node instanceof AST_Scope) {
  829. return true;
  830. }
  831. }));
  832. };
  833. /* -----[ boolean/negation helpers ]----- */
  834. // methods to determine whether an expression has a boolean result type
  835. (function (def){
  836. var unary_bool = [ "!", "delete" ];
  837. var binary_bool = [ "in", "instanceof", "==", "!=", "===", "!==", "<", "<=", ">=", ">" ];
  838. def(AST_Node, function(){ return false });
  839. def(AST_UnaryPrefix, function(){
  840. return member(this.operator, unary_bool);
  841. });
  842. def(AST_Binary, function(){
  843. return member(this.operator, binary_bool) ||
  844. ( (this.operator == "&&" || this.operator == "||") &&
  845. this.left.is_boolean() && this.right.is_boolean() );
  846. });
  847. def(AST_Conditional, function(){
  848. return this.consequent.is_boolean() && this.alternative.is_boolean();
  849. });
  850. def(AST_Assign, function(){
  851. return this.operator == "=" && this.right.is_boolean();
  852. });
  853. def(AST_Seq, function(){
  854. return this.cdr.is_boolean();
  855. });
  856. def(AST_True, function(){ return true });
  857. def(AST_False, function(){ return true });
  858. })(function(node, func){
  859. node.DEFMETHOD("is_boolean", func);
  860. });
  861. // methods to determine if an expression has a string result type
  862. (function (def){
  863. def(AST_Node, function(){ return false });
  864. def(AST_String, function(){ return true });
  865. def(AST_UnaryPrefix, function(){
  866. return this.operator == "typeof";
  867. });
  868. def(AST_Binary, function(compressor){
  869. return this.operator == "+" &&
  870. (this.left.is_string(compressor) || this.right.is_string(compressor));
  871. });
  872. def(AST_Assign, function(compressor){
  873. return (this.operator == "=" || this.operator == "+=") && this.right.is_string(compressor);
  874. });
  875. def(AST_Seq, function(compressor){
  876. return this.cdr.is_string(compressor);
  877. });
  878. def(AST_Conditional, function(compressor){
  879. return this.consequent.is_string(compressor) && this.alternative.is_string(compressor);
  880. });
  881. def(AST_Call, function(compressor){
  882. return compressor.option("unsafe")
  883. && this.expression instanceof AST_SymbolRef
  884. && this.expression.name == "String"
  885. && this.expression.undeclared();
  886. });
  887. })(function(node, func){
  888. node.DEFMETHOD("is_string", func);
  889. });
  890. function best_of(ast1, ast2) {
  891. return ast1.print_to_string().length >
  892. ast2.print_to_string().length
  893. ? ast2 : ast1;
  894. };
  895. // methods to evaluate a constant expression
  896. (function (def){
  897. // The evaluate method returns an array with one or two
  898. // elements. If the node has been successfully reduced to a
  899. // constant, then the second element tells us the value;
  900. // otherwise the second element is missing. The first element
  901. // of the array is always an AST_Node descendant; if
  902. // evaluation was successful it's a node that represents the
  903. // constant; otherwise it's the original or a replacement node.
  904. AST_Node.DEFMETHOD("evaluate", function(compressor){
  905. if (!compressor.option("evaluate")) return [ this ];
  906. try {
  907. var val = this._eval(compressor);
  908. return [ best_of(make_node_from_constant(compressor, val, this), this), val ];
  909. } catch(ex) {
  910. if (ex !== def) throw ex;
  911. return [ this ];
  912. }
  913. });
  914. AST_Node.DEFMETHOD("is_constant", function(compressor){
  915. // Accomodate when compress option evaluate=false
  916. // as well as the common constant expressions !0 and !1
  917. return this instanceof AST_Constant
  918. || (this instanceof AST_UnaryPrefix && this.operator == "!"
  919. && this.expression instanceof AST_Constant)
  920. || this.evaluate(compressor).length > 1;
  921. });
  922. // Obtain the constant value of an expression already known to be constant.
  923. // Result only valid iff this.is_constant(compressor) is true.
  924. AST_Node.DEFMETHOD("constant_value", function(compressor){
  925. // Accomodate when option evaluate=false.
  926. if (this instanceof AST_Constant) return this.value;
  927. // Accomodate the common constant expressions !0 and !1 when option evaluate=false.
  928. if (this instanceof AST_UnaryPrefix
  929. && this.operator == "!"
  930. && this.expression instanceof AST_Constant) {
  931. return !this.expression.value;
  932. }
  933. var result = this.evaluate(compressor)
  934. if (result.length > 1) {
  935. return result[1];
  936. }
  937. // should never be reached
  938. return undefined;
  939. });
  940. def(AST_Statement, function(){
  941. throw new Error(string_template("Cannot evaluate a statement [{file}:{line},{col}]", this.start));
  942. });
  943. def(AST_Function, function(){
  944. // XXX: AST_Function inherits from AST_Scope, which itself
  945. // inherits from AST_Statement; however, an AST_Function
  946. // isn't really a statement. This could byte in other
  947. // places too. :-( Wish JS had multiple inheritance.
  948. throw def;
  949. });
  950. function ev(node, compressor) {
  951. if (!compressor) throw new Error("Compressor must be passed");
  952. return node._eval(compressor);
  953. };
  954. def(AST_Node, function(){
  955. throw def; // not constant
  956. });
  957. def(AST_Constant, function(){
  958. return this.getValue();
  959. });
  960. def(AST_UnaryPrefix, function(compressor){
  961. var e = this.expression;
  962. switch (this.operator) {
  963. case "!": return !ev(e, compressor);
  964. case "typeof":
  965. // Function would be evaluated to an array and so typeof would
  966. // incorrectly return 'object'. Hence making is a special case.
  967. if (e instanceof AST_Function) return typeof function(){};
  968. e = ev(e, compressor);
  969. // typeof <RegExp> returns "object" or "function" on different platforms
  970. // so cannot evaluate reliably
  971. if (e instanceof RegExp) throw def;
  972. return typeof e;
  973. case "void": return void ev(e, compressor);
  974. case "~": return ~ev(e, compressor);
  975. case "-": return -ev(e, compressor);
  976. case "+": return +ev(e, compressor);
  977. }
  978. throw def;
  979. });
  980. def(AST_Binary, function(c){
  981. var left = this.left, right = this.right, result;
  982. switch (this.operator) {
  983. case "&&" : result = ev(left, c) && ev(right, c); break;
  984. case "||" : result = ev(left, c) || ev(right, c); break;
  985. case "|" : result = ev(left, c) | ev(right, c); break;
  986. case "&" : result = ev(left, c) & ev(right, c); break;
  987. case "^" : result = ev(left, c) ^ ev(right, c); break;
  988. case "+" : result = ev(left, c) + ev(right, c); break;
  989. case "*" : result = ev(left, c) * ev(right, c); break;
  990. case "/" : result = ev(left, c) / ev(right, c); break;
  991. case "%" : result = ev(left, c) % ev(right, c); break;
  992. case "-" : result = ev(left, c) - ev(right, c); break;
  993. case "<<" : result = ev(left, c) << ev(right, c); break;
  994. case ">>" : result = ev(left, c) >> ev(right, c); break;
  995. case ">>>" : result = ev(left, c) >>> ev(right, c); break;
  996. case "==" : result = ev(left, c) == ev(right, c); break;
  997. case "===" : result = ev(left, c) === ev(right, c); break;
  998. case "!=" : result = ev(left, c) != ev(right, c); break;
  999. case "!==" : result = ev(left, c) !== ev(right, c); break;
  1000. case "<" : result = ev(left, c) < ev(right, c); break;
  1001. case "<=" : result = ev(left, c) <= ev(right, c); break;
  1002. case ">" : result = ev(left, c) > ev(right, c); break;
  1003. case ">=" : result = ev(left, c) >= ev(right, c); break;
  1004. default:
  1005. throw def;
  1006. }
  1007. if (isNaN(result) && c.find_parent(AST_With)) {
  1008. // leave original expression as is
  1009. throw def;
  1010. }
  1011. return result;
  1012. });
  1013. def(AST_Conditional, function(compressor){
  1014. return ev(this.condition, compressor)
  1015. ? ev(this.consequent, compressor)
  1016. : ev(this.alternative, compressor);
  1017. });
  1018. def(AST_SymbolRef, function(compressor){
  1019. if (this._evaluating) throw def;
  1020. this._evaluating = true;
  1021. try {
  1022. var d = this.definition();
  1023. if (d && d.constant && d.init) {
  1024. return ev(d.init, compressor);
  1025. }
  1026. } finally {
  1027. this._evaluating = false;
  1028. }
  1029. throw def;
  1030. });
  1031. def(AST_Dot, function(compressor){
  1032. if (compressor.option("unsafe") && this.property == "length") {
  1033. var str = ev(this.expression, compressor);
  1034. if (typeof str == "string")
  1035. return str.length;
  1036. }
  1037. throw def;
  1038. });
  1039. })(function(node, func){
  1040. node.DEFMETHOD("_eval", func);
  1041. });
  1042. // method to negate an expression
  1043. (function(def){
  1044. function basic_negation(exp) {
  1045. return make_node(AST_UnaryPrefix, exp, {
  1046. operator: "!",
  1047. expression: exp
  1048. });
  1049. };
  1050. def(AST_Node, function(){
  1051. return basic_negation(this);
  1052. });
  1053. def(AST_Statement, function(){
  1054. throw new Error("Cannot negate a statement");
  1055. });
  1056. def(AST_Function, function(){
  1057. return basic_negation(this);
  1058. });
  1059. def(AST_UnaryPrefix, function(){
  1060. if (this.operator == "!")
  1061. return this.expression;
  1062. return basic_negation(this);
  1063. });
  1064. def(AST_Seq, function(compressor){
  1065. var self = this.clone();
  1066. self.cdr = self.cdr.negate(compressor);
  1067. return self;
  1068. });
  1069. def(AST_Conditional, function(compressor){
  1070. var self = this.clone();
  1071. self.consequent = self.consequent.negate(compressor);
  1072. self.alternative = self.alternative.negate(compressor);
  1073. return best_of(basic_negation(this), self);
  1074. });
  1075. def(AST_Binary, function(compressor){
  1076. var self = this.clone(), op = this.operator;
  1077. if (compressor.option("unsafe_comps")) {
  1078. switch (op) {
  1079. case "<=" : self.operator = ">" ; return self;
  1080. case "<" : self.operator = ">=" ; return self;
  1081. case ">=" : self.operator = "<" ; return self;
  1082. case ">" : self.operator = "<=" ; return self;
  1083. }
  1084. }
  1085. switch (op) {
  1086. case "==" : self.operator = "!="; return self;
  1087. case "!=" : self.operator = "=="; return self;
  1088. case "===": self.operator = "!=="; return self;
  1089. case "!==": self.operator = "==="; return self;
  1090. case "&&":
  1091. self.operator = "||";
  1092. self.left = self.left.negate(compressor);
  1093. self.right = self.right.negate(compressor);
  1094. return best_of(basic_negation(this), self);
  1095. case "||":
  1096. self.operator = "&&";
  1097. self.left = self.left.negate(compressor);
  1098. self.right = self.right.negate(compressor);
  1099. return best_of(basic_negation(this), self);
  1100. }
  1101. return basic_negation(this);
  1102. });
  1103. })(function(node, func){
  1104. node.DEFMETHOD("negate", function(compressor){
  1105. return func.call(this, compressor);
  1106. });
  1107. });
  1108. // determine if expression has side effects
  1109. (function(def){
  1110. def(AST_Node, function(compressor){ return true });
  1111. def(AST_EmptyStatement, function(compressor){ return false });
  1112. def(AST_Constant, function(compressor){ return false });
  1113. def(AST_This, function(compressor){ return false });
  1114. def(AST_Call, function(compressor){
  1115. var pure = compressor.option("pure_funcs");
  1116. if (!pure) return true;
  1117. if (typeof pure == "function") return pure(this);
  1118. return pure.indexOf(this.expression.print_to_string()) < 0;
  1119. });
  1120. def(AST_Block, function(compressor){
  1121. for (var i = this.body.length; --i >= 0;) {
  1122. if (this.body[i].has_side_effects(compressor))
  1123. return true;
  1124. }
  1125. return false;
  1126. });
  1127. def(AST_SimpleStatement, function(compressor){
  1128. return this.body.has_side_effects(compressor);
  1129. });
  1130. def(AST_Defun, function(compressor){ return true });
  1131. def(AST_Function, function(compressor){ return false });
  1132. def(AST_Binary, function(compressor){
  1133. return this.left.has_side_effects(compressor)
  1134. || this.right.has_side_effects(compressor);
  1135. });
  1136. def(AST_Assign, function(compressor){ return true });
  1137. def(AST_Conditional, function(compressor){
  1138. return this.condition.has_side_effects(compressor)
  1139. || this.consequent.has_side_effects(compressor)
  1140. || this.alternative.has_side_effects(compressor);
  1141. });
  1142. def(AST_Unary, function(compressor){
  1143. return this.operator == "delete"
  1144. || this.operator == "++"
  1145. || this.operator == "--"
  1146. || this.expression.has_side_effects(compressor);
  1147. });
  1148. def(AST_SymbolRef, function(compressor){
  1149. return this.global() && this.undeclared();
  1150. });
  1151. def(AST_Object, function(compressor){
  1152. for (var i = this.properties.length; --i >= 0;)
  1153. if (this.properties[i].has_side_effects(compressor))
  1154. return true;
  1155. return false;
  1156. });
  1157. def(AST_ObjectProperty, function(compressor){
  1158. return this.value.has_side_effects(compressor);
  1159. });
  1160. def(AST_Array, function(compressor){
  1161. for (var i = this.elements.length; --i >= 0;)
  1162. if (this.elements[i].has_side_effects(compressor))
  1163. return true;
  1164. return false;
  1165. });
  1166. def(AST_Dot, function(compressor){
  1167. if (!compressor.option("pure_getters")) return true;
  1168. return this.expression.has_side_effects(compressor);
  1169. });
  1170. def(AST_Sub, function(compressor){
  1171. if (!compressor.option("pure_getters")) return true;
  1172. return this.expression.has_side_effects(compressor)
  1173. || this.property.has_side_effects(compressor);
  1174. });
  1175. def(AST_PropAccess, function(compressor){
  1176. return !compressor.option("pure_getters");
  1177. });
  1178. def(AST_Seq, function(compressor){
  1179. return this.car.has_side_effects(compressor)
  1180. || this.cdr.has_side_effects(compressor);
  1181. });
  1182. })(function(node, func){
  1183. node.DEFMETHOD("has_side_effects", func);
  1184. });
  1185. // tell me if a statement aborts
  1186. function aborts(thing) {
  1187. return thing && thing.aborts();
  1188. };
  1189. (function(def){
  1190. def(AST_Statement, function(){ return null });
  1191. def(AST_Jump, function(){ return this });
  1192. function block_aborts(){
  1193. var n = this.body.length;
  1194. return n > 0 && aborts(this.body[n - 1]);
  1195. };
  1196. def(AST_BlockStatement, block_aborts);
  1197. def(AST_SwitchBranch, block_aborts);
  1198. def(AST_If, function(){
  1199. return this.alternative && aborts(this.body) && aborts(this.alternative) && this;
  1200. });
  1201. })(function(node, func){
  1202. node.DEFMETHOD("aborts", func);
  1203. });
  1204. /* -----[ optimizers ]----- */
  1205. OPT(AST_Directive, function(self, compressor){
  1206. if (compressor.has_directive(self.value) === "up") {
  1207. return make_node(AST_EmptyStatement, self);
  1208. }
  1209. return self;
  1210. });
  1211. OPT(AST_Debugger, function(self, compressor){
  1212. if (compressor.option("drop_debugger"))
  1213. return make_node(AST_EmptyStatement, self);
  1214. return self;
  1215. });
  1216. OPT(AST_LabeledStatement, function(self, compressor){
  1217. if (self.body instanceof AST_Break
  1218. && compressor.loopcontrol_target(self.body.label) === self.body) {
  1219. return make_node(AST_EmptyStatement, self);
  1220. }
  1221. return self.label.references.length == 0 ? self.body : self;
  1222. });
  1223. OPT(AST_Block, function(self, compressor){
  1224. self.body = tighten_body(self.body, compressor);
  1225. return self;
  1226. });
  1227. OPT(AST_BlockStatement, function(self, compressor){
  1228. self.body = tighten_body(self.body, compressor);
  1229. switch (self.body.length) {
  1230. case 1: return self.body[0];
  1231. case 0: return make_node(AST_EmptyStatement, self);
  1232. }
  1233. return self;
  1234. });
  1235. AST_Scope.DEFMETHOD("drop_unused", function(compressor){
  1236. var self = this;
  1237. if (compressor.has_directive("use asm")) return self;
  1238. if (compressor.option("unused")
  1239. && !(self instanceof AST_Toplevel)
  1240. && !self.uses_eval
  1241. && !self.uses_with
  1242. ) {
  1243. var in_use = [];
  1244. var in_use_ids = {}; // avoid expensive linear scans of in_use
  1245. var initializations = new Dictionary();
  1246. // pass 1: find out which symbols are directly used in
  1247. // this scope (not in nested scopes).
  1248. var scope = this;
  1249. var tw = new TreeWalker(function(node, descend){
  1250. if (node !== self) {
  1251. if (node instanceof AST_Defun) {
  1252. initializations.add(node.name.name, node);
  1253. return true; // don't go in nested scopes
  1254. }
  1255. if (node instanceof AST_Definitions && scope === self) {
  1256. node.definitions.forEach(function(def){
  1257. if (def.value) {
  1258. initializations.add(def.name.name, def.value);
  1259. if (def.value.has_side_effects(compressor)) {
  1260. def.value.walk(tw);
  1261. }
  1262. }
  1263. });
  1264. return true;
  1265. }
  1266. if (node instanceof AST_SymbolRef) {
  1267. var node_def = node.definition();
  1268. if (!(node_def.id in in_use_ids)) {
  1269. in_use_ids[node_def.id] = true;
  1270. in_use.push(node_def);
  1271. }
  1272. return true;
  1273. }
  1274. if (node instanceof AST_Scope) {
  1275. var save_scope = scope;
  1276. scope = node;
  1277. descend();
  1278. scope = save_scope;
  1279. return true;
  1280. }
  1281. }
  1282. });
  1283. self.walk(tw);
  1284. // pass 2: for every used symbol we need to walk its
  1285. // initialization code to figure out if it uses other
  1286. // symbols (that may not be in_use).
  1287. for (var i = 0; i < in_use.length; ++i) {
  1288. in_use[i].orig.forEach(function(decl){
  1289. // undeclared globals will be instanceof AST_SymbolRef
  1290. var init = initializations.get(decl.name);
  1291. if (init) init.forEach(function(init){
  1292. var tw = new TreeWalker(function(node){
  1293. if (node instanceof AST_SymbolRef) {
  1294. var node_def = node.definition();
  1295. if (!(node_def.id in in_use_ids)) {
  1296. in_use_ids[node_def.id] = true;
  1297. in_use.push(node_def);
  1298. }
  1299. }
  1300. });
  1301. init.walk(tw);
  1302. });
  1303. });
  1304. }
  1305. // pass 3: we should drop declarations not in_use
  1306. var tt = new TreeTransformer(
  1307. function before(node, descend, in_list) {
  1308. if (node instanceof AST_Lambda && !(node instanceof AST_Accessor)) {
  1309. if (!compressor.option("keep_fargs")) {
  1310. for (var a = node.argnames, i = a.length; --i >= 0;) {
  1311. var sym = a[i];
  1312. if (sym.unreferenced()) {
  1313. a.pop();
  1314. compressor.warn("Dropping unused function argument {name} [{file}:{line},{col}]", {
  1315. name : sym.name,
  1316. file : sym.start.file,
  1317. line : sym.start.line,
  1318. col : sym.start.col
  1319. });
  1320. }
  1321. else break;
  1322. }
  1323. }
  1324. }
  1325. if (node instanceof AST_Defun && node !== self) {
  1326. if (!(node.name.definition().id in in_use_ids)) {
  1327. compressor.warn("Dropping unused function {name} [{file}:{line},{col}]", {
  1328. name : node.name.name,
  1329. file : node.name.start.file,
  1330. line : node.name.start.line,
  1331. col : node.name.start.col
  1332. });
  1333. return make_node(AST_EmptyStatement, node);
  1334. }
  1335. return node;
  1336. }
  1337. if (node instanceof AST_Definitions && !(tt.parent() instanceof AST_ForIn)) {
  1338. var def = node.definitions.filter(function(def){
  1339. if (def.name.definition().id in in_use_ids) return true;
  1340. var w = {
  1341. name : def.name.name,
  1342. file : def.name.start.file,
  1343. line : def.name.start.line,
  1344. col : def.name.start.col
  1345. };
  1346. if (def.value && def.value.has_side_effects(compressor)) {
  1347. def._unused_side_effects = true;
  1348. compressor.warn("Side effects in initialization of unused variable {name} [{file}:{line},{col}]", w);
  1349. return true;
  1350. }
  1351. compressor.warn("Dropping unused variable {name} [{file}:{line},{col}]", w);
  1352. return false;
  1353. });
  1354. // place uninitialized names at the start
  1355. def = mergeSort(def, function(a, b){
  1356. if (!a.value && b.value) return -1;
  1357. if (!b.value && a.value) return 1;
  1358. return 0;
  1359. });
  1360. // for unused names whose initialization has
  1361. // side effects, we can cascade the init. code
  1362. // into the next one, or next statement.
  1363. var side_effects = [];
  1364. for (var i = 0; i < def.length;) {
  1365. var x = def[i];
  1366. if (x._unused_side_effects) {
  1367. side_effects.push(x.value);
  1368. def.splice(i, 1);
  1369. } else {
  1370. if (side_effects.length > 0) {
  1371. side_effects.push(x.value);
  1372. x.value = AST_Seq.from_array(side_effects);
  1373. side_effects = [];
  1374. }
  1375. ++i;
  1376. }
  1377. }
  1378. if (side_effects.length > 0) {
  1379. side_effects = make_node(AST_BlockStatement, node, {
  1380. body: [ make_node(AST_SimpleStatement, node, {
  1381. body: AST_Seq.from_array(side_effects)
  1382. }) ]
  1383. });
  1384. } else {
  1385. side_effects = null;
  1386. }
  1387. if (def.length == 0 && !side_effects) {
  1388. return make_node(AST_EmptyStatement, node);
  1389. }
  1390. if (def.length == 0) {
  1391. return in_list ? MAP.splice(side_effects.body) : side_effects;
  1392. }
  1393. node.definitions = def;
  1394. if (side_effects) {
  1395. side_effects.body.unshift(node);
  1396. return in_list ? MAP.splice(side_effects.body) : side_effects;
  1397. }
  1398. return node;
  1399. }
  1400. if (node instanceof AST_For) {
  1401. descend(node, this);
  1402. if (node.init instanceof AST_BlockStatement) {
  1403. // certain combination of unused name + side effect leads to:
  1404. // https://github.com/mishoo/UglifyJS2/issues/44
  1405. // that's an invalid AST.
  1406. // We fix it at this stage by moving the `var` outside the `for`.
  1407. var body = node.init.body.slice(0, -1);
  1408. node.init = node.init.body.slice(-1)[0].body;
  1409. body.push(node);
  1410. return in_list ? MAP.splice(body) : make_node(AST_BlockStatement, node, {
  1411. body: body
  1412. });
  1413. }
  1414. }
  1415. if (node instanceof AST_Scope && node !== self)
  1416. return node;
  1417. }
  1418. );
  1419. self.transform(tt);
  1420. }
  1421. });
  1422. AST_Scope.DEFMETHOD("hoist_declarations", function(compressor){
  1423. var self = this;
  1424. if (compressor.has_directive("use asm")) return self;
  1425. var hoist_funs = compressor.option("hoist_funs");
  1426. var hoist_vars = compressor.option("hoist_vars");
  1427. if (hoist_funs || hoist_vars) {
  1428. var dirs = [];
  1429. var hoisted = [];
  1430. var vars = new Dictionary(), vars_found = 0, var_decl = 0;
  1431. // let's count var_decl first, we seem to waste a lot of
  1432. // space if we hoist `var` when there's only one.
  1433. self.walk(new TreeWalker(function(node){
  1434. if (node instanceof AST_Scope && node !== self)
  1435. return true;
  1436. if (node instanceof AST_Var) {
  1437. ++var_decl;
  1438. return true;
  1439. }
  1440. }));
  1441. hoist_vars = hoist_vars && var_decl > 1;
  1442. var tt = new TreeTransformer(
  1443. function before(node) {
  1444. if (node !== self) {
  1445. if (node instanceof AST_Directive) {
  1446. dirs.push(node);
  1447. return make_node(AST_EmptyStatement, node);
  1448. }
  1449. if (node instanceof AST_Defun && hoist_funs) {
  1450. hoisted.push(node);
  1451. return make_node(AST_EmptyStatement, node);
  1452. }
  1453. if (node instanceof AST_Var && hoist_vars) {
  1454. node.definitions.forEach(function(def){
  1455. vars.set(def.name.name, def);
  1456. ++vars_found;
  1457. });
  1458. var seq = node.to_assignments();
  1459. var p = tt.parent();
  1460. if (p instanceof AST_ForIn && p.init === node) {
  1461. if (seq == null) {
  1462. var def = node.definitions[0].name;
  1463. return make_node(AST_SymbolRef, def, def);
  1464. }
  1465. return seq;
  1466. }
  1467. if (p instanceof AST_For && p.init === node) {
  1468. return seq;
  1469. }
  1470. if (!seq) return make_node(AST_EmptyStatement, node);
  1471. return make_node(AST_SimpleStatement, node, {
  1472. body: seq
  1473. });
  1474. }
  1475. if (node instanceof AST_Scope)
  1476. return node; // to avoid descending in nested scopes
  1477. }
  1478. }
  1479. );
  1480. self = self.transform(tt);
  1481. if (vars_found > 0) {
  1482. // collect only vars which don't show up in self's arguments list
  1483. var defs = [];
  1484. vars.each(function(def, name){
  1485. if (self instanceof AST_Lambda
  1486. && find_if(function(x){ return x.name == def.name.name },
  1487. self.argnames)) {
  1488. vars.del(name);
  1489. } else {
  1490. def = def.clone();
  1491. def.value = null;
  1492. defs.push(def);
  1493. vars.set(name, def);
  1494. }
  1495. });
  1496. if (defs.length > 0) {
  1497. // try to merge in assignments
  1498. for (var i = 0; i < self.body.length;) {
  1499. if (self.body[i] instanceof AST_SimpleStatement) {
  1500. var expr = self.body[i].body, sym, assign;
  1501. if (expr instanceof AST_Assign
  1502. && expr.operator == "="
  1503. && (sym = expr.left) instanceof AST_Symbol
  1504. && vars.has(sym.name))
  1505. {
  1506. var def = vars.get(sym.name);
  1507. if (def.value) break;
  1508. def.value = expr.right;
  1509. remove(defs, def);
  1510. defs.push(def);
  1511. self.body.splice(i, 1);
  1512. continue;
  1513. }
  1514. if (expr instanceof AST_Seq
  1515. && (assign = expr.car) instanceof AST_Assign
  1516. && assign.operator == "="
  1517. && (sym = assign.left) instanceof AST_Symbol
  1518. && vars.has(sym.name))
  1519. {
  1520. var def = vars.get(sym.name);
  1521. if (def.value) break;
  1522. def.value = assign.right;
  1523. remove(defs, def);
  1524. defs.push(def);
  1525. self.body[i].body = expr.cdr;
  1526. continue;
  1527. }
  1528. }
  1529. if (self.body[i] instanceof AST_EmptyStatement) {
  1530. self.body.splice(i, 1);
  1531. continue;
  1532. }
  1533. if (self.body[i] instanceof AST_BlockStatement) {
  1534. var tmp = [ i, 1 ].concat(self.body[i].body);
  1535. self.body.splice.apply(self.body, tmp);
  1536. continue;
  1537. }
  1538. break;
  1539. }
  1540. defs = make_node(AST_Var, self, {
  1541. definitions: defs
  1542. });
  1543. hoisted.push(defs);
  1544. };
  1545. }
  1546. self.body = dirs.concat(hoisted, self.body);
  1547. }
  1548. return self;
  1549. });
  1550. OPT(AST_SimpleStatement, function(self, compressor){
  1551. if (compressor.option("side_effects")) {
  1552. if (!self.body.has_side_effects(compressor)) {
  1553. compressor.warn("Dropping side-effect-free statement [{file}:{line},{col}]", self.start);
  1554. return make_node(AST_EmptyStatement, self);
  1555. }
  1556. }
  1557. return self;
  1558. });
  1559. OPT(AST_DWLoop, function(self, compressor){
  1560. var cond = self.condition.evaluate(compressor);
  1561. self.condition = cond[0];
  1562. if (!compressor.option("loops")) return self;
  1563. if (cond.length > 1) {
  1564. if (cond[1]) {
  1565. return make_node(AST_For, self, {
  1566. body: self.body
  1567. });
  1568. } else if (self instanceof AST_While) {
  1569. if (compressor.option("dead_code")) {
  1570. var a = [];
  1571. extract_declarations_from_unreachable_code(compressor, self.body, a);
  1572. return make_node(AST_BlockStatement, self, { body: a });
  1573. }
  1574. }
  1575. }
  1576. return self;
  1577. });
  1578. function if_break_in_loop(self, compressor) {
  1579. function drop_it(rest) {
  1580. rest = as_statement_array(rest);
  1581. if (self.body instanceof AST_BlockStatement) {
  1582. self.body = self.body.clone();
  1583. self.body.body = rest.concat(self.body.body.slice(1));
  1584. self.body = self.body.transform(compressor);
  1585. } else {
  1586. self.body = make_node(AST_BlockStatement, self.body, {
  1587. body: rest
  1588. }).transform(compressor);
  1589. }
  1590. if_break_in_loop(self, compressor);
  1591. }
  1592. var first = self.body instanceof AST_BlockStatement ? self.body.body[0] : self.body;
  1593. if (first instanceof AST_If) {
  1594. if (first.body instanceof AST_Break
  1595. && compressor.loopcontrol_target(first.body.label) === self) {
  1596. if (self.condition) {
  1597. self.condition = make_node(AST_Binary, self.condition, {
  1598. left: self.condition,
  1599. operator: "&&",
  1600. right: first.condition.negate(compressor),
  1601. });
  1602. } else {
  1603. self.condition = first.condition.negate(compressor);
  1604. }
  1605. drop_it(first.alternative);
  1606. }
  1607. else if (first.alternative instanceof AST_Break
  1608. && compressor.loopcontrol_target(first.alternative.label) === self) {
  1609. if (self.condition) {
  1610. self.condition = make_node(AST_Binary, self.condition, {
  1611. left: self.condition,
  1612. operator: "&&",
  1613. right: first.condition,
  1614. });
  1615. } else {
  1616. self.condition = first.condition;
  1617. }
  1618. drop_it(first.body);
  1619. }
  1620. }
  1621. };
  1622. OPT(AST_While, function(self, compressor) {
  1623. if (!compressor.option("loops")) return self;
  1624. self = AST_DWLoop.prototype.optimize.call(self, compressor);
  1625. if (self instanceof AST_While) {
  1626. if_break_in_loop(self, compressor);
  1627. self = make_node(AST_For, self, self).transform(compressor);
  1628. }
  1629. return self;
  1630. });
  1631. OPT(AST_For, function(self, compressor){
  1632. var cond = self.condition;
  1633. if (cond) {
  1634. cond = cond.evaluate(compressor);
  1635. self.condition = cond[0];
  1636. }
  1637. if (!compressor.option("loops")) return self;
  1638. if (cond) {
  1639. if (cond.length > 1 && !cond[1]) {
  1640. if (compressor.option("dead_code")) {
  1641. var a = [];
  1642. if (self.init instanceof AST_Statement) {
  1643. a.push(self.init);
  1644. }
  1645. else if (self.init) {
  1646. a.push(make_node(AST_SimpleStatement, self.init, {
  1647. body: self.init
  1648. }));
  1649. }
  1650. extract_declarations_from_unreachable_code(compressor, self.body, a);
  1651. return make_node(AST_BlockStatement, self, { body: a });
  1652. }
  1653. }
  1654. }
  1655. if_break_in_loop(self, compressor);
  1656. return self;
  1657. });
  1658. OPT(AST_If, function(self, compressor){
  1659. if (!compressor.option("conditionals")) return self;
  1660. // if condition can be statically determined, warn and drop
  1661. // one of the blocks. note, statically determined implies
  1662. // “has no side effects”; also it doesn't work for cases like
  1663. // `x && true`, though it probably should.
  1664. var cond = self.condition.evaluate(compressor);
  1665. self.condition = cond[0];
  1666. if (cond.length > 1) {
  1667. if (cond[1]) {
  1668. compressor.warn("Condition always true [{file}:{line},{col}]", self.condition.start);
  1669. if (compressor.option("dead_code")) {
  1670. var a = [];
  1671. if (self.alternative) {
  1672. extract_declarations_from_unreachable_code(compressor, self.alternative, a);
  1673. }
  1674. a.push(self.body);
  1675. return make_node(AST_BlockStatement, self, { body: a }).transform(compressor);
  1676. }
  1677. } else {
  1678. compressor.warn("Condition always false [{file}:{line},{col}]", self.condition.start);
  1679. if (compressor.option("dead_code")) {
  1680. var a = [];
  1681. extract_declarations_from_unreachable_code(compressor, self.body, a);
  1682. if (self.alternative) a.push(self.alternative);
  1683. return make_node(AST_BlockStatement, self, { body: a }).transform(compressor);
  1684. }
  1685. }
  1686. }
  1687. if (is_empty(self.alternative)) self.alternative = null;
  1688. var negated = self.condition.negate(compressor);
  1689. var self_condition_length = self.condition.print_to_string().length;
  1690. var negated_length = negated.print_to_string().length;
  1691. var negated_is_best = negated_length < self_condition_length;
  1692. if (self.alternative && negated_is_best) {
  1693. negated_is_best = false; // because we already do the switch here.
  1694. // no need to swap values of self_condition_length and negated_length
  1695. // here because they are only used in an equality comparison later on.
  1696. self.condition = negated;
  1697. var tmp = self.body;
  1698. self.body = self.alternative || make_node(AST_EmptyStatement);
  1699. self.alternative = tmp;
  1700. }
  1701. if (is_empty(self.body) && is_empty(self.alternative)) {
  1702. return make_node(AST_SimpleStatement, self.condition, {
  1703. body: self.condition
  1704. }).transform(compressor);
  1705. }
  1706. if (self.body instanceof AST_SimpleStatement
  1707. && self.alternative instanceof AST_SimpleStatement) {
  1708. return make_node(AST_SimpleStatement, self, {
  1709. body: make_node(AST_Conditional, self, {
  1710. condition : self.condition,
  1711. consequent : self.body.body,
  1712. alternative : self.alternative.body
  1713. })
  1714. }).transform(compressor);
  1715. }
  1716. if (is_empty(self.alternative) && self.body instanceof AST_SimpleStatement) {
  1717. if (self_condition_length === negated_length && !negated_is_best
  1718. && self.condition instanceof AST_Binary && self.condition.operator == "||") {
  1719. // although the code length of self.condition and negated are the same,
  1720. // negated does not require additional surrounding parentheses.
  1721. // see https://github.com/mishoo/UglifyJS2/issues/979
  1722. negated_is_best = true;
  1723. }
  1724. if (negated_is_best) return make_node(AST_SimpleStatement, self, {
  1725. body: make_node(AST_Binary, self, {
  1726. operator : "||",
  1727. left : negated,
  1728. right : self.body.body
  1729. })
  1730. }).transform(compressor);
  1731. return make_node(AST_SimpleStatement, self, {
  1732. body: make_node(AST_Binary, self, {
  1733. operator : "&&",
  1734. left : self.condition,
  1735. right : self.body.body
  1736. })
  1737. }).transform(compressor);
  1738. }
  1739. if (self.body instanceof AST_EmptyStatement
  1740. && self.alternative
  1741. && self.alternative instanceof AST_SimpleStatement) {
  1742. return make_node(AST_SimpleStatement, self, {
  1743. body: make_node(AST_Binary, self, {
  1744. operator : "||",
  1745. left : self.condition,
  1746. right : self.alternative.body
  1747. })
  1748. }).transform(compressor);
  1749. }
  1750. if (self.body instanceof AST_Exit
  1751. && self.alternative instanceof AST_Exit
  1752. && self.body.TYPE == self.alternative.TYPE) {
  1753. return make_node(self.body.CTOR, self, {
  1754. value: make_node(AST_Conditional, self, {
  1755. condition : self.condition,
  1756. consequent : self.body.value || make_node(AST_Undefined, self.body).optimize(compressor),
  1757. alternative : self.alternative.value || make_node(AST_Undefined, self.alternative).optimize(compressor)
  1758. })
  1759. }).transform(compressor);
  1760. }
  1761. if (self.body instanceof AST_If
  1762. && !self.body.alternative
  1763. && !self.alternative) {
  1764. self.condition = make_node(AST_Binary, self.condition, {
  1765. operator: "&&",
  1766. left: self.condition,
  1767. right: self.body.condition
  1768. }).transform(compressor);
  1769. self.body = self.body.body;
  1770. }
  1771. if (aborts(self.body)) {
  1772. if (self.alternative) {
  1773. var alt = self.alternative;
  1774. self.alternative = null;
  1775. return make_node(AST_BlockStatement, self, {
  1776. body: [ self, alt ]
  1777. }).transform(compressor);
  1778. }
  1779. }
  1780. if (aborts(self.alternative)) {
  1781. var body = self.body;
  1782. self.body = self.alternative;
  1783. self.condition = negated_is_best ? negated : self.condition.negate(compressor);
  1784. self.alternative = null;
  1785. return make_node(AST_BlockStatement, self, {
  1786. body: [ self, body ]
  1787. }).transform(compressor);
  1788. }
  1789. return self;
  1790. });
  1791. OPT(AST_Switch, function(self, compressor){
  1792. if (self.body.length == 0 && compressor.option("conditionals")) {
  1793. return make_node(AST_SimpleStatement, self, {
  1794. body: self.expression
  1795. }).transform(compressor);
  1796. }
  1797. for(;;) {
  1798. var last_branch = self.body[self.body.length - 1];
  1799. if (last_branch) {
  1800. var stat = last_branch.body[last_branch.body.length - 1]; // last statement
  1801. if (stat instanceof AST_Break && loop_body(compressor.loopcontrol_target(stat.label)) === self)
  1802. last_branch.body.pop();
  1803. if (last_branch instanceof AST_Default && last_branch.body.length == 0) {
  1804. self.body.pop();
  1805. continue;
  1806. }
  1807. }
  1808. break;
  1809. }
  1810. var exp = self.expression.evaluate(compressor);
  1811. out: if (exp.length == 2) try {
  1812. // constant expression
  1813. self.expression = exp[0];
  1814. if (!compressor.option("dead_code")) break out;
  1815. var value = exp[1];
  1816. var in_if = false;
  1817. var in_block = false;
  1818. var started = false;
  1819. var stopped = false;
  1820. var ruined = false;
  1821. var tt = new TreeTransformer(function(node, descend, in_list){
  1822. if (node instanceof AST_Lambda || node instanceof AST_SimpleStatement) {
  1823. // no need to descend these node types
  1824. return node;
  1825. }
  1826. else if (node instanceof AST_Switch && node === self) {
  1827. node = node.clone();
  1828. descend(node, this);
  1829. return ruined ? node : make_node(AST_BlockStatement, node, {
  1830. body: node.body.reduce(function(a, branch){
  1831. return a.concat(branch.body);
  1832. }, [])
  1833. }).transform(compressor);
  1834. }
  1835. else if (node instanceof AST_If || node instanceof AST_Try) {
  1836. var save = in_if;
  1837. in_if = !in_block;
  1838. descend(node, this);
  1839. in_if = save;
  1840. return node;
  1841. }
  1842. else if (node instanceof AST_StatementWithBody || node instanceof AST_Switch) {
  1843. var save = in_block;
  1844. in_block = true;
  1845. descend(node, this);
  1846. in_block = save;
  1847. return node;
  1848. }
  1849. else if (node instanceof AST_Break && this.loopcontrol_target(node.label) === self) {
  1850. if (in_if) {
  1851. ruined = true;
  1852. return node;
  1853. }
  1854. if (in_block) return node;
  1855. stopped = true;
  1856. return in_list ? MAP.skip : make_node(AST_EmptyStatement, node);
  1857. }
  1858. else if (node instanceof AST_SwitchBranch && this.parent() === self) {
  1859. if (stopped) return MAP.skip;
  1860. if (node instanceof AST_Case) {
  1861. var exp = node.expression.evaluate(compressor);
  1862. if (exp.length < 2) {
  1863. // got a case with non-constant expression, baling out
  1864. throw self;
  1865. }
  1866. if (exp[1] === value || started) {
  1867. started = true;
  1868. if (aborts(node)) stopped = true;
  1869. descend(node, this);
  1870. return node;
  1871. }
  1872. return MAP.skip;
  1873. }
  1874. descend(node, this);
  1875. return node;
  1876. }
  1877. });
  1878. tt.stack = compressor.stack.slice(); // so that's able to see parent nodes
  1879. self = self.transform(tt);
  1880. } catch(ex) {
  1881. if (ex !== self) throw ex;
  1882. }
  1883. return self;
  1884. });
  1885. OPT(AST_Case, function(self, compressor){
  1886. self.body = tighten_body(self.body, compressor);
  1887. return self;
  1888. });
  1889. OPT(AST_Try, function(self, compressor){
  1890. self.body = tighten_body(self.body, compressor);
  1891. return self;
  1892. });
  1893. AST_Definitions.DEFMETHOD("remove_initializers", function(){
  1894. this.definitions.forEach(function(def){ def.value = null });
  1895. });
  1896. AST_Definitions.DEFMETHOD("to_assignments", function(){
  1897. var assignments = this.definitions.reduce(function(a, def){
  1898. if (def.value) {
  1899. var name = make_node(AST_SymbolRef, def.name, def.name);
  1900. a.push(make_node(AST_Assign, def, {
  1901. operator : "=",
  1902. left : name,
  1903. right : def.value
  1904. }));
  1905. }
  1906. return a;
  1907. }, []);
  1908. if (assignments.length == 0) return null;
  1909. return AST_Seq.from_array(assignments);
  1910. });
  1911. OPT(AST_Definitions, function(self, compressor){
  1912. if (self.definitions.length == 0)
  1913. return make_node(AST_EmptyStatement, self);
  1914. return self;
  1915. });
  1916. OPT(AST_Function, function(self, compressor){
  1917. self = AST_Lambda.prototype.optimize.call(self, compressor);
  1918. if (compressor.option("unused") && !compressor.option("keep_fnames")) {
  1919. if (self.name && self.name.unreferenced()) {
  1920. self.name = null;
  1921. }
  1922. }
  1923. return self;
  1924. });
  1925. OPT(AST_Call, function(self, compressor){
  1926. if (compressor.option("unsafe")) {
  1927. var exp = self.expression;
  1928. if (exp instanceof AST_SymbolRef && exp.undeclared()) {
  1929. switch (exp.name) {
  1930. case "Array":
  1931. if (self.args.length != 1) {
  1932. return make_node(AST_Array, self, {
  1933. elements: self.args
  1934. }).transform(compressor);
  1935. }
  1936. break;
  1937. case "Object":
  1938. if (self.args.length == 0) {
  1939. return make_node(AST_Object, self, {
  1940. properties: []
  1941. });
  1942. }
  1943. break;
  1944. case "String":
  1945. if (self.args.length == 0) return make_node(AST_String, self, {
  1946. value: ""
  1947. });
  1948. if (self.args.length <= 1) return make_node(AST_Binary, self, {
  1949. left: self.args[0],
  1950. operator: "+",
  1951. right: make_node(AST_String, self, { value: "" })
  1952. }).transform(compressor);
  1953. break;
  1954. case "Number":
  1955. if (self.args.length == 0) return make_node(AST_Number, self, {
  1956. value: 0
  1957. });
  1958. if (self.args.length == 1) return make_node(AST_UnaryPrefix, self, {
  1959. expression: self.args[0],
  1960. operator: "+"
  1961. }).transform(compressor);
  1962. case "Boolean":
  1963. if (self.args.length == 0) return make_node(AST_False, self);
  1964. if (self.args.length == 1) return make_node(AST_UnaryPrefix, self, {
  1965. expression: make_node(AST_UnaryPrefix, null, {
  1966. expression: self.args[0],
  1967. operator: "!"
  1968. }),
  1969. operator: "!"
  1970. }).transform(compressor);
  1971. break;
  1972. case "Function":
  1973. // new Function() => function(){}
  1974. if (self.args.length == 0) return make_node(AST_Function, self, {
  1975. argnames: [],
  1976. body: []
  1977. });
  1978. if (all(self.args, function(x){ return x instanceof AST_String })) {
  1979. // quite a corner-case, but we can handle it:
  1980. // https://github.com/mishoo/UglifyJS2/issues/203
  1981. // if the code argument is a constant, then we can minify it.
  1982. try {
  1983. var code = "(function(" + self.args.slice(0, -1).map(function(arg){
  1984. return arg.value;
  1985. }).join(",") + "){" + self.args[self.args.length - 1].value + "})()";
  1986. var ast = parse(code);
  1987. ast.figure_out_scope({ screw_ie8: compressor.option("screw_ie8") });
  1988. var comp = new Compressor(compressor.options);
  1989. ast = ast.transform(comp);
  1990. ast.figure_out_scope({ screw_ie8: compressor.option("screw_ie8") });
  1991. ast.mangle_names();
  1992. var fun;
  1993. try {
  1994. ast.walk(new TreeWalker(function(node){
  1995. if (node instanceof AST_Lambda) {
  1996. fun = node;
  1997. throw ast;
  1998. }
  1999. }));
  2000. } catch(ex) {
  2001. if (ex !== ast) throw ex;
  2002. };
  2003. if (!fun) return self;
  2004. var args = fun.argnames.map(function(arg, i){
  2005. return make_node(AST_String, self.args[i], {
  2006. value: arg.print_to_string()
  2007. });
  2008. });
  2009. var code = OutputStream();
  2010. AST_BlockStatement.prototype._codegen.call(fun, fun, code);
  2011. code = code.toString().replace(/^\{|\}$/g, "");
  2012. args.push(make_node(AST_String, self.args[self.args.length - 1], {
  2013. value: code
  2014. }));
  2015. self.args = args;
  2016. return self;
  2017. } catch(ex) {
  2018. if (ex instanceof JS_Parse_Error) {
  2019. compressor.warn("Error parsing code passed to new Function [{file}:{line},{col}]", self.args[self.args.length - 1].start);
  2020. compressor.warn(ex.toString());
  2021. } else {
  2022. console.log(ex);
  2023. throw ex;
  2024. }
  2025. }
  2026. }
  2027. break;
  2028. }
  2029. }
  2030. else if (exp instanceof AST_Dot && exp.property == "toString" && self.args.length == 0) {
  2031. return make_node(AST_Binary, self, {
  2032. left: make_node(AST_String, self, { value: "" }),
  2033. operator: "+",
  2034. right: exp.expression
  2035. }).transform(compressor);
  2036. }
  2037. else if (exp instanceof AST_Dot && exp.expression instanceof AST_Array && exp.property == "join") EXIT: {
  2038. var separator = self.args.length == 0 ? "," : self.args[0].evaluate(compressor)[1];
  2039. if (separator == null) break EXIT; // not a constant
  2040. var elements = exp.expression.elements.reduce(function(a, el){
  2041. el = el.evaluate(compressor);
  2042. if (a.length == 0 || el.length == 1) {
  2043. a.push(el);
  2044. } else {
  2045. var last = a[a.length - 1];
  2046. if (last.length == 2) {
  2047. // it's a constant
  2048. var val = "" + last[1] + separator + el[1];
  2049. a[a.length - 1] = [ make_node_from_constant(compressor, val, last[0]), val ];
  2050. } else {
  2051. a.push(el);
  2052. }
  2053. }
  2054. return a;
  2055. }, []);
  2056. if (elements.length == 0) return make_node(AST_String, self, { value: "" });
  2057. if (elements.length == 1) return elements[0][0];
  2058. if (separator == "") {
  2059. var first;
  2060. if (elements[0][0] instanceof AST_String
  2061. || elements[1][0] instanceof AST_String) {
  2062. first = elements.shift()[0];
  2063. } else {
  2064. first = make_node(AST_String, self, { value: "" });
  2065. }
  2066. return elements.reduce(function(prev, el){
  2067. return make_node(AST_Binary, el[0], {
  2068. operator : "+",
  2069. left : prev,
  2070. right : el[0],
  2071. });
  2072. }, first).transform(compressor);
  2073. }
  2074. // need this awkward cloning to not affect original element
  2075. // best_of will decide which one to get through.
  2076. var node = self.clone();
  2077. node.expression = node.expression.clone();
  2078. node.expression.expression = node.expression.expression.clone();
  2079. node.expression.expression.elements = elements.map(function(el){
  2080. return el[0];
  2081. });
  2082. return best_of(self, node);
  2083. }
  2084. }
  2085. if (compressor.option("side_effects")) {
  2086. if (self.expression instanceof AST_Function
  2087. && self.args.length == 0
  2088. && !AST_Block.prototype.has_side_effects.call(self.expression, compressor)) {
  2089. return make_node(AST_Undefined, self).transform(compressor);
  2090. }
  2091. }
  2092. if (compressor.option("drop_console")) {
  2093. if (self.expression instanceof AST_PropAccess) {
  2094. var name = self.expression.expression;
  2095. while (name.expression) {
  2096. name = name.expression;
  2097. }
  2098. if (name instanceof AST_SymbolRef
  2099. && name.name == "console"
  2100. && name.undeclared()) {
  2101. return make_node(AST_Undefined, self).transform(compressor);
  2102. }
  2103. }
  2104. }
  2105. return self.evaluate(compressor)[0];
  2106. });
  2107. OPT(AST_New, function(self, compressor){
  2108. if (compressor.option("unsafe")) {
  2109. var exp = self.expression;
  2110. if (exp instanceof AST_SymbolRef && exp.undeclared()) {
  2111. switch (exp.name) {
  2112. case "Object":
  2113. case "RegExp":
  2114. case "Function":
  2115. case "Error":
  2116. case "Array":
  2117. return make_node(AST_Call, self, self).transform(compressor);
  2118. }
  2119. }
  2120. }
  2121. return self;
  2122. });
  2123. OPT(AST_Seq, function(self, compressor){
  2124. if (!compressor.option("side_effects"))
  2125. return self;
  2126. if (!self.car.has_side_effects(compressor)) {
  2127. return maintain_this_binding(compressor.parent(), self, self.cdr);
  2128. }
  2129. if (compressor.option("cascade")) {
  2130. if (self.car instanceof AST_Assign
  2131. && !self.car.left.has_side_effects(compressor)) {
  2132. if (self.car.left.equivalent_to(self.cdr)) {
  2133. return self.car;
  2134. }
  2135. if (self.cdr instanceof AST_Call
  2136. && self.cdr.expression.equivalent_to(self.car.left)) {
  2137. self.cdr.expression = self.car;
  2138. return self.cdr;
  2139. }
  2140. }
  2141. if (!self.car.has_side_effects(compressor)
  2142. && !self.cdr.has_side_effects(compressor)
  2143. && self.car.equivalent_to(self.cdr)) {
  2144. return self.car;
  2145. }
  2146. }
  2147. if (self.cdr instanceof AST_UnaryPrefix
  2148. && self.cdr.operator == "void"
  2149. && !self.cdr.expression.has_side_effects(compressor)) {
  2150. self.cdr.expression = self.car;
  2151. return self.cdr;
  2152. }
  2153. if (self.cdr instanceof AST_Undefined) {
  2154. return make_node(AST_UnaryPrefix, self, {
  2155. operator : "void",
  2156. expression : self.car
  2157. });
  2158. }
  2159. return self;
  2160. });
  2161. AST_Unary.DEFMETHOD("lift_sequences", function(compressor){
  2162. if (compressor.option("sequences")) {
  2163. if (this.expression instanceof AST_Seq) {
  2164. var seq = this.expression;
  2165. var x = seq.to_array();
  2166. this.expression = x.pop();
  2167. x.push(this);
  2168. seq = AST_Seq.from_array(x).transform(compressor);
  2169. return seq;
  2170. }
  2171. }
  2172. return this;
  2173. });
  2174. OPT(AST_UnaryPostfix, function(self, compressor){
  2175. return self.lift_sequences(compressor);
  2176. });
  2177. OPT(AST_UnaryPrefix, function(self, compressor){
  2178. self = self.lift_sequences(compressor);
  2179. var e = self.expression;
  2180. if (compressor.option("booleans") && compressor.in_boolean_context()) {
  2181. switch (self.operator) {
  2182. case "!":
  2183. if (e instanceof AST_UnaryPrefix && e.operator == "!") {
  2184. // !!foo ==> foo, if we're in boolean context
  2185. return e.expression;
  2186. }
  2187. break;
  2188. case "typeof":
  2189. // typeof always returns a non-empty string, thus it's
  2190. // always true in booleans
  2191. compressor.warn("Boolean expression always true [{file}:{line},{col}]", self.start);
  2192. return make_node(AST_True, self);
  2193. }
  2194. if (e instanceof AST_Binary && self.operator == "!") {
  2195. self = best_of(self, e.negate(compressor));
  2196. }
  2197. }
  2198. return self.evaluate(compressor)[0];
  2199. });
  2200. function has_side_effects_or_prop_access(node, compressor) {
  2201. var save_pure_getters = compressor.option("pure_getters");
  2202. compressor.options.pure_getters = false;
  2203. var ret = node.has_side_effects(compressor);
  2204. compressor.options.pure_getters = save_pure_getters;
  2205. return ret;
  2206. }
  2207. AST_Binary.DEFMETHOD("lift_sequences", function(compressor){
  2208. if (compressor.option("sequences")) {
  2209. if (this.left instanceof AST_Seq) {
  2210. var seq = this.left;
  2211. var x = seq.to_array();
  2212. this.left = x.pop();
  2213. x.push(this);
  2214. seq = AST_Seq.from_array(x).transform(compressor);
  2215. return seq;
  2216. }
  2217. if (this.right instanceof AST_Seq
  2218. && this instanceof AST_Assign
  2219. && !has_side_effects_or_prop_access(this.left, compressor)) {
  2220. var seq = this.right;
  2221. var x = seq.to_array();
  2222. this.right = x.pop();
  2223. x.push(this);
  2224. seq = AST_Seq.from_array(x).transform(compressor);
  2225. return seq;
  2226. }
  2227. }
  2228. return this;
  2229. });
  2230. var commutativeOperators = makePredicate("== === != !== * & | ^");
  2231. OPT(AST_Binary, function(self, compressor){
  2232. function reverse(op, force) {
  2233. if (force || !(self.left.has_side_effects(compressor) || self.right.has_side_effects(compressor))) {
  2234. if (op) self.operator = op;
  2235. var tmp = self.left;
  2236. self.left = self.right;
  2237. self.right = tmp;
  2238. }
  2239. }
  2240. if (commutativeOperators(self.operator)) {
  2241. if (self.right instanceof AST_Constant
  2242. && !(self.left instanceof AST_Constant)) {
  2243. // if right is a constant, whatever side effects the
  2244. // left side might have could not influence the
  2245. // result. hence, force switch.
  2246. if (!(self.left instanceof AST_Binary
  2247. && PRECEDENCE[self.left.operator] >= PRECEDENCE[self.operator])) {
  2248. reverse(null, true);
  2249. }
  2250. }
  2251. if (/^[!=]==?$/.test(self.operator)) {
  2252. if (self.left instanceof AST_SymbolRef && self.right instanceof AST_Conditional) {
  2253. if (self.right.consequent instanceof AST_SymbolRef
  2254. && self.right.consequent.definition() === self.left.definition()) {
  2255. if (/^==/.test(self.operator)) return self.right.condition;
  2256. if (/^!=/.test(self.operator)) return self.right.condition.negate(compressor);
  2257. }
  2258. if (self.right.alternative instanceof AST_SymbolRef
  2259. && self.right.alternative.definition() === self.left.definition()) {
  2260. if (/^==/.test(self.operator)) return self.right.condition.negate(compressor);
  2261. if (/^!=/.test(self.operator)) return self.right.condition;
  2262. }
  2263. }
  2264. if (self.right instanceof AST_SymbolRef && self.left instanceof AST_Conditional) {
  2265. if (self.left.consequent instanceof AST_SymbolRef
  2266. && self.left.consequent.definition() === self.right.definition()) {
  2267. if (/^==/.test(self.operator)) return self.left.condition;
  2268. if (/^!=/.test(self.operator)) return self.left.condition.negate(compressor);
  2269. }
  2270. if (self.left.alternative instanceof AST_SymbolRef
  2271. && self.left.alternative.definition() === self.right.definition()) {
  2272. if (/^==/.test(self.operator)) return self.left.condition.negate(compressor);
  2273. if (/^!=/.test(self.operator)) return self.left.condition;
  2274. }
  2275. }
  2276. }
  2277. }
  2278. self = self.lift_sequences(compressor);
  2279. if (compressor.option("comparisons")) switch (self.operator) {
  2280. case "===":
  2281. case "!==":
  2282. if ((self.left.is_string(compressor) && self.right.is_string(compressor)) ||
  2283. (self.left.is_boolean() && self.right.is_boolean())) {
  2284. self.operator = self.operator.substr(0, 2);
  2285. }
  2286. // XXX: intentionally falling down to the next case
  2287. case "==":
  2288. case "!=":
  2289. if (self.left instanceof AST_String
  2290. && self.left.value == "undefined"
  2291. && self.right instanceof AST_UnaryPrefix
  2292. && self.right.operator == "typeof"
  2293. && compressor.option("unsafe")) {
  2294. if (!(self.right.expression instanceof AST_SymbolRef)
  2295. || !self.right.expression.undeclared()) {
  2296. self.right = self.right.expression;
  2297. self.left = make_node(AST_Undefined, self.left).optimize(compressor);
  2298. if (self.operator.length == 2) self.operator += "=";
  2299. }
  2300. }
  2301. break;
  2302. }
  2303. if (compressor.option("conditionals")) {
  2304. if (self.operator == "&&") {
  2305. var ll = self.left.evaluate(compressor);
  2306. if (ll.length > 1) {
  2307. if (ll[1]) {
  2308. compressor.warn("Condition left of && always true [{file}:{line},{col}]", self.start);
  2309. return maintain_this_binding(compressor.parent(), self, self.right.evaluate(compressor)[0]);
  2310. } else {
  2311. compressor.warn("Condition left of && always false [{file}:{line},{col}]", self.start);
  2312. return maintain_this_binding(compressor.parent(), self, ll[0]);
  2313. }
  2314. }
  2315. }
  2316. else if (self.operator == "||") {
  2317. var ll = self.left.evaluate(compressor);
  2318. if (ll.length > 1) {
  2319. if (ll[1]) {
  2320. compressor.warn("Condition left of || always true [{file}:{line},{col}]", self.start);
  2321. return maintain_this_binding(compressor.parent(), self, ll[0]);
  2322. } else {
  2323. compressor.warn("Condition left of || always false [{file}:{line},{col}]", self.start);
  2324. return maintain_this_binding(compressor.parent(), self, self.right.evaluate(compressor)[0]);
  2325. }
  2326. }
  2327. }
  2328. }
  2329. if (compressor.option("booleans") && compressor.in_boolean_context()) switch (self.operator) {
  2330. case "&&":
  2331. var ll = self.left.evaluate(compressor);
  2332. var rr = self.right.evaluate(compressor);
  2333. if ((ll.length > 1 && !ll[1]) || (rr.length > 1 && !rr[1])) {
  2334. compressor.warn("Boolean && always false [{file}:{line},{col}]", self.start);
  2335. if (self.left.has_side_effects(compressor)) {
  2336. return make_node(AST_Seq, self, {
  2337. car: self.left,
  2338. cdr: make_node(AST_False)
  2339. }).optimize(compressor);
  2340. }
  2341. return make_node(AST_False, self);
  2342. }
  2343. if (ll.length > 1 && ll[1]) {
  2344. return rr[0];
  2345. }
  2346. if (rr.length > 1 && rr[1]) {
  2347. return ll[0];
  2348. }
  2349. break;
  2350. case "||":
  2351. var ll = self.left.evaluate(compressor);
  2352. var rr = self.right.evaluate(compressor);
  2353. if ((ll.length > 1 && ll[1]) || (rr.length > 1 && rr[1])) {
  2354. compressor.warn("Boolean || always true [{file}:{line},{col}]", self.start);
  2355. if (self.left.has_side_effects(compressor)) {
  2356. return make_node(AST_Seq, self, {
  2357. car: self.left,
  2358. cdr: make_node(AST_True)
  2359. }).optimize(compressor);
  2360. }
  2361. return make_node(AST_True, self);
  2362. }
  2363. if (ll.length > 1 && !ll[1]) {
  2364. return rr[0];
  2365. }
  2366. if (rr.length > 1 && !rr[1]) {
  2367. return ll[0];
  2368. }
  2369. break;
  2370. case "+":
  2371. var ll = self.left.evaluate(compressor);
  2372. var rr = self.right.evaluate(compressor);
  2373. if ((ll.length > 1 && ll[0] instanceof AST_String && ll[1]) ||
  2374. (rr.length > 1 && rr[0] instanceof AST_String && rr[1])) {
  2375. compressor.warn("+ in boolean context always true [{file}:{line},{col}]", self.start);
  2376. return make_node(AST_True, self);
  2377. }
  2378. break;
  2379. }
  2380. if (compressor.option("comparisons") && self.is_boolean()) {
  2381. if (!(compressor.parent() instanceof AST_Binary)
  2382. || compressor.parent() instanceof AST_Assign) {
  2383. var negated = make_node(AST_UnaryPrefix, self, {
  2384. operator: "!",
  2385. expression: self.negate(compressor)
  2386. });
  2387. self = best_of(self, negated);
  2388. }
  2389. if (compressor.option("unsafe_comps")) {
  2390. switch (self.operator) {
  2391. case "<": reverse(">"); break;
  2392. case "<=": reverse(">="); break;
  2393. }
  2394. }
  2395. }
  2396. if (self.operator == "+" && self.right instanceof AST_String
  2397. && self.right.getValue() === "" && self.left instanceof AST_Binary
  2398. && self.left.operator == "+" && self.left.is_string(compressor)) {
  2399. return self.left;
  2400. }
  2401. if (compressor.option("evaluate")) {
  2402. if (self.operator == "+") {
  2403. if (self.left instanceof AST_Constant
  2404. && self.right instanceof AST_Binary
  2405. && self.right.operator == "+"
  2406. && self.right.left instanceof AST_Constant
  2407. && self.right.is_string(compressor)) {
  2408. self = make_node(AST_Binary, self, {
  2409. operator: "+",
  2410. left: make_node(AST_String, null, {
  2411. value: "" + self.left.getValue() + self.right.left.getValue(),
  2412. start: self.left.start,
  2413. end: self.right.left.end
  2414. }),
  2415. right: self.right.right
  2416. });
  2417. }
  2418. if (self.right instanceof AST_Constant
  2419. && self.left instanceof AST_Binary
  2420. && self.left.operator == "+"
  2421. && self.left.right instanceof AST_Constant
  2422. && self.left.is_string(compressor)) {
  2423. self = make_node(AST_Binary, self, {
  2424. operator: "+",
  2425. left: self.left.left,
  2426. right: make_node(AST_String, null, {
  2427. value: "" + self.left.right.getValue() + self.right.getValue(),
  2428. start: self.left.right.start,
  2429. end: self.right.end
  2430. })
  2431. });
  2432. }
  2433. if (self.left instanceof AST_Binary
  2434. && self.left.operator == "+"
  2435. && self.left.is_string(compressor)
  2436. && self.left.right instanceof AST_Constant
  2437. && self.right instanceof AST_Binary
  2438. && self.right.operator == "+"
  2439. && self.right.left instanceof AST_Constant
  2440. && self.right.is_string(compressor)) {
  2441. self = make_node(AST_Binary, self, {
  2442. operator: "+",
  2443. left: make_node(AST_Binary, self.left, {
  2444. operator: "+",
  2445. left: self.left.left,
  2446. right: make_node(AST_String, null, {
  2447. value: "" + self.left.right.getValue() + self.right.left.getValue(),
  2448. start: self.left.right.start,
  2449. end: self.right.left.end
  2450. })
  2451. }),
  2452. right: self.right.right
  2453. });
  2454. }
  2455. }
  2456. }
  2457. // x && (y && z) ==> x && y && z
  2458. // x || (y || z) ==> x || y || z
  2459. if (self.right instanceof AST_Binary
  2460. && self.right.operator == self.operator
  2461. && (self.operator == "&&" || self.operator == "||"))
  2462. {
  2463. self.left = make_node(AST_Binary, self.left, {
  2464. operator : self.operator,
  2465. left : self.left,
  2466. right : self.right.left
  2467. });
  2468. self.right = self.right.right;
  2469. return self.transform(compressor);
  2470. }
  2471. return self.evaluate(compressor)[0];
  2472. });
  2473. OPT(AST_SymbolRef, function(self, compressor){
  2474. function isLHS(symbol, parent) {
  2475. return (
  2476. parent instanceof AST_Binary &&
  2477. parent.operator === '=' &&
  2478. parent.left === symbol
  2479. );
  2480. }
  2481. if (self.undeclared() && !isLHS(self, compressor.parent())) {
  2482. var defines = compressor.option("global_defs");
  2483. if (defines && HOP(defines, self.name)) {
  2484. return make_node_from_constant(compressor, defines[self.name], self);
  2485. }
  2486. // testing against !self.scope.uses_with first is an optimization
  2487. if (!self.scope.uses_with || !compressor.find_parent(AST_With)) {
  2488. switch (self.name) {
  2489. case "undefined":
  2490. return make_node(AST_Undefined, self);
  2491. case "NaN":
  2492. return make_node(AST_NaN, self).transform(compressor);
  2493. case "Infinity":
  2494. return make_node(AST_Infinity, self).transform(compressor);
  2495. }
  2496. }
  2497. }
  2498. return self;
  2499. });
  2500. OPT(AST_Infinity, function (self, compressor) {
  2501. return make_node(AST_Binary, self, {
  2502. operator : '/',
  2503. left : make_node(AST_Number, self, {value: 1}),
  2504. right : make_node(AST_Number, self, {value: 0})
  2505. });
  2506. });
  2507. OPT(AST_Undefined, function(self, compressor){
  2508. if (compressor.option("unsafe")) {
  2509. var scope = compressor.find_parent(AST_Scope);
  2510. var undef = scope.find_variable("undefined");
  2511. if (undef) {
  2512. var ref = make_node(AST_SymbolRef, self, {
  2513. name : "undefined",
  2514. scope : scope,
  2515. thedef : undef
  2516. });
  2517. ref.reference();
  2518. return ref;
  2519. }
  2520. }
  2521. return self;
  2522. });
  2523. var ASSIGN_OPS = [ '+', '-', '/', '*', '%', '>>', '<<', '>>>', '|', '^', '&' ];
  2524. OPT(AST_Assign, function(self, compressor){
  2525. self = self.lift_sequences(compressor);
  2526. if (self.operator == "="
  2527. && self.left instanceof AST_SymbolRef
  2528. && self.right instanceof AST_Binary
  2529. && self.right.left instanceof AST_SymbolRef
  2530. && self.right.left.name == self.left.name
  2531. && member(self.right.operator, ASSIGN_OPS)) {
  2532. self.operator = self.right.operator + "=";
  2533. self.right = self.right.right;
  2534. }
  2535. return self;
  2536. });
  2537. OPT(AST_Conditional, function(self, compressor){
  2538. if (!compressor.option("conditionals")) return self;
  2539. if (self.condition instanceof AST_Seq) {
  2540. var car = self.condition.car;
  2541. self.condition = self.condition.cdr;
  2542. return AST_Seq.cons(car, self);
  2543. }
  2544. var cond = self.condition.evaluate(compressor);
  2545. if (cond.length > 1) {
  2546. if (cond[1]) {
  2547. compressor.warn("Condition always true [{file}:{line},{col}]", self.start);
  2548. return maintain_this_binding(compressor.parent(), self, self.consequent);
  2549. } else {
  2550. compressor.warn("Condition always false [{file}:{line},{col}]", self.start);
  2551. return maintain_this_binding(compressor.parent(), self, self.alternative);
  2552. }
  2553. }
  2554. var negated = cond[0].negate(compressor);
  2555. if (best_of(cond[0], negated) === negated) {
  2556. self = make_node(AST_Conditional, self, {
  2557. condition: negated,
  2558. consequent: self.alternative,
  2559. alternative: self.consequent
  2560. });
  2561. }
  2562. var consequent = self.consequent;
  2563. var alternative = self.alternative;
  2564. if (consequent instanceof AST_Assign
  2565. && alternative instanceof AST_Assign
  2566. && consequent.operator == alternative.operator
  2567. && consequent.left.equivalent_to(alternative.left)
  2568. && !consequent.left.has_side_effects(compressor)
  2569. ) {
  2570. /*
  2571. * Stuff like this:
  2572. * if (foo) exp = something; else exp = something_else;
  2573. * ==>
  2574. * exp = foo ? something : something_else;
  2575. */
  2576. return make_node(AST_Assign, self, {
  2577. operator: consequent.operator,
  2578. left: consequent.left,
  2579. right: make_node(AST_Conditional, self, {
  2580. condition: self.condition,
  2581. consequent: consequent.right,
  2582. alternative: alternative.right
  2583. })
  2584. });
  2585. }
  2586. if (consequent instanceof AST_Call
  2587. && alternative.TYPE === consequent.TYPE
  2588. && consequent.args.length == alternative.args.length
  2589. && !consequent.expression.has_side_effects(compressor)
  2590. && consequent.expression.equivalent_to(alternative.expression)) {
  2591. if (consequent.args.length == 0) {
  2592. return make_node(AST_Seq, self, {
  2593. car: self.condition,
  2594. cdr: consequent
  2595. });
  2596. }
  2597. if (consequent.args.length == 1) {
  2598. consequent.args[0] = make_node(AST_Conditional, self, {
  2599. condition: self.condition,
  2600. consequent: consequent.args[0],
  2601. alternative: alternative.args[0]
  2602. });
  2603. return consequent;
  2604. }
  2605. }
  2606. // x?y?z:a:a --> x&&y?z:a
  2607. if (consequent instanceof AST_Conditional
  2608. && consequent.alternative.equivalent_to(alternative)) {
  2609. return make_node(AST_Conditional, self, {
  2610. condition: make_node(AST_Binary, self, {
  2611. left: self.condition,
  2612. operator: "&&",
  2613. right: consequent.condition
  2614. }),
  2615. consequent: consequent.consequent,
  2616. alternative: alternative
  2617. });
  2618. }
  2619. // y?1:1 --> 1
  2620. if (consequent.is_constant(compressor)
  2621. && alternative.is_constant(compressor)
  2622. && consequent.equivalent_to(alternative)) {
  2623. var consequent_value = consequent.constant_value(compressor);
  2624. if (self.condition.has_side_effects(compressor)) {
  2625. return AST_Seq.from_array([self.condition, make_node_from_constant(compressor, consequent_value, self)]);
  2626. } else {
  2627. return make_node_from_constant(compressor, consequent_value, self);
  2628. }
  2629. }
  2630. if (is_true(self.consequent)) {
  2631. if (is_false(self.alternative)) {
  2632. // c ? true : false ---> !!c
  2633. return booleanize(self.condition);
  2634. }
  2635. // c ? true : x ---> !!c || x
  2636. return make_node(AST_Binary, self, {
  2637. operator: "||",
  2638. left: booleanize(self.condition),
  2639. right: self.alternative
  2640. });
  2641. }
  2642. if (is_false(self.consequent)) {
  2643. if (is_true(self.alternative)) {
  2644. // c ? false : true ---> !c
  2645. return booleanize(self.condition.negate(compressor));
  2646. }
  2647. // c ? false : x ---> !c && x
  2648. return make_node(AST_Binary, self, {
  2649. operator: "&&",
  2650. left: booleanize(self.condition.negate(compressor)),
  2651. right: self.alternative
  2652. });
  2653. }
  2654. if (is_true(self.alternative)) {
  2655. // c ? x : true ---> !c || x
  2656. return make_node(AST_Binary, self, {
  2657. operator: "||",
  2658. left: booleanize(self.condition.negate(compressor)),
  2659. right: self.consequent
  2660. });
  2661. }
  2662. if (is_false(self.alternative)) {
  2663. // c ? x : false ---> !!c && x
  2664. return make_node(AST_Binary, self, {
  2665. operator: "&&",
  2666. left: booleanize(self.condition),
  2667. right: self.consequent
  2668. });
  2669. }
  2670. return self;
  2671. function booleanize(node) {
  2672. if (node.is_boolean()) return node;
  2673. // !!expression
  2674. return make_node(AST_UnaryPrefix, node, {
  2675. operator: "!",
  2676. expression: node.negate(compressor)
  2677. });
  2678. }
  2679. // AST_True or !0
  2680. function is_true(node) {
  2681. return node instanceof AST_True
  2682. || (node instanceof AST_UnaryPrefix
  2683. && node.operator == "!"
  2684. && node.expression instanceof AST_Constant
  2685. && !node.expression.value);
  2686. }
  2687. // AST_False or !1
  2688. function is_false(node) {
  2689. return node instanceof AST_False
  2690. || (node instanceof AST_UnaryPrefix
  2691. && node.operator == "!"
  2692. && node.expression instanceof AST_Constant
  2693. && !!node.expression.value);
  2694. }
  2695. });
  2696. OPT(AST_Boolean, function(self, compressor){
  2697. if (compressor.option("booleans")) {
  2698. var p = compressor.parent();
  2699. if (p instanceof AST_Binary && (p.operator == "=="
  2700. || p.operator == "!=")) {
  2701. compressor.warn("Non-strict equality against boolean: {operator} {value} [{file}:{line},{col}]", {
  2702. operator : p.operator,
  2703. value : self.value,
  2704. file : p.start.file,
  2705. line : p.start.line,
  2706. col : p.start.col,
  2707. });
  2708. return make_node(AST_Number, self, {
  2709. value: +self.value
  2710. });
  2711. }
  2712. return make_node(AST_UnaryPrefix, self, {
  2713. operator: "!",
  2714. expression: make_node(AST_Number, self, {
  2715. value: 1 - self.value
  2716. })
  2717. });
  2718. }
  2719. return self;
  2720. });
  2721. OPT(AST_Sub, function(self, compressor){
  2722. var prop = self.property;
  2723. if (prop instanceof AST_String && compressor.option("properties")) {
  2724. prop = prop.getValue();
  2725. if (RESERVED_WORDS(prop) ? compressor.option("screw_ie8") : is_identifier_string(prop)) {
  2726. return make_node(AST_Dot, self, {
  2727. expression : self.expression,
  2728. property : prop
  2729. }).optimize(compressor);
  2730. }
  2731. var v = parseFloat(prop);
  2732. if (!isNaN(v) && v.toString() == prop) {
  2733. self.property = make_node(AST_Number, self.property, {
  2734. value: v
  2735. });
  2736. }
  2737. }
  2738. return self;
  2739. });
  2740. OPT(AST_Dot, function(self, compressor){
  2741. var prop = self.property;
  2742. if (RESERVED_WORDS(prop) && !compressor.option("screw_ie8")) {
  2743. return make_node(AST_Sub, self, {
  2744. expression : self.expression,
  2745. property : make_node(AST_String, self, {
  2746. value: prop
  2747. })
  2748. }).optimize(compressor);
  2749. }
  2750. return self.evaluate(compressor)[0];
  2751. });
  2752. function literals_in_boolean_context(self, compressor) {
  2753. if (compressor.option("booleans") && compressor.in_boolean_context() && !self.has_side_effects(compressor)) {
  2754. return make_node(AST_True, self);
  2755. }
  2756. return self;
  2757. };
  2758. OPT(AST_Array, literals_in_boolean_context);
  2759. OPT(AST_Object, literals_in_boolean_context);
  2760. OPT(AST_RegExp, literals_in_boolean_context);
  2761. OPT(AST_Return, function(self, compressor){
  2762. if (self.value instanceof AST_Undefined) {
  2763. self.value = null;
  2764. }
  2765. return self;
  2766. });
  2767. })();