printer.js 27 KB

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