diff --git a/lib/token.cpp b/lib/token.cpp index b4524ded7..3a50406f8 100644 --- a/lib/token.cpp +++ b/lib/token.cpp @@ -1202,6 +1202,33 @@ std::string Token::expressionString() const } end = end->astOperand2() ? end->astOperand2() : end->astOperand1(); } + + // move start to lpar in such expression: '(*it).x' + int par = 0; + for (const Token *tok = start; tok != end; tok = tok->next()) { + if (tok->str() == "(") + ++par; + else if (tok->str() == ")") { + if (par == 0) + start = tok->link(); + else + --par; + } + } + + // move end to rpar in such expression: '2>(x+1)' + par = 0; + for (const Token *tok = end; tok != start; tok = tok->previous()) { + if (tok->str() == ")") + ++par; + else if (tok->str() == "(") { + if (par == 0) + end = tok->link(); + else + --par; + } + } + std::string ret; for (const Token *tok = start; tok && tok != end; tok = tok->next()) { ret += tok->str(); diff --git a/test/testcondition.cpp b/test/testcondition.cpp index 172fa95e2..e539ef720 100644 --- a/test/testcondition.cpp +++ b/test/testcondition.cpp @@ -1418,6 +1418,17 @@ private: " if (x>0 || (x<0 && y)) {}\n" "}"); ASSERT_EQUALS("", errout.str()); + + // Test Token::expressionString, TODO move this test + check("void f() {\n" + " if (!dead || (dead && (*it).ticks > 0)) {}\n" + "}"); + ASSERT_EQUALS("[test.cpp:2]: (style) Redundant condition: dead. '!dead || (dead && (*it).ticks>0)' is equivalent to '!dead || (*it).ticks>0'\n", errout.str()); + + check("void f() {\n" + " if (!x || (x && (2>(y-1)))) {}\n" + "}"); + ASSERT_EQUALS("[test.cpp:2]: (style) Redundant condition: x. '!x || (x && 2>(y-1))' is equivalent to '!x || 2>(y-1)'\n", errout.str()); } // clarify conditions with bitwise operator and comparison