printer.js 26 KB

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