diff --git a/src/tokenize.cpp b/src/tokenize.cpp index 24a85ee2a..ce2b35bd2 100644 --- a/src/tokenize.cpp +++ b/src/tokenize.cpp @@ -2938,7 +2938,7 @@ bool Tokenizer::simplifyCalculations() } // (1-2) - if (Token::Match(tok, "[[,(=<>] %num% [+-*/] %num% [],);=<>]")) + if (Token::Match(tok, "[[,(=<>+-*] %num% [+-*/] %num% [],);=<>+-*]")) { tok = tok->next(); @@ -2965,6 +2965,14 @@ bool Tokenizer::simplifyCalculations() tok->deleteNext(); tok->deleteNext(); + // evaluate "2 + 2 - 2 - 2" + // as (((2 + 2) - 2) - 2) = 0 + // instead of ((2 + 2) - (2 - 2)) = 4 + if (Token::Match(tok->next(), "[+-*/]")) { + tok = tok->tokAt(-2); + continue; + } + ret = true; } diff --git a/test/testsimplifytokens.cpp b/test/testsimplifytokens.cpp index 418c751ef..e64017eb2 100644 --- a/test/testsimplifytokens.cpp +++ b/test/testsimplifytokens.cpp @@ -115,6 +115,9 @@ private: // Simplify "?:" TEST_CASE(conditionOperator); + + // Simplify calculations + TEST_CASE(calculations); } std::string tok(const char code[]) @@ -1155,6 +1158,35 @@ private: TODO_ASSERT_EQUALS("( abc . a )", tok(code)); } } + + void calculations() + { + { + const char code[] = "a[i+8+2]"; + ASSERT_EQUALS("a [ i + 10 ]", tok(code)); + } + { + const char code[] = "a[8+2+i]"; + ASSERT_EQUALS("a [ 10 + i ]", tok(code)); + } + { + const char code[] = "a[i + 2 * (2 * 4)]"; + ASSERT_EQUALS("a [ i + 16 ]", tok(code)); + } + { + const char code[] = "a[i + 100 - 90]"; + ASSERT_EQUALS("a [ i + 10 ]", tok(code)); + } + { + const char code[] = "a[1+1+1+1+1+1+1+1+1+1-2+5-3]"; + ASSERT_EQUALS("a [ 10 ]", tok(code)); + } + { + const char code[] = "a[10+10-10-10]"; + ASSERT_EQUALS("a [ 0 ]", tok(code)); + } + } + }; REGISTER_TEST(TestSimplifyTokens)