printer.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.default = void 0;
  6. var _buffer = require("./buffer");
  7. var n = require("./node");
  8. var _t = require("@babel/types");
  9. var generatorFunctions = require("./generators");
  10. const {
  11. isFunction,
  12. isStatement,
  13. isClassBody,
  14. isTSInterfaceBody
  15. } = _t;
  16. const SCIENTIFIC_NOTATION = /e/i;
  17. const ZERO_DECIMAL_INTEGER = /\.0+$/;
  18. const NON_DECIMAL_LITERAL = /^0[box]/;
  19. const PURE_ANNOTATION_RE = /^\s*[@#]__PURE__\s*$/;
  20. const HAS_NEWLINE = /[\n\r\u2028\u2029]/;
  21. const HAS_BlOCK_COMMENT_END = /\*\//;
  22. const {
  23. needsParens
  24. } = n;
  25. class Printer {
  26. constructor(format, map) {
  27. this.inForStatementInitCounter = 0;
  28. this._printStack = [];
  29. this._indent = 0;
  30. this._indentChar = 0;
  31. this._indentRepeat = 0;
  32. this._insideAux = false;
  33. this._parenPushNewlineState = null;
  34. this._noLineTerminator = false;
  35. this._printAuxAfterOnNextUserNode = false;
  36. this._printedComments = new Set();
  37. this._endsWithInteger = false;
  38. this._endsWithWord = false;
  39. this._lastCommentLine = 0;
  40. this._endsWithInnerRaw = false;
  41. this._indentInnerComments = true;
  42. this.format = format;
  43. this._buf = new _buffer.default(map);
  44. this._indentChar = format.indent.style.charCodeAt(0);
  45. this._indentRepeat = format.indent.style.length;
  46. }
  47. generate(ast) {
  48. this.print(ast);
  49. this._maybeAddAuxComment();
  50. return this._buf.get();
  51. }
  52. indent() {
  53. if (this.format.compact || this.format.concise) return;
  54. this._indent++;
  55. }
  56. dedent() {
  57. if (this.format.compact || this.format.concise) return;
  58. this._indent--;
  59. }
  60. semicolon(force = false) {
  61. this._maybeAddAuxComment();
  62. if (force) {
  63. this._appendChar(59);
  64. } else {
  65. this._queue(59);
  66. }
  67. this._noLineTerminator = false;
  68. }
  69. rightBrace() {
  70. if (this.format.minified) {
  71. this._buf.removeLastSemicolon();
  72. }
  73. this.tokenChar(125);
  74. }
  75. space(force = false) {
  76. if (this.format.compact) return;
  77. if (force) {
  78. this._space();
  79. } else if (this._buf.hasContent()) {
  80. const lastCp = this.getLastChar();
  81. if (lastCp !== 32 && lastCp !== 10) {
  82. this._space();
  83. }
  84. }
  85. }
  86. word(str, noLineTerminatorAfter = false) {
  87. this._maybePrintInnerComments();
  88. if (this._endsWithWord || str.charCodeAt(0) === 47 && this.endsWith(47)) {
  89. this._space();
  90. }
  91. this._maybeAddAuxComment();
  92. this._append(str, false);
  93. this._endsWithWord = true;
  94. this._noLineTerminator = noLineTerminatorAfter;
  95. }
  96. number(str) {
  97. this.word(str);
  98. this._endsWithInteger = Number.isInteger(+str) && !NON_DECIMAL_LITERAL.test(str) && !SCIENTIFIC_NOTATION.test(str) && !ZERO_DECIMAL_INTEGER.test(str) && str.charCodeAt(str.length - 1) !== 46;
  99. }
  100. token(str, maybeNewline = false) {
  101. this._maybePrintInnerComments();
  102. const lastChar = this.getLastChar();
  103. const strFirst = str.charCodeAt(0);
  104. if (lastChar === 33 && str === "--" ||
  105. strFirst === 43 && lastChar === 43 || strFirst === 45 && lastChar === 45 ||
  106. strFirst === 46 && this._endsWithInteger) {
  107. this._space();
  108. }
  109. this._maybeAddAuxComment();
  110. this._append(str, maybeNewline);
  111. this._noLineTerminator = false;
  112. }
  113. tokenChar(char) {
  114. this._maybePrintInnerComments();
  115. const lastChar = this.getLastChar();
  116. if (
  117. char === 43 && lastChar === 43 || char === 45 && lastChar === 45 ||
  118. char === 46 && this._endsWithInteger) {
  119. this._space();
  120. }
  121. this._maybeAddAuxComment();
  122. this._appendChar(char);
  123. this._noLineTerminator = false;
  124. }
  125. newline(i = 1, force) {
  126. if (i <= 0) return;
  127. if (!force) {
  128. if (this.format.retainLines || this.format.compact) return;
  129. if (this.format.concise) {
  130. this.space();
  131. return;
  132. }
  133. }
  134. if (i > 2) i = 2;
  135. i -= this._buf.getNewlineCount();
  136. for (let j = 0; j < i; j++) {
  137. this._newline();
  138. }
  139. return;
  140. }
  141. endsWith(char) {
  142. return this.getLastChar() === char;
  143. }
  144. getLastChar() {
  145. return this._buf.getLastChar();
  146. }
  147. endsWithCharAndNewline() {
  148. return this._buf.endsWithCharAndNewline();
  149. }
  150. removeTrailingNewline() {
  151. this._buf.removeTrailingNewline();
  152. }
  153. exactSource(loc, cb) {
  154. if (!loc) return cb();
  155. this._catchUp("start", loc);
  156. this._buf.exactSource(loc, cb);
  157. }
  158. source(prop, loc) {
  159. if (!loc) return;
  160. this._catchUp(prop, loc);
  161. this._buf.source(prop, loc);
  162. }
  163. sourceWithOffset(prop, loc, lineOffset, columnOffset) {
  164. if (!loc) return;
  165. this._catchUp(prop, loc);
  166. this._buf.sourceWithOffset(prop, loc, lineOffset, columnOffset);
  167. }
  168. withSource(prop, loc, cb) {
  169. if (!loc) return cb();
  170. this._catchUp(prop, loc);
  171. this._buf.withSource(prop, loc, cb);
  172. }
  173. _space() {
  174. this._queue(32);
  175. }
  176. _newline() {
  177. this._queue(10);
  178. }
  179. _append(str, maybeNewline) {
  180. this._maybeAddParen(str);
  181. this._maybeIndent(str.charCodeAt(0));
  182. this._buf.append(str, maybeNewline);
  183. this._endsWithWord = false;
  184. this._endsWithInteger = false;
  185. }
  186. _appendChar(char) {
  187. this._maybeAddParenChar(char);
  188. this._maybeIndent(char);
  189. this._buf.appendChar(char);
  190. this._endsWithWord = false;
  191. this._endsWithInteger = false;
  192. }
  193. _queue(char) {
  194. this._maybeAddParenChar(char);
  195. this._maybeIndent(char);
  196. this._buf.queue(char);
  197. this._endsWithWord = false;
  198. this._endsWithInteger = false;
  199. }
  200. _maybeIndent(firstChar) {
  201. if (this._indent && firstChar !== 10 && this.endsWith(10)) {
  202. this._buf.queueIndentation(this._indentChar, this._getIndent());
  203. }
  204. }
  205. _shouldIndent(firstChar) {
  206. if (this._indent && firstChar !== 10 && this.endsWith(10)) {
  207. return true;
  208. }
  209. }
  210. _maybeAddParenChar(char) {
  211. const parenPushNewlineState = this._parenPushNewlineState;
  212. if (!parenPushNewlineState) return;
  213. if (char === 32) {
  214. return;
  215. }
  216. if (char !== 10) {
  217. this._parenPushNewlineState = null;
  218. return;
  219. }
  220. this.tokenChar(40);
  221. this.indent();
  222. parenPushNewlineState.printed = true;
  223. }
  224. _maybeAddParen(str) {
  225. const parenPushNewlineState = this._parenPushNewlineState;
  226. if (!parenPushNewlineState) return;
  227. const len = str.length;
  228. let i;
  229. for (i = 0; i < len && str.charCodeAt(i) === 32; i++) continue;
  230. if (i === len) {
  231. return;
  232. }
  233. const cha = str.charCodeAt(i);
  234. if (cha !== 10) {
  235. if (
  236. cha !== 47 ||
  237. i + 1 === len) {
  238. this._parenPushNewlineState = null;
  239. return;
  240. }
  241. const chaPost = str.charCodeAt(i + 1);
  242. if (chaPost === 42) {
  243. if (PURE_ANNOTATION_RE.test(str.slice(i + 2, len - 2))) {
  244. return;
  245. }
  246. } else if (chaPost !== 47) {
  247. this._parenPushNewlineState = null;
  248. return;
  249. }
  250. }
  251. this.tokenChar(40);
  252. this.indent();
  253. parenPushNewlineState.printed = true;
  254. }
  255. catchUp(line) {
  256. if (!this.format.retainLines) return;
  257. const count = line - this._buf.getCurrentLine();
  258. for (let i = 0; i < count; i++) {
  259. this._newline();
  260. }
  261. }
  262. _catchUp(prop, loc) {
  263. if (!this.format.retainLines) return;
  264. const pos = loc ? loc[prop] : null;
  265. if ((pos == null ? void 0 : pos.line) != null) {
  266. const count = pos.line - this._buf.getCurrentLine();
  267. for (let i = 0; i < count; i++) {
  268. this._newline();
  269. }
  270. }
  271. }
  272. _getIndent() {
  273. return this._indentRepeat * this._indent;
  274. }
  275. printTerminatorless(node, parent, isLabel) {
  276. if (isLabel) {
  277. this._noLineTerminator = true;
  278. this.print(node, parent);
  279. } else {
  280. const terminatorState = {
  281. printed: false
  282. };
  283. this._parenPushNewlineState = terminatorState;
  284. this.print(node, parent);
  285. if (terminatorState.printed) {
  286. this.dedent();
  287. this.newline();
  288. this.tokenChar(41);
  289. }
  290. }
  291. }
  292. print(node, parent, noLineTerminatorAfter,
  293. trailingCommentsLineOffset, forceParens) {
  294. if (!node) return;
  295. this._endsWithInnerRaw = false;
  296. const nodeType = node.type;
  297. const format = this.format;
  298. const oldConcise = format.concise;
  299. if (
  300. node._compact) {
  301. format.concise = true;
  302. }
  303. const printMethod = this[nodeType];
  304. if (printMethod === undefined) {
  305. throw new ReferenceError(`unknown node of type ${JSON.stringify(nodeType)} with constructor ${JSON.stringify(node.constructor.name)}`);
  306. }
  307. this._printStack.push(node);
  308. const oldInAux = this._insideAux;
  309. this._insideAux = node.loc == undefined;
  310. this._maybeAddAuxComment(this._insideAux && !oldInAux);
  311. let shouldPrintParens = false;
  312. if (forceParens) {
  313. shouldPrintParens = true;
  314. } else if (format.retainFunctionParens && nodeType === "FunctionExpression" && node.extra && node.extra.parenthesized) {
  315. shouldPrintParens = true;
  316. } else {
  317. shouldPrintParens = needsParens(node, parent, this._printStack);
  318. }
  319. if (shouldPrintParens) this.tokenChar(40);
  320. this._lastCommentLine = 0;
  321. this._printLeadingComments(node, parent);
  322. const loc = nodeType === "Program" || nodeType === "File" ? null : node.loc;
  323. this.exactSource(loc, printMethod.bind(this, node, parent));
  324. if (shouldPrintParens) {
  325. this._printTrailingComments(node, parent);
  326. this.tokenChar(41);
  327. this._noLineTerminator = noLineTerminatorAfter;
  328. } else if (noLineTerminatorAfter && !this._noLineTerminator) {
  329. this._noLineTerminator = true;
  330. this._printTrailingComments(node, parent);
  331. } else {
  332. this._printTrailingComments(node, parent, trailingCommentsLineOffset);
  333. }
  334. this._printStack.pop();
  335. format.concise = oldConcise;
  336. this._insideAux = oldInAux;
  337. this._endsWithInnerRaw = false;
  338. }
  339. _maybeAddAuxComment(enteredPositionlessNode) {
  340. if (enteredPositionlessNode) this._printAuxBeforeComment();
  341. if (!this._insideAux) this._printAuxAfterComment();
  342. }
  343. _printAuxBeforeComment() {
  344. if (this._printAuxAfterOnNextUserNode) return;
  345. this._printAuxAfterOnNextUserNode = true;
  346. const comment = this.format.auxiliaryCommentBefore;
  347. if (comment) {
  348. this._printComment({
  349. type: "CommentBlock",
  350. value: comment
  351. }, 0);
  352. }
  353. }
  354. _printAuxAfterComment() {
  355. if (!this._printAuxAfterOnNextUserNode) return;
  356. this._printAuxAfterOnNextUserNode = false;
  357. const comment = this.format.auxiliaryCommentAfter;
  358. if (comment) {
  359. this._printComment({
  360. type: "CommentBlock",
  361. value: comment
  362. }, 0);
  363. }
  364. }
  365. getPossibleRaw(node) {
  366. const extra = node.extra;
  367. if (extra && extra.raw != null && extra.rawValue != null && node.value === extra.rawValue) {
  368. return extra.raw;
  369. }
  370. }
  371. printJoin(nodes, parent, opts = {}) {
  372. if (!(nodes != null && nodes.length)) return;
  373. if (opts.indent) this.indent();
  374. const newlineOpts = {
  375. addNewlines: opts.addNewlines,
  376. nextNodeStartLine: 0
  377. };
  378. const separator = opts.separator ? opts.separator.bind(this) : null;
  379. const len = nodes.length;
  380. for (let i = 0; i < len; i++) {
  381. const node = nodes[i];
  382. if (!node) continue;
  383. if (opts.statement) this._printNewline(i === 0, newlineOpts);
  384. this.print(node, parent, undefined, opts.trailingCommentsLineOffset || 0);
  385. opts.iterator == null ? void 0 : opts.iterator(node, i);
  386. if (i < len - 1) separator == null ? void 0 : separator();
  387. if (opts.statement) {
  388. if (i + 1 === len) {
  389. this.newline(1);
  390. } else {
  391. var _nextNode$loc;
  392. const nextNode = nodes[i + 1];
  393. newlineOpts.nextNodeStartLine = ((_nextNode$loc = nextNode.loc) == null ? void 0 : _nextNode$loc.start.line) || 0;
  394. this._printNewline(true, newlineOpts);
  395. }
  396. }
  397. }
  398. if (opts.indent) this.dedent();
  399. }
  400. printAndIndentOnComments(node, parent) {
  401. const indent = node.leadingComments && node.leadingComments.length > 0;
  402. if (indent) this.indent();
  403. this.print(node, parent);
  404. if (indent) this.dedent();
  405. }
  406. printBlock(parent) {
  407. const node = parent.body;
  408. if (node.type !== "EmptyStatement") {
  409. this.space();
  410. }
  411. this.print(node, parent);
  412. }
  413. _printTrailingComments(node, parent, lineOffset) {
  414. const comments = node.trailingComments;
  415. if (!(comments != null && comments.length)) return;
  416. this._printComments(2, comments, node, parent, lineOffset);
  417. }
  418. _printLeadingComments(node, parent) {
  419. const comments = node.leadingComments;
  420. if (!(comments != null && comments.length)) return;
  421. this._printComments(0, comments, node, parent);
  422. }
  423. _maybePrintInnerComments() {
  424. if (this._endsWithInnerRaw) this.printInnerComments();
  425. this._endsWithInnerRaw = true;
  426. this._indentInnerComments = true;
  427. }
  428. printInnerComments() {
  429. const node = this._printStack[this._printStack.length - 1];
  430. const comments = node.innerComments;
  431. if (!(comments != null && comments.length)) return;
  432. const hasSpace = this.endsWith(32);
  433. const indent = this._indentInnerComments;
  434. const printedCommentsCount = this._printedComments.size;
  435. if (indent) this.indent();
  436. this._printComments(1, comments, node);
  437. if (hasSpace && printedCommentsCount !== this._printedComments.size) {
  438. this.space();
  439. }
  440. if (indent) this.dedent();
  441. }
  442. noIndentInnerCommentsHere() {
  443. this._indentInnerComments = false;
  444. }
  445. printSequence(nodes, parent, opts = {}) {
  446. opts.statement = true;
  447. return this.printJoin(nodes, parent, opts);
  448. }
  449. printList(items, parent, opts = {}) {
  450. if (opts.separator == null) {
  451. opts.separator = commaSeparator;
  452. }
  453. return this.printJoin(items, parent, opts);
  454. }
  455. _printNewline(newLine, opts) {
  456. if (this.format.retainLines || this.format.compact) return;
  457. if (this.format.concise) {
  458. this.space();
  459. return;
  460. }
  461. if (!newLine) {
  462. return;
  463. }
  464. const startLine = opts.nextNodeStartLine;
  465. const lastCommentLine = this._lastCommentLine;
  466. if (startLine > 0 && lastCommentLine > 0) {
  467. const offset = startLine - lastCommentLine;
  468. if (offset >= 0) {
  469. this.newline(offset || 1);
  470. return;
  471. }
  472. }
  473. if (this._buf.hasContent()) {
  474. this.newline(1);
  475. }
  476. }
  477. _printComment(comment, skipNewLines) {
  478. if (comment.ignore) return false;
  479. if (this._printedComments.has(comment)) return false;
  480. const noLineTerminator = this._noLineTerminator;
  481. if (noLineTerminator && (HAS_NEWLINE.test(comment.value) || HAS_BlOCK_COMMENT_END.test(comment.value))) {
  482. return true;
  483. }
  484. if (!this.format.shouldPrintComment(comment.value)) return false;
  485. this._printedComments.add(comment);
  486. const isBlockComment = comment.type === "CommentBlock";
  487. const printNewLines = isBlockComment && skipNewLines !== 1 && !this._noLineTerminator;
  488. if (printNewLines && this._buf.hasContent() && skipNewLines !== 2) {
  489. this.newline(1);
  490. }
  491. const lastCharCode = this.getLastChar();
  492. if (lastCharCode !== 91 && lastCharCode !== 123) {
  493. this.space();
  494. }
  495. let val;
  496. if (isBlockComment) {
  497. val = `/*${comment.value}*/`;
  498. if (this.format.indent.adjustMultilineComment) {
  499. var _comment$loc;
  500. const offset = (_comment$loc = comment.loc) == null ? void 0 : _comment$loc.start.column;
  501. if (offset) {
  502. const newlineRegex = new RegExp("\\n\\s{1," + offset + "}", "g");
  503. val = val.replace(newlineRegex, "\n");
  504. }
  505. let indentSize = this.format.retainLines ? 0 : this._buf.getCurrentColumn();
  506. if (this._shouldIndent(47) || this.format.retainLines) {
  507. indentSize += this._getIndent();
  508. }
  509. val = val.replace(/\n(?!$)/g, `\n${" ".repeat(indentSize)}`);
  510. }
  511. } else if (!noLineTerminator) {
  512. val = `//${comment.value}`;
  513. } else {
  514. val = `/*${comment.value}*/`;
  515. }
  516. if (this.endsWith(47)) this._space();
  517. this.source("start", comment.loc);
  518. this._append(val, isBlockComment);
  519. if (!isBlockComment && !noLineTerminator) {
  520. this.newline(1, true);
  521. }
  522. if (printNewLines && skipNewLines !== 3) {
  523. this.newline(1);
  524. }
  525. return false;
  526. }
  527. _printComments(type, comments, node, parent, lineOffset = 0) {
  528. const nodeLoc = node.loc;
  529. const len = comments.length;
  530. let hasLoc = !!nodeLoc;
  531. const nodeStartLine = hasLoc ? nodeLoc.start.line : 0;
  532. const nodeEndLine = hasLoc ? nodeLoc.end.line : 0;
  533. let lastLine = 0;
  534. let leadingCommentNewline = 0;
  535. const maybeNewline = this._noLineTerminator ? function () {} : this.newline.bind(this);
  536. for (let i = 0; i < len; i++) {
  537. const comment = comments[i];
  538. const printed = this._printedComments.has(comment);
  539. if (hasLoc && comment.loc && !printed) {
  540. const commentStartLine = comment.loc.start.line;
  541. const commentEndLine = comment.loc.end.line;
  542. if (type === 0) {
  543. let offset = 0;
  544. if (i === 0) {
  545. if (this._buf.hasContent() && (comment.type === "CommentLine" || commentStartLine != commentEndLine)) {
  546. offset = leadingCommentNewline = 1;
  547. }
  548. } else {
  549. offset = commentStartLine - lastLine;
  550. }
  551. lastLine = commentEndLine;
  552. maybeNewline(offset);
  553. this._printComment(comment, 1);
  554. if (i + 1 === len) {
  555. maybeNewline(Math.max(nodeStartLine - lastLine, leadingCommentNewline));
  556. lastLine = nodeStartLine;
  557. }
  558. } else if (type === 1) {
  559. const offset = commentStartLine - (i === 0 ? nodeStartLine : lastLine);
  560. lastLine = commentEndLine;
  561. maybeNewline(offset);
  562. if (this._printComment(comment, 1)) break;
  563. if (i + 1 === len) {
  564. maybeNewline(Math.min(1, nodeEndLine - lastLine));
  565. lastLine = nodeEndLine;
  566. }
  567. } else {
  568. const offset = commentStartLine - (i === 0 ? nodeEndLine - lineOffset : lastLine);
  569. lastLine = commentEndLine;
  570. maybeNewline(offset);
  571. this._printComment(comment, 1);
  572. }
  573. } else {
  574. hasLoc = false;
  575. if (printed) continue;
  576. if (len === 1) {
  577. const singleLine = comment.loc ? comment.loc.start.line === comment.loc.end.line : !HAS_NEWLINE.test(comment.value);
  578. const shouldSkipNewline = singleLine && !isStatement(node) && !isClassBody(parent) && !isTSInterfaceBody(parent);
  579. if (type === 0) {
  580. this._printComment(comment, shouldSkipNewline && node.type !== "ObjectExpression" || singleLine && isFunction(parent, {
  581. body: node
  582. }) ? 1 : 0);
  583. } else if (shouldSkipNewline && type === 2) {
  584. if (this._printComment(comment, 1)) {
  585. break;
  586. }
  587. } else {
  588. this._printComment(comment, 0);
  589. }
  590. } else if (type === 1 && !(node.type === "ObjectExpression" && node.properties.length > 1) && node.type !== "ClassBody" && node.type !== "TSInterfaceBody") {
  591. const skippedDueToNewline = this._printComment(comment, i === 0 ? 2 : i === len - 1 ? 3 : 0);
  592. if (skippedDueToNewline) break;
  593. } else {
  594. this._printComment(comment, 0);
  595. }
  596. }
  597. }
  598. if (type === 2 && hasLoc && lastLine) {
  599. this._lastCommentLine = lastLine;
  600. }
  601. }
  602. }
  603. Object.assign(Printer.prototype, generatorFunctions);
  604. {
  605. Printer.prototype.Noop = function Noop() {};
  606. }
  607. var _default = Printer;
  608. exports.default = _default;
  609. function commaSeparator() {
  610. this.tokenChar(44);
  611. this.space();
  612. }
  613. //# sourceMappingURL=printer.js.map