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