From 9cd5558f5e467ea41944a3d3e3d2878886a9a1e6 Mon Sep 17 00:00:00 2001 From: Reijo Tomperi Date: Sat, 6 Jun 2009 00:33:13 +0300 Subject: [PATCH] Fix ticket #364 (false positive:: division by zero) http://apps.sourceforge.net/trac/cppcheck/ticket/364 --- src/tokenize.cpp | 46 ++++++++++++++++++++++++++++++++++++++++++++++ src/tokenize.h | 5 +++++ test/testother.cpp | 8 ++++++-- 3 files changed, 57 insertions(+), 2 deletions(-) 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<