Skip to content

Commit 55319e1

Browse files
authored
feat: fix indent bug with semicolon-first style (#15951)
* feat: fix indent bug with semicolon-first style Fixes #15930 * add test with else-if
1 parent f6d7920 commit 55319e1

2 files changed

Lines changed: 751 additions & 12 deletions

File tree

lib/rules/indent.js

Lines changed: 44 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -916,18 +916,6 @@ module.exports = {
916916
}
917917

918918
offsets.setDesiredOffsets([firstBodyToken.range[0], lastBodyToken.range[1]], lastParentToken, 1);
919-
920-
/*
921-
* For blockless nodes with semicolon-first style, don't indent the semicolon.
922-
* e.g.
923-
* if (foo) bar()
924-
* ; [1, 2, 3].map(foo)
925-
*/
926-
const lastToken = sourceCode.getLastToken(node);
927-
928-
if (node.type !== "EmptyStatement" && astUtils.isSemicolonToken(lastToken)) {
929-
offsets.setDesiredOffset(lastToken, lastParentToken, 0);
930-
}
931919
}
932920
}
933921

@@ -1271,6 +1259,50 @@ module.exports = {
12711259
}
12721260
},
12731261

1262+
/*
1263+
* For blockless nodes with semicolon-first style, don't indent the semicolon.
1264+
* e.g.
1265+
* if (foo)
1266+
* bar()
1267+
* ; [1, 2, 3].map(foo)
1268+
*
1269+
* Traversal into the node sets indentation of the semicolon, so we need to override it on exit.
1270+
*/
1271+
":matches(DoWhileStatement, ForStatement, ForInStatement, ForOfStatement, IfStatement, WhileStatement):exit"(node) {
1272+
let nodesToCheck;
1273+
1274+
if (node.type === "IfStatement") {
1275+
nodesToCheck = [node.consequent];
1276+
if (node.alternate) {
1277+
nodesToCheck.push(node.alternate);
1278+
}
1279+
} else {
1280+
nodesToCheck = [node.body];
1281+
}
1282+
1283+
for (const nodeToCheck of nodesToCheck) {
1284+
const lastToken = sourceCode.getLastToken(nodeToCheck);
1285+
1286+
if (astUtils.isSemicolonToken(lastToken)) {
1287+
const tokenBeforeLast = sourceCode.getTokenBefore(lastToken);
1288+
const tokenAfterLast = sourceCode.getTokenAfter(lastToken);
1289+
1290+
// override indentation of `;` only if its line looks like a semicolon-first style line
1291+
if (
1292+
!astUtils.isTokenOnSameLine(tokenBeforeLast, lastToken) &&
1293+
tokenAfterLast &&
1294+
astUtils.isTokenOnSameLine(lastToken, tokenAfterLast)
1295+
) {
1296+
offsets.setDesiredOffset(
1297+
lastToken,
1298+
sourceCode.getFirstToken(node),
1299+
0
1300+
);
1301+
}
1302+
}
1303+
}
1304+
},
1305+
12741306
ImportDeclaration(node) {
12751307
if (node.specifiers.some(specifier => specifier.type === "ImportSpecifier")) {
12761308
const openingCurly = sourceCode.getFirstToken(node, astUtils.isOpeningBraceToken);

0 commit comments

Comments
 (0)