printer.js 27 KB

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