Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: fix indent bug with semicolon-first style #15951

Merged
merged 2 commits into from Jun 3, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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