From f937dde1e02c415671107bf6bf56291be6fc6db5 Mon Sep 17 00:00:00 2001 From: Dmitry-Me Date: Mon, 1 Sep 2014 16:40:28 +0400 Subject: [PATCH] Improve C style casts detection --- lib/checkother.cpp | 11 +++++++++-- test/testother.cpp | 35 +++++++++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+), 2 deletions(-) diff --git a/lib/checkother.cpp b/lib/checkother.cpp index ba94c39a0..3709d4fe1 100644 --- a/lib/checkother.cpp +++ b/lib/checkother.cpp @@ -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); } } diff --git a/test/testother.cpp b/test/testother.cpp index e6e4bf588..f2d6edd7d 100644 --- a/test/testother.cpp +++ b/test/testother.cpp @@ -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"