diff --git a/src/tokenize.cpp b/src/tokenize.cpp index fcc6e8a05..25954e729 100644 --- a/src/tokenize.cpp +++ b/src/tokenize.cpp @@ -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; diff --git a/src/tokenize.h b/src/tokenize.h index 62264d3fe..e10d301d9 100644 --- a/src/tokenize.h +++ b/src/tokenize.h @@ -100,6 +100,9 @@ protected: */ bool simplifyKnownVariables(); + /** Simplify "if else" */ + bool elseif(); + std::vector _functionList; private: diff --git a/test/testsimplifytokens.cpp b/test/testsimplifytokens.cpp index 7f45b90c7..0ee27918a 100644 --- a/test/testsimplifytokens.cpp +++ b/test/testsimplifytokens.cpp @@ -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)