From 67e40a85e5fbe01aac206e55b7349a0d7899c8c7 Mon Sep 17 00:00:00 2001 From: Arpit Chaudhary Date: Tue, 4 Sep 2012 16:06:00 +0530 Subject: [PATCH] Improved check for shifting by negative values and removed false positives --- lib/checkother.cpp | 14 +++++++++++--- test/testother.cpp | 20 ++++++++++++++++++++ 2 files changed, 31 insertions(+), 3 deletions(-) diff --git a/lib/checkother.cpp b/lib/checkother.cpp index 9928e779f..a809e76be 100644 --- a/lib/checkother.cpp +++ b/lib/checkother.cpp @@ -3329,10 +3329,18 @@ void CheckOther::redundantCopyError(const Token *tok,const std::string& varname) void CheckOther::checkNegativeBitwiseShift() { + const SymbolDatabase *symbolDatabase = _tokenizer->getSymbolDatabase(); + for (const Token *tok = _tokenizer->tokens(); tok ; tok = tok->next()) { - if (Token::Match(tok,"%var% >>|<< %num%") || Token::Match(tok,"%num >>|<< %num%")) { - if ((tok->strAt(2))[0] == '-') - negativeBitwiseShiftError(tok); + if ((Token::Match(tok,"%var% >>|<< %num%") || Token::Match(tok,"%num% >>|<< %num%")) && !Token::Match(tok->previous(),">>|<<")) { + if (tok->isName()) { + const Variable* var = symbolDatabase->getVariableFromVarId(tok->varId()); + if (var && var->typeStartToken()->isStandardType() && (tok->strAt(2))[0] == '-') + negativeBitwiseShiftError(tok); + } else { + if ((tok->strAt(2))[0] == '-') + negativeBitwiseShiftError(tok); + } } } } diff --git a/test/testother.cpp b/test/testother.cpp index 61982eb1e..82a9520ca 100644 --- a/test/testother.cpp +++ b/test/testother.cpp @@ -6111,6 +6111,26 @@ private: " a >>= -1;\n" "}"); ASSERT_EQUALS("[test.cpp:4]: (error) Shifting by a negative value.\n", errout.str()); + check("void foo()\n" + "{\n" + " int a = 123 << -1;\n" + "}"); + TODO_ASSERT_EQUALS("[test.cpp:3]: (error) Shifting by a negative value.\n", "", errout.str()); + check("void foo()\n" + "{\n" + " std::cout << -1;\n" + "}"); + ASSERT_EQUALS("", errout.str()); + check("void foo()\n" + "{\n" + " std::cout << a << -1 ;\n" + "}"); + ASSERT_EQUALS("", errout.str()); + check("void foo()\n" + "{\n" + " std::cout << 3 << -1 ;\n" + "}"); + ASSERT_EQUALS("", errout.str()); } void incompleteArrayFill() {