printer.js 27 KB

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