Skip to content

Commit

Permalink
feat: fix indent bug with semicolon-first style (#15951)
Browse files Browse the repository at this point in the history
* feat: fix indent bug with semicolon-first style

Fixes #15930

* add test with else-if
  • Loading branch information
mdjermanovic committed Jun 3, 2022
1 parent f6d7920 commit 55319e1
Show file tree
Hide file tree
Showing 2 changed files with 751 additions and 12 deletions.
56 changes: 44 additions & 12 deletions lib/rules/indent.js
Expand Up @@ -916,18 +916,6 @@ module.exports = {
}

offsets.setDesiredOffsets([firstBodyToken.range[0], lastBodyToken.range[1]], lastParentToken, 1);

/*
* For blockless nodes with semicolon-first style, don't indent the semicolon.
* e.g.
* if (foo) bar()
* ; [1, 2, 3].map(foo)
*/
const lastToken = sourceCode.getLastToken(node);

if (node.type !== "EmptyStatement" && astUtils.isSemicolonToken(lastToken)) {
offsets.setDesiredOffset(lastToken, lastParentToken, 0);
}
}
}

Expand Down Expand Up @@ -1271,6 +1259,50 @@ module.exports = {
}
},

/*
* For blockless nodes with semicolon-first style, don't indent the semicolon.
* e.g.
* if (foo)
* bar()
* ; [1, 2, 3].map(foo)
*
* Traversal into the node sets indentation of the semicolon, so we need to override it on exit.
*/
":matches(DoWhileStatement, ForStatement, ForInStatement, ForOfStatement, IfStatement, WhileStatement):exit"(node) {
let nodesToCheck;

if (node.type === "IfStatement") {
nodesToCheck = [node.consequent];
if (node.alternate) {
nodesToCheck.push(node.alternate);
}
} else {
nodesToCheck = [node.body];
}

for (const nodeToCheck of nodesToCheck) {
const lastToken = sourceCode.getLastToken(nodeToCheck);

if (astUtils.isSemicolonToken(lastToken)) {
const tokenBeforeLast = sourceCode.getTokenBefore(lastToken);
const tokenAfterLast = sourceCode.getTokenAfter(lastToken);

// override indentation of `;` only if its line looks like a semicolon-first style line
if (
!astUtils.isTokenOnSameLine(tokenBeforeLast, lastToken) &&
tokenAfterLast &&
astUtils.isTokenOnSameLine(lastToken, tokenAfterLast)
) {
offsets.setDesiredOffset(
lastToken,
sourceCode.getFirstToken(node),
0
);
}
}
}
},

ImportDeclaration(node) {
if (node.specifiers.some(specifier => specifier.type === "ImportSpecifier")) {
const openingCurly = sourceCode.getFirstToken(node, astUtils.isOpeningBraceToken);
Expand Down

0 comments on commit 55319e1

Please sign in to comment.