From acc38a8bbf39becc77d2a5b742722c03b784ed5e Mon Sep 17 00:00:00 2001 From: Slava Semushin Date: Sat, 22 Aug 2009 17:42:19 +0700 Subject: [PATCH] Fixed #592 (Tokenizer: improve the tokenization of do .. while) http://sourceforge.net/apps/trac/cppcheck/ticket/592 --- src/tokenize.cpp | 49 +++++++++++++++++++++++++++++++++++++++++++ src/tokenize.h | 6 ++++++ test/testtokenize.cpp | 7 +++++++ 3 files changed, 62 insertions(+) diff --git a/src/tokenize.cpp b/src/tokenize.cpp index f6c2e0971..f16ccd480 100644 --- a/src/tokenize.cpp +++ b/src/tokenize.cpp @@ -1561,6 +1561,7 @@ void Tokenizer::simplifyTokenList() } } + simplifyDoWhileAddBraces(); simplifyIfAddBraces(); simplifyFunctionParameters(); @@ -1884,6 +1885,54 @@ bool Tokenizer::simplifyIfAddBraces() return ret; } +bool Tokenizer::simplifyDoWhileAddBraces() +{ + bool ret = false; + + for (Token *tok = _tokens; tok; tok = (tok ? tok->next() : NULL)) + { + if (! Token::Match(tok, "do !!{")) + { + continue; + } + + Token *tok1 = tok; // token with "do" + Token *tok2 = NULL; // token with "while" + Token *tok3 = tok; + + // skip loop body + while (tok3) + { + if (tok3->str() == "while") + { + tok2 = tok3; + break; + } + + tok3 = tok3->next(); + } + + if (tok2) + { + // insert "{" after "do" + tok1->insertToken("{"); + + // insert "}" before "while" + tok2->previous()->insertToken("}"); + + // allow link() works + tok1 = tok1->next(); + tok2 = tok2->previous(); + tok1->link(tok2); + tok2->link(tok1); + + ret = true; + } + } + + return ret; +} + bool Tokenizer::simplifyConditionOperator() { bool ret = false; diff --git a/src/tokenize.h b/src/tokenize.h index 71e65423c..3765c35c9 100644 --- a/src/tokenize.h +++ b/src/tokenize.h @@ -185,6 +185,12 @@ private: */ bool simplifyIfAddBraces(); + /** Add braces to an do-while block + * @return true if something is modified + * false if nothing is done. + */ + bool simplifyDoWhileAddBraces(); + /** Simplify casts * @return true if something is modified * false if nothing is done. diff --git a/test/testtokenize.cpp b/test/testtokenize.cpp index 305cc837b..1df89e6c5 100644 --- a/test/testtokenize.cpp +++ b/test/testtokenize.cpp @@ -62,6 +62,7 @@ private: TEST_CASE(ifAddBraces8); TEST_CASE(whileAddBraces); + TEST_CASE(doWhileAddBraces); TEST_CASE(numeric_true_condition); TEST_CASE(pointers_condition); @@ -521,7 +522,13 @@ private: } } + void doWhileAddBraces() + { + const char code[] = "do ; while (0);"; + const char result[] = "do { ; } while ( false ) ;"; + ASSERT_EQUALS(result, tokenizeAndStringify(code, true)); + } void simplifyKnownVariables1() {