diff --git a/src/tokenize.cpp b/src/tokenize.cpp index 682d5ec9e..d905a7c2b 100644 --- a/src/tokenize.cpp +++ b/src/tokenize.cpp @@ -1465,6 +1465,7 @@ void Tokenizer::simplifyTokenList() modified |= removeReduntantConditions(); modified |= simplifyRedundantParanthesis(); modified |= simplifyCalculations(); + modified |= simplifyQuestionMark(); } createLinks(); @@ -1840,6 +1841,51 @@ bool Tokenizer::simplifyConditions() return ret; } +bool Tokenizer::simplifyQuestionMark() +{ + bool ret = false; + for (Token *tok = _tokens; tok; tok = tok->next()) + { + if (tok->str() != "?") + continue; + + if (!tok->previous() || !tok->previous()->previous()) + continue; + + if (!Token::Match(tok->previous()->previous(), "[=,(]")) + continue; + + if (!Token::Match(tok->previous(), "%bool%") && + !Token::Match(tok->previous(), "%num%")) + continue; + + if (tok->previous()->str() == "false" || + tok->previous()->str() == "0") + { + // Use code after semicolon, remove code before it. + const Token *end = Token::findmatch(tok, ":"); + if (!end || !end->next()) + continue; + + end = end->next(); + tok = tok->previous(); + while (tok->next() != end) + { + tok->deleteNext(); + } + + Token *temp = tok; + tok = tok->next(); + temp->deleteThis(); + } + else + { + // Use code before semicolon + } + } + + return ret; +} bool Tokenizer::simplifyCasts() { diff --git a/src/tokenize.h b/src/tokenize.h index a4fac3a38..e51d84961 100644 --- a/src/tokenize.h +++ b/src/tokenize.h @@ -100,6 +100,11 @@ public: */ bool simplifyVarDecl(); + /** + * Simplify question mark - colon operator + * Example: 0 ? (2/0) : 0 => 0 + */ + bool simplifyQuestionMark(); /** * simplify if-assignments.. diff --git a/test/testother.cpp b/test/testother.cpp index 6eaf2093a..b09ee78ff 100644 --- a/test/testother.cpp +++ b/test/testother.cpp @@ -111,10 +111,14 @@ private: " cout<