diff --git a/src/tokenize.cpp b/src/tokenize.cpp index 96040417f..977040c1b 100644 --- a/src/tokenize.cpp +++ b/src/tokenize.cpp @@ -1459,6 +1459,7 @@ bool Tokenizer::simplifyIfAddBraces() // insert open brace.. tok->insertToken("{"); tok = tok->next(); + Token *tempToken = tok; // insert close brace.. // In most cases it would work to just search for the next ';' and insert a closing brace after it. @@ -1467,31 +1468,31 @@ bool Tokenizer::simplifyIfAddBraces() // * if (cond1) if (cond2) { } int parlevel = 0; int indentlevel = 0; - while ((tok = tok->next()) != NULL) + while ((tempToken = tempToken->next()) != NULL) { - if (tok->str() == "{") + if (tempToken->str() == "{") ++indentlevel; - else if (tok->str() == "}") + else if (tempToken->str() == "}") { --indentlevel; if (indentlevel == 0) break; } - else if (tok->str() == "(") + else if (tempToken->str() == "(") ++parlevel; - else if (tok->str() == ")") + else if (tempToken->str() == ")") --parlevel; - else if (indentlevel == 0 && parlevel == 0 && tok->str() == ";") + else if (indentlevel == 0 && parlevel == 0 && tempToken->str() == ";") break; } - if (tok) + if (tempToken) { - tok->insertToken("}"); + tempToken->insertToken("}"); ret = true; } } diff --git a/test/testtokenize.cpp b/test/testtokenize.cpp index e012f35e3..8a1fc1afe 100644 --- a/test/testtokenize.cpp +++ b/test/testtokenize.cpp @@ -75,6 +75,7 @@ private: TEST_CASE(ifAddBraces2); TEST_CASE(ifAddBraces3); TEST_CASE(ifAddBraces4); + TEST_CASE(ifAddBraces5); TEST_CASE(numeric_true_condition); @@ -397,6 +398,32 @@ private: ASSERT_EQUALS(std::string(" char * foo ( ) { char * str = malloc ( 10 ) ; if ( somecondition ) { for ( ; ; ) { } } return str ; }"), ostr.str()); } + void ifAddBraces5() + { + const char code[] = "void f()\n" + "{\n" + "for(int i = 0; i < 2; i++)\n" + "if(true)\n" + "return;\n" + "\n" + "return;\n" + "}\n"; + + + // tokenize.. + OurTokenizer tokenizer; + std::istringstream istr(code); + tokenizer.tokenize(istr, "test.cpp"); + + ASSERT_EQUALS(true, tokenizer.simplifyIfAddBraces()); + + std::ostringstream ostr; + for (const Token *tok = tokenizer.tokens(); tok; tok = tok->next()) + ostr << " " << tok->str(); + ASSERT_EQUALS(std::string(" void f ( ) { for ( int i = 0 ; i < 2 ; i ++ ) { if ( true ) { return ; } } return ; }"), ostr.str()); + } + + void simplifyKnownVariables1() { const char code[] = "void f()\n"