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/AST/ASTContext.h"
11 #include "clang/ASTMatchers/ASTMatchFinder.h"
12 #include "clang/Lex/Lexer.h"
13
14 using namespace clang::ast_matchers;
15
16 namespace clang {
17 namespace tidy {
18 namespace bugprone {
19
registerMatchers(MatchFinder * Finder)20 void InaccurateEraseCheck::registerMatchers(MatchFinder *Finder) {
21 const auto EndCall =
22 callExpr(
23 callee(functionDecl(hasAnyName("remove", "remove_if", "unique"))),
24 hasArgument(
25 1,
26 anyOf(cxxConstructExpr(has(ignoringImplicit(
27 cxxMemberCallExpr(callee(cxxMethodDecl(hasName("end"))))
28 .bind("end")))),
29 anything())))
30 .bind("alg");
31
32 const auto DeclInStd = type(hasUnqualifiedDesugaredType(
33 tagType(hasDeclaration(decl(isInStdNamespace())))));
34 Finder->addMatcher(
35 traverse(
36 ast_type_traits::TK_AsIs,
37 cxxMemberCallExpr(
38 on(anyOf(hasType(DeclInStd), hasType(pointsTo(DeclInStd)))),
39 callee(cxxMethodDecl(hasName("erase"))), argumentCountIs(1),
40 hasArgument(0, has(ignoringImplicit(anyOf(
41 EndCall, has(ignoringImplicit(EndCall)))))),
42 unless(isInTemplateInstantiation()))
43 .bind("erase")),
44 this);
45 }
46
check(const MatchFinder::MatchResult & Result)47 void InaccurateEraseCheck::check(const MatchFinder::MatchResult &Result) {
48 const auto *MemberCall =
49 Result.Nodes.getNodeAs<CXXMemberCallExpr>("erase");
50 const auto *EndExpr =
51 Result.Nodes.getNodeAs<CXXMemberCallExpr>("end");
52 const SourceLocation Loc = MemberCall->getBeginLoc();
53
54 FixItHint Hint;
55
56 if (!Loc.isMacroID() && EndExpr) {
57 const auto *AlgCall = Result.Nodes.getNodeAs<CallExpr>("alg");
58 std::string ReplacementText = std::string(Lexer::getSourceText(
59 CharSourceRange::getTokenRange(EndExpr->getSourceRange()),
60 *Result.SourceManager, getLangOpts()));
61 const SourceLocation EndLoc = Lexer::getLocForEndOfToken(
62 AlgCall->getEndLoc(), 0, *Result.SourceManager, getLangOpts());
63 Hint = FixItHint::CreateInsertion(EndLoc, ", " + ReplacementText);
64 }
65
66 diag(Loc, "this call will remove at most one item even when multiple items "
67 "should be removed")
68 << Hint;
69 }
70
71 } // namespace bugprone
72 } // namespace tidy
73 } // namespace clang
74