CheckBool::checkAssignBoolToPointer: Refactor to use AST.

This commit is contained in:
Daniel Marjamäki 2014-03-27 05:39:48 +01:00
parent f71a4ad216
commit 2248cdfea0
2 changed files with 27 additions and 12 deletions

View File

@ -28,6 +28,12 @@ namespace {
CheckBool instance; CheckBool instance;
} }
static bool astIsBool(const Token *expr)
{
return Token::Match(expr, "%comp%|%bool%|%oror%|&&");
}
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
void CheckBool::checkIncrementBoolean() void CheckBool::checkIncrementBoolean()
@ -332,20 +338,14 @@ void CheckBool::checkAssignBoolToPointer()
for (std::size_t i = 0; i < functions; ++i) { for (std::size_t i = 0; i < functions; ++i) {
const Scope * scope = symbolDatabase->functionScopes[i]; const Scope * scope = symbolDatabase->functionScopes[i];
for (const Token* tok = scope->classStart; tok != scope->classEnd; tok = tok->next()) { for (const Token* tok = scope->classStart; tok != scope->classEnd; tok = tok->next()) {
if (Token::Match(tok, "%var% = %bool% ;")) { if (tok->str() == "=" && astIsBool(tok->astOperand2())) {
// check if there is a deref const Token *lhs = tok->astOperand1();
// *x.p = true; // <- don't warn while (lhs && lhs->str() == ".")
// x.p = true; // <- warn lhs = lhs->astOperand2();
const Token *prev = tok; if (!lhs || !lhs->variable() || !lhs->variable()->isPointer())
while (Token::Match(prev->tokAt(-2), "%var% ."))
prev = prev->tokAt(-2);
if (Token::Match(prev->previous(), "[*.)]"))
continue; continue;
// Is variable a pointer? assignBoolToPointerError(tok);
const Variable *var1(tok->variable());
if (var1 && var1->isPointer())
assignBoolToPointerError(tok);
} }
} }
} }

View File

@ -92,6 +92,21 @@ private:
"}"); "}");
ASSERT_EQUALS("[test.cpp:2]: (error) Boolean value assigned to pointer.\n", errout.str()); ASSERT_EQUALS("[test.cpp:2]: (error) Boolean value assigned to pointer.\n", errout.str());
check("void foo(bool *p) {\n"
" p = (x<y);\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (error) Boolean value assigned to pointer.\n", errout.str());
check("void foo(bool *p) {\n"
" p = (x||y);\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (error) Boolean value assigned to pointer.\n", errout.str());
check("void foo(bool *p) {\n"
" p = (x&&y);\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (error) Boolean value assigned to pointer.\n", errout.str());
// check against potential false positives // check against potential false positives
check("void foo(bool *p) {\n" check("void foo(bool *p) {\n"
" *p = false;\n" " *p = false;\n"