From 8cd680bba26dc917db4177f7ba533e6c576ff8e0 Mon Sep 17 00:00:00 2001 From: chrchr-github <78114321+chrchr-github@users.noreply.github.com> Date: Mon, 15 Apr 2024 22:43:04 +0200 Subject: [PATCH] Fix #8862 Enhancement: false negative: variablescope (#6294) --- lib/checkother.cpp | 4 ++++ test/testother.cpp | 23 +++++++++++++++++++++++ 2 files changed, 27 insertions(+) diff --git a/lib/checkother.cpp b/lib/checkother.cpp index 453495af520..171437a20db 100644 --- a/lib/checkother.cpp +++ b/lib/checkother.cpp @@ -915,6 +915,10 @@ static bool isSimpleExpr(const Token* tok, const Variable* var, const Settings* if (Token::Match(ftok, "%name% (") && ((ftok->function() && ftok->function()->isConst()) || settings->library.isFunctionConst(ftok->str(), /*pure*/ true))) needsCheck = true; + if (tok->isArithmeticalOp() && + (!tok->astOperand1() || isSimpleExpr(tok->astOperand1(), var, settings)) && + (!tok->astOperand2() || isSimpleExpr(tok->astOperand2(), var, settings))) + return true; } return (needsCheck && !findExpressionChanged(tok, tok->astParent(), var->scope()->bodyEnd, settings)); } diff --git a/test/testother.cpp b/test/testother.cpp index 4d4286ce1d5..85ee90f7ff6 100644 --- a/test/testother.cpp +++ b/test/testother.cpp @@ -100,6 +100,7 @@ class TestOther : public TestFixture { TEST_CASE(varScope37); // #12158 TEST_CASE(varScope38); TEST_CASE(varScope39); + TEST_CASE(varScope40); TEST_CASE(oldStylePointerCast); TEST_CASE(invalidPointerCast); @@ -1710,6 +1711,28 @@ class TestOther : public TestFixture { ASSERT_EQUALS("", errout_str()); } + void varScope40() { + checkP("#define NUM (-999.9)\n" + "double f(int i) {\n" + " double a = NUM;\n" + " double b = -NUM;\n" + " double c = -1.0 * NUM;\n" + " if (i == 1) {\n" + " return a;\n" + " }\n" + " if (i == 2) {\n" + " return b;\n" + " }\n" + " if (i == 3) {\n" + " return c;\n" + " }\n" + " return 0.0;\n" + "}\n"); + ASSERT_EQUALS("[test.cpp:3]: (style) The scope of the variable 'a' can be reduced.\n" + "[test.cpp:4]: (style) The scope of the variable 'b' can be reduced.\n" + "[test.cpp:5]: (style) The scope of the variable 'c' can be reduced.\n", + errout_str()); + } #define checkOldStylePointerCast(code) checkOldStylePointerCast_(code, __FILE__, __LINE__) void checkOldStylePointerCast_(const char code[], const char* file, int line) {