Improve C style casts detection

This commit is contained in:
Dmitry-Me 2014-09-01 16:40:28 +04:00
parent 353a9e9a64
commit f937dde1e0
2 changed files with 44 additions and 2 deletions

View File

@ -368,17 +368,24 @@ void CheckOther::warningOldStylePointerCast()
tok = scope->classStart;
for (; tok && tok != scope->classEnd; tok = tok->next()) {
// 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;
// skip first "const" in "const Type* const"
if (tok->strAt(1) == "const")
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
continue;
// Is "type" a class?
if (_tokenizer->getSymbolDatabase()->isClassOrStruct(tok->strAt(1)))
if (_tokenizer->getSymbolDatabase()->isClassOrStruct(typeTok->str()))
cstyleCastError(tok);
}
}

View File

@ -1098,6 +1098,41 @@ private:
"}");
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"
"void foo()\n"
"{\n"