diff --git a/lib/tokenize.cpp b/lib/tokenize.cpp index cf8201cb9..1888dfbe8 100644 --- a/lib/tokenize.cpp +++ b/lib/tokenize.cpp @@ -4807,6 +4807,48 @@ bool Tokenizer::simplifyKnownVariables() ret = true; } + // Using the variable in for-condition.. + if (Token::simpleMatch(tok3, "for (")) + { + for (Token *tok4 = tok3->tokAt(2); tok4; tok4 = tok4->next()) + { + if (tok4->str() == "(" || tok4->str() == ")") + break; + + // Replace variable used in condition.. + if (Token::Match(tok4, "; %var% <|<=|!= %var% ; ++| %var% ++| )")) + { + const Token *inctok = tok4->tokAt(5); + if (inctok->str() == "++") + inctok = inctok->next(); + if (inctok->varId() == varid) + break; + + if (tok4->next()->varId() == varid) + { + tok4->next()->str(value); + ret = true; + } + if (tok4->tokAt(3)->varId() == varid) + { + tok4->tokAt(3)->str(value); + ret = true; + } + } + } + + if (tok3->next()->varId() == varid) + { + tok3->next()->str(value); + ret = true; + } + else if (tok3->tokAt(3)->varId() == varid) + { + tok3->tokAt(3)->str(value); + ret = true; + } + } + if (Token::Match(tok3->next(), "%varid% ++|--", varid) && MathLib::isInt(value)) { const std::string op(tok3->strAt(2)); diff --git a/test/testtokenize.cpp b/test/testtokenize.cpp index 22ce8b370..8039cb761 100644 --- a/test/testtokenize.cpp +++ b/test/testtokenize.cpp @@ -99,6 +99,7 @@ private: TEST_CASE(simplifyKnownVariables18); TEST_CASE(simplifyKnownVariables19); TEST_CASE(simplifyKnownVariables20); + TEST_CASE(simplifyKnownVariables21); TEST_CASE(match1); @@ -1063,6 +1064,15 @@ private: simplifyKnownVariables(code)); } + void simplifyKnownVariables21() + { + const char code[] = "void foo() { int n = 10; for (int i = 0; i < n; ++i) { } }"; + + ASSERT_EQUALS( + "void foo ( ) { int n ; n = 10 ; for ( int i = 0 ; i < 10 ; ++ i ) { } }", + simplifyKnownVariables(code)); + } + void match1() { // Match "%var% | %var%"