printer.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554
  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 ? false : arguments[0];
  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 ? false : arguments[0];
  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 ? false : arguments[1];
  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 (needsParens) this.token("(");
  204. this._printLeadingComments(node, parent);
  205. var loc = t.isProgram(node) || t.isFile(node) ? null : node.loc;
  206. this.withSource("start", loc, function () {
  207. _this[node.type](node, parent);
  208. });
  209. this._printTrailingComments(node, parent);
  210. if (needsParens) this.token(")");
  211. this._printStack.pop();
  212. this.format.concise = oldConcise;
  213. this._insideAux = oldInAux;
  214. };
  215. Printer.prototype._maybeAddAuxComment = function _maybeAddAuxComment(enteredPositionlessNode) {
  216. if (enteredPositionlessNode) this._printAuxBeforeComment();
  217. if (!this._insideAux) this._printAuxAfterComment();
  218. };
  219. Printer.prototype._printAuxBeforeComment = function _printAuxBeforeComment() {
  220. if (this._printAuxAfterOnNextUserNode) return;
  221. this._printAuxAfterOnNextUserNode = true;
  222. var comment = this.format.auxiliaryCommentBefore;
  223. if (comment) {
  224. this._printComment({
  225. type: "CommentBlock",
  226. value: comment
  227. });
  228. }
  229. };
  230. Printer.prototype._printAuxAfterComment = function _printAuxAfterComment() {
  231. if (!this._printAuxAfterOnNextUserNode) return;
  232. this._printAuxAfterOnNextUserNode = false;
  233. var comment = this.format.auxiliaryCommentAfter;
  234. if (comment) {
  235. this._printComment({
  236. type: "CommentBlock",
  237. value: comment
  238. });
  239. }
  240. };
  241. Printer.prototype.getPossibleRaw = function getPossibleRaw(node) {
  242. if (this.format.minified) return;
  243. var extra = node.extra;
  244. if (extra && extra.raw != null && extra.rawValue != null && node.value === extra.rawValue) {
  245. return extra.raw;
  246. }
  247. };
  248. Printer.prototype.printJoin = function printJoin(nodes, parent) {
  249. var opts = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2];
  250. if (!nodes || !nodes.length) return;
  251. if (opts.indent) this.indent();
  252. var newlineOpts = {
  253. addNewlines: opts.addNewlines
  254. };
  255. for (var i = 0; i < nodes.length; i++) {
  256. var node = nodes[i];
  257. if (!node) continue;
  258. if (opts.statement) this._printNewline(true, node, parent, newlineOpts);
  259. this.print(node, parent);
  260. if (opts.iterator) {
  261. opts.iterator(node, i);
  262. }
  263. if (opts.separator && i < nodes.length - 1) {
  264. opts.separator.call(this);
  265. }
  266. if (opts.statement) this._printNewline(false, node, parent, newlineOpts);
  267. }
  268. if (opts.indent) this.dedent();
  269. };
  270. Printer.prototype.printAndIndentOnComments = function printAndIndentOnComments(node, parent) {
  271. var indent = !!node.leadingComments;
  272. if (indent) this.indent();
  273. this.print(node, parent);
  274. if (indent) this.dedent();
  275. };
  276. Printer.prototype.printBlock = function printBlock(parent) {
  277. var node = parent.body;
  278. if (!t.isEmptyStatement(node)) {
  279. this.space();
  280. }
  281. this.print(node, parent);
  282. };
  283. Printer.prototype._printTrailingComments = function _printTrailingComments(node, parent) {
  284. this._printComments(this._getComments(false, node, parent));
  285. };
  286. Printer.prototype._printLeadingComments = function _printLeadingComments(node, parent) {
  287. this._printComments(this._getComments(true, node, parent));
  288. };
  289. Printer.prototype.printInnerComments = function printInnerComments(node) {
  290. var indent = arguments.length <= 1 || arguments[1] === undefined ? true : arguments[1];
  291. if (!node.innerComments) return;
  292. if (indent) this.indent();
  293. this._printComments(node.innerComments);
  294. if (indent) this.dedent();
  295. };
  296. Printer.prototype.printSequence = function printSequence(nodes, parent) {
  297. var opts = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2];
  298. opts.statement = true;
  299. return this.printJoin(nodes, parent, opts);
  300. };
  301. Printer.prototype.printList = function printList(items, parent) {
  302. var opts = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2];
  303. if (opts.separator == null) {
  304. opts.separator = commaSeparator;
  305. }
  306. return this.printJoin(items, parent, opts);
  307. };
  308. Printer.prototype._printNewline = function _printNewline(leading, node, parent, opts) {
  309. var _this2 = this;
  310. if (this.format.retainLines || this.format.compact) return;
  311. if (this.format.concise) {
  312. this.space();
  313. return;
  314. }
  315. var lines = 0;
  316. if (node.start != null && !node._ignoreUserWhitespace && this._whitespace) {
  317. if (leading) {
  318. var _comments = node.leadingComments;
  319. var _comment = _comments && (0, _find2.default)(_comments, function (comment) {
  320. return !!comment.loc && _this2.format.shouldPrintComment(comment.value);
  321. });
  322. lines = this._whitespace.getNewlinesBefore(_comment || node);
  323. } else {
  324. var _comments2 = node.trailingComments;
  325. var _comment2 = _comments2 && (0, _findLast2.default)(_comments2, function (comment) {
  326. return !!comment.loc && _this2.format.shouldPrintComment(comment.value);
  327. });
  328. lines = this._whitespace.getNewlinesAfter(_comment2 || node);
  329. }
  330. } else {
  331. if (!leading) lines++;
  332. if (opts.addNewlines) lines += opts.addNewlines(leading, node) || 0;
  333. var needs = n.needsWhitespaceAfter;
  334. if (leading) needs = n.needsWhitespaceBefore;
  335. if (needs(node, parent)) lines++;
  336. if (!this._buf.hasContent()) lines = 0;
  337. }
  338. this.newline(lines);
  339. };
  340. Printer.prototype._getComments = function _getComments(leading, node) {
  341. return node && (leading ? node.leadingComments : node.trailingComments) || [];
  342. };
  343. Printer.prototype._printComment = function _printComment(comment) {
  344. var _this3 = this;
  345. if (!this.format.shouldPrintComment(comment.value)) return;
  346. if (comment.ignore) return;
  347. if (this._printedComments.has(comment)) return;
  348. this._printedComments.add(comment);
  349. if (comment.start != null) {
  350. if (this._printedCommentStarts[comment.start]) return;
  351. this._printedCommentStarts[comment.start] = true;
  352. }
  353. this.newline(this._whitespace ? this._whitespace.getNewlinesBefore(comment) : 0);
  354. if (!this.endsWith("[") && !this.endsWith("{")) this.space();
  355. var val = comment.type === "CommentLine" ? "//" + comment.value + "\n" : "/*" + comment.value + "*/";
  356. if (comment.type === "CommentBlock" && this.format.indent.adjustMultilineComment) {
  357. var offset = comment.loc && comment.loc.start.column;
  358. if (offset) {
  359. var newlineRegex = new RegExp("\\n\\s{1," + offset + "}", "g");
  360. val = val.replace(newlineRegex, "\n");
  361. }
  362. var indentSize = Math.max(this._getIndent().length, this._buf.getCurrentColumn());
  363. val = val.replace(/\n(?!$)/g, "\n" + (0, _repeat2.default)(" ", indentSize));
  364. }
  365. this.withSource("start", comment.loc, function () {
  366. _this3._append(val);
  367. });
  368. this.newline((this._whitespace ? this._whitespace.getNewlinesAfter(comment) : 0) + (comment.type === "CommentLine" ? -1 : 0));
  369. };
  370. Printer.prototype._printComments = function _printComments(comments) {
  371. if (!comments || !comments.length) return;
  372. for (var _iterator = comments, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) {
  373. var _ref;
  374. if (_isArray) {
  375. if (_i >= _iterator.length) break;
  376. _ref = _iterator[_i++];
  377. } else {
  378. _i = _iterator.next();
  379. if (_i.done) break;
  380. _ref = _i.value;
  381. }
  382. var _comment3 = _ref;
  383. this._printComment(_comment3);
  384. }
  385. };
  386. return Printer;
  387. }();
  388. exports.default = Printer;
  389. function commaSeparator() {
  390. this.token(",");
  391. this.space();
  392. }
  393. 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")];
  394. for (var _i2 = 0; _i2 < _arr.length; _i2++) {
  395. var generator = _arr[_i2];
  396. (0, _assign2.default)(Printer.prototype, generator);
  397. }
  398. module.exports = exports["default"];