simplifyCondition: handle also '( a || true || b)' -> '(true)' and '( a && false && b)' -> '(false)'.

Clarify a comment about previous commit.
This commit is contained in:
Edoardo Prezioso 2012-01-26 23:12:01 +01:00
parent 0f1f3c0f5f
commit 421ae9df03
2 changed files with 61 additions and 1 deletions

View File

@ -3955,7 +3955,7 @@ bool Tokenizer::removeRedundantConditions()
if (Token::simpleMatch(elseTag, "else {")) { if (Token::simpleMatch(elseTag, "else {")) {
// Handle else // Handle else
if (boolValue == false) { if (boolValue == false) {
// Convert "if( false ) {aaa;} else {bbb;}" => "{bbb;}" or ";{bbb;}" // Convert "if( false ) {aaa;} else {bbb;}" => "{bbb;}"
//remove '(false)' //remove '(false)'
tok->deleteNext(3); tok->deleteNext(3);
@ -4508,6 +4508,30 @@ bool Tokenizer::simplifyConditions()
ret = true; ret = true;
} }
else if (Token::simpleMatch(tok, "&& false &&") ||
Token::simpleMatch(tok, "|| true ||")) {
//goto '('
Token *tok2 = tok;
while (tok2->previous()) {
if (tok2->previous()->str() == ")")
tok2 = tok2->previous()->link();
else {
tok2 = tok2->previous();
if (tok2->str() == "(")
break;
}
}
if (!tok2)
continue;
//move tok to 'true|false' position
tok = tok->next();
//remove everything before 'true|false'
Token::eraseTokens(tok2, tok);
//remove everything after 'true|false'
Token::eraseTokens(tok, tok2->link());
ret = true;
}
// Change numeric constant in condition to "true" or "false" // Change numeric constant in condition to "true" or "false"
if (Token::Match(tok, "if|while ( %num% )|%oror%|&&")) { if (Token::Match(tok, "if|while ( %num% )|%oror%|&&")) {
tok->tokAt(2)->str((tok->strAt(2) != "0") ? "true" : "false"); tok->tokAt(2)->str((tok->strAt(2) != "0") ? "true" : "false");

View File

@ -6359,6 +6359,42 @@ private:
"}"; "}";
ASSERT_EQUALS("void f ( int a ) { g ( ) ; }", tok(code)); ASSERT_EQUALS("void f ( int a ) { g ( ) ; }", tok(code));
} }
{
const char code[] =
"void f(int a)\n"
"{\n"
"if (a || true || b) g();\n"
"}";
ASSERT_EQUALS("void f ( int a ) { g ( ) ; }", tok(code));
}
{
const char code[] =
"void f(int a)\n"
"{\n"
"if (a && false && b) g();\n"
"}";
ASSERT_EQUALS("void f ( int a ) { }", tok(code));
}
{
const char code[] =
"void f(int a)\n"
"{\n"
"if (a || (b && false && c) || d) g();\n"
"}";
ASSERT_EQUALS("void f ( int a ) { if ( a || d ) { g ( ) ; } }", tok(code));
}
{
const char code[] =
"void f(int a)\n"
"{\n"
"if ((a && b) || true || (c && d)) g();\n"
"}";
ASSERT_EQUALS("void f ( int a ) { g ( ) ; }", tok(code));
}
} }