output.js 64 KB

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