blob: ad517698fd5e896b567237c88d3b5f76f55671f9 [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"
Chandler Carruth3cbd71c2015-01-14 11:24:38 +000011#include "clang/AST/ASTContext.h"
Benjamin Kramer47c4d102014-07-15 09:50:32 +000012#include "clang/ASTMatchers/ASTMatchFinder.h"
13#include "clang/ASTMatchers/ASTMatchers.h"
Benjamin Kramer47c4d102014-07-15 09:50:32 +000014
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(
Benjamin Kramer6bcbe6e2014-09-03 13:30:28 +000033 callExpr(unless(isInTemplateInstantiation()),
Benjamin Kramera5d954b2014-08-05 15:33:46 +000034 callee(expr(ignoringParenImpCasts(
Benjamin Kramerddf36de2014-07-21 09:40:52 +000035 declRefExpr(hasExplicitTemplateArgs(),
36 to(functionDecl(hasName("::std::make_pair"))))
Benjamin Kramera5d954b2014-08-05 15:33:46 +000037 .bind("declref"))))).bind("call"),
Benjamin Kramer47c4d102014-07-15 09:50:32 +000038 this);
39}
40
41void ExplicitMakePairCheck::check(const MatchFinder::MatchResult &Result) {
42 const auto *Call = Result.Nodes.getNodeAs<CallExpr>("call");
43 const auto *DeclRef = Result.Nodes.getNodeAs<DeclRefExpr>("declref");
44
45 // Sanity check: The use might have overriden ::std::make_pair.
46 if (Call->getNumArgs() != 2)
47 return;
48
49 const Expr *Arg0 = Call->getArg(0)->IgnoreParenImpCasts();
50 const Expr *Arg1 = Call->getArg(1)->IgnoreParenImpCasts();
51
52 // If types don't match, we suggest replacing with std::pair and explicit
53 // template arguments. Otherwise just remove the template arguments from
54 // make_pair.
55 if (Arg0->getType() != Call->getArg(0)->getType() ||
56 Arg1->getType() != Call->getArg(1)->getType()) {
57 diag(Call->getLocStart(), "for C++11-compatibility, use pair directly")
58 << FixItHint::CreateReplacement(
59 SourceRange(DeclRef->getLocStart(), DeclRef->getLAngleLoc()),
60 "std::pair<");
61 } else {
62 diag(Call->getLocStart(),
63 "for C++11-compatibility, omit template arguments from make_pair")
64 << FixItHint::CreateRemoval(
65 SourceRange(DeclRef->getLAngleLoc(), DeclRef->getRAngleLoc()));
66 }
67}
68
69} // namespace build
70} // namespace tidy
71} // namespace clang