Tokenizer: Better simplifications of static constants

This commit is contained in:
Daniel Marjamäki 2011-01-29 16:14:09 +01:00
parent 081e364298
commit a299411a82
2 changed files with 20 additions and 6 deletions

View File

@ -6231,22 +6231,22 @@ bool Tokenizer::simplifyKnownVariables()
std::map<unsigned int, std::string> constantValues;
for (Token *tok = _tokens; tok; tok = tok->next())
{
if (Token::Match(tok, "static| const %type% %var% = %any% ;"))
if (Token::Match(tok, "static| const static| %type% %var% = %any% ;"))
{
Token *tok1 = tok;
// start of statement
if (tok != _tokens && !Token::Match(tok->previous(),"[;{}]"))
continue;
// skip "static"
if (tok->str() == "static")
// skip "const" and "static"
while (tok->str() == "const" || tok->str() == "static")
tok = tok->next();
// pod type
if (!tok->next()->isStandardType())
if (!tok->isStandardType())
continue;
const Token * const vartok = tok->tokAt(2);
const Token * const valuetok = tok->tokAt(4);
const Token * const vartok = tok->next();
const Token * const valuetok = tok->tokAt(3);
if (valuetok->isNumber() || Token::Match(valuetok, "%str% ;"))
{
constantValues[vartok->varId()] = valuetok->str();

View File

@ -211,6 +211,7 @@ private:
TEST_CASE(tokenize_strings);
TEST_CASE(simplify_constants);
TEST_CASE(simplify_constants2);
TEST_CASE(simplify_constants3);
TEST_CASE(vardecl1);
TEST_CASE(vardecl2);
@ -3812,6 +3813,19 @@ private:
ASSERT_EQUALS(oss.str(), ostr.str());
}
void simplify_constants3()
{
const char code[] =
"static const char str[] = \"abcd\";\n"
"static const unsigned int SZ = sizeof(str);\n"
"void f() {\n"
"a = SZ;\n"
"}\n";
const char expected[] =
"static const char str [ 5 ] = \"abcd\" ;\n\nvoid f ( ) {\na = 5 ;\n}";
ASSERT_EQUALS(expected, tokenizeAndStringify(code,true));
}
void vardecl1()
{
const char code[] = "unsigned int a, b;";