From e8260f2dcc24b33dfcb759b46edbc49d0f57e3ff Mon Sep 17 00:00:00 2001 From: chrchr-github <78114321+chrchr-github@users.noreply.github.com> Date: Thu, 16 Dec 2021 22:32:15 +0100 Subject: [PATCH] Improve fix for #9570: check if ternary operator is used in assignment to reference (#3614) --- lib/astutils.cpp | 9 ++++++--- lib/checkother.cpp | 2 +- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/lib/astutils.cpp b/lib/astutils.cpp index 59203ce3a..3817e16c3 100644 --- a/lib/astutils.cpp +++ b/lib/astutils.cpp @@ -1036,9 +1036,6 @@ static bool compareKnownValue(const Token * const tok1, const Token * const tok2 { static const auto isKnownFn = std::mem_fn(&ValueFlow::Value::isKnown); - if ((tok1->variable() && tok1->variable()->isStatic()) || (tok2->variable() && tok2->variable()->isStatic())) - return false; - const auto v1 = std::find_if(tok1->values().begin(), tok1->values().end(), isKnownFn); if (v1 == tok1->values().end()) { return false; @@ -2114,6 +2111,10 @@ bool isVariableChanged(const Token *tok, int indirect, const Settings *settings, { if (!tok) return false; + + if (indirect == 0 && isConstVarExpression(tok)) + return false; + const Token *tok2 = tok; int derefs = 0; while (Token::simpleMatch(tok2->astParent(), "*") || @@ -2582,6 +2583,8 @@ bool isConstVarExpression(const Token *tok, const char* skipMatch) { if (!tok) return false; + if (tok->str() == "?" && tok->astOperand2() && tok->astOperand2()->str() == ":") // ternary operator + return isConstVarExpression(tok->astOperand2()->astOperand1()) && isConstVarExpression(tok->astOperand2()->astOperand2()); // left and right of ":" if (skipMatch && Token::Match(tok, skipMatch)) return false; if (Token::simpleMatch(tok->previous(), "sizeof (")) diff --git a/lib/checkother.cpp b/lib/checkother.cpp index 9219eac8a..b5db71c20 100644 --- a/lib/checkother.cpp +++ b/lib/checkother.cpp @@ -2293,7 +2293,7 @@ void CheckOther::checkDuplicateExpression() } } } else if (styleEnabled && tok->astOperand1() && tok->astOperand2() && tok->str() == ":" && tok->astParent() && tok->astParent()->str() == "?") { - if (!tok->astOperand1()->values().empty() && !tok->astOperand2()->values().empty() && isEqualKnownValue(tok->astOperand1(), tok->astOperand2())) + if (!isVariableChanged(tok->astParent(), /*indirect*/ 0, mSettings, mTokenizer->isCPP()) && !tok->astOperand1()->values().empty() && !tok->astOperand2()->values().empty() && isEqualKnownValue(tok->astOperand1(), tok->astOperand2())) duplicateValueTernaryError(tok); else if (isSameExpression(mTokenizer->isCPP(), true, tok->astOperand1(), tok->astOperand2(), mSettings->library, false, true, &errorPath)) duplicateExpressionTernaryError(tok, errorPath);