| 1 | //===--- InaccurateEraseCheck.cpp - clang-tidy-----------------------------===// |
| 2 | // |
| 3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
| 4 | // See https://llvm.org/LICENSE.txt for license information. |
| 5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
| 6 | // |
| 7 | //===----------------------------------------------------------------------===// |
| 8 | |
| 9 | #include "InaccurateEraseCheck.h" |
| 10 | #include "clang/ASTMatchers/ASTMatchFinder.h" |
| 11 | #include "clang/Lex/Lexer.h" |
| 12 | |
| 13 | using namespace clang::ast_matchers; |
| 14 | |
| 15 | namespace clang::tidy::bugprone { |
| 16 | |
| 17 | void InaccurateEraseCheck::registerMatchers(MatchFinder *Finder) { |
| 18 | const auto EndCall = |
| 19 | callExpr( |
| 20 | callee(InnerMatcher: functionDecl(hasAnyName("remove" , "remove_if" , "unique" ))), |
| 21 | hasArgument(N: 1, InnerMatcher: optionally(cxxMemberCallExpr( |
| 22 | callee(InnerMatcher: cxxMethodDecl(hasName(Name: "end" )))) |
| 23 | .bind(ID: "end" )))) |
| 24 | .bind(ID: "alg" ); |
| 25 | |
| 26 | const auto DeclInStd = type(hasUnqualifiedDesugaredType( |
| 27 | InnerMatcher: tagType(hasDeclaration(InnerMatcher: decl(isInStdNamespace()))))); |
| 28 | Finder->addMatcher( |
| 29 | NodeMatch: cxxMemberCallExpr( |
| 30 | on(InnerMatcher: anyOf(hasType(InnerMatcher: DeclInStd), hasType(InnerMatcher: pointsTo(InnerMatcher: DeclInStd)))), |
| 31 | callee(InnerMatcher: cxxMethodDecl(hasName(Name: "erase" ))), argumentCountIs(N: 1), |
| 32 | hasArgument(N: 0, InnerMatcher: EndCall)) |
| 33 | .bind(ID: "erase" ), |
| 34 | Action: this); |
| 35 | } |
| 36 | |
| 37 | void InaccurateEraseCheck::check(const MatchFinder::MatchResult &Result) { |
| 38 | const auto *MemberCall = Result.Nodes.getNodeAs<CXXMemberCallExpr>(ID: "erase" ); |
| 39 | const auto *EndExpr = Result.Nodes.getNodeAs<CXXMemberCallExpr>(ID: "end" ); |
| 40 | const SourceLocation Loc = MemberCall->getBeginLoc(); |
| 41 | |
| 42 | FixItHint Hint; |
| 43 | |
| 44 | if (!Loc.isMacroID() && EndExpr) { |
| 45 | const auto *AlgCall = Result.Nodes.getNodeAs<CallExpr>(ID: "alg" ); |
| 46 | std::string ReplacementText = std::string(Lexer::getSourceText( |
| 47 | Range: CharSourceRange::getTokenRange(EndExpr->getSourceRange()), |
| 48 | SM: *Result.SourceManager, LangOpts: getLangOpts())); |
| 49 | const SourceLocation EndLoc = Lexer::getLocForEndOfToken( |
| 50 | Loc: AlgCall->getEndLoc(), Offset: 0, SM: *Result.SourceManager, LangOpts: getLangOpts()); |
| 51 | Hint = FixItHint::CreateInsertion(InsertionLoc: EndLoc, Code: ", " + ReplacementText); |
| 52 | } |
| 53 | |
| 54 | diag(Loc, Description: "this call will remove at most one item even when multiple items " |
| 55 | "should be removed" ) |
| 56 | << Hint; |
| 57 | } |
| 58 | |
| 59 | } // namespace clang::tidy::bugprone |
| 60 | |