Fix regression FN constVariable with static arrays (#3965)

* Fix regression FN constVariable with static arrays

* Fix test case
This commit is contained in:
chrchr-github 2022-04-02 20:39:45 +02:00 committed by GitHub
parent a9f29fbc09
commit 7a7b3e40eb
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 19 additions and 4 deletions

View File

@ -1548,7 +1548,9 @@ void CheckOther::checkConstPointer()
continue;
if (!tok->variable()->isLocal() && !tok->variable()->isArgument())
continue;
if (tok == tok->variable()->nameToken())
const Token* const nameTok = tok->variable()->nameToken();
// declarations of (static) pointers are (not) split up, array declarations are never split up
if (tok == nameTok && (!Token::simpleMatch(tok->variable()->typeStartToken()->previous(), "static") || Token::simpleMatch(nameTok->next(), "[")))
continue;
if (!tok->valueType())
continue;
@ -1561,7 +1563,7 @@ void CheckOther::checkConstPointer()
bool deref = false;
if (parent && parent->isUnaryOp("*"))
deref = true;
else if (Token::simpleMatch(parent, "[") && parent->astOperand1() == tok)
else if (Token::simpleMatch(parent, "[") && parent->astOperand1() == tok && parent->astOperand1() != nameTok)
deref = true;
if (deref) {
if (Token::Match(parent->astParent(), "%cop%") && !parent->astParent()->isUnaryOp("&") && !parent->astParent()->isUnaryOp("*"))
@ -1593,7 +1595,7 @@ void CheckOther::checkConstPointer()
if (nonConstPointers.find(p) == nonConstPointers.end()) {
const Token *start = (p->isArgument()) ? p->scope()->bodyStart : p->nameToken()->next();
const int indirect = p->isArray() ? p->dimensions().size() : 1;
if (p->isStatic() || isVariableChanged(start, p->scope()->bodyEnd, indirect, p->declarationId(), false, mSettings, mTokenizer->isCPP()))
if (isVariableChanged(start, p->scope()->bodyEnd, indirect, p->declarationId(), false, mSettings, mTokenizer->isCPP()))
continue;
constVariableError(p, nullptr);
}

View File

@ -2974,11 +2974,24 @@ private:
// #10744
check("S& f() {\n"
" static S * p = new S();\n"
" static S* p = new S();\n"
" return *p;\n"
"}\n");
ASSERT_EQUALS("", errout.str());
check("int f() {\n"
" static int i[1] = {};\n"
" return i[0];\n"
"}\n");
ASSERT_EQUALS("[test.cpp:2]: (style) Variable 'i' can be declared with const\n", errout.str());
check("int f() {\n"
" static int i[] = { 0 };\n"
" int j = i[0] + 1;\n"
" return j;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:2]: (style) Variable 'i' can be declared with const\n", errout.str());
// #10471
check("void f(std::array<int, 1> const& i) {\n"
" if (i[0] == 0) {}\n"