From 241ad528a9d99a68c5d3b7fb7f1bee1703c4b794 Mon Sep 17 00:00:00 2001 From: Reijo Tomperi Date: Fri, 1 May 2009 13:07:10 +0300 Subject: [PATCH] Fix ticket #275 Simplify if( a == 0 ), if( 0 == a ) into if( !a ) http://apps.sourceforge.net/trac/cppcheck/ticket/275 --- src/tokenize.cpp | 49 +++++++++++++++++++++++++++++++------ test/testsimplifytokens.cpp | 4 +++ 2 files changed, 45 insertions(+), 8 deletions(-) diff --git a/src/tokenize.cpp b/src/tokenize.cpp index 34e8a45f2..3c852938a 100644 --- a/src/tokenize.cpp +++ b/src/tokenize.cpp @@ -785,6 +785,7 @@ void Tokenizer::simplifyNamespaces() bool Tokenizer::createLinks() { std::list links; + std::list 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; diff --git a/test/testsimplifytokens.cpp b/test/testsimplifytokens.cpp index 3a6b973c4..d66babc91 100644 --- a/test/testsimplifytokens.cpp +++ b/test/testsimplifytokens.cpp @@ -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)")); } };