Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix #12900 FP useStlAlgorithm with assignment #7247

Merged
merged 3 commits into from
Jan 23, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion lib/checkstl.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2905,6 +2905,13 @@ void CheckStl::useStlAlgorithm()
return isConstExpression(tok->linkAt(-1)->astOperand2(), mSettings->library);
};

auto isAccumulation = [](const Token* tok, int varId) {
if (tok->str() != "=")
return true;
const Token* end = Token::findmatch(tok, "%varid%|;", varId); // TODO: lambdas?
return end && end->varId() != 0;
};

for (const Scope *function : mTokenizer->getSymbolDatabase()->functionScopes) {
for (const Token *tok = function->bodyStart; tok != function->bodyEnd; tok = tok->next()) {
// Parse range-based for loop
Expand Down Expand Up @@ -2970,8 +2977,10 @@ void CheckStl::useStlAlgorithm()
algo = "std::any_of, std::all_of, std::none_of, or std::accumulate";
else if (Token::Match(assignTok, "= %var% <|<=|>=|> %var% ? %var% : %var%") && hasVarIds(assignTok->tokAt(6), loopVar->varId(), assignVarId))
algo = minmaxCompare(assignTok->tokAt(2), loopVar->varId(), assignVarId, assignTok->tokAt(5)->varId() == assignVarId);
else
else if (isAccumulation(assignTok, assignVarId))
algo = "std::accumulate";
else
continue;
}
useStlAlgorithmError(assignTok, algo);
continue;
Expand Down
8 changes: 8 additions & 0 deletions test/teststl.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -5430,6 +5430,14 @@ class TestStl : public TestFixture {
" return sum;\n"
"}\n");
ASSERT_EQUALS("", errout_str());

check("int f(const std::vector<int>& v) {\n" // #12900
" int x{};\n"
" for (const auto i : v)\n"
" x = dostuff(i);\n"
" return x;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}

void loopAlgoContainerInsert() {
Expand Down
Loading