From 3629f953f001e27d469ae0af8b59421e13e5c2c1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Marjam=C3=A4ki?= Date: Fri, 6 May 2011 21:16:01 +0200 Subject: [PATCH] Fixed #2770 (False positives (scope can be reduced / variable is assigned value that is never used)) --- lib/checkother.cpp | 21 ++++++++++++--------- test/testother.cpp | 12 ++++++++++++ test/testunusedvar.cpp | 6 ++++++ 3 files changed, 30 insertions(+), 9 deletions(-) diff --git a/lib/checkother.cpp b/lib/checkother.cpp index 481ec4279..ae4d43341 100644 --- a/lib/checkother.cpp +++ b/lib/checkother.cpp @@ -2230,6 +2230,15 @@ void CheckOther::functionVariableUsage() else variables.modified(tok->varId()); } + + else if (tok->isAssignmentOp()) + { + for (const Token *tok2 = tok->next(); tok2 && tok2->str() != ";"; tok2 = tok2->next()) + { + if (tok2->varId()) + variables.read(tok2->varId()); + } + } } // Check usage of all variables in the current scope.. @@ -2473,19 +2482,13 @@ void CheckOther::lookupVar(const Token *tok1, const std::string &varname) for_or_while = true; } - if (Token::simpleMatch(tok, "do {")) + else if (Token::simpleMatch(tok, "do {")) for_or_while = true; // possible unexpanded macro hiding for/while.. - if (Token::Match(tok->previous(), "[;{}] %type% {")) + else if (tok->str() != "else" && Token::Match(tok->previous(), "[;{}] %type% {")) { - bool upper = true; - for (unsigned int i = 0; i < tok->str().length(); ++i) - { - if (!std::isupper(tok->str()[i])) - upper = false; - } - for_or_while |= upper; + for_or_while = true; } if (parlevel == 0 && (tok->str() == ";")) diff --git a/test/testother.cpp b/test/testother.cpp index 21f296301..c518fec65 100644 --- a/test/testother.cpp +++ b/test/testother.cpp @@ -60,6 +60,7 @@ private: TEST_CASE(varScope9); // classes may have extra side-effects TEST_CASE(varScope10); // Undefined macro FOR TEST_CASE(varScope11); // #2475 - struct initialization is not inner scope + TEST_CASE(varScope12); // variable usage in inner loop TEST_CASE(oldStylePointerCast); @@ -686,6 +687,17 @@ private: ASSERT_EQUALS("", errout.str()); } + void varScope12() + { + // #2770 + varScope("void f() {\n" + " int i = 0;\n" + " forever {\n" + " if (i++ == 42) { break; }\n" + " }\n" + "}"); + ASSERT_EQUALS("", errout.str()); + } void checkOldStylePointerCast(const char code[]) { diff --git a/test/testunusedvar.cpp b/test/testunusedvar.cpp index c782364f2..3ad693053 100644 --- a/test/testunusedvar.cpp +++ b/test/testunusedvar.cpp @@ -2394,6 +2394,12 @@ private: " a |= b;\n" "}\n"); ASSERT_EQUALS("[test.cpp:3]: (style) Variable 'a' is assigned a value that is never used\n", errout.str()); + + functionVariableUsage("void foo() {\n" + " int a = 1;\n" + " (b).x += a;\n" + "}\n"); + ASSERT_EQUALS("", errout.str()); } void localvarFor()