simplify tokens: move assignment out from condition (Ticket #201)

This commit is contained in:
Daniel Marjamäki 2009-03-23 18:20:56 +01:00
parent c9d02273b8
commit 7905cbc5e7
3 changed files with 82 additions and 3 deletions

View File

@ -1134,10 +1134,8 @@ void Tokenizer::simplifyTokenList()
simplifyIfAddBraces();
simplifyFunctionParameters();
// In case variable declarations have been updated...
setVarId();
elseif();
simplifyIfAssign();
for (Token *tok = _tokens; tok; tok = tok->next())
{
@ -1147,6 +1145,9 @@ void Tokenizer::simplifyTokenList()
tok->next()->insertToken(";");
}
// In case variable declarations have been updated...
setVarId();
bool modified = true;
while (modified)
{
@ -1806,6 +1807,51 @@ bool Tokenizer::simplifyVarDecl()
}
bool Tokenizer::simplifyIfAssign()
{
bool ret = false;
for (Token *tok = _tokens; tok; tok = tok->next())
{
if (Token::Match(tok->next(), "if ( (| %var% ="))
{
tok->deleteNext();
int numpar = 0;
while (tok->next()->str() == "(")
{
++numpar;
tok->deleteNext();
}
Token *tok2 = tok;
int indentlevel = 0;
for (tok2 = tok; tok2; tok2 = tok2->next())
{
if (tok2->str() == "(")
++indentlevel;
else if (tok2->str() == ")")
{
if (indentlevel <= 0)
break;
--indentlevel;
}
}
if (tok2)
{
tok2 = tok2->previous();
tok2->insertToken(tok->strAt(1));
for (int p = 0; p < numpar; ++p)
tok2->insertToken("(");
tok2->insertToken("if");
tok2->insertToken(";");
ret = true;
}
}
}
return ret;
}
bool Tokenizer::simplifyKnownVariables()
{
bool ret = false;

View File

@ -95,6 +95,12 @@ public:
bool simplifyVarDecl();
/**
* simplify if-assignments..
* Example: "if(a=b);" => "a=b;if(a);"
*/
bool simplifyIfAssign();
protected:
/** Add braces to an if-block

View File

@ -84,6 +84,9 @@ private:
TEST_CASE(template5);
TEST_CASE(namespaces);
// Assignment in condition..
TEST_CASE(ifassign1);
}
std::string tok(const char code[])
@ -544,6 +547,30 @@ private:
ASSERT_EQUALS(expected, sizeof_(code));
}
}
std::string simplifyIfAssign(const char code[])
{
// tokenize..
Tokenizer tokenizer;
std::istringstream istr(code);
tokenizer.tokenize(istr, "test.cpp");
tokenizer.simplifyIfAssign();
std::ostringstream ostr;
for (const Token *tok = tokenizer.tokens(); tok; tok = tok->next())
ostr << (tok->previous() ? " " : "") << tok->str();
return ostr.str();
}
void ifassign1()
{
ASSERT_EQUALS("; a = b ; if ( a ) ;", simplifyIfAssign(";if(a=b);"));
ASSERT_EQUALS("; a = b ( ) ; if ( ( a ) ) ;", simplifyIfAssign(";if((a=b()));"));
}
};
REGISTER_TEST(TestSimplifyTokens)