| 1 | import Buffer from "./buffer"; |
| 2 | import type { Loc } from "./buffer"; |
| 3 | import * as n from "./node"; |
| 4 | import type * as t from "@babel/types"; |
| 5 | import { |
| 6 | isFunction, |
| 7 | isStatement, |
| 8 | isClassBody, |
| 9 | isTSInterfaceBody, |
| 10 | isTSEnumDeclaration, |
| 11 | } from "@babel/types"; |
| 12 | import type { |
| 13 | RecordAndTuplePluginOptions, |
| 14 | PipelineOperatorPluginOptions, |
| 15 | } from "@babel/parser"; |
| 16 | import type { Opts as jsescOptions } from "jsesc"; |
| 17 | |
| 18 | import * as generatorFunctions from "./generators"; |
| 19 | import type SourceMap from "./source-map"; |
| 20 | import * as charCodes from "charcodes"; |
| 21 | |
| 22 | const SCIENTIFIC_NOTATION = /e/i; |
| 23 | const ZERO_DECIMAL_INTEGER = /\.0+$/; |
| 24 | const NON_DECIMAL_LITERAL = /^0[box]/; |
| 25 | const PURE_ANNOTATION_RE = /^\s*[@#]__PURE__\s*$/; |
| 26 | const HAS_NEWLINE = /[\n\r\u2028\u2029]/; |
| 27 | const HAS_BlOCK_COMMENT_END = /\*\//; |
| 28 | |
| 29 | const { needsParens } = n; |
| 30 | |
| 31 | const enum COMMENT_TYPE { |
| 32 | LEADING, |
| 33 | INNER, |
| 34 | TRAILING, |
| 35 | } |
| 36 | |
| 37 | const enum COMMENT_SKIP_NEWLINE { |
| 38 | DEFAULT, |
| 39 | ALL, |
| 40 | LEADING, |
| 41 | TRAILING, |
| 42 | } |
| 43 | |
| 44 | const enum PRINT_COMMENT_HINT { |
| 45 | SKIP, |
| 46 | ALLOW, |
| 47 | DEFER, |
| 48 | } |
| 49 | |
| 50 | export type Format = { |
| 51 | shouldPrintComment: (comment: string) => boolean; |
| 52 | retainLines: boolean; |
| 53 | retainFunctionParens: boolean; |
| 54 | comments: boolean; |
| 55 | auxiliaryCommentBefore: string; |
| 56 | auxiliaryCommentAfter: string; |
| 57 | compact: boolean | "auto"; |
| 58 | minified: boolean; |
| 59 | concise: boolean; |
| 60 | indent: { |
| 61 | adjustMultilineComment: boolean; |
| 62 | style: string; |
| 63 | }; |
| 64 | recordAndTupleSyntaxType: RecordAndTuplePluginOptions["syntaxType"]; |
| 65 | jsescOption: jsescOptions; |
| 66 | jsonCompatibleStrings?: boolean; |
| 67 | /** |
| 68 | * For use with the Hack-style pipe operator. |
| 69 | * Changes what token is used for pipe bodies’ topic references. |
| 70 | */ |
| 71 | topicToken?: PipelineOperatorPluginOptions["topicToken"]; |
| 72 | /** |
| 73 | * @deprecated Removed in Babel 8 |
| 74 | */ |
| 75 | decoratorsBeforeExport?: boolean; |
| 76 | }; |
| 77 | |
| 78 | interface AddNewlinesOptions { |
| 79 | addNewlines(leading: boolean, node: t.Node): number; |
| 80 | nextNodeStartLine: number; |
| 81 | } |
| 82 | |
| 83 | interface PrintSequenceOptions extends Partial<AddNewlinesOptions> { |
| 84 | statement?: boolean; |
| 85 | indent?: boolean; |
| 86 | trailingCommentsLineOffset?: number; |
| 87 | } |
| 88 | |
| 89 | interface PrintListOptions { |
| 90 | separator?: (this: Printer) => void; |
| 91 | iterator?: (node: t.Node, index: number) => void; |
| 92 | statement?: boolean; |
| 93 | indent?: boolean; |
| 94 | } |
| 95 | |
| 96 | export type PrintJoinOptions = PrintListOptions & PrintSequenceOptions; |
| 97 | class Printer { |
| 98 | constructor(format: Format, map: SourceMap) { |
| 99 | this.format = format; |
| 100 | this._buf = new Buffer(map); |
| 101 | |
| 102 | this._indentChar = format.indent.style.charCodeAt(0); |
| 103 | this._indentRepeat = format.indent.style.length; |
| 104 | } |
| 105 | |
| 106 | declare format: Format; |
| 107 | inForStatementInitCounter: number = 0; |
| 108 | |
| 109 | declare _buf: Buffer; |
| 110 | _printStack: Array<t.Node> = []; |
| 111 | _indent: number = 0; |
| 112 | _indentChar: number = 0; |
| 113 | _indentRepeat: number = 0; |
| 114 | _insideAux: boolean = false; |
| 115 | _parenPushNewlineState: { printed: boolean } | null = null; |
| 116 | _noLineTerminator: boolean = false; |
| 117 | _printAuxAfterOnNextUserNode: boolean = false; |
| 118 | _printedComments = new Set<t.Comment>(); |
| 119 | _endsWithInteger = false; |
| 120 | _endsWithWord = false; |
| 121 | _lastCommentLine = 0; |
| 122 | _endsWithInnerRaw: boolean = false; |
| 123 | _indentInnerComments: boolean = true; |
| 124 | |
| 125 | generate(ast: t.Node) { |
| 126 | this.print(ast); |
| 127 | this._maybeAddAuxComment(); |
| 128 | |
| 129 | return this._buf.get(); |
| 130 | } |
| 131 | |
| 132 | /** |
| 133 | * Increment indent size. |
| 134 | */ |
| 135 | |
| 136 | indent(): void { |
| 137 | if (this.format.compact || this.format.concise) return; |
| 138 | |
| 139 | this._indent++; |
| 140 | } |
| 141 | |
| 142 | /** |
| 143 | * Decrement indent size. |
| 144 | */ |
| 145 | |
| 146 | dedent(): void { |
| 147 | if (this.format.compact || this.format.concise) return; |
| 148 | |
| 149 | this._indent--; |
| 150 | } |
| 151 | |
| 152 | /** |
| 153 | * Add a semicolon to the buffer. |
| 154 | */ |
| 155 | |
| 156 | semicolon(force: boolean = false): void { |
| 157 | this._maybeAddAuxComment(); |
| 158 | if (force) { |
| 159 | this._appendChar(charCodes.semicolon); |
| 160 | } else { |
| 161 | this._queue(charCodes.semicolon); |
| 162 | } |
| 163 | this._noLineTerminator = false; |
| 164 | } |
| 165 | |
| 166 | /** |
| 167 | * Add a right brace to the buffer. |
| 168 | */ |
| 169 | |
| 170 | rightBrace(): void { |
| 171 | if (this.format.minified) { |
| 172 | this._buf.removeLastSemicolon(); |
| 173 | } |
| 174 | this.token("}"); |
| 175 | } |
| 176 | |
| 177 | /** |
| 178 | * Add a space to the buffer unless it is compact. |
| 179 | */ |
| 180 | |
| 181 | space(force: boolean = false): void { |
| 182 | if (this.format.compact) return; |
| 183 | |
| 184 | if (force) { |
| 185 | this._space(); |
| 186 | } else if (this._buf.hasContent()) { |
| 187 | const lastCp = this.getLastChar(); |
| 188 | if (lastCp !== charCodes.space && lastCp !== charCodes.lineFeed) { |
| 189 | this._space(); |
| 190 | } |
| 191 | } |
| 192 | } |
| 193 | |
| 194 | /** |
| 195 | * Writes a token that can't be safely parsed without taking whitespace into account. |
| 196 | */ |
| 197 | |
| 198 | word(str: string, noLineTerminatorAfter: boolean = false): void { |
| 199 | this._maybePrintInnerComments(); |
| 200 | |
| 201 | // prevent concatenating words and creating // comment out of division and regex |
| 202 | if ( |
| 203 | this._endsWithWord || |
| 204 | (str.charCodeAt(0) === charCodes.slash && this.endsWith(charCodes.slash)) |
| 205 | ) { |
| 206 | this._space(); |
| 207 | } |
| 208 | |
| 209 | this._maybeAddAuxComment(); |
| 210 | this._append(str, false); |
| 211 | |
| 212 | this._endsWithWord = true; |
| 213 | this._noLineTerminator = noLineTerminatorAfter; |
| 214 | } |
| 215 | |
| 216 | /** |
| 217 | * Writes a number token so that we can validate if it is an integer. |
| 218 | */ |
| 219 | |
| 220 | number(str: string): void { |
| 221 | this.word(str); |
| 222 | |
| 223 | // Integer tokens need special handling because they cannot have '.'s inserted |
| 224 | // immediately after them. |
| 225 | this._endsWithInteger = |
| 226 | Number.isInteger(+str) && |
| 227 | !NON_DECIMAL_LITERAL.test(str) && |
| 228 | !SCIENTIFIC_NOTATION.test(str) && |
| 229 | !ZERO_DECIMAL_INTEGER.test(str) && |
| 230 | str.charCodeAt(str.length - 1) !== charCodes.dot; |
| 231 | } |
| 232 | |
| 233 | /** |
| 234 | * Writes a simple token. |
| 235 | */ |
| 236 | |
| 237 | token(str: string, maybeNewline = false): void { |
| 238 | this._maybePrintInnerComments(); |
| 239 | |
| 240 | // space is mandatory to avoid outputting <!-- |
| 241 | // http://javascript.spec.whatwg.org/#comment-syntax |
| 242 | const lastChar = this.getLastChar(); |
| 243 | const strFirst = str.charCodeAt(0); |
| 244 | if ( |
| 245 | (lastChar === charCodes.exclamationMark && str === "--") || |
| 246 | // Need spaces for operators of the same kind to avoid: `a+++b` |
| 247 | (strFirst === charCodes.plusSign && lastChar === charCodes.plusSign) || |
| 248 | (strFirst === charCodes.dash && lastChar === charCodes.dash) || |
| 249 | // Needs spaces to avoid changing '34' to '34.', which would still be a valid number. |
| 250 | (strFirst === charCodes.dot && this._endsWithInteger) |
| 251 | ) { |
| 252 | this._space(); |
| 253 | } |
| 254 | |
| 255 | this._maybeAddAuxComment(); |
| 256 | this._append(str, maybeNewline); |
| 257 | this._noLineTerminator = false; |
| 258 | } |
| 259 | |
| 260 | tokenChar(char: number): void { |
| 261 | this._maybePrintInnerComments(); |
| 262 | |
| 263 | // space is mandatory to avoid outputting <!-- |
| 264 | // http://javascript.spec.whatwg.org/#comment-syntax |
| 265 | const lastChar = this.getLastChar(); |
| 266 | if ( |
| 267 | // Need spaces for operators of the same kind to avoid: `a+++b` |
| 268 | (char === charCodes.plusSign && lastChar === charCodes.plusSign) || |
| 269 | (char === charCodes.dash && lastChar === charCodes.dash) || |
| 270 | // Needs spaces to avoid changing '34' to '34.', which would still be a valid number. |
| 271 | (char === charCodes.dot && this._endsWithInteger) |
| 272 | ) { |
| 273 | this._space(); |
| 274 | } |
| 275 | |
| 276 | this._maybeAddAuxComment(); |
| 277 | this._appendChar(char); |
| 278 | this._noLineTerminator = false; |
| 279 | } |
| 280 | |
| 281 | /** |
| 282 | * Add a newline (or many newlines), maintaining formatting. |
| 283 | * This function checks the number of newlines in the queue and subtracts them. |
| 284 | * It currently has some limitations. |
| 285 | * @see {Buffer#getNewlineCount} |
| 286 | */ |
| 287 | newline(i: number = 1, force?: boolean): void { |
| 288 | if (i <= 0) return; |
| 289 | |
| 290 | if (!force) { |
| 291 | if (this.format.retainLines || this.format.compact) return; |
| 292 | |
| 293 | if (this.format.concise) { |
| 294 | this.space(); |
| 295 | return; |
| 296 | } |
| 297 | } |
| 298 | |
| 299 | if (i > 2) i = 2; // Max two lines |
| 300 | |
| 301 | i -= this._buf.getNewlineCount(); |
| 302 | |
| 303 | for (let j = 0; j < i; j++) { |
| 304 | this._newline(); |
| 305 | } |
| 306 | |
| 307 | return; |
| 308 | } |
| 309 | |
| 310 | endsWith(char: number): boolean { |
| 311 | return this.getLastChar() === char; |
| 312 | } |
| 313 | |
| 314 | getLastChar(): number { |
| 315 | return this._buf.getLastChar(); |
| 316 | } |
| 317 | |
| 318 | endsWithCharAndNewline(): number { |
| 319 | return this._buf.endsWithCharAndNewline(); |
| 320 | } |
| 321 | |
| 322 | removeTrailingNewline(): void { |
| 323 | this._buf.removeTrailingNewline(); |
| 324 | } |
| 325 | |
| 326 | exactSource(loc: Loc | undefined, cb: () => void) { |
| 327 | if (!loc) return cb(); |
| 328 | |
| 329 | this._catchUp("start", loc); |
| 330 | |
| 331 | this._buf.exactSource(loc, cb); |
| 332 | } |
| 333 | |
| 334 | source(prop: "start" | "end", loc: Loc | undefined): void { |
| 335 | if (!loc) return; |
| 336 | |
| 337 | this._catchUp(prop, loc); |
| 338 | |
| 339 | this._buf.source(prop, loc); |
| 340 | } |
| 341 | |
| 342 | sourceWithOffset( |
| 343 | prop: "start" | "end", |
| 344 | loc: Loc | undefined, |
| 345 | lineOffset: number, |
| 346 | columnOffset: number, |
| 347 | ): void { |
| 348 | if (!loc) return; |
| 349 | |
| 350 | this._catchUp(prop, loc); |
| 351 | |
| 352 | this._buf.sourceWithOffset(prop, loc, lineOffset, columnOffset); |
| 353 | } |
| 354 | |
| 355 | withSource( |
| 356 | prop: "start" | "end", |
| 357 | loc: Loc | undefined, |
| 358 | cb: () => void, |
| 359 | ): void { |
| 360 | if (!loc) return cb(); |
| 361 | |
| 362 | this._catchUp(prop, loc); |
| 363 | |
| 364 | this._buf.withSource(prop, loc, cb); |
| 365 | } |
| 366 | |
| 367 | _space(): void { |
| 368 | this._queue(charCodes.space); |
| 369 | } |
| 370 | |
| 371 | _newline(): void { |
| 372 | this._queue(charCodes.lineFeed); |
| 373 | } |
| 374 | |
| 375 | _append(str: string, maybeNewline: boolean): void { |
| 376 | this._maybeAddParen(str); |
| 377 | this._maybeIndent(str.charCodeAt(0)); |
| 378 | |
| 379 | this._buf.append(str, maybeNewline); |
| 380 | |
| 381 | this._endsWithWord = false; |
| 382 | this._endsWithInteger = false; |
| 383 | } |
| 384 | |
| 385 | _appendChar(char: number): void { |
| 386 | this._maybeAddParenChar(char); |
| 387 | this._maybeIndent(char); |
| 388 | |
| 389 | this._buf.appendChar(char); |
| 390 | |
| 391 | this._endsWithWord = false; |
| 392 | this._endsWithInteger = false; |
| 393 | } |
| 394 | |
| 395 | _queue(char: number) { |
| 396 | this._maybeAddParenChar(char); |
| 397 | this._maybeIndent(char); |
| 398 | |
| 399 | this._buf.queue(char); |
| 400 | |
| 401 | this._endsWithWord = false; |
| 402 | this._endsWithInteger = false; |
| 403 | } |
| 404 | |
| 405 | _maybeIndent(firstChar: number): void { |
| 406 | // we've got a newline before us so prepend on the indentation |
| 407 | if ( |
| 408 | this._indent && |
| 409 | firstChar !== charCodes.lineFeed && |
| 410 | this.endsWith(charCodes.lineFeed) |
| 411 | ) { |
| 412 | this._buf.queueIndentation(this._indentChar, this._getIndent()); |
| 413 | } |
| 414 | } |
| 415 | |
| 416 | _shouldIndent(firstChar: number) { |
| 417 | // we've got a newline before us so prepend on the indentation |
| 418 | if ( |
| 419 | this._indent && |
| 420 | firstChar !== charCodes.lineFeed && |
| 421 | this.endsWith(charCodes.lineFeed) |
| 422 | ) { |
| 423 | return true; |
| 424 | } |
| 425 | } |
| 426 | |
| 427 | _maybeAddParenChar(char: number): void { |
| 428 | // see startTerminatorless() instance method |
| 429 | const parenPushNewlineState = this._parenPushNewlineState; |
| 430 | if (!parenPushNewlineState) return; |
| 431 | |
| 432 | // This function does two things: |
| 433 | // - If needed, prints a parenthesis |
| 434 | // - If the currently printed string removes the need for the paren, |
| 435 | // it resets the _parenPushNewlineState field. |
| 436 | // Almost everything removes the need for a paren, except for |
| 437 | // comments and whitespaces. |
| 438 | |
| 439 | if (char === charCodes.space) { |
| 440 | // Whitespaces only, the parentheses might still be needed. |
| 441 | return; |
| 442 | } |
| 443 | |
| 444 | // Check for newline or comment. |
| 445 | if (char !== charCodes.lineFeed) { |
| 446 | this._parenPushNewlineState = null; |
| 447 | return; |
| 448 | } |
| 449 | |
| 450 | this.token("("); |
| 451 | this.indent(); |
| 452 | parenPushNewlineState.printed = true; |
| 453 | } |
| 454 | |
| 455 | _maybeAddParen(str: string): void { |
| 456 | // see startTerminatorless() instance method |
| 457 | const parenPushNewlineState = this._parenPushNewlineState; |
| 458 | if (!parenPushNewlineState) return; |
| 459 | |
| 460 | // This function does two things: |
| 461 | // - If needed, prints a parenthesis |
| 462 | // - If the currently printed string removes the need for the paren, |
| 463 | // it resets the _parenPushNewlineState field. |
| 464 | // Almost everything removes the need for a paren, except for |
| 465 | // comments and whitespaces. |
| 466 | |
| 467 | const len = str.length; |
| 468 | |
| 469 | let i; |
| 470 | for (i = 0; i < len && str.charCodeAt(i) === charCodes.space; i++) continue; |
| 471 | if (i === len) { |
| 472 | // Whitespaces only, the parentheses might still be needed. |
| 473 | return; |
| 474 | } |
| 475 | |
| 476 | // Check for newline or comment. |
| 477 | const cha = str.charCodeAt(i); |
| 478 | if (cha !== charCodes.lineFeed) { |
| 479 | if ( |
| 480 | // This is not a comment (it doesn't start with /) |
| 481 | cha !== charCodes.slash || |
| 482 | // This is not a comment (it's a / operator) |
| 483 | i + 1 === len |
| 484 | ) { |
| 485 | // After a normal token, the parentheses aren't needed anymore |
| 486 | this._parenPushNewlineState = null; |
| 487 | return; |
| 488 | } |
| 489 | |
| 490 | const chaPost = str.charCodeAt(i + 1); |
| 491 | |
| 492 | if (chaPost === charCodes.asterisk) { |
| 493 | // This is a block comment |
| 494 | |
| 495 | if (PURE_ANNOTATION_RE.test(str.slice(i + 2, len - 2))) { |
| 496 | // We avoid printing newlines after #__PURE__ comments (we treat |
| 497 | // then as unary operators), but we must keep the old |
| 498 | // parenPushNewlineState because, if a newline was forbidden, it is |
| 499 | // still forbidden after the comment. |
| 500 | return; |
| 501 | } |
| 502 | |
| 503 | // NOTE: code flow continues from here to after these if/elses |
| 504 | } else if (chaPost !== charCodes.slash) { |
| 505 | // This is neither a block comment, nor a line comment. |
| 506 | // After a normal token, the parentheses aren't needed anymore |
| 507 | this._parenPushNewlineState = null; |
| 508 | return; |
| 509 | } |
| 510 | } |
| 511 | |
| 512 | this.token("("); |
| 513 | this.indent(); |
| 514 | parenPushNewlineState.printed = true; |
| 515 | } |
| 516 | |
| 517 | catchUp(line: number) { |
| 518 | if (!this.format.retainLines) return; |
| 519 | |
| 520 | // catch up to this nodes newline if we're behind |
| 521 | const count = line - this._buf.getCurrentLine(); |
| 522 | |
| 523 | for (let i = 0; i < count; i++) { |
| 524 | this._newline(); |
| 525 | } |
| 526 | } |
| 527 | |
| 528 | _catchUp(prop: "start" | "end", loc?: Loc) { |
| 529 | if (!this.format.retainLines) return; |
| 530 | |
| 531 | // catch up to this nodes newline if we're behind |
| 532 | const pos = loc ? loc[prop] : null; |
| 533 | if (pos?.line != null) { |
| 534 | const count = pos.line - this._buf.getCurrentLine(); |
| 535 | |
| 536 | for (let i = 0; i < count; i++) { |
| 537 | this._newline(); |
| 538 | } |
| 539 | } |
| 540 | } |
| 541 | |
| 542 | /** |
| 543 | * Get the current indent. |
| 544 | */ |
| 545 | |
| 546 | _getIndent(): number { |
| 547 | return this._indentRepeat * this._indent; |
| 548 | } |
| 549 | |
| 550 | printTerminatorless(node: t.Node, parent: t.Node, isLabel: boolean) { |
| 551 | /** |
| 552 | * Set some state that will be modified if a newline has been inserted before any |
| 553 | * non-space characters. |
| 554 | * |
| 555 | * This is to prevent breaking semantics for terminatorless separator nodes. eg: |
| 556 | * |
| 557 | * return foo; |
| 558 | * |
| 559 | * returns `foo`. But if we do: |
| 560 | * |
| 561 | * return |
| 562 | * foo; |
| 563 | * |
| 564 | * `undefined` will be returned and not `foo` due to the terminator. |
| 565 | */ |
| 566 | if (isLabel) { |
| 567 | this._noLineTerminator = true; |
| 568 | this.print(node, parent); |
| 569 | } else { |
| 570 | const terminatorState = { |
| 571 | printed: false, |
| 572 | }; |
| 573 | this._parenPushNewlineState = terminatorState; |
| 574 | this.print(node, parent); |
| 575 | /** |
| 576 | * Print an ending parentheses if a starting one has been printed. |
| 577 | */ |
| 578 | if (terminatorState.printed) { |
| 579 | this.dedent(); |
| 580 | this.newline(); |
| 581 | this.token(")"); |
| 582 | } |
| 583 | } |
| 584 | } |
| 585 | |
| 586 | print( |
| 587 | node: t.Node | null, |
| 588 | parent?: t.Node, |
| 589 | noLineTerminatorAfter?: boolean, |
| 590 | // trailingCommentsLineOffset also used to check if called from printJoin |
| 591 | // it will be ignored if `noLineTerminatorAfter||this._noLineTerminator` |
| 592 | trailingCommentsLineOffset?: number, |
| 593 | forceParens?: boolean, |
| 594 | ) { |
| 595 | if (!node) return; |
| 596 | |
| 597 | this._endsWithInnerRaw = false; |
| 598 | |
| 599 | const nodeType = node.type; |
| 600 | const format = this.format; |
| 601 | |
| 602 | const oldConcise = format.concise; |
| 603 | if ( |
| 604 | // @ts-expect-error document _compact AST properties |
| 605 | node._compact |
| 606 | ) { |
| 607 | format.concise = true; |
| 608 | } |
| 609 | |
| 610 | const printMethod = |
| 611 | this[ |
| 612 | nodeType as Exclude< |
| 613 | t.Node["type"], |
| 614 | // removed |
| 615 | | "Noop" |
| 616 | // renamed |
| 617 | | t.DeprecatedAliases["type"] |
| 618 | > |
| 619 | ]; |
| 620 | if (printMethod === undefined) { |
| 621 | throw new ReferenceError( |
| 622 | `unknown node of type ${JSON.stringify( |
| 623 | nodeType, |
| 624 | )} with constructor ${JSON.stringify(node.constructor.name)}`, |
| 625 | ); |
| 626 | } |
| 627 | |
| 628 | this._printStack.push(node); |
| 629 | |
| 630 | const oldInAux = this._insideAux; |
| 631 | this._insideAux = node.loc == undefined; |
| 632 | this._maybeAddAuxComment(this._insideAux && !oldInAux); |
| 633 | |
| 634 | let shouldPrintParens = false; |
| 635 | if (forceParens) { |
| 636 | shouldPrintParens = true; |
| 637 | } else if ( |
| 638 | format.retainFunctionParens && |
| 639 | nodeType === "FunctionExpression" && |
| 640 | node.extra && |
| 641 | node.extra.parenthesized |
| 642 | ) { |
| 643 | shouldPrintParens = true; |
| 644 | } else { |
| 645 | shouldPrintParens = needsParens(node, parent, this._printStack); |
| 646 | } |
| 647 | if (shouldPrintParens) { |
| 648 | this.token("("); |
| 649 | this._endsWithInnerRaw = false; |
| 650 | } |
| 651 | |
| 652 | this._lastCommentLine = 0; |
| 653 | |
| 654 | this._printLeadingComments(node, parent); |
| 655 | |
| 656 | const loc = nodeType === "Program" || nodeType === "File" ? null : node.loc; |
| 657 | |
| 658 | this.exactSource(loc, printMethod.bind(this, node, parent)); |
| 659 | |
| 660 | if (shouldPrintParens) { |
| 661 | this._printTrailingComments(node, parent); |
| 662 | this.token(")"); |
| 663 | this._noLineTerminator = noLineTerminatorAfter; |
| 664 | } else if (noLineTerminatorAfter && !this._noLineTerminator) { |
| 665 | this._noLineTerminator = true; |
| 666 | this._printTrailingComments(node, parent); |
| 667 | } else { |
| 668 | this._printTrailingComments(node, parent, trailingCommentsLineOffset); |
| 669 | } |
| 670 | |
| 671 | // end |
| 672 | this._printStack.pop(); |
| 673 | |
| 674 | format.concise = oldConcise; |
| 675 | this._insideAux = oldInAux; |
| 676 | |
| 677 | this._endsWithInnerRaw = false; |
| 678 | } |
| 679 | |
| 680 | _maybeAddAuxComment(enteredPositionlessNode?: boolean) { |
| 681 | if (enteredPositionlessNode) this._printAuxBeforeComment(); |
| 682 | if (!this._insideAux) this._printAuxAfterComment(); |
| 683 | } |
| 684 | |
| 685 | _printAuxBeforeComment() { |
| 686 | if (this._printAuxAfterOnNextUserNode) return; |
| 687 | this._printAuxAfterOnNextUserNode = true; |
| 688 | |
| 689 | const comment = this.format.auxiliaryCommentBefore; |
| 690 | if (comment) { |
| 691 | this._printComment( |
| 692 | { |
| 693 | type: "CommentBlock", |
| 694 | value: comment, |
| 695 | }, |
| 696 | COMMENT_SKIP_NEWLINE.DEFAULT, |
| 697 | ); |
| 698 | } |
| 699 | } |
| 700 | |
| 701 | _printAuxAfterComment() { |
| 702 | if (!this._printAuxAfterOnNextUserNode) return; |
| 703 | this._printAuxAfterOnNextUserNode = false; |
| 704 | |
| 705 | const comment = this.format.auxiliaryCommentAfter; |
| 706 | if (comment) { |
| 707 | this._printComment( |
| 708 | { |
| 709 | type: "CommentBlock", |
| 710 | value: comment, |
| 711 | }, |
| 712 | COMMENT_SKIP_NEWLINE.DEFAULT, |
| 713 | ); |
| 714 | } |
| 715 | } |
| 716 | |
| 717 | getPossibleRaw( |
| 718 | node: |
| 719 | | t.StringLiteral |
| 720 | | t.NumericLiteral |
| 721 | | t.BigIntLiteral |
| 722 | | t.DecimalLiteral |
| 723 | | t.DirectiveLiteral |
| 724 | | t.JSXText, |
| 725 | ): string | undefined { |
| 726 | const extra = node.extra; |
| 727 | if ( |
| 728 | extra && |
| 729 | extra.raw != null && |
| 730 | extra.rawValue != null && |
| 731 | node.value === extra.rawValue |
| 732 | ) { |
| 733 | // @ts-expect-error: The extra.raw of these AST node types must be a string |
| 734 | return extra.raw; |
| 735 | } |
| 736 | } |
| 737 | |
| 738 | printJoin( |
| 739 | nodes: Array<t.Node> | undefined | null, |
| 740 | parent: t.Node, |
| 741 | opts: PrintJoinOptions = {}, |
| 742 | ) { |
| 743 | if (!nodes?.length) return; |
| 744 | |
| 745 | if (opts.indent) this.indent(); |
| 746 | |
| 747 | const newlineOpts: AddNewlinesOptions = { |
| 748 | addNewlines: opts.addNewlines, |
| 749 | nextNodeStartLine: 0, |
| 750 | }; |
| 751 | |
| 752 | const separator = opts.separator ? opts.separator.bind(this) : null; |
| 753 | |
| 754 | const len = nodes.length; |
| 755 | for (let i = 0; i < len; i++) { |
| 756 | const node = nodes[i]; |
| 757 | if (!node) continue; |
| 758 | |
| 759 | if (opts.statement) this._printNewline(i === 0, newlineOpts); |
| 760 | |
| 761 | this.print(node, parent, undefined, opts.trailingCommentsLineOffset || 0); |
| 762 | |
| 763 | opts.iterator?.(node, i); |
| 764 | |
| 765 | if (i < len - 1) separator?.(); |
| 766 | |
| 767 | if (opts.statement) { |
| 768 | if (i + 1 === len) { |
| 769 | this.newline(1); |
| 770 | } else { |
| 771 | const nextNode = nodes[i + 1]; |
| 772 | newlineOpts.nextNodeStartLine = nextNode.loc?.start.line || 0; |
| 773 | |
| 774 | this._printNewline(true, newlineOpts); |
| 775 | } |
| 776 | } |
| 777 | } |
| 778 | |
| 779 | if (opts.indent) this.dedent(); |
| 780 | } |
| 781 | |
| 782 | printAndIndentOnComments(node: t.Node, parent: t.Node) { |
| 783 | const indent = node.leadingComments && node.leadingComments.length > 0; |
| 784 | if (indent) this.indent(); |
| 785 | this.print(node, parent); |
| 786 | if (indent) this.dedent(); |
| 787 | } |
| 788 | |
| 789 | printBlock(parent: Extract<t.Node, { body: t.Statement }>) { |
| 790 | const node = parent.body; |
| 791 | |
| 792 | if (node.type !== "EmptyStatement") { |
| 793 | this.space(); |
| 794 | } |
| 795 | |
| 796 | this.print(node, parent); |
| 797 | } |
| 798 | |
| 799 | _printTrailingComments(node: t.Node, parent?: t.Node, lineOffset?: number) { |
| 800 | const { innerComments, trailingComments } = node; |
| 801 | // We print inner comments here, so that if for some reason they couldn't |
| 802 | // be printed in earlier locations they are still printed *somehwere*, |
| 803 | // even if at the end of the node. |
| 804 | if (innerComments?.length) { |
| 805 | this._printComments( |
| 806 | COMMENT_TYPE.TRAILING, |
| 807 | innerComments, |
| 808 | node, |
| 809 | parent, |
| 810 | lineOffset, |
| 811 | ); |
| 812 | } |
| 813 | if (trailingComments?.length) { |
| 814 | this._printComments( |
| 815 | COMMENT_TYPE.TRAILING, |
| 816 | trailingComments, |
| 817 | node, |
| 818 | parent, |
| 819 | lineOffset, |
| 820 | ); |
| 821 | } |
| 822 | } |
| 823 | |
| 824 | _printLeadingComments(node: t.Node, parent: t.Node) { |
| 825 | const comments = node.leadingComments; |
| 826 | if (!comments?.length) return; |
| 827 | this._printComments(COMMENT_TYPE.LEADING, comments, node, parent); |
| 828 | } |
| 829 | |
| 830 | _maybePrintInnerComments() { |
| 831 | if (this._endsWithInnerRaw) this.printInnerComments(); |
| 832 | this._endsWithInnerRaw = true; |
| 833 | this._indentInnerComments = true; |
| 834 | } |
| 835 | |
| 836 | printInnerComments() { |
| 837 | const node = this._printStack[this._printStack.length - 1]; |
| 838 | const comments = node.innerComments; |
| 839 | if (!comments?.length) return; |
| 840 | |
| 841 | const hasSpace = this.endsWith(charCodes.space); |
| 842 | const indent = this._indentInnerComments; |
| 843 | const printedCommentsCount = this._printedComments.size; |
| 844 | if (indent) this.indent(); |
| 845 | this._printComments(COMMENT_TYPE.INNER, comments, node); |
| 846 | if (hasSpace && printedCommentsCount !== this._printedComments.size) { |
| 847 | this.space(); |
| 848 | } |
| 849 | if (indent) this.dedent(); |
| 850 | } |
| 851 | |
| 852 | noIndentInnerCommentsHere() { |
| 853 | this._indentInnerComments = false; |
| 854 | } |
| 855 | |
| 856 | printSequence( |
| 857 | nodes: t.Node[], |
| 858 | parent: t.Node, |
| 859 | opts: PrintSequenceOptions = {}, |
| 860 | ) { |
| 861 | opts.statement = true; |
| 862 | return this.printJoin(nodes, parent, opts); |
| 863 | } |
| 864 | |
| 865 | printList(items: t.Node[], parent: t.Node, opts: PrintListOptions = {}) { |
| 866 | if (opts.separator == null) { |
| 867 | opts.separator = commaSeparator; |
| 868 | } |
| 869 | |
| 870 | return this.printJoin(items, parent, opts); |
| 871 | } |
| 872 | |
| 873 | _printNewline(newLine: boolean, opts: AddNewlinesOptions) { |
| 874 | // Fast path since 'this.newline' does nothing when not tracking lines. |
| 875 | if (this.format.retainLines || this.format.compact) return; |
| 876 | |
| 877 | // Fast path for concise since 'this.newline' just inserts a space when |
| 878 | // concise formatting is in use. |
| 879 | if (this.format.concise) { |
| 880 | this.space(); |
| 881 | return; |
| 882 | } |
| 883 | |
| 884 | if (!newLine) { |
| 885 | return; |
| 886 | } |
| 887 | |
| 888 | const startLine = opts.nextNodeStartLine; |
| 889 | const lastCommentLine = this._lastCommentLine; |
| 890 | if (startLine > 0 && lastCommentLine > 0) { |
| 891 | const offset = startLine - lastCommentLine; |
| 892 | if (offset >= 0) { |
| 893 | this.newline(offset || 1); |
| 894 | return; |
| 895 | } |
| 896 | } |
| 897 | |
| 898 | // don't add newlines at the beginning of the file |
| 899 | if (this._buf.hasContent()) { |
| 900 | // Here is the logic of the original line wrapping according to the node layout, we are not using it now. |
| 901 | // We currently add at most one newline to each node in the list, ignoring `opts.addNewlines`. |
| 902 | |
| 903 | // let lines = 0; |
| 904 | // if (!leading) lines++; // always include at least a single line after |
| 905 | // if (opts.addNewlines) lines += opts.addNewlines(leading, node) || 0; |
| 906 | |
| 907 | // const needs = leading ? needsWhitespaceBefore : needsWhitespaceAfter; |
| 908 | // if (needs(node, parent)) lines++; |
| 909 | |
| 910 | // this.newline(Math.min(2, lines)); |
| 911 | |
| 912 | this.newline(1); |
| 913 | } |
| 914 | } |
| 915 | |
| 916 | // Returns `PRINT_COMMENT_HINT.DEFER` if the comment cannot be printed in this position due to |
| 917 | // line terminators, signaling that the print comments loop can stop and |
| 918 | // resume printing comments at the next possible position. This happens when |
| 919 | // printing inner comments, since if we have an inner comment with a multiline |
| 920 | // there is at least one inner position where line terminators are allowed. |
| 921 | _shouldPrintComment(comment: t.Comment): PRINT_COMMENT_HINT { |
| 922 | // Some plugins (such as flow-strip-types) use this to mark comments as removed using the AST-root 'comments' property, |
| 923 | // where they can't manually mutate the AST node comment lists. |
| 924 | if (comment.ignore) return PRINT_COMMENT_HINT.SKIP; |
| 925 | |
| 926 | if (this._printedComments.has(comment)) return PRINT_COMMENT_HINT.SKIP; |
| 927 | |
| 928 | if ( |
| 929 | this._noLineTerminator && |
| 930 | (HAS_NEWLINE.test(comment.value) || |
| 931 | HAS_BlOCK_COMMENT_END.test(comment.value)) |
| 932 | ) { |
| 933 | return PRINT_COMMENT_HINT.DEFER; |
| 934 | } |
| 935 | |
| 936 | this._printedComments.add(comment); |
| 937 | |
| 938 | if (!this.format.shouldPrintComment(comment.value)) { |
| 939 | return PRINT_COMMENT_HINT.SKIP; |
| 940 | } |
| 941 | |
| 942 | return PRINT_COMMENT_HINT.ALLOW; |
| 943 | } |
| 944 | |
| 945 | _printComment(comment: t.Comment, skipNewLines: COMMENT_SKIP_NEWLINE) { |
| 946 | const noLineTerminator = this._noLineTerminator; |
| 947 | const isBlockComment = comment.type === "CommentBlock"; |
| 948 | |
| 949 | // Add a newline before and after a block comment, unless explicitly |
| 950 | // disallowed |
| 951 | const printNewLines = |
| 952 | isBlockComment && |
| 953 | skipNewLines !== COMMENT_SKIP_NEWLINE.ALL && |
| 954 | !this._noLineTerminator; |
| 955 | |
| 956 | if ( |
| 957 | printNewLines && |
| 958 | this._buf.hasContent() && |
| 959 | skipNewLines !== COMMENT_SKIP_NEWLINE.LEADING |
| 960 | ) { |
| 961 | this.newline(1); |
| 962 | } |
| 963 | |
| 964 | const lastCharCode = this.getLastChar(); |
| 965 | if ( |
| 966 | lastCharCode !== charCodes.leftSquareBracket && |
| 967 | lastCharCode !== charCodes.leftCurlyBrace |
| 968 | ) { |
| 969 | this.space(); |
| 970 | } |
| 971 | |
| 972 | let val; |
| 973 | if (isBlockComment) { |
| 974 | val = `/*${comment.value}*/`; |
| 975 | if (this.format.indent.adjustMultilineComment) { |
| 976 | const offset = comment.loc?.start.column; |
| 977 | if (offset) { |
| 978 | const newlineRegex = new RegExp("\\n\\s{1," + offset + "}", "g"); |
| 979 | val = val.replace(newlineRegex, "\n"); |
| 980 | } |
| 981 | |
| 982 | let indentSize = this.format.retainLines |
| 983 | ? 0 |
| 984 | : this._buf.getCurrentColumn(); |
| 985 | |
| 986 | if (this._shouldIndent(charCodes.slash) || this.format.retainLines) { |
| 987 | indentSize += this._getIndent(); |
| 988 | } |
| 989 | |
| 990 | val = val.replace(/\n(?!$)/g, `\n${" ".repeat(indentSize)}`); |
| 991 | } |
| 992 | } else if (!noLineTerminator) { |
| 993 | val = `//${comment.value}`; |
| 994 | } else { |
| 995 | // It was a single-line comment, so it's guaranteed to not |
| 996 | // contain newlines and it can be safely printed as a block |
| 997 | // comment. |
| 998 | val = `/*${comment.value}*/`; |
| 999 | } |
| 1000 | |
| 1001 | // Avoid creating //* comments |
| 1002 | if (this.endsWith(charCodes.slash)) this._space(); |
| 1003 | |
| 1004 | this.source("start", comment.loc); |
| 1005 | this._append(val, isBlockComment); |
| 1006 | |
| 1007 | if (!isBlockComment && !noLineTerminator) { |
| 1008 | this.newline(1, true); |
| 1009 | } |
| 1010 | |
| 1011 | if (printNewLines && skipNewLines !== COMMENT_SKIP_NEWLINE.TRAILING) { |
| 1012 | this.newline(1); |
| 1013 | } |
| 1014 | } |
| 1015 | |
| 1016 | _printComments( |
| 1017 | type: COMMENT_TYPE, |
| 1018 | comments: readonly t.Comment[], |
| 1019 | node: t.Node, |
| 1020 | parent?: t.Node, |
| 1021 | lineOffset: number = 0, |
| 1022 | ) { |
| 1023 | const nodeLoc = node.loc; |
| 1024 | const len = comments.length; |
| 1025 | let hasLoc = !!nodeLoc; |
| 1026 | const nodeStartLine = hasLoc ? nodeLoc.start.line : 0; |
| 1027 | const nodeEndLine = hasLoc ? nodeLoc.end.line : 0; |
| 1028 | let lastLine = 0; |
| 1029 | let leadingCommentNewline = 0; |
| 1030 | |
| 1031 | const maybeNewline = this._noLineTerminator |
| 1032 | ? function () {} |
| 1033 | : this.newline.bind(this); |
| 1034 | |
| 1035 | for (let i = 0; i < len; i++) { |
| 1036 | const comment = comments[i]; |
| 1037 | |
| 1038 | const shouldPrint = this._shouldPrintComment(comment); |
| 1039 | if (shouldPrint === PRINT_COMMENT_HINT.DEFER) { |
| 1040 | hasLoc = false; |
| 1041 | break; |
| 1042 | } |
| 1043 | if (hasLoc && comment.loc && shouldPrint === PRINT_COMMENT_HINT.ALLOW) { |
| 1044 | const commentStartLine = comment.loc.start.line; |
| 1045 | const commentEndLine = comment.loc.end.line; |
| 1046 | if (type === COMMENT_TYPE.LEADING) { |
| 1047 | let offset = 0; |
| 1048 | if (i === 0) { |
| 1049 | // Because currently we cannot handle blank lines before leading comments, |
| 1050 | // we always wrap before and after multi-line comments. |
| 1051 | if ( |
| 1052 | this._buf.hasContent() && |
| 1053 | (comment.type === "CommentLine" || |
| 1054 | commentStartLine != commentEndLine) |
| 1055 | ) { |
| 1056 | offset = leadingCommentNewline = 1; |
| 1057 | } |
| 1058 | } else { |
| 1059 | offset = commentStartLine - lastLine; |
| 1060 | } |
| 1061 | lastLine = commentEndLine; |
| 1062 | |
| 1063 | maybeNewline(offset); |
| 1064 | this._printComment(comment, COMMENT_SKIP_NEWLINE.ALL); |
| 1065 | |
| 1066 | if (i + 1 === len) { |
| 1067 | maybeNewline( |
| 1068 | Math.max(nodeStartLine - lastLine, leadingCommentNewline), |
| 1069 | ); |
| 1070 | lastLine = nodeStartLine; |
| 1071 | } |
| 1072 | } else if (type === COMMENT_TYPE.INNER) { |
| 1073 | const offset = |
| 1074 | commentStartLine - (i === 0 ? nodeStartLine : lastLine); |
| 1075 | lastLine = commentEndLine; |
| 1076 | |
| 1077 | maybeNewline(offset); |
| 1078 | this._printComment(comment, COMMENT_SKIP_NEWLINE.ALL); |
| 1079 | |
| 1080 | if (i + 1 === len) { |
| 1081 | maybeNewline(Math.min(1, nodeEndLine - lastLine)); // TODO: Improve here when inner comments processing is stronger |
| 1082 | lastLine = nodeEndLine; |
| 1083 | } |
| 1084 | } else { |
| 1085 | const offset = |
| 1086 | commentStartLine - (i === 0 ? nodeEndLine - lineOffset : lastLine); |
| 1087 | lastLine = commentEndLine; |
| 1088 | |
| 1089 | maybeNewline(offset); |
| 1090 | this._printComment(comment, COMMENT_SKIP_NEWLINE.ALL); |
| 1091 | } |
| 1092 | } else { |
| 1093 | hasLoc = false; |
| 1094 | if (shouldPrint !== PRINT_COMMENT_HINT.ALLOW) { |
| 1095 | continue; |
| 1096 | } |
| 1097 | |
| 1098 | if (len === 1) { |
| 1099 | const singleLine = comment.loc |
| 1100 | ? comment.loc.start.line === comment.loc.end.line |
| 1101 | : !HAS_NEWLINE.test(comment.value); |
| 1102 | |
| 1103 | const shouldSkipNewline = |
| 1104 | singleLine && |
| 1105 | !isStatement(node) && |
| 1106 | !isClassBody(parent) && |
| 1107 | !isTSInterfaceBody(parent) && |
| 1108 | !isTSEnumDeclaration(parent); |
| 1109 | |
| 1110 | if (type === COMMENT_TYPE.LEADING) { |
| 1111 | this._printComment( |
| 1112 | comment, |
| 1113 | (shouldSkipNewline && node.type !== "ObjectExpression") || |
| 1114 | (singleLine && isFunction(parent, { body: node })) |
| 1115 | ? COMMENT_SKIP_NEWLINE.ALL |
| 1116 | : COMMENT_SKIP_NEWLINE.DEFAULT, |
| 1117 | ); |
| 1118 | } else if (shouldSkipNewline && type === COMMENT_TYPE.TRAILING) { |
| 1119 | this._printComment(comment, COMMENT_SKIP_NEWLINE.ALL); |
| 1120 | } else { |
| 1121 | this._printComment(comment, COMMENT_SKIP_NEWLINE.DEFAULT); |
| 1122 | } |
| 1123 | } else if ( |
| 1124 | type === COMMENT_TYPE.INNER && |
| 1125 | !(node.type === "ObjectExpression" && node.properties.length > 1) && |
| 1126 | node.type !== "ClassBody" && |
| 1127 | node.type !== "TSInterfaceBody" |
| 1128 | ) { |
| 1129 | // class X { |
| 1130 | // /*:: a: number*/ |
| 1131 | // /*:: b: ?string*/ |
| 1132 | // } |
| 1133 | |
| 1134 | this._printComment( |
| 1135 | comment, |
| 1136 | i === 0 |
| 1137 | ? COMMENT_SKIP_NEWLINE.LEADING |
| 1138 | : i === len - 1 |
| 1139 | ? COMMENT_SKIP_NEWLINE.TRAILING |
| 1140 | : COMMENT_SKIP_NEWLINE.DEFAULT, |
| 1141 | ); |
| 1142 | } else { |
| 1143 | this._printComment(comment, COMMENT_SKIP_NEWLINE.DEFAULT); |
| 1144 | } |
| 1145 | } |
| 1146 | } |
| 1147 | |
| 1148 | if (type === COMMENT_TYPE.TRAILING && hasLoc && lastLine) { |
| 1149 | this._lastCommentLine = lastLine; |
| 1150 | } |
| 1151 | } |
| 1152 | } |
| 1153 | |
| 1154 | // Expose the node type functions and helpers on the prototype for easy usage. |
| 1155 | Object.assign(Printer.prototype, generatorFunctions); |
| 1156 | |
| 1157 | if (!process.env.BABEL_8_BREAKING) { |
| 1158 | // @ts-ignore(Babel 7 vs Babel 8) Babel 7 has Noop print method |
| 1159 | Printer.prototype.Noop = function Noop(this: Printer) {}; |
| 1160 | } |
| 1161 | |
| 1162 | type GeneratorFunctions = typeof generatorFunctions; |
| 1163 | interface Printer extends GeneratorFunctions {} |
| 1164 | export default Printer; |
| 1165 | |
| 1166 | function commaSeparator(this: Printer) { |
| 1167 | this.token(","); |
| 1168 | this.space(); |
| 1169 | } |