Fixed #8954 (false positive: Local variable x shadows outer variable)

This commit is contained in:
Daniel Marjamäki 2019-02-23 16:22:16 +01:00
parent 23d4d9abeb
commit 68062e3702
2 changed files with 13 additions and 5 deletions

View File

@ -2762,6 +2762,8 @@ static const Token *findShadowed(const Scope *scope, const std::string &varname,
if (f.name() == varname)
return f.tokenDef;
}
if (scope->type == Scope::eLambda)
return nullptr;
return findShadowed(scope->nestedIn, varname, linenr);
}
@ -2771,7 +2773,7 @@ void CheckOther::checkShadowVariables()
return;
const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope & scope : symbolDatabase->scopeList) {
if (!scope.isExecutable())
if (!scope.isExecutable() || scope.type == Scope::eLambda)
continue;
for (const Variable &var : scope.varlist) {
const Token *shadowed = findShadowed(scope.nestedIn, var.name(), var.nameToken()->linenr());
@ -2791,7 +2793,7 @@ void CheckOther::shadowError(const Token *var, const Token *shadowed, bool shado
errorPath.push_back(ErrorPathItem(var, "Shadow variable"));
const std::string &varname = var ? var->str() : (shadowVar ? "var" : "f");
const char *id = shadowVar ? "shadowVar" : "shadowFunction";
std::string message = "$symbol:" + varname + "\nLocal variable $symbol shadows outer " + (shadowVar ? "variable" : "function");
std::string message = "$symbol:" + varname + "\nLocal variable \'$symbol\' shadows outer " + (shadowVar ? "variable" : "function");
reportError(errorPath, Severity::style, id, message, CWE398, false);
}

View File

@ -5392,7 +5392,7 @@ private:
" const int a = getA + 3;\n"
" return 0;\n"
"}");
ASSERT_EQUALS("[test.cpp:1] -> [test.cpp:4]: (style) Local variable getA shadows outer function\n", errout.str());
ASSERT_EQUALS("[test.cpp:1] -> [test.cpp:4]: (style) Local variable \'getA\' shadows outer function\n", errout.str());
check("class A{public:A(){}};\n"
"const A& getA(){static A a;return a;}\n"
@ -7487,11 +7487,11 @@ private:
void shadowVariables() {
check("int x;\n"
"void f() { int x; }\n");
ASSERT_EQUALS("[test.cpp:1] -> [test.cpp:2]: (style) Local variable x shadows outer variable\n", errout.str());
ASSERT_EQUALS("[test.cpp:1] -> [test.cpp:2]: (style) Local variable \'x\' shadows outer variable\n", errout.str());
check("int x();\n"
"void f() { int x; }\n");
ASSERT_EQUALS("[test.cpp:1] -> [test.cpp:2]: (style) Local variable x shadows outer function\n", errout.str());
ASSERT_EQUALS("[test.cpp:1] -> [test.cpp:2]: (style) Local variable \'x\' shadows outer function\n", errout.str());
check("struct C {\n"
" C(int x) : x(x) {}\n" // <- we do not want a FP here
@ -7509,6 +7509,12 @@ private:
" int size;\n" // <- not a shadow variable
"}\n");
ASSERT_EQUALS("", errout.str());
check("void f() {\n" // #8954 - lambda
" int x;\n"
" auto f = [](){ int x; }"
"}");
ASSERT_EQUALS("", errout.str());
}
void constArgument() {