printer.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555
  1. "use strict";
  2. exports.__esModule = true;
  3. var _assign = require("babel-runtime/core-js/object/assign");
  4. var _assign2 = _interopRequireDefault(_assign);
  5. var _getIterator2 = require("babel-runtime/core-js/get-iterator");
  6. var _getIterator3 = _interopRequireDefault(_getIterator2);
  7. var _stringify = require("babel-runtime/core-js/json/stringify");
  8. var _stringify2 = _interopRequireDefault(_stringify);
  9. var _weakSet = require("babel-runtime/core-js/weak-set");
  10. var _weakSet2 = _interopRequireDefault(_weakSet);
  11. var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck");
  12. var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
  13. var _find = require("lodash/find");
  14. var _find2 = _interopRequireDefault(_find);
  15. var _findLast = require("lodash/findLast");
  16. var _findLast2 = _interopRequireDefault(_findLast);
  17. var _isInteger = require("lodash/isInteger");
  18. var _isInteger2 = _interopRequireDefault(_isInteger);
  19. var _repeat = require("lodash/repeat");
  20. var _repeat2 = _interopRequireDefault(_repeat);
  21. var _buffer = require("./buffer");
  22. var _buffer2 = _interopRequireDefault(_buffer);
  23. var _node = require("./node");
  24. var n = _interopRequireWildcard(_node);
  25. var _whitespace = require("./whitespace");
  26. var _whitespace2 = _interopRequireDefault(_whitespace);
  27. var _babelTypes = require("babel-types");
  28. var t = _interopRequireWildcard(_babelTypes);
  29. function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
  30. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  31. var SCIENTIFIC_NOTATION = /e/i;
  32. var ZERO_DECIMAL_INTEGER = /\.0+$/;
  33. var NON_DECIMAL_LITERAL = /^0[box]/;
  34. var Printer = function () {
  35. function Printer(format, map, tokens) {
  36. (0, _classCallCheck3.default)(this, Printer);
  37. this.inForStatementInitCounter = 0;
  38. this._printStack = [];
  39. this._indent = 0;
  40. this._insideAux = false;
  41. this._printedCommentStarts = {};
  42. this._parenPushNewlineState = null;
  43. this._printAuxAfterOnNextUserNode = false;
  44. this._printedComments = new _weakSet2.default();
  45. this._endsWithInteger = false;
  46. this._endsWithWord = false;
  47. this.format = format || {};
  48. this._buf = new _buffer2.default(map);
  49. this._whitespace = tokens.length > 0 ? new _whitespace2.default(tokens) : null;
  50. }
  51. Printer.prototype.generate = function generate(ast) {
  52. this.print(ast);
  53. this._maybeAddAuxComment();
  54. return this._buf.get();
  55. };
  56. Printer.prototype.indent = function indent() {
  57. if (this.format.compact || this.format.concise) return;
  58. this._indent++;
  59. };
  60. Printer.prototype.dedent = function dedent() {
  61. if (this.format.compact || this.format.concise) return;
  62. this._indent--;
  63. };
  64. Printer.prototype.semicolon = function semicolon() {
  65. var force = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
  66. this._maybeAddAuxComment();
  67. this._append(";", !force);
  68. };
  69. Printer.prototype.rightBrace = function rightBrace() {
  70. if (this.format.minified) {
  71. this._buf.removeLastSemicolon();
  72. }
  73. this.token("}");
  74. };
  75. Printer.prototype.space = function space() {
  76. var force = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
  77. if (this.format.compact) return;
  78. if (this._buf.hasContent() && !this.endsWith(" ") && !this.endsWith("\n") || force) {
  79. this._space();
  80. }
  81. };
  82. Printer.prototype.word = function word(str) {
  83. if (this._endsWithWord) this._space();
  84. this._maybeAddAuxComment();
  85. this._append(str);
  86. this._endsWithWord = true;
  87. };
  88. Printer.prototype.number = function number(str) {
  89. this.word(str);
  90. this._endsWithInteger = (0, _isInteger2.default)(+str) && !NON_DECIMAL_LITERAL.test(str) && !SCIENTIFIC_NOTATION.test(str) && !ZERO_DECIMAL_INTEGER.test(str) && str[str.length - 1] !== ".";
  91. };
  92. Printer.prototype.token = function token(str) {
  93. if (str === "--" && this.endsWith("!") || str[0] === "+" && this.endsWith("+") || str[0] === "-" && this.endsWith("-") || str[0] === "." && this._endsWithInteger) {
  94. this._space();
  95. }
  96. this._maybeAddAuxComment();
  97. this._append(str);
  98. };
  99. Printer.prototype.newline = function newline(i) {
  100. if (this.format.retainLines || this.format.compact) return;
  101. if (this.format.concise) {
  102. this.space();
  103. return;
  104. }
  105. if (this.endsWith("\n\n")) return;
  106. if (typeof i !== "number") i = 1;
  107. i = Math.min(2, i);
  108. if (this.endsWith("{\n") || this.endsWith(":\n")) i--;
  109. if (i <= 0) return;
  110. for (var j = 0; j < i; j++) {
  111. this._newline();
  112. }
  113. };
  114. Printer.prototype.endsWith = function endsWith(str) {
  115. return this._buf.endsWith(str);
  116. };
  117. Printer.prototype.removeTrailingNewline = function removeTrailingNewline() {
  118. this._buf.removeTrailingNewline();
  119. };
  120. Printer.prototype.source = function source(prop, loc) {
  121. this._catchUp(prop, loc);
  122. this._buf.source(prop, loc);
  123. };
  124. Printer.prototype.withSource = function withSource(prop, loc, cb) {
  125. this._catchUp(prop, loc);
  126. this._buf.withSource(prop, loc, cb);
  127. };
  128. Printer.prototype._space = function _space() {
  129. this._append(" ", true);
  130. };
  131. Printer.prototype._newline = function _newline() {
  132. this._append("\n", true);
  133. };
  134. Printer.prototype._append = function _append(str) {
  135. var queue = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
  136. this._maybeAddParen(str);
  137. this._maybeIndent(str);
  138. if (queue) this._buf.queue(str);else this._buf.append(str);
  139. this._endsWithWord = false;
  140. this._endsWithInteger = false;
  141. };
  142. Printer.prototype._maybeIndent = function _maybeIndent(str) {
  143. if (this._indent && this.endsWith("\n") && str[0] !== "\n") {
  144. this._buf.queue(this._getIndent());
  145. }
  146. };
  147. Printer.prototype._maybeAddParen = function _maybeAddParen(str) {
  148. var parenPushNewlineState = this._parenPushNewlineState;
  149. if (!parenPushNewlineState) return;
  150. this._parenPushNewlineState = null;
  151. var i = void 0;
  152. for (i = 0; i < str.length && str[i] === " "; i++) {
  153. continue;
  154. }if (i === str.length) return;
  155. var cha = str[i];
  156. if (cha === "\n" || cha === "/") {
  157. this.token("(");
  158. this.indent();
  159. parenPushNewlineState.printed = true;
  160. }
  161. };
  162. Printer.prototype._catchUp = function _catchUp(prop, loc) {
  163. if (!this.format.retainLines) return;
  164. var pos = loc ? loc[prop] : null;
  165. if (pos && pos.line !== null) {
  166. var count = pos.line - this._buf.getCurrentLine();
  167. for (var i = 0; i < count; i++) {
  168. this._newline();
  169. }
  170. }
  171. };
  172. Printer.prototype._getIndent = function _getIndent() {
  173. return (0, _repeat2.default)(this.format.indent.style, this._indent);
  174. };
  175. Printer.prototype.startTerminatorless = function startTerminatorless() {
  176. return this._parenPushNewlineState = {
  177. printed: false
  178. };
  179. };
  180. Printer.prototype.endTerminatorless = function endTerminatorless(state) {
  181. if (state.printed) {
  182. this.dedent();
  183. this.newline();
  184. this.token(")");
  185. }
  186. };
  187. Printer.prototype.print = function print(node, parent) {
  188. var _this = this;
  189. if (!node) return;
  190. var oldConcise = this.format.concise;
  191. if (node._compact) {
  192. this.format.concise = true;
  193. }
  194. var printMethod = this[node.type];
  195. if (!printMethod) {
  196. throw new ReferenceError("unknown node of type " + (0, _stringify2.default)(node.type) + " with constructor " + (0, _stringify2.default)(node && node.constructor.name));
  197. }
  198. this._printStack.push(node);
  199. var oldInAux = this._insideAux;
  200. this._insideAux = !node.loc;
  201. this._maybeAddAuxComment(this._insideAux && !oldInAux);
  202. var needsParens = n.needsParens(node, parent, this._printStack);
  203. if (this.format.retainFunctionParens && node.type === "FunctionExpression" && node.extra && node.extra.parenthesized) {
  204. needsParens = true;
  205. }
  206. if (needsParens) this.token("(");
  207. this._printLeadingComments(node, parent);
  208. var loc = t.isProgram(node) || t.isFile(node) ? null : node.loc;
  209. this.withSource("start", loc, function () {
  210. _this[node.type](node, parent);
  211. });
  212. this._printTrailingComments(node, parent);
  213. if (needsParens) this.token(")");
  214. this._printStack.pop();
  215. this.format.concise = oldConcise;
  216. this._insideAux = oldInAux;
  217. };
  218. Printer.prototype._maybeAddAuxComment = function _maybeAddAuxComment(enteredPositionlessNode) {
  219. if (enteredPositionlessNode) this._printAuxBeforeComment();
  220. if (!this._insideAux) this._printAuxAfterComment();
  221. };
  222. Printer.prototype._printAuxBeforeComment = function _printAuxBeforeComment() {
  223. if (this._printAuxAfterOnNextUserNode) return;
  224. this._printAuxAfterOnNextUserNode = true;
  225. var comment = this.format.auxiliaryCommentBefore;
  226. if (comment) {
  227. this._printComment({
  228. type: "CommentBlock",
  229. value: comment
  230. });
  231. }
  232. };
  233. Printer.prototype._printAuxAfterComment = function _printAuxAfterComment() {
  234. if (!this._printAuxAfterOnNextUserNode) return;
  235. this._printAuxAfterOnNextUserNode = false;
  236. var comment = this.format.auxiliaryCommentAfter;
  237. if (comment) {
  238. this._printComment({
  239. type: "CommentBlock",
  240. value: comment
  241. });
  242. }
  243. };
  244. Printer.prototype.getPossibleRaw = function getPossibleRaw(node) {
  245. var extra = node.extra;
  246. if (extra && extra.raw != null && extra.rawValue != null && node.value === extra.rawValue) {
  247. return extra.raw;
  248. }
  249. };
  250. Printer.prototype.printJoin = function printJoin(nodes, parent) {
  251. var opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  252. if (!nodes || !nodes.length) return;
  253. if (opts.indent) this.indent();
  254. var newlineOpts = {
  255. addNewlines: opts.addNewlines
  256. };
  257. for (var i = 0; i < nodes.length; i++) {
  258. var node = nodes[i];
  259. if (!node) continue;
  260. if (opts.statement) this._printNewline(true, node, parent, newlineOpts);
  261. this.print(node, parent);
  262. if (opts.iterator) {
  263. opts.iterator(node, i);
  264. }
  265. if (opts.separator && i < nodes.length - 1) {
  266. opts.separator.call(this);
  267. }
  268. if (opts.statement) this._printNewline(false, node, parent, newlineOpts);
  269. }
  270. if (opts.indent) this.dedent();
  271. };
  272. Printer.prototype.printAndIndentOnComments = function printAndIndentOnComments(node, parent) {
  273. var indent = !!node.leadingComments;
  274. if (indent) this.indent();
  275. this.print(node, parent);
  276. if (indent) this.dedent();
  277. };
  278. Printer.prototype.printBlock = function printBlock(parent) {
  279. var node = parent.body;
  280. if (!t.isEmptyStatement(node)) {
  281. this.space();
  282. }
  283. this.print(node, parent);
  284. };
  285. Printer.prototype._printTrailingComments = function _printTrailingComments(node, parent) {
  286. this._printComments(this._getComments(false, node, parent));
  287. };
  288. Printer.prototype._printLeadingComments = function _printLeadingComments(node, parent) {
  289. this._printComments(this._getComments(true, node, parent));
  290. };
  291. Printer.prototype.printInnerComments = function printInnerComments(node) {
  292. var indent = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
  293. if (!node.innerComments) return;
  294. if (indent) this.indent();
  295. this._printComments(node.innerComments);
  296. if (indent) this.dedent();
  297. };
  298. Printer.prototype.printSequence = function printSequence(nodes, parent) {
  299. var opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  300. opts.statement = true;
  301. return this.printJoin(nodes, parent, opts);
  302. };
  303. Printer.prototype.printList = function printList(items, parent) {
  304. var opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  305. if (opts.separator == null) {
  306. opts.separator = commaSeparator;
  307. }
  308. return this.printJoin(items, parent, opts);
  309. };
  310. Printer.prototype._printNewline = function _printNewline(leading, node, parent, opts) {
  311. var _this2 = this;
  312. if (this.format.retainLines || this.format.compact) return;
  313. if (this.format.concise) {
  314. this.space();
  315. return;
  316. }
  317. var lines = 0;
  318. if (node.start != null && !node._ignoreUserWhitespace && this._whitespace) {
  319. if (leading) {
  320. var _comments = node.leadingComments;
  321. var _comment = _comments && (0, _find2.default)(_comments, function (comment) {
  322. return !!comment.loc && _this2.format.shouldPrintComment(comment.value);
  323. });
  324. lines = this._whitespace.getNewlinesBefore(_comment || node);
  325. } else {
  326. var _comments2 = node.trailingComments;
  327. var _comment2 = _comments2 && (0, _findLast2.default)(_comments2, function (comment) {
  328. return !!comment.loc && _this2.format.shouldPrintComment(comment.value);
  329. });
  330. lines = this._whitespace.getNewlinesAfter(_comment2 || node);
  331. }
  332. } else {
  333. if (!leading) lines++;
  334. if (opts.addNewlines) lines += opts.addNewlines(leading, node) || 0;
  335. var needs = n.needsWhitespaceAfter;
  336. if (leading) needs = n.needsWhitespaceBefore;
  337. if (needs(node, parent)) lines++;
  338. if (!this._buf.hasContent()) lines = 0;
  339. }
  340. this.newline(lines);
  341. };
  342. Printer.prototype._getComments = function _getComments(leading, node) {
  343. return node && (leading ? node.leadingComments : node.trailingComments) || [];
  344. };
  345. Printer.prototype._printComment = function _printComment(comment) {
  346. var _this3 = this;
  347. if (!this.format.shouldPrintComment(comment.value)) return;
  348. if (comment.ignore) return;
  349. if (this._printedComments.has(comment)) return;
  350. this._printedComments.add(comment);
  351. if (comment.start != null) {
  352. if (this._printedCommentStarts[comment.start]) return;
  353. this._printedCommentStarts[comment.start] = true;
  354. }
  355. this.newline(this._whitespace ? this._whitespace.getNewlinesBefore(comment) : 0);
  356. if (!this.endsWith("[") && !this.endsWith("{")) this.space();
  357. var val = comment.type === "CommentLine" ? "//" + comment.value + "\n" : "/*" + comment.value + "*/";
  358. if (comment.type === "CommentBlock" && this.format.indent.adjustMultilineComment) {
  359. var offset = comment.loc && comment.loc.start.column;
  360. if (offset) {
  361. var newlineRegex = new RegExp("\\n\\s{1," + offset + "}", "g");
  362. val = val.replace(newlineRegex, "\n");
  363. }
  364. var indentSize = Math.max(this._getIndent().length, this._buf.getCurrentColumn());
  365. val = val.replace(/\n(?!$)/g, "\n" + (0, _repeat2.default)(" ", indentSize));
  366. }
  367. this.withSource("start", comment.loc, function () {
  368. _this3._append(val);
  369. });
  370. this.newline((this._whitespace ? this._whitespace.getNewlinesAfter(comment) : 0) + (comment.type === "CommentLine" ? -1 : 0));
  371. };
  372. Printer.prototype._printComments = function _printComments(comments) {
  373. if (!comments || !comments.length) return;
  374. for (var _iterator = comments, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) {
  375. var _ref;
  376. if (_isArray) {
  377. if (_i >= _iterator.length) break;
  378. _ref = _iterator[_i++];
  379. } else {
  380. _i = _iterator.next();
  381. if (_i.done) break;
  382. _ref = _i.value;
  383. }
  384. var _comment3 = _ref;
  385. this._printComment(_comment3);
  386. }
  387. };
  388. return Printer;
  389. }();
  390. exports.default = Printer;
  391. function commaSeparator() {
  392. this.token(",");
  393. this.space();
  394. }
  395. var _arr = [require("./generators/template-literals"), require("./generators/expressions"), require("./generators/statements"), require("./generators/classes"), require("./generators/methods"), require("./generators/modules"), require("./generators/types"), require("./generators/flow"), require("./generators/base"), require("./generators/jsx")];
  396. for (var _i2 = 0; _i2 < _arr.length; _i2++) {
  397. var generator = _arr[_i2];
  398. (0, _assign2.default)(Printer.prototype, generator);
  399. }
  400. module.exports = exports["default"];