Fixed #8901 (Unused value: const variable initialization)

This commit is contained in:
Daniel Marjamäki 2018-12-16 19:01:05 +01:00
parent 21eb1c5e22
commit c8d688607a
3 changed files with 20 additions and 6 deletions

View File

@ -1138,9 +1138,12 @@ struct FwdAnalysis::Result FwdAnalysis::checkRecursive(const Token *expr, const
if (exprVarIds.find(tok->varId()) != exprVarIds.end()) {
const Token *parent = tok;
bool other = false;
bool same = false;
while (Token::Match(parent->astParent(), ".|::|[")) {
parent = parent->astParent();
if (Token::Match(parent, ". %var%") && parent->next()->varId() && exprVarIds.find(parent->next()->varId()) == exprVarIds.end()) {
if (parent && isSameExpression(mCpp, false, expr, parent->astOperand1(), mLibrary, false, false, nullptr))
same = true;
if (!same && Token::Match(parent, ". %var%") && parent->next()->varId() && exprVarIds.find(parent->next()->varId()) == exprVarIds.end()) {
other = true;
break;
}

View File

@ -1236,6 +1236,16 @@ void CheckUnusedVar::checkFunctionVariableUsage()
if (Token::simpleMatch(tok, "try {"))
// todo: check try blocks
tok = tok->linkAt(1);
const Token *varDecl = nullptr;
if (tok->variable() && tok->variable()->nameToken() == tok) {
const Token * eq = tok->next();
while (Token::simpleMatch(eq, "["))
eq = eq->link()->next();
if (Token::simpleMatch(eq, "=")) {
varDecl = tok;
tok = eq;
}
}
// not assignment/initialization => continue
if ((!tok->isAssignmentOp() || !tok->astOperand1()) && !(Token::Match(tok, "%var% (") && tok->variable() && tok->variable()->nameToken() == tok))
continue;
@ -1271,11 +1281,7 @@ void CheckUnusedVar::checkFunctionVariableUsage()
// Is there a redundant assignment?
const Token *start = tok->findExpressionStartEndTokens().second->next();
const Token *expr = tok->astOperand1();
if (Token::Match(expr->previous(), "%var% [") && expr->previous()->variable() && expr->previous()->variable()->nameToken() == expr->previous())
expr = expr->previous();
else if (Token::Match(expr, "& %var% ="))
expr = expr->next();
const Token *expr = varDecl ? varDecl : tok->astOperand1();
FwdAnalysis fwdAnalysis(mTokenizer->isCPP(), mSettings->library);
if (fwdAnalysis.unusedValue(expr, start, scope->bodyEnd))

View File

@ -3966,6 +3966,11 @@ private:
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Variable 's' is assigned a value that is never used.\n", errout.str());
functionVariableUsage("void foo() {\n" // #8901
" const std::string s = \"foo\";\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Variable 's' is assigned a value that is never used.\n", errout.str());
functionVariableUsage("std::string foo() {\n"
" std::string s;\n" // Class instances are initialized. Assignment is not necessary
" return s;\n"