10 #include "clang/AST/ASTContext.h"
11 #include "clang/ASTMatchers/ASTMatchFinder.h"
19 UseTransparentFunctorsCheck::UseTransparentFunctorsCheck(
29 const auto TransparentFunctors =
30 classTemplateSpecializationDecl(
31 unless(hasAnyTemplateArgument(refersToType(voidType()))),
32 hasAnyName(
"::std::plus",
"::std::minus",
"::std::multiplies",
33 "::std::divides",
"::std::modulus",
"::std::negate",
34 "::std::equal_to",
"::std::not_equal_to",
"::std::greater",
35 "::std::less",
"::std::greater_equal",
"::std::less_equal",
36 "::std::logical_and",
"::std::logical_or",
37 "::std::logical_not",
"::std::bit_and",
"::std::bit_or",
38 "::std::bit_xor",
"::std::bit_not"))
39 .bind(
"FunctorClass");
44 unless(elaboratedType()),
45 hasDeclaration(classTemplateSpecializationDecl(
46 unless(hasAnyTemplateArgument(templateArgument(refersToType(
47 qualType(pointsTo(qualType(isAnyCharacter()))))))),
48 hasAnyTemplateArgument(
49 templateArgument(refersToType(qualType(hasDeclaration(
50 TransparentFunctors))))
52 .bind(
"FunctorParentLoc"),
60 Finder->addMatcher(cxxConstructExpr(hasDeclaration(cxxMethodDecl(
61 ofClass(TransparentFunctors))),
62 unless(isInTemplateInstantiation()))
67 static const StringRef
Message =
"prefer transparent functors '%0'";
71 while (Result.isNull() && !
Loc.isNull()) {
72 Result =
Loc.getAs<T>();
73 Loc =
Loc.getNextTypeLoc();
79 const MatchFinder::MatchResult &Result) {
80 const auto *FuncClass =
81 Result.Nodes.getNodeAs<ClassTemplateSpecializationDecl>(
"FunctorClass");
82 if (
const auto *FuncInst =
83 Result.Nodes.getNodeAs<CXXConstructExpr>(
"FuncInst")) {
85 << (FuncClass->getName() +
"<>").str();
89 const auto *Functor = Result.Nodes.getNodeAs<TemplateArgument>(
"Functor");
90 const auto FunctorParentLoc =
91 Result.Nodes.getNodeAs<TypeLoc>(
"FunctorParentLoc")
92 ->getAs<TemplateSpecializationTypeLoc>();
94 if (!FunctorParentLoc)
98 const auto *FunctorParentType =
99 FunctorParentLoc.getType()->castAs<TemplateSpecializationType>();
100 for (; ArgNum < FunctorParentType->getNumArgs(); ++ArgNum) {
101 const TemplateArgument &Arg = FunctorParentType->getArg(ArgNum);
104 QualType ParentArgType = Arg.getAsType();
105 if (ParentArgType->isRecordType() &&
106 ParentArgType->getAsCXXRecordDecl() ==
107 Functor->getAsType()->getAsCXXRecordDecl())
111 if (ArgNum == FunctorParentType->getNumArgs())
113 TemplateArgumentLoc FunctorLoc = FunctorParentLoc.getArgLoc(ArgNum);
114 auto FunctorTypeLoc = getInnerTypeLocAs<TemplateSpecializationTypeLoc>(
115 FunctorLoc.getTypeSourceInfo()->getTypeLoc());
116 if (FunctorTypeLoc.isNull())
119 SourceLocation ReportLoc = FunctorLoc.getLocation();
120 if (ReportLoc.isInvalid())
122 diag(ReportLoc,
Message) << (FuncClass->getName() +
"<>").str()
123 << FixItHint::CreateRemoval(
124 FunctorTypeLoc.getArgLoc(0).getSourceRange());