From e0d072a09b2ef3fc76a46183447ea2ba939ebf6b Mon Sep 17 00:00:00 2001 From: Nitin Kumar Date: Sat, 23 Jul 2022 16:47:46 +0530 Subject: [PATCH] fix: check if comment is after the `{` token --- lib/rules/lines-around-comment.js | 12 ++++-- tests/lib/rules/lines-around-comment.js | 50 +++++++++++++++++++++++++ 2 files changed, 59 insertions(+), 3 deletions(-) diff --git a/lib/rules/lines-around-comment.js b/lib/rules/lines-around-comment.js index 1c1a174c407..2c1b2f40199 100644 --- a/lib/rules/lines-around-comment.js +++ b/lib/rules/lines-around-comment.js @@ -231,9 +231,15 @@ module.exports = { const parent = getParentNodeOfToken(token); if (parent && isParentNodeType(parent, nodeType)) { - const parentStartNodeOrToken = parent.type === "StaticBlock" - ? sourceCode.getFirstToken(parent, { skip: 1 }) // opening brace of the static block - : parent; + let parentStartNodeOrToken = parent; + + if (parent.type === "StaticBlock") { + parentStartNodeOrToken = sourceCode.getFirstToken(parent, { skip: 1 }); // opening brace of the static block + } else if (parent.type === "SwitchStatement") { + parentStartNodeOrToken = sourceCode.getFirstToken(parent, { + filter: t => t.type === "Punctuator" && t.value === "{" + }); // opening brace of the switch statement + } return token.loc.start.line - parentStartNodeOrToken.loc.start.line === 1; } diff --git a/tests/lib/rules/lines-around-comment.js b/tests/lib/rules/lines-around-comment.js index ded745d2315..9fa1c559bbb 100644 --- a/tests/lib/rules/lines-around-comment.js +++ b/tests/lib/rules/lines-around-comment.js @@ -384,6 +384,23 @@ ruleTester.run("lines-around-comment", rule, { allowBlockEnd: true }] }, + { + code: ` + switch (foo) + { + // this comment is allowed by allowBlockStart: true + + case 1: + bar(); + break; + } + `, + options: [{ + allowBlockStart: true, + beforeLineComment: true, + afterLineComment: true + }] + }, // check for block end comments { @@ -2127,6 +2144,39 @@ ruleTester.run("lines-around-comment", rule, { output: "foo;\n\n/* fallthrough */", options: [], errors: [{ messageId: "before", type: "Block" }] + }, + { + code: ` + switch ( + // this comment is not allowed by allowBlockStart: true + + foo + ) + { + case 1: + bar(); + break; + } + `, + output: ` + switch ( + + // this comment is not allowed by allowBlockStart: true + + foo + ) + { + case 1: + bar(); + break; + } + `, + options: [{ + allowBlockStart: true, + beforeLineComment: true, + afterLineComment: true + }], + errors: [{ messageId: "before", type: "Line" }] } ]