You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2626 lines
94 KiB

  1. /*
  2. Copyright (C) 2012-2014 Yusuke Suzuki <utatane.tea@gmail.com>
  3. Copyright (C) 2015 Ingvar Stepanyan <me@rreverser.com>
  4. Copyright (C) 2014 Ivan Nikulin <ifaaan@gmail.com>
  5. Copyright (C) 2012-2013 Michael Ficarra <escodegen.copyright@michael.ficarra.me>
  6. Copyright (C) 2012-2013 Mathias Bynens <mathias@qiwi.be>
  7. Copyright (C) 2013 Irakli Gozalishvili <rfobic@gmail.com>
  8. Copyright (C) 2012 Robert Gust-Bardon <donate@robert.gust-bardon.org>
  9. Copyright (C) 2012 John Freeman <jfreeman08@gmail.com>
  10. Copyright (C) 2011-2012 Ariya Hidayat <ariya.hidayat@gmail.com>
  11. Copyright (C) 2012 Joost-Wim Boekesteijn <joost-wim@boekesteijn.nl>
  12. Copyright (C) 2012 Kris Kowal <kris.kowal@cixar.com>
  13. Copyright (C) 2012 Arpad Borsos <arpad.borsos@googlemail.com>
  14. Redistribution and use in source and binary forms, with or without
  15. modification, are permitted provided that the following conditions are met:
  16. * Redistributions of source code must retain the above copyright
  17. notice, this list of conditions and the following disclaimer.
  18. * Redistributions in binary form must reproduce the above copyright
  19. notice, this list of conditions and the following disclaimer in the
  20. documentation and/or other materials provided with the distribution.
  21. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  22. AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  23. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  24. ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
  25. DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  26. (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  27. LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  28. ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  29. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  30. THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  31. */
  32. /*global exports:true, require:true, global:true*/
  33. (function () {
  34. 'use strict';
  35. var Syntax,
  36. Precedence,
  37. BinaryPrecedence,
  38. SourceNode,
  39. estraverse,
  40. esutils,
  41. base,
  42. indent,
  43. json,
  44. renumber,
  45. hexadecimal,
  46. quotes,
  47. escapeless,
  48. newline,
  49. space,
  50. parentheses,
  51. semicolons,
  52. safeConcatenation,
  53. directive,
  54. extra,
  55. parse,
  56. sourceMap,
  57. sourceCode,
  58. preserveBlankLines,
  59. FORMAT_MINIFY,
  60. FORMAT_DEFAULTS;
  61. estraverse = require('estraverse');
  62. esutils = require('esutils');
  63. Syntax = estraverse.Syntax;
  64. // Generation is done by generateExpression.
  65. function isExpression(node) {
  66. return CodeGenerator.Expression.hasOwnProperty(node.type);
  67. }
  68. // Generation is done by generateStatement.
  69. function isStatement(node) {
  70. return CodeGenerator.Statement.hasOwnProperty(node.type);
  71. }
  72. Precedence = {
  73. Sequence: 0,
  74. Yield: 1,
  75. Assignment: 1,
  76. Conditional: 2,
  77. ArrowFunction: 2,
  78. LogicalOR: 3,
  79. LogicalAND: 4,
  80. BitwiseOR: 5,
  81. BitwiseXOR: 6,
  82. BitwiseAND: 7,
  83. Equality: 8,
  84. Relational: 9,
  85. BitwiseSHIFT: 10,
  86. Additive: 11,
  87. Multiplicative: 12,
  88. Exponentiation: 13,
  89. Await: 14,
  90. Unary: 14,
  91. Postfix: 15,
  92. Call: 16,
  93. New: 17,
  94. TaggedTemplate: 18,
  95. Member: 19,
  96. Primary: 20
  97. };
  98. BinaryPrecedence = {
  99. '||': Precedence.LogicalOR,
  100. '&&': Precedence.LogicalAND,
  101. '|': Precedence.BitwiseOR,
  102. '^': Precedence.BitwiseXOR,
  103. '&': Precedence.BitwiseAND,
  104. '==': Precedence.Equality,
  105. '!=': Precedence.Equality,
  106. '===': Precedence.Equality,
  107. '!==': Precedence.Equality,
  108. 'is': Precedence.Equality,
  109. 'isnt': Precedence.Equality,
  110. '<': Precedence.Relational,
  111. '>': Precedence.Relational,
  112. '<=': Precedence.Relational,
  113. '>=': Precedence.Relational,
  114. 'in': Precedence.Relational,
  115. 'instanceof': Precedence.Relational,
  116. '<<': Precedence.BitwiseSHIFT,
  117. '>>': Precedence.BitwiseSHIFT,
  118. '>>>': Precedence.BitwiseSHIFT,
  119. '+': Precedence.Additive,
  120. '-': Precedence.Additive,
  121. '*': Precedence.Multiplicative,
  122. '%': Precedence.Multiplicative,
  123. '/': Precedence.Multiplicative,
  124. '**': Precedence.Exponentiation
  125. };
  126. //Flags
  127. var F_ALLOW_IN = 1,
  128. F_ALLOW_CALL = 1 << 1,
  129. F_ALLOW_UNPARATH_NEW = 1 << 2,
  130. F_FUNC_BODY = 1 << 3,
  131. F_DIRECTIVE_CTX = 1 << 4,
  132. F_SEMICOLON_OPT = 1 << 5;
  133. //Expression flag sets
  134. //NOTE: Flag order:
  135. // F_ALLOW_IN
  136. // F_ALLOW_CALL
  137. // F_ALLOW_UNPARATH_NEW
  138. var E_FTT = F_ALLOW_CALL | F_ALLOW_UNPARATH_NEW,
  139. E_TTF = F_ALLOW_IN | F_ALLOW_CALL,
  140. E_TTT = F_ALLOW_IN | F_ALLOW_CALL | F_ALLOW_UNPARATH_NEW,
  141. E_TFF = F_ALLOW_IN,
  142. E_FFT = F_ALLOW_UNPARATH_NEW,
  143. E_TFT = F_ALLOW_IN | F_ALLOW_UNPARATH_NEW;
  144. //Statement flag sets
  145. //NOTE: Flag order:
  146. // F_ALLOW_IN
  147. // F_FUNC_BODY
  148. // F_DIRECTIVE_CTX
  149. // F_SEMICOLON_OPT
  150. var S_TFFF = F_ALLOW_IN,
  151. S_TFFT = F_ALLOW_IN | F_SEMICOLON_OPT,
  152. S_FFFF = 0x00,
  153. S_TFTF = F_ALLOW_IN | F_DIRECTIVE_CTX,
  154. S_TTFF = F_ALLOW_IN | F_FUNC_BODY;
  155. function getDefaultOptions() {
  156. // default options
  157. return {
  158. indent: null,
  159. base: null,
  160. parse: null,
  161. comment: false,
  162. format: {
  163. indent: {
  164. style: ' ',
  165. base: 0,
  166. adjustMultilineComment: false
  167. },
  168. newline: '\n',
  169. space: ' ',
  170. json: false,
  171. renumber: false,
  172. hexadecimal: false,
  173. quotes: 'single',
  174. escapeless: false,
  175. compact: false,
  176. parentheses: true,
  177. semicolons: true,
  178. safeConcatenation: false,
  179. preserveBlankLines: false
  180. },
  181. moz: {
  182. comprehensionExpressionStartsWithAssignment: false,
  183. starlessGenerator: false
  184. },
  185. sourceMap: null,
  186. sourceMapRoot: null,
  187. sourceMapWithCode: false,
  188. directive: false,
  189. raw: true,
  190. verbatim: null,
  191. sourceCode: null
  192. };
  193. }
  194. function stringRepeat(str, num) {
  195. var result = '';
  196. for (num |= 0; num > 0; num >>>= 1, str += str) {
  197. if (num & 1) {
  198. result += str;
  199. }
  200. }
  201. return result;
  202. }
  203. function hasLineTerminator(str) {
  204. return (/[\r\n]/g).test(str);
  205. }
  206. function endsWithLineTerminator(str) {
  207. var len = str.length;
  208. return len && esutils.code.isLineTerminator(str.charCodeAt(len - 1));
  209. }
  210. function merge(target, override) {
  211. var key;
  212. for (key in override) {
  213. if (override.hasOwnProperty(key)) {
  214. target[key] = override[key];
  215. }
  216. }
  217. return target;
  218. }
  219. function updateDeeply(target, override) {
  220. var key, val;
  221. function isHashObject(target) {
  222. return typeof target === 'object' && target instanceof Object && !(target instanceof RegExp);
  223. }
  224. for (key in override) {
  225. if (override.hasOwnProperty(key)) {
  226. val = override[key];
  227. if (isHashObject(val)) {
  228. if (isHashObject(target[key])) {
  229. updateDeeply(target[key], val);
  230. } else {
  231. target[key] = updateDeeply({}, val);
  232. }
  233. } else {
  234. target[key] = val;
  235. }
  236. }
  237. }
  238. return target;
  239. }
  240. function generateNumber(value) {
  241. var result, point, temp, exponent, pos;
  242. if (value !== value) {
  243. throw new Error('Numeric literal whose value is NaN');
  244. }
  245. if (value < 0 || (value === 0 && 1 / value < 0)) {
  246. throw new Error('Numeric literal whose value is negative');
  247. }
  248. if (value === 1 / 0) {
  249. return json ? 'null' : renumber ? '1e400' : '1e+400';
  250. }
  251. result = '' + value;
  252. if (!renumber || result.length < 3) {
  253. return result;
  254. }
  255. point = result.indexOf('.');
  256. if (!json && result.charCodeAt(0) === 0x30 /* 0 */ && point === 1) {
  257. point = 0;
  258. result = result.slice(1);
  259. }
  260. temp = result;
  261. result = result.replace('e+', 'e');
  262. exponent = 0;
  263. if ((pos = temp.indexOf('e')) > 0) {
  264. exponent = +temp.slice(pos + 1);
  265. temp = temp.slice(0, pos);
  266. }
  267. if (point >= 0) {
  268. exponent -= temp.length - point - 1;
  269. temp = +(temp.slice(0, point) + temp.slice(point + 1)) + '';
  270. }
  271. pos = 0;
  272. while (temp.charCodeAt(temp.length + pos - 1) === 0x30 /* 0 */) {
  273. --pos;
  274. }
  275. if (pos !== 0) {
  276. exponent -= pos;
  277. temp = temp.slice(0, pos);
  278. }
  279. if (exponent !== 0) {
  280. temp += 'e' + exponent;
  281. }
  282. if ((temp.length < result.length ||
  283. (hexadecimal && value > 1e12 && Math.floor(value) === value && (temp = '0x' + value.toString(16)).length < result.length)) &&
  284. +temp === value) {
  285. result = temp;
  286. }
  287. return result;
  288. }
  289. // Generate valid RegExp expression.
  290. // This function is based on https://github.com/Constellation/iv Engine
  291. function escapeRegExpCharacter(ch, previousIsBackslash) {
  292. // not handling '\' and handling \u2028 or \u2029 to unicode escape sequence
  293. if ((ch & ~1) === 0x2028) {
  294. return (previousIsBackslash ? 'u' : '\\u') + ((ch === 0x2028) ? '2028' : '2029');
  295. } else if (ch === 10 || ch === 13) { // \n, \r
  296. return (previousIsBackslash ? '' : '\\') + ((ch === 10) ? 'n' : 'r');
  297. }
  298. return String.fromCharCode(ch);
  299. }
  300. function generateRegExp(reg) {
  301. var match, result, flags, i, iz, ch, characterInBrack, previousIsBackslash;
  302. result = reg.toString();
  303. if (reg.source) {
  304. // extract flag from toString result
  305. match = result.match(/\/([^/]*)$/);
  306. if (!match) {
  307. return result;
  308. }
  309. flags = match[1];
  310. result = '';
  311. characterInBrack = false;
  312. previousIsBackslash = false;
  313. for (i = 0, iz = reg.source.length; i < iz; ++i) {
  314. ch = reg.source.charCodeAt(i);
  315. if (!previousIsBackslash) {
  316. if (characterInBrack) {
  317. if (ch === 93) { // ]
  318. characterInBrack = false;
  319. }
  320. } else {
  321. if (ch === 47) { // /
  322. result += '\\';
  323. } else if (ch === 91) { // [
  324. characterInBrack = true;
  325. }
  326. }
  327. result += escapeRegExpCharacter(ch, previousIsBackslash);
  328. previousIsBackslash = ch === 92; // \
  329. } else {
  330. // if new RegExp("\\\n') is provided, create /\n/
  331. result += escapeRegExpCharacter(ch, previousIsBackslash);
  332. // prevent like /\\[/]/
  333. previousIsBackslash = false;
  334. }
  335. }
  336. return '/' + result + '/' + flags;
  337. }
  338. return result;
  339. }
  340. function escapeAllowedCharacter(code, next) {
  341. var hex;
  342. if (code === 0x08 /* \b */) {
  343. return '\\b';
  344. }
  345. if (code === 0x0C /* \f */) {
  346. return '\\f';
  347. }
  348. if (code === 0x09 /* \t */) {
  349. return '\\t';
  350. }
  351. hex = code.toString(16).toUpperCase();
  352. if (json || code > 0xFF) {
  353. return '\\u' + '0000'.slice(hex.length) + hex;
  354. } else if (code === 0x0000 && !esutils.code.isDecimalDigit(next)) {
  355. return '\\0';
  356. } else if (code === 0x000B /* \v */) { // '\v'
  357. return '\\x0B';
  358. } else {
  359. return '\\x' + '00'.slice(hex.length) + hex;
  360. }
  361. }
  362. function escapeDisallowedCharacter(code) {
  363. if (code === 0x5C /* \ */) {
  364. return '\\\\';
  365. }
  366. if (code === 0x0A /* \n */) {
  367. return '\\n';
  368. }
  369. if (code === 0x0D /* \r */) {
  370. return '\\r';
  371. }
  372. if (code === 0x2028) {
  373. return '\\u2028';
  374. }
  375. if (code === 0x2029) {
  376. return '\\u2029';
  377. }
  378. throw new Error('Incorrectly classified character');
  379. }
  380. function escapeDirective(str) {
  381. var i, iz, code, quote;
  382. quote = quotes === 'double' ? '"' : '\'';
  383. for (i = 0, iz = str.length; i < iz; ++i) {
  384. code = str.charCodeAt(i);
  385. if (code === 0x27 /* ' */) {
  386. quote = '"';
  387. break;
  388. } else if (code === 0x22 /* " */) {
  389. quote = '\'';
  390. break;
  391. } else if (code === 0x5C /* \ */) {
  392. ++i;
  393. }
  394. }
  395. return quote + str + quote;
  396. }
  397. function escapeString(str) {
  398. var result = '', i, len, code, singleQuotes = 0, doubleQuotes = 0, single, quote;
  399. for (i = 0, len = str.length; i < len; ++i) {
  400. code = str.charCodeAt(i);
  401. if (code === 0x27 /* ' */) {
  402. ++singleQuotes;
  403. } else if (code === 0x22 /* " */) {
  404. ++doubleQuotes;
  405. } else if (code === 0x2F /* / */ && json) {
  406. result += '\\';
  407. } else if (esutils.code.isLineTerminator(code) || code === 0x5C /* \ */) {
  408. result += escapeDisallowedCharacter(code);
  409. continue;
  410. } else if (!esutils.code.isIdentifierPartES5(code) && (json && code < 0x20 /* SP */ || !json && !escapeless && (code < 0x20 /* SP */ || code > 0x7E /* ~ */))) {
  411. result += escapeAllowedCharacter(code, str.charCodeAt(i + 1));
  412. continue;
  413. }
  414. result += String.fromCharCode(code);
  415. }
  416. single = !(quotes === 'double' || (quotes === 'auto' && doubleQuotes < singleQuotes));
  417. quote = single ? '\'' : '"';
  418. if (!(single ? singleQuotes : doubleQuotes)) {
  419. return quote + result + quote;
  420. }
  421. str = result;
  422. result = quote;
  423. for (i = 0, len = str.length; i < len; ++i) {
  424. code = str.charCodeAt(i);
  425. if ((code === 0x27 /* ' */ && single) || (code === 0x22 /* " */ && !single)) {
  426. result += '\\';
  427. }
  428. result += String.fromCharCode(code);
  429. }
  430. return result + quote;
  431. }
  432. /**
  433. * flatten an array to a string, where the array can contain
  434. * either strings or nested arrays
  435. */
  436. function flattenToString(arr) {
  437. var i, iz, elem, result = '';
  438. for (i = 0, iz = arr.length; i < iz; ++i) {
  439. elem = arr[i];
  440. result += Array.isArray(elem) ? flattenToString(elem) : elem;
  441. }
  442. return result;
  443. }
  444. /**
  445. * convert generated to a SourceNode when source maps are enabled.
  446. */
  447. function toSourceNodeWhenNeeded(generated, node) {
  448. if (!sourceMap) {
  449. // with no source maps, generated is either an
  450. // array or a string. if an array, flatten it.
  451. // if a string, just return it
  452. if (Array.isArray(generated)) {
  453. return flattenToString(generated);
  454. } else {
  455. return generated;
  456. }
  457. }
  458. if (node == null) {
  459. if (generated instanceof SourceNode) {
  460. return generated;
  461. } else {
  462. node = {};
  463. }
  464. }
  465. if (node.loc == null) {
  466. return new SourceNode(null, null, sourceMap, generated, node.name || null);
  467. }
  468. return new SourceNode(node.loc.start.line, node.loc.start.column, (sourceMap === true ? node.loc.source || null : sourceMap), generated, node.name || null);
  469. }
  470. function noEmptySpace() {
  471. return (space) ? space : ' ';
  472. }
  473. function join(left, right) {
  474. var leftSource,
  475. rightSource,
  476. leftCharCode,
  477. rightCharCode;
  478. leftSource = toSourceNodeWhenNeeded(left).toString();
  479. if (leftSource.length === 0) {
  480. return [right];
  481. }
  482. rightSource = toSourceNodeWhenNeeded(right).toString();
  483. if (rightSource.length === 0) {
  484. return [left];
  485. }
  486. leftCharCode = leftSource.charCodeAt(leftSource.length - 1);
  487. rightCharCode = rightSource.charCodeAt(0);
  488. if ((leftCharCode === 0x2B /* + */ || leftCharCode === 0x2D /* - */) && leftCharCode === rightCharCode ||
  489. esutils.code.isIdentifierPartES5(leftCharCode) && esutils.code.isIdentifierPartES5(rightCharCode) ||
  490. leftCharCode === 0x2F /* / */ && rightCharCode === 0x69 /* i */) { // infix word operators all start with `i`
  491. return [left, noEmptySpace(), right];
  492. } else if (esutils.code.isWhiteSpace(leftCharCode) || esutils.code.isLineTerminator(leftCharCode) ||
  493. esutils.code.isWhiteSpace(rightCharCode) || esutils.code.isLineTerminator(rightCharCode)) {
  494. return [left, right];
  495. }
  496. return [left, space, right];
  497. }
  498. function addIndent(stmt) {
  499. return [base, stmt];
  500. }
  501. function withIndent(fn) {
  502. var previousBase;
  503. previousBase = base;
  504. base += indent;
  505. fn(base);
  506. base = previousBase;
  507. }
  508. function calculateSpaces(str) {
  509. var i;
  510. for (i = str.length - 1; i >= 0; --i) {
  511. if (esutils.code.isLineTerminator(str.charCodeAt(i))) {
  512. break;
  513. }
  514. }
  515. return (str.length - 1) - i;
  516. }
  517. function adjustMultilineComment(value, specialBase) {
  518. var array, i, len, line, j, spaces, previousBase, sn;
  519. array = value.split(/\r\n|[\r\n]/);
  520. spaces = Number.MAX_VALUE;
  521. // first line doesn't have indentation
  522. for (i = 1, len = array.length; i < len; ++i) {
  523. line = array[i];
  524. j = 0;
  525. while (j < line.length && esutils.code.isWhiteSpace(line.charCodeAt(j))) {
  526. ++j;
  527. }
  528. if (spaces > j) {
  529. spaces = j;
  530. }
  531. }
  532. if (typeof specialBase !== 'undefined') {
  533. // pattern like
  534. // {
  535. // var t = 20; /*
  536. // * this is comment
  537. // */
  538. // }
  539. previousBase = base;
  540. if (array[1][spaces] === '*') {
  541. specialBase += ' ';
  542. }
  543. base = specialBase;
  544. } else {
  545. if (spaces & 1) {
  546. // /*
  547. // *
  548. // */
  549. // If spaces are odd number, above pattern is considered.
  550. // We waste 1 space.
  551. --spaces;
  552. }
  553. previousBase = base;
  554. }
  555. for (i = 1, len = array.length; i < len; ++i) {
  556. sn = toSourceNodeWhenNeeded(addIndent(array[i].slice(spaces)));
  557. array[i] = sourceMap ? sn.join('') : sn;
  558. }
  559. base = previousBase;
  560. return array.join('\n');
  561. }
  562. function generateComment(comment, specialBase) {
  563. if (comment.type === 'Line') {
  564. if (endsWithLineTerminator(comment.value)) {
  565. return '//' + comment.value;
  566. } else {
  567. // Always use LineTerminator
  568. var result = '//' + comment.value;
  569. if (!preserveBlankLines) {
  570. result += '\n';
  571. }
  572. return result;
  573. }
  574. }
  575. if (extra.format.indent.adjustMultilineComment && /[\n\r]/.test(comment.value)) {
  576. return adjustMultilineComment('/*' + comment.value + '*/', specialBase);
  577. }
  578. return '/*' + comment.value + '*/';
  579. }
  580. function addComments(stmt, result) {
  581. var i, len, comment, save, tailingToStatement, specialBase, fragment,
  582. extRange, range, prevRange, prefix, infix, suffix, count;
  583. if (stmt.leadingComments && stmt.leadingComments.length > 0) {
  584. save = result;
  585. if (preserveBlankLines) {
  586. comment = stmt.leadingComments[0];
  587. result = [];
  588. extRange = comment.extendedRange;
  589. range = comment.range;
  590. prefix = sourceCode.substring(extRange[0], range[0]);
  591. count = (prefix.match(/\n/g) || []).length;
  592. if (count > 0) {
  593. result.push(stringRepeat('\n', count));
  594. result.push(addIndent(generateComment(comment)));
  595. } else {
  596. result.push(prefix);
  597. result.push(generateComment(comment));
  598. }
  599. prevRange = range;
  600. for (i = 1, len = stmt.leadingComments.length; i < len; i++) {
  601. comment = stmt.leadingComments[i];
  602. range = comment.range;
  603. infix = sourceCode.substring(prevRange[1], range[0]);
  604. count = (infix.match(/\n/g) || []).length;
  605. result.push(stringRepeat('\n', count));
  606. result.push(addIndent(generateComment(comment)));
  607. prevRange = range;
  608. }
  609. suffix = sourceCode.substring(range[1], extRange[1]);
  610. count = (suffix.match(/\n/g) || []).length;
  611. result.push(stringRepeat('\n', count));
  612. } else {
  613. comment = stmt.leadingComments[0];
  614. result = [];
  615. if (safeConcatenation && stmt.type === Syntax.Program && stmt.body.length === 0) {
  616. result.push('\n');
  617. }
  618. result.push(generateComment(comment));
  619. if (!endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString())) {
  620. result.push('\n');
  621. }
  622. for (i = 1, len = stmt.leadingComments.length; i < len; ++i) {
  623. comment = stmt.leadingComments[i];
  624. fragment = [generateComment(comment)];
  625. if (!endsWithLineTerminator(toSourceNodeWhenNeeded(fragment).toString())) {
  626. fragment.push('\n');
  627. }
  628. result.push(addIndent(fragment));
  629. }
  630. }
  631. result.push(addIndent(save));
  632. }
  633. if (stmt.trailingComments) {
  634. if (preserveBlankLines) {
  635. comment = stmt.trailingComments[0];
  636. extRange = comment.extendedRange;
  637. range = comment.range;
  638. prefix = sourceCode.substring(extRange[0], range[0]);
  639. count = (prefix.match(/\n/g) || []).length;
  640. if (count > 0) {
  641. result.push(stringRepeat('\n', count));
  642. result.push(addIndent(generateComment(comment)));
  643. } else {
  644. result.push(prefix);
  645. result.push(generateComment(comment));
  646. }
  647. } else {
  648. tailingToStatement = !endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString());
  649. specialBase = stringRepeat(' ', calculateSpaces(toSourceNodeWhenNeeded([base, result, indent]).toString()));
  650. for (i = 0, len = stmt.trailingComments.length; i < len; ++i) {
  651. comment = stmt.trailingComments[i];
  652. if (tailingToStatement) {
  653. // We assume target like following script
  654. //
  655. // var t = 20; /**
  656. // * This is comment of t
  657. // */
  658. if (i === 0) {
  659. // first case
  660. result = [result, indent];
  661. } else {
  662. result = [result, specialBase];
  663. }
  664. result.push(generateComment(comment, specialBase));
  665. } else {
  666. result = [result, addIndent(generateComment(comment))];
  667. }
  668. if (i !== len - 1 && !endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString())) {
  669. result = [result, '\n'];
  670. }
  671. }
  672. }
  673. }
  674. return result;
  675. }
  676. function generateBlankLines(start, end, result) {
  677. var j, newlineCount = 0;
  678. for (j = start; j < end; j++) {
  679. if (sourceCode[j] === '\n') {
  680. newlineCount++;
  681. }
  682. }
  683. for (j = 1; j < newlineCount; j++) {
  684. result.push(newline);
  685. }
  686. }
  687. function parenthesize(text, current, should) {
  688. if (current < should) {
  689. return ['(', text, ')'];
  690. }
  691. return text;
  692. }
  693. function generateVerbatimString(string) {
  694. var i, iz, result;
  695. result = string.split(/\r\n|\n/);
  696. for (i = 1, iz = result.length; i < iz; i++) {
  697. result[i] = newline + base + result[i];
  698. }
  699. return result;
  700. }
  701. function generateVerbatim(expr, precedence) {
  702. var verbatim, result, prec;
  703. verbatim = expr[extra.verbatim];
  704. if (typeof verbatim === 'string') {
  705. result = parenthesize(generateVerbatimString(verbatim), Precedence.Sequence, precedence);
  706. } else {
  707. // verbatim is object
  708. result = generateVerbatimString(verbatim.content);
  709. prec = (verbatim.precedence != null) ? verbatim.precedence : Precedence.Sequence;
  710. result = parenthesize(result, prec, precedence);
  711. }
  712. return toSourceNodeWhenNeeded(result, expr);
  713. }
  714. function CodeGenerator() {
  715. }
  716. // Helpers.
  717. CodeGenerator.prototype.maybeBlock = function(stmt, flags) {
  718. var result, noLeadingComment, that = this;
  719. noLeadingComment = !extra.comment || !stmt.leadingComments;
  720. if (stmt.type === Syntax.BlockStatement && noLeadingComment) {
  721. return [space, this.generateStatement(stmt, flags)];
  722. }
  723. if (stmt.type === Syntax.EmptyStatement && noLeadingComment) {
  724. return ';';
  725. }
  726. withIndent(function () {
  727. result = [
  728. newline,
  729. addIndent(that.generateStatement(stmt, flags))
  730. ];
  731. });
  732. return result;
  733. };
  734. CodeGenerator.prototype.maybeBlockSuffix = function (stmt, result) {
  735. var ends = endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString());
  736. if (stmt.type === Syntax.BlockStatement && (!extra.comment || !stmt.leadingComments) && !ends) {
  737. return [result, space];
  738. }
  739. if (ends) {
  740. return [result, base];
  741. }
  742. return [result, newline, base];
  743. };
  744. function generateIdentifier(node) {
  745. return toSourceNodeWhenNeeded(node.name, node);
  746. }
  747. function generateAsyncPrefix(node, spaceRequired) {
  748. return node.async ? 'async' + (spaceRequired ? noEmptySpace() : space) : '';
  749. }
  750. function generateStarSuffix(node) {
  751. var isGenerator = node.generator && !extra.moz.starlessGenerator;
  752. return isGenerator ? '*' + space : '';
  753. }
  754. function generateMethodPrefix(prop) {
  755. var func = prop.value, prefix = '';
  756. if (func.async) {
  757. prefix += generateAsyncPrefix(func, !prop.computed);
  758. }
  759. if (func.generator) {
  760. // avoid space before method name
  761. prefix += generateStarSuffix(func) ? '*' : '';
  762. }
  763. return prefix;
  764. }
  765. CodeGenerator.prototype.generatePattern = function (node, precedence, flags) {
  766. if (node.type === Syntax.Identifier) {
  767. return generateIdentifier(node);
  768. }
  769. return this.generateExpression(node, precedence, flags);
  770. };
  771. CodeGenerator.prototype.generateFunctionParams = function (node) {
  772. var i, iz, result, hasDefault;
  773. hasDefault = false;
  774. if (node.type === Syntax.ArrowFunctionExpression &&
  775. !node.rest && (!node.defaults || node.defaults.length === 0) &&
  776. node.params.length === 1 && node.params[0].type === Syntax.Identifier) {
  777. // arg => { } case
  778. result = [generateAsyncPrefix(node, true), generateIdentifier(node.params[0])];
  779. } else {
  780. result = node.type === Syntax.ArrowFunctionExpression ? [generateAsyncPrefix(node, false)] : [];
  781. result.push('(');
  782. if (node.defaults) {
  783. hasDefault = true;
  784. }
  785. for (i = 0, iz = node.params.length; i < iz; ++i) {
  786. if (hasDefault && node.defaults[i]) {
  787. // Handle default values.
  788. result.push(this.generateAssignment(node.params[i], node.defaults[i], '=', Precedence.Assignment, E_TTT));
  789. } else {
  790. result.push(this.generatePattern(node.params[i], Precedence.Assignment, E_TTT));
  791. }
  792. if (i + 1 < iz) {
  793. result.push(',' + space);
  794. }
  795. }
  796. if (node.rest) {
  797. if (node.params.length) {
  798. result.push(',' + space);
  799. }
  800. result.push('...');
  801. result.push(generateIdentifier(node.rest));
  802. }
  803. result.push(')');
  804. }
  805. return result;
  806. };
  807. CodeGenerator.prototype.generateFunctionBody = function (node) {
  808. var result, expr;
  809. result = this.generateFunctionParams(node);
  810. if (node.type === Syntax.ArrowFunctionExpression) {
  811. result.push(space);
  812. result.push('=>');
  813. }
  814. if (node.expression) {
  815. result.push(space);
  816. expr = this.generateExpression(node.body, Precedence.Assignment, E_TTT);
  817. if (expr.toString().charAt(0) === '{') {
  818. expr = ['(', expr, ')'];
  819. }
  820. result.push(expr);
  821. } else {
  822. result.push(this.maybeBlock(node.body, S_TTFF));
  823. }
  824. return result;
  825. };
  826. CodeGenerator.prototype.generateIterationForStatement = function (operator, stmt, flags) {
  827. var result = ['for' + (stmt.await ? noEmptySpace() + 'await' : '') + space + '('], that = this;
  828. withIndent(function () {
  829. if (stmt.left.type === Syntax.VariableDeclaration) {
  830. withIndent(function () {
  831. result.push(stmt.left.kind + noEmptySpace());
  832. result.push(that.generateStatement(stmt.left.declarations[0], S_FFFF));
  833. });
  834. } else {
  835. result.push(that.generateExpression(stmt.left, Precedence.Call, E_TTT));
  836. }
  837. result = join(result, operator);
  838. result = [join(
  839. result,
  840. that.generateExpression(stmt.right, Precedence.Assignment, E_TTT)
  841. ), ')'];
  842. });
  843. result.push(this.maybeBlock(stmt.body, flags));
  844. return result;
  845. };
  846. CodeGenerator.prototype.generatePropertyKey = function (expr, computed) {
  847. var result = [];
  848. if (computed) {
  849. result.push('[');
  850. }
  851. result.push(this.generateExpression(expr, Precedence.Assignment, E_TTT));
  852. if (computed) {
  853. result.push(']');
  854. }
  855. return result;
  856. };
  857. CodeGenerator.prototype.generateAssignment = function (left, right, operator, precedence, flags) {
  858. if (Precedence.Assignment < precedence) {
  859. flags |= F_ALLOW_IN;
  860. }
  861. return parenthesize(
  862. [
  863. this.generateExpression(left, Precedence.Call, flags),
  864. space + operator + space,
  865. this.generateExpression(right, Precedence.Assignment, flags)
  866. ],
  867. Precedence.Assignment,
  868. precedence
  869. );
  870. };
  871. CodeGenerator.prototype.semicolon = function (flags) {
  872. if (!semicolons && flags & F_SEMICOLON_OPT) {
  873. return '';
  874. }
  875. return ';';
  876. };
  877. // Statements.
  878. CodeGenerator.Statement = {
  879. BlockStatement: function (stmt, flags) {
  880. var range, content, result = ['{', newline], that = this;
  881. withIndent(function () {
  882. // handle functions without any code
  883. if (stmt.body.length === 0 && preserveBlankLines) {
  884. range = stmt.range;
  885. if (range[1] - range[0] > 2) {
  886. content = sourceCode.substring(range[0] + 1, range[1] - 1);
  887. if (content[0] === '\n') {
  888. result = ['{'];
  889. }
  890. result.push(content);
  891. }
  892. }
  893. var i, iz, fragment, bodyFlags;
  894. bodyFlags = S_TFFF;
  895. if (flags & F_FUNC_BODY) {
  896. bodyFlags |= F_DIRECTIVE_CTX;
  897. }
  898. for (i = 0, iz = stmt.body.length; i < iz; ++i) {
  899. if (preserveBlankLines) {
  900. // handle spaces before the first line
  901. if (i === 0) {
  902. if (stmt.body[0].leadingComments) {
  903. range = stmt.body[0].leadingComments[0].extendedRange;
  904. content = sourceCode.substring(range[0], range[1]);
  905. if (content[0] === '\n') {
  906. result = ['{'];
  907. }
  908. }
  909. if (!stmt.body[0].leadingComments) {
  910. generateBlankLines(stmt.range[0], stmt.body[0].range[0], result);
  911. }
  912. }
  913. // handle spaces between lines
  914. if (i > 0) {
  915. if (!stmt.body[i - 1].trailingComments && !stmt.body[i].leadingComments) {
  916. generateBlankLines(stmt.body[i - 1].range[1], stmt.body[i].range[0], result);
  917. }
  918. }
  919. }
  920. if (i === iz - 1) {
  921. bodyFlags |= F_SEMICOLON_OPT;
  922. }
  923. if (stmt.body[i].leadingComments && preserveBlankLines) {
  924. fragment = that.generateStatement(stmt.body[i], bodyFlags);
  925. } else {
  926. fragment = addIndent(that.generateStatement(stmt.body[i], bodyFlags));
  927. }
  928. result.push(fragment);
  929. if (!endsWithLineTerminator(toSourceNodeWhenNeeded(fragment).toString())) {
  930. if (preserveBlankLines && i < iz - 1) {
  931. // don't add a new line if there are leading coments
  932. // in the next statement
  933. if (!stmt.body[i + 1].leadingComments) {
  934. result.push(newline);
  935. }
  936. } else {
  937. result.push(newline);
  938. }
  939. }
  940. if (preserveBlankLines) {
  941. // handle spaces after the last line
  942. if (i === iz - 1) {
  943. if (!stmt.body[i].trailingComments) {
  944. generateBlankLines(stmt.body[i].range[1], stmt.range[1], result);
  945. }
  946. }
  947. }
  948. }
  949. });
  950. result.push(addIndent('}'));
  951. return result;
  952. },
  953. BreakStatement: function (stmt, flags) {
  954. if (stmt.label) {
  955. return 'break ' + stmt.label.name + this.semicolon(flags);
  956. }
  957. return 'break' + this.semicolon(flags);
  958. },
  959. ContinueStatement: function (stmt, flags) {
  960. if (stmt.label) {
  961. return 'continue ' + stmt.label.name + this.semicolon(flags);
  962. }
  963. return 'continue' + this.semicolon(flags);
  964. },
  965. ClassBody: function (stmt, flags) {
  966. var result = [ '{', newline], that = this;
  967. withIndent(function (indent) {
  968. var i, iz;
  969. for (i = 0, iz = stmt.body.length; i < iz; ++i) {
  970. result.push(indent);
  971. result.push(that.generateExpression(stmt.body[i], Precedence.Sequence, E_TTT));
  972. if (i + 1 < iz) {
  973. result.push(newline);
  974. }
  975. }
  976. });
  977. if (!endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString())) {
  978. result.push(newline);
  979. }
  980. result.push(base);
  981. result.push('}');
  982. return result;
  983. },
  984. ClassDeclaration: function (stmt, flags) {
  985. var result, fragment;
  986. result = ['class'];
  987. if (stmt.id) {
  988. result = join(result, this.generateExpression(stmt.id, Precedence.Sequence, E_TTT));
  989. }
  990. if (stmt.superClass) {
  991. fragment = join('extends', this.generateExpression(stmt.superClass, Precedence.Unary, E_TTT));
  992. result = join(result, fragment);
  993. }
  994. result.push(space);
  995. result.push(this.generateStatement(stmt.body, S_TFFT));
  996. return result;
  997. },
  998. DirectiveStatement: function (stmt, flags) {
  999. if (extra.raw && stmt.raw) {
  1000. return stmt.raw + this.semicolon(flags);
  1001. }
  1002. return escapeDirective(stmt.directive) + this.semicolon(flags);
  1003. },
  1004. DoWhileStatement: function (stmt, flags) {
  1005. // Because `do 42 while (cond)` is Syntax Error. We need semicolon.
  1006. var result = join('do', this.maybeBlock(stmt.body, S_TFFF));
  1007. result = this.maybeBlockSuffix(stmt.body, result);
  1008. return join(result, [
  1009. 'while' + space + '(',
  1010. this.generateExpression(stmt.test, Precedence.Sequence, E_TTT),
  1011. ')' + this.semicolon(flags)
  1012. ]);
  1013. },
  1014. CatchClause: function (stmt, flags) {
  1015. var result, that = this;
  1016. withIndent(function () {
  1017. var guard;
  1018. if (stmt.param) {
  1019. result = [
  1020. 'catch' + space + '(',
  1021. that.generateExpression(stmt.param, Precedence.Sequence, E_TTT),
  1022. ')'
  1023. ];
  1024. if (stmt.guard) {
  1025. guard = that.generateExpression(stmt.guard, Precedence.Sequence, E_TTT);
  1026. result.splice(2, 0, ' if ', guard);
  1027. }
  1028. } else {
  1029. result = ['catch'];
  1030. }
  1031. });
  1032. result.push(this.maybeBlock(stmt.body, S_TFFF));
  1033. return result;
  1034. },
  1035. DebuggerStatement: function (stmt, flags) {
  1036. return 'debugger' + this.semicolon(flags);
  1037. },
  1038. EmptyStatement: function (stmt, flags) {
  1039. return ';';
  1040. },
  1041. ExportDefaultDeclaration: function (stmt, flags) {
  1042. var result = [ 'export' ], bodyFlags;
  1043. bodyFlags = (flags & F_SEMICOLON_OPT) ? S_TFFT : S_TFFF;
  1044. // export default HoistableDeclaration[Default]
  1045. // export default AssignmentExpression[In] ;
  1046. result = join(result, 'default');
  1047. if (isStatement(stmt.declaration)) {
  1048. result = join(result, this.generateStatement(stmt.declaration, bodyFlags));
  1049. } else {
  1050. result = join(result, this.generateExpression(stmt.declaration, Precedence.Assignment, E_TTT) + this.semicolon(flags));
  1051. }
  1052. return result;
  1053. },
  1054. ExportNamedDeclaration: function (stmt, flags) {
  1055. var result = [ 'export' ], bodyFlags, that = this;
  1056. bodyFlags = (flags & F_SEMICOLON_OPT) ? S_TFFT : S_TFFF;
  1057. // export VariableStatement
  1058. // export Declaration[Default]
  1059. if (stmt.declaration) {
  1060. return join(result, this.generateStatement(stmt.declaration, bodyFlags));
  1061. }
  1062. // export ExportClause[NoReference] FromClause ;
  1063. // export ExportClause ;
  1064. if (stmt.specifiers) {
  1065. if (stmt.specifiers.length === 0) {
  1066. result = join(result, '{' + space + '}');
  1067. } else if (stmt.specifiers[0].type === Syntax.ExportBatchSpecifier) {
  1068. result = join(result, this.generateExpression(stmt.specifiers[0], Precedence.Sequence, E_TTT));
  1069. } else {
  1070. result = join(result, '{');
  1071. withIndent(function (indent) {
  1072. var i, iz;
  1073. result.push(newline);
  1074. for (i = 0, iz = stmt.specifiers.length; i < iz; ++i) {
  1075. result.push(indent);
  1076. result.push(that.generateExpression(stmt.specifiers[i], Precedence.Sequence, E_TTT));
  1077. if (i + 1 < iz) {
  1078. result.push(',' + newline);
  1079. }
  1080. }
  1081. });
  1082. if (!endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString())) {
  1083. result.push(newline);
  1084. }
  1085. result.push(base + '}');
  1086. }
  1087. if (stmt.source) {
  1088. result = join(result, [
  1089. 'from' + space,
  1090. // ModuleSpecifier
  1091. this.generateExpression(stmt.source, Precedence.Sequence, E_TTT),
  1092. this.semicolon(flags)
  1093. ]);
  1094. } else {
  1095. result.push(this.semicolon(flags));
  1096. }
  1097. }
  1098. return result;
  1099. },
  1100. ExportAllDeclaration: function (stmt, flags) {
  1101. // export * FromClause ;
  1102. return [
  1103. 'export' + space,
  1104. '*' + space,
  1105. 'from' + space,
  1106. // ModuleSpecifier
  1107. this.generateExpression(stmt.source, Precedence.Sequence, E_TTT),
  1108. this.semicolon(flags)
  1109. ];
  1110. },
  1111. ExpressionStatement: function (stmt, flags) {
  1112. var result, fragment;
  1113. function isClassPrefixed(fragment) {
  1114. var code;
  1115. if (fragment.slice(0, 5) !== 'class') {
  1116. return false;
  1117. }
  1118. code = fragment.charCodeAt(5);
  1119. return code === 0x7B /* '{' */ || esutils.code.isWhiteSpace(code) || esutils.code.isLineTerminator(code);
  1120. }
  1121. function isFunctionPrefixed(fragment) {
  1122. var code;
  1123. if (fragment.slice(0, 8) !== 'function') {
  1124. return false;
  1125. }
  1126. code = fragment.charCodeAt(8);
  1127. return code === 0x28 /* '(' */ || esutils.code.isWhiteSpace(code) || code === 0x2A /* '*' */ || esutils.code.isLineTerminator(code);
  1128. }
  1129. function isAsyncPrefixed(fragment) {
  1130. var code, i, iz;
  1131. if (fragment.slice(0, 5) !== 'async') {
  1132. return false;
  1133. }
  1134. if (!esutils.code.isWhiteSpace(fragment.charCodeAt(5))) {
  1135. return false;
  1136. }
  1137. for (i = 6, iz = fragment.length; i < iz; ++i) {
  1138. if (!esutils.code.isWhiteSpace(fragment.charCodeAt(i))) {
  1139. break;
  1140. }
  1141. }
  1142. if (i === iz) {
  1143. return false;
  1144. }
  1145. if (fragment.slice(i, i + 8) !== 'function') {
  1146. return false;
  1147. }
  1148. code = fragment.charCodeAt(i + 8);
  1149. return code === 0x28 /* '(' */ || esutils.code.isWhiteSpace(code) || code === 0x2A /* '*' */ || esutils.code.isLineTerminator(code);
  1150. }
  1151. result = [this.generateExpression(stmt.expression, Precedence.Sequence, E_TTT)];
  1152. // 12.4 '{', 'function', 'class' is not allowed in this position.
  1153. // wrap expression with parentheses
  1154. fragment = toSourceNodeWhenNeeded(result).toString();
  1155. if (fragment.charCodeAt(0) === 0x7B /* '{' */ || // ObjectExpression
  1156. isClassPrefixed(fragment) ||
  1157. isFunctionPrefixed(fragment) ||
  1158. isAsyncPrefixed(fragment) ||
  1159. (directive && (flags & F_DIRECTIVE_CTX) && stmt.expression.type === Syntax.Literal && typeof stmt.expression.value === 'string')) {
  1160. result = ['(', result, ')' + this.semicolon(flags)];
  1161. } else {
  1162. result.push(this.semicolon(flags));
  1163. }
  1164. return result;
  1165. },
  1166. ImportDeclaration: function (stmt, flags) {
  1167. // ES6: 15.2.1 valid import declarations:
  1168. // - import ImportClause FromClause ;
  1169. // - import ModuleSpecifier ;
  1170. var result, cursor, that = this;
  1171. // If no ImportClause is present,
  1172. // this should be `import ModuleSpecifier` so skip `from`
  1173. // ModuleSpecifier is StringLiteral.
  1174. if (stmt.specifiers.length === 0) {
  1175. // import ModuleSpecifier ;
  1176. return [
  1177. 'import',
  1178. space,
  1179. // ModuleSpecifier
  1180. this.generateExpression(stmt.source, Precedence.Sequence, E_TTT),
  1181. this.semicolon(flags)
  1182. ];
  1183. }
  1184. // import ImportClause FromClause ;
  1185. result = [
  1186. 'import'
  1187. ];
  1188. cursor = 0;
  1189. // ImportedBinding
  1190. if (stmt.specifiers[cursor].type === Syntax.ImportDefaultSpecifier) {
  1191. result = join(result, [
  1192. this.generateExpression(stmt.specifiers[cursor], Precedence.Sequence, E_TTT)
  1193. ]);
  1194. ++cursor;
  1195. }
  1196. if (stmt.specifiers[cursor]) {
  1197. if (cursor !== 0) {
  1198. result.push(',');
  1199. }
  1200. if (stmt.specifiers[cursor].type === Syntax.ImportNamespaceSpecifier) {
  1201. // NameSpaceImport
  1202. result = join(result, [
  1203. space,
  1204. this.generateExpression(stmt.specifiers[cursor], Precedence.Sequence, E_TTT)
  1205. ]);
  1206. } else {
  1207. // NamedImports
  1208. result.push(space + '{');
  1209. if ((stmt.specifiers.length - cursor) === 1) {
  1210. // import { ... } from "...";
  1211. result.push(space);
  1212. result.push(this.generateExpression(stmt.specifiers[cursor], Precedence.Sequence, E_TTT));
  1213. result.push(space + '}' + space);
  1214. } else {
  1215. // import {
  1216. // ...,
  1217. // ...,
  1218. // } from "...";
  1219. withIndent(function (indent) {
  1220. var i, iz;
  1221. result.push(newline);
  1222. for (i = cursor, iz = stmt.specifiers.length; i < iz; ++i) {
  1223. result.push(indent);
  1224. result.push(that.generateExpression(stmt.specifiers[i], Precedence.Sequence, E_TTT));
  1225. if (i + 1 < iz) {
  1226. result.push(',' + newline);
  1227. }
  1228. }
  1229. });
  1230. if (!endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString())) {
  1231. result.push(newline);
  1232. }
  1233. result.push(base + '}' + space);
  1234. }
  1235. }
  1236. }
  1237. result = join(result, [
  1238. 'from' + space,
  1239. // ModuleSpecifier
  1240. this.generateExpression(stmt.source, Precedence.Sequence, E_TTT),
  1241. this.semicolon(flags)
  1242. ]);
  1243. return result;
  1244. },
  1245. VariableDeclarator: function (stmt, flags) {
  1246. var itemFlags = (flags & F_ALLOW_IN) ? E_TTT : E_FTT;
  1247. if (stmt.init) {
  1248. return [
  1249. this.generateExpression(stmt.id, Precedence.Assignment, itemFlags),
  1250. space,
  1251. '=',
  1252. space,
  1253. this.generateExpression(stmt.init, Precedence.Assignment, itemFlags)
  1254. ];
  1255. }
  1256. return this.generatePattern(stmt.id, Precedence.Assignment, itemFlags);
  1257. },
  1258. VariableDeclaration: function (stmt, flags) {
  1259. // VariableDeclarator is typed as Statement,
  1260. // but joined with comma (not LineTerminator).
  1261. // So if comment is attached to target node, we should specialize.
  1262. var result, i, iz, node, bodyFlags, that = this;
  1263. result = [ stmt.kind ];
  1264. bodyFlags = (flags & F_ALLOW_IN) ? S_TFFF : S_FFFF;
  1265. function block() {
  1266. node = stmt.declarations[0];
  1267. if (extra.comment && node.leadingComments) {
  1268. result.push('\n');
  1269. result.push(addIndent(that.generateStatement(node, bodyFlags)));
  1270. } else {
  1271. result.push(noEmptySpace());
  1272. result.push(that.generateStatement(node, bodyFlags));
  1273. }
  1274. for (i = 1, iz = stmt.declarations.length; i < iz; ++i) {
  1275. node = stmt.declarations[i];
  1276. if (extra.comment && node.leadingComments) {
  1277. result.push(',' + newline);
  1278. result.push(addIndent(that.generateStatement(node, bodyFlags)));
  1279. } else {
  1280. result.push(',' + space);
  1281. result.push(that.generateStatement(node, bodyFlags));
  1282. }
  1283. }
  1284. }
  1285. if (stmt.declarations.length > 1) {
  1286. withIndent(block);
  1287. } else {
  1288. block();
  1289. }
  1290. result.push(this.semicolon(flags));
  1291. return result;
  1292. },
  1293. ThrowStatement: function (stmt, flags) {
  1294. return [join(
  1295. 'throw',
  1296. this.generateExpression(stmt.argument, Precedence.Sequence, E_TTT)
  1297. ), this.semicolon(flags)];
  1298. },
  1299. TryStatement: function (stmt, flags) {
  1300. var result, i, iz, guardedHandlers;
  1301. result = ['try', this.maybeBlock(stmt.block, S_TFFF)];
  1302. result = this.maybeBlockSuffix(stmt.block, result);
  1303. if (stmt.handlers) {
  1304. // old interface
  1305. for (i = 0, iz = stmt.handlers.length; i < iz; ++i) {
  1306. result = join(result, this.generateStatement(stmt.handlers[i], S_TFFF));
  1307. if (stmt.finalizer || i + 1 !== iz) {
  1308. result = this.maybeBlockSuffix(stmt.handlers[i].body, result);
  1309. }
  1310. }
  1311. } else {
  1312. guardedHandlers = stmt.guardedHandlers || [];
  1313. for (i = 0, iz = guardedHandlers.length; i < iz; ++i) {
  1314. result = join(result, this.generateStatement(guardedHandlers[i], S_TFFF));
  1315. if (stmt.finalizer || i + 1 !== iz) {
  1316. result = this.maybeBlockSuffix(guardedHandlers[i].body, result);
  1317. }
  1318. }
  1319. // new interface
  1320. if (stmt.handler) {
  1321. if (Array.isArray(stmt.handler)) {
  1322. for (i = 0, iz = stmt.handler.length; i < iz; ++i) {
  1323. result = join(result, this.generateStatement(stmt.handler[i], S_TFFF));
  1324. if (stmt.finalizer || i + 1 !== iz) {
  1325. result = this.maybeBlockSuffix(stmt.handler[i].body, result);
  1326. }
  1327. }
  1328. } else {
  1329. result = join(result, this.generateStatement(stmt.handler, S_TFFF));
  1330. if (stmt.finalizer) {
  1331. result = this.maybeBlockSuffix(stmt.handler.body, result);
  1332. }
  1333. }
  1334. }
  1335. }
  1336. if (stmt.finalizer) {
  1337. result = join(result, ['finally', this.maybeBlock(stmt.finalizer, S_TFFF)]);
  1338. }
  1339. return result;
  1340. },
  1341. SwitchStatement: function (stmt, flags) {
  1342. var result, fragment, i, iz, bodyFlags, that = this;
  1343. withIndent(function () {
  1344. result = [
  1345. 'switch' + space + '(',
  1346. that.generateExpression(stmt.discriminant, Precedence.Sequence, E_TTT),
  1347. ')' + space + '{' + newline
  1348. ];
  1349. });
  1350. if (stmt.cases) {
  1351. bodyFlags = S_TFFF;
  1352. for (i = 0, iz = stmt.cases.length; i < iz; ++i) {
  1353. if (i === iz - 1) {
  1354. bodyFlags |= F_SEMICOLON_OPT;
  1355. }
  1356. fragment = addIndent(this.generateStatement(stmt.cases[i], bodyFlags));
  1357. result.push(fragment);
  1358. if (!endsWithLineTerminator(toSourceNodeWhenNeeded(fragment).toString())) {
  1359. result.push(newline);
  1360. }
  1361. }
  1362. }
  1363. result.push(addIndent('}'));
  1364. return result;
  1365. },
  1366. SwitchCase: function (stmt, flags) {
  1367. var result, fragment, i, iz, bodyFlags, that = this;
  1368. withIndent(function () {
  1369. if (stmt.test) {
  1370. result = [
  1371. join('case', that.generateExpression(stmt.test, Precedence.Sequence, E_TTT)),
  1372. ':'
  1373. ];
  1374. } else {
  1375. result = ['default:'];
  1376. }
  1377. i = 0;
  1378. iz = stmt.consequent.length;
  1379. if (iz && stmt.consequent[0].type === Syntax.BlockStatement) {
  1380. fragment = that.maybeBlock(stmt.consequent[0], S_TFFF);
  1381. result.push(fragment);
  1382. i = 1;
  1383. }
  1384. if (i !== iz && !endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString())) {
  1385. result.push(newline);
  1386. }
  1387. bodyFlags = S_TFFF;
  1388. for (; i < iz; ++i) {
  1389. if (i === iz - 1 && flags & F_SEMICOLON_OPT) {
  1390. bodyFlags |= F_SEMICOLON_OPT;
  1391. }
  1392. fragment = addIndent(that.generateStatement(stmt.consequent[i], bodyFlags));
  1393. result.push(fragment);
  1394. if (i + 1 !== iz && !endsWithLineTerminator(toSourceNodeWhenNeeded(fragment).toString())) {
  1395. result.push(newline);
  1396. }
  1397. }
  1398. });
  1399. return result;
  1400. },
  1401. IfStatement: function (stmt, flags) {
  1402. var result, bodyFlags, semicolonOptional, that = this;
  1403. withIndent(function () {
  1404. result = [
  1405. 'if' + space + '(',
  1406. that.generateExpression(stmt.test, Precedence.Sequence, E_TTT),
  1407. ')'
  1408. ];
  1409. });
  1410. semicolonOptional = flags & F_SEMICOLON_OPT;
  1411. bodyFlags = S_TFFF;
  1412. if (semicolonOptional) {
  1413. bodyFlags |= F_SEMICOLON_OPT;
  1414. }
  1415. if (stmt.alternate) {
  1416. result.push(this.maybeBlock(stmt.consequent, S_TFFF));
  1417. result = this.maybeBlockSuffix(stmt.consequent, result);
  1418. if (stmt.alternate.type === Syntax.IfStatement) {
  1419. result = join(result, ['else ', this.generateStatement(stmt.alternate, bodyFlags)]);
  1420. } else {
  1421. result = join(result, join('else', this.maybeBlock(stmt.alternate, bodyFlags)));
  1422. }
  1423. } else {
  1424. result.push(this.maybeBlock(stmt.consequent, bodyFlags));
  1425. }
  1426. return result;
  1427. },
  1428. ForStatement: function (stmt, flags) {
  1429. var result, that = this;
  1430. withIndent(function () {
  1431. result = ['for' + space + '('];
  1432. if (stmt.init) {
  1433. if (stmt.init.type === Syntax.VariableDeclaration) {
  1434. result.push(that.generateStatement(stmt.init, S_FFFF));
  1435. } else {
  1436. // F_ALLOW_IN becomes false.
  1437. result.push(that.generateExpression(stmt.init, Precedence.Sequence, E_FTT));
  1438. result.push(';');
  1439. }
  1440. } else {
  1441. result.push(';');
  1442. }
  1443. if (stmt.test) {
  1444. result.push(space);
  1445. result.push(that.generateExpression(stmt.test, Precedence.Sequence, E_TTT));
  1446. result.push(';');
  1447. } else {
  1448. result.push(';');
  1449. }
  1450. if (stmt.update) {
  1451. result.push(space);
  1452. result.push(that.generateExpression(stmt.update, Precedence.Sequence, E_TTT));
  1453. result.push(')');
  1454. } else {
  1455. result.push(')');
  1456. }
  1457. });
  1458. result.push(this.maybeBlock(stmt.body, flags & F_SEMICOLON_OPT ? S_TFFT : S_TFFF));
  1459. return result;
  1460. },
  1461. ForInStatement: function (stmt, flags) {
  1462. return this.generateIterationForStatement('in', stmt, flags & F_SEMICOLON_OPT ? S_TFFT : S_TFFF);
  1463. },
  1464. ForOfStatement: function (stmt, flags) {
  1465. return this.generateIterationForStatement('of', stmt, flags & F_SEMICOLON_OPT ? S_TFFT : S_TFFF);
  1466. },
  1467. LabeledStatement: function (stmt, flags) {
  1468. return [stmt.label.name + ':', this.maybeBlock(stmt.body, flags & F_SEMICOLON_OPT ? S_TFFT : S_TFFF)];
  1469. },
  1470. Program: function (stmt, flags) {
  1471. var result, fragment, i, iz, bodyFlags;
  1472. iz = stmt.body.length;
  1473. result = [safeConcatenation && iz > 0 ? '\n' : ''];
  1474. bodyFlags = S_TFTF;
  1475. for (i = 0; i < iz; ++i) {
  1476. if (!safeConcatenation && i === iz - 1) {
  1477. bodyFlags |= F_SEMICOLON_OPT;
  1478. }
  1479. if (preserveBlankLines) {
  1480. // handle spaces before the first line
  1481. if (i === 0) {
  1482. if (!stmt.body[0].leadingComments) {
  1483. generateBlankLines(stmt.range[0], stmt.body[i].range[0], result);
  1484. }
  1485. }
  1486. // handle spaces between lines
  1487. if (i > 0) {
  1488. if (!stmt.body[i - 1].trailingComments && !stmt.body[i].leadingComments) {
  1489. generateBlankLines(stmt.body[i - 1].range[1], stmt.body[i].range[0], result);
  1490. }
  1491. }
  1492. }
  1493. fragment = addIndent(this.generateStatement(stmt.body[i], bodyFlags));
  1494. result.push(fragment);
  1495. if (i + 1 < iz && !endsWithLineTerminator(toSourceNodeWhenNeeded(fragment).toString())) {
  1496. if (preserveBlankLines) {
  1497. if (!stmt.body[i + 1].leadingComments) {
  1498. result.push(newline);
  1499. }
  1500. } else {
  1501. result.push(newline);
  1502. }
  1503. }
  1504. if (preserveBlankLines) {
  1505. // handle spaces after the last line
  1506. if (i === iz - 1) {
  1507. if (!stmt.body[i].trailingComments) {
  1508. generateBlankLines(stmt.body[i].range[1], stmt.range[1], result);
  1509. }
  1510. }
  1511. }
  1512. }
  1513. return result;
  1514. },
  1515. FunctionDeclaration: function (stmt, flags) {
  1516. return [
  1517. generateAsyncPrefix(stmt, true),
  1518. 'function',
  1519. generateStarSuffix(stmt) || noEmptySpace(),
  1520. stmt.id ? generateIdentifier(stmt.id) : '',
  1521. this.generateFunctionBody(stmt)
  1522. ];
  1523. },
  1524. ReturnStatement: function (stmt, flags) {
  1525. if (stmt.argument) {
  1526. return [join(
  1527. 'return',
  1528. this.generateExpression(stmt.argument, Precedence.Sequence, E_TTT)
  1529. ), this.semicolon(flags)];
  1530. }
  1531. return ['return' + this.semicolon(flags)];
  1532. },
  1533. WhileStatement: function (stmt, flags) {
  1534. var result, that = this;
  1535. withIndent(function () {
  1536. result = [
  1537. 'while' + space + '(',
  1538. that.generateExpression(stmt.test, Precedence.Sequence, E_TTT),
  1539. ')'
  1540. ];
  1541. });
  1542. result.push(this.maybeBlock(stmt.body, flags & F_SEMICOLON_OPT ? S_TFFT : S_TFFF));
  1543. return result;
  1544. },
  1545. WithStatement: function (stmt, flags) {
  1546. var result, that = this;
  1547. withIndent(function () {
  1548. result = [
  1549. 'with' + space + '(',
  1550. that.generateExpression(stmt.object, Precedence.Sequence, E_TTT),
  1551. ')'
  1552. ];
  1553. });
  1554. result.push(this.maybeBlock(stmt.body, flags & F_SEMICOLON_OPT ? S_TFFT : S_TFFF));
  1555. return result;
  1556. }
  1557. };
  1558. merge(CodeGenerator.prototype, CodeGenerator.Statement);
  1559. // Expressions.
  1560. CodeGenerator.Expression = {
  1561. SequenceExpression: function (expr, precedence, flags) {
  1562. var result, i, iz;
  1563. if (Precedence.Sequence < precedence) {
  1564. flags |= F_ALLOW_IN;
  1565. }
  1566. result = [];
  1567. for (i = 0, iz = expr.expressions.length; i < iz; ++i) {
  1568. result.push(this.generateExpression(expr.expressions[i], Precedence.Assignment, flags));
  1569. if (i + 1 < iz) {
  1570. result.push(',' + space);
  1571. }
  1572. }
  1573. return parenthesize(result, Precedence.Sequence, precedence);
  1574. },
  1575. AssignmentExpression: function (expr, precedence, flags) {
  1576. return this.generateAssignment(expr.left, expr.right, expr.operator, precedence, flags);
  1577. },
  1578. ArrowFunctionExpression: function (expr, precedence, flags) {
  1579. return parenthesize(this.generateFunctionBody(expr), Precedence.ArrowFunction, precedence);
  1580. },
  1581. ConditionalExpression: function (expr, precedence, flags) {
  1582. if (Precedence.Conditional < precedence) {
  1583. flags |= F_ALLOW_IN;
  1584. }
  1585. return parenthesize(
  1586. [
  1587. this.generateExpression(expr.test, Precedence.LogicalOR, flags),
  1588. space + '?' + space,
  1589. this.generateExpression(expr.consequent, Precedence.Assignment, flags),
  1590. space + ':' + space,
  1591. this.generateExpression(expr.alternate, Precedence.Assignment, flags)
  1592. ],
  1593. Precedence.Conditional,
  1594. precedence
  1595. );
  1596. },
  1597. LogicalExpression: function (expr, precedence, flags) {
  1598. return this.BinaryExpression(expr, precedence, flags);
  1599. },
  1600. BinaryExpression: function (expr, precedence, flags) {
  1601. var result, leftPrecedence, rightPrecedence, currentPrecedence, fragment, leftSource;
  1602. currentPrecedence = BinaryPrecedence[expr.operator];
  1603. leftPrecedence = expr.operator === '**' ? Precedence.Postfix : currentPrecedence;
  1604. rightPrecedence = expr.operator === '**' ? currentPrecedence : currentPrecedence + 1;
  1605. if (currentPrecedence < precedence) {
  1606. flags |= F_ALLOW_IN;
  1607. }
  1608. fragment = this.generateExpression(expr.left, leftPrecedence, flags);
  1609. leftSource = fragment.toString();
  1610. if (leftSource.charCodeAt(leftSource.length - 1) === 0x2F /* / */ && esutils.code.isIdentifierPartES5(expr.operator.charCodeAt(0))) {
  1611. result = [fragment, noEmptySpace(), expr.operator];
  1612. } else {
  1613. result = join(fragment, expr.operator);
  1614. }
  1615. fragment = this.generateExpression(expr.right, rightPrecedence, flags);
  1616. if (expr.operator === '/' && fragment.toString().charAt(0) === '/' ||
  1617. expr.operator.slice(-1) === '<' && fragment.toString().slice(0, 3) === '!--') {
  1618. // If '/' concats with '/' or `<` concats with `!--`, it is interpreted as comment start
  1619. result.push(noEmptySpace());
  1620. result.push(fragment);
  1621. } else {
  1622. result = join(result, fragment);
  1623. }
  1624. if (expr.operator === 'in' && !(flags & F_ALLOW_IN)) {
  1625. return ['(', result, ')'];
  1626. }
  1627. return parenthesize(result, currentPrecedence, precedence);
  1628. },
  1629. CallExpression: function (expr, precedence, flags) {
  1630. var result, i, iz;
  1631. // F_ALLOW_UNPARATH_NEW becomes false.
  1632. result = [this.generateExpression(expr.callee, Precedence.Call, E_TTF)];
  1633. result.push('(');
  1634. for (i = 0, iz = expr['arguments'].length; i < iz; ++i) {
  1635. result.push(this.generateExpression(expr['arguments'][i], Precedence.Assignment, E_TTT));
  1636. if (i + 1 < iz) {
  1637. result.push(',' + space);
  1638. }
  1639. }
  1640. result.push(')');
  1641. if (!(flags & F_ALLOW_CALL)) {
  1642. return ['(', result, ')'];
  1643. }
  1644. return parenthesize(result, Precedence.Call, precedence);
  1645. },
  1646. NewExpression: function (expr, precedence, flags) {
  1647. var result, length, i, iz, itemFlags;
  1648. length = expr['arguments'].length;
  1649. // F_ALLOW_CALL becomes false.
  1650. // F_ALLOW_UNPARATH_NEW may become false.
  1651. itemFlags = (flags & F_ALLOW_UNPARATH_NEW && !parentheses && length === 0) ? E_TFT : E_TFF;
  1652. result = join(
  1653. 'new',
  1654. this.generateExpression(expr.callee, Precedence.New, itemFlags)
  1655. );
  1656. if (!(flags & F_ALLOW_UNPARATH_NEW) || parentheses || length > 0) {
  1657. result.push('(');
  1658. for (i = 0, iz = length; i < iz; ++i) {
  1659. result.push(this.generateExpression(expr['arguments'][i], Precedence.Assignment, E_TTT));
  1660. if (i + 1 < iz) {
  1661. result.push(',' + space);
  1662. }
  1663. }
  1664. result.push(')');
  1665. }
  1666. return parenthesize(result, Precedence.New, precedence);
  1667. },
  1668. MemberExpression: function (expr, precedence, flags) {
  1669. var result, fragment;
  1670. // F_ALLOW_UNPARATH_NEW becomes false.
  1671. result = [this.generateExpression(expr.object, Precedence.Call, (flags & F_ALLOW_CALL) ? E_TTF : E_TFF)];
  1672. if (expr.computed) {
  1673. result.push('[');
  1674. result.push(this.generateExpression(expr.property, Precedence.Sequence, flags & F_ALLOW_CALL ? E_TTT : E_TFT));
  1675. result.push(']');
  1676. } else {
  1677. if (expr.object.type === Syntax.Literal && typeof expr.object.value === 'number') {
  1678. fragment = toSourceNodeWhenNeeded(result).toString();
  1679. // When the following conditions are all true,
  1680. // 1. No floating point
  1681. // 2. Don't have exponents
  1682. // 3. The last character is a decimal digit
  1683. // 4. Not hexadecimal OR octal number literal
  1684. // we should add a floating point.
  1685. if (
  1686. fragment.indexOf('.') < 0 &&
  1687. !/[eExX]/.test(fragment) &&
  1688. esutils.code.isDecimalDigit(fragment.charCodeAt(fragment.length - 1)) &&
  1689. !(fragment.length >= 2 && fragment.charCodeAt(0) === 48) // '0'
  1690. ) {
  1691. result.push(' ');
  1692. }
  1693. }
  1694. result.push('.');
  1695. result.push(generateIdentifier(expr.property));
  1696. }
  1697. return parenthesize(result, Precedence.Member, precedence);
  1698. },
  1699. MetaProperty: function (expr, precedence, flags) {
  1700. var result;
  1701. result = [];
  1702. result.push(typeof expr.meta === "string" ? expr.meta : generateIdentifier(expr.meta));
  1703. result.push('.');
  1704. result.push(typeof expr.property === "string" ? expr.property : generateIdentifier(expr.property));
  1705. return parenthesize(result, Precedence.Member, precedence);
  1706. },
  1707. UnaryExpression: function (expr, precedence, flags) {
  1708. var result, fragment, rightCharCode, leftSource, leftCharCode;
  1709. fragment = this.generateExpression(expr.argument, Precedence.Unary, E_TTT);
  1710. if (space === '') {
  1711. result = join(expr.operator, fragment);
  1712. } else {
  1713. result = [expr.operator];
  1714. if (expr.operator.length > 2) {
  1715. // delete, void, typeof
  1716. // get `typeof []`, not `typeof[]`
  1717. result = join(result, fragment);
  1718. } else {
  1719. // Prevent inserting spaces between operator and argument if it is unnecessary
  1720. // like, `!cond`
  1721. leftSource = toSourceNodeWhenNeeded(result).toString();
  1722. leftCharCode = leftSource.charCodeAt(leftSource.length - 1);
  1723. rightCharCode = fragment.toString().charCodeAt(0);
  1724. if (((leftCharCode === 0x2B /* + */ || leftCharCode === 0x2D /* - */) && leftCharCode === rightCharCode) ||
  1725. (esutils.code.isIdentifierPartES5(leftCharCode) && esutils.code.isIdentifierPartES5(rightCharCode))) {
  1726. result.push(noEmptySpace());
  1727. result.push(fragment);
  1728. } else {
  1729. result.push(fragment);
  1730. }
  1731. }
  1732. }
  1733. return parenthesize(result, Precedence.Unary, precedence);
  1734. },
  1735. YieldExpression: function (expr, precedence, flags) {
  1736. var result;
  1737. if (expr.delegate) {
  1738. result = 'yield*';
  1739. } else {
  1740. result = 'yield';
  1741. }
  1742. if (expr.argument) {
  1743. result = join(
  1744. result,
  1745. this.generateExpression(expr.argument, Precedence.Yield, E_TTT)
  1746. );
  1747. }
  1748. return parenthesize(result, Precedence.Yield, precedence);
  1749. },
  1750. AwaitExpression: function (expr, precedence, flags) {
  1751. var result = join(
  1752. expr.all ? 'await*' : 'await',
  1753. this.generateExpression(expr.argument, Precedence.Await, E_TTT)
  1754. );
  1755. return parenthesize(result, Precedence.Await, precedence);
  1756. },
  1757. UpdateExpression: function (expr, precedence, flags) {
  1758. if (expr.prefix) {
  1759. return parenthesize(
  1760. [
  1761. expr.operator,
  1762. this.generateExpression(expr.argument, Precedence.Unary, E_TTT)
  1763. ],
  1764. Precedence.Unary,
  1765. precedence
  1766. );
  1767. }
  1768. return parenthesize(
  1769. [
  1770. this.generateExpression(expr.argument, Precedence.Postfix, E_TTT),
  1771. expr.operator
  1772. ],
  1773. Precedence.Postfix,
  1774. precedence
  1775. );
  1776. },
  1777. FunctionExpression: function (expr, precedence, flags) {
  1778. var result = [
  1779. generateAsyncPrefix(expr, true),
  1780. 'function'
  1781. ];
  1782. if (expr.id) {
  1783. result.push(generateStarSuffix(expr) || noEmptySpace());
  1784. result.push(generateIdentifier(expr.id));
  1785. } else {
  1786. result.push(generateStarSuffix(expr) || space);
  1787. }
  1788. result.push(this.generateFunctionBody(expr));
  1789. return result;
  1790. },
  1791. ArrayPattern: function (expr, precedence, flags) {
  1792. return this.ArrayExpression(expr, precedence, flags, true);
  1793. },
  1794. ArrayExpression: function (expr, precedence, flags, isPattern) {
  1795. var result, multiline, that = this;
  1796. if (!expr.elements.length) {
  1797. return '[]';
  1798. }
  1799. multiline = isPattern ? false : expr.elements.length > 1;
  1800. result = ['[', multiline ? newline : ''];
  1801. withIndent(function (indent) {
  1802. var i, iz;
  1803. for (i = 0, iz = expr.elements.length; i < iz; ++i) {
  1804. if (!expr.elements[i]) {
  1805. if (multiline) {
  1806. result.push(indent);
  1807. }
  1808. if (i + 1 === iz) {
  1809. result.push(',');
  1810. }
  1811. } else {
  1812. result.push(multiline ? indent : '');
  1813. result.push(that.generateExpression(expr.elements[i], Precedence.Assignment, E_TTT));
  1814. }
  1815. if (i + 1 < iz) {
  1816. result.push(',' + (multiline ? newline : space));
  1817. }
  1818. }
  1819. });
  1820. if (multiline && !endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString())) {
  1821. result.push(newline);
  1822. }
  1823. result.push(multiline ? base : '');
  1824. result.push(']');
  1825. return result;
  1826. },
  1827. RestElement: function(expr, precedence, flags) {
  1828. return '...' + this.generatePattern(expr.argument);
  1829. },
  1830. ClassExpression: function (expr, precedence, flags) {
  1831. var result, fragment;
  1832. result = ['class'];
  1833. if (expr.id) {
  1834. result = join(result, this.generateExpression(expr.id, Precedence.Sequence, E_TTT));
  1835. }
  1836. if (expr.superClass) {
  1837. fragment = join('extends', this.generateExpression(expr.superClass, Precedence.Unary, E_TTT));
  1838. result = join(result, fragment);
  1839. }
  1840. result.push(space);
  1841. result.push(this.generateStatement(expr.body, S_TFFT));
  1842. return result;
  1843. },
  1844. MethodDefinition: function (expr, precedence, flags) {
  1845. var result, fragment;
  1846. if (expr['static']) {
  1847. result = ['static' + space];
  1848. } else {
  1849. result = [];
  1850. }
  1851. if (expr.kind === 'get' || expr.kind === 'set') {
  1852. fragment = [
  1853. join(expr.kind, this.generatePropertyKey(expr.key, expr.computed)),
  1854. this.generateFunctionBody(expr.value)
  1855. ];
  1856. } else {
  1857. fragment = [
  1858. generateMethodPrefix(expr),
  1859. this.generatePropertyKey(expr.key, expr.computed),
  1860. this.generateFunctionBody(expr.value)
  1861. ];
  1862. }
  1863. return join(result, fragment);
  1864. },
  1865. Property: function (expr, precedence, flags) {
  1866. if (expr.kind === 'get' || expr.kind === 'set') {
  1867. return [
  1868. expr.kind, noEmptySpace(),
  1869. this.generatePropertyKey(expr.key, expr.computed),
  1870. this.generateFunctionBody(expr.value)
  1871. ];
  1872. }
  1873. if (expr.shorthand) {
  1874. if (expr.value.type === "AssignmentPattern") {
  1875. return this.AssignmentPattern(expr.value, Precedence.Sequence, E_TTT);
  1876. }
  1877. return this.generatePropertyKey(expr.key, expr.computed);
  1878. }
  1879. if (expr.method) {
  1880. return [
  1881. generateMethodPrefix(expr),
  1882. this.generatePropertyKey(expr.key, expr.computed),
  1883. this.generateFunctionBody(expr.value)
  1884. ];
  1885. }
  1886. return [
  1887. this.generatePropertyKey(expr.key, expr.computed),
  1888. ':' + space,
  1889. this.generateExpression(expr.value, Precedence.Assignment, E_TTT)
  1890. ];
  1891. },
  1892. ObjectExpression: function (expr, precedence, flags) {
  1893. var multiline, result, fragment, that = this;
  1894. if (!expr.properties.length) {
  1895. return '{}';
  1896. }
  1897. multiline = expr.properties.length > 1;
  1898. withIndent(function () {
  1899. fragment = that.generateExpression(expr.properties[0], Precedence.Sequence, E_TTT);
  1900. });
  1901. if (!multiline) {
  1902. // issues 4
  1903. // Do not transform from
  1904. // dejavu.Class.declare({
  1905. // method2: function () {}
  1906. // });
  1907. // to
  1908. // dejavu.Class.declare({method2: function () {
  1909. // }});
  1910. if (!hasLineTerminator(toSourceNodeWhenNeeded(fragment).toString())) {
  1911. return [ '{', space, fragment, space, '}' ];
  1912. }
  1913. }
  1914. withIndent(function (indent) {
  1915. var i, iz;
  1916. result = [ '{', newline, indent, fragment ];
  1917. if (multiline) {
  1918. result.push(',' + newline);
  1919. for (i = 1, iz = expr.properties.length; i < iz; ++i) {
  1920. result.push(indent);
  1921. result.push(that.generateExpression(expr.properties[i], Precedence.Sequence, E_TTT));
  1922. if (i + 1 < iz) {
  1923. result.push(',' + newline);
  1924. }
  1925. }
  1926. }
  1927. });
  1928. if (!endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString())) {
  1929. result.push(newline);
  1930. }
  1931. result.push(base);
  1932. result.push('}');
  1933. return result;
  1934. },
  1935. AssignmentPattern: function(expr, precedence, flags) {
  1936. return this.generateAssignment(expr.left, expr.right, '=', precedence, flags);
  1937. },
  1938. ObjectPattern: function (expr, precedence, flags) {
  1939. var result, i, iz, multiline, property, that = this;
  1940. if (!expr.properties.length) {
  1941. return '{}';
  1942. }
  1943. multiline = false;
  1944. if (expr.properties.length === 1) {
  1945. property = expr.properties[0];
  1946. if (
  1947. property.type === Syntax.Property
  1948. && property.value.type !== Syntax.Identifier
  1949. ) {
  1950. multiline = true;
  1951. }
  1952. } else {
  1953. for (i = 0, iz = expr.properties.length; i < iz; ++i) {
  1954. property = expr.properties[i];
  1955. if (
  1956. property.type === Syntax.Property
  1957. && !property.shorthand
  1958. ) {
  1959. multiline = true;
  1960. break;
  1961. }
  1962. }
  1963. }
  1964. result = ['{', multiline ? newline : '' ];
  1965. withIndent(function (indent) {
  1966. var i, iz;
  1967. for (i = 0, iz = expr.properties.length; i < iz; ++i) {
  1968. result.push(multiline ? indent : '');
  1969. result.push(that.generateExpression(expr.properties[i], Precedence.Sequence, E_TTT));
  1970. if (i + 1 < iz) {
  1971. result.push(',' + (multiline ? newline : space));
  1972. }
  1973. }
  1974. });
  1975. if (multiline && !endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString())) {
  1976. result.push(newline);
  1977. }
  1978. result.push(multiline ? base : '');
  1979. result.push('}');
  1980. return result;
  1981. },
  1982. ThisExpression: function (expr, precedence, flags) {
  1983. return 'this';
  1984. },
  1985. Super: function (expr, precedence, flags) {
  1986. return 'super';
  1987. },
  1988. Identifier: function (expr, precedence, flags) {
  1989. return generateIdentifier(expr);
  1990. },
  1991. ImportDefaultSpecifier: function (expr, precedence, flags) {
  1992. return generateIdentifier(expr.id || expr.local);
  1993. },
  1994. ImportNamespaceSpecifier: function (expr, precedence, flags) {
  1995. var result = ['*'];
  1996. var id = expr.id || expr.local;
  1997. if (id) {
  1998. result.push(space + 'as' + noEmptySpace() + generateIdentifier(id));
  1999. }
  2000. return result;
  2001. },
  2002. ImportSpecifier: function (expr, precedence, flags) {
  2003. var imported = expr.imported;
  2004. var result = [ imported.name ];
  2005. var local = expr.local;
  2006. if (local && local.name !== imported.name) {
  2007. result.push(noEmptySpace() + 'as' + noEmptySpace() + generateIdentifier(local));
  2008. }
  2009. return result;
  2010. },
  2011. ExportSpecifier: function (expr, precedence, flags) {
  2012. var local = expr.local;
  2013. var result = [ local.name ];
  2014. var exported = expr.exported;
  2015. if (exported && exported.name !== local.name) {
  2016. result.push(noEmptySpace() + 'as' + noEmptySpace() + generateIdentifier(exported));
  2017. }
  2018. return result;
  2019. },
  2020. Literal: function (expr, precedence, flags) {
  2021. var raw;
  2022. if (expr.hasOwnProperty('raw') && parse && extra.raw) {
  2023. try {
  2024. raw = parse(expr.raw).body[0].expression;
  2025. if (raw.type === Syntax.Literal) {
  2026. if (raw.value === expr.value) {
  2027. return expr.raw;
  2028. }
  2029. }
  2030. } catch (e) {
  2031. // not use raw property
  2032. }
  2033. }
  2034. if (expr.regex) {
  2035. return '/' + expr.regex.pattern + '/' + expr.regex.flags;
  2036. }
  2037. if (expr.value === null) {
  2038. return 'null';
  2039. }
  2040. if (typeof expr.value === 'string') {
  2041. return escapeString(expr.value);
  2042. }
  2043. if (typeof expr.value === 'number') {
  2044. return generateNumber(expr.value);
  2045. }
  2046. if (typeof expr.value === 'boolean') {
  2047. return expr.value ? 'true' : 'false';
  2048. }
  2049. return generateRegExp(expr.value);
  2050. },
  2051. GeneratorExpression: function (expr, precedence, flags) {
  2052. return this.ComprehensionExpression(expr, precedence, flags);
  2053. },
  2054. ComprehensionExpression: function (expr, precedence, flags) {
  2055. // GeneratorExpression should be parenthesized with (...), ComprehensionExpression with [...]
  2056. // Due to https://bugzilla.mozilla.org/show_bug.cgi?id=883468 position of expr.body can differ in Spidermonkey and ES6
  2057. var result, i, iz, fragment, that = this;
  2058. result = (expr.type === Syntax.GeneratorExpression) ? ['('] : ['['];
  2059. if (extra.moz.comprehensionExpressionStartsWithAssignment) {
  2060. fragment = this.generateExpression(expr.body, Precedence.Assignment, E_TTT);
  2061. result.push(fragment);
  2062. }
  2063. if (expr.blocks) {
  2064. withIndent(function () {
  2065. for (i = 0, iz = expr.blocks.length; i < iz; ++i) {
  2066. fragment = that.generateExpression(expr.blocks[i], Precedence.Sequence, E_TTT);
  2067. if (i > 0 || extra.moz.comprehensionExpressionStartsWithAssignment) {
  2068. result = join(result, fragment);
  2069. } else {
  2070. result.push(fragment);
  2071. }
  2072. }
  2073. });
  2074. }
  2075. if (expr.filter) {
  2076. result = join(result, 'if' + space);
  2077. fragment = this.generateExpression(expr.filter, Precedence.Sequence, E_TTT);
  2078. result = join(result, [ '(', fragment, ')' ]);
  2079. }
  2080. if (!extra.moz.comprehensionExpressionStartsWithAssignment) {
  2081. fragment = this.generateExpression(expr.body, Precedence.Assignment, E_TTT);
  2082. result = join(result, fragment);
  2083. }
  2084. result.push((expr.type === Syntax.GeneratorExpression) ? ')' : ']');
  2085. return result;
  2086. },
  2087. ComprehensionBlock: function (expr, precedence, flags) {
  2088. var fragment;
  2089. if (expr.left.type === Syntax.VariableDeclaration) {
  2090. fragment = [
  2091. expr.left.kind, noEmptySpace(),
  2092. this.generateStatement(expr.left.declarations[0], S_FFFF)
  2093. ];
  2094. } else {
  2095. fragment = this.generateExpression(expr.left, Precedence.Call, E_TTT);
  2096. }
  2097. fragment = join(fragment, expr.of ? 'of' : 'in');
  2098. fragment = join(fragment, this.generateExpression(expr.right, Precedence.Sequence, E_TTT));
  2099. return [ 'for' + space + '(', fragment, ')' ];
  2100. },
  2101. SpreadElement: function (expr, precedence, flags) {
  2102. return [
  2103. '...',
  2104. this.generateExpression(expr.argument, Precedence.Assignment, E_TTT)
  2105. ];
  2106. },
  2107. TaggedTemplateExpression: function (expr, precedence, flags) {
  2108. var itemFlags = E_TTF;
  2109. if (!(flags & F_ALLOW_CALL)) {
  2110. itemFlags = E_TFF;
  2111. }
  2112. var result = [
  2113. this.generateExpression(expr.tag, Precedence.Call, itemFlags),
  2114. this.generateExpression(expr.quasi, Precedence.Primary, E_FFT)
  2115. ];
  2116. return parenthesize(result, Precedence.TaggedTemplate, precedence);
  2117. },
  2118. TemplateElement: function (expr, precedence, flags) {
  2119. // Don't use "cooked". Since tagged template can use raw template
  2120. // representation. So if we do so, it breaks the script semantics.
  2121. return expr.value.raw;
  2122. },
  2123. TemplateLiteral: function (expr, precedence, flags) {
  2124. var result, i, iz;
  2125. result = [ '`' ];
  2126. for (i = 0, iz = expr.quasis.length; i < iz; ++i) {
  2127. result.push(this.generateExpression(expr.quasis[i], Precedence.Primary, E_TTT));
  2128. if (i + 1 < iz) {
  2129. result.push('${' + space);
  2130. result.push(this.generateExpression(expr.expressions[i], Precedence.Sequence, E_TTT));
  2131. result.push(space + '}');
  2132. }
  2133. }
  2134. result.push('`');
  2135. return result;
  2136. },
  2137. ModuleSpecifier: function (expr, precedence, flags) {
  2138. return this.Literal(expr, precedence, flags);
  2139. },
  2140. ImportExpression: function(expr, precedence, flag) {
  2141. return parenthesize([
  2142. 'import(',
  2143. this.generateExpression(expr.source, Precedence.Assignment, E_TTT),
  2144. ')'
  2145. ], Precedence.Call, precedence);
  2146. },
  2147. };
  2148. merge(CodeGenerator.prototype, CodeGenerator.Expression);
  2149. CodeGenerator.prototype.generateExpression = function (expr, precedence, flags) {
  2150. var result, type;
  2151. type = expr.type || Syntax.Property;
  2152. if (extra.verbatim && expr.hasOwnProperty(extra.verbatim)) {
  2153. return generateVerbatim(expr, precedence);
  2154. }
  2155. result = this[type](expr, precedence, flags);
  2156. if (extra.comment) {
  2157. result = addComments(expr, result);
  2158. }
  2159. return toSourceNodeWhenNeeded(result, expr);
  2160. };
  2161. CodeGenerator.prototype.generateStatement = function (stmt, flags) {
  2162. var result,
  2163. fragment;
  2164. result = this[stmt.type](stmt, flags);
  2165. // Attach comments
  2166. if (extra.comment) {
  2167. result = addComments(stmt, result);
  2168. }
  2169. fragment = toSourceNodeWhenNeeded(result).toString();
  2170. if (stmt.type === Syntax.Program && !safeConcatenation && newline === '' && fragment.charAt(fragment.length - 1) === '\n') {
  2171. result = sourceMap ? toSourceNodeWhenNeeded(result).replaceRight(/\s+$/, '') : fragment.replace(/\s+$/, '');
  2172. }
  2173. return toSourceNodeWhenNeeded(result, stmt);
  2174. };
  2175. function generateInternal(node) {
  2176. var codegen;
  2177. codegen = new CodeGenerator();
  2178. if (isStatement(node)) {
  2179. return codegen.generateStatement(node, S_TFFF);
  2180. }
  2181. if (isExpression(node)) {
  2182. return codegen.generateExpression(node, Precedence.Sequence, E_TTT);
  2183. }
  2184. throw new Error('Unknown node type: ' + node.type);
  2185. }
  2186. function generate(node, options) {
  2187. var defaultOptions = getDefaultOptions(), result, pair;
  2188. if (options != null) {
  2189. // Obsolete options
  2190. //
  2191. // `options.indent`
  2192. // `options.base`
  2193. //
  2194. // Instead of them, we can use `option.format.indent`.
  2195. if (typeof options.indent === 'string') {
  2196. defaultOptions.format.indent.style = options.indent;
  2197. }
  2198. if (typeof options.base === 'number') {
  2199. defaultOptions.format.indent.base = options.base;
  2200. }
  2201. options = updateDeeply(defaultOptions, options);
  2202. indent = options.format.indent.style;
  2203. if (typeof options.base === 'string') {
  2204. base = options.base;
  2205. } else {
  2206. base = stringRepeat(indent, options.format.indent.base);
  2207. }
  2208. } else {
  2209. options = defaultOptions;
  2210. indent = options.format.indent.style;
  2211. base = stringRepeat(indent, options.format.indent.base);
  2212. }
  2213. json = options.format.json;
  2214. renumber = options.format.renumber;
  2215. hexadecimal = json ? false : options.format.hexadecimal;
  2216. quotes = json ? 'double' : options.format.quotes;
  2217. escapeless = options.format.escapeless;
  2218. newline = options.format.newline;
  2219. space = options.format.space;
  2220. if (options.format.compact) {
  2221. newline = space = indent = base = '';
  2222. }
  2223. parentheses = options.format.parentheses;
  2224. semicolons = options.format.semicolons;
  2225. safeConcatenation = options.format.safeConcatenation;
  2226. directive = options.directive;
  2227. parse = json ? null : options.parse;
  2228. sourceMap = options.sourceMap;
  2229. sourceCode = options.sourceCode;
  2230. preserveBlankLines = options.format.preserveBlankLines && sourceCode !== null;
  2231. extra = options;
  2232. if (sourceMap) {
  2233. if (!exports.browser) {
  2234. // We assume environment is node.js
  2235. // And prevent from including source-map by browserify
  2236. SourceNode = require('source-map').SourceNode;
  2237. } else {
  2238. SourceNode = global.sourceMap.SourceNode;
  2239. }
  2240. }
  2241. result = generateInternal(node);
  2242. if (!sourceMap) {
  2243. pair = {code: result.toString(), map: null};
  2244. return options.sourceMapWithCode ? pair : pair.code;
  2245. }
  2246. pair = result.toStringWithSourceMap({
  2247. file: options.file,
  2248. sourceRoot: options.sourceMapRoot
  2249. });
  2250. if (options.sourceContent) {
  2251. pair.map.setSourceContent(options.sourceMap,
  2252. options.sourceContent);
  2253. }
  2254. if (options.sourceMapWithCode) {
  2255. return pair;
  2256. }
  2257. return pair.map.toString();
  2258. }
  2259. FORMAT_MINIFY = {
  2260. indent: {
  2261. style: '',
  2262. base: 0
  2263. },
  2264. renumber: true,
  2265. hexadecimal: true,
  2266. quotes: 'auto',
  2267. escapeless: true,
  2268. compact: true,
  2269. parentheses: false,
  2270. semicolons: false
  2271. };
  2272. FORMAT_DEFAULTS = getDefaultOptions().format;
  2273. exports.version = require('./package.json').version;
  2274. exports.generate = generate;
  2275. exports.attachComments = estraverse.attachComments;
  2276. exports.Precedence = updateDeeply({}, Precedence);
  2277. exports.browser = false;
  2278. exports.FORMAT_MINIFY = FORMAT_MINIFY;
  2279. exports.FORMAT_DEFAULTS = FORMAT_DEFAULTS;
  2280. }());
  2281. /* vim: set sw=4 ts=4 et tw=80 : */