From 739b6a93e244aa1d27366cc5dfba1a2ce262ae6a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Marjam=C3=A4ki?= Date: Sat, 16 Apr 2011 12:07:56 +0200 Subject: [PATCH] Fixed #2713 (False positive (Redundant assignment)) --- lib/tokenize.cpp | 16 ++++++++++++++++ lib/tokenize.h | 3 ++- test/testother.cpp | 12 ++++++++++++ test/testsimplifytokens.cpp | 19 +++++++++++++++---- 4 files changed, 45 insertions(+), 5 deletions(-) diff --git a/lib/tokenize.cpp b/lib/tokenize.cpp index 6eeaef283..1406816d5 100644 --- a/lib/tokenize.cpp +++ b/lib/tokenize.cpp @@ -6213,6 +6213,22 @@ void Tokenizer::simplifyIfNotNull() { Token *deleteFrom = NULL; + // Remove 'x = (x != 0)' + if (Token::simpleMatch(tok, "= (")) + { + if (Token::Match(tok->tokAt(-2), "[;{}] %var%")) + { + const unsigned int varid = tok->previous()->varId(); + if (Token::Match(tok, "= ( %varid% != 0 ) ;", varid) || + Token::Match(tok, "= ( 0 != %varid% ) ;", varid)) + { + tok = tok->tokAt(-2); + Token::eraseTokens(tok, tok->tokAt(9)); + } + } + continue; + } + if (Token::Match(tok, "(|&&|%oror%")) { tok = tok->next(); diff --git a/lib/tokenize.h b/lib/tokenize.h index fb1eefc20..1a1377325 100644 --- a/lib/tokenize.h +++ b/lib/tokenize.h @@ -253,7 +253,8 @@ public: /** * simplify if-not NULL - * - "if(0!=x);" => "if(x);" + * Example: "if(0!=x);" => "if(x);" + * Special case: 'x = (0 != x);' is removed. */ void simplifyIfNotNull(); diff --git a/test/testother.cpp b/test/testother.cpp index e65f6a025..2fd0006c1 100644 --- a/test/testother.cpp +++ b/test/testother.cpp @@ -1582,6 +1582,18 @@ private: " Fred fred; fred = fred;\n" "}\n"); ASSERT_EQUALS("", errout.str()); + + check("void f(int x) {\n" + " x = (x == 0);" + " func(x);\n" + "}"); + ASSERT_EQUALS("", errout.str()); + + check("void f(int x) {\n" + " x = (x != 0);" + " func(x);\n" + "}"); + ASSERT_EQUALS("", errout.str()); } void testScanf1() diff --git a/test/testsimplifytokens.cpp b/test/testsimplifytokens.cpp index 345354679..05419b35c 100644 --- a/test/testsimplifytokens.cpp +++ b/test/testsimplifytokens.cpp @@ -6727,11 +6727,22 @@ private: ASSERT_EQUALS("", errout.str()); } - void simplifyIfNotNull() // ticket # 2601 segmentation fault + void simplifyIfNotNull() { - const char code[] = "|| #if #define <="; - tok(code, false); - ASSERT_EQUALS("", errout.str()); + { + // ticket # 2601 segmentation fault + const char code[] = "|| #if #define <="; + tok(code, false); + ASSERT_EQUALS("", errout.str()); + } + + { + const char code[] = "void f(int x) {\n" + " x = (x != 0);\n" + "}"; + ASSERT_EQUALS("void f ( int x ) { }", tok(code, false)); + } + } };