printer.js 14 KB

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