Merge pull request #413 from Dmitry-Me/improveCStyleCastsDetection

Improve C style casts detection
This commit is contained in:
PKEuS 2014-09-02 08:07:53 +02:00
commit ddc19febb5
2 changed files with 44 additions and 2 deletions

View File

@ -368,17 +368,24 @@ void CheckOther::warningOldStylePointerCast()
tok = scope->classStart; tok = scope->classStart;
for (; tok && tok != scope->classEnd; tok = tok->next()) { for (; tok && tok != scope->classEnd; tok = tok->next()) {
// Old style pointer casting.. // Old style pointer casting..
if (!Token::Match(tok, "( const| %type% * ) (| %var%|%num%|%bool%|%char%|%str%")) if (!Token::Match(tok, "( const| %type% * const| ) (| %var%|%num%|%bool%|%char%|%str%"))
continue; continue;
// skip first "const" in "const Type* const"
if (tok->strAt(1) == "const") if (tok->strAt(1) == "const")
tok = tok->next(); tok = tok->next();
const Token* typeTok = tok ? tok->next() : nullptr;
if (!typeTok)
continue;
// skip second "const" in "const Type* const"
if (tok->strAt(3) == "const")
tok = tok->next();
if (tok->strAt(4) == "0") // Casting nullpointers is safe if (tok->strAt(4) == "0") // Casting nullpointers is safe
continue; continue;
// Is "type" a class? // Is "type" a class?
if (_tokenizer->getSymbolDatabase()->isClassOrStruct(tok->strAt(1))) if (_tokenizer->getSymbolDatabase()->isClassOrStruct(typeTok->str()))
cstyleCastError(tok); cstyleCastError(tok);
} }
} }

View File

@ -1098,6 +1098,41 @@ private:
"}"); "}");
ASSERT_EQUALS("[test.cpp:4]: (style) C-style pointer casting\n", errout.str()); ASSERT_EQUALS("[test.cpp:4]: (style) C-style pointer casting\n", errout.str());
checkOldStylePointerCast("class Base;\n"
"void foo()\n"
"{\n"
" Base * b = (const Base * const) derived;\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (style) C-style pointer casting\n", errout.str());
checkOldStylePointerCast("class Base;\n"
"void foo()\n"
"{\n"
" Base * b = (volatile Base *) derived;\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (style) C-style pointer casting\n", errout.str());
checkOldStylePointerCast("class Base;\n"
"void foo()\n"
"{\n"
" Base * b = (volatile Base * const) derived;\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (style) C-style pointer casting\n", errout.str());
checkOldStylePointerCast("class Base;\n"
"void foo()\n"
"{\n"
" Base * b = (const volatile Base *) derived;\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (style) C-style pointer casting\n", errout.str());
checkOldStylePointerCast("class Base;\n"
"void foo()\n"
"{\n"
" Base * b = (const volatile Base * const) derived;\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (style) C-style pointer casting\n", errout.str());
checkOldStylePointerCast("class Base;\n" checkOldStylePointerCast("class Base;\n"
"void foo()\n" "void foo()\n"
"{\n" "{\n"