From 421ae9df03190045302464521fc625bd93379c70 Mon Sep 17 00:00:00 2001 From: Edoardo Prezioso Date: Thu, 26 Jan 2012 23:12:01 +0100 Subject: [PATCH] simplifyCondition: handle also '( a || true || b)' -> '(true)' and '( a && false && b)' -> '(false)'. Clarify a comment about previous commit. --- lib/tokenize.cpp | 26 +++++++++++++++++++++++++- test/testsimplifytokens.cpp | 36 ++++++++++++++++++++++++++++++++++++ 2 files changed, 61 insertions(+), 1 deletion(-) diff --git a/lib/tokenize.cpp b/lib/tokenize.cpp index b999c4fa3..a99cc2898 100644 --- a/lib/tokenize.cpp +++ b/lib/tokenize.cpp @@ -3955,7 +3955,7 @@ bool Tokenizer::removeRedundantConditions() if (Token::simpleMatch(elseTag, "else {")) { // Handle else if (boolValue == false) { - // Convert "if( false ) {aaa;} else {bbb;}" => "{bbb;}" or ";{bbb;}" + // Convert "if( false ) {aaa;} else {bbb;}" => "{bbb;}" //remove '(false)' tok->deleteNext(3); @@ -4508,6 +4508,30 @@ bool Tokenizer::simplifyConditions() 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" if (Token::Match(tok, "if|while ( %num% )|%oror%|&&")) { tok->tokAt(2)->str((tok->strAt(2) != "0") ? "true" : "false"); diff --git a/test/testsimplifytokens.cpp b/test/testsimplifytokens.cpp index af3381451..5be7295ca 100644 --- a/test/testsimplifytokens.cpp +++ b/test/testsimplifytokens.cpp @@ -6359,6 +6359,42 @@ private: "}"; 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)); + } }