Fix ticket #364 (false positive:: division by zero)

http://apps.sourceforge.net/trac/cppcheck/ticket/364
This commit is contained in:
Reijo Tomperi 2009-06-06 00:33:13 +03:00
parent 51349d126b
commit 9cd5558f5e
3 changed files with 57 additions and 2 deletions

View File

@ -1465,6 +1465,7 @@ void Tokenizer::simplifyTokenList()
modified |= removeReduntantConditions();
modified |= simplifyRedundantParanthesis();
modified |= simplifyCalculations();
modified |= simplifyQuestionMark();
}
createLinks();
@ -1840,6 +1841,51 @@ bool Tokenizer::simplifyConditions()
return ret;
}
bool Tokenizer::simplifyQuestionMark()
{
bool ret = false;
for (Token *tok = _tokens; tok; tok = tok->next())
{
if (tok->str() != "?")
continue;
if (!tok->previous() || !tok->previous()->previous())
continue;
if (!Token::Match(tok->previous()->previous(), "[=,(]"))
continue;
if (!Token::Match(tok->previous(), "%bool%") &&
!Token::Match(tok->previous(), "%num%"))
continue;
if (tok->previous()->str() == "false" ||
tok->previous()->str() == "0")
{
// Use code after semicolon, remove code before it.
const Token *end = Token::findmatch(tok, ":");
if (!end || !end->next())
continue;
end = end->next();
tok = tok->previous();
while (tok->next() != end)
{
tok->deleteNext();
}
Token *temp = tok;
tok = tok->next();
temp->deleteThis();
}
else
{
// Use code before semicolon
}
}
return ret;
}
bool Tokenizer::simplifyCasts()
{

View File

@ -100,6 +100,11 @@ public:
*/
bool simplifyVarDecl();
/**
* Simplify question mark - colon operator
* Example: 0 ? (2/0) : 0 => 0
*/
bool simplifyQuestionMark();
/**
* simplify if-assignments..

View File

@ -111,10 +111,14 @@ private:
" cout<<b/sum;\n"
"}\n");
ASSERT_EQUALS("", errout.str());
check("void foo()\n"
"{\n"
" int a = 0 ? (2/0) : 0;\n"
"}\n");
ASSERT_EQUALS("", errout.str());
}
void delete1()
{
check("void foo()\n"