Skip to content

Commit beb3362

Browse files
Fix #13838 FP variableScope with stuctured binding (#7521)
Co-authored-by: chrchr-github <[email protected]>
1 parent 1bbbc28 commit beb3362

File tree

3 files changed

+27
-1
lines changed

3 files changed

+27
-1
lines changed

lib/astutils.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1163,7 +1163,7 @@ static bool hasUnknownVars(const Token* startTok)
11631163

11641164
bool isStructuredBindingVariable(const Variable* var)
11651165
{
1166-
if (!var)
1166+
if (!var || var->isArray())
11671167
return false;
11681168
const Token* tok = var->nameToken();
11691169
while (tok && Token::Match(tok->astParent(), "[|,|:"))

lib/checkother.cpp

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1093,6 +1093,9 @@ void CheckOther::checkVariableScope()
10931093

10941094
if (var->nameToken()->isExpandedMacro())
10951095
continue;
1096+
if (isStructuredBindingVariable(var) && // warn for single decomposition
1097+
!(Token::simpleMatch(var->nameToken()->astParent(), "[") && var->nameToken()->astParent()->astOperand2() == var->nameToken()))
1098+
continue;
10961099

10971100
const bool isPtrOrRef = var->isPointer() || var->isReference();
10981101
const bool isSimpleType = var->typeStartToken()->isStandardType() || var->typeStartToken()->isEnumType() || (var->typeStartToken()->isC() && var->type() && var->type()->isStructType());

test/testother.cpp

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,7 @@ class TestOther : public TestFixture {
106106
TEST_CASE(varScope40);
107107
TEST_CASE(varScope41); // #11845
108108
TEST_CASE(varScope42);
109+
TEST_CASE(varScope43);
109110

110111
TEST_CASE(oldStylePointerCast);
111112
TEST_CASE(invalidPointerCast);
@@ -1874,6 +1875,28 @@ class TestOther : public TestFixture {
18741875
ASSERT_EQUALS("[test.cpp:3:17]: (style) The scope of the variable 's' can be reduced. [variableScope]\n", errout_str());
18751876
}
18761877

1878+
void varScope43() {
1879+
check("struct S { int a, b; };\n" // #13838
1880+
"int f(S s) {\n"
1881+
" auto& [x, y] = s;\n"
1882+
" if (x < 5) {\n"
1883+
" return y;\n"
1884+
" }\n"
1885+
" return 0;\n"
1886+
"}\n");
1887+
ASSERT_EQUALS("", errout_str());
1888+
1889+
check("struct S { int a; };\n"
1890+
"int f(S s) {\n"
1891+
" auto& [x] = s;\n"
1892+
" if (y) {\n"
1893+
" return x;\n"
1894+
" }\n"
1895+
" return 0;\n"
1896+
"}\n");
1897+
ASSERT_EQUALS("[test.cpp:3:12]: (style) The scope of the variable 'x' can be reduced. [variableScope]\n", errout_str());
1898+
}
1899+
18771900
#define checkOldStylePointerCast(...) checkOldStylePointerCast_(__FILE__, __LINE__, __VA_ARGS__)
18781901
template<size_t size>
18791902
void checkOldStylePointerCast_(const char* file, int line, const char (&code)[size], Standards::cppstd_t std = Standards::CPPLatest) {

0 commit comments

Comments
 (0)