| 1 | // From packages\babel-generator\src\printer.ts |
| 2 | |
| 3 | import Buffer from "./buffer"; |
| 4 | import type { Loc } from "./buffer"; |
| 5 | import * as n from "./node"; |
| 6 | import type * as t from "@babel/types"; |
| 7 | import type { |
| 8 | RecordAndTuplePluginOptions, |
| 9 | PipelineOperatorPluginOptions, |
| 10 | } from "@babel/parser"; |
| 11 | import type { Opts as jsescOptions } from "jsesc"; |
| 12 | |
| 13 | import * as generatorFunctions from "./generators"; |
| 14 | import type SourceMap from "./source-map"; |
| 15 | import * as charCodes from "charcodes"; |
| 16 | |
| 17 | const SCIENTIFIC_NOTATION = /e/i; |
| 18 | const ZERO_DECIMAL_INTEGER = /\.0+$/; |
| 19 | const NON_DECIMAL_LITERAL = /^0[box]/; |
| 20 | const PURE_ANNOTATION_RE = /^\s*[@#]__PURE__\s*$/; |
| 21 | |
| 22 | const { needsParens, needsWhitespaceAfter, needsWhitespaceBefore } = n; |
| 23 | |
| 24 | export type Format = { |
| 25 | shouldPrintComment: (comment: string) => boolean; |
| 26 | retainLines: boolean; |
| 27 | retainFunctionParens: boolean; |
| 28 | comments: boolean; |
| 29 | auxiliaryCommentBefore: string; |
| 30 | auxiliaryCommentAfter: string; |
| 31 | compact: boolean | "auto"; |
| 32 | minified: boolean; |
| 33 | concise: boolean; |
| 34 | indent: { |
| 35 | adjustMultilineComment: boolean; |
| 36 | style: string; |
| 37 | }; |
| 38 | recordAndTupleSyntaxType: RecordAndTuplePluginOptions["syntaxType"]; |
| 39 | jsescOption: jsescOptions; |
| 40 | jsonCompatibleStrings?: boolean; |
| 41 | /** |
| 42 | * For use with the Hack-style pipe operator. |
| 43 | * Changes what token is used for pipe bodies’ topic references. |
| 44 | */ |
| 45 | topicToken?: PipelineOperatorPluginOptions["topicToken"]; |
| 46 | /** |
| 47 | * @deprecated Removed in Babel 8 |
| 48 | */ |
| 49 | decoratorsBeforeExport?: boolean; |
| 50 | }; |
| 51 | |
| 52 | interface AddNewlinesOptions { |
| 53 | addNewlines(leading: boolean, node: t.Node): number; |
| 54 | } |
| 55 | |
| 56 | interface PrintSequenceOptions extends Partial<AddNewlinesOptions> { |
| 57 | statement?: boolean; |
| 58 | indent?: boolean; |
| 59 | } |
| 60 | |
| 61 | interface PrintListOptions { |
| 62 | separator?: (this: Printer) => void; |
| 63 | statement?: boolean; |
| 64 | indent?: boolean; |
| 65 | } |
| 66 | |
| 67 | type PrintJoinOptions = PrintListOptions & |
| 68 | PrintSequenceOptions & { |
| 69 | iterator?: (node: t.Node, index: number) => void; |
| 70 | }; |
| 71 | class Printer { |
| 72 | constructor(format: Format, map: SourceMap) { |
| 73 | this.format = format; |
| 74 | this._buf = new Buffer(map); |
| 75 | |
| 76 | this._indentChar = format.indent.style.charCodeAt(0); |
| 77 | this._indentRepeat = format.indent.style.length; |
| 78 | } |
| 79 | |
| 80 | declare format: Format; |
| 81 | inForStatementInitCounter: number = 0; |
| 82 | |
| 83 | declare _buf: Buffer; |
| 84 | _printStack: Array<t.Node> = []; |
| 85 | _indent: number = 0; |
| 86 | _indentChar: number = 0; |
| 87 | _indentRepeat: number = 0; |
| 88 | _insideAux: boolean = false; |
| 89 | _parenPushNewlineState: { printed: boolean } | null = null; |
| 90 | _noLineTerminator: boolean = false; |
| 91 | _printAuxAfterOnNextUserNode: boolean = false; |
| 92 | _printedComments = new Set<t.Comment>(); |
| 93 | _endsWithInteger = false; |
| 94 | _endsWithWord = false; |
| 95 | |
| 96 | generate(ast: t.Node) { |
| 97 | this.print(ast); |
| 98 | this._maybeAddAuxComment(); |
| 99 | |
| 100 | return this._buf.get(); |
| 101 | } |
| 102 | |
| 103 | /** |
| 104 | * Increment indent size. |
| 105 | */ |
| 106 | |
| 107 | indent(): void { |
| 108 | if (this.format.compact || this.format.concise) return; |
| 109 | |
| 110 | this._indent++; |
| 111 | } |
| 112 | |
| 113 | /** |
| 114 | * Decrement indent size. |
| 115 | */ |
| 116 | |
| 117 | dedent(): void { |
| 118 | if (this.format.compact || this.format.concise) return; |
| 119 | |
| 120 | this._indent--; |
| 121 | } |
| 122 | |
| 123 | /** |
| 124 | * Add a semicolon to the buffer. |
| 125 | */ |
| 126 | |
| 127 | semicolon(force: boolean = false): void { |
| 128 | this._maybeAddAuxComment(); |
| 129 | if (force) { |
| 130 | this._appendChar(charCodes.semicolon); |
| 131 | } else { |
| 132 | this._queue(charCodes.semicolon); |
| 133 | } |
| 134 | } |
| 135 | |
| 136 | /** |
| 137 | * Add a right brace to the buffer. |
| 138 | */ |
| 139 | |
| 140 | rightBrace(): void { |
| 141 | if (this.format.minified) { |
| 142 | this._buf.removeLastSemicolon(); |
| 143 | } |
| 144 | this.token("}"); |
| 145 | } |
| 146 | |
| 147 | /** |
| 148 | * Add a space to the buffer unless it is compact. |
| 149 | */ |
| 150 | |
| 151 | space(force: boolean = false): void { |
| 152 | if (this.format.compact) return; |
| 153 | |
| 154 | if (force) { |
| 155 | this._space(); |
| 156 | } else if (this._buf.hasContent()) { |
| 157 | const lastCp = this.getLastChar(); |
| 158 | if (lastCp !== charCodes.space && lastCp !== charCodes.lineFeed) { |
| 159 | this._space(); |
| 160 | } |
| 161 | } |
| 162 | } |
| 163 | |
| 164 | /** |
| 165 | * Writes a token that can't be safely parsed without taking whitespace into account. |
| 166 | */ |
| 167 | |
| 168 | word(str: string): void { |
| 169 | // prevent concatenating words and creating // comment out of division and regex |
| 170 | if ( |
| 171 | this._endsWithWord || |
| 172 | (str.charCodeAt(0) === charCodes.slash && this.endsWith(charCodes.slash)) |
| 173 | ) { |
| 174 | this._space(); |
| 175 | } |
| 176 | |
| 177 | this._maybeAddAuxComment(); |
| 178 | this._append(str, false); |
| 179 | |
| 180 | this._endsWithWord = true; |
| 181 | } |
| 182 | |
| 183 | /** |
| 184 | * Writes a number token so that we can validate if it is an integer. |
| 185 | */ |
| 186 | |
| 187 | number(str: string): void { |
| 188 | this.word(str); |
| 189 | |
| 190 | // Integer tokens need special handling because they cannot have '.'s inserted |
| 191 | // immediately after them. |
| 192 | this._endsWithInteger = |
| 193 | Number.isInteger(+str) && |
| 194 | !NON_DECIMAL_LITERAL.test(str) && |
| 195 | !SCIENTIFIC_NOTATION.test(str) && |
| 196 | !ZERO_DECIMAL_INTEGER.test(str) && |
| 197 | str.charCodeAt(str.length - 1) !== charCodes.dot; |
| 198 | } |
| 199 | |
| 200 | /** |
| 201 | * Writes a simple token. |
| 202 | */ |
| 203 | |
| 204 | token(str: string, maybeNewline = false): void { |
| 205 | // space is mandatory to avoid outputting <!-- |
| 206 | // http://javascript.spec.whatwg.org/#comment-syntax |
| 207 | const lastChar = this.getLastChar(); |
| 208 | const strFirst = str.charCodeAt(0); |
| 209 | if ( |
| 210 | (lastChar === charCodes.exclamationMark && str === "--") || |
| 211 | // Need spaces for operators of the same kind to avoid: `a+++b` |
| 212 | (strFirst === charCodes.plusSign && lastChar === charCodes.plusSign) || |
| 213 | (strFirst === charCodes.dash && lastChar === charCodes.dash) || |
| 214 | // Needs spaces to avoid changing '34' to '34.', which would still be a valid number. |
| 215 | (strFirst === charCodes.dot && this._endsWithInteger) |
| 216 | ) { |
| 217 | this._space(); |
| 218 | } |
| 219 | |
| 220 | this._maybeAddAuxComment(); |
| 221 | this._append(str, maybeNewline); |
| 222 | } |
| 223 | |
| 224 | tokenChar(char: number): void { |
| 225 | // space is mandatory to avoid outputting <!-- |
| 226 | // http://javascript.spec.whatwg.org/#comment-syntax |
| 227 | const lastChar = this.getLastChar(); |
| 228 | if ( |
| 229 | // Need spaces for operators of the same kind to avoid: `a+++b` |
| 230 | (char === charCodes.plusSign && lastChar === charCodes.plusSign) || |
| 231 | (char === charCodes.dash && lastChar === charCodes.dash) || |
| 232 | // Needs spaces to avoid changing '34' to '34.', which would still be a valid number. |
| 233 | (char === charCodes.dot && this._endsWithInteger) |
| 234 | ) { |
| 235 | this._space(); |
| 236 | } |
| 237 | |
| 238 | this._maybeAddAuxComment(); |
| 239 | this._appendChar(char); |
| 240 | } |
| 241 | |
| 242 | /** |
| 243 | * Add a newline (or many newlines), maintaining formatting. |
| 244 | */ |
| 245 | |
| 246 | newline(i: number = 1): void { |
| 247 | if (this.format.retainLines || this.format.compact) return; |
| 248 | |
| 249 | if (this.format.concise) { |
| 250 | this.space(); |
| 251 | return; |
| 252 | } |
| 253 | |
| 254 | const charBeforeNewline = this.endsWithCharAndNewline(); |
| 255 | // never allow more than two lines |
| 256 | if (charBeforeNewline === charCodes.lineFeed) return; |
| 257 | |
| 258 | if ( |
| 259 | charBeforeNewline === charCodes.leftCurlyBrace || |
| 260 | charBeforeNewline === charCodes.colon |
| 261 | ) { |
| 262 | i--; |
| 263 | } |
| 264 | if (i <= 0) return; |
| 265 | |
| 266 | for (let j = 0; j < i; j++) { |
| 267 | this._newline(); |
| 268 | } |
| 269 | } |
| 270 | |
| 271 | endsWith(char: number): boolean { |
| 272 | return this.getLastChar() === char; |
| 273 | } |
| 274 | |
| 275 | getLastChar(): number { |
| 276 | return this._buf.getLastChar(); |
| 277 | } |
| 278 | |
| 279 | endsWithCharAndNewline(): number { |
| 280 | return this._buf.endsWithCharAndNewline(); |
| 281 | } |
| 282 | |
| 283 | removeTrailingNewline(): void { |
| 284 | this._buf.removeTrailingNewline(); |
| 285 | } |
| 286 | |
| 287 | exactSource(loc: Loc | undefined, cb: () => void) { |
| 288 | this._catchUp("start", loc); |
| 289 | |
| 290 | this._buf.exactSource(loc, cb); |
| 291 | } |
| 292 | |
| 293 | source(prop: "start" | "end", loc: Loc | undefined): void { |
| 294 | this._catchUp(prop, loc); |
| 295 | |
| 296 | this._buf.source(prop, loc); |
| 297 | } |
| 298 | |
| 299 | sourceWithOffset( |
| 300 | prop: "start" | "end", |
| 301 | loc: Loc | undefined, |
| 302 | lineOffset: number, |
| 303 | columnOffset: number, |
| 304 | ): void { |
| 305 | this._catchUp(prop, loc); |
| 306 | |
| 307 | this._buf.sourceWithOffset(prop, loc, lineOffset, columnOffset); |
| 308 | } |
| 309 | |
| 310 | withSource( |
| 311 | prop: "start" | "end", |
| 312 | loc: Loc | undefined, |
| 313 | cb: () => void, |
| 314 | ): void { |
| 315 | this._catchUp(prop, loc); |
| 316 | |
| 317 | this._buf.withSource(prop, loc, cb); |
| 318 | } |
| 319 | |
| 320 | _space(): void { |
| 321 | this._queue(charCodes.space); |
| 322 | } |
| 323 | |
| 324 | _newline(): void { |
| 325 | this._queue(charCodes.lineFeed); |
| 326 | } |
| 327 | |
| 328 | _append(str: string, maybeNewline: boolean): void { |
| 329 | this._maybeAddParen(str); |
| 330 | this._maybeIndent(str.charCodeAt(0)); |
| 331 | |
| 332 | this._buf.append(str, maybeNewline); |
| 333 | |
| 334 | this._endsWithWord = false; |
| 335 | this._endsWithInteger = false; |
| 336 | } |
| 337 | |
| 338 | _appendChar(char: number): void { |
| 339 | this._maybeAddParenChar(char); |
| 340 | this._maybeIndent(char); |
| 341 | |
| 342 | this._buf.appendChar(char); |
| 343 | |
| 344 | this._endsWithWord = false; |
| 345 | this._endsWithInteger = false; |
| 346 | } |
| 347 | |
| 348 | _queue(char: number) { |
| 349 | this._maybeAddParenChar(char); |
| 350 | this._maybeIndent(char); |
| 351 | |
| 352 | this._buf.queue(char); |
| 353 | |
| 354 | this._endsWithWord = false; |
| 355 | this._endsWithInteger = false; |
| 356 | } |
| 357 | |
| 358 | _maybeIndent(firstChar: number): void { |
| 359 | // we've got a newline before us so prepend on the indentation |
| 360 | if ( |
| 361 | this._indent && |
| 362 | firstChar !== charCodes.lineFeed && |
| 363 | this.endsWith(charCodes.lineFeed) |
| 364 | ) { |
| 365 | this._buf.queueIndentation(this._indentChar, this._getIndent()); |
| 366 | } |
| 367 | } |
| 368 | |
| 369 | _maybeAddParenChar(char: number): void { |
| 370 | // see startTerminatorless() instance method |
| 371 | const parenPushNewlineState = this._parenPushNewlineState; |
| 372 | if (!parenPushNewlineState) return; |
| 373 | |
| 374 | // This function does two things: |
| 375 | // - If needed, prints a parenthesis |
| 376 | // - If the currently printed string removes the need for the paren, |
| 377 | // it resets the _parenPushNewlineState field. |
| 378 | // Almost everything removes the need for a paren, except for |
| 379 | // comments and whitespaces. |
| 380 | |
| 381 | if (char === charCodes.space) { |
| 382 | // Whitespaces only, the parentheses might still be needed. |
| 383 | return; |
| 384 | } |
| 385 | |
| 386 | // Check for newline or comment. |
| 387 | if (char !== charCodes.lineFeed) { |
| 388 | this._parenPushNewlineState = null; |
| 389 | return; |
| 390 | } |
| 391 | |
| 392 | this.token("("); |
| 393 | this.indent(); |
| 394 | parenPushNewlineState.printed = true; |
| 395 | } |
| 396 | |
| 397 | _maybeAddParen(str: string): void { |
| 398 | // see startTerminatorless() instance method |
| 399 | const parenPushNewlineState = this._parenPushNewlineState; |
| 400 | if (!parenPushNewlineState) return; |
| 401 | |
| 402 | // This function does two things: |
| 403 | // - If needed, prints a parenthesis |
| 404 | // - If the currently printed string removes the need for the paren, |
| 405 | // it resets the _parenPushNewlineState field. |
| 406 | // Almost everything removes the need for a paren, except for |
| 407 | // comments and whitespaces. |
| 408 | |
| 409 | const len = str.length; |
| 410 | |
| 411 | let i; |
| 412 | for (i = 0; i < len && str.charCodeAt(i) === charCodes.space; i++) continue; |
| 413 | if (i === len) { |
| 414 | // Whitespaces only, the parentheses might still be needed. |
| 415 | return; |
| 416 | } |
| 417 | |
| 418 | // Check for newline or comment. |
| 419 | const cha = str.charCodeAt(i); |
| 420 | if (cha !== charCodes.lineFeed) { |
| 421 | if ( |
| 422 | // This is not a comment (it doesn't start with /) |
| 423 | cha !== charCodes.slash || |
| 424 | // This is not a comment (it's a / operator) |
| 425 | i + 1 === len |
| 426 | ) { |
| 427 | // After a normal token, the parentheses aren't needed anymore |
| 428 | this._parenPushNewlineState = null; |
| 429 | return; |
| 430 | } |
| 431 | |
| 432 | const chaPost = str.charCodeAt(i + 1); |
| 433 | |
| 434 | if (chaPost === charCodes.asterisk) { |
| 435 | // This is a block comment |
| 436 | |
| 437 | if (PURE_ANNOTATION_RE.test(str.slice(i + 2, len - 2))) { |
| 438 | // We avoid printing newlines after #__PURE__ comments (we treat |
| 439 | // then as unary operators), but we must keep the old |
| 440 | // parenPushNewlineState because, if a newline was forbidden, it is |
| 441 | // still forbidden after the comment. |
| 442 | return; |
| 443 | } |
| 444 | |
| 445 | // NOTE: code flow continues from here to after these if/elses |
| 446 | } else if (chaPost !== charCodes.slash) { |
| 447 | // This is neither a block comment, nor a line comment. |
| 448 | // After a normal token, the parentheses aren't needed anymore |
| 449 | this._parenPushNewlineState = null; |
| 450 | return; |
| 451 | } |
| 452 | } |
| 453 | |
| 454 | this.token("("); |
| 455 | this.indent(); |
| 456 | parenPushNewlineState.printed = true; |
| 457 | } |
| 458 | |
| 459 | _catchUp(prop: "start" | "end", loc?: Loc) { |
| 460 | if (!this.format.retainLines) return; |
| 461 | |
| 462 | // catch up to this nodes newline if we're behind |
| 463 | const pos = loc ? loc[prop] : null; |
| 464 | if (pos?.line != null) { |
| 465 | const count = pos.line - this._buf.getCurrentLine(); |
| 466 | |
| 467 | for (let i = 0; i < count; i++) { |
| 468 | this._newline(); |
| 469 | } |
| 470 | } |
| 471 | } |
| 472 | |
| 473 | /** |
| 474 | * Get the current indent. |
| 475 | */ |
| 476 | |
| 477 | _getIndent(): number { |
| 478 | return this._indentRepeat * this._indent; |
| 479 | } |
| 480 | |
| 481 | printTerminatorless(node: t.Node, parent: t.Node, isLabel: boolean) { |
| 482 | /** |
| 483 | * Set some state that will be modified if a newline has been inserted before any |
| 484 | * non-space characters. |
| 485 | * |
| 486 | * This is to prevent breaking semantics for terminatorless separator nodes. eg: |
| 487 | * |
| 488 | * return foo; |
| 489 | * |
| 490 | * returns `foo`. But if we do: |
| 491 | * |
| 492 | * return |
| 493 | * foo; |
| 494 | * |
| 495 | * `undefined` will be returned and not `foo` due to the terminator. |
| 496 | */ |
| 497 | if (isLabel) { |
| 498 | this._noLineTerminator = true; |
| 499 | this.print(node, parent); |
| 500 | this._noLineTerminator = false; |
| 501 | } else { |
| 502 | const terminatorState = { |
| 503 | printed: false, |
| 504 | }; |
| 505 | this._parenPushNewlineState = terminatorState; |
| 506 | this.print(node, parent); |
| 507 | /** |
| 508 | * Print an ending parentheses if a starting one has been printed. |
| 509 | */ |
| 510 | if (terminatorState.printed) { |
| 511 | this.dedent(); |
| 512 | this.newline(); |
| 513 | this.token(")"); |
| 514 | } |
| 515 | } |
| 516 | } |
| 517 | |
| 518 | print(node: t.Node | null, parent?: t.Node, noLineTerminator?: boolean) { |
| 519 | if (!node) return; |
| 520 | |
| 521 | const nodeType = node.type; |
| 522 | const format = this.format; |
| 523 | |
| 524 | const oldConcise = format.concise; |
| 525 | if ( |
| 526 | // @ts-expect-error document _compact AST properties |
| 527 | node._compact |
| 528 | ) { |
| 529 | format.concise = true; |
| 530 | } |
| 531 | |
| 532 | const printMethod = |
| 533 | this[ |
| 534 | nodeType as Exclude< |
| 535 | t.Node["type"], |
| 536 | // removed |
| 537 | | "Noop" |
| 538 | // renamed |
| 539 | | t.DeprecatedAliases["type"] |
| 540 | > |
| 541 | ]; |
| 542 | if (printMethod === undefined) { |
| 543 | throw new ReferenceError( |
| 544 | `unknown node of type ${JSON.stringify( |
| 545 | nodeType, |
| 546 | )} with constructor ${JSON.stringify(node.constructor.name)}`, |
| 547 | ); |
| 548 | } |
| 549 | |
| 550 | this._printStack.push(node); |
| 551 | |
| 552 | const oldInAux = this._insideAux; |
| 553 | this._insideAux = node.loc == undefined; |
| 554 | this._maybeAddAuxComment(this._insideAux && !oldInAux); |
| 555 | |
| 556 | let shouldPrintParens: boolean; |
| 557 | if ( |
| 558 | format.retainFunctionParens && |
| 559 | nodeType === "FunctionExpression" && |
| 560 | node.extra && |
| 561 | node.extra.parenthesized |
| 562 | ) { |
| 563 | shouldPrintParens = true; |
| 564 | } else { |
| 565 | shouldPrintParens = needsParens(node, parent, this._printStack); |
| 566 | } |
| 567 | if (shouldPrintParens) this.token("("); |
| 568 | |
| 569 | this._printLeadingComments(node); |
| 570 | |
| 571 | const loc = nodeType === "Program" || nodeType === "File" ? null : node.loc; |
| 572 | |
| 573 | this.exactSource(loc, printMethod.bind(this, node, parent)); |
| 574 | |
| 575 | if (noLineTerminator && !this._noLineTerminator) { |
| 576 | this._noLineTerminator = true; |
| 577 | this._printTrailingComments(node); |
| 578 | this._noLineTerminator = false; |
| 579 | } else { |
| 580 | this._printTrailingComments(node); |
| 581 | } |
| 582 | |
| 583 | if (shouldPrintParens) this.token(")"); |
| 584 | |
| 585 | // end |
| 586 | this._printStack.pop(); |
| 587 | |
| 588 | format.concise = oldConcise; |
| 589 | this._insideAux = oldInAux; |
| 590 | } |
| 591 | |
| 592 | _maybeAddAuxComment(enteredPositionlessNode?: boolean) { |
| 593 | if (enteredPositionlessNode) this._printAuxBeforeComment(); |
| 594 | if (!this._insideAux) this._printAuxAfterComment(); |
| 595 | } |
| 596 | |
| 597 | _printAuxBeforeComment() { |
| 598 | if (this._printAuxAfterOnNextUserNode) return; |
| 599 | this._printAuxAfterOnNextUserNode = true; |
| 600 | |
| 601 | const comment = this.format.auxiliaryCommentBefore; |
| 602 | if (comment) { |
| 603 | this._printComment({ |
| 604 | type: "CommentBlock", |
| 605 | value: comment, |
| 606 | }); |
| 607 | } |
| 608 | } |
| 609 | |
| 610 | _printAuxAfterComment() { |
| 611 | if (!this._printAuxAfterOnNextUserNode) return; |
| 612 | this._printAuxAfterOnNextUserNode = false; |
| 613 | |
| 614 | const comment = this.format.auxiliaryCommentAfter; |
| 615 | if (comment) { |
| 616 | this._printComment({ |
| 617 | type: "CommentBlock", |
| 618 | value: comment, |
| 619 | }); |
| 620 | } |
| 621 | } |
| 622 | |
| 623 | getPossibleRaw( |
| 624 | node: |
| 625 | | t.StringLiteral |
| 626 | | t.NumericLiteral |
| 627 | | t.BigIntLiteral |
| 628 | | t.DecimalLiteral |
| 629 | | t.DirectiveLiteral |
| 630 | | t.JSXText, |
| 631 | ): string | undefined { |
| 632 | const extra = node.extra; |
| 633 | if ( |
| 634 | extra && |
| 635 | extra.raw != null && |
| 636 | extra.rawValue != null && |
| 637 | node.value === extra.rawValue |
| 638 | ) { |
| 639 | // @ts-expect-error: The extra.raw of these AST node types must be a string |
| 640 | return extra.raw; |
| 641 | } |
| 642 | } |
| 643 | |
| 644 | printJoin( |
| 645 | nodes: Array<t.Node> | undefined | null, |
| 646 | parent: t.Node, |
| 647 | opts: PrintJoinOptions = {}, |
| 648 | ) { |
| 649 | if (!nodes?.length) return; |
| 650 | |
| 651 | if (opts.indent) this.indent(); |
| 652 | |
| 653 | const newlineOpts: AddNewlinesOptions = { |
| 654 | addNewlines: opts.addNewlines, |
| 655 | }; |
| 656 | |
| 657 | const len = nodes.length; |
| 658 | for (let i = 0; i < len; i++) { |
| 659 | const node = nodes[i]; |
| 660 | if (!node) continue; |
| 661 | |
| 662 | if (opts.statement) this._printNewline(true, node, parent, newlineOpts); |
| 663 | |
| 664 | this.print(node, parent); |
| 665 | |
| 666 | if (opts.iterator) { |
| 667 | opts.iterator(node, i); |
| 668 | } |
| 669 | |
| 670 | if (opts.separator && i < len - 1) { |
| 671 | opts.separator.call(this); |
| 672 | } |
| 673 | |
| 674 | if (opts.statement) this._printNewline(false, node, parent, newlineOpts); |
| 675 | } |
| 676 | |
| 677 | if (opts.indent) this.dedent(); |
| 678 | } |
| 679 | |
| 680 | printAndIndentOnComments(node: t.Node, parent: t.Node) { |
| 681 | const indent = node.leadingComments && node.leadingComments.length > 0; |
| 682 | if (indent) this.indent(); |
| 683 | this.print(node, parent); |
| 684 | if (indent) this.dedent(); |
| 685 | } |
| 686 | |
| 687 | printBlock(parent: Extract<t.Node, { body: t.Statement }>) { |
| 688 | const node = parent.body; |
| 689 | |
| 690 | if (node.type !== "EmptyStatement") { |
| 691 | this.space(); |
| 692 | } |
| 693 | |
| 694 | this.print(node, parent); |
| 695 | } |
| 696 | |
| 697 | _printTrailingComments(node: t.Node) { |
| 698 | this._printComments(this._getComments(false, node)); |
| 699 | } |
| 700 | |
| 701 | _printLeadingComments(node: t.Node) { |
| 702 | this._printComments( |
| 703 | this._getComments(true, node), |
| 704 | // Don't add leading/trailing new lines to #__PURE__ annotations |
| 705 | true, |
| 706 | ); |
| 707 | } |
| 708 | |
| 709 | printInnerComments(node: t.Node, indent = true) { |
| 710 | if (!node.innerComments?.length) return; |
| 711 | if (indent) this.indent(); |
| 712 | this._printComments(node.innerComments); |
| 713 | if (indent) this.dedent(); |
| 714 | } |
| 715 | |
| 716 | printSequence( |
| 717 | nodes: t.Node[], |
| 718 | parent: t.Node, |
| 719 | opts: PrintSequenceOptions = {}, |
| 720 | ) { |
| 721 | opts.statement = true; |
| 722 | return this.printJoin(nodes, parent, opts); |
| 723 | } |
| 724 | |
| 725 | printList(items: t.Node[], parent: t.Node, opts: PrintListOptions = {}) { |
| 726 | if (opts.separator == null) { |
| 727 | opts.separator = commaSeparator; |
| 728 | } |
| 729 | |
| 730 | return this.printJoin(items, parent, opts); |
| 731 | } |
| 732 | |
| 733 | _printNewline( |
| 734 | leading: boolean, |
| 735 | node: t.Node, |
| 736 | parent: t.Node, |
| 737 | opts: AddNewlinesOptions, |
| 738 | ) { |
| 739 | // Fast path since 'this.newline' does nothing when not tracking lines. |
| 740 | if (this.format.retainLines || this.format.compact) return; |
| 741 | |
| 742 | // Fast path for concise since 'this.newline' just inserts a space when |
| 743 | // concise formatting is in use. |
| 744 | if (this.format.concise) { |
| 745 | this.space(); |
| 746 | return; |
| 747 | } |
| 748 | |
| 749 | let lines = 0; |
| 750 | // don't add newlines at the beginning of the file |
| 751 | if (this._buf.hasContent()) { |
| 752 | if (!leading) lines++; // always include at least a single line after |
| 753 | if (opts.addNewlines) lines += opts.addNewlines(leading, node) || 0; |
| 754 | |
| 755 | const needs = leading ? needsWhitespaceBefore : needsWhitespaceAfter; |
| 756 | if (needs(node, parent)) lines++; |
| 757 | } |
| 758 | |
| 759 | this.newline(Math.min(2, lines)); |
| 760 | } |
| 761 | |
| 762 | _getComments(leading: boolean, node: t.Node) { |
| 763 | // Note, we use a boolean flag here instead of passing in the attribute name as it is faster |
| 764 | // because this is called extremely frequently. |
| 765 | return ( |
| 766 | (node && (leading ? node.leadingComments : node.trailingComments)) || null |
| 767 | ); |
| 768 | } |
| 769 | |
| 770 | _printComment(comment: t.Comment, skipNewLines?: boolean) { |
| 771 | // Some plugins (such as flow-strip-types) use this to mark comments as removed using the AST-root 'comments' property, |
| 772 | // where they can't manually mutate the AST node comment lists. |
| 773 | if (comment.ignore) return; |
| 774 | |
| 775 | if (this._printedComments.has(comment)) return; |
| 776 | |
| 777 | if (!this.format.shouldPrintComment(comment.value)) return; |
| 778 | |
| 779 | this._printedComments.add(comment); |
| 780 | |
| 781 | const isBlockComment = comment.type === "CommentBlock"; |
| 782 | |
| 783 | // Add a newline before and after a block comment, unless explicitly |
| 784 | // disallowed |
| 785 | const printNewLines = |
| 786 | isBlockComment && !skipNewLines && !this._noLineTerminator; |
| 787 | |
| 788 | if (printNewLines && this._buf.hasContent()) this.newline(1); |
| 789 | |
| 790 | const lastCharCode = this.getLastChar(); |
| 791 | if ( |
| 792 | lastCharCode !== charCodes.leftSquareBracket && |
| 793 | lastCharCode !== charCodes.leftCurlyBrace |
| 794 | ) { |
| 795 | this.space(); |
| 796 | } |
| 797 | |
| 798 | let val; |
| 799 | let maybeNewline = false; |
| 800 | if (isBlockComment) { |
| 801 | val = `/*${comment.value}*/`; |
| 802 | if (this.format.indent.adjustMultilineComment) { |
| 803 | const offset = comment.loc?.start.column; |
| 804 | if (offset) { |
| 805 | const newlineRegex = new RegExp("\\n\\s{1," + offset + "}", "g"); |
| 806 | val = val.replace(newlineRegex, "\n"); |
| 807 | } |
| 808 | |
| 809 | const indentSize = Math.max( |
| 810 | this._getIndent(), |
| 811 | this.format.retainLines ? 0 : this._buf.getCurrentColumn(), |
| 812 | ); |
| 813 | val = val.replace(/\n(?!$)/g, `\n${" ".repeat(indentSize)}`); |
| 814 | |
| 815 | maybeNewline = true; |
| 816 | } |
| 817 | } else if (!this._noLineTerminator) { |
| 818 | val = `//${comment.value}\n`; |
| 819 | maybeNewline = true; |
| 820 | } else { |
| 821 | val = `/*${comment.value}*/`; |
| 822 | } |
| 823 | |
| 824 | // Avoid creating //* comments |
| 825 | if (this.endsWith(charCodes.slash)) this._space(); |
| 826 | |
| 827 | this.withSource( |
| 828 | "start", |
| 829 | comment.loc, |
| 830 | this._append.bind(this, val, maybeNewline), |
| 831 | ); |
| 832 | |
| 833 | if (printNewLines) this.newline(1); |
| 834 | } |
| 835 | |
| 836 | _printComments( |
| 837 | comments?: readonly t.Comment[], |
| 838 | inlinePureAnnotation?: boolean, |
| 839 | ) { |
| 840 | if (!comments?.length) return; |
| 841 | |
| 842 | if ( |
| 843 | inlinePureAnnotation && |
| 844 | comments.length === 1 && |
| 845 | PURE_ANNOTATION_RE.test(comments[0].value) |
| 846 | ) { |
| 847 | this._printComment( |
| 848 | comments[0], |
| 849 | // Keep newlines if the comment marks a standalone call |
| 850 | this._buf.hasContent() && !this.endsWith(charCodes.lineFeed), |
| 851 | ); |
| 852 | } else { |
| 853 | for (const comment of comments) { |
| 854 | this._printComment(comment); |
| 855 | } |
| 856 | } |
| 857 | } |
| 858 | // todo(flow->ts): was Node |
| 859 | printAssertions(node: Extract<t.Node, { assertions?: t.ImportAttribute[] }>) { |
| 860 | if (node.assertions?.length) { |
| 861 | this.space(); |
| 862 | this.word("assert"); |
| 863 | this.space(); |
| 864 | this.token("{"); |
| 865 | this.space(); |
| 866 | this.printList(node.assertions, node); |
| 867 | this.space(); |
| 868 | this.token("}"); |
| 869 | } |
| 870 | } |
| 871 | } |
| 872 | |
| 873 | // Expose the node type functions and helpers on the prototype for easy usage. |
| 874 | Object.assign(Printer.prototype, generatorFunctions); |
| 875 | |
| 876 | if (!process.env.BABEL_8_BREAKING) { |
| 877 | // @ts-ignore(Babel 7 vs Babel 8) Babel 7 has Noop print method |
| 878 | Printer.prototype.Noop = function Noop(this: Printer) {}; |
| 879 | } |
| 880 | |
| 881 | type GeneratorFunctions = typeof generatorFunctions; |
| 882 | interface Printer extends GeneratorFunctions {} |
| 883 | export default Printer; |
| 884 | |
| 885 | function commaSeparator(this: Printer) { |
| 886 | this.token(","); |
| 887 | this.space(); |
| 888 | } |