From a903aa7070545e20aff978357070d69c5312b54b Mon Sep 17 00:00:00 2001 From: Paul Fultz II Date: Mon, 23 Sep 2019 01:49:04 -0500 Subject: [PATCH] Fix issue 9351: false negative: (style) Condition '...' is always true (#2201) --- lib/checkcondition.cpp | 3 ++- lib/valueflow.cpp | 2 +- test/testcondition.cpp | 8 ++++++++ 3 files changed, 11 insertions(+), 2 deletions(-) diff --git a/lib/checkcondition.cpp b/lib/checkcondition.cpp index 718ef45b6..64d5ca2cb 100644 --- a/lib/checkcondition.cpp +++ b/lib/checkcondition.cpp @@ -1357,8 +1357,9 @@ void CheckCondition::alwaysTrueFalse() const bool compExpr = Token::Match(tok, "%comp%|!"); // a compare expression const bool returnStatement = Token::simpleMatch(tok->astTop(), "return") && Token::Match(tok->astParent(), "%oror%|&&|return"); + const bool ternaryExpression = Token::simpleMatch(tok->astParent(), "?"); - if (!(constIfWhileExpression || constValExpr || compExpr || returnStatement)) + if (!(constIfWhileExpression || constValExpr || compExpr || returnStatement || ternaryExpression)) continue; if (returnStatement && (!scope->function || !Token::simpleMatch(scope->function->retDef, "bool"))) diff --git a/lib/valueflow.cpp b/lib/valueflow.cpp index 893bafb25..33d4dfdaf 100644 --- a/lib/valueflow.cpp +++ b/lib/valueflow.cpp @@ -4730,7 +4730,7 @@ static void valueFlowInferCondition(TokenList* tokenlist, continue; if (tok->hasKnownValue()) continue; - if (Token::Match(tok, "%var%") && (Token::Match(tok->astParent(), "&&|!|%oror%") || + if (Token::Match(tok, "%var%") && (Token::Match(tok->astParent(), "?|&&|!|%oror%") || Token::Match(tok->astParent()->previous(), "if|while ("))) { const ValueFlow::Value* result = proveNotEqual(tok->values(), 0); if (!result) diff --git a/test/testcondition.cpp b/test/testcondition.cpp index 1a9ba624b..743c3fedf 100644 --- a/test/testcondition.cpp +++ b/test/testcondition.cpp @@ -3295,6 +3295,14 @@ private: "}\n"); ASSERT_EQUALS("", errout.str()); + // #9351 + check("int f(int x) {\n" + " const bool b = x < 42;\n" + " if(b) return b?0:-1;\n" + " return 42;\n" + "}\n"); + ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:3]: (style) Condition 'b' is always true\n", errout.str()); + // #9362 check("uint8_t g();\n" "void f() {\n"