diff --git a/packages/babel-generator/src/buffer.js b/packages/babel-generator/src/buffer.js index 6b6e20d4d0..65b35ce16d 100644 --- a/packages/babel-generator/src/buffer.js +++ b/packages/babel-generator/src/buffer.js @@ -26,6 +26,7 @@ export default class Buffer { column: null, filename: null, }; + this._endsWithWord = false; } printedCommentStarts: Object; @@ -44,7 +45,7 @@ export default class Buffer { // catch up to this nodes newline if we're behind if (node.loc && this.format.retainLines && this.buf) { while (this.position.line < node.loc.start.line) { - this._push("\n"); + this.push("\n"); } } } @@ -98,15 +99,7 @@ export default class Buffer { */ semicolon() { - this.push(";"); - } - - /** - * Ensure last character is a semicolon. - */ - - ensureSemicolon() { - if (!this.isLast(";")) this.semicolon(); + this.token(";"); } /** @@ -118,7 +111,7 @@ export default class Buffer { if (this.format.minified && !this._lastPrintedIsEmptyStatement) { this._removeLast(";"); } - this.push("}"); + this.token("}"); } /** @@ -126,22 +119,52 @@ export default class Buffer { */ keyword(name: string) { - this.push(name); + this.word(name); this.space(); } /** - * Add a space to the buffer unless it is compact (override with force). + * Add a space to the buffer unless it is compact. */ - space(force?: boolean) { - if (!force && this.format.compact) return; + space() { + if (this.format.compact) return; - if (force || this.buf && !this.isLast(" ") && !this.isLast("\n")) { + if (this.buf && !this.endsWith(" ") && !this.endsWith("\n")) { this.push(" "); } } + /** + * Writes a token that can't be safely parsed without taking whitespace into account. + */ + + word(str: string) { + if (this._endsWithWord) this.push(" "); + + this.push(str); + this._endsWithWord = true; + } + + /** + * Writes a simple token. + */ + + token(str: string) { + // space is mandatory to avoid outputting