From 69d03bac3471141af31c707f6fcc2d5f375cedd2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Marjam=C3=A4ki?= Date: Sun, 19 Feb 2012 15:25:46 +0100 Subject: [PATCH] Fixed #3603 (False Positive: Variable is assigned a value that is never used) --- lib/checkunusedvar.cpp | 27 +++++++++++++++++---------- test/testunusedvar.cpp | 11 +++++++++++ 2 files changed, 28 insertions(+), 10 deletions(-) diff --git a/lib/checkunusedvar.cpp b/lib/checkunusedvar.cpp index 075b99039..6b1f1749b 100644 --- a/lib/checkunusedvar.cpp +++ b/lib/checkunusedvar.cpp @@ -662,17 +662,24 @@ void CheckUnusedVar::checkFunctionVariableUsage_iterateScopes(const Scope* const break; } - if (Token::Match(tok, "%type% const| *|&| const| *| const| %var% [;=[(]") && tok->str() != "return" && tok->str() != "throw") { // Declaration: Skip - tok = tok->next(); - while (Token::Match(tok, "const|*|&")) + if (Token::Match(tok, "%type% const| *|&| const| *| const| %var% [;=[(]")) { // Declaration: Skip + // Before a declaration there should be ;{} + const Token *prev = tok; + while (prev && prev->isName() && prev->str() != "return" && prev->str() != "throw") + prev = prev->previous(); + if (Token::Match(prev, "[;{}]")) { + tok = tok->next(); - tok = Token::findmatch(tok, "[;=[(]"); - if (tok && Token::Match(tok, "( %var% )")) // Simple initialization through copy ctor - tok = tok->next(); - else if (tok && Token::Match(tok, "= %var% ;")) // Simple initialization - tok = tok->next(); - if (!tok) - break; + while (Token::Match(tok, "const|*|&")) + tok = tok->next(); + tok = Token::findmatch(tok, "[;=[(]"); + if (tok && Token::Match(tok, "( %var% )")) // Simple initialization through copy ctor + tok = tok->next(); + else if (tok && Token::Match(tok, "= %var% ;")) // Simple initialization + tok = tok->next(); + if (!tok) + break; + } } // Freeing memory (not considered "using" the pointer if it was also allocated in this function) if (Token::Match(tok, "free|g_free|kfree|vfree ( %var% )") || diff --git a/test/testunusedvar.cpp b/test/testunusedvar.cpp index 0f4f66a91..212727a4b 100644 --- a/test/testunusedvar.cpp +++ b/test/testunusedvar.cpp @@ -87,6 +87,7 @@ private: TEST_CASE(localvar39); // ticket #3454 TEST_CASE(localvar40); // ticket #3473 TEST_CASE(localvar41); // ticket #3481 + TEST_CASE(localvar42); // ticket #3603 TEST_CASE(localvaralias1); TEST_CASE(localvaralias2); // ticket #1637 TEST_CASE(localvaralias3); // ticket #1639 @@ -1401,6 +1402,16 @@ private: ASSERT_EQUALS("", errout.str()); } + void localvar42() { + // #3603 - false positive 'x is assigned a value that is never used' + functionVariableUsage("int f() {\n" + " int x = 1;\n" + " int y = FOO::VALUE * x;\n" + " return y;\n" + "}\n"); + ASSERT_EQUALS("", errout.str()); + } + void localvaralias1() { functionVariableUsage("void foo()\n" "{\n"