clang-tools  5.0.0
InaccurateEraseCheck.cpp
Go to the documentation of this file.
1 //===--- InaccurateEraseCheck.cpp - clang-tidy-----------------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "InaccurateEraseCheck.h"
11 #include "clang/AST/ASTContext.h"
12 #include "clang/ASTMatchers/ASTMatchFinder.h"
13 #include "clang/Lex/Lexer.h"
14 
15 using namespace clang::ast_matchers;
16 
17 namespace clang {
18 namespace tidy {
19 namespace misc {
20 
21 namespace {
22 AST_MATCHER(Decl, isInStdNamespace) { return Node.isInStdNamespace(); }
23 }
24 
25 void InaccurateEraseCheck::registerMatchers(MatchFinder *Finder) {
26  // Only register the matchers for C++; the functionality currently does not
27  // provide any benefit to other languages, despite being benign.
28  if (!getLangOpts().CPlusPlus)
29  return;
30 
31  const auto EndCall =
32  callExpr(
33  callee(functionDecl(hasAnyName("remove", "remove_if", "unique"))),
34  hasArgument(
35  1,
36  anyOf(cxxConstructExpr(has(ignoringImplicit(
37  cxxMemberCallExpr(callee(cxxMethodDecl(hasName("end"))))
38  .bind("end")))),
39  anything())))
40  .bind("alg");
41 
42  const auto DeclInStd = decl(isInStdNamespace());
43  Finder->addMatcher(
44  cxxMemberCallExpr(
45  on(anyOf(hasType(DeclInStd), hasType(pointsTo(DeclInStd)))),
46  callee(cxxMethodDecl(hasName("erase"))), argumentCountIs(1),
47  hasArgument(0, has(ignoringImplicit(
48  anyOf(EndCall, has(ignoringImplicit(EndCall)))))),
49  unless(isInTemplateInstantiation()))
50  .bind("erase"),
51  this);
52 }
53 
54 void InaccurateEraseCheck::check(const MatchFinder::MatchResult &Result) {
55  const auto *MemberCall =
56  Result.Nodes.getNodeAs<CXXMemberCallExpr>("erase");
57  const auto *EndExpr =
58  Result.Nodes.getNodeAs<CXXMemberCallExpr>("end");
59  const SourceLocation Loc = MemberCall->getLocStart();
60 
61  FixItHint Hint;
62 
63  if (!Loc.isMacroID() && EndExpr) {
64  const auto *AlgCall = Result.Nodes.getNodeAs<CallExpr>("alg");
65  std::string ReplacementText = Lexer::getSourceText(
66  CharSourceRange::getTokenRange(EndExpr->getSourceRange()),
67  *Result.SourceManager, getLangOpts());
68  const SourceLocation EndLoc = Lexer::getLocForEndOfToken(
69  AlgCall->getLocEnd(), 0, *Result.SourceManager, getLangOpts());
70  Hint = FixItHint::CreateInsertion(EndLoc, ", " + ReplacementText);
71  }
72 
73  diag(Loc, "this call will remove at most one item even when multiple items "
74  "should be removed")
75  << Hint;
76 }
77 
78 } // namespace misc
79 } // namespace tidy
80 } // namespace clang
SourceLocation Loc
'#' location in the include directive
std::unique_ptr< ast_matchers::MatchFinder > Finder
Definition: ClangTidy.cpp:275
AST_MATCHER(VarDecl, isAsm)