printer.js 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.default = void 0;
  6. var _buffer = require("./buffer.js");
  7. var n = require("./node/index.js");
  8. var _t = require("@babel/types");
  9. var _tokenMap = require("./token-map.js");
  10. var generatorFunctions = require("./generators/index.js");
  11. const {
  12. isExpression,
  13. isFunction,
  14. isStatement,
  15. isClassBody,
  16. isTSInterfaceBody,
  17. isTSEnumDeclaration
  18. } = _t;
  19. const SCIENTIFIC_NOTATION = /e/i;
  20. const ZERO_DECIMAL_INTEGER = /\.0+$/;
  21. const HAS_NEWLINE = /[\n\r\u2028\u2029]/;
  22. const HAS_NEWLINE_OR_BlOCK_COMMENT_END = /[\n\r\u2028\u2029]|\*\//;
  23. function commentIsNewline(c) {
  24. return c.type === "CommentLine" || HAS_NEWLINE.test(c.value);
  25. }
  26. const {
  27. needsParens
  28. } = n;
  29. class Printer {
  30. constructor(format, map, tokens, originalCode) {
  31. this.inForStatementInit = false;
  32. this.tokenContext = 0;
  33. this._tokens = null;
  34. this._originalCode = null;
  35. this._currentNode = null;
  36. this._indent = 0;
  37. this._indentRepeat = 0;
  38. this._insideAux = false;
  39. this._noLineTerminator = false;
  40. this._noLineTerminatorAfterNode = null;
  41. this._printAuxAfterOnNextUserNode = false;
  42. this._printedComments = new Set();
  43. this._endsWithInteger = false;
  44. this._endsWithWord = false;
  45. this._endsWithDiv = false;
  46. this._lastCommentLine = 0;
  47. this._endsWithInnerRaw = false;
  48. this._indentInnerComments = true;
  49. this.tokenMap = null;
  50. this._boundGetRawIdentifier = this._getRawIdentifier.bind(this);
  51. this.format = format;
  52. this._tokens = tokens;
  53. this._originalCode = originalCode;
  54. this._indentRepeat = format.indent.style.length;
  55. this._inputMap = map == null ? void 0 : map._inputMap;
  56. this._buf = new _buffer.default(map, format.indent.style[0]);
  57. }
  58. enterForStatementInit() {
  59. if (this.inForStatementInit) return () => {};
  60. this.inForStatementInit = true;
  61. return () => {
  62. this.inForStatementInit = false;
  63. };
  64. }
  65. enterDelimited() {
  66. const oldInForStatementInit = this.inForStatementInit;
  67. const oldNoLineTerminatorAfterNode = this._noLineTerminatorAfterNode;
  68. if (oldInForStatementInit === false && oldNoLineTerminatorAfterNode === null) {
  69. return () => {};
  70. }
  71. this.inForStatementInit = false;
  72. this._noLineTerminatorAfterNode = null;
  73. return () => {
  74. this.inForStatementInit = oldInForStatementInit;
  75. this._noLineTerminatorAfterNode = oldNoLineTerminatorAfterNode;
  76. };
  77. }
  78. generate(ast) {
  79. if (this.format.preserveFormat) {
  80. this.tokenMap = new _tokenMap.TokenMap(ast, this._tokens, this._originalCode);
  81. }
  82. this.print(ast);
  83. this._maybeAddAuxComment();
  84. return this._buf.get();
  85. }
  86. indent() {
  87. const {
  88. format
  89. } = this;
  90. if (format.preserveFormat || format.compact || format.concise) {
  91. return;
  92. }
  93. this._indent++;
  94. }
  95. dedent() {
  96. const {
  97. format
  98. } = this;
  99. if (format.preserveFormat || format.compact || format.concise) {
  100. return;
  101. }
  102. this._indent--;
  103. }
  104. semicolon(force = false) {
  105. this._maybeAddAuxComment();
  106. if (force) {
  107. this._appendChar(59);
  108. this._noLineTerminator = false;
  109. return;
  110. }
  111. if (this.tokenMap) {
  112. const node = this._currentNode;
  113. if (node.start != null && node.end != null) {
  114. if (!this.tokenMap.endMatches(node, ";")) {
  115. return;
  116. }
  117. const indexes = this.tokenMap.getIndexes(this._currentNode);
  118. this._catchUpTo(this._tokens[indexes[indexes.length - 1]].loc.start);
  119. }
  120. }
  121. this._queue(59);
  122. this._noLineTerminator = false;
  123. }
  124. rightBrace(node) {
  125. if (this.format.minified) {
  126. this._buf.removeLastSemicolon();
  127. }
  128. this.sourceWithOffset("end", node.loc, -1);
  129. this.tokenChar(125);
  130. }
  131. rightParens(node) {
  132. this.sourceWithOffset("end", node.loc, -1);
  133. this.tokenChar(41);
  134. }
  135. space(force = false) {
  136. const {
  137. format
  138. } = this;
  139. if (format.compact || format.preserveFormat) return;
  140. if (force) {
  141. this._space();
  142. } else if (this._buf.hasContent()) {
  143. const lastCp = this.getLastChar();
  144. if (lastCp !== 32 && lastCp !== 10) {
  145. this._space();
  146. }
  147. }
  148. }
  149. word(str, noLineTerminatorAfter = false) {
  150. this.tokenContext = 0;
  151. this._maybePrintInnerComments(str);
  152. if (this._endsWithWord || this._endsWithDiv && str.charCodeAt(0) === 47) {
  153. this._space();
  154. }
  155. this._maybeAddAuxComment();
  156. this._append(str, false);
  157. this._endsWithWord = true;
  158. this._noLineTerminator = noLineTerminatorAfter;
  159. }
  160. number(str, number) {
  161. function isNonDecimalLiteral(str) {
  162. if (str.length > 2 && str.charCodeAt(0) === 48) {
  163. const secondChar = str.charCodeAt(1);
  164. return secondChar === 98 || secondChar === 111 || secondChar === 120;
  165. }
  166. return false;
  167. }
  168. this.word(str);
  169. this._endsWithInteger = Number.isInteger(number) && !isNonDecimalLiteral(str) && !SCIENTIFIC_NOTATION.test(str) && !ZERO_DECIMAL_INTEGER.test(str) && str.charCodeAt(str.length - 1) !== 46;
  170. }
  171. token(str, maybeNewline = false, occurrenceCount = 0) {
  172. this.tokenContext = 0;
  173. this._maybePrintInnerComments(str, occurrenceCount);
  174. const lastChar = this.getLastChar();
  175. const strFirst = str.charCodeAt(0);
  176. if (lastChar === 33 && (str === "--" || strFirst === 61) || strFirst === 43 && lastChar === 43 || strFirst === 45 && lastChar === 45 || strFirst === 46 && this._endsWithInteger) {
  177. this._space();
  178. }
  179. this._maybeAddAuxComment();
  180. this._append(str, maybeNewline, occurrenceCount);
  181. this._noLineTerminator = false;
  182. }
  183. tokenChar(char) {
  184. this.tokenContext = 0;
  185. this._maybePrintInnerComments(String.fromCharCode(char));
  186. const lastChar = this.getLastChar();
  187. if (char === 43 && lastChar === 43 || char === 45 && lastChar === 45 || char === 46 && this._endsWithInteger) {
  188. this._space();
  189. }
  190. this._maybeAddAuxComment();
  191. this._appendChar(char);
  192. this._noLineTerminator = false;
  193. }
  194. newline(i = 1, force) {
  195. if (i <= 0) return;
  196. if (!force) {
  197. if (this.format.retainLines || this.format.compact) return;
  198. if (this.format.concise) {
  199. this.space();
  200. return;
  201. }
  202. }
  203. if (i > 2) i = 2;
  204. i -= this._buf.getNewlineCount();
  205. for (let j = 0; j < i; j++) {
  206. this._newline();
  207. }
  208. return;
  209. }
  210. endsWith(char) {
  211. return this.getLastChar() === char;
  212. }
  213. getLastChar() {
  214. return this._buf.getLastChar();
  215. }
  216. endsWithCharAndNewline() {
  217. return this._buf.endsWithCharAndNewline();
  218. }
  219. removeTrailingNewline() {
  220. this._buf.removeTrailingNewline();
  221. }
  222. exactSource(loc, cb) {
  223. if (!loc) {
  224. cb();
  225. return;
  226. }
  227. this._catchUp("start", loc);
  228. this._buf.exactSource(loc, cb);
  229. }
  230. source(prop, loc) {
  231. if (!loc) return;
  232. this._catchUp(prop, loc);
  233. this._buf.source(prop, loc);
  234. }
  235. sourceWithOffset(prop, loc, columnOffset) {
  236. if (!loc || this.format.preserveFormat) return;
  237. this._catchUp(prop, loc);
  238. this._buf.sourceWithOffset(prop, loc, columnOffset);
  239. }
  240. sourceIdentifierName(identifierName, pos) {
  241. if (!this._buf._canMarkIdName) return;
  242. const sourcePosition = this._buf._sourcePosition;
  243. sourcePosition.identifierNamePos = pos;
  244. sourcePosition.identifierName = identifierName;
  245. }
  246. _space() {
  247. this._queue(32);
  248. }
  249. _newline() {
  250. this._queue(10);
  251. }
  252. _append(str, maybeNewline, occurrenceCount = 0) {
  253. if (this.tokenMap) {
  254. const token = this.tokenMap.findMatching(this._currentNode, str, occurrenceCount);
  255. if (token) this._catchUpTo(token.loc.start);
  256. }
  257. this._maybeIndent(str.charCodeAt(0));
  258. this._buf.append(str, maybeNewline);
  259. this._endsWithWord = false;
  260. this._endsWithInteger = false;
  261. this._endsWithDiv = false;
  262. }
  263. _appendChar(char) {
  264. if (this.tokenMap) {
  265. const token = this.tokenMap.findMatching(this._currentNode, String.fromCharCode(char));
  266. if (token) this._catchUpTo(token.loc.start);
  267. }
  268. this._maybeIndent(char);
  269. this._buf.appendChar(char);
  270. this._endsWithWord = false;
  271. this._endsWithInteger = false;
  272. this._endsWithDiv = false;
  273. }
  274. _queue(char) {
  275. this._maybeIndent(char);
  276. this._buf.queue(char);
  277. this._endsWithWord = false;
  278. this._endsWithInteger = false;
  279. }
  280. _maybeIndent(firstChar) {
  281. if (this._indent && firstChar !== 10 && this.endsWith(10)) {
  282. this._buf.queueIndentation(this._getIndent());
  283. }
  284. }
  285. _shouldIndent(firstChar) {
  286. if (this._indent && firstChar !== 10 && this.endsWith(10)) {
  287. return true;
  288. }
  289. }
  290. catchUp(line) {
  291. if (!this.format.retainLines) return;
  292. const count = line - this._buf.getCurrentLine();
  293. for (let i = 0; i < count; i++) {
  294. this._newline();
  295. }
  296. }
  297. _catchUp(prop, loc) {
  298. const {
  299. format
  300. } = this;
  301. if (!format.preserveFormat) {
  302. if (format.retainLines && loc != null && loc[prop]) {
  303. this.catchUp(loc[prop].line);
  304. }
  305. return;
  306. }
  307. const pos = loc == null ? void 0 : loc[prop];
  308. if (pos != null) this._catchUpTo(pos);
  309. }
  310. _catchUpTo({
  311. line,
  312. column,
  313. index
  314. }) {
  315. const count = line - this._buf.getCurrentLine();
  316. if (count > 0 && this._noLineTerminator) {
  317. return;
  318. }
  319. for (let i = 0; i < count; i++) {
  320. this._newline();
  321. }
  322. const spacesCount = count > 0 ? column : column - this._buf.getCurrentColumn();
  323. if (spacesCount > 0) {
  324. const spaces = this._originalCode ? this._originalCode.slice(index - spacesCount, index).replace(/[^\t\x0B\f \xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF]/gu, " ") : " ".repeat(spacesCount);
  325. this._append(spaces, false);
  326. }
  327. }
  328. _getIndent() {
  329. return this._indentRepeat * this._indent;
  330. }
  331. printTerminatorless(node) {
  332. this._noLineTerminator = true;
  333. this.print(node);
  334. }
  335. print(node, noLineTerminatorAfter, trailingCommentsLineOffset) {
  336. var _node$extra, _node$leadingComments, _node$leadingComments2;
  337. if (!node) return;
  338. this._endsWithInnerRaw = false;
  339. const nodeType = node.type;
  340. const format = this.format;
  341. const oldConcise = format.concise;
  342. if (node._compact) {
  343. format.concise = true;
  344. }
  345. const printMethod = this[nodeType];
  346. if (printMethod === undefined) {
  347. throw new ReferenceError(`unknown node of type ${JSON.stringify(nodeType)} with constructor ${JSON.stringify(node.constructor.name)}`);
  348. }
  349. const parent = this._currentNode;
  350. this._currentNode = node;
  351. const oldInAux = this._insideAux;
  352. this._insideAux = node.loc == null;
  353. this._maybeAddAuxComment(this._insideAux && !oldInAux);
  354. const parenthesized = (_node$extra = node.extra) == null ? void 0 : _node$extra.parenthesized;
  355. let shouldPrintParens = parenthesized && format.preserveFormat || parenthesized && format.retainFunctionParens && nodeType === "FunctionExpression" || needsParens(node, parent, this.tokenContext, this.inForStatementInit, format.preserveFormat ? this._boundGetRawIdentifier : undefined);
  356. if (!shouldPrintParens && parenthesized && (_node$leadingComments = node.leadingComments) != null && _node$leadingComments.length && node.leadingComments[0].type === "CommentBlock") {
  357. const parentType = parent == null ? void 0 : parent.type;
  358. switch (parentType) {
  359. case "ExpressionStatement":
  360. case "VariableDeclarator":
  361. case "AssignmentExpression":
  362. case "ReturnStatement":
  363. break;
  364. case "CallExpression":
  365. case "OptionalCallExpression":
  366. case "NewExpression":
  367. if (parent.callee !== node) break;
  368. default:
  369. shouldPrintParens = true;
  370. }
  371. }
  372. let indentParenthesized = false;
  373. if (!shouldPrintParens && this._noLineTerminator && ((_node$leadingComments2 = node.leadingComments) != null && _node$leadingComments2.some(commentIsNewline) || this.format.retainLines && node.loc && node.loc.start.line > this._buf.getCurrentLine())) {
  374. shouldPrintParens = true;
  375. indentParenthesized = true;
  376. }
  377. let oldNoLineTerminatorAfterNode;
  378. let oldInForStatementInitWasTrue;
  379. if (!shouldPrintParens) {
  380. noLineTerminatorAfter || (noLineTerminatorAfter = parent && this._noLineTerminatorAfterNode === parent && n.isLastChild(parent, node));
  381. if (noLineTerminatorAfter) {
  382. var _node$trailingComment;
  383. if ((_node$trailingComment = node.trailingComments) != null && _node$trailingComment.some(commentIsNewline)) {
  384. if (isExpression(node)) shouldPrintParens = true;
  385. } else {
  386. oldNoLineTerminatorAfterNode = this._noLineTerminatorAfterNode;
  387. this._noLineTerminatorAfterNode = node;
  388. }
  389. }
  390. }
  391. if (shouldPrintParens) {
  392. this.tokenChar(40);
  393. if (indentParenthesized) this.indent();
  394. this._endsWithInnerRaw = false;
  395. if (this.inForStatementInit) {
  396. oldInForStatementInitWasTrue = true;
  397. this.inForStatementInit = false;
  398. }
  399. oldNoLineTerminatorAfterNode = this._noLineTerminatorAfterNode;
  400. this._noLineTerminatorAfterNode = null;
  401. }
  402. this._lastCommentLine = 0;
  403. this._printLeadingComments(node, parent);
  404. const loc = nodeType === "Program" || nodeType === "File" ? null : node.loc;
  405. this.exactSource(loc, printMethod.bind(this, node, parent));
  406. if (shouldPrintParens) {
  407. this._printTrailingComments(node, parent);
  408. if (indentParenthesized) {
  409. this.dedent();
  410. this.newline();
  411. }
  412. this.tokenChar(41);
  413. this._noLineTerminator = noLineTerminatorAfter;
  414. if (oldInForStatementInitWasTrue) this.inForStatementInit = true;
  415. } else if (noLineTerminatorAfter && !this._noLineTerminator) {
  416. this._noLineTerminator = true;
  417. this._printTrailingComments(node, parent);
  418. } else {
  419. this._printTrailingComments(node, parent, trailingCommentsLineOffset);
  420. }
  421. this._currentNode = parent;
  422. format.concise = oldConcise;
  423. this._insideAux = oldInAux;
  424. if (oldNoLineTerminatorAfterNode !== undefined) {
  425. this._noLineTerminatorAfterNode = oldNoLineTerminatorAfterNode;
  426. }
  427. this._endsWithInnerRaw = false;
  428. }
  429. _maybeAddAuxComment(enteredPositionlessNode) {
  430. if (enteredPositionlessNode) this._printAuxBeforeComment();
  431. if (!this._insideAux) this._printAuxAfterComment();
  432. }
  433. _printAuxBeforeComment() {
  434. if (this._printAuxAfterOnNextUserNode) return;
  435. this._printAuxAfterOnNextUserNode = true;
  436. const comment = this.format.auxiliaryCommentBefore;
  437. if (comment) {
  438. this._printComment({
  439. type: "CommentBlock",
  440. value: comment
  441. }, 0);
  442. }
  443. }
  444. _printAuxAfterComment() {
  445. if (!this._printAuxAfterOnNextUserNode) return;
  446. this._printAuxAfterOnNextUserNode = false;
  447. const comment = this.format.auxiliaryCommentAfter;
  448. if (comment) {
  449. this._printComment({
  450. type: "CommentBlock",
  451. value: comment
  452. }, 0);
  453. }
  454. }
  455. getPossibleRaw(node) {
  456. const extra = node.extra;
  457. if ((extra == null ? void 0 : extra.raw) != null && extra.rawValue != null && node.value === extra.rawValue) {
  458. return extra.raw;
  459. }
  460. }
  461. printJoin(nodes, opts = {}) {
  462. if (!(nodes != null && nodes.length)) return;
  463. let {
  464. indent
  465. } = opts;
  466. if (indent == null && this.format.retainLines) {
  467. var _nodes$0$loc;
  468. const startLine = (_nodes$0$loc = nodes[0].loc) == null ? void 0 : _nodes$0$loc.start.line;
  469. if (startLine != null && startLine !== this._buf.getCurrentLine()) {
  470. indent = true;
  471. }
  472. }
  473. if (indent) this.indent();
  474. const newlineOpts = {
  475. addNewlines: opts.addNewlines,
  476. nextNodeStartLine: 0
  477. };
  478. const separator = opts.separator ? opts.separator.bind(this) : null;
  479. const len = nodes.length;
  480. for (let i = 0; i < len; i++) {
  481. const node = nodes[i];
  482. if (!node) continue;
  483. if (opts.statement) this._printNewline(i === 0, newlineOpts);
  484. this.print(node, undefined, opts.trailingCommentsLineOffset || 0);
  485. opts.iterator == null || opts.iterator(node, i);
  486. if (separator != null) {
  487. if (i < len - 1) separator(i, false);else if (opts.printTrailingSeparator) separator(i, true);
  488. }
  489. if (opts.statement) {
  490. var _node$trailingComment2;
  491. if (!((_node$trailingComment2 = node.trailingComments) != null && _node$trailingComment2.length)) {
  492. this._lastCommentLine = 0;
  493. }
  494. if (i + 1 === len) {
  495. this.newline(1);
  496. } else {
  497. var _nextNode$loc;
  498. const nextNode = nodes[i + 1];
  499. newlineOpts.nextNodeStartLine = ((_nextNode$loc = nextNode.loc) == null ? void 0 : _nextNode$loc.start.line) || 0;
  500. this._printNewline(true, newlineOpts);
  501. }
  502. }
  503. }
  504. if (indent) this.dedent();
  505. }
  506. printAndIndentOnComments(node) {
  507. const indent = node.leadingComments && node.leadingComments.length > 0;
  508. if (indent) this.indent();
  509. this.print(node);
  510. if (indent) this.dedent();
  511. }
  512. printBlock(parent) {
  513. const node = parent.body;
  514. if (node.type !== "EmptyStatement") {
  515. this.space();
  516. }
  517. this.print(node);
  518. }
  519. _printTrailingComments(node, parent, lineOffset) {
  520. const {
  521. innerComments,
  522. trailingComments
  523. } = node;
  524. if (innerComments != null && innerComments.length) {
  525. this._printComments(2, innerComments, node, parent, lineOffset);
  526. }
  527. if (trailingComments != null && trailingComments.length) {
  528. this._printComments(2, trailingComments, node, parent, lineOffset);
  529. }
  530. }
  531. _printLeadingComments(node, parent) {
  532. const comments = node.leadingComments;
  533. if (!(comments != null && comments.length)) return;
  534. this._printComments(0, comments, node, parent);
  535. }
  536. _maybePrintInnerComments(nextTokenStr, nextTokenOccurrenceCount) {
  537. if (this._endsWithInnerRaw) {
  538. var _this$tokenMap;
  539. this.printInnerComments((_this$tokenMap = this.tokenMap) == null ? void 0 : _this$tokenMap.findMatching(this._currentNode, nextTokenStr, nextTokenOccurrenceCount));
  540. }
  541. this._endsWithInnerRaw = true;
  542. this._indentInnerComments = true;
  543. }
  544. printInnerComments(nextToken) {
  545. const node = this._currentNode;
  546. const comments = node.innerComments;
  547. if (!(comments != null && comments.length)) return;
  548. const hasSpace = this.endsWith(32);
  549. const indent = this._indentInnerComments;
  550. const printedCommentsCount = this._printedComments.size;
  551. if (indent) this.indent();
  552. this._printComments(1, comments, node, undefined, undefined, nextToken);
  553. if (hasSpace && printedCommentsCount !== this._printedComments.size) {
  554. this.space();
  555. }
  556. if (indent) this.dedent();
  557. }
  558. noIndentInnerCommentsHere() {
  559. this._indentInnerComments = false;
  560. }
  561. printSequence(nodes, opts = {}) {
  562. var _opts$indent;
  563. opts.statement = true;
  564. (_opts$indent = opts.indent) != null ? _opts$indent : opts.indent = false;
  565. this.printJoin(nodes, opts);
  566. }
  567. printList(items, opts = {}) {
  568. if (opts.separator == null) {
  569. opts.separator = commaSeparator;
  570. }
  571. this.printJoin(items, opts);
  572. }
  573. shouldPrintTrailingComma(listEnd) {
  574. if (!this.tokenMap) return null;
  575. const listEndIndex = this.tokenMap.findLastIndex(this._currentNode, token => this.tokenMap.matchesOriginal(token, listEnd));
  576. if (listEndIndex <= 0) return null;
  577. return this.tokenMap.matchesOriginal(this._tokens[listEndIndex - 1], ",");
  578. }
  579. _printNewline(newLine, opts) {
  580. const format = this.format;
  581. if (format.retainLines || format.compact) return;
  582. if (format.concise) {
  583. this.space();
  584. return;
  585. }
  586. if (!newLine) {
  587. return;
  588. }
  589. const startLine = opts.nextNodeStartLine;
  590. const lastCommentLine = this._lastCommentLine;
  591. if (startLine > 0 && lastCommentLine > 0) {
  592. const offset = startLine - lastCommentLine;
  593. if (offset >= 0) {
  594. this.newline(offset || 1);
  595. return;
  596. }
  597. }
  598. if (this._buf.hasContent()) {
  599. this.newline(1);
  600. }
  601. }
  602. _shouldPrintComment(comment, nextToken) {
  603. if (comment.ignore) return 0;
  604. if (this._printedComments.has(comment)) return 0;
  605. if (this._noLineTerminator && HAS_NEWLINE_OR_BlOCK_COMMENT_END.test(comment.value)) {
  606. return 2;
  607. }
  608. if (nextToken && this.tokenMap) {
  609. const commentTok = this.tokenMap.find(this._currentNode, token => token.value === comment.value);
  610. if (commentTok && commentTok.start > nextToken.start) {
  611. return 2;
  612. }
  613. }
  614. this._printedComments.add(comment);
  615. if (!this.format.shouldPrintComment(comment.value)) {
  616. return 0;
  617. }
  618. return 1;
  619. }
  620. _printComment(comment, skipNewLines) {
  621. const noLineTerminator = this._noLineTerminator;
  622. const isBlockComment = comment.type === "CommentBlock";
  623. const printNewLines = isBlockComment && skipNewLines !== 1 && !this._noLineTerminator;
  624. if (printNewLines && this._buf.hasContent() && skipNewLines !== 2) {
  625. this.newline(1);
  626. }
  627. const lastCharCode = this.getLastChar();
  628. if (lastCharCode !== 91 && lastCharCode !== 123 && lastCharCode !== 40) {
  629. this.space();
  630. }
  631. let val;
  632. if (isBlockComment) {
  633. val = `/*${comment.value}*/`;
  634. if (this.format.indent.adjustMultilineComment) {
  635. var _comment$loc;
  636. const offset = (_comment$loc = comment.loc) == null ? void 0 : _comment$loc.start.column;
  637. if (offset) {
  638. const newlineRegex = new RegExp("\\n\\s{1," + offset + "}", "g");
  639. val = val.replace(newlineRegex, "\n");
  640. }
  641. if (this.format.concise) {
  642. val = val.replace(/\n(?!$)/g, `\n`);
  643. } else {
  644. let indentSize = this.format.retainLines ? 0 : this._buf.getCurrentColumn();
  645. if (this._shouldIndent(47) || this.format.retainLines) {
  646. indentSize += this._getIndent();
  647. }
  648. val = val.replace(/\n(?!$)/g, `\n${" ".repeat(indentSize)}`);
  649. }
  650. }
  651. } else if (!noLineTerminator) {
  652. val = `//${comment.value}`;
  653. } else {
  654. val = `/*${comment.value}*/`;
  655. }
  656. if (this._endsWithDiv) this._space();
  657. this.source("start", comment.loc);
  658. this._append(val, isBlockComment);
  659. if (!isBlockComment && !noLineTerminator) {
  660. this.newline(1, true);
  661. }
  662. if (printNewLines && skipNewLines !== 3) {
  663. this.newline(1);
  664. }
  665. }
  666. _printComments(type, comments, node, parent, lineOffset = 0, nextToken) {
  667. const nodeLoc = node.loc;
  668. const len = comments.length;
  669. let hasLoc = !!nodeLoc;
  670. const nodeStartLine = hasLoc ? nodeLoc.start.line : 0;
  671. const nodeEndLine = hasLoc ? nodeLoc.end.line : 0;
  672. let lastLine = 0;
  673. let leadingCommentNewline = 0;
  674. const maybeNewline = this._noLineTerminator ? function () {} : this.newline.bind(this);
  675. for (let i = 0; i < len; i++) {
  676. const comment = comments[i];
  677. const shouldPrint = this._shouldPrintComment(comment, nextToken);
  678. if (shouldPrint === 2) {
  679. hasLoc = false;
  680. break;
  681. }
  682. if (hasLoc && comment.loc && shouldPrint === 1) {
  683. const commentStartLine = comment.loc.start.line;
  684. const commentEndLine = comment.loc.end.line;
  685. if (type === 0) {
  686. let offset = 0;
  687. if (i === 0) {
  688. if (this._buf.hasContent() && (comment.type === "CommentLine" || commentStartLine !== commentEndLine)) {
  689. offset = leadingCommentNewline = 1;
  690. }
  691. } else {
  692. offset = commentStartLine - lastLine;
  693. }
  694. lastLine = commentEndLine;
  695. maybeNewline(offset);
  696. this._printComment(comment, 1);
  697. if (i + 1 === len) {
  698. maybeNewline(Math.max(nodeStartLine - lastLine, leadingCommentNewline));
  699. lastLine = nodeStartLine;
  700. }
  701. } else if (type === 1) {
  702. const offset = commentStartLine - (i === 0 ? nodeStartLine : lastLine);
  703. lastLine = commentEndLine;
  704. maybeNewline(offset);
  705. this._printComment(comment, 1);
  706. if (i + 1 === len) {
  707. maybeNewline(Math.min(1, nodeEndLine - lastLine));
  708. lastLine = nodeEndLine;
  709. }
  710. } else {
  711. const offset = commentStartLine - (i === 0 ? nodeEndLine - lineOffset : lastLine);
  712. lastLine = commentEndLine;
  713. maybeNewline(offset);
  714. this._printComment(comment, 1);
  715. }
  716. } else {
  717. hasLoc = false;
  718. if (shouldPrint !== 1) {
  719. continue;
  720. }
  721. if (len === 1) {
  722. const singleLine = comment.loc ? comment.loc.start.line === comment.loc.end.line : !HAS_NEWLINE.test(comment.value);
  723. const shouldSkipNewline = singleLine && !isStatement(node) && !isClassBody(parent) && !isTSInterfaceBody(parent) && !isTSEnumDeclaration(parent);
  724. if (type === 0) {
  725. this._printComment(comment, shouldSkipNewline && node.type !== "ObjectExpression" || singleLine && isFunction(parent, {
  726. body: node
  727. }) ? 1 : 0);
  728. } else if (shouldSkipNewline && type === 2) {
  729. this._printComment(comment, 1);
  730. } else {
  731. this._printComment(comment, 0);
  732. }
  733. } else if (type === 1 && !(node.type === "ObjectExpression" && node.properties.length > 1) && node.type !== "ClassBody" && node.type !== "TSInterfaceBody") {
  734. this._printComment(comment, i === 0 ? 2 : i === len - 1 ? 3 : 0);
  735. } else {
  736. this._printComment(comment, 0);
  737. }
  738. }
  739. }
  740. if (type === 2 && hasLoc && lastLine) {
  741. this._lastCommentLine = lastLine;
  742. }
  743. }
  744. }
  745. Object.assign(Printer.prototype, generatorFunctions);
  746. {
  747. Printer.prototype.Noop = function Noop() {};
  748. }
  749. var _default = exports.default = Printer;
  750. function commaSeparator(occurrenceCount, last) {
  751. this.token(",", false, occurrenceCount);
  752. if (!last) this.space();
  753. }
  754. //# sourceMappingURL=printer.js.map