Fix logic to insert parens in return statements with comments (#11306)

This commit is contained in:
Nicolò Ribaudo 2020-03-21 20:53:38 +01:00 committed by GitHub
parent 5b2c1f34d3
commit b0315b81c7
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 54 additions and 7 deletions

View File

@ -249,22 +249,57 @@ export default class Printer {
// see startTerminatorless() instance method // see startTerminatorless() instance method
const parenPushNewlineState = this._parenPushNewlineState; const parenPushNewlineState = this._parenPushNewlineState;
if (!parenPushNewlineState) return; if (!parenPushNewlineState) return;
this._parenPushNewlineState = null;
// This function does two things:
// - If needed, prints a parenthesis
// - If the currently printed string removes the need for the paren,
// it resets the _parenPushNewlineState field.
// Almost everything removes the need for a paren, except for
// comments and whitespaces.
let i; let i;
for (i = 0; i < str.length && str[i] === " "; i++) continue; for (i = 0; i < str.length && str[i] === " "; i++) continue;
if (i === str.length) return; if (i === str.length) {
// Whitespaces only, the parentheses might still be needed.
return;
}
// Check for newline or comment. // Check for newline or comment.
const cha = str[i]; const cha = str[i];
if (cha !== "\n") { if (cha !== "\n") {
if (cha !== "/") return; if (
if (i + 1 === str.length) return; // This is not a comment (it doesn't start with /)
const chaPost = str[i + 1]; cha !== "/" ||
if (chaPost !== "/" && chaPost !== "*") return; // This is not a comment (it's a / operator)
// We don't print newlines aroung /*#__PURE__*/ annotations i + 1 === str.length
if (PURE_ANNOTATION_RE.test(str.slice(i + 2, str.length - 2))) return; ) {
// After a normal token, the parentheses aren't needed anymore
this._parenPushNewlineState = null;
return;
} }
const chaPost = str[i + 1];
if (chaPost === "*") {
// This is a block comment
if (PURE_ANNOTATION_RE.test(str.slice(i + 2, str.length - 2))) {
// We avoid printing newlines after #__PURE__ comments (we treat
// then as unary operators), but we must keep the old
// parenPushNewlineState because, if a newline was forbidden, it is
// still forbidden after the comment.
return;
}
// NOTE: code flow continues from here to after these if/elses
} else if (chaPost !== "/") {
// This is neither a block comment, nor a line comment.
// After a normal token, the parentheses aren't needed anymore
this._parenPushNewlineState = null;
return;
}
}
this.token("("); this.token("(");
this.indent(); this.indent();
parenPushNewlineState.printed = true; parenPushNewlineState.printed = true;

View File

@ -0,0 +1,7 @@
function f() {
return (
/*#__PURE__*/
//test
0
);
}

View File

@ -0,0 +1,3 @@
{
"compact": true
}

View File

@ -0,0 +1,2 @@
function f(){return/*#__PURE__*/ (//test
0);}