Added Tokenizer::elseif for breaking up 'else if' into 'else { if ..'

This commit is contained in:
Daniel Marjamäki 2009-02-17 19:18:26 +00:00
parent 5b24319cf1
commit 1043b76d31
3 changed files with 75 additions and 2 deletions

View File

@ -543,7 +543,7 @@ void Tokenizer::setVarId()
else if (tok2->str() == ")")
{
// Is this a function parameter or a variable declared in for example a for loop?
if (parlevel==0 && indentlevel==0 && Token::Match(tok2, ") const| {"))
if (parlevel == 0 && indentlevel == 0 && Token::Match(tok2, ") const| {"))
;
else
--parlevel;
@ -1650,6 +1650,38 @@ bool Tokenizer::simplifyKnownVariables()
return ret;
}
bool Tokenizer::elseif()
{
bool ret = false;
for (Token *tok = _tokens; tok; tok = tok->next())
{
if (!Token::simpleMatch(tok, "else if"))
continue;
int indent = 0;
for (Token *tok2 = tok; indent >= 0 && tok2; tok2 = tok2->next())
{
if (Token::Match(tok2, "(|{"))
++indent;
else if (Token::Match(tok2, ")|}"))
--indent;
if (indent == 0 && Token::Match(tok2, "}|;"))
{
if (!Token::simpleMatch(tok2->next(), "else"))
{
tok->insertToken("{");
tok2->insertToken("}");
ret = true;
break;
}
}
}
}
return ret;
}
bool Tokenizer::simplifyRedundantParanthesis()
{
bool ret = false;

View File

@ -100,6 +100,9 @@ protected:
*/
bool simplifyKnownVariables();
/** Simplify "if else" */
bool elseif();
std::vector<const Token *> _functionList;
private:

View File

@ -25,6 +25,27 @@
extern std::ostringstream errout;
// A test tokenizer where protected functions are made public
class OpenTokenizer : public Tokenizer
{
public:
OpenTokenizer(const char code[]) : Tokenizer()
{
std::istringstream istr(code);
tokenize(istr, "test.cpp");
}
virtual ~OpenTokenizer()
{ }
bool elseif_()
{
return elseif();
}
};
class TestSimplifyTokens : public TestFixture
{
public:
@ -43,6 +64,8 @@ private:
TEST_CASE(double_plus);
TEST_CASE(redundant_plus);
TEST_CASE(parantheses1);
TEST_CASE(elseif1);
}
std::string tok(const char code[])
@ -50,7 +73,6 @@ private:
std::istringstream istr(code);
Tokenizer tokenizer;
tokenizer.tokenize(istr, "test.cpp");
tokenizer.setVarId();
tokenizer.simplifyTokenList();
std::string ret;
for (const Token *tok = tokenizer.tokens(); tok; tok = tok->next())
@ -289,6 +311,22 @@ private:
const char code1[] = "<= (10+100);";
ASSERT_EQUALS("<= 110 ; ", tok(code1));
}
std::string elseif(const char code[])
{
std::istringstream istr(code);
OpenTokenizer tokenizer(code);
tokenizer.elseif_();
return tokenizer.tokens()->stringifyList(false);
}
void elseif1()
{
const char code[] = "else if(ab) { cd } else { ef }gh";
ASSERT_EQUALS("\n1: else { if ( ab ) { cd } else { ef } } gh\n", elseif(code));
}
};
REGISTER_TEST(TestSimplifyTokens)