Skip to content

Commit b021c4f

Browse files
Fix #14497 FN variableScope (else branch, regression) (#8227)
1 parent 179f04a commit b021c4f

3 files changed

Lines changed: 15 additions & 3 deletions

File tree

lib/checkother.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1292,7 +1292,7 @@ void CheckOther::checkVariableScope()
12921292
tok = tok->link();
12931293

12941294
// parse else if blocks..
1295-
} else if (Token::simpleMatch(tok, "else { if (") && Token::simpleMatch(tok->linkAt(3), ") {")) {
1295+
} else if (Token::simpleMatch(tok, "else { if (") && tok->next()->isSimplifiedScope() && Token::simpleMatch(tok->linkAt(3), ") {")) {
12961296
tok = tok->next();
12971297
} else if (tok->varId() == var->declarationId() || tok->str() == "goto") {
12981298
reduce = false;

lib/tokenize.cpp

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7964,8 +7964,8 @@ void Tokenizer::elseif()
79647964

79657965
if (Token::Match(tok2, "}|;")) {
79667966
if (tok2->next() && tok2->strAt(1) != "else") {
7967-
tok->insertToken("{");
7968-
tok2->insertToken("}");
7967+
tok->insertToken("{")->isSimplifiedScope(true);
7968+
tok2->insertToken("}")->isSimplifiedScope(true);
79697969
Token::createMutualLinks(tok->next(), tok2->next());
79707970
break;
79717971
}

test/testother.cpp

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -122,6 +122,7 @@ class TestOther : public TestFixture {
122122
TEST_CASE(varScope42);
123123
TEST_CASE(varScope43);
124124
TEST_CASE(varScope44);
125+
TEST_CASE(varScope45);
125126

126127
TEST_CASE(oldStylePointerCast);
127128
TEST_CASE(intToPointerCast);
@@ -1972,6 +1973,17 @@ class TestOther : public TestFixture {
19721973
errout_str());
19731974
}
19741975

1976+
void varScope45() {
1977+
check("void g(int x, int y) {\n" // #14497
1978+
" int a = x, b = y;\n"
1979+
" if (a) {}\n"
1980+
" else {\n"
1981+
" if (b) {}\n"
1982+
" }\n"
1983+
"}\n");
1984+
ASSERT_EQUALS("[test.cpp:2:16]: (style) The scope of the variable 'b' can be reduced. [variableScope]\n", errout_str());
1985+
}
1986+
19751987
#define checkOldStylePointerCast(...) checkOldStylePointerCast_(__FILE__, __LINE__, __VA_ARGS__)
19761988
template<size_t size>
19771989
void checkOldStylePointerCast_(const char* file, int line, const char (&code)[size], Standards::cppstd_t std = Standards::CPPLatest) {

0 commit comments

Comments
 (0)