diff --git a/testsimplifytokens.cpp b/testsimplifytokens.cpp index fb23b3854..81b9b01d8 100644 --- a/testsimplifytokens.cpp +++ b/testsimplifytokens.cpp @@ -98,7 +98,7 @@ private: { const char code1[] = " void f() { int a; bool use = false; if( use ) a=0; else a=1; int c=1; } "; - const char code2[] = " void f() { int a; bool use = false; a=1; int c=1; } "; + const char code2[] = " void f() { int a; bool use = false; { a=1; } int c=1; } "; ASSERT_EQUALS( tok(code2), tok(code1) ); } diff --git a/testtokenize.cpp b/testtokenize.cpp index 50741964c..859a93ed0 100644 --- a/testtokenize.cpp +++ b/testtokenize.cpp @@ -234,6 +234,7 @@ private: const char code[] = "void f()\n" "{\n" " if (a);\n" + " else ;\n" "}\n"; // tokenize.. @@ -246,7 +247,7 @@ private: std::ostringstream ostr; for (const TOKEN *tok = tokenizer.tokens(); tok; tok = tok->next()) ostr << " " << tok->str(); - ASSERT_EQUALS( std::string(" void f ( ) { if ( a ) { ; } }"), ostr.str() ); + ASSERT_EQUALS( std::string(" void f ( ) { if ( a ) { ; } else { ; } }"), ostr.str() ); } void ifAddBraces2() diff --git a/tokenize.cpp b/tokenize.cpp index 62e23db91..2c491dcd6 100644 --- a/tokenize.cpp +++ b/tokenize.cpp @@ -1224,23 +1224,35 @@ bool Tokenizer::simplifyIfAddBraces() for ( TOKEN *tok = _tokens; tok; tok = tok ? tok->next() : NULL ) { - if ( ! TOKEN::Match(tok, "if|for|while (") ) - continue; - - // Goto the ending ')' - int parlevel = 1; - tok = tok->next(); - while ( parlevel >= 1 && (tok = tok->next()) ) + if ( TOKEN::Match(tok, "if|for|while (") ) { - if ( tok->str() == "(" ) - ++parlevel; - else if ( tok->str() == ")" ) - --parlevel; + // Goto the ending ')' + int parlevel = 1; + tok = tok->next(); + while ( parlevel >= 1 && (tok = tok->next()) ) + { + if ( tok->str() == "(" ) + ++parlevel; + else if ( tok->str() == ")" ) + --parlevel; + } + + // ')' should be followed by '{' + if (!tok || TOKEN::Match(tok, ") {")) + continue; } - // ')' should be followed by '{' - if (!tok || TOKEN::Match(tok, ") {")) + else if ( tok->str() == "else" ) + { + // An else followed by an if or brace don't need to be processed further + if ( TOKEN::Match( tok, "else if|{" ) ) + continue; + } + + else + { continue; + } // insert open brace.. tok->insertToken("{"); @@ -1251,7 +1263,7 @@ bool Tokenizer::simplifyIfAddBraces() // But here are special cases.. // * if (cond) for (;;) break; // * if (cond1) if (cond2) { } - parlevel = 0; + int parlevel = 0; int indentlevel = 0; while ( (tok = tok->next()) != NULL ) {