Skip to content

Commit

Permalink
feat: update semi rule for class static blocks (#15286)
Browse files Browse the repository at this point in the history
Updates `omitLastInOneLineBlock` option to apply to class static blocks.

Refs #15016
  • Loading branch information
mdjermanovic committed Nov 15, 2021
1 parent a2e6328 commit 0f0971f
Show file tree
Hide file tree
Showing 3 changed files with 395 additions and 11 deletions.
8 changes: 8 additions & 0 deletions docs/rules/semi.md
Expand Up @@ -172,6 +172,14 @@ Examples of additional **correct** code for this rule with the `"always", { "omi
if (foo) { bar() }

if (foo) { bar(); baz() }

function f() { bar(); baz() }

class C {
foo() { bar(); baz() }

static { bar(); baz() }
}
```

#### beforeStatementContinuationChars
Expand Down
27 changes: 18 additions & 9 deletions lib/rules/semi.js
Expand Up @@ -306,22 +306,31 @@ module.exports = {
}

/**
* Checks a node to see if it's in a one-liner block statement.
* Checks a node to see if it's the last item in a one-liner block.
* Block is any `BlockStatement` or `StaticBlock` node. Block is a one-liner if its
* braces (and consequently everything between them) are on the same line.
* @param {ASTNode} node The node to check.
* @returns {boolean} whether the node is in a one-liner block statement.
* @returns {boolean} whether the node is the last item in a one-liner block.
*/
function isOneLinerBlock(node) {
function isLastInOneLinerBlock(node) {
const parent = node.parent;
const nextToken = sourceCode.getTokenAfter(node);

if (!nextToken || nextToken.value !== "}") {
return false;
}
return (
!!parent &&
parent.type === "BlockStatement" &&
parent.loc.start.line === parent.loc.end.line
);

if (parent.type === "BlockStatement") {
return parent.loc.start.line === parent.loc.end.line;
}

if (parent.type === "StaticBlock") {
const openingBrace = sourceCode.getFirstToken(parent, { skip: 1 }); // skip the `static` token

return openingBrace.loc.start.line === parent.loc.end.line;
}

return false;
}

/**
Expand All @@ -343,7 +352,7 @@ module.exports = {
report(node);
}
} else {
const oneLinerBlock = (exceptOneLine && isOneLinerBlock(node));
const oneLinerBlock = (exceptOneLine && isLastInOneLinerBlock(node));

if (isSemi && oneLinerBlock) {
report(node, true);
Expand Down

0 comments on commit 0f0971f

Please sign in to comment.