diff --git a/lib/tokenize.cpp b/lib/tokenize.cpp index ba4125bed..548143f58 100644 --- a/lib/tokenize.cpp +++ b/lib/tokenize.cpp @@ -1646,6 +1646,9 @@ bool Tokenizer::tokenize(std::istream &code, // replace 'NULL' and similar '0'-defined macros with '0' simplifyNull(); + // replace 'sin(0)' to '0' and other similar math expressions + simplifyMathExpressions(); + // combine "- %num%" concatenateNegativeNumber(); @@ -9218,6 +9221,32 @@ void Tokenizer::printUnknownTypes() } } +void Tokenizer::simplifyMathExpressions() +{ + for (Token *tok = list.front(); tok; tok = tok->next()) { + + if (Token::Match(tok,"exp ( 0 )") || Token::Match(tok,"cosh ( 0 )") || Token::Match(tok,"cos ( 0 )") || Token::Match(tok,"sqrt ( 1 )")) { + tok->deleteNext(3); + tok->str("1"); + } + + if (Token::Match(tok,"sinh ( 0 )") || Token::Match(tok,"sin ( 0 )") || Token::Match(tok,"sqrt ( 0 )") || Token::Match(tok,"ln ( 1 )")) { + tok->deleteNext(3); + tok->str("0"); + } + + if (Token::Match(tok,"pow ( sin ( %var% ) , 2 ) + pow ( cos ( %var% ) , 2 )")) { + tok->deleteNext(18); + tok->str("1"); + } + + if (Token::Match(tok,"pow ( sinh ( %var% ) , 2 ) - pow ( cosh ( %var% ) , 2 )")) { + tok->deleteNext(18); + tok->str("-1"); + } + } +} + const std::string& Tokenizer::getSourceFilePath() const { if (list.getFiles().empty()) { diff --git a/lib/tokenize.h b/lib/tokenize.h index f4f07a334..c15c7947c 100644 --- a/lib/tokenize.h +++ b/lib/tokenize.h @@ -461,6 +461,11 @@ public: */ void simplifyMathFunctions(); + /** + * Simplify e.g. 'sin(0)' into '0' + */ + void simplifyMathExpressions(); + /** * Modify strings in the token list by replacing hex and oct * values. E.g. "\x61" -> "a" and "\000" -> "\0" diff --git a/test/testtokenize.cpp b/test/testtokenize.cpp index 97b864a56..90ebf1212 100644 --- a/test/testtokenize.cpp +++ b/test/testtokenize.cpp @@ -439,6 +439,8 @@ private: TEST_CASE(platformWin64); TEST_CASE(platformUnix32); TEST_CASE(platformUnix64); + + TEST_CASE(simplifyMathExpressions); //ticket #1620 } std::string tokenizeAndStringify(const char code[], bool simplify = false, bool expand = true, Settings::PlatformType platform = Settings::Unspecified, const char* filename = "test.cpp", bool cpp11 = true) { @@ -7188,6 +7190,36 @@ private: ASSERT_EQUALS(expected, tokenizeAndStringify(code, true, true, Settings::Unix64)); } + + void simplifyMathExpressions() {//#1620 + const char *code1 ="void foo() {\n" + "std::cout<