From e553940e23762cd2aca9b5eab55549c760bfa9be Mon Sep 17 00:00:00 2001 From: olabetskyi <153490942+olabetskyi@users.noreply.github.com> Date: Sun, 24 Dec 2023 15:01:01 +0200 Subject: [PATCH] =?UTF-8?q?#12158:=20improve=20check:=20variableScope=20is?= =?UTF-8?q?=20not=20reported=20when=20there=20is=20el=E2=80=A6=20(#5758)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit variableScope is not reported when there is else if --- lib/checkother.cpp | 11 +---------- test/testother.cpp | 31 +++++++++++++++++++++++++++++++ 2 files changed, 32 insertions(+), 10 deletions(-) diff --git a/lib/checkother.cpp b/lib/checkother.cpp index 3e324a683..8e23a0617 100644 --- a/lib/checkother.cpp +++ b/lib/checkother.cpp @@ -995,16 +995,7 @@ void CheckOther::checkVariableScope() // parse else if blocks.. } else if (Token::simpleMatch(tok, "else { if (") && Token::simpleMatch(tok->linkAt(3), ") {")) { - const Token *endif = tok->linkAt(3)->linkAt(1); - bool elseif = false; - if (Token::simpleMatch(endif, "} }")) - elseif = true; - else if (Token::simpleMatch(endif, "} else {") && Token::simpleMatch(endif->linkAt(2),"} }")) - elseif = true; - if (elseif && Token::findmatch(tok->next(), "%varid%", tok->linkAt(1), var->declarationId())) { - reduce = false; - break; - } + tok = tok->next(); } else if (tok->varId() == var->declarationId() || tok->str() == "goto") { reduce = false; break; diff --git a/test/testother.cpp b/test/testother.cpp index 93f2a5e48..e73ef09e0 100644 --- a/test/testother.cpp +++ b/test/testother.cpp @@ -101,6 +101,8 @@ private: TEST_CASE(varScope33); TEST_CASE(varScope34); TEST_CASE(varScope35); + TEST_CASE(varScope36); // #12158 + TEST_CASE(varScope37); // #12158 TEST_CASE(oldStylePointerCast); TEST_CASE(invalidPointerCast); @@ -1667,6 +1669,35 @@ private: ASSERT_EQUALS("[test.cpp:4]: (style) The scope of the variable 'buf' can be reduced.\n", errout.str()); } + void varScope36() { + // #12158 + check("void f( uint32_t value ) {\n" + " uint32_t i = 0U;\n" + " if ( value > 100U ) { }\n" + " else if( value > 50U ) { }\n" + " else{\n" + " for( i = 0U; i < 5U; i++ ) {}\n" + " }\n" + "}\n", nullptr, false); + ASSERT_EQUALS("[test.cpp:2]: (style) The scope of the variable 'i' can be reduced.\n", errout.str()); + } + + void varScope37() { + // #12158 + check("void f( uint32_t value ) {\n" + " uint32_t i = 0U;\n" + " if ( value > 100U ) { }\n" + " else {\n" + " if( value > 50U ) { }\n" + " else{\n" + " for( i = 0U; i < 5U; i++ ) {}\n" + " }\n" + " }\n" + "}\n", nullptr, false); + ASSERT_EQUALS("[test.cpp:2]: (style) The scope of the variable 'i' can be reduced.\n", errout.str()); + } + + #define checkOldStylePointerCast(code) checkOldStylePointerCast_(code, __FILE__, __LINE__) void checkOldStylePointerCast_(const char code[], const char* file, int line) { // Clear the error buffer..