Fix ticket #177 (Tokenizer doesn't add braces around if-scope)

http://apps.sourceforge.net/trac/cppcheck/ticket/177
This commit is contained in:
Reijo Tomperi 2009-03-15 14:44:57 +02:00
parent bb3316a45b
commit ca7870af33
2 changed files with 36 additions and 8 deletions

View File

@ -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;
}
}

View File

@ -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"