From edde0eedaa75a58dab2ad7f273147ab351b9ea99 Mon Sep 17 00:00:00 2001 From: Paul Fultz II Date: Sun, 21 Oct 2018 01:04:00 -0500 Subject: [PATCH] Fix FP issue 8801: Condition 'a+b' is always true (#1444) --- lib/checkcondition.cpp | 21 ++++++++++++++++++++- test/testcondition.cpp | 7 +++++++ 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/lib/checkcondition.cpp b/lib/checkcondition.cpp index a969edcc2..cd9c1c557 100644 --- a/lib/checkcondition.cpp +++ b/lib/checkcondition.cpp @@ -1235,6 +1235,25 @@ void CheckCondition::clarifyConditionError(const Token *tok, bool assign, bool b errmsg, CWE398, false); } +static bool isConstVarExpression(const Token * tok) +{ + if(!tok) + return false; + if(Token::Match(tok, "%cop%")) { + if(tok->astOperand1() && !isConstVarExpression(tok->astOperand1())) + return false; + if(tok->astOperand2() && !isConstVarExpression(tok->astOperand2())) + return false; + return true; + } + if(Token::Match(tok, "%bool%|%num%|%str%|%char%|nullptr|NULL")) + return true; + if(tok->isEnumerator()) + return true; + if(tok->variable()) + return tok->variable()->isConst(); + return false; +} void CheckCondition::alwaysTrueFalse() { @@ -1269,7 +1288,7 @@ void CheckCondition::alwaysTrueFalse() if (!(constIfWhileExpression || constValExpr || compExpr || returnStatement)) continue; - if (returnStatement && (tok->isEnumerator() || Token::Match(tok, "nullptr|NULL"))) + if (returnStatement && isConstVarExpression(tok)) continue; if (returnStatement && Token::simpleMatch(tok->astParent(), "return") && tok->variable() && ( diff --git a/test/testcondition.cpp b/test/testcondition.cpp index 280860ed2..5f53c6944 100644 --- a/test/testcondition.cpp +++ b/test/testcondition.cpp @@ -2603,6 +2603,13 @@ private: "}\n"); ASSERT_EQUALS("", errout.str()); + check("int f() {\n" + " const int a = 50;\n" + " const int b = 52;\n" + " return a+b;\n" + "}\n"); + ASSERT_EQUALS("", errout.str()); + check("bool& g();\n" "bool f() {\n" " bool & b = g();\n"