blob: 1331c57142a03b2bfee3c75bd52746d2d7ceb3bf [file] [log] [blame]
Benjamin Kramer47c4d102014-07-15 09:50:32 +00001//===--- ExplicitMakePairCheck.cpp - clang-tidy -----------------*- C++ -*-===//
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 "ExplicitMakePairCheck.h"
11#include "clang/ASTMatchers/ASTMatchFinder.h"
12#include "clang/ASTMatchers/ASTMatchers.h"
13#include "clang/AST/ASTContext.h"
14
15using namespace clang::ast_matchers;
16
17namespace clang {
18
19namespace ast_matchers {
20AST_MATCHER(DeclRefExpr, hasExplicitTemplateArgs) {
21 return Node.hasExplicitTemplateArgs();
22}
23} // namespace ast_matchers
24
25namespace tidy {
26namespace build {
27
28void
29ExplicitMakePairCheck::registerMatchers(ast_matchers::MatchFinder *Finder) {
30 // Look for std::make_pair with explicit template args. Ignore calls in
31 // templates.
32 Finder->addMatcher(
33 callExpr(unless(hasAncestor(decl(anyOf(
34 recordDecl(ast_matchers::isTemplateInstantiation()),
35 functionDecl(ast_matchers::isTemplateInstantiation()))))),
Benjamin Kramera5d954b2014-08-05 15:33:46 +000036 callee(expr(ignoringParenImpCasts(
Benjamin Kramerddf36de2014-07-21 09:40:52 +000037 declRefExpr(hasExplicitTemplateArgs(),
38 to(functionDecl(hasName("::std::make_pair"))))
Benjamin Kramera5d954b2014-08-05 15:33:46 +000039 .bind("declref"))))).bind("call"),
Benjamin Kramer47c4d102014-07-15 09:50:32 +000040 this);
41}
42
43void ExplicitMakePairCheck::check(const MatchFinder::MatchResult &Result) {
44 const auto *Call = Result.Nodes.getNodeAs<CallExpr>("call");
45 const auto *DeclRef = Result.Nodes.getNodeAs<DeclRefExpr>("declref");
46
47 // Sanity check: The use might have overriden ::std::make_pair.
48 if (Call->getNumArgs() != 2)
49 return;
50
51 const Expr *Arg0 = Call->getArg(0)->IgnoreParenImpCasts();
52 const Expr *Arg1 = Call->getArg(1)->IgnoreParenImpCasts();
53
54 // If types don't match, we suggest replacing with std::pair and explicit
55 // template arguments. Otherwise just remove the template arguments from
56 // make_pair.
57 if (Arg0->getType() != Call->getArg(0)->getType() ||
58 Arg1->getType() != Call->getArg(1)->getType()) {
59 diag(Call->getLocStart(), "for C++11-compatibility, use pair directly")
60 << FixItHint::CreateReplacement(
61 SourceRange(DeclRef->getLocStart(), DeclRef->getLAngleLoc()),
62 "std::pair<");
63 } else {
64 diag(Call->getLocStart(),
65 "for C++11-compatibility, omit template arguments from make_pair")
66 << FixItHint::CreateRemoval(
67 SourceRange(DeclRef->getLAngleLoc(), DeclRef->getRAngleLoc()));
68 }
69}
70
71} // namespace build
72} // namespace tidy
73} // namespace clang