Fixed #5016 (false negative: condition is always true / comparing boolean result with '<' (x > -1 < 5))

This commit is contained in:
Daniel Marjamäki 2013-09-07 11:32:11 +02:00
parent 83c460fc56
commit 08556d071e
2 changed files with 47 additions and 0 deletions

View File

@ -395,6 +395,44 @@ void CheckBool::checkComparisonOfBoolExpressionWithInt()
op = opTok->str()[0]=='>'?'<':'>';
}
// boolean result in lhs compared with <|<=|>|>=
else if (Token::Match(tok,"<|<=|>|>=")) {
const Token *lhs = tok;
while (NULL != (lhs = lhs->previous())) {
if (lhs->isName() || lhs->isNumber())
continue;
if (Token::Match(lhs,"[+-*/.]"))
continue;
if (Token::Match(lhs, ")|]")) {
lhs = lhs->previous();
continue;
}
break;
}
if (Token::Match(lhs,"<|<=|>|>=")) {
while (NULL != (lhs = lhs->previous())) {
if ((lhs->isName() && lhs->str() != "return") || lhs->isNumber())
continue;
if (Token::Match(lhs,"[+-*/.]"))
continue;
if (Token::Match(lhs, ")|]")) {
lhs = lhs->previous();
continue;
}
break;
}
std::string expression;
for (const Token *t = lhs ? lhs->next() : _tokenizer->tokens(); t != tok; t = t->next()) {
if (!expression.empty())
expression += ' ';
expression += t->str();
}
comparisonOfBoolWithInvalidComparator(tok, expression);
}
}
if (numTok && opTok) {
if (numTok->isNumber()) {
if (((numTok->str() != "0" && numTok->str() != "1") || !Token::Match(opTok, "!=|==")) && !((op == '<' && numTok->str() == "1") || (op == '>' && numTok->str() == "0")))

View File

@ -40,6 +40,7 @@ private:
TEST_CASE(comparisonOfBoolExpressionWithInt1);
TEST_CASE(comparisonOfBoolExpressionWithInt2);
TEST_CASE(comparisonOfBoolExpressionWithInt3);
TEST_CASE(comparisonOfBoolExpressionWithInt4);
TEST_CASE(comparisonOfBoolWithInt1);
TEST_CASE(comparisonOfBoolWithInt2);
@ -346,6 +347,14 @@ private:
ASSERT_EQUALS("", errout.str());
}
void comparisonOfBoolExpressionWithInt4() {
// #5016
check("void f() {\n"
" for(int i = 4; i > -1 < 5 ; --i) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Comparison of a boolean value using relational operator (<, >, <= or >=).\n", errout.str());
}
void checkComparisonOfFuncReturningBool1() {
check("void f(){\n"
" int temp = 4;\n"