Fixed ticket #345 ('!' and 'not' tokens interpreted differently even though they mean the same)

This commit is contained in:
Daniel Marjamäki 2009-05-31 10:42:27 +02:00
parent 8b76301ee2
commit aba7518aeb
3 changed files with 55 additions and 0 deletions

View File

@ -1420,6 +1420,7 @@ void Tokenizer::simplifyTokenList()
elseif();
simplifyIfNot();
simplifyNot();
simplifyIfAssign();
for (Token *tok = _tokens; tok; tok = tok->next())
@ -2233,6 +2234,25 @@ bool Tokenizer::simplifyIfNot()
return ret;
}
bool Tokenizer::simplifyNot()
{
// "if (not p)" => "if (!p)"
bool ret = false;
for (Token *tok = _tokens; tok; tok = tok->next())
{
if (Token::Match(tok, "if|while ( not %var%"))
tok->next()->next()->str("!");
if (Token::Match(tok, "&& not %var%"))
tok->next()->str("!");
if (Token::Match(tok, "|| not %var%"))
tok->next()->str("!");
}
return ret;
}
bool Tokenizer::simplifyKnownVariables()
{
createLinks();

View File

@ -113,6 +113,12 @@ public:
*/
bool simplifyIfNot();
/**
* simplify the "not" keyword to "!"
* Example: "if (not p)" => "if (!p)"
*/
bool simplifyNot();
protected:
/** Add braces to an if-block

View File

@ -99,6 +99,9 @@ private:
// "if(0==x)" => "if(!x)"
TEST_CASE(ifnot);
TEST_CASE(combine_wstrings);
// Simplify "not" to "!" (#345)
TEST_CASE(not1);
}
std::string tok(const char code[])
@ -858,6 +861,32 @@ private:
ASSERT_EQUALS("if ( ! ( a = b ) )", simplifyIfNot("if((a=b)==0)"));
}
std::string simplifyNot(const char code[])
{
// tokenize..
Tokenizer tokenizer;
std::istringstream istr(code);
tokenizer.tokenize(istr, "test.cpp");
tokenizer.simplifyNot();
std::ostringstream ostr;
for (const Token *tok = tokenizer.tokens(); tok; tok = tok->next())
ostr << (tok->previous() ? " " : "") << tok->str();
return ostr.str();
}
void not1()
{
ASSERT_EQUALS("if ( ! p )", simplifyNot("if (not p)"));
ASSERT_EQUALS("if ( p && ! q )", simplifyNot("if (p && not q)"));
ASSERT_EQUALS("void foo ( not i )", simplifyNot("void foo ( not i )"));
}
};
REGISTER_TEST(TestSimplifyTokens)