Fix #365 (Improve simplifyQuestionMark() in tokenize.cpp)

http://sourceforge.net/apps/trac/cppcheck/ticket/365
This commit is contained in:
Reijo Tomperi 2009-10-05 17:34:38 +03:00
parent 50d9bc78ef
commit edb28d2856
2 changed files with 41 additions and 11 deletions

View File

@ -1890,6 +1890,7 @@ void Tokenizer::simplifyTokenList()
modified |= removeReduntantConditions(); modified |= removeReduntantConditions();
modified |= simplifyRedundantParanthesis(); modified |= simplifyRedundantParanthesis();
modified |= simplifyQuestionMark(); modified |= simplifyQuestionMark();
modified |= simplifyCalculations();
} }
// Remove redundant parantheses in return.. // Remove redundant parantheses in return..
@ -2335,7 +2336,7 @@ bool Tokenizer::simplifyQuestionMark()
if (tok->str() != "?") if (tok->str() != "?")
continue; continue;
if (!tok->previous() || !tok->tokAt(-2)) if (!tok->tokAt(-2))
continue; continue;
if (!Token::Match(tok->tokAt(-2), "[=,(]")) if (!Token::Match(tok->tokAt(-2), "[=,(]"))
@ -2382,15 +2383,37 @@ bool Tokenizer::simplifyQuestionMark()
} }
// The condition is true. Delete the operator after the ":".. // The condition is true. Delete the operator after the ":"..
else if (Token::Match(semicolon, ": %num%") || Token::Match(semicolon, ": %var% [);]")) else
{ {
// delete the condition token and the "?" // delete the condition token and the "?"
tok = tok->tokAt(-2); tok = tok->tokAt(-2);
Token::eraseTokens(tok, tok->tokAt(3)); Token::eraseTokens(tok, tok->tokAt(3));
int ind = 0;
for (const Token *end = semicolon; end; end = end->next())
{
if (end->str() == ";")
{
Token::eraseTokens(semicolon->previous(), end->next());
ret = true;
break;
}
// delete the ":" token and the token after it.. else if (end->str() == "(")
semicolon->deleteThis(); {
semicolon->deleteThis(); ++ind;
}
else if (end->str() == ")")
{
--ind;
if (ind < 0)
{
Token::eraseTokens(semicolon->previous(), end);
ret = true;
break;
}
}
}
} }
} }

View File

@ -402,8 +402,7 @@ private:
void parantheses1() void parantheses1()
{ {
const char code1[] = "<= (10+100);"; ASSERT_EQUALS("<= 110 ;", tok("<= (10+100);"));
ASSERT_EQUALS("<= 110 ;", tok(code1));
} }
void paranthesesVar() void paranthesesVar()
@ -1424,16 +1423,24 @@ private:
ASSERT_EQUALS("( 2 )", tok(code)); ASSERT_EQUALS("( 2 )", tok(code));
} }
{
const char code[] = "int a = (1?0:1 == 1?0:1);";
ASSERT_EQUALS("int a ; a = 0 ;", tok(code));
}
{
const char code[] = "(1?0:foo())";
ASSERT_EQUALS("( 0 )", tok(code));
}
{ {
const char code[] = "( true ? a ( ) : b ( ) )"; const char code[] = "( true ? a ( ) : b ( ) )";
ASSERT_EQUALS(code, tok(code)); ASSERT_EQUALS("( a ( ) )", tok(code));
TODO_ASSERT_EQUALS("( a ( ) )", tok(code));
} }
{ {
const char code[] = "( true ? abc . a : abc . b )"; const char code[] = "( true ? abc . a : abc . b )";
ASSERT_EQUALS(code, tok(code)); ASSERT_EQUALS("( abc . a )", tok(code));
TODO_ASSERT_EQUALS("( abc . a )", tok(code));
} }
} }