Fix ticket #275 Simplify if( a == 0 ), if( 0 == a ) into if( !a )

http://apps.sourceforge.net/trac/cppcheck/ticket/275
This commit is contained in:
Reijo Tomperi 2009-05-01 13:07:10 +03:00
parent 1ad5cf1ec5
commit 241ad528a9
2 changed files with 45 additions and 8 deletions

View File

@ -785,6 +785,7 @@ void Tokenizer::simplifyNamespaces()
bool Tokenizer::createLinks()
{
std::list<Token*> links;
std::list<Token*> links2;
for (Token *token = _tokens; token; token = token->next())
{
if (token->link())
@ -808,9 +809,25 @@ bool Tokenizer::createLinks()
links.back()->link(token);
links.pop_back();
}
else if (token->str() == "(")
{
links2.push_back(token);
}
else if (token->str() == ")")
{
if (links2.size() == 0)
{
// Error, ( and ) don't match.
return false;
}
token->link(links2.back());
links2.back()->link(token);
links2.pop_back();
}
}
if (links.size() > 0)
if (links.size() > 0 || links2.size() > 0 )
{
// Error, { and } don't match.
return false;
@ -1926,24 +1943,40 @@ bool Tokenizer::simplifyIfAssign()
bool Tokenizer::simplifyIfNot()
{
// Make sure we have working links
createLinks();
bool ret = false;
for (Token *tok = _tokens; tok; tok = tok->next())
{
if (Token::Match(tok, "if ( 0 == %var% )") || Token::simpleMatch(tok, "if ( 0 == ("))
if (Token::Match(tok, "0 == (") ||
Token::Match(tok, "0 == %var%"))
{
tok = tok->next();
tok->deleteNext();
tok->next()->str("!");
tok = tok->tokAt(3);
tok->str("!");
ret = true;
}
if (Token::Match(tok, "%var% == 0") )
{
tok->deleteNext();
tok->next()->str(tok->str().c_str());
tok->str("!");
ret = true;
}
if ( tok->link() && Token::Match(tok, ") == 0") )
{
tok->deleteNext();
tok->deleteNext();
tok->link()->insertToken("(");
tok->link()->str("!");
ret = true;
}
}
return ret;
}
bool Tokenizer::simplifyKnownVariables()
{
bool ret = false;

View File

@ -634,6 +634,10 @@ private:
{
ASSERT_EQUALS("if ( ! x )", simplifyIfNot("if(0==x)"));
ASSERT_EQUALS("if ( ! ( a = b ) )", simplifyIfNot("if(0==(a=b))"));
ASSERT_EQUALS("if ( ! x )", simplifyIfNot("if(x==0)"));
ASSERT_EQUALS("if ( ! a && b ( ) )", simplifyIfNot("if( 0 == a && b() )"));
ASSERT_EQUALS("if ( b ( ) && ! a )", simplifyIfNot("if( b() && 0 == a )"));
ASSERT_EQUALS("if ( ! ( a = b ) )", simplifyIfNot("if((a=b)==0)"));
}
};