Opposite conditions: Better matching when outer condition uses &&

This commit is contained in:
Daniel Marjamäki 2017-09-01 23:24:15 +02:00
parent 3bbcede43b
commit 0b751dcc1b
3 changed files with 19 additions and 3 deletions

View File

@ -256,8 +256,14 @@ bool isOppositeCond(bool isNot, bool cpp, const Token * const cond1, const Token
if (cond2->str() == "!")
return isOppositeCond(isNot, cpp, cond2, cond1, library, pure);
if (!cond1->isComparisonOp() || !cond2->isComparisonOp())
if (!cond1->isComparisonOp() || !cond2->isComparisonOp()) {
if (!isNot && cond1->str() == "&&" && cond2->isComparisonOp()) {
return isOppositeCond(isNot, cpp, cond1->astOperand1(), cond2, library, pure) ||
isOppositeCond(isNot, cpp, cond1->astOperand2(), cond2, library, pure);
}
return false;
}
const std::string &comp1 = cond1->str();

View File

@ -540,7 +540,7 @@ void CheckCondition::oppositeInnerCondition()
const Token *cond2 = ifToken->next()->astOperand2();
if (isOppositeCond(false, _tokenizer->isCPP(), cond1, cond2, _settings->library, true))
oppositeInnerConditionError(scope->classDef, cond2);
oppositeInnerConditionError(cond1, cond2);
}
}
@ -548,7 +548,7 @@ void CheckCondition::oppositeInnerConditionError(const Token *tok1, const Token*
{
ErrorPath errorPath;
errorPath.push_back(ErrorPathItem(tok1, "outer condition"));
errorPath.push_back(ErrorPathItem(tok2, "opposite inner condition => always false when outer condition is true"));
errorPath.push_back(ErrorPathItem(tok2, "opposite inner condition"));
reportError(errorPath, Severity::warning, "oppositeInnerCondition", "Opposite inner 'if' condition leads to a dead code block.", CWE398, false);
}

View File

@ -77,6 +77,7 @@ private:
TEST_CASE(oppositeInnerCondition);
TEST_CASE(oppositeInnerCondition2);
TEST_CASE(oppositeInnerConditionAnd);
TEST_CASE(clarifyCondition1); // if (a = b() < 0)
TEST_CASE(clarifyCondition2); // if (a & b == c)
@ -1699,6 +1700,15 @@ private:
, errout.str());
}
void oppositeInnerConditionAnd() {
check("void f(int x) {\n"
" if (a>3 && x > 100) {\n"
" if (x < 10) {}\n"
" }"
"}");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:3]: (warning) Opposite inner 'if' condition leads to a dead code block.\n", errout.str());
}
// clarify conditions with = and comparison
void clarifyCondition1() {
check("void f() {\n"