output.js 65 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941
  1. /***********************************************************************
  2. A JavaScript tokenizer / parser / beautifier / compressor.
  3. https://github.com/mishoo/UglifyJS
  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 is_some_comments(comment) {
  35. // multiline comment
  36. return comment.type == "comment2" && /@preserve|@license|@cc_on/i.test(comment.value);
  37. }
  38. function OutputStream(options) {
  39. options = defaults(options, {
  40. annotations : false,
  41. ascii_only : false,
  42. beautify : false,
  43. braces : false,
  44. comments : false,
  45. galio : false,
  46. ie8 : false,
  47. indent_level : 4,
  48. indent_start : 0,
  49. inline_script : true,
  50. keep_quoted_props: false,
  51. max_line_len : false,
  52. preamble : null,
  53. preserve_line : false,
  54. quote_keys : false,
  55. quote_style : 0,
  56. semicolons : true,
  57. shebang : true,
  58. source_map : null,
  59. v8 : false,
  60. webkit : false,
  61. width : 80,
  62. wrap_iife : false,
  63. }, true);
  64. // Convert comment option to RegExp if neccessary and set up comments filter
  65. var comment_filter = return_false; // Default case, throw all comments away
  66. if (options.comments) {
  67. var comments = options.comments;
  68. if (typeof options.comments === "string" && /^\/.*\/[a-zA-Z]*$/.test(options.comments)) {
  69. var regex_pos = options.comments.lastIndexOf("/");
  70. comments = new RegExp(
  71. options.comments.substr(1, regex_pos - 1),
  72. options.comments.substr(regex_pos + 1)
  73. );
  74. }
  75. if (comments instanceof RegExp) {
  76. comment_filter = function(comment) {
  77. return comment.type != "comment5" && comments.test(comment.value);
  78. };
  79. } else if (typeof comments === "function") {
  80. comment_filter = function(comment) {
  81. return comment.type != "comment5" && comments(this, comment);
  82. };
  83. } else if (comments === "some") {
  84. comment_filter = is_some_comments;
  85. } else { // NOTE includes "all" option
  86. comment_filter = return_true;
  87. }
  88. }
  89. var current_col = 0;
  90. var current_line = 1;
  91. var current_pos = 0;
  92. var indentation = options.indent_start;
  93. var last;
  94. var line_end = 0;
  95. var line_fixed = true;
  96. var mappings = options.source_map && [];
  97. var mapping_name;
  98. var mapping_token;
  99. var might_need_space;
  100. var might_need_semicolon;
  101. var need_newline_indented = false;
  102. var need_space = false;
  103. var newline_insert = -1;
  104. var stack;
  105. var OUTPUT;
  106. function reset() {
  107. last = "";
  108. might_need_space = false;
  109. might_need_semicolon = false;
  110. stack = [];
  111. var str = OUTPUT;
  112. OUTPUT = "";
  113. return str;
  114. }
  115. reset();
  116. var to_utf8 = options.ascii_only ? function(str, identifier) {
  117. if (identifier) str = str.replace(/[\ud800-\udbff][\udc00-\udfff]/g, function(ch) {
  118. return "\\u{" + (ch.charCodeAt(0) - 0xd7c0 << 10 | ch.charCodeAt(1) - 0xdc00).toString(16) + "}";
  119. });
  120. return str.replace(/[\u0000-\u001f\u007f-\uffff]/g, function(ch) {
  121. var code = ch.charCodeAt(0).toString(16);
  122. if (code.length <= 2 && !identifier) {
  123. while (code.length < 2) code = "0" + code;
  124. return "\\x" + code;
  125. } else {
  126. while (code.length < 4) code = "0" + code;
  127. return "\\u" + code;
  128. }
  129. });
  130. } : function(str) {
  131. var s = "";
  132. for (var i = 0, j = 0; i < str.length; i++) {
  133. var code = str.charCodeAt(i);
  134. if (is_surrogate_pair_head(code)) {
  135. if (is_surrogate_pair_tail(str.charCodeAt(i + 1))) {
  136. i++;
  137. continue;
  138. }
  139. } else if (!is_surrogate_pair_tail(code)) {
  140. continue;
  141. }
  142. s += str.slice(j, i) + "\\u" + code.toString(16);
  143. j = i + 1;
  144. }
  145. return j == 0 ? str : s + str.slice(j);
  146. };
  147. function quote_single(str) {
  148. return "'" + str.replace(/\x27/g, "\\'") + "'";
  149. }
  150. function quote_double(str) {
  151. return '"' + str.replace(/\x22/g, '\\"') + '"';
  152. }
  153. var quote_string = [
  154. null,
  155. quote_single,
  156. quote_double,
  157. function(str, quote) {
  158. return quote == "'" ? quote_single(str) : quote_double(str);
  159. },
  160. ][options.quote_style] || function(str, quote, dq, sq) {
  161. return dq > sq ? quote_single(str) : quote_double(str);
  162. };
  163. function make_string(str, quote) {
  164. var dq = 0, sq = 0;
  165. str = str.replace(/[\\\b\f\n\r\v\t\x22\x27\u2028\u2029\0\ufeff]/g, function(s, i) {
  166. switch (s) {
  167. case '"': ++dq; return '"';
  168. case "'": ++sq; return "'";
  169. case "\\": return "\\\\";
  170. case "\n": return "\\n";
  171. case "\r": return "\\r";
  172. case "\t": return "\\t";
  173. case "\b": return "\\b";
  174. case "\f": return "\\f";
  175. case "\x0B": return options.ie8 ? "\\x0B" : "\\v";
  176. case "\u2028": return "\\u2028";
  177. case "\u2029": return "\\u2029";
  178. case "\ufeff": return "\\ufeff";
  179. case "\0":
  180. return /[0-9]/.test(str.charAt(i+1)) ? "\\x00" : "\\0";
  181. }
  182. return s;
  183. });
  184. return quote_string(to_utf8(str), quote, dq, sq);
  185. }
  186. /* -----[ beautification/minification ]----- */
  187. var adjust_mappings = mappings ? function(line, col) {
  188. mappings.forEach(function(mapping) {
  189. mapping.line += line;
  190. mapping.col += col;
  191. });
  192. } : noop;
  193. var flush_mappings = mappings ? function() {
  194. mappings.forEach(function(mapping) {
  195. options.source_map.add(
  196. mapping.token.file,
  197. mapping.line, mapping.col,
  198. mapping.token.line, mapping.token.col,
  199. !mapping.name && mapping.token.type == "name" ? mapping.token.value : mapping.name
  200. );
  201. });
  202. mappings = [];
  203. } : noop;
  204. function insert_newlines(count) {
  205. var index = OUTPUT.lastIndexOf("\n");
  206. if (line_end < index) line_end = index;
  207. var left = OUTPUT.slice(0, line_end);
  208. var right = OUTPUT.slice(line_end);
  209. adjust_mappings(count, right.length - current_col);
  210. current_line += count;
  211. current_pos += count;
  212. current_col = right.length;
  213. OUTPUT = left;
  214. while (count--) OUTPUT += "\n";
  215. OUTPUT += right;
  216. }
  217. var fix_line = options.max_line_len ? function() {
  218. if (line_fixed) {
  219. if (current_col > options.max_line_len) {
  220. AST_Node.warn("Output exceeds {max_line_len} characters", options);
  221. }
  222. return;
  223. }
  224. if (current_col > options.max_line_len) insert_newlines(1);
  225. line_fixed = true;
  226. flush_mappings();
  227. } : noop;
  228. var requireSemicolonChars = makePredicate("( [ + * / - , .");
  229. var print = options.beautify
  230. || options.comments
  231. || options.max_line_len
  232. || options.preserve_line
  233. || options.shebang
  234. || !options.semicolons
  235. || options.source_map
  236. || options.width ? function(str) {
  237. var ch = str.charAt(0);
  238. if (need_newline_indented && ch) {
  239. need_newline_indented = false;
  240. if (ch != "\n") {
  241. print("\n");
  242. indent();
  243. }
  244. }
  245. if (need_space && ch) {
  246. need_space = false;
  247. if (!/[\s;})]/.test(ch)) {
  248. space();
  249. }
  250. }
  251. newline_insert = -1;
  252. var prev = last.slice(-1);
  253. if (might_need_semicolon) {
  254. might_need_semicolon = false;
  255. if (prev == ":" && ch == "}" || (!ch || ";}".indexOf(ch) < 0) && prev != ";") {
  256. if (options.semicolons || requireSemicolonChars[ch]) {
  257. OUTPUT += ";";
  258. current_col++;
  259. current_pos++;
  260. } else {
  261. fix_line();
  262. OUTPUT += "\n";
  263. current_pos++;
  264. current_line++;
  265. current_col = 0;
  266. if (/^\s+$/.test(str)) {
  267. // reset the semicolon flag, since we didn't print one
  268. // now and might still have to later
  269. might_need_semicolon = true;
  270. }
  271. }
  272. if (!options.beautify)
  273. might_need_space = false;
  274. }
  275. }
  276. if (might_need_space) {
  277. if (is_identifier_char(prev) && (is_identifier_char(ch) || ch == "\\")
  278. || (ch == "/" && ch == prev)
  279. || ((ch == "+" || ch == "-") && ch == last)
  280. || str == "--" && last == "!"
  281. || str == "in" && prev == "/"
  282. || last == "--" && ch == ">") {
  283. OUTPUT += " ";
  284. current_col++;
  285. current_pos++;
  286. }
  287. if (prev != "<" || str != "!") might_need_space = false;
  288. }
  289. if (mapping_token) {
  290. mappings.push({
  291. token: mapping_token,
  292. name: mapping_name,
  293. line: current_line,
  294. col: current_col
  295. });
  296. mapping_token = false;
  297. if (line_fixed) flush_mappings();
  298. }
  299. OUTPUT += str;
  300. current_pos += str.length;
  301. var a = str.split(/\r?\n/), n = a.length - 1;
  302. current_line += n;
  303. current_col += a[0].length;
  304. if (n > 0) {
  305. fix_line();
  306. current_col = a[n].length;
  307. }
  308. last = str;
  309. } : function(str) {
  310. var ch = str.charAt(0);
  311. var prev = last.slice(-1);
  312. if (might_need_semicolon) {
  313. might_need_semicolon = false;
  314. if (prev == ":" && ch == "}" || (!ch || ";}".indexOf(ch) < 0) && prev != ";") {
  315. OUTPUT += ";";
  316. might_need_space = false;
  317. }
  318. }
  319. if (might_need_space) {
  320. if (is_identifier_char(prev) && (is_identifier_char(ch) || ch == "\\")
  321. || (ch == "/" && ch == prev)
  322. || ((ch == "+" || ch == "-") && ch == last)
  323. || str == "--" && last == "!"
  324. || str == "in" && prev == "/"
  325. || last == "--" && ch == ">") {
  326. OUTPUT += " ";
  327. }
  328. if (prev != "<" || str != "!") might_need_space = false;
  329. }
  330. OUTPUT += str;
  331. last = str;
  332. };
  333. var space = options.beautify ? function() {
  334. print(" ");
  335. } : function() {
  336. might_need_space = true;
  337. };
  338. var indent = options.beautify ? function(half) {
  339. if (need_newline_indented) print("\n");
  340. print(repeat_string(" ", half ? indentation - (options.indent_level >> 1) : indentation));
  341. } : noop;
  342. var with_indent = options.beautify ? function(cont) {
  343. var save_indentation = indentation;
  344. indentation += options.indent_level;
  345. cont();
  346. indentation = save_indentation;
  347. } : function(cont) { cont() };
  348. var may_add_newline = options.max_line_len || options.preserve_line ? function() {
  349. fix_line();
  350. line_end = OUTPUT.length;
  351. line_fixed = false;
  352. } : noop;
  353. var newline = options.beautify ? function() {
  354. if (newline_insert < 0) return print("\n");
  355. if (OUTPUT[newline_insert] != "\n") {
  356. OUTPUT = OUTPUT.slice(0, newline_insert) + "\n" + OUTPUT.slice(newline_insert);
  357. current_pos++;
  358. current_line++;
  359. }
  360. newline_insert++;
  361. } : may_add_newline;
  362. var semicolon = options.beautify ? function() {
  363. print(";");
  364. } : function() {
  365. might_need_semicolon = true;
  366. };
  367. function force_semicolon() {
  368. if (might_need_semicolon) print(";");
  369. print(";");
  370. }
  371. function with_block(cont) {
  372. print("{");
  373. newline();
  374. with_indent(cont);
  375. indent();
  376. print("}");
  377. }
  378. function with_parens(cont) {
  379. print("(");
  380. may_add_newline();
  381. cont();
  382. may_add_newline();
  383. print(")");
  384. }
  385. function with_square(cont) {
  386. print("[");
  387. may_add_newline();
  388. cont();
  389. may_add_newline();
  390. print("]");
  391. }
  392. function comma() {
  393. may_add_newline();
  394. print(",");
  395. may_add_newline();
  396. space();
  397. }
  398. function colon() {
  399. print(":");
  400. space();
  401. }
  402. var add_mapping = mappings ? function(token, name) {
  403. mapping_token = token;
  404. mapping_name = name;
  405. } : noop;
  406. function get() {
  407. if (!line_fixed) fix_line();
  408. return OUTPUT;
  409. }
  410. function has_nlb() {
  411. var index = OUTPUT.lastIndexOf("\n");
  412. return /^ *$/.test(OUTPUT.slice(index + 1));
  413. }
  414. function pad_comment(token, force) {
  415. if (need_newline_indented) return;
  416. if (token.nlb && (force || !has_nlb())) {
  417. need_newline_indented = true;
  418. } else if (force) {
  419. need_space = true;
  420. }
  421. }
  422. function print_comment(comment) {
  423. var value = comment.value.replace(/[@#]__PURE__/g, " ");
  424. if (/^\s*$/.test(value) && !/^\s*$/.test(comment.value)) return false;
  425. if (/comment[134]/.test(comment.type)) {
  426. print("//" + value);
  427. need_newline_indented = true;
  428. } else if (comment.type == "comment2") {
  429. print("/*" + value + "*/");
  430. }
  431. return true;
  432. }
  433. function should_merge_comments(node, parent) {
  434. if (parent instanceof AST_Binary) return parent.left === node;
  435. if (parent.TYPE == "Call") return parent.expression === node;
  436. if (parent instanceof AST_Conditional) return parent.condition === node;
  437. if (parent instanceof AST_Dot) return parent.expression === node;
  438. if (parent instanceof AST_Exit) return true;
  439. if (parent instanceof AST_Sequence) return parent.expressions[0] === node;
  440. if (parent instanceof AST_Sub) return parent.expression === node;
  441. if (parent instanceof AST_UnaryPostfix) return true;
  442. if (parent instanceof AST_Yield) return true;
  443. }
  444. function prepend_comments(node) {
  445. var self = this;
  446. var scan;
  447. if (node instanceof AST_Exit) {
  448. scan = node.value;
  449. } else if (node instanceof AST_Yield) {
  450. scan = node.expression;
  451. }
  452. var comments = dump(node);
  453. if (!comments) comments = [];
  454. if (scan) {
  455. var tw = new TreeWalker(function(node) {
  456. if (!should_merge_comments(node, tw.parent())) return true;
  457. var before = dump(node);
  458. if (before) comments = comments.concat(before);
  459. });
  460. tw.push(node);
  461. scan.walk(tw);
  462. }
  463. if (current_pos == 0) {
  464. if (comments.length > 0 && options.shebang && comments[0].type == "comment5") {
  465. print("#!" + comments.shift().value + "\n");
  466. indent();
  467. }
  468. var preamble = options.preamble;
  469. if (preamble) {
  470. print(preamble.replace(/\r\n?|[\n\u2028\u2029]|\s*$/g, "\n"));
  471. }
  472. }
  473. comments = comments.filter(comment_filter, node);
  474. var printed = false;
  475. comments.forEach(function(comment, index) {
  476. pad_comment(comment, index);
  477. if (print_comment(comment)) printed = true;
  478. });
  479. if (printed) pad_comment(node.start, true);
  480. function dump(node) {
  481. var token = node.start;
  482. if (!token) {
  483. if (!scan) return;
  484. node.start = token = new AST_Token();
  485. }
  486. var comments = token.comments_before;
  487. if (!comments) {
  488. if (!scan) return;
  489. token.comments_before = comments = [];
  490. }
  491. if (comments._dumped === self) return;
  492. comments._dumped = self;
  493. return comments;
  494. }
  495. }
  496. function append_comments(node, tail) {
  497. var self = this;
  498. var token = node.end;
  499. if (!token) return;
  500. var comments = token[tail ? "comments_before" : "comments_after"];
  501. if (!comments || comments._dumped === self) return;
  502. if (!(node instanceof AST_Statement || all(comments, function(c) {
  503. return !/comment[134]/.test(c.type);
  504. }))) return;
  505. comments._dumped = self;
  506. var insert = OUTPUT.length;
  507. comments.filter(comment_filter, node).forEach(function(comment, index) {
  508. pad_comment(comment, index || !tail);
  509. print_comment(comment);
  510. });
  511. if (OUTPUT.length > insert) newline_insert = insert;
  512. }
  513. return {
  514. get : get,
  515. reset : reset,
  516. indent : indent,
  517. should_break : options.width ? function() {
  518. return current_col - indentation >= options.width;
  519. } : return_false,
  520. has_parens : function() { return last.slice(-1) == "(" },
  521. newline : newline,
  522. print : print,
  523. space : space,
  524. comma : comma,
  525. colon : colon,
  526. last : function() { return last },
  527. semicolon : semicolon,
  528. force_semicolon : force_semicolon,
  529. to_utf8 : to_utf8,
  530. print_name : function(name) { print(to_utf8(name.toString(), true)) },
  531. print_string : options.inline_script ? function(str, quote) {
  532. str = make_string(str, quote).replace(/<\x2f(script)([>\/\t\n\f\r ])/gi, "<\\/$1$2");
  533. print(str.replace(/\x3c!--/g, "\\x3c!--").replace(/--\x3e/g, "--\\x3e"));
  534. } : function(str, quote) {
  535. print(make_string(str, quote));
  536. },
  537. with_indent : with_indent,
  538. with_block : with_block,
  539. with_parens : with_parens,
  540. with_square : with_square,
  541. add_mapping : add_mapping,
  542. option : function(opt) { return options[opt] },
  543. prepend_comments: options.comments || options.shebang ? prepend_comments : noop,
  544. append_comments : options.comments ? append_comments : noop,
  545. push_node : function(node) { stack.push(node) },
  546. pop_node : options.preserve_line ? function() {
  547. var node = stack.pop();
  548. if (node.start && node.start.line > current_line) {
  549. insert_newlines(node.start.line - current_line);
  550. }
  551. } : function() {
  552. stack.pop();
  553. },
  554. parent : function(n) {
  555. return stack[stack.length - 2 - (n || 0)];
  556. },
  557. };
  558. }
  559. /* -----[ code generators ]----- */
  560. (function() {
  561. /* -----[ utils ]----- */
  562. function DEFPRINT(nodetype, generator) {
  563. nodetype.DEFMETHOD("_codegen", generator);
  564. }
  565. var use_asm = false;
  566. AST_Node.DEFMETHOD("print", function(stream, force_parens) {
  567. var self = this;
  568. stream.push_node(self);
  569. if (force_parens || self.needs_parens(stream)) {
  570. stream.with_parens(doit);
  571. } else {
  572. doit();
  573. }
  574. stream.pop_node();
  575. function doit() {
  576. stream.prepend_comments(self);
  577. self.add_source_map(stream);
  578. self._codegen(stream);
  579. stream.append_comments(self);
  580. }
  581. });
  582. var readonly = OutputStream({
  583. inline_script: false,
  584. shebang: false,
  585. width: false,
  586. });
  587. AST_Node.DEFMETHOD("print_to_string", function(options) {
  588. if (options) {
  589. var stream = OutputStream(options);
  590. this.print(stream);
  591. return stream.get();
  592. }
  593. this.print(readonly);
  594. return readonly.reset();
  595. });
  596. /* -----[ PARENTHESES ]----- */
  597. function PARENS(nodetype, func) {
  598. nodetype.DEFMETHOD("needs_parens", func);
  599. }
  600. PARENS(AST_Node, return_false);
  601. // a function expression needs parens around it when it's provably
  602. // the first token to appear in a statement.
  603. function needs_parens_function(output) {
  604. var p = output.parent();
  605. if (!output.has_parens() && first_in_statement(output, false, true)) {
  606. // export default function() {}
  607. // export default (function foo() {});
  608. // export default (function() {})(foo);
  609. // export default (function() {})`foo`;
  610. // export default (function() {}) ? foo : bar;
  611. return this.name || !(p instanceof AST_ExportDefault);
  612. }
  613. if (output.option("webkit") && p instanceof AST_PropAccess && p.expression === this) return true;
  614. if (output.option("wrap_iife") && p instanceof AST_Call && p.expression === this) return true;
  615. }
  616. PARENS(AST_AsyncFunction, needs_parens_function);
  617. PARENS(AST_AsyncGeneratorFunction, needs_parens_function);
  618. PARENS(AST_ClassExpression, needs_parens_function);
  619. PARENS(AST_Function, needs_parens_function);
  620. PARENS(AST_GeneratorFunction, needs_parens_function);
  621. // same goes for an object literal, because otherwise it would be
  622. // interpreted as a block of code.
  623. function needs_parens_obj(output) {
  624. return !output.has_parens() && first_in_statement(output, true);
  625. }
  626. PARENS(AST_Object, needs_parens_obj);
  627. function needs_parens_unary(output) {
  628. var p = output.parent();
  629. // (-x) ** y
  630. if (p instanceof AST_Binary) return p.operator == "**" && p.left === this;
  631. // (await x)(y)
  632. // new (await x)
  633. if (p instanceof AST_Call) return p.expression === this;
  634. // class extends (x++) {}
  635. // class x extends (typeof y) {}
  636. if (p instanceof AST_Class) return true;
  637. // (x++)[y]
  638. // (typeof x).y
  639. if (p instanceof AST_PropAccess) return p.expression === this;
  640. // (~x)`foo`
  641. if (p instanceof AST_Template) return p.tag === this;
  642. }
  643. PARENS(AST_Await, needs_parens_unary);
  644. PARENS(AST_Unary, needs_parens_unary);
  645. PARENS(AST_Sequence, function(output) {
  646. var p = output.parent();
  647. // [ 1, (2, 3), 4 ] ---> [ 1, 3, 4 ]
  648. return p instanceof AST_Array
  649. // () ---> (foo, bar)
  650. || is_arrow(p) && p.value === this
  651. // await (foo, bar)
  652. || p instanceof AST_Await
  653. // 1 + (2, 3) + 4 ---> 8
  654. || p instanceof AST_Binary
  655. // new (foo, bar) or foo(1, (2, 3), 4)
  656. || p instanceof AST_Call
  657. // class extends (foo, bar) {}
  658. // class foo extends (bar, baz) {}
  659. || p instanceof AST_Class
  660. // class { foo = (bar, baz) }
  661. // class { [(foo, bar)]() {} }
  662. || p instanceof AST_ClassProperty
  663. // (false, true) ? (a = 10, b = 20) : (c = 30)
  664. // ---> 20 (side effect, set a := 10 and b := 20)
  665. || p instanceof AST_Conditional
  666. // [ a = (1, 2) ] = [] ---> a == 2
  667. || p instanceof AST_DefaultValue
  668. // { [(1, 2)]: foo } = bar
  669. // { 1: (2, foo) } = bar
  670. || p instanceof AST_DestructuredKeyVal
  671. // export default (foo, bar)
  672. || p instanceof AST_ExportDefault
  673. // for (foo of (bar, baz));
  674. || p instanceof AST_ForOf
  675. // { [(1, 2)]: 3 }[2] ---> 3
  676. // { foo: (1, 2) }.foo ---> 2
  677. || p instanceof AST_ObjectProperty
  678. // (1, {foo:2}).foo or (1, {foo:2})["foo"] ---> 2
  679. || p instanceof AST_PropAccess && p.expression === this
  680. // ...(foo, bar, baz)
  681. || p instanceof AST_Spread
  682. // (foo, bar)`baz`
  683. || p instanceof AST_Template && p.tag === this
  684. // !(foo, bar, baz)
  685. || p instanceof AST_Unary
  686. // var a = (1, 2), b = a + a; ---> b == 4
  687. || p instanceof AST_VarDef
  688. // yield (foo, bar)
  689. || p instanceof AST_Yield;
  690. });
  691. PARENS(AST_Binary, function(output) {
  692. var p = output.parent();
  693. // await (foo && bar)
  694. if (p instanceof AST_Await) return true;
  695. // this deals with precedence:
  696. // 3 * (2 + 1)
  697. // 3 - (2 - 1)
  698. // (1 ** 2) ** 3
  699. if (p instanceof AST_Binary) {
  700. var po = p.operator, pp = PRECEDENCE[po];
  701. var so = this.operator, sp = PRECEDENCE[so];
  702. return pp > sp
  703. || po == "??" && (so == "&&" || so == "||")
  704. || (pp == sp && this === p[po == "**" ? "left" : "right"]);
  705. }
  706. // (foo && bar)()
  707. if (p instanceof AST_Call) return p.expression === this;
  708. // class extends (foo && bar) {}
  709. // class foo extends (bar || null) {}
  710. if (p instanceof AST_Class) return true;
  711. // (foo && bar)["prop"], (foo && bar).prop
  712. if (p instanceof AST_PropAccess) return p.expression === this;
  713. // (foo && bar)``
  714. if (p instanceof AST_Template) return p.tag === this;
  715. // typeof (foo && bar)
  716. if (p instanceof AST_Unary) return true;
  717. });
  718. function lhs_has_optional(node, output) {
  719. var p = output.parent();
  720. if (p instanceof AST_PropAccess && p.expression === node && is_lhs(p, output.parent(1))) {
  721. // ++(foo?.bar).baz
  722. // (foo?.()).bar = baz
  723. do {
  724. if (node.optional) return true;
  725. node = node.expression;
  726. } while (node.TYPE == "Call" || node instanceof AST_PropAccess);
  727. }
  728. }
  729. PARENS(AST_PropAccess, function(output) {
  730. var node = this;
  731. var p = output.parent();
  732. if (p instanceof AST_New) {
  733. if (p.expression !== node) return false;
  734. // i.e. new (foo().bar)
  735. //
  736. // if there's one call into this subtree, then we need
  737. // parens around it too, otherwise the call will be
  738. // interpreted as passing the arguments to the upper New
  739. // expression.
  740. do {
  741. node = node.expression;
  742. } while (node instanceof AST_PropAccess);
  743. return node.TYPE == "Call";
  744. }
  745. return lhs_has_optional(node, output);
  746. });
  747. PARENS(AST_Call, function(output) {
  748. var node = this;
  749. var p = output.parent();
  750. if (p instanceof AST_New) return p.expression === node;
  751. // https://bugs.webkit.org/show_bug.cgi?id=123506
  752. if (output.option("webkit")
  753. && node.expression instanceof AST_Function
  754. && p instanceof AST_PropAccess
  755. && p.expression === node) {
  756. var g = output.parent(1);
  757. if (g instanceof AST_Assign && g.left === p) return true;
  758. }
  759. return lhs_has_optional(node, output);
  760. });
  761. PARENS(AST_New, function(output) {
  762. if (need_constructor_parens(this, output)) return false;
  763. var p = output.parent();
  764. // (new foo)(bar)
  765. if (p instanceof AST_Call) return p.expression === this;
  766. // (new Date).getTime(), (new Date)["getTime"]()
  767. if (p instanceof AST_PropAccess) return true;
  768. // (new foo)`bar`
  769. if (p instanceof AST_Template) return p.tag === this;
  770. });
  771. PARENS(AST_Number, function(output) {
  772. if (!output.option("galio")) return false;
  773. // https://github.com/mishoo/UglifyJS/pull/1009
  774. var p = output.parent();
  775. return p instanceof AST_PropAccess && p.expression === this && /^0/.test(make_num(this.value));
  776. });
  777. function needs_parens_assign_cond(self, output) {
  778. var p = output.parent();
  779. // await (a = foo)
  780. if (p instanceof AST_Await) return true;
  781. // 1 + (a = 2) + 3 → 6, side effect setting a = 2
  782. if (p instanceof AST_Binary) return !(p instanceof AST_Assign);
  783. // (a = func)() —or— new (a = Object)()
  784. if (p instanceof AST_Call) return p.expression === self;
  785. // class extends (a = foo) {}
  786. // class foo extends (bar ? baz : moo) {}
  787. if (p instanceof AST_Class) return true;
  788. // (a = foo) ? bar : baz
  789. if (p instanceof AST_Conditional) return p.condition === self;
  790. // (a = foo)["prop"] —or— (a = foo).prop
  791. if (p instanceof AST_PropAccess) return p.expression === self;
  792. // (a = foo)`bar`
  793. if (p instanceof AST_Template) return p.tag === self;
  794. // !(a = false) → true
  795. if (p instanceof AST_Unary) return true;
  796. }
  797. PARENS(AST_Arrow, function(output) {
  798. return needs_parens_assign_cond(this, output);
  799. });
  800. PARENS(AST_Assign, function(output) {
  801. if (needs_parens_assign_cond(this, output)) return true;
  802. // v8 parser bug ---> workaround
  803. // f([1], [a] = []) ---> f([1], ([a] = []))
  804. if (output.option("v8")) return this.left instanceof AST_Destructured;
  805. // ({ p: a } = o);
  806. if (this.left instanceof AST_DestructuredObject) return needs_parens_obj(output);
  807. });
  808. PARENS(AST_AsyncArrow, function(output) {
  809. return needs_parens_assign_cond(this, output);
  810. });
  811. PARENS(AST_Conditional, function(output) {
  812. return needs_parens_assign_cond(this, output);
  813. });
  814. PARENS(AST_Yield, function(output) {
  815. return needs_parens_assign_cond(this, output);
  816. });
  817. /* -----[ PRINTERS ]----- */
  818. DEFPRINT(AST_Directive, function(output) {
  819. var quote = this.quote;
  820. var value = this.value;
  821. switch (output.option("quote_style")) {
  822. case 0:
  823. case 2:
  824. if (value.indexOf('"') == -1) quote = '"';
  825. break;
  826. case 1:
  827. if (value.indexOf("'") == -1) quote = "'";
  828. break;
  829. }
  830. output.print(quote + value + quote);
  831. output.semicolon();
  832. });
  833. DEFPRINT(AST_Debugger, function(output) {
  834. output.print("debugger");
  835. output.semicolon();
  836. });
  837. /* -----[ statements ]----- */
  838. function display_body(body, is_toplevel, output, allow_directives) {
  839. var last = body.length - 1;
  840. var in_directive = allow_directives;
  841. var was_asm = use_asm;
  842. body.forEach(function(stmt, i) {
  843. if (in_directive) {
  844. if (stmt instanceof AST_Directive) {
  845. if (stmt.value == "use asm") use_asm = true;
  846. } else if (!(stmt instanceof AST_EmptyStatement)) {
  847. if (stmt instanceof AST_SimpleStatement && stmt.body instanceof AST_String) {
  848. output.force_semicolon();
  849. }
  850. in_directive = false;
  851. }
  852. }
  853. if (stmt instanceof AST_EmptyStatement) return;
  854. output.indent();
  855. stmt.print(output);
  856. if (i == last && is_toplevel) return;
  857. output.newline();
  858. if (is_toplevel) output.newline();
  859. });
  860. use_asm = was_asm;
  861. }
  862. DEFPRINT(AST_Toplevel, function(output) {
  863. display_body(this.body, true, output, true);
  864. output.print("");
  865. });
  866. DEFPRINT(AST_LabeledStatement, function(output) {
  867. this.label.print(output);
  868. output.colon();
  869. this.body.print(output);
  870. });
  871. DEFPRINT(AST_SimpleStatement, function(output) {
  872. this.body.print(output);
  873. output.semicolon();
  874. });
  875. function print_braced_empty(self, output) {
  876. output.print("{");
  877. output.with_indent(function() {
  878. output.append_comments(self, true);
  879. });
  880. output.print("}");
  881. }
  882. function print_braced(self, output, allow_directives) {
  883. if (self.body.length > 0) {
  884. output.with_block(function() {
  885. display_body(self.body, false, output, allow_directives);
  886. });
  887. } else print_braced_empty(self, output);
  888. }
  889. DEFPRINT(AST_BlockStatement, function(output) {
  890. print_braced(this, output);
  891. });
  892. DEFPRINT(AST_EmptyStatement, function(output) {
  893. output.semicolon();
  894. });
  895. DEFPRINT(AST_Do, function(output) {
  896. var self = this;
  897. output.print("do");
  898. output.space();
  899. make_block(self.body, output);
  900. output.space();
  901. output.print("while");
  902. output.space();
  903. output.with_parens(function() {
  904. self.condition.print(output);
  905. });
  906. output.semicolon();
  907. });
  908. DEFPRINT(AST_While, function(output) {
  909. var self = this;
  910. output.print("while");
  911. output.space();
  912. output.with_parens(function() {
  913. self.condition.print(output);
  914. });
  915. output.space();
  916. force_statement(self.body, output);
  917. });
  918. DEFPRINT(AST_For, function(output) {
  919. var self = this;
  920. output.print("for");
  921. output.space();
  922. output.with_parens(function() {
  923. if (self.init) {
  924. if (self.init instanceof AST_Definitions) {
  925. self.init.print(output);
  926. } else {
  927. parenthesize_for_noin(self.init, output, true);
  928. }
  929. output.print(";");
  930. output.space();
  931. } else {
  932. output.print(";");
  933. }
  934. if (self.condition) {
  935. self.condition.print(output);
  936. output.print(";");
  937. output.space();
  938. } else {
  939. output.print(";");
  940. }
  941. if (self.step) {
  942. self.step.print(output);
  943. }
  944. });
  945. output.space();
  946. force_statement(self.body, output);
  947. });
  948. function print_for_enum(prefix, infix) {
  949. return function(output) {
  950. var self = this;
  951. output.print(prefix);
  952. output.space();
  953. output.with_parens(function() {
  954. self.init.print(output);
  955. output.space();
  956. output.print(infix);
  957. output.space();
  958. self.object.print(output);
  959. });
  960. output.space();
  961. force_statement(self.body, output);
  962. };
  963. }
  964. DEFPRINT(AST_ForAwaitOf, print_for_enum("for await", "of"));
  965. DEFPRINT(AST_ForIn, print_for_enum("for", "in"));
  966. DEFPRINT(AST_ForOf, print_for_enum("for", "of"));
  967. DEFPRINT(AST_With, function(output) {
  968. var self = this;
  969. output.print("with");
  970. output.space();
  971. output.with_parens(function() {
  972. self.expression.print(output);
  973. });
  974. output.space();
  975. force_statement(self.body, output);
  976. });
  977. DEFPRINT(AST_ExportDeclaration, function(output) {
  978. output.print("export");
  979. output.space();
  980. this.body.print(output);
  981. });
  982. DEFPRINT(AST_ExportDefault, function(output) {
  983. output.print("export");
  984. output.space();
  985. output.print("default");
  986. output.space();
  987. var body = this.body;
  988. body.print(output);
  989. if (body instanceof AST_ClassExpression) {
  990. if (!body.name) return;
  991. }
  992. if (body instanceof AST_DefClass) return;
  993. if (body instanceof AST_LambdaDefinition) return;
  994. if (body instanceof AST_LambdaExpression) {
  995. if (!body.name && !is_arrow(body)) return;
  996. }
  997. output.semicolon();
  998. });
  999. DEFPRINT(AST_ExportForeign, function(output) {
  1000. var self = this;
  1001. output.print("export");
  1002. output.space();
  1003. var len = self.keys.length;
  1004. if (len == 0) {
  1005. print_braced_empty(self, output);
  1006. } else if (self.keys[0] == "*") {
  1007. print_entry(0);
  1008. } else output.with_block(function() {
  1009. output.indent();
  1010. print_entry(0);
  1011. for (var i = 1; i < len; i++) {
  1012. output.print(",");
  1013. output.newline();
  1014. output.indent();
  1015. print_entry(i);
  1016. }
  1017. output.newline();
  1018. });
  1019. output.space();
  1020. output.print("from");
  1021. output.space();
  1022. output.print_string(self.path, self.quote);
  1023. output.semicolon();
  1024. function print_entry(index) {
  1025. var alias = self.aliases[index];
  1026. var key = self.keys[index];
  1027. output.print_name(key);
  1028. if (alias != key) {
  1029. output.space();
  1030. output.print("as");
  1031. output.space();
  1032. output.print_name(alias);
  1033. }
  1034. }
  1035. });
  1036. DEFPRINT(AST_ExportReferences, function(output) {
  1037. var self = this;
  1038. output.print("export");
  1039. output.space();
  1040. print_properties(self, output);
  1041. output.semicolon();
  1042. });
  1043. DEFPRINT(AST_Import, function(output) {
  1044. var self = this;
  1045. output.print("import");
  1046. output.space();
  1047. if (self.default) self.default.print(output);
  1048. if (self.all) {
  1049. if (self.default) output.comma();
  1050. self.all.print(output);
  1051. }
  1052. if (self.properties) {
  1053. if (self.default) output.comma();
  1054. print_properties(self, output);
  1055. }
  1056. if (self.all || self.default || self.properties) {
  1057. output.space();
  1058. output.print("from");
  1059. output.space();
  1060. }
  1061. output.print_string(self.path, self.quote);
  1062. output.semicolon();
  1063. });
  1064. /* -----[ functions ]----- */
  1065. function print_funargs(self, output) {
  1066. output.with_parens(function() {
  1067. self.argnames.forEach(function(arg, i) {
  1068. if (i) output.comma();
  1069. arg.print(output);
  1070. });
  1071. if (self.rest) {
  1072. if (self.argnames.length) output.comma();
  1073. output.print("...");
  1074. self.rest.print(output);
  1075. }
  1076. });
  1077. }
  1078. function print_arrow(self, output) {
  1079. if (self.argnames.length == 1 && self.argnames[0] instanceof AST_SymbolFunarg && !self.rest) {
  1080. self.argnames[0].print(output);
  1081. } else {
  1082. print_funargs(self, output);
  1083. }
  1084. output.space();
  1085. output.print("=>");
  1086. output.space();
  1087. if (self.value) {
  1088. self.value.print(output);
  1089. } else {
  1090. print_braced(self, output, true);
  1091. }
  1092. }
  1093. DEFPRINT(AST_Arrow, function(output) {
  1094. print_arrow(this, output);
  1095. });
  1096. DEFPRINT(AST_AsyncArrow, function(output) {
  1097. output.print("async");
  1098. output.space();
  1099. print_arrow(this, output);
  1100. });
  1101. function print_lambda(self, output) {
  1102. if (self.name) {
  1103. output.space();
  1104. self.name.print(output);
  1105. }
  1106. print_funargs(self, output);
  1107. output.space();
  1108. print_braced(self, output, true);
  1109. }
  1110. DEFPRINT(AST_Lambda, function(output) {
  1111. output.print("function");
  1112. print_lambda(this, output);
  1113. });
  1114. function print_async(output) {
  1115. output.print("async");
  1116. output.space();
  1117. output.print("function");
  1118. print_lambda(this, output);
  1119. }
  1120. DEFPRINT(AST_AsyncDefun, print_async);
  1121. DEFPRINT(AST_AsyncFunction, print_async);
  1122. function print_async_generator(output) {
  1123. output.print("async");
  1124. output.space();
  1125. output.print("function*");
  1126. print_lambda(this, output);
  1127. }
  1128. DEFPRINT(AST_AsyncGeneratorDefun, print_async_generator);
  1129. DEFPRINT(AST_AsyncGeneratorFunction, print_async_generator);
  1130. function print_generator(output) {
  1131. output.print("function*");
  1132. print_lambda(this, output);
  1133. }
  1134. DEFPRINT(AST_GeneratorDefun, print_generator);
  1135. DEFPRINT(AST_GeneratorFunction, print_generator);
  1136. /* -----[ classes ]----- */
  1137. DEFPRINT(AST_Class, function(output) {
  1138. var self = this;
  1139. output.print("class");
  1140. if (self.name) {
  1141. output.space();
  1142. self.name.print(output);
  1143. }
  1144. if (self.extends) {
  1145. output.space();
  1146. output.print("extends");
  1147. output.space();
  1148. self.extends.print(output);
  1149. }
  1150. output.space();
  1151. print_properties(self, output, true);
  1152. });
  1153. DEFPRINT(AST_ClassField, function(output) {
  1154. var self = this;
  1155. if (self.static) {
  1156. output.print("static");
  1157. output.space();
  1158. }
  1159. print_property_key(self, output);
  1160. if (self.value) {
  1161. output.space();
  1162. output.print("=");
  1163. output.space();
  1164. self.value.print(output);
  1165. }
  1166. output.semicolon();
  1167. });
  1168. DEFPRINT(AST_ClassGetter, print_accessor("get"));
  1169. DEFPRINT(AST_ClassSetter, print_accessor("set"));
  1170. function print_method(self, output) {
  1171. var fn = self.value;
  1172. if (is_async(fn)) {
  1173. output.print("async");
  1174. output.space();
  1175. }
  1176. if (is_generator(fn)) output.print("*");
  1177. print_property_key(self, output);
  1178. print_lambda(self.value, output);
  1179. }
  1180. DEFPRINT(AST_ClassMethod, function(output) {
  1181. var self = this;
  1182. if (self.static) {
  1183. output.print("static");
  1184. output.space();
  1185. }
  1186. print_method(self, output);
  1187. });
  1188. /* -----[ jumps ]----- */
  1189. function print_jump(kind, prop) {
  1190. return function(output) {
  1191. output.print(kind);
  1192. var target = this[prop];
  1193. if (target) {
  1194. output.space();
  1195. target.print(output);
  1196. }
  1197. output.semicolon();
  1198. };
  1199. }
  1200. DEFPRINT(AST_Return, print_jump("return", "value"));
  1201. DEFPRINT(AST_Throw, print_jump("throw", "value"));
  1202. DEFPRINT(AST_Break, print_jump("break", "label"));
  1203. DEFPRINT(AST_Continue, print_jump("continue", "label"));
  1204. /* -----[ if ]----- */
  1205. function make_then(self, output) {
  1206. var b = self.body;
  1207. if (output.option("braces") && !(b instanceof AST_Const || b instanceof AST_Let)
  1208. || output.option("ie8") && b instanceof AST_Do)
  1209. return make_block(b, output);
  1210. // The squeezer replaces "block"-s that contain only a single
  1211. // statement with the statement itself; technically, the AST
  1212. // is correct, but this can create problems when we output an
  1213. // IF having an ELSE clause where the THEN clause ends in an
  1214. // IF *without* an ELSE block (then the outer ELSE would refer
  1215. // to the inner IF). This function checks for this case and
  1216. // adds the block braces if needed.
  1217. if (!b) return output.force_semicolon();
  1218. while (true) {
  1219. if (b instanceof AST_If) {
  1220. if (!b.alternative) {
  1221. make_block(self.body, output);
  1222. return;
  1223. }
  1224. b = b.alternative;
  1225. } else if (b instanceof AST_StatementWithBody) {
  1226. b = b.body;
  1227. } else break;
  1228. }
  1229. force_statement(self.body, output);
  1230. }
  1231. DEFPRINT(AST_If, function(output) {
  1232. var self = this;
  1233. output.print("if");
  1234. output.space();
  1235. output.with_parens(function() {
  1236. self.condition.print(output);
  1237. });
  1238. output.space();
  1239. if (self.alternative) {
  1240. make_then(self, output);
  1241. output.space();
  1242. output.print("else");
  1243. output.space();
  1244. if (self.alternative instanceof AST_If)
  1245. self.alternative.print(output);
  1246. else
  1247. force_statement(self.alternative, output);
  1248. } else {
  1249. force_statement(self.body, output);
  1250. }
  1251. });
  1252. /* -----[ switch ]----- */
  1253. DEFPRINT(AST_Switch, function(output) {
  1254. var self = this;
  1255. output.print("switch");
  1256. output.space();
  1257. output.with_parens(function() {
  1258. self.expression.print(output);
  1259. });
  1260. output.space();
  1261. var last = self.body.length - 1;
  1262. if (last < 0) print_braced_empty(self, output);
  1263. else output.with_block(function() {
  1264. self.body.forEach(function(branch, i) {
  1265. output.indent(true);
  1266. branch.print(output);
  1267. if (i < last && branch.body.length > 0)
  1268. output.newline();
  1269. });
  1270. });
  1271. });
  1272. function print_branch_body(self, output) {
  1273. output.newline();
  1274. self.body.forEach(function(stmt) {
  1275. output.indent();
  1276. stmt.print(output);
  1277. output.newline();
  1278. });
  1279. }
  1280. DEFPRINT(AST_Default, function(output) {
  1281. output.print("default:");
  1282. print_branch_body(this, output);
  1283. });
  1284. DEFPRINT(AST_Case, function(output) {
  1285. var self = this;
  1286. output.print("case");
  1287. output.space();
  1288. self.expression.print(output);
  1289. output.print(":");
  1290. print_branch_body(self, output);
  1291. });
  1292. /* -----[ exceptions ]----- */
  1293. DEFPRINT(AST_Try, function(output) {
  1294. var self = this;
  1295. output.print("try");
  1296. output.space();
  1297. print_braced(self, output);
  1298. if (self.bcatch) {
  1299. output.space();
  1300. self.bcatch.print(output);
  1301. }
  1302. if (self.bfinally) {
  1303. output.space();
  1304. self.bfinally.print(output);
  1305. }
  1306. });
  1307. DEFPRINT(AST_Catch, function(output) {
  1308. var self = this;
  1309. output.print("catch");
  1310. if (self.argname) {
  1311. output.space();
  1312. output.with_parens(function() {
  1313. self.argname.print(output);
  1314. });
  1315. }
  1316. output.space();
  1317. print_braced(self, output);
  1318. });
  1319. DEFPRINT(AST_Finally, function(output) {
  1320. output.print("finally");
  1321. output.space();
  1322. print_braced(this, output);
  1323. });
  1324. function print_definitinos(type) {
  1325. return function(output) {
  1326. var self = this;
  1327. output.print(type);
  1328. output.space();
  1329. self.definitions.forEach(function(def, i) {
  1330. if (i) output.comma();
  1331. def.print(output);
  1332. });
  1333. var p = output.parent();
  1334. if (!(p instanceof AST_IterationStatement && p.init === self)) output.semicolon();
  1335. };
  1336. }
  1337. DEFPRINT(AST_Const, print_definitinos("const"));
  1338. DEFPRINT(AST_Let, print_definitinos("let"));
  1339. DEFPRINT(AST_Var, print_definitinos("var"));
  1340. function parenthesize_for_noin(node, output, noin) {
  1341. var parens = false;
  1342. // need to take some precautions here:
  1343. // https://github.com/mishoo/UglifyJS/issues/60
  1344. if (noin) node.walk(new TreeWalker(function(node) {
  1345. if (parens) return true;
  1346. if (node instanceof AST_Binary && node.operator == "in") return parens = true;
  1347. if (node instanceof AST_Scope && !(is_arrow(node) && node.value)) return true;
  1348. }));
  1349. node.print(output, parens);
  1350. }
  1351. DEFPRINT(AST_VarDef, function(output) {
  1352. var self = this;
  1353. self.name.print(output);
  1354. if (self.value) {
  1355. output.space();
  1356. output.print("=");
  1357. output.space();
  1358. var p = output.parent(1);
  1359. var noin = p instanceof AST_For || p instanceof AST_ForEnumeration;
  1360. parenthesize_for_noin(self.value, output, noin);
  1361. }
  1362. });
  1363. DEFPRINT(AST_DefaultValue, function(output) {
  1364. var self = this;
  1365. self.name.print(output);
  1366. output.space();
  1367. output.print("=");
  1368. output.space();
  1369. self.value.print(output);
  1370. });
  1371. /* -----[ other expressions ]----- */
  1372. function print_annotation(self, output) {
  1373. if (!output.option("annotations")) return;
  1374. if (!self.pure) return;
  1375. var level = 0, parent = self, node;
  1376. do {
  1377. node = parent;
  1378. parent = output.parent(level++);
  1379. if (parent instanceof AST_Call && parent.expression === node) return;
  1380. } while (parent instanceof AST_PropAccess && parent.expression === node);
  1381. output.print(typeof self.pure == "string" ? "/*" + self.pure + "*/" : "/*@__PURE__*/");
  1382. }
  1383. function print_call_args(self, output) {
  1384. if (self.expression instanceof AST_Call || self.expression instanceof AST_Lambda) {
  1385. output.add_mapping(self.start);
  1386. }
  1387. output.with_parens(function() {
  1388. self.args.forEach(function(expr, i) {
  1389. if (i) output.comma();
  1390. expr.print(output);
  1391. });
  1392. });
  1393. }
  1394. DEFPRINT(AST_Call, function(output) {
  1395. var self = this;
  1396. print_annotation(self, output);
  1397. self.expression.print(output);
  1398. if (self.optional) output.print("?.");
  1399. print_call_args(self, output);
  1400. });
  1401. DEFPRINT(AST_New, function(output) {
  1402. var self = this;
  1403. print_annotation(self, output);
  1404. output.print("new");
  1405. output.space();
  1406. self.expression.print(output);
  1407. if (need_constructor_parens(self, output)) print_call_args(self, output);
  1408. });
  1409. DEFPRINT(AST_Sequence, function(output) {
  1410. this.expressions.forEach(function(node, index) {
  1411. if (index > 0) {
  1412. output.comma();
  1413. if (output.should_break()) {
  1414. output.newline();
  1415. output.indent();
  1416. }
  1417. }
  1418. node.print(output);
  1419. });
  1420. });
  1421. DEFPRINT(AST_Dot, function(output) {
  1422. var self = this;
  1423. var expr = self.expression;
  1424. expr.print(output);
  1425. var prop = self.property;
  1426. if (output.option("ie8") && RESERVED_WORDS[prop]) {
  1427. output.print(self.optional ? "?.[" : "[");
  1428. output.add_mapping(self.end);
  1429. output.print_string(prop);
  1430. output.print("]");
  1431. } else {
  1432. if (expr instanceof AST_Number && !/[ex.)]/i.test(output.last())) output.print(".");
  1433. output.print(self.optional ? "?." : ".");
  1434. // the name after dot would be mapped about here.
  1435. output.add_mapping(self.end);
  1436. output.print_name(prop);
  1437. }
  1438. });
  1439. DEFPRINT(AST_Sub, function(output) {
  1440. var self = this;
  1441. self.expression.print(output);
  1442. output.print(self.optional ? "?.[" : "[");
  1443. self.property.print(output);
  1444. output.print("]");
  1445. });
  1446. DEFPRINT(AST_Spread, function(output) {
  1447. output.print("...");
  1448. this.expression.print(output);
  1449. });
  1450. DEFPRINT(AST_UnaryPrefix, function(output) {
  1451. var op = this.operator;
  1452. var exp = this.expression;
  1453. output.print(op);
  1454. if (/^[a-z]/i.test(op)
  1455. || (/[+-]$/.test(op)
  1456. && exp instanceof AST_UnaryPrefix
  1457. && /^[+-]/.test(exp.operator))) {
  1458. output.space();
  1459. }
  1460. exp.print(output);
  1461. });
  1462. DEFPRINT(AST_UnaryPostfix, function(output) {
  1463. this.expression.print(output);
  1464. output.print(this.operator);
  1465. });
  1466. DEFPRINT(AST_Binary, function(output) {
  1467. var self = this;
  1468. self.left.print(output);
  1469. output.space();
  1470. output.print(self.operator);
  1471. output.space();
  1472. self.right.print(output);
  1473. });
  1474. DEFPRINT(AST_Conditional, function(output) {
  1475. var self = this;
  1476. self.condition.print(output);
  1477. output.space();
  1478. output.print("?");
  1479. output.space();
  1480. self.consequent.print(output);
  1481. output.space();
  1482. output.colon();
  1483. self.alternative.print(output);
  1484. });
  1485. DEFPRINT(AST_Await, function(output) {
  1486. output.print("await");
  1487. output.space();
  1488. this.expression.print(output);
  1489. });
  1490. DEFPRINT(AST_Yield, function(output) {
  1491. output.print(this.nested ? "yield*" : "yield");
  1492. if (this.expression) {
  1493. output.space();
  1494. this.expression.print(output);
  1495. }
  1496. });
  1497. /* -----[ literals ]----- */
  1498. DEFPRINT(AST_Array, function(output) {
  1499. var a = this.elements, len = a.length;
  1500. output.with_square(len > 0 ? function() {
  1501. output.space();
  1502. a.forEach(function(exp, i) {
  1503. if (i) output.comma();
  1504. exp.print(output);
  1505. // If the final element is a hole, we need to make sure it
  1506. // doesn't look like a trailing comma, by inserting an actual
  1507. // trailing comma.
  1508. if (i === len - 1 && exp instanceof AST_Hole)
  1509. output.comma();
  1510. });
  1511. output.space();
  1512. } : noop);
  1513. });
  1514. DEFPRINT(AST_DestructuredArray, function(output) {
  1515. var a = this.elements, len = a.length, rest = this.rest;
  1516. output.with_square(len || rest ? function() {
  1517. output.space();
  1518. a.forEach(function(exp, i) {
  1519. if (i) output.comma();
  1520. exp.print(output);
  1521. });
  1522. if (rest) {
  1523. if (len) output.comma();
  1524. output.print("...");
  1525. rest.print(output);
  1526. } else if (a[len - 1] instanceof AST_Hole) {
  1527. // If the final element is a hole, we need to make sure it
  1528. // doesn't look like a trailing comma, by inserting an actual
  1529. // trailing comma.
  1530. output.comma();
  1531. }
  1532. output.space();
  1533. } : noop);
  1534. });
  1535. DEFPRINT(AST_DestructuredKeyVal, function(output) {
  1536. var self = this;
  1537. var key = print_property_key(self, output);
  1538. var value = self.value;
  1539. if (key && value instanceof AST_SymbolDeclaration && key == get_symbol_name(value)) return;
  1540. output.colon();
  1541. value.print(output);
  1542. });
  1543. DEFPRINT(AST_DestructuredObject, function(output) {
  1544. var props = this.properties, len = props.length, rest = this.rest;
  1545. if (len || rest) output.with_block(function() {
  1546. props.forEach(function(prop, i) {
  1547. if (i) {
  1548. output.print(",");
  1549. output.newline();
  1550. }
  1551. output.indent();
  1552. prop.print(output);
  1553. });
  1554. if (rest) {
  1555. if (len) {
  1556. output.print(",");
  1557. output.newline();
  1558. }
  1559. output.indent();
  1560. output.print("...");
  1561. rest.print(output);
  1562. }
  1563. output.newline();
  1564. });
  1565. else print_braced_empty(this, output);
  1566. });
  1567. function print_properties(self, output, no_comma) {
  1568. var props = self.properties;
  1569. if (props.length > 0) output.with_block(function() {
  1570. props.forEach(function(prop, i) {
  1571. if (i) {
  1572. if (!no_comma) output.print(",");
  1573. output.newline();
  1574. }
  1575. output.indent();
  1576. prop.print(output);
  1577. });
  1578. output.newline();
  1579. });
  1580. else print_braced_empty(self, output);
  1581. }
  1582. DEFPRINT(AST_Object, function(output) {
  1583. print_properties(this, output);
  1584. });
  1585. function print_property_key(self, output) {
  1586. var key = self.key;
  1587. if (key instanceof AST_Node) {
  1588. output.with_square(function() {
  1589. key.print(output);
  1590. });
  1591. } else if (output.option("quote_keys")) {
  1592. output.print_string(key);
  1593. } else if ("" + +key == key && key >= 0) {
  1594. output.print(make_num(key));
  1595. } else {
  1596. var quote = self.start && self.start.quote;
  1597. if (self.private) {
  1598. output.print_name(key);
  1599. } else if (RESERVED_WORDS[key] ? !output.option("ie8") : is_identifier_string(key)) {
  1600. if (quote && output.option("keep_quoted_props")) {
  1601. output.print_string(key, quote);
  1602. } else {
  1603. output.print_name(key);
  1604. return key;
  1605. }
  1606. } else {
  1607. output.print_string(key, quote);
  1608. }
  1609. }
  1610. }
  1611. DEFPRINT(AST_ObjectKeyVal, function(output) {
  1612. var self = this;
  1613. print_property_key(self, output);
  1614. output.colon();
  1615. self.value.print(output);
  1616. });
  1617. DEFPRINT(AST_ObjectMethod, function(output) {
  1618. print_method(this, output);
  1619. });
  1620. function print_accessor(type) {
  1621. return function(output) {
  1622. var self = this;
  1623. if (self.static) {
  1624. output.print("static");
  1625. output.space();
  1626. }
  1627. output.print(type);
  1628. output.space();
  1629. print_property_key(self, output);
  1630. print_lambda(self.value, output);
  1631. };
  1632. }
  1633. DEFPRINT(AST_ObjectGetter, print_accessor("get"));
  1634. DEFPRINT(AST_ObjectSetter, print_accessor("set"));
  1635. function get_symbol_name(sym) {
  1636. var def = sym.definition();
  1637. return def && def.mangled_name || sym.name;
  1638. }
  1639. DEFPRINT(AST_Symbol, function(output) {
  1640. output.print_name(get_symbol_name(this));
  1641. });
  1642. DEFPRINT(AST_SymbolExport, function(output) {
  1643. var self = this;
  1644. var name = get_symbol_name(self);
  1645. output.print_name(name);
  1646. var alias = self.alias;
  1647. if (alias != name) {
  1648. output.space();
  1649. output.print("as");
  1650. output.space();
  1651. output.print_name(alias);
  1652. }
  1653. });
  1654. DEFPRINT(AST_SymbolImport, function(output) {
  1655. var self = this;
  1656. var name = get_symbol_name(self);
  1657. var key = self.key;
  1658. if (key && key != name) {
  1659. output.print_name(key);
  1660. output.space();
  1661. output.print("as");
  1662. output.space();
  1663. }
  1664. output.print_name(name);
  1665. });
  1666. DEFPRINT(AST_Hole, noop);
  1667. DEFPRINT(AST_Template, function(output) {
  1668. var self = this;
  1669. if (self.tag) self.tag.print(output);
  1670. output.print("`");
  1671. for (var i = 0; i < self.expressions.length; i++) {
  1672. output.print(self.strings[i]);
  1673. output.print("${");
  1674. self.expressions[i].print(output);
  1675. output.print("}");
  1676. }
  1677. output.print(self.strings[i]);
  1678. output.print("`");
  1679. });
  1680. DEFPRINT(AST_Constant, function(output) {
  1681. output.print("" + this.value);
  1682. });
  1683. DEFPRINT(AST_String, function(output) {
  1684. output.print_string(this.value, this.quote);
  1685. });
  1686. DEFPRINT(AST_Number, function(output) {
  1687. var start = this.start;
  1688. if (use_asm && start && start.raw != null) {
  1689. output.print(start.raw);
  1690. } else {
  1691. output.print(make_num(this.value));
  1692. }
  1693. });
  1694. DEFPRINT(AST_RegExp, function(output) {
  1695. var regexp = this.value;
  1696. var str = regexp.toString();
  1697. var end = str.lastIndexOf("/");
  1698. if (regexp.raw_source) {
  1699. str = "/" + regexp.raw_source + str.slice(end);
  1700. } else if (end == 1) {
  1701. str = "/(?:)" + str.slice(end);
  1702. } else if (str.indexOf("/", 1) < end) {
  1703. str = "/" + str.slice(1, end).replace(/\\\\|[^/]?\//g, function(match) {
  1704. return match[0] == "\\" ? match : match.slice(0, -1) + "\\/";
  1705. }) + str.slice(end);
  1706. }
  1707. output.print(output.to_utf8(str).replace(/\\(?:\0(?![0-9])|[^\0])/g, function(match) {
  1708. switch (match[1]) {
  1709. case "\n": return "\\n";
  1710. case "\r": return "\\r";
  1711. case "\t": return "\t";
  1712. case "\b": return "\b";
  1713. case "\f": return "\f";
  1714. case "\0": return "\0";
  1715. case "\x0B": return "\v";
  1716. case "\u2028": return "\\u2028";
  1717. case "\u2029": return "\\u2029";
  1718. default: return match;
  1719. }
  1720. }).replace(/[\n\r\u2028\u2029]/g, function(c) {
  1721. switch (c) {
  1722. case "\n": return "\\n";
  1723. case "\r": return "\\r";
  1724. case "\u2028": return "\\u2028";
  1725. case "\u2029": return "\\u2029";
  1726. }
  1727. }));
  1728. var p = output.parent();
  1729. if (p instanceof AST_Binary && /^in/.test(p.operator) && p.left === this)
  1730. output.print(" ");
  1731. });
  1732. function force_statement(stat, output) {
  1733. if (output.option("braces") && !(stat instanceof AST_Const || stat instanceof AST_Let)) {
  1734. make_block(stat, output);
  1735. } else if (stat instanceof AST_EmptyStatement) {
  1736. output.force_semicolon();
  1737. } else {
  1738. stat.print(output);
  1739. }
  1740. }
  1741. // self should be AST_New. decide if we want to show parens or not.
  1742. function need_constructor_parens(self, output) {
  1743. // Always print parentheses with arguments
  1744. if (self.args.length > 0) return true;
  1745. return output.option("beautify");
  1746. }
  1747. function best_of(a) {
  1748. var best = a[0], len = best.length;
  1749. for (var i = 1; i < a.length; ++i) {
  1750. if (a[i].length < len) {
  1751. best = a[i];
  1752. len = best.length;
  1753. }
  1754. }
  1755. return best;
  1756. }
  1757. function make_num(num) {
  1758. var str = num.toString(10).replace(/^0\./, ".").replace("e+", "e");
  1759. var candidates = [ str ];
  1760. if (Math.floor(num) === num) {
  1761. if (num < 0) {
  1762. candidates.push("-0x" + (-num).toString(16).toLowerCase());
  1763. } else {
  1764. candidates.push("0x" + num.toString(16).toLowerCase());
  1765. }
  1766. }
  1767. var match, len, digits;
  1768. if (match = /^\.0+/.exec(str)) {
  1769. len = match[0].length;
  1770. digits = str.slice(len);
  1771. candidates.push(digits + "e-" + (digits.length + len - 1));
  1772. } else if (match = /0+$/.exec(str)) {
  1773. len = match[0].length;
  1774. candidates.push(str.slice(0, -len) + "e" + len);
  1775. } else if (match = /^(\d)\.(\d+)e(-?\d+)$/.exec(str)) {
  1776. candidates.push(match[1] + match[2] + "e" + (match[3] - match[2].length));
  1777. }
  1778. return best_of(candidates);
  1779. }
  1780. function make_block(stmt, output) {
  1781. if (stmt instanceof AST_EmptyStatement) {
  1782. print_braced_empty(stmt, output);
  1783. } else if (stmt instanceof AST_BlockStatement) {
  1784. stmt.print(output);
  1785. } else output.with_block(function() {
  1786. output.indent();
  1787. stmt.print(output);
  1788. output.newline();
  1789. });
  1790. }
  1791. /* -----[ source map generators ]----- */
  1792. function DEFMAP(nodetype, generator) {
  1793. nodetype.forEach(function(nodetype) {
  1794. nodetype.DEFMETHOD("add_source_map", generator);
  1795. });
  1796. }
  1797. DEFMAP([
  1798. // We could easily add info for ALL nodes, but it seems to me that
  1799. // would be quite wasteful, hence this noop in the base class.
  1800. AST_Node,
  1801. // since the label symbol will mark it
  1802. AST_LabeledStatement,
  1803. ], noop);
  1804. // XXX: I'm not exactly sure if we need it for all of these nodes,
  1805. // or if we should add even more.
  1806. DEFMAP([
  1807. AST_Array,
  1808. AST_BlockStatement,
  1809. AST_Catch,
  1810. AST_Constant,
  1811. AST_Debugger,
  1812. AST_Definitions,
  1813. AST_Destructured,
  1814. AST_Finally,
  1815. AST_Jump,
  1816. AST_Lambda,
  1817. AST_New,
  1818. AST_Object,
  1819. AST_StatementWithBody,
  1820. AST_Symbol,
  1821. AST_Switch,
  1822. AST_SwitchBranch,
  1823. AST_Try,
  1824. ], function(output) {
  1825. output.add_mapping(this.start);
  1826. });
  1827. DEFMAP([ AST_DestructuredKeyVal, AST_ObjectProperty ], function(output) {
  1828. if (typeof this.key == "string") output.add_mapping(this.start, this.key);
  1829. });
  1830. })();