simplify tokens (known variable values in conditions)

This commit is contained in:
Daniel Marjamäki 2009-03-25 07:10:17 +01:00
parent a66cf8b20f
commit 9f3634412e
3 changed files with 28 additions and 5 deletions

View File

@ -1933,10 +1933,10 @@ bool Tokenizer::simplifyKnownVariables()
if (tok3->varId() == varid)
break;
// Replace variable with numeric constant..
if (Token::Match(tok3, "if ( %varid% )", varid))
// Using the variable in condition..
if (Token::Match(tok3, "(|==|!=|<|<=|>|>= %varid% )|==|!=|<|<=|>|>=", varid))
{
tok3 = tok3->next()->next();
tok3 = tok3->next();
tok3->str(value.c_str());
ret = true;
}

View File

@ -1834,7 +1834,7 @@ private:
{
check("void foo()\n"
"{\n"
" char *str = 0;\n"
" char *str = malloc(10);\n"
" free(str);\n"
" char c = str[10];\n"
"}\n");

View File

@ -89,6 +89,7 @@ private:
TEST_CASE(simplifyKnownVariables6);
TEST_CASE(simplifyKnownVariables7);
TEST_CASE(simplifyKnownVariables8);
TEST_CASE(simplifyKnownVariables9);
TEST_CASE(multiCompare);
@ -528,7 +529,7 @@ private:
std::ostringstream ostr;
for (const Token *tok = tokenizer.tokens(); tok; tok = tok->next())
ostr << " " << tok->str();
ASSERT_EQUALS(std::string(" void f ( ) { int a ; a = 4 ; if ( g ( a ) ) ; }"), ostr.str());
ASSERT_EQUALS(std::string(" void f ( ) { int a ; a = 4 ; if ( g ( 4 ) ) ; }"), ostr.str());
}
void simplifyKnownVariables5()
@ -620,6 +621,28 @@ private:
ASSERT_EQUALS(std::string(" void foo ( ) { int i ; i = 23 ; ; abc [ 23 ] = 0 ; }"), ostr.str());
}
void simplifyKnownVariables9()
{
const char code[] = "void foo()\n"
"{\n"
" int a = 1, b = 2;\n"
" if (a < b)\n"
" ;\n"
"}\n";
// tokenize..
OurTokenizer tokenizer;
std::istringstream istr(code);
tokenizer.tokenize(istr, "test.cpp");
tokenizer.setVarId();
tokenizer.simplifyKnownVariables();
std::ostringstream ostr;
for (const Token *tok = tokenizer.tokens(); tok; tok = tok->next())
ostr << " " << tok->str();
ASSERT_EQUALS(std::string(" void foo ( ) { int a ; a = 1 ; int b ; b = 2 ; if ( 1 < 2 ) ; }"), ostr.str());
}
void multiCompare()