PageRenderTime 58ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/back/node_modules/synth/node_modules/bower/node_modules/handlebars/node_modules/uglify-js/lib/output.js

https://github.com/DavidRagone/SetReviewGrader
JavaScript | 1229 lines | 1060 code | 63 blank | 106 comment | 196 complexity | 31b5ea2e8d428897186aab2aaa505eb5 MD5 | raw file
Possible License(s): MIT, 0BSD, BSD-2-Clause, BSD-3-Clause, Apache-2.0, MPL-2.0-no-copyleft-exception, AGPL-3.0
  1. /***********************************************************************
  2. A JavaScript tokenizer / parser / beautifier / compressor.
  3. https://github.com/mishoo/UglifyJS2
  4. -------------------------------- (C) ---------------------------------
  5. Author: Mihai Bazon
  6. <mihai.bazon@gmail.com>
  7. http://mihai.bazon.net/blog
  8. Distributed under the BSD license:
  9. Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com>
  10. Redistribution and use in source and binary forms, with or without
  11. modification, are permitted provided that the following conditions
  12. are met:
  13. * Redistributions of source code must retain the above
  14. copyright notice, this list of conditions and the following
  15. disclaimer.
  16. * Redistributions in binary form must reproduce the above
  17. copyright notice, this list of conditions and the following
  18. disclaimer in the documentation and/or other materials
  19. provided with the distribution.
  20. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
  21. EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  22. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  23. PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
  24. LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
  25. OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  26. PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  27. PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  28. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
  29. TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
  30. THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  31. SUCH DAMAGE.
  32. ***********************************************************************/
  33. "use strict";
  34. function OutputStream(options) {
  35. options = defaults(options, {
  36. indent_start : 0,
  37. indent_level : 4,
  38. quote_keys : false,
  39. space_colon : true,
  40. ascii_only : false,
  41. inline_script : false,
  42. width : 80,
  43. max_line_len : 32000,
  44. ie_proof : true,
  45. beautify : false,
  46. source_map : null,
  47. bracketize : false,
  48. semicolons : true,
  49. comments : false,
  50. preserve_line : false,
  51. negate_iife : !(options && options.beautify),
  52. }, true);
  53. var indentation = 0;
  54. var current_col = 0;
  55. var current_line = 1;
  56. var current_pos = 0;
  57. var OUTPUT = "";
  58. function to_ascii(str, identifier) {
  59. return str.replace(/[\u0080-\uffff]/g, function(ch) {
  60. var code = ch.charCodeAt(0).toString(16);
  61. if (code.length <= 2 && !identifier) {
  62. while (code.length < 2) code = "0" + code;
  63. return "\\x" + code;
  64. } else {
  65. while (code.length < 4) code = "0" + code;
  66. return "\\u" + code;
  67. }
  68. });
  69. };
  70. function make_string(str) {
  71. var dq = 0, sq = 0;
  72. str = str.replace(/[\\\b\f\n\r\t\x22\x27\u2028\u2029\0]/g, function(s){
  73. switch (s) {
  74. case "\\": return "\\\\";
  75. case "\b": return "\\b";
  76. case "\f": return "\\f";
  77. case "\n": return "\\n";
  78. case "\r": return "\\r";
  79. case "\u2028": return "\\u2028";
  80. case "\u2029": return "\\u2029";
  81. case '"': ++dq; return '"';
  82. case "'": ++sq; return "'";
  83. case "\0": return "\\0";
  84. }
  85. return s;
  86. });
  87. if (options.ascii_only) str = to_ascii(str);
  88. if (dq > sq) return "'" + str.replace(/\x27/g, "\\'") + "'";
  89. else return '"' + str.replace(/\x22/g, '\\"') + '"';
  90. };
  91. function encode_string(str) {
  92. var ret = make_string(str);
  93. if (options.inline_script)
  94. ret = ret.replace(/<\x2fscript([>\/\t\n\f\r ])/gi, "<\\/script$1");
  95. return ret;
  96. };
  97. function make_name(name) {
  98. name = name.toString();
  99. if (options.ascii_only)
  100. name = to_ascii(name, true);
  101. return name;
  102. };
  103. function make_indent(back) {
  104. return repeat_string(" ", options.indent_start + indentation - back * options.indent_level);
  105. };
  106. /* -----[ beautification/minification ]----- */
  107. var might_need_space = false;
  108. var might_need_semicolon = false;
  109. var last = null;
  110. function last_char() {
  111. return last.charAt(last.length - 1);
  112. };
  113. function maybe_newline() {
  114. if (options.max_line_len && current_col > options.max_line_len)
  115. print("\n");
  116. };
  117. var requireSemicolonChars = makePredicate("( [ + * / - , .");
  118. function print(str) {
  119. str = String(str);
  120. var ch = str.charAt(0);
  121. if (might_need_semicolon) {
  122. if ((!ch || ";}".indexOf(ch) < 0) && !/[;]$/.test(last)) {
  123. if (options.semicolons || requireSemicolonChars(ch)) {
  124. OUTPUT += ";";
  125. current_col++;
  126. current_pos++;
  127. } else {
  128. OUTPUT += "\n";
  129. current_pos++;
  130. current_line++;
  131. current_col = 0;
  132. }
  133. if (!options.beautify)
  134. might_need_space = false;
  135. }
  136. might_need_semicolon = false;
  137. maybe_newline();
  138. }
  139. if (!options.beautify && options.preserve_line && stack[stack.length - 1]) {
  140. var target_line = stack[stack.length - 1].start.line;
  141. while (current_line < target_line) {
  142. OUTPUT += "\n";
  143. current_pos++;
  144. current_line++;
  145. current_col = 0;
  146. might_need_space = false;
  147. }
  148. }
  149. if (might_need_space) {
  150. var prev = last_char();
  151. if ((is_identifier_char(prev)
  152. && (is_identifier_char(ch) || ch == "\\"))
  153. || (/^[\+\-\/]$/.test(ch) && ch == prev))
  154. {
  155. OUTPUT += " ";
  156. current_col++;
  157. current_pos++;
  158. }
  159. might_need_space = false;
  160. }
  161. var a = str.split(/\r?\n/), n = a.length - 1;
  162. current_line += n;
  163. if (n == 0) {
  164. current_col += a[n].length;
  165. } else {
  166. current_col = a[n].length;
  167. }
  168. current_pos += str.length;
  169. last = str;
  170. OUTPUT += str;
  171. };
  172. var space = options.beautify ? function() {
  173. print(" ");
  174. } : function() {
  175. might_need_space = true;
  176. };
  177. var indent = options.beautify ? function(half) {
  178. if (options.beautify) {
  179. print(make_indent(half ? 0.5 : 0));
  180. }
  181. } : noop;
  182. var with_indent = options.beautify ? function(col, cont) {
  183. if (col === true) col = next_indent();
  184. var save_indentation = indentation;
  185. indentation = col;
  186. var ret = cont();
  187. indentation = save_indentation;
  188. return ret;
  189. } : function(col, cont) { return cont() };
  190. var newline = options.beautify ? function() {
  191. print("\n");
  192. } : noop;
  193. var semicolon = options.beautify ? function() {
  194. print(";");
  195. } : function() {
  196. might_need_semicolon = true;
  197. };
  198. function force_semicolon() {
  199. might_need_semicolon = false;
  200. print(";");
  201. };
  202. function next_indent() {
  203. return indentation + options.indent_level;
  204. };
  205. function with_block(cont) {
  206. var ret;
  207. print("{");
  208. newline();
  209. with_indent(next_indent(), function(){
  210. ret = cont();
  211. });
  212. indent();
  213. print("}");
  214. return ret;
  215. };
  216. function with_parens(cont) {
  217. print("(");
  218. //XXX: still nice to have that for argument lists
  219. //var ret = with_indent(current_col, cont);
  220. var ret = cont();
  221. print(")");
  222. return ret;
  223. };
  224. function with_square(cont) {
  225. print("[");
  226. //var ret = with_indent(current_col, cont);
  227. var ret = cont();
  228. print("]");
  229. return ret;
  230. };
  231. function comma() {
  232. print(",");
  233. space();
  234. };
  235. function colon() {
  236. print(":");
  237. if (options.space_colon) space();
  238. };
  239. var add_mapping = options.source_map ? function(token, name) {
  240. try {
  241. if (token) options.source_map.add(
  242. token.file || "?",
  243. current_line, current_col,
  244. token.line, token.col,
  245. (!name && token.type == "name") ? token.value : name
  246. );
  247. } catch(ex) {
  248. AST_Node.warn("Couldn't figure out mapping for {file}:{line},{col} → {cline},{ccol} [{name}]", {
  249. file: token.file,
  250. line: token.line,
  251. col: token.col,
  252. cline: current_line,
  253. ccol: current_col,
  254. name: name || ""
  255. })
  256. }
  257. } : noop;
  258. function get() {
  259. return OUTPUT;
  260. };
  261. var stack = [];
  262. return {
  263. get : get,
  264. toString : get,
  265. indent : indent,
  266. indentation : function() { return indentation },
  267. current_width : function() { return current_col - indentation },
  268. should_break : function() { return options.width && this.current_width() >= options.width },
  269. newline : newline,
  270. print : print,
  271. space : space,
  272. comma : comma,
  273. colon : colon,
  274. last : function() { return last },
  275. semicolon : semicolon,
  276. force_semicolon : force_semicolon,
  277. to_ascii : to_ascii,
  278. print_name : function(name) { print(make_name(name)) },
  279. print_string : function(str) { print(encode_string(str)) },
  280. next_indent : next_indent,
  281. with_indent : with_indent,
  282. with_block : with_block,
  283. with_parens : with_parens,
  284. with_square : with_square,
  285. add_mapping : add_mapping,
  286. option : function(opt) { return options[opt] },
  287. line : function() { return current_line },
  288. col : function() { return current_col },
  289. pos : function() { return current_pos },
  290. push_node : function(node) { stack.push(node) },
  291. pop_node : function() { return stack.pop() },
  292. stack : function() { return stack },
  293. parent : function(n) {
  294. return stack[stack.length - 2 - (n || 0)];
  295. }
  296. };
  297. };
  298. /* -----[ code generators ]----- */
  299. (function(){
  300. /* -----[ utils ]----- */
  301. function DEFPRINT(nodetype, generator) {
  302. nodetype.DEFMETHOD("_codegen", generator);
  303. };
  304. AST_Node.DEFMETHOD("print", function(stream, force_parens){
  305. var self = this, generator = self._codegen;
  306. stream.push_node(self);
  307. var needs_parens = self.needs_parens(stream);
  308. var fc = self instanceof AST_Function && stream.option("negate_iife");
  309. if (force_parens || (needs_parens && !fc)) {
  310. stream.with_parens(function(){
  311. self.add_comments(stream);
  312. self.add_source_map(stream);
  313. generator(self, stream);
  314. });
  315. } else {
  316. self.add_comments(stream);
  317. if (needs_parens && fc) stream.print("!");
  318. self.add_source_map(stream);
  319. generator(self, stream);
  320. }
  321. stream.pop_node();
  322. });
  323. AST_Node.DEFMETHOD("print_to_string", function(options){
  324. var s = OutputStream(options);
  325. this.print(s);
  326. return s.get();
  327. });
  328. /* -----[ comments ]----- */
  329. AST_Node.DEFMETHOD("add_comments", function(output){
  330. var c = output.option("comments"), self = this;
  331. if (c) {
  332. var start = self.start;
  333. if (start && !start._comments_dumped) {
  334. start._comments_dumped = true;
  335. var comments = start.comments_before;
  336. // XXX: ugly fix for https://github.com/mishoo/UglifyJS2/issues/112
  337. // if this node is `return` or `throw`, we cannot allow comments before
  338. // the returned or thrown value.
  339. if (self instanceof AST_Exit &&
  340. self.value && self.value.start.comments_before.length > 0) {
  341. comments = (comments || []).concat(self.value.start.comments_before);
  342. self.value.start.comments_before = [];
  343. }
  344. if (c.test) {
  345. comments = comments.filter(function(comment){
  346. return c.test(comment.value);
  347. });
  348. } else if (typeof c == "function") {
  349. comments = comments.filter(function(comment){
  350. return c(self, comment);
  351. });
  352. }
  353. comments.forEach(function(c){
  354. if (c.type == "comment1") {
  355. output.print("//" + c.value + "\n");
  356. output.indent();
  357. }
  358. else if (c.type == "comment2") {
  359. output.print("/*" + c.value + "*/");
  360. if (start.nlb) {
  361. output.print("\n");
  362. output.indent();
  363. } else {
  364. output.space();
  365. }
  366. }
  367. });
  368. }
  369. }
  370. });
  371. /* -----[ PARENTHESES ]----- */
  372. function PARENS(nodetype, func) {
  373. nodetype.DEFMETHOD("needs_parens", func);
  374. };
  375. PARENS(AST_Node, function(){
  376. return false;
  377. });
  378. // a function expression needs parens around it when it's provably
  379. // the first token to appear in a statement.
  380. PARENS(AST_Function, function(output){
  381. return first_in_statement(output);
  382. });
  383. // same goes for an object literal, because otherwise it would be
  384. // interpreted as a block of code.
  385. PARENS(AST_Object, function(output){
  386. return first_in_statement(output);
  387. });
  388. PARENS(AST_Unary, function(output){
  389. var p = output.parent();
  390. return p instanceof AST_PropAccess && p.expression === this;
  391. });
  392. PARENS(AST_Seq, function(output){
  393. var p = output.parent();
  394. return p instanceof AST_Call // (foo, bar)() or foo(1, (2, 3), 4)
  395. || p instanceof AST_Unary // !(foo, bar, baz)
  396. || p instanceof AST_Binary // 1 + (2, 3) + 4 ==> 8
  397. || p instanceof AST_VarDef // var a = (1, 2), b = a + a; ==> b == 4
  398. || p instanceof AST_Dot // (1, {foo:2}).foo ==> 2
  399. || p instanceof AST_Array // [ 1, (2, 3), 4 ] ==> [ 1, 3, 4 ]
  400. || p instanceof AST_ObjectProperty // { foo: (1, 2) }.foo ==> 2
  401. || p instanceof AST_Conditional /* (false, true) ? (a = 10, b = 20) : (c = 30)
  402. * ==> 20 (side effect, set a := 10 and b := 20) */
  403. ;
  404. });
  405. PARENS(AST_Binary, function(output){
  406. var p = output.parent();
  407. // (foo && bar)()
  408. if (p instanceof AST_Call && p.expression === this)
  409. return true;
  410. // typeof (foo && bar)
  411. if (p instanceof AST_Unary)
  412. return true;
  413. // (foo && bar)["prop"], (foo && bar).prop
  414. if (p instanceof AST_PropAccess && p.expression === this)
  415. return true;
  416. // this deals with precedence: 3 * (2 + 1)
  417. if (p instanceof AST_Binary) {
  418. var po = p.operator, pp = PRECEDENCE[po];
  419. var so = this.operator, sp = PRECEDENCE[so];
  420. if (pp > sp
  421. || (pp == sp
  422. && this === p.right
  423. && !(so == po &&
  424. (so == "*" ||
  425. so == "&&" ||
  426. so == "||")))) {
  427. return true;
  428. }
  429. }
  430. });
  431. PARENS(AST_PropAccess, function(output){
  432. var p = output.parent();
  433. if (p instanceof AST_New && p.expression === this) {
  434. // i.e. new (foo.bar().baz)
  435. //
  436. // if there's one call into this subtree, then we need
  437. // parens around it too, otherwise the call will be
  438. // interpreted as passing the arguments to the upper New
  439. // expression.
  440. try {
  441. this.walk(new TreeWalker(function(node){
  442. if (node instanceof AST_Call) throw p;
  443. }));
  444. } catch(ex) {
  445. if (ex !== p) throw ex;
  446. return true;
  447. }
  448. }
  449. });
  450. PARENS(AST_Call, function(output){
  451. var p = output.parent();
  452. return p instanceof AST_New && p.expression === this;
  453. });
  454. PARENS(AST_New, function(output){
  455. var p = output.parent();
  456. if (no_constructor_parens(this, output)
  457. && (p instanceof AST_PropAccess // (new Date).getTime(), (new Date)["getTime"]()
  458. || p instanceof AST_Call && p.expression === this)) // (new foo)(bar)
  459. return true;
  460. });
  461. PARENS(AST_Number, function(output){
  462. var p = output.parent();
  463. if (this.getValue() < 0 && p instanceof AST_PropAccess && p.expression === this)
  464. return true;
  465. });
  466. PARENS(AST_NaN, function(output){
  467. var p = output.parent();
  468. if (p instanceof AST_PropAccess && p.expression === this)
  469. return true;
  470. });
  471. function assign_and_conditional_paren_rules(output) {
  472. var p = output.parent();
  473. // !(a = false) → true
  474. if (p instanceof AST_Unary)
  475. return true;
  476. // 1 + (a = 2) + 3 → 6, side effect setting a = 2
  477. if (p instanceof AST_Binary && !(p instanceof AST_Assign))
  478. return true;
  479. // (a = func)() —or— new (a = Object)()
  480. if (p instanceof AST_Call && p.expression === this)
  481. return true;
  482. // (a = foo) ? bar : baz
  483. if (p instanceof AST_Conditional && p.condition === this)
  484. return true;
  485. // (a = foo)["prop"] —or— (a = foo).prop
  486. if (p instanceof AST_PropAccess && p.expression === this)
  487. return true;
  488. };
  489. PARENS(AST_Assign, assign_and_conditional_paren_rules);
  490. PARENS(AST_Conditional, assign_and_conditional_paren_rules);
  491. /* -----[ PRINTERS ]----- */
  492. DEFPRINT(AST_Directive, function(self, output){
  493. output.print_string(self.value);
  494. output.semicolon();
  495. });
  496. DEFPRINT(AST_Debugger, function(self, output){
  497. output.print("debugger");
  498. output.semicolon();
  499. });
  500. /* -----[ statements ]----- */
  501. function display_body(body, is_toplevel, output) {
  502. var last = body.length - 1;
  503. body.forEach(function(stmt, i){
  504. if (!(stmt instanceof AST_EmptyStatement)) {
  505. output.indent();
  506. stmt.print(output);
  507. if (!(i == last && is_toplevel)) {
  508. output.newline();
  509. if (is_toplevel) output.newline();
  510. }
  511. }
  512. });
  513. };
  514. AST_StatementWithBody.DEFMETHOD("_do_print_body", function(output){
  515. force_statement(this.body, output);
  516. });
  517. DEFPRINT(AST_Statement, function(self, output){
  518. self.body.print(output);
  519. output.semicolon();
  520. });
  521. DEFPRINT(AST_Toplevel, function(self, output){
  522. display_body(self.body, true, output);
  523. output.print("");
  524. });
  525. DEFPRINT(AST_LabeledStatement, function(self, output){
  526. self.label.print(output);
  527. output.colon();
  528. self.body.print(output);
  529. });
  530. DEFPRINT(AST_SimpleStatement, function(self, output){
  531. self.body.print(output);
  532. output.semicolon();
  533. });
  534. function print_bracketed(body, output) {
  535. if (body.length > 0) output.with_block(function(){
  536. display_body(body, false, output);
  537. });
  538. else output.print("{}");
  539. };
  540. DEFPRINT(AST_BlockStatement, function(self, output){
  541. print_bracketed(self.body, output);
  542. });
  543. DEFPRINT(AST_EmptyStatement, function(self, output){
  544. output.semicolon();
  545. });
  546. DEFPRINT(AST_Do, function(self, output){
  547. output.print("do");
  548. output.space();
  549. self._do_print_body(output);
  550. output.space();
  551. output.print("while");
  552. output.space();
  553. output.with_parens(function(){
  554. self.condition.print(output);
  555. });
  556. output.semicolon();
  557. });
  558. DEFPRINT(AST_While, function(self, output){
  559. output.print("while");
  560. output.space();
  561. output.with_parens(function(){
  562. self.condition.print(output);
  563. });
  564. output.space();
  565. self._do_print_body(output);
  566. });
  567. DEFPRINT(AST_For, function(self, output){
  568. output.print("for");
  569. output.space();
  570. output.with_parens(function(){
  571. if (self.init) {
  572. if (self.init instanceof AST_Definitions) {
  573. self.init.print(output);
  574. } else {
  575. parenthesize_for_noin(self.init, output, true);
  576. }
  577. output.print(";");
  578. output.space();
  579. } else {
  580. output.print(";");
  581. }
  582. if (self.condition) {
  583. self.condition.print(output);
  584. output.print(";");
  585. output.space();
  586. } else {
  587. output.print(";");
  588. }
  589. if (self.step) {
  590. self.step.print(output);
  591. }
  592. });
  593. output.space();
  594. self._do_print_body(output);
  595. });
  596. DEFPRINT(AST_ForIn, function(self, output){
  597. output.print("for");
  598. output.space();
  599. output.with_parens(function(){
  600. self.init.print(output);
  601. output.space();
  602. output.print("in");
  603. output.space();
  604. self.object.print(output);
  605. });
  606. output.space();
  607. self._do_print_body(output);
  608. });
  609. DEFPRINT(AST_With, function(self, output){
  610. output.print("with");
  611. output.space();
  612. output.with_parens(function(){
  613. self.expression.print(output);
  614. });
  615. output.space();
  616. self._do_print_body(output);
  617. });
  618. /* -----[ functions ]----- */
  619. AST_Lambda.DEFMETHOD("_do_print", function(output, nokeyword){
  620. var self = this;
  621. if (!nokeyword) {
  622. output.print("function");
  623. }
  624. if (self.name) {
  625. output.space();
  626. self.name.print(output);
  627. }
  628. output.with_parens(function(){
  629. self.argnames.forEach(function(arg, i){
  630. if (i) output.comma();
  631. arg.print(output);
  632. });
  633. });
  634. output.space();
  635. print_bracketed(self.body, output);
  636. });
  637. DEFPRINT(AST_Lambda, function(self, output){
  638. self._do_print(output);
  639. });
  640. /* -----[ exits ]----- */
  641. AST_Exit.DEFMETHOD("_do_print", function(output, kind){
  642. output.print(kind);
  643. if (this.value) {
  644. output.space();
  645. this.value.print(output);
  646. }
  647. output.semicolon();
  648. });
  649. DEFPRINT(AST_Return, function(self, output){
  650. self._do_print(output, "return");
  651. });
  652. DEFPRINT(AST_Throw, function(self, output){
  653. self._do_print(output, "throw");
  654. });
  655. /* -----[ loop control ]----- */
  656. AST_LoopControl.DEFMETHOD("_do_print", function(output, kind){
  657. output.print(kind);
  658. if (this.label) {
  659. output.space();
  660. this.label.print(output);
  661. }
  662. output.semicolon();
  663. });
  664. DEFPRINT(AST_Break, function(self, output){
  665. self._do_print(output, "break");
  666. });
  667. DEFPRINT(AST_Continue, function(self, output){
  668. self._do_print(output, "continue");
  669. });
  670. /* -----[ if ]----- */
  671. function make_then(self, output) {
  672. if (output.option("bracketize")) {
  673. make_block(self.body, output);
  674. return;
  675. }
  676. // The squeezer replaces "block"-s that contain only a single
  677. // statement with the statement itself; technically, the AST
  678. // is correct, but this can create problems when we output an
  679. // IF having an ELSE clause where the THEN clause ends in an
  680. // IF *without* an ELSE block (then the outer ELSE would refer
  681. // to the inner IF). This function checks for this case and
  682. // adds the block brackets if needed.
  683. if (!self.body)
  684. return output.force_semicolon();
  685. if (self.body instanceof AST_Do
  686. && output.option("ie_proof")) {
  687. // https://github.com/mishoo/UglifyJS/issues/#issue/57 IE
  688. // croaks with "syntax error" on code like this: if (foo)
  689. // do ... while(cond); else ... we need block brackets
  690. // around do/while
  691. make_block(self.body, output);
  692. return;
  693. }
  694. var b = self.body;
  695. while (true) {
  696. if (b instanceof AST_If) {
  697. if (!b.alternative) {
  698. make_block(self.body, output);
  699. return;
  700. }
  701. b = b.alternative;
  702. }
  703. else if (b instanceof AST_StatementWithBody) {
  704. b = b.body;
  705. }
  706. else break;
  707. }
  708. force_statement(self.body, output);
  709. };
  710. DEFPRINT(AST_If, function(self, output){
  711. output.print("if");
  712. output.space();
  713. output.with_parens(function(){
  714. self.condition.print(output);
  715. });
  716. output.space();
  717. if (self.alternative) {
  718. make_then(self, output);
  719. output.space();
  720. output.print("else");
  721. output.space();
  722. force_statement(self.alternative, output);
  723. } else {
  724. self._do_print_body(output);
  725. }
  726. });
  727. /* -----[ switch ]----- */
  728. DEFPRINT(AST_Switch, function(self, output){
  729. output.print("switch");
  730. output.space();
  731. output.with_parens(function(){
  732. self.expression.print(output);
  733. });
  734. output.space();
  735. if (self.body.length > 0) output.with_block(function(){
  736. self.body.forEach(function(stmt, i){
  737. if (i) output.newline();
  738. output.indent(true);
  739. stmt.print(output);
  740. });
  741. });
  742. else output.print("{}");
  743. });
  744. AST_SwitchBranch.DEFMETHOD("_do_print_body", function(output){
  745. if (this.body.length > 0) {
  746. output.newline();
  747. this.body.forEach(function(stmt){
  748. output.indent();
  749. stmt.print(output);
  750. output.newline();
  751. });
  752. }
  753. });
  754. DEFPRINT(AST_Default, function(self, output){
  755. output.print("default:");
  756. self._do_print_body(output);
  757. });
  758. DEFPRINT(AST_Case, function(self, output){
  759. output.print("case");
  760. output.space();
  761. self.expression.print(output);
  762. output.print(":");
  763. self._do_print_body(output);
  764. });
  765. /* -----[ exceptions ]----- */
  766. DEFPRINT(AST_Try, function(self, output){
  767. output.print("try");
  768. output.space();
  769. print_bracketed(self.body, output);
  770. if (self.bcatch) {
  771. output.space();
  772. self.bcatch.print(output);
  773. }
  774. if (self.bfinally) {
  775. output.space();
  776. self.bfinally.print(output);
  777. }
  778. });
  779. DEFPRINT(AST_Catch, function(self, output){
  780. output.print("catch");
  781. output.space();
  782. output.with_parens(function(){
  783. self.argname.print(output);
  784. });
  785. output.space();
  786. print_bracketed(self.body, output);
  787. });
  788. DEFPRINT(AST_Finally, function(self, output){
  789. output.print("finally");
  790. output.space();
  791. print_bracketed(self.body, output);
  792. });
  793. /* -----[ var/const ]----- */
  794. AST_Definitions.DEFMETHOD("_do_print", function(output, kind){
  795. output.print(kind);
  796. output.space();
  797. this.definitions.forEach(function(def, i){
  798. if (i) output.comma();
  799. def.print(output);
  800. });
  801. var p = output.parent();
  802. var in_for = p instanceof AST_For || p instanceof AST_ForIn;
  803. var avoid_semicolon = in_for && p.init === this;
  804. if (!avoid_semicolon)
  805. output.semicolon();
  806. });
  807. DEFPRINT(AST_Var, function(self, output){
  808. self._do_print(output, "var");
  809. });
  810. DEFPRINT(AST_Const, function(self, output){
  811. self._do_print(output, "const");
  812. });
  813. function parenthesize_for_noin(node, output, noin) {
  814. if (!noin) node.print(output);
  815. else try {
  816. // need to take some precautions here:
  817. // https://github.com/mishoo/UglifyJS2/issues/60
  818. node.walk(new TreeWalker(function(node){
  819. if (node instanceof AST_Binary && node.operator == "in")
  820. throw output;
  821. }));
  822. node.print(output);
  823. } catch(ex) {
  824. if (ex !== output) throw ex;
  825. node.print(output, true);
  826. }
  827. };
  828. DEFPRINT(AST_VarDef, function(self, output){
  829. self.name.print(output);
  830. if (self.value) {
  831. output.space();
  832. output.print("=");
  833. output.space();
  834. var p = output.parent(1);
  835. var noin = p instanceof AST_For || p instanceof AST_ForIn;
  836. parenthesize_for_noin(self.value, output, noin);
  837. }
  838. });
  839. /* -----[ other expressions ]----- */
  840. DEFPRINT(AST_Call, function(self, output){
  841. self.expression.print(output);
  842. if (self instanceof AST_New && no_constructor_parens(self, output))
  843. return;
  844. output.with_parens(function(){
  845. self.args.forEach(function(expr, i){
  846. if (i) output.comma();
  847. expr.print(output);
  848. });
  849. });
  850. });
  851. DEFPRINT(AST_New, function(self, output){
  852. output.print("new");
  853. output.space();
  854. AST_Call.prototype._codegen(self, output);
  855. });
  856. AST_Seq.DEFMETHOD("_do_print", function(output){
  857. this.car.print(output);
  858. if (this.cdr) {
  859. output.comma();
  860. if (output.should_break()) {
  861. output.newline();
  862. output.indent();
  863. }
  864. this.cdr.print(output);
  865. }
  866. });
  867. DEFPRINT(AST_Seq, function(self, output){
  868. self._do_print(output);
  869. // var p = output.parent();
  870. // if (p instanceof AST_Statement) {
  871. // output.with_indent(output.next_indent(), function(){
  872. // self._do_print(output);
  873. // });
  874. // } else {
  875. // self._do_print(output);
  876. // }
  877. });
  878. DEFPRINT(AST_Dot, function(self, output){
  879. var expr = self.expression;
  880. expr.print(output);
  881. if (expr instanceof AST_Number && expr.getValue() >= 0) {
  882. if (!/[xa-f.]/i.test(output.last())) {
  883. output.print(".");
  884. }
  885. }
  886. output.print(".");
  887. // the name after dot would be mapped about here.
  888. output.add_mapping(self.end);
  889. output.print_name(self.property);
  890. });
  891. DEFPRINT(AST_Sub, function(self, output){
  892. self.expression.print(output);
  893. output.print("[");
  894. self.property.print(output);
  895. output.print("]");
  896. });
  897. DEFPRINT(AST_UnaryPrefix, function(self, output){
  898. var op = self.operator;
  899. output.print(op);
  900. if (/^[a-z]/i.test(op))
  901. output.space();
  902. self.expression.print(output);
  903. });
  904. DEFPRINT(AST_UnaryPostfix, function(self, output){
  905. self.expression.print(output);
  906. output.print(self.operator);
  907. });
  908. DEFPRINT(AST_Binary, function(self, output){
  909. self.left.print(output);
  910. output.space();
  911. output.print(self.operator);
  912. output.space();
  913. self.right.print(output);
  914. });
  915. DEFPRINT(AST_Conditional, function(self, output){
  916. self.condition.print(output);
  917. output.space();
  918. output.print("?");
  919. output.space();
  920. self.consequent.print(output);
  921. output.space();
  922. output.colon();
  923. self.alternative.print(output);
  924. });
  925. /* -----[ literals ]----- */
  926. DEFPRINT(AST_Array, function(self, output){
  927. output.with_square(function(){
  928. var a = self.elements, len = a.length;
  929. if (len > 0) output.space();
  930. a.forEach(function(exp, i){
  931. if (i) output.comma();
  932. exp.print(output);
  933. });
  934. if (len > 0) output.space();
  935. });
  936. });
  937. DEFPRINT(AST_Object, function(self, output){
  938. if (self.properties.length > 0) output.with_block(function(){
  939. self.properties.forEach(function(prop, i){
  940. if (i) {
  941. output.print(",");
  942. output.newline();
  943. }
  944. output.indent();
  945. prop.print(output);
  946. });
  947. output.newline();
  948. });
  949. else output.print("{}");
  950. });
  951. DEFPRINT(AST_ObjectKeyVal, function(self, output){
  952. var key = self.key;
  953. if (output.option("quote_keys")) {
  954. output.print_string(key + "");
  955. } else if ((typeof key == "number"
  956. || !output.option("beautify")
  957. && +key + "" == key)
  958. && parseFloat(key) >= 0) {
  959. output.print(make_num(key));
  960. } else if (!is_identifier(key)) {
  961. output.print_string(key);
  962. } else {
  963. output.print_name(key);
  964. }
  965. output.colon();
  966. self.value.print(output);
  967. });
  968. DEFPRINT(AST_ObjectSetter, function(self, output){
  969. output.print("set");
  970. self.value._do_print(output, true);
  971. });
  972. DEFPRINT(AST_ObjectGetter, function(self, output){
  973. output.print("get");
  974. self.value._do_print(output, true);
  975. });
  976. DEFPRINT(AST_Symbol, function(self, output){
  977. var def = self.definition();
  978. output.print_name(def ? def.mangled_name || def.name : self.name);
  979. });
  980. DEFPRINT(AST_Undefined, function(self, output){
  981. output.print("void 0");
  982. });
  983. DEFPRINT(AST_Hole, noop);
  984. DEFPRINT(AST_Infinity, function(self, output){
  985. output.print("1/0");
  986. });
  987. DEFPRINT(AST_NaN, function(self, output){
  988. output.print("0/0");
  989. });
  990. DEFPRINT(AST_This, function(self, output){
  991. output.print("this");
  992. });
  993. DEFPRINT(AST_Constant, function(self, output){
  994. output.print(self.getValue());
  995. });
  996. DEFPRINT(AST_String, function(self, output){
  997. output.print_string(self.getValue());
  998. });
  999. DEFPRINT(AST_Number, function(self, output){
  1000. output.print(make_num(self.getValue()));
  1001. });
  1002. DEFPRINT(AST_RegExp, function(self, output){
  1003. var str = self.getValue().toString();
  1004. if (output.option("ascii_only"))
  1005. str = output.to_ascii(str);
  1006. output.print(str);
  1007. var p = output.parent();
  1008. if (p instanceof AST_Binary && /^in/.test(p.operator) && p.left === self)
  1009. output.print(" ");
  1010. });
  1011. function force_statement(stat, output) {
  1012. if (output.option("bracketize")) {
  1013. if (!stat || stat instanceof AST_EmptyStatement)
  1014. output.print("{}");
  1015. else if (stat instanceof AST_BlockStatement)
  1016. stat.print(output);
  1017. else output.with_block(function(){
  1018. output.indent();
  1019. stat.print(output);
  1020. output.newline();
  1021. });
  1022. } else {
  1023. if (!stat || stat instanceof AST_EmptyStatement)
  1024. output.force_semicolon();
  1025. else
  1026. stat.print(output);
  1027. }
  1028. };
  1029. // return true if the node at the top of the stack (that means the
  1030. // innermost node in the current output) is lexically the first in
  1031. // a statement.
  1032. function first_in_statement(output) {
  1033. var a = output.stack(), i = a.length, node = a[--i], p = a[--i];
  1034. while (i > 0) {
  1035. if (p instanceof AST_Statement && p.body === node)
  1036. return true;
  1037. if ((p instanceof AST_Seq && p.car === node ) ||
  1038. (p instanceof AST_Call && p.expression === node && !(p instanceof AST_New) ) ||
  1039. (p instanceof AST_Dot && p.expression === node ) ||
  1040. (p instanceof AST_Sub && p.expression === node ) ||
  1041. (p instanceof AST_Conditional && p.condition === node ) ||
  1042. (p instanceof AST_Binary && p.left === node ) ||
  1043. (p instanceof AST_UnaryPostfix && p.expression === node ))
  1044. {
  1045. node = p;
  1046. p = a[--i];
  1047. } else {
  1048. return false;
  1049. }
  1050. }
  1051. };
  1052. // self should be AST_New. decide if we want to show parens or not.
  1053. function no_constructor_parens(self, output) {
  1054. return self.args.length == 0 && !output.option("beautify");
  1055. };
  1056. function best_of(a) {
  1057. var best = a[0], len = best.length;
  1058. for (var i = 1; i < a.length; ++i) {
  1059. if (a[i].length < len) {
  1060. best = a[i];
  1061. len = best.length;
  1062. }
  1063. }
  1064. return best;
  1065. };
  1066. function make_num(num) {
  1067. var str = num.toString(10), a = [ str.replace(/^0\./, ".").replace('e+', 'e') ], m;
  1068. if (Math.floor(num) === num) {
  1069. if (num >= 0) {
  1070. a.push("0x" + num.toString(16).toLowerCase(), // probably pointless
  1071. "0" + num.toString(8)); // same.
  1072. } else {
  1073. a.push("-0x" + (-num).toString(16).toLowerCase(), // probably pointless
  1074. "-0" + (-num).toString(8)); // same.
  1075. }
  1076. if ((m = /^(.*?)(0+)$/.exec(num))) {
  1077. a.push(m[1] + "e" + m[2].length);
  1078. }
  1079. } else if ((m = /^0?\.(0+)(.*)$/.exec(num))) {
  1080. a.push(m[2] + "e-" + (m[1].length + m[2].length),
  1081. str.substr(str.indexOf(".")));
  1082. }
  1083. return best_of(a);
  1084. };
  1085. function make_block(stmt, output) {
  1086. if (stmt instanceof AST_BlockStatement) {
  1087. stmt.print(output);
  1088. return;
  1089. }
  1090. output.with_block(function(){
  1091. output.indent();
  1092. stmt.print(output);
  1093. output.newline();
  1094. });
  1095. };
  1096. /* -----[ source map generators ]----- */
  1097. function DEFMAP(nodetype, generator) {
  1098. nodetype.DEFMETHOD("add_source_map", function(stream){
  1099. generator(this, stream);
  1100. });
  1101. };
  1102. // We could easily add info for ALL nodes, but it seems to me that
  1103. // would be quite wasteful, hence this noop in the base class.
  1104. DEFMAP(AST_Node, noop);
  1105. function basic_sourcemap_gen(self, output) {
  1106. output.add_mapping(self.start);
  1107. };
  1108. // XXX: I'm not exactly sure if we need it for all of these nodes,
  1109. // or if we should add even more.
  1110. DEFMAP(AST_Directive, basic_sourcemap_gen);
  1111. DEFMAP(AST_Debugger, basic_sourcemap_gen);
  1112. DEFMAP(AST_Symbol, basic_sourcemap_gen);
  1113. DEFMAP(AST_Jump, basic_sourcemap_gen);
  1114. DEFMAP(AST_StatementWithBody, basic_sourcemap_gen);
  1115. DEFMAP(AST_LabeledStatement, noop); // since the label symbol will mark it
  1116. DEFMAP(AST_Lambda, basic_sourcemap_gen);
  1117. DEFMAP(AST_Switch, basic_sourcemap_gen);
  1118. DEFMAP(AST_SwitchBranch, basic_sourcemap_gen);
  1119. DEFMAP(AST_BlockStatement, basic_sourcemap_gen);
  1120. DEFMAP(AST_Toplevel, noop);
  1121. DEFMAP(AST_New, basic_sourcemap_gen);
  1122. DEFMAP(AST_Try, basic_sourcemap_gen);
  1123. DEFMAP(AST_Catch, basic_sourcemap_gen);
  1124. DEFMAP(AST_Finally, basic_sourcemap_gen);
  1125. DEFMAP(AST_Definitions, basic_sourcemap_gen);
  1126. DEFMAP(AST_Constant, basic_sourcemap_gen);
  1127. DEFMAP(AST_ObjectProperty, function(self, output){
  1128. output.add_mapping(self.start, self.key);
  1129. });
  1130. })();