output.js 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513
  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. braces : false,
  45. comments : 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. webkit : false,
  60. width : 80,
  61. wrap_iife : false,
  62. }, true);
  63. // Convert comment option to RegExp if neccessary and set up comments filter
  64. var comment_filter = return_false; // Default case, throw all comments away
  65. if (options.comments) {
  66. var comments = options.comments;
  67. if (typeof options.comments === "string" && /^\/.*\/[a-zA-Z]*$/.test(options.comments)) {
  68. var regex_pos = options.comments.lastIndexOf("/");
  69. comments = new RegExp(
  70. options.comments.substr(1, regex_pos - 1),
  71. options.comments.substr(regex_pos + 1)
  72. );
  73. }
  74. if (comments instanceof RegExp) {
  75. comment_filter = function(comment) {
  76. return comment.type != "comment5" && comments.test(comment.value);
  77. };
  78. }
  79. else if (typeof comments === "function") {
  80. comment_filter = function(comment) {
  81. return comment.type != "comment5" && comments(this, comment);
  82. };
  83. }
  84. else if (comments === "some") {
  85. comment_filter = is_some_comments;
  86. } else { // NOTE includes "all" option
  87. comment_filter = return_true;
  88. }
  89. }
  90. var indentation = 0;
  91. var current_col = 0;
  92. var current_line = 1;
  93. var current_pos = 0;
  94. var OUTPUT = "";
  95. var to_utf8 = options.ascii_only ? function(str, identifier) {
  96. return str.replace(/[\u0000-\u001f\u007f-\uffff]/g, function(ch) {
  97. var code = ch.charCodeAt(0).toString(16);
  98. if (code.length <= 2 && !identifier) {
  99. while (code.length < 2) code = "0" + code;
  100. return "\\x" + code;
  101. } else {
  102. while (code.length < 4) code = "0" + code;
  103. return "\\u" + code;
  104. }
  105. });
  106. } : function(str) {
  107. var s = "";
  108. for (var i = 0, len = str.length; i < len; i++) {
  109. if (is_surrogate_pair_head(str[i]) && !is_surrogate_pair_tail(str[i + 1])
  110. || is_surrogate_pair_tail(str[i]) && !is_surrogate_pair_head(str[i - 1])) {
  111. s += "\\u" + str.charCodeAt(i).toString(16);
  112. } else {
  113. s += str[i];
  114. }
  115. }
  116. return s;
  117. };
  118. function make_string(str, quote) {
  119. var dq = 0, sq = 0;
  120. str = str.replace(/[\\\b\f\n\r\v\t\x22\x27\u2028\u2029\0\ufeff]/g,
  121. function(s, i) {
  122. switch (s) {
  123. case '"': ++dq; return '"';
  124. case "'": ++sq; return "'";
  125. case "\\": return "\\\\";
  126. case "\n": return "\\n";
  127. case "\r": return "\\r";
  128. case "\t": return "\\t";
  129. case "\b": return "\\b";
  130. case "\f": return "\\f";
  131. case "\x0B": return options.ie8 ? "\\x0B" : "\\v";
  132. case "\u2028": return "\\u2028";
  133. case "\u2029": return "\\u2029";
  134. case "\ufeff": return "\\ufeff";
  135. case "\0":
  136. return /[0-9]/.test(str.charAt(i+1)) ? "\\x00" : "\\0";
  137. }
  138. return s;
  139. });
  140. function quote_single() {
  141. return "'" + str.replace(/\x27/g, "\\'") + "'";
  142. }
  143. function quote_double() {
  144. return '"' + str.replace(/\x22/g, '\\"') + '"';
  145. }
  146. str = to_utf8(str);
  147. switch (options.quote_style) {
  148. case 1:
  149. return quote_single();
  150. case 2:
  151. return quote_double();
  152. case 3:
  153. return quote == "'" ? quote_single() : quote_double();
  154. default:
  155. return dq > sq ? quote_single() : quote_double();
  156. }
  157. }
  158. function encode_string(str, quote) {
  159. var ret = make_string(str, quote);
  160. if (options.inline_script) {
  161. ret = ret.replace(/<\x2f(script)([>\/\t\n\f\r ])/gi, "<\\/$1$2");
  162. ret = ret.replace(/\x3c!--/g, "\\x3c!--");
  163. ret = ret.replace(/--\x3e/g, "--\\x3e");
  164. }
  165. return ret;
  166. }
  167. function make_name(name) {
  168. name = name.toString();
  169. name = to_utf8(name, true);
  170. return name;
  171. }
  172. function make_indent(back) {
  173. return repeat_string(" ", options.indent_start + indentation - back * options.indent_level);
  174. }
  175. /* -----[ beautification/minification ]----- */
  176. var has_parens = false;
  177. var line_end = 0;
  178. var line_fixed = true;
  179. var might_need_space = false;
  180. var might_need_semicolon = false;
  181. var need_newline_indented = false;
  182. var need_space = false;
  183. var newline_insert = -1;
  184. var last = "";
  185. var mapping_token, mapping_name, mappings = options.source_map && [];
  186. var adjust_mappings = mappings ? function(line, col) {
  187. mappings.forEach(function(mapping) {
  188. mapping.line += line;
  189. mapping.col += col;
  190. });
  191. } : noop;
  192. var flush_mappings = mappings ? function() {
  193. mappings.forEach(function(mapping) {
  194. try {
  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. } catch(ex) {
  202. AST_Node.warn("Couldn't figure out mapping for {file}:{line},{col} → {cline},{ccol} [{name}]", {
  203. file: mapping.token.file,
  204. line: mapping.token.line,
  205. col: mapping.token.col,
  206. cline: mapping.line,
  207. ccol: mapping.col,
  208. name: mapping.name || ""
  209. })
  210. }
  211. });
  212. mappings = [];
  213. } : noop;
  214. function insert_newlines(count) {
  215. var index = OUTPUT.lastIndexOf("\n");
  216. if (line_end < index) line_end = index;
  217. var left = OUTPUT.slice(0, line_end);
  218. var right = OUTPUT.slice(line_end);
  219. adjust_mappings(count, right.length - current_col);
  220. current_line += count;
  221. current_pos += count;
  222. current_col = right.length;
  223. OUTPUT = left;
  224. while (count--) OUTPUT += "\n";
  225. OUTPUT += right;
  226. }
  227. var fix_line = options.max_line_len ? function() {
  228. if (line_fixed) {
  229. if (current_col > options.max_line_len) {
  230. AST_Node.warn("Output exceeds {max_line_len} characters", options);
  231. }
  232. return;
  233. }
  234. if (current_col > options.max_line_len) insert_newlines(1);
  235. line_fixed = true;
  236. flush_mappings();
  237. } : noop;
  238. var requireSemicolonChars = makePredicate("( [ + * / - , .");
  239. function print(str) {
  240. str = String(str);
  241. var ch = str.charAt(0);
  242. if (need_newline_indented && ch) {
  243. need_newline_indented = false;
  244. if (ch != "\n") {
  245. print("\n");
  246. indent();
  247. }
  248. }
  249. if (need_space && ch) {
  250. need_space = false;
  251. if (!/[\s;})]/.test(ch)) {
  252. space();
  253. }
  254. }
  255. newline_insert = -1;
  256. var prev = last.charAt(last.length - 1);
  257. if (might_need_semicolon) {
  258. might_need_semicolon = false;
  259. if (prev == ":" && ch == "}" || (!ch || ";}".indexOf(ch) < 0) && prev != ";") {
  260. if (options.semicolons || requireSemicolonChars[ch]) {
  261. OUTPUT += ";";
  262. current_col++;
  263. current_pos++;
  264. } else {
  265. fix_line();
  266. OUTPUT += "\n";
  267. current_pos++;
  268. current_line++;
  269. current_col = 0;
  270. if (/^\s+$/.test(str)) {
  271. // reset the semicolon flag, since we didn't print one
  272. // now and might still have to later
  273. might_need_semicolon = true;
  274. }
  275. }
  276. if (!options.beautify)
  277. might_need_space = false;
  278. }
  279. }
  280. if (might_need_space) {
  281. if ((is_identifier_char(prev)
  282. && (is_identifier_char(ch) || ch == "\\"))
  283. || (ch == "/" && ch == prev)
  284. || ((ch == "+" || ch == "-") && ch == last))
  285. {
  286. OUTPUT += " ";
  287. current_col++;
  288. current_pos++;
  289. }
  290. might_need_space = false;
  291. }
  292. if (mapping_token) {
  293. mappings.push({
  294. token: mapping_token,
  295. name: mapping_name,
  296. line: current_line,
  297. col: current_col
  298. });
  299. mapping_token = false;
  300. if (line_fixed) flush_mappings();
  301. }
  302. OUTPUT += str;
  303. has_parens = str[str.length - 1] == "(";
  304. current_pos += str.length;
  305. var a = str.split(/\r?\n/), n = a.length - 1;
  306. current_line += n;
  307. current_col += a[0].length;
  308. if (n > 0) {
  309. fix_line();
  310. current_col = a[n].length;
  311. }
  312. last = str;
  313. }
  314. var space = options.beautify ? function() {
  315. print(" ");
  316. } : function() {
  317. might_need_space = true;
  318. };
  319. var indent = options.beautify ? function(half) {
  320. if (options.beautify) {
  321. print(make_indent(half ? 0.5 : 0));
  322. }
  323. } : noop;
  324. var with_indent = options.beautify ? function(col, cont) {
  325. if (col === true) col = next_indent();
  326. var save_indentation = indentation;
  327. indentation = col;
  328. var ret = cont();
  329. indentation = save_indentation;
  330. return ret;
  331. } : function(col, cont) { return cont() };
  332. var may_add_newline = options.max_line_len || options.preserve_line ? function() {
  333. fix_line();
  334. line_end = OUTPUT.length;
  335. line_fixed = false;
  336. } : noop;
  337. var newline = options.beautify ? function() {
  338. if (newline_insert < 0) return print("\n");
  339. if (OUTPUT[newline_insert] != "\n") {
  340. OUTPUT = OUTPUT.slice(0, newline_insert) + "\n" + OUTPUT.slice(newline_insert);
  341. current_pos++;
  342. current_line++;
  343. }
  344. newline_insert++;
  345. } : may_add_newline;
  346. var semicolon = options.beautify ? function() {
  347. print(";");
  348. } : function() {
  349. might_need_semicolon = true;
  350. };
  351. function force_semicolon() {
  352. might_need_semicolon = false;
  353. print(";");
  354. }
  355. function next_indent() {
  356. return indentation + options.indent_level;
  357. }
  358. function with_block(cont) {
  359. var ret;
  360. print("{");
  361. newline();
  362. with_indent(next_indent(), function() {
  363. ret = cont();
  364. });
  365. indent();
  366. print("}");
  367. return ret;
  368. }
  369. function with_parens(cont) {
  370. print("(");
  371. may_add_newline();
  372. //XXX: still nice to have that for argument lists
  373. //var ret = with_indent(current_col, cont);
  374. var ret = cont();
  375. may_add_newline();
  376. print(")");
  377. return ret;
  378. }
  379. function with_square(cont) {
  380. print("[");
  381. may_add_newline();
  382. //var ret = with_indent(current_col, cont);
  383. var ret = cont();
  384. may_add_newline();
  385. print("]");
  386. return ret;
  387. }
  388. function comma() {
  389. may_add_newline();
  390. print(",");
  391. may_add_newline();
  392. space();
  393. }
  394. function colon() {
  395. print(":");
  396. space();
  397. }
  398. var add_mapping = mappings ? function(token, name) {
  399. mapping_token = token;
  400. mapping_name = name;
  401. } : noop;
  402. function get() {
  403. if (!line_fixed) fix_line();
  404. return OUTPUT;
  405. }
  406. function has_nlb() {
  407. var index = OUTPUT.lastIndexOf("\n");
  408. return /^ *$/.test(OUTPUT.slice(index + 1));
  409. }
  410. function prepend_comments(node) {
  411. var self = this;
  412. var start = node.start;
  413. if (!start) return;
  414. if (start.comments_before && start.comments_before._dumped === self) return;
  415. var comments = start.comments_before;
  416. if (!comments) {
  417. comments = start.comments_before = [];
  418. }
  419. comments._dumped = self;
  420. if (node instanceof AST_Exit && node.value) {
  421. var tw = new TreeWalker(function(node) {
  422. var parent = tw.parent();
  423. if (parent instanceof AST_Exit
  424. || parent instanceof AST_Binary && parent.left === node
  425. || parent.TYPE == "Call" && parent.expression === node
  426. || parent instanceof AST_Conditional && parent.condition === node
  427. || parent instanceof AST_Dot && parent.expression === node
  428. || parent instanceof AST_Sequence && parent.expressions[0] === node
  429. || parent instanceof AST_Sub && parent.expression === node
  430. || parent instanceof AST_UnaryPostfix) {
  431. var text = node.start.comments_before;
  432. if (text && text._dumped !== self) {
  433. text._dumped = self;
  434. comments = comments.concat(text);
  435. }
  436. } else {
  437. return true;
  438. }
  439. });
  440. tw.push(node);
  441. node.value.walk(tw);
  442. }
  443. if (current_pos == 0) {
  444. if (comments.length > 0 && options.shebang && comments[0].type == "comment5") {
  445. print("#!" + comments.shift().value + "\n");
  446. indent();
  447. }
  448. var preamble = options.preamble;
  449. if (preamble) {
  450. print(preamble.replace(/\r\n?|[\n\u2028\u2029]|\s*$/g, "\n"));
  451. }
  452. }
  453. comments = comments.filter(comment_filter, node);
  454. if (comments.length == 0) return;
  455. var last_nlb = has_nlb();
  456. comments.forEach(function(c, i) {
  457. if (!last_nlb) {
  458. if (c.nlb) {
  459. print("\n");
  460. indent();
  461. last_nlb = true;
  462. } else if (i > 0) {
  463. space();
  464. }
  465. }
  466. if (/comment[134]/.test(c.type)) {
  467. print("//" + c.value.replace(/[@#]__PURE__/g, ' ') + "\n");
  468. indent();
  469. last_nlb = true;
  470. } else if (c.type == "comment2") {
  471. print("/*" + c.value.replace(/[@#]__PURE__/g, ' ') + "*/");
  472. last_nlb = false;
  473. }
  474. });
  475. if (!last_nlb) {
  476. if (start.nlb) {
  477. print("\n");
  478. indent();
  479. } else {
  480. space();
  481. }
  482. }
  483. }
  484. function append_comments(node, tail) {
  485. var self = this;
  486. var token = node.end;
  487. if (!token) return;
  488. var comments = token[tail ? "comments_before" : "comments_after"];
  489. if (!comments || comments._dumped === self) return;
  490. if (!(node instanceof AST_Statement || all(comments, function(c) {
  491. return !/comment[134]/.test(c.type);
  492. }))) return;
  493. comments._dumped = self;
  494. var insert = OUTPUT.length;
  495. comments.filter(comment_filter, node).forEach(function(c, i) {
  496. need_space = false;
  497. if (need_newline_indented) {
  498. print("\n");
  499. indent();
  500. need_newline_indented = false;
  501. } else if (c.nlb && (i > 0 || !has_nlb())) {
  502. print("\n");
  503. indent();
  504. } else if (i > 0 || !tail) {
  505. space();
  506. }
  507. if (/comment[134]/.test(c.type)) {
  508. print("//" + c.value.replace(/[@#]__PURE__/g, ' '));
  509. need_newline_indented = true;
  510. } else if (c.type == "comment2") {
  511. print("/*" + c.value.replace(/[@#]__PURE__/g, ' ') + "*/");
  512. need_space = true;
  513. }
  514. });
  515. if (OUTPUT.length > insert) newline_insert = insert;
  516. }
  517. var stack = [];
  518. return {
  519. get : get,
  520. toString : get,
  521. indent : indent,
  522. indentation : function() { return indentation },
  523. current_width : function() { return current_col - indentation },
  524. should_break : function() { return options.width && this.current_width() >= options.width },
  525. has_parens : function() { return has_parens },
  526. newline : newline,
  527. print : print,
  528. space : space,
  529. comma : comma,
  530. colon : colon,
  531. last : function() { return last },
  532. semicolon : semicolon,
  533. force_semicolon : force_semicolon,
  534. to_utf8 : to_utf8,
  535. print_name : function(name) { print(make_name(name)) },
  536. print_string : function(str, quote, escape_directive) {
  537. var encoded = encode_string(str, quote);
  538. if (escape_directive === true && encoded.indexOf("\\") === -1) {
  539. // Insert semicolons to break directive prologue
  540. if (!EXPECT_DIRECTIVE.test(OUTPUT)) {
  541. force_semicolon();
  542. }
  543. force_semicolon();
  544. }
  545. print(encoded);
  546. },
  547. encode_string : encode_string,
  548. next_indent : next_indent,
  549. with_indent : with_indent,
  550. with_block : with_block,
  551. with_parens : with_parens,
  552. with_square : with_square,
  553. add_mapping : add_mapping,
  554. option : function(opt) { return options[opt] },
  555. prepend_comments: readonly ? noop : prepend_comments,
  556. append_comments : readonly || comment_filter === return_false ? noop : append_comments,
  557. line : function() { return current_line },
  558. col : function() { return current_col },
  559. pos : function() { return current_pos },
  560. push_node : function(node) { stack.push(node) },
  561. pop_node : options.preserve_line ? function() {
  562. var node = stack.pop();
  563. if (node.start && node.start.line > current_line) {
  564. insert_newlines(node.start.line - current_line);
  565. }
  566. } : function() {
  567. stack.pop();
  568. },
  569. parent : function(n) {
  570. return stack[stack.length - 2 - (n || 0)];
  571. }
  572. };
  573. }
  574. /* -----[ code generators ]----- */
  575. (function() {
  576. /* -----[ utils ]----- */
  577. function DEFPRINT(nodetype, generator) {
  578. nodetype.DEFMETHOD("_codegen", generator);
  579. }
  580. var in_directive = false;
  581. var active_scope = null;
  582. var use_asm = null;
  583. AST_Node.DEFMETHOD("print", function(stream, force_parens) {
  584. var self = this, generator = self._codegen;
  585. if (self instanceof AST_Scope) {
  586. active_scope = self;
  587. }
  588. else if (!use_asm && self instanceof AST_Directive && self.value == "use asm") {
  589. use_asm = active_scope;
  590. }
  591. function doit() {
  592. stream.prepend_comments(self);
  593. self.add_source_map(stream);
  594. generator(self, stream);
  595. stream.append_comments(self);
  596. }
  597. stream.push_node(self);
  598. if (force_parens || self.needs_parens(stream)) {
  599. stream.with_parens(doit);
  600. } else {
  601. doit();
  602. }
  603. stream.pop_node();
  604. if (self === use_asm) {
  605. use_asm = null;
  606. }
  607. });
  608. AST_Node.DEFMETHOD("_print", AST_Node.prototype.print);
  609. AST_Node.DEFMETHOD("print_to_string", function(options) {
  610. var s = OutputStream(options);
  611. this.print(s);
  612. return s.get();
  613. });
  614. /* -----[ PARENTHESES ]----- */
  615. function PARENS(nodetype, func) {
  616. if (Array.isArray(nodetype)) {
  617. nodetype.forEach(function(nodetype) {
  618. PARENS(nodetype, func);
  619. });
  620. } else {
  621. nodetype.DEFMETHOD("needs_parens", func);
  622. }
  623. }
  624. PARENS(AST_Node, return_false);
  625. // a function expression needs parens around it when it's provably
  626. // the first token to appear in a statement.
  627. PARENS(AST_Function, function(output) {
  628. if (!output.has_parens() && first_in_statement(output)) return true;
  629. if (output.option('webkit')) {
  630. var p = output.parent();
  631. if (p instanceof AST_PropAccess && p.expression === this) return true;
  632. }
  633. if (output.option('wrap_iife')) {
  634. var p = output.parent();
  635. if (p instanceof AST_Call && p.expression === this) return true;
  636. }
  637. });
  638. // same goes for an object literal, because otherwise it would be
  639. // interpreted as a block of code.
  640. PARENS(AST_Object, function(output) {
  641. return !output.has_parens() && first_in_statement(output);
  642. });
  643. PARENS(AST_Unary, function(output) {
  644. var p = output.parent();
  645. return p instanceof AST_PropAccess && p.expression === this
  646. || p instanceof AST_Call && p.expression === this;
  647. });
  648. PARENS(AST_Sequence, function(output) {
  649. var p = output.parent();
  650. return p instanceof AST_Call // (foo, bar)() or foo(1, (2, 3), 4)
  651. || p instanceof AST_Unary // !(foo, bar, baz)
  652. || p instanceof AST_Binary // 1 + (2, 3) + 4 ==> 8
  653. || p instanceof AST_VarDef // var a = (1, 2), b = a + a; ==> b == 4
  654. || p instanceof AST_PropAccess // (1, {foo:2}).foo or (1, {foo:2})["foo"] ==> 2
  655. || p instanceof AST_Array // [ 1, (2, 3), 4 ] ==> [ 1, 3, 4 ]
  656. || p instanceof AST_ObjectProperty // { foo: (1, 2) }.foo ==> 2
  657. || p instanceof AST_Conditional /* (false, true) ? (a = 10, b = 20) : (c = 30)
  658. * ==> 20 (side effect, set a := 10 and b := 20) */
  659. ;
  660. });
  661. PARENS(AST_Binary, function(output) {
  662. var p = output.parent();
  663. // (foo && bar)()
  664. if (p instanceof AST_Call && p.expression === this)
  665. return true;
  666. // typeof (foo && bar)
  667. if (p instanceof AST_Unary)
  668. return true;
  669. // (foo && bar)["prop"], (foo && bar).prop
  670. if (p instanceof AST_PropAccess && p.expression === this)
  671. return true;
  672. // this deals with precedence: 3 * (2 + 1)
  673. if (p instanceof AST_Binary) {
  674. var po = p.operator, pp = PRECEDENCE[po];
  675. var so = this.operator, sp = PRECEDENCE[so];
  676. if (pp > sp
  677. || (pp == sp
  678. && this === p.right)) {
  679. return true;
  680. }
  681. }
  682. });
  683. PARENS(AST_PropAccess, function(output) {
  684. var p = output.parent();
  685. if (p instanceof AST_New && p.expression === this) {
  686. // i.e. new (foo.bar().baz)
  687. //
  688. // if there's one call into this subtree, then we need
  689. // parens around it too, otherwise the call will be
  690. // interpreted as passing the arguments to the upper New
  691. // expression.
  692. var parens = false;
  693. this.walk(new TreeWalker(function(node) {
  694. if (parens || node instanceof AST_Scope) return true;
  695. if (node instanceof AST_Call) {
  696. parens = true;
  697. return true;
  698. }
  699. }));
  700. return parens;
  701. }
  702. });
  703. PARENS(AST_Call, function(output) {
  704. var p = output.parent();
  705. if (p instanceof AST_New && p.expression === this) return true;
  706. // https://bugs.webkit.org/show_bug.cgi?id=123506
  707. if (output.option('webkit')) {
  708. var g = output.parent(1);
  709. return this.expression instanceof AST_Function
  710. && p instanceof AST_PropAccess
  711. && p.expression === this
  712. && g instanceof AST_Assign
  713. && g.left === p;
  714. }
  715. });
  716. PARENS(AST_New, function(output) {
  717. var p = output.parent();
  718. if (!need_constructor_parens(this, output)
  719. && (p instanceof AST_PropAccess // (new Date).getTime(), (new Date)["getTime"]()
  720. || p instanceof AST_Call && p.expression === this)) // (new foo)(bar)
  721. return true;
  722. });
  723. PARENS(AST_Number, function(output) {
  724. var p = output.parent();
  725. if (p instanceof AST_PropAccess && p.expression === this) {
  726. var value = this.getValue();
  727. if (value < 0 || /^0/.test(make_num(value))) {
  728. return true;
  729. }
  730. }
  731. });
  732. PARENS([ AST_Assign, AST_Conditional ], function(output) {
  733. var p = output.parent();
  734. // !(a = false) → true
  735. if (p instanceof AST_Unary)
  736. return true;
  737. // 1 + (a = 2) + 3 → 6, side effect setting a = 2
  738. if (p instanceof AST_Binary && !(p instanceof AST_Assign))
  739. return true;
  740. // (a = func)() —or— new (a = Object)()
  741. if (p instanceof AST_Call && p.expression === this)
  742. return true;
  743. // (a = foo) ? bar : baz
  744. if (p instanceof AST_Conditional && p.condition === this)
  745. return true;
  746. // (a = foo)["prop"] —or— (a = foo).prop
  747. if (p instanceof AST_PropAccess && p.expression === this)
  748. return true;
  749. });
  750. /* -----[ PRINTERS ]----- */
  751. DEFPRINT(AST_Directive, function(self, output) {
  752. output.print_string(self.value, self.quote);
  753. output.semicolon();
  754. });
  755. DEFPRINT(AST_Debugger, function(self, output) {
  756. output.print("debugger");
  757. output.semicolon();
  758. });
  759. /* -----[ statements ]----- */
  760. function display_body(body, is_toplevel, output, allow_directives) {
  761. var last = body.length - 1;
  762. in_directive = allow_directives;
  763. body.forEach(function(stmt, i) {
  764. if (in_directive === true && !(stmt instanceof AST_Directive ||
  765. stmt instanceof AST_EmptyStatement ||
  766. (stmt instanceof AST_SimpleStatement && stmt.body instanceof AST_String)
  767. )) {
  768. in_directive = false;
  769. }
  770. if (!(stmt instanceof AST_EmptyStatement)) {
  771. output.indent();
  772. stmt.print(output);
  773. if (!(i == last && is_toplevel)) {
  774. output.newline();
  775. if (is_toplevel) output.newline();
  776. }
  777. }
  778. if (in_directive === true &&
  779. stmt instanceof AST_SimpleStatement &&
  780. stmt.body instanceof AST_String
  781. ) {
  782. in_directive = false;
  783. }
  784. });
  785. in_directive = false;
  786. }
  787. AST_StatementWithBody.DEFMETHOD("_do_print_body", function(output) {
  788. force_statement(this.body, output);
  789. });
  790. DEFPRINT(AST_Statement, function(self, output) {
  791. self.body.print(output);
  792. output.semicolon();
  793. });
  794. DEFPRINT(AST_Toplevel, function(self, output) {
  795. display_body(self.body, true, output, true);
  796. output.print("");
  797. });
  798. DEFPRINT(AST_LabeledStatement, function(self, output) {
  799. self.label.print(output);
  800. output.colon();
  801. self.body.print(output);
  802. });
  803. DEFPRINT(AST_SimpleStatement, function(self, output) {
  804. self.body.print(output);
  805. output.semicolon();
  806. });
  807. function print_braced_empty(self, output) {
  808. output.print("{");
  809. output.with_indent(output.next_indent(), function() {
  810. output.append_comments(self, true);
  811. });
  812. output.print("}");
  813. }
  814. function print_braced(self, output, allow_directives) {
  815. if (self.body.length > 0) {
  816. output.with_block(function() {
  817. display_body(self.body, false, output, allow_directives);
  818. });
  819. } else print_braced_empty(self, output);
  820. }
  821. DEFPRINT(AST_BlockStatement, function(self, output) {
  822. print_braced(self, output);
  823. });
  824. DEFPRINT(AST_EmptyStatement, function(self, output) {
  825. output.semicolon();
  826. });
  827. DEFPRINT(AST_Do, function(self, output) {
  828. output.print("do");
  829. output.space();
  830. make_block(self.body, output);
  831. output.space();
  832. output.print("while");
  833. output.space();
  834. output.with_parens(function() {
  835. self.condition.print(output);
  836. });
  837. output.semicolon();
  838. });
  839. DEFPRINT(AST_While, function(self, output) {
  840. output.print("while");
  841. output.space();
  842. output.with_parens(function() {
  843. self.condition.print(output);
  844. });
  845. output.space();
  846. self._do_print_body(output);
  847. });
  848. DEFPRINT(AST_For, function(self, output) {
  849. output.print("for");
  850. output.space();
  851. output.with_parens(function() {
  852. if (self.init) {
  853. if (self.init instanceof AST_Definitions) {
  854. self.init.print(output);
  855. } else {
  856. parenthesize_for_noin(self.init, output, true);
  857. }
  858. output.print(";");
  859. output.space();
  860. } else {
  861. output.print(";");
  862. }
  863. if (self.condition) {
  864. self.condition.print(output);
  865. output.print(";");
  866. output.space();
  867. } else {
  868. output.print(";");
  869. }
  870. if (self.step) {
  871. self.step.print(output);
  872. }
  873. });
  874. output.space();
  875. self._do_print_body(output);
  876. });
  877. DEFPRINT(AST_ForIn, function(self, output) {
  878. output.print("for");
  879. output.space();
  880. output.with_parens(function() {
  881. self.init.print(output);
  882. output.space();
  883. output.print("in");
  884. output.space();
  885. self.object.print(output);
  886. });
  887. output.space();
  888. self._do_print_body(output);
  889. });
  890. DEFPRINT(AST_With, function(self, output) {
  891. output.print("with");
  892. output.space();
  893. output.with_parens(function() {
  894. self.expression.print(output);
  895. });
  896. output.space();
  897. self._do_print_body(output);
  898. });
  899. /* -----[ functions ]----- */
  900. AST_Lambda.DEFMETHOD("_do_print", function(output, nokeyword) {
  901. var self = this;
  902. if (!nokeyword) {
  903. output.print("function");
  904. }
  905. if (self.name) {
  906. output.space();
  907. self.name.print(output);
  908. }
  909. output.with_parens(function() {
  910. self.argnames.forEach(function(arg, i) {
  911. if (i) output.comma();
  912. arg.print(output);
  913. });
  914. });
  915. output.space();
  916. print_braced(self, output, true);
  917. });
  918. DEFPRINT(AST_Lambda, function(self, output) {
  919. self._do_print(output);
  920. });
  921. /* -----[ jumps ]----- */
  922. function print_jump(output, kind, target) {
  923. output.print(kind);
  924. if (target) {
  925. output.space();
  926. target.print(output);
  927. }
  928. output.semicolon();
  929. }
  930. DEFPRINT(AST_Return, function(self, output) {
  931. print_jump(output, "return", self.value);
  932. });
  933. DEFPRINT(AST_Throw, function(self, output) {
  934. print_jump(output, "throw", self.value);
  935. });
  936. DEFPRINT(AST_Break, function(self, output) {
  937. print_jump(output, "break", self.label);
  938. });
  939. DEFPRINT(AST_Continue, function(self, output) {
  940. print_jump(output, "continue", self.label);
  941. });
  942. /* -----[ if ]----- */
  943. function make_then(self, output) {
  944. var b = self.body;
  945. if (output.option("braces")
  946. || output.option("ie8") && b instanceof AST_Do)
  947. return make_block(b, output);
  948. // The squeezer replaces "block"-s that contain only a single
  949. // statement with the statement itself; technically, the AST
  950. // is correct, but this can create problems when we output an
  951. // IF having an ELSE clause where the THEN clause ends in an
  952. // IF *without* an ELSE block (then the outer ELSE would refer
  953. // to the inner IF). This function checks for this case and
  954. // adds the block braces if needed.
  955. if (!b) return output.force_semicolon();
  956. while (true) {
  957. if (b instanceof AST_If) {
  958. if (!b.alternative) {
  959. make_block(self.body, output);
  960. return;
  961. }
  962. b = b.alternative;
  963. }
  964. else if (b instanceof AST_StatementWithBody) {
  965. b = b.body;
  966. }
  967. else break;
  968. }
  969. force_statement(self.body, output);
  970. }
  971. DEFPRINT(AST_If, function(self, output) {
  972. output.print("if");
  973. output.space();
  974. output.with_parens(function() {
  975. self.condition.print(output);
  976. });
  977. output.space();
  978. if (self.alternative) {
  979. make_then(self, output);
  980. output.space();
  981. output.print("else");
  982. output.space();
  983. if (self.alternative instanceof AST_If)
  984. self.alternative.print(output);
  985. else
  986. force_statement(self.alternative, output);
  987. } else {
  988. self._do_print_body(output);
  989. }
  990. });
  991. /* -----[ switch ]----- */
  992. DEFPRINT(AST_Switch, function(self, output) {
  993. output.print("switch");
  994. output.space();
  995. output.with_parens(function() {
  996. self.expression.print(output);
  997. });
  998. output.space();
  999. var last = self.body.length - 1;
  1000. if (last < 0) print_braced_empty(self, output);
  1001. else output.with_block(function() {
  1002. self.body.forEach(function(branch, i) {
  1003. output.indent(true);
  1004. branch.print(output);
  1005. if (i < last && branch.body.length > 0)
  1006. output.newline();
  1007. });
  1008. });
  1009. });
  1010. AST_SwitchBranch.DEFMETHOD("_do_print_body", function(output) {
  1011. output.newline();
  1012. this.body.forEach(function(stmt) {
  1013. output.indent();
  1014. stmt.print(output);
  1015. output.newline();
  1016. });
  1017. });
  1018. DEFPRINT(AST_Default, function(self, output) {
  1019. output.print("default:");
  1020. self._do_print_body(output);
  1021. });
  1022. DEFPRINT(AST_Case, function(self, output) {
  1023. output.print("case");
  1024. output.space();
  1025. self.expression.print(output);
  1026. output.print(":");
  1027. self._do_print_body(output);
  1028. });
  1029. /* -----[ exceptions ]----- */
  1030. DEFPRINT(AST_Try, function(self, output) {
  1031. output.print("try");
  1032. output.space();
  1033. print_braced(self, output);
  1034. if (self.bcatch) {
  1035. output.space();
  1036. self.bcatch.print(output);
  1037. }
  1038. if (self.bfinally) {
  1039. output.space();
  1040. self.bfinally.print(output);
  1041. }
  1042. });
  1043. DEFPRINT(AST_Catch, function(self, output) {
  1044. output.print("catch");
  1045. output.space();
  1046. output.with_parens(function() {
  1047. self.argname.print(output);
  1048. });
  1049. output.space();
  1050. print_braced(self, output);
  1051. });
  1052. DEFPRINT(AST_Finally, function(self, output) {
  1053. output.print("finally");
  1054. output.space();
  1055. print_braced(self, output);
  1056. });
  1057. DEFPRINT(AST_Var, function(self, output) {
  1058. output.print("var");
  1059. output.space();
  1060. self.definitions.forEach(function(def, i) {
  1061. if (i) output.comma();
  1062. def.print(output);
  1063. });
  1064. var p = output.parent();
  1065. if (p && p.init !== self || !(p instanceof AST_For || p instanceof AST_ForIn)) output.semicolon();
  1066. });
  1067. function parenthesize_for_noin(node, output, noin) {
  1068. var parens = false;
  1069. // need to take some precautions here:
  1070. // https://github.com/mishoo/UglifyJS2/issues/60
  1071. if (noin) node.walk(new TreeWalker(function(node) {
  1072. if (parens || node instanceof AST_Scope) return true;
  1073. if (node instanceof AST_Binary && node.operator == "in") {
  1074. parens = true;
  1075. return true;
  1076. }
  1077. }));
  1078. node.print(output, parens);
  1079. }
  1080. DEFPRINT(AST_VarDef, function(self, output) {
  1081. self.name.print(output);
  1082. if (self.value) {
  1083. output.space();
  1084. output.print("=");
  1085. output.space();
  1086. var p = output.parent(1);
  1087. var noin = p instanceof AST_For || p instanceof AST_ForIn;
  1088. parenthesize_for_noin(self.value, output, noin);
  1089. }
  1090. });
  1091. /* -----[ other expressions ]----- */
  1092. DEFPRINT(AST_Call, function(self, output) {
  1093. self.expression.print(output);
  1094. if (self instanceof AST_New && !need_constructor_parens(self, output))
  1095. return;
  1096. if (self.expression instanceof AST_Call || self.expression instanceof AST_Lambda) {
  1097. output.add_mapping(self.start);
  1098. }
  1099. output.with_parens(function() {
  1100. self.args.forEach(function(expr, i) {
  1101. if (i) output.comma();
  1102. expr.print(output);
  1103. });
  1104. });
  1105. });
  1106. DEFPRINT(AST_New, function(self, output) {
  1107. output.print("new");
  1108. output.space();
  1109. AST_Call.prototype._codegen(self, output);
  1110. });
  1111. DEFPRINT(AST_Sequence, function(self, output) {
  1112. self.expressions.forEach(function(node, index) {
  1113. if (index > 0) {
  1114. output.comma();
  1115. if (output.should_break()) {
  1116. output.newline();
  1117. output.indent();
  1118. }
  1119. }
  1120. node.print(output);
  1121. });
  1122. });
  1123. DEFPRINT(AST_Dot, function(self, output) {
  1124. var expr = self.expression;
  1125. expr.print(output);
  1126. var prop = self.property;
  1127. if (output.option("ie8") && RESERVED_WORDS[prop]) {
  1128. output.print("[");
  1129. output.add_mapping(self.end);
  1130. output.print_string(prop);
  1131. output.print("]");
  1132. } else {
  1133. if (expr instanceof AST_Number && expr.getValue() >= 0) {
  1134. if (!/[xa-f.)]/i.test(output.last())) {
  1135. output.print(".");
  1136. }
  1137. }
  1138. output.print(".");
  1139. // the name after dot would be mapped about here.
  1140. output.add_mapping(self.end);
  1141. output.print_name(prop);
  1142. }
  1143. });
  1144. DEFPRINT(AST_Sub, function(self, output) {
  1145. self.expression.print(output);
  1146. output.print("[");
  1147. self.property.print(output);
  1148. output.print("]");
  1149. });
  1150. DEFPRINT(AST_UnaryPrefix, function(self, output) {
  1151. var op = self.operator;
  1152. output.print(op);
  1153. if (/^[a-z]/i.test(op)
  1154. || (/[+-]$/.test(op)
  1155. && self.expression instanceof AST_UnaryPrefix
  1156. && /^[+-]/.test(self.expression.operator))) {
  1157. output.space();
  1158. }
  1159. self.expression.print(output);
  1160. });
  1161. DEFPRINT(AST_UnaryPostfix, function(self, output) {
  1162. self.expression.print(output);
  1163. output.print(self.operator);
  1164. });
  1165. DEFPRINT(AST_Binary, function(self, output) {
  1166. var op = self.operator;
  1167. self.left.print(output);
  1168. if (op[0] == ">" /* ">>" ">>>" ">" ">=" */
  1169. && self.left instanceof AST_UnaryPostfix
  1170. && self.left.operator == "--") {
  1171. // space is mandatory to avoid outputting -->
  1172. output.print(" ");
  1173. } else {
  1174. // the space is optional depending on "beautify"
  1175. output.space();
  1176. }
  1177. output.print(op);
  1178. if ((op == "<" || op == "<<")
  1179. && self.right instanceof AST_UnaryPrefix
  1180. && self.right.operator == "!"
  1181. && self.right.expression instanceof AST_UnaryPrefix
  1182. && self.right.expression.operator == "--") {
  1183. // space is mandatory to avoid outputting <!--
  1184. output.print(" ");
  1185. } else {
  1186. // the space is optional depending on "beautify"
  1187. output.space();
  1188. }
  1189. self.right.print(output);
  1190. });
  1191. DEFPRINT(AST_Conditional, function(self, output) {
  1192. self.condition.print(output);
  1193. output.space();
  1194. output.print("?");
  1195. output.space();
  1196. self.consequent.print(output);
  1197. output.space();
  1198. output.colon();
  1199. self.alternative.print(output);
  1200. });
  1201. /* -----[ literals ]----- */
  1202. DEFPRINT(AST_Array, function(self, output) {
  1203. output.with_square(function() {
  1204. var a = self.elements, len = a.length;
  1205. if (len > 0) output.space();
  1206. a.forEach(function(exp, i) {
  1207. if (i) output.comma();
  1208. exp.print(output);
  1209. // If the final element is a hole, we need to make sure it
  1210. // doesn't look like a trailing comma, by inserting an actual
  1211. // trailing comma.
  1212. if (i === len - 1 && exp instanceof AST_Hole)
  1213. output.comma();
  1214. });
  1215. if (len > 0) output.space();
  1216. });
  1217. });
  1218. DEFPRINT(AST_Object, function(self, output) {
  1219. if (self.properties.length > 0) output.with_block(function() {
  1220. self.properties.forEach(function(prop, i) {
  1221. if (i) {
  1222. output.print(",");
  1223. output.newline();
  1224. }
  1225. output.indent();
  1226. prop.print(output);
  1227. });
  1228. output.newline();
  1229. });
  1230. else print_braced_empty(self, output);
  1231. });
  1232. function print_property_name(key, quote, output) {
  1233. if (output.option("quote_keys")) {
  1234. output.print_string(key);
  1235. } else if ("" + +key == key && key >= 0) {
  1236. output.print(make_num(key));
  1237. } else if (RESERVED_WORDS[key] ? !output.option("ie8") : is_identifier_string(key)) {
  1238. if (quote && output.option("keep_quoted_props")) {
  1239. output.print_string(key, quote);
  1240. } else {
  1241. output.print_name(key);
  1242. }
  1243. } else {
  1244. output.print_string(key, quote);
  1245. }
  1246. }
  1247. DEFPRINT(AST_ObjectKeyVal, function(self, output) {
  1248. print_property_name(self.key, self.quote, output);
  1249. output.colon();
  1250. self.value.print(output);
  1251. });
  1252. AST_ObjectProperty.DEFMETHOD("_print_getter_setter", function(type, output) {
  1253. output.print(type);
  1254. output.space();
  1255. print_property_name(this.key.name, this.quote, output);
  1256. this.value._do_print(output, true);
  1257. });
  1258. DEFPRINT(AST_ObjectSetter, function(self, output) {
  1259. self._print_getter_setter("set", output);
  1260. });
  1261. DEFPRINT(AST_ObjectGetter, function(self, output) {
  1262. self._print_getter_setter("get", output);
  1263. });
  1264. DEFPRINT(AST_Symbol, function(self, output) {
  1265. var def = self.definition();
  1266. output.print_name(def ? def.mangled_name || def.name : self.name);
  1267. });
  1268. DEFPRINT(AST_Hole, noop);
  1269. DEFPRINT(AST_This, function(self, output) {
  1270. output.print("this");
  1271. });
  1272. DEFPRINT(AST_Constant, function(self, output) {
  1273. output.print(self.getValue());
  1274. });
  1275. DEFPRINT(AST_String, function(self, output) {
  1276. output.print_string(self.getValue(), self.quote, in_directive);
  1277. });
  1278. DEFPRINT(AST_Number, function(self, output) {
  1279. if (use_asm && self.start && self.start.raw != null) {
  1280. output.print(self.start.raw);
  1281. } else {
  1282. output.print(make_num(self.getValue()));
  1283. }
  1284. });
  1285. DEFPRINT(AST_RegExp, function(self, output) {
  1286. var regexp = self.getValue();
  1287. var str = regexp.toString();
  1288. if (regexp.raw_source) {
  1289. str = "/" + regexp.raw_source + str.slice(str.lastIndexOf("/"));
  1290. }
  1291. str = output.to_utf8(str);
  1292. output.print(str);
  1293. var p = output.parent();
  1294. if (p instanceof AST_Binary && /^in/.test(p.operator) && p.left === self)
  1295. output.print(" ");
  1296. });
  1297. function force_statement(stat, output) {
  1298. if (output.option("braces")) {
  1299. make_block(stat, output);
  1300. } else {
  1301. if (!stat || stat instanceof AST_EmptyStatement)
  1302. output.force_semicolon();
  1303. else
  1304. stat.print(output);
  1305. }
  1306. }
  1307. // self should be AST_New. decide if we want to show parens or not.
  1308. function need_constructor_parens(self, output) {
  1309. // Always print parentheses with arguments
  1310. if (self.args.length > 0) return true;
  1311. return output.option("beautify");
  1312. }
  1313. function best_of(a) {
  1314. var best = a[0], len = best.length;
  1315. for (var i = 1; i < a.length; ++i) {
  1316. if (a[i].length < len) {
  1317. best = a[i];
  1318. len = best.length;
  1319. }
  1320. }
  1321. return best;
  1322. }
  1323. function make_num(num) {
  1324. var str = num.toString(10).replace(/^0\./, ".").replace("e+", "e");
  1325. var candidates = [ str ];
  1326. if (Math.floor(num) === num) {
  1327. if (num < 0) {
  1328. candidates.push("-0x" + (-num).toString(16).toLowerCase());
  1329. } else {
  1330. candidates.push("0x" + num.toString(16).toLowerCase());
  1331. }
  1332. }
  1333. var match, len, digits;
  1334. if (match = /^\.0+/.exec(str)) {
  1335. len = match[0].length;
  1336. digits = str.slice(len);
  1337. candidates.push(digits + "e-" + (digits.length + len - 1));
  1338. } else if (match = /0+$/.exec(str)) {
  1339. len = match[0].length;
  1340. candidates.push(str.slice(0, -len) + "e" + len);
  1341. } else if (match = /^(\d)\.(\d+)e(-?\d+)$/.exec(str)) {
  1342. candidates.push(match[1] + match[2] + "e" + (match[3] - match[2].length));
  1343. }
  1344. return best_of(candidates);
  1345. }
  1346. function make_block(stmt, output) {
  1347. if (!stmt || stmt instanceof AST_EmptyStatement)
  1348. output.print("{}");
  1349. else if (stmt instanceof AST_BlockStatement)
  1350. stmt.print(output);
  1351. else output.with_block(function() {
  1352. output.indent();
  1353. stmt.print(output);
  1354. output.newline();
  1355. });
  1356. }
  1357. /* -----[ source map generators ]----- */
  1358. function DEFMAP(nodetype, generator) {
  1359. nodetype.forEach(function(nodetype) {
  1360. nodetype.DEFMETHOD("add_source_map", generator);
  1361. });
  1362. }
  1363. DEFMAP([
  1364. // We could easily add info for ALL nodes, but it seems to me that
  1365. // would be quite wasteful, hence this noop in the base class.
  1366. AST_Node,
  1367. // since the label symbol will mark it
  1368. AST_LabeledStatement,
  1369. AST_Toplevel,
  1370. ], noop);
  1371. // XXX: I'm not exactly sure if we need it for all of these nodes,
  1372. // or if we should add even more.
  1373. DEFMAP([
  1374. AST_Array,
  1375. AST_BlockStatement,
  1376. AST_Catch,
  1377. AST_Constant,
  1378. AST_Debugger,
  1379. AST_Definitions,
  1380. AST_Directive,
  1381. AST_Finally,
  1382. AST_Jump,
  1383. AST_Lambda,
  1384. AST_New,
  1385. AST_Object,
  1386. AST_StatementWithBody,
  1387. AST_Symbol,
  1388. AST_Switch,
  1389. AST_SwitchBranch,
  1390. AST_Try,
  1391. ], function(output) {
  1392. output.add_mapping(this.start);
  1393. });
  1394. DEFMAP([
  1395. AST_ObjectGetter,
  1396. AST_ObjectSetter,
  1397. ], function(output) {
  1398. output.add_mapping(this.start, this.key.name);
  1399. });
  1400. DEFMAP([ AST_ObjectProperty ], function(output) {
  1401. output.add_mapping(this.start, this.key);
  1402. });
  1403. })();