clang-tools  3.8.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 void InaccurateEraseCheck::registerMatchers(MatchFinder *Finder) {
22  // Only register the matchers for C++; the functionality currently does not
23  // provide any benefit to other languages, despite being benign.
24  if (!getLangOpts().CPlusPlus)
25  return;
26 
27  const auto CheckForEndCall = hasArgument(
28  1, anyOf(cxxConstructExpr(
29  has(cxxMemberCallExpr(callee(cxxMethodDecl(hasName("end"))))
30  .bind("InaccEndCall"))),
31  anything()));
32 
33  Finder->addMatcher(
34  cxxMemberCallExpr(
35  on(hasType(namedDecl(matchesName("^::std::")))),
36  callee(cxxMethodDecl(hasName("erase"))), argumentCountIs(1),
37  hasArgument(0, has(callExpr(callee(functionDecl(matchesName(
38  "^::std::(remove(_if)?|unique)$"))),
39  CheckForEndCall)
40  .bind("InaccAlgCall"))),
41  unless(isInTemplateInstantiation()))
42  .bind("InaccErase"),
43  this);
44 }
45 
46 void InaccurateEraseCheck::check(const MatchFinder::MatchResult &Result) {
47  const auto *MemberCall =
48  Result.Nodes.getNodeAs<CXXMemberCallExpr>("InaccErase");
49  const auto *EndExpr =
50  Result.Nodes.getNodeAs<CXXMemberCallExpr>("InaccEndCall");
51  const SourceLocation Loc = MemberCall->getLocStart();
52 
53  FixItHint Hint;
54 
55  if (!Loc.isMacroID() && EndExpr) {
56  const auto *AlgCall = Result.Nodes.getNodeAs<CallExpr>("InaccAlgCall");
57  std::string ReplacementText = Lexer::getSourceText(
58  CharSourceRange::getTokenRange(EndExpr->getSourceRange()),
59  *Result.SourceManager, Result.Context->getLangOpts());
60  const SourceLocation EndLoc = Lexer::getLocForEndOfToken(
61  AlgCall->getLocEnd(), 0, *Result.SourceManager,
62  Result.Context->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 misc
72 } // namespace tidy
73 } // namespace clang
SourceLocation Loc
'#' location in the include directive
std::unique_ptr< ast_matchers::MatchFinder > Finder
Definition: ClangTidy.cpp:188
const NamedDecl * Result
Definition: USRFinder.cpp:121