simplify tokens: simplify known variable value handles ++ and -- better

This commit is contained in:
Daniel Marjamäki 2009-02-24 16:11:37 +00:00
parent d15aea1b0c
commit 1e3047b9c2
2 changed files with 61 additions and 2 deletions

View File

@ -1604,6 +1604,22 @@ bool Tokenizer::simplifyFunctionReturn()
return ret;
}
static void incdec(std::string &value, const std::string &op)
{
int ivalue = 0;
std::istringstream istr(value.c_str());
istr >> ivalue;
if (op == "++")
++ivalue;
else if (op == "--")
--ivalue;
std::ostringstream ostr;
ostr << ivalue;
value = ostr.str();
}
bool Tokenizer::simplifyKnownVariables()
{
bool ret = false;
@ -1635,6 +1651,8 @@ bool Tokenizer::simplifyKnownVariables()
if (varid == 0)
continue;
std::string value(tok2->strAt(2));
for (Token *tok3 = tok2->next(); tok3; tok3 = tok3->next())
{
// Perhaps it's a loop => bail out
@ -1649,7 +1667,7 @@ bool Tokenizer::simplifyKnownVariables()
if (Token::Match(tok3, "if ( %varid% )", varid))
{
tok3 = tok3->next()->next();
tok3->str(tok2->strAt(2));
tok3->str(value.c_str());
ret = true;
}
@ -1657,9 +1675,25 @@ bool Tokenizer::simplifyKnownVariables()
if (Token::Match(tok3, "[=+-*/[] %varid% [+-*/;]]", varid))
{
tok3 = tok3->next();
tok3->str(tok2->strAt(2));
tok3->str(value.c_str());
ret = true;
}
if (Token::Match(tok3->next(), "%varid% ++|--", varid))
{
tok3 = tok3->next();
tok3->str(value.c_str());
incdec(value, tok3->strAt(1));
tok3->deleteNext();
}
if (Token::Match(tok3->next(), "++|-- %varid%", varid))
{
incdec(value, tok3->strAt(1));
tok3->deleteNext();
tok3 = tok3->next();
tok3->str(value.c_str());
}
}
}
}

View File

@ -84,6 +84,7 @@ private:
TEST_CASE(simplifyKnownVariables4);
TEST_CASE(simplifyKnownVariables5);
TEST_CASE(simplifyKnownVariables6);
TEST_CASE(simplifyKnownVariables7);
TEST_CASE(multiCompare);
@ -534,6 +535,30 @@ private:
ASSERT_EQUALS(std::string(" void f ( ) { char str [ 2 ] ; int a = 4 ; str [ 4 ] = 0 ; }"), ostr.str());
}
void simplifyKnownVariables7()
{
const char code[] = "void foo()\n"
"{\n"
" int i = 22;\n"
" abc[i++] = 1;\n"
" abc[++i] = 2;\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 i = 22 ; abc [ 22 ] = 1 ; abc [ 24 ] = 2 ; }"), ostr.str());
}
void multiCompare()
{
// Test for found