clang-tools  3.9.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(has(ignoringParenImpCasts(
29  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(ignoringParenImpCasts(
38  callExpr(callee(functionDecl(matchesName(
39  "^::std::(remove(_if)?|unique)$"))),
40  CheckForEndCall)
41  .bind("InaccAlgCall")))),
42  unless(isInTemplateInstantiation()))
43  .bind("InaccErase"),
44  this);
45 }
46 
47 void InaccurateEraseCheck::check(const MatchFinder::MatchResult &Result) {
48  const auto *MemberCall =
49  Result.Nodes.getNodeAs<CXXMemberCallExpr>("InaccErase");
50  const auto *EndExpr =
51  Result.Nodes.getNodeAs<CXXMemberCallExpr>("InaccEndCall");
52  const SourceLocation Loc = MemberCall->getLocStart();
53 
54  FixItHint Hint;
55 
56  if (!Loc.isMacroID() && EndExpr) {
57  const auto *AlgCall = Result.Nodes.getNodeAs<CallExpr>("InaccAlgCall");
58  std::string ReplacementText = Lexer::getSourceText(
59  CharSourceRange::getTokenRange(EndExpr->getSourceRange()),
60  *Result.SourceManager, Result.Context->getLangOpts());
61  const SourceLocation EndLoc = Lexer::getLocForEndOfToken(
62  AlgCall->getLocEnd(), 0, *Result.SourceManager,
63  Result.Context->getLangOpts());
64  Hint = FixItHint::CreateInsertion(EndLoc, ", " + ReplacementText);
65  }
66 
67  diag(Loc, "this call will remove at most one item even when multiple items "
68  "should be removed")
69  << Hint;
70 }
71 
72 } // namespace misc
73 } // namespace tidy
74 } // namespace clang
SourceLocation Loc
'#' location in the include directive
std::unique_ptr< ast_matchers::MatchFinder > Finder
Definition: ClangTidy.cpp:210
const NamedDecl * Result
Definition: USRFinder.cpp:137