clang-tools 23.0.0git
MissingStdForwardCheck.cpp
Go to the documentation of this file.
1//===----------------------------------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
10#include "../utils/Matchers.h"
11#include "clang/AST/ASTContext.h"
12#include "clang/ASTMatchers/ASTMatchFinder.h"
13#include "clang/Basic/IdentifierTable.h"
14
15using namespace clang::ast_matchers;
16
18
19namespace {
20
21using matchers::hasUnevaluatedContext;
22
23AST_MATCHER_P(QualType, possiblyPackExpansionOf,
24 ast_matchers::internal::Matcher<QualType>, InnerMatcher) {
25 return InnerMatcher.matches(Node.getNonPackExpansionType(), Finder, Builder);
26}
27
28AST_MATCHER(ParmVarDecl, isTemplateTypeParameter) {
29 const ast_matchers::internal::Matcher<QualType> Inner =
30 possiblyPackExpansionOf(
31 qualType(rValueReferenceType(),
32 references(templateTypeParmType(
33 hasDeclaration(templateTypeParmDecl()))),
34 unless(references(qualType(isConstQualified())))));
35 if (!Inner.matches(Node.getType(), Finder, Builder))
36 return false;
37
38 const auto *Function = dyn_cast<FunctionDecl>(Node.getDeclContext());
39 if (!Function)
40 return false;
41
42 const FunctionTemplateDecl *FuncTemplate =
43 Function->getDescribedFunctionTemplate();
44 if (!FuncTemplate)
45 return false;
46
47 const QualType ParamType =
48 Node.getType().getNonPackExpansionType()->getPointeeType();
49
50 // Explicit object parameters with a type constraint are still forwarding
51 // references per [temp.deduct.call]. We conservatively suppress warnings
52 // here to avoid false positives when constraints restrict the deduced type,
53 // accepting false negatives as a trade-off.
54 if (Node.isExplicitObjectParameter())
55 if (const auto *TTPT = ParamType->getAs<TemplateTypeParmType>())
56 if (const auto *Decl = TTPT->getDecl(); Decl && Decl->hasTypeConstraint())
57 return false;
58
59 const auto *TemplateType = ParamType->getAsCanonical<TemplateTypeParmType>();
60 if (!TemplateType)
61 return false;
62
63 return TemplateType->getDepth() ==
64 FuncTemplate->getTemplateParameters()->getDepth();
65}
66
67AST_MATCHER_P(NamedDecl, hasSameNameAsBoundNode, std::string, BindingID) {
68 const IdentifierInfo *II = Node.getIdentifier();
69 if (nullptr == II)
70 return false;
71 const StringRef Name = II->getName();
72
73 return Builder->removeBindings(
74 [this, Name](const ast_matchers::internal::BoundNodesMap &Nodes) {
75 const DynTypedNode &BN = Nodes.getNode(this->BindingID);
76 if (const auto *ND = BN.get<NamedDecl>()) {
77 if (!isa<FieldDecl, CXXMethodDecl, VarDecl>(ND))
78 return true;
79 return ND->getName() != Name;
80 }
81 return true;
82 });
83}
84
85AST_MATCHER_P(LambdaCapture, hasCaptureKind, LambdaCaptureKind, Kind) {
86 return Node.getCaptureKind() == Kind;
87}
88
89AST_MATCHER_P(LambdaExpr, hasCaptureDefaultKind, LambdaCaptureDefault, Kind) {
90 return Node.getCaptureDefault() == Kind;
91}
92
93AST_MATCHER(VarDecl, hasIdentifier) {
94 const IdentifierInfo *ID = Node.getIdentifier();
95 return ID != nullptr && !ID->isPlaceholder();
96}
97
98} // namespace
99
101 auto RefToParmImplicit = allOf(
102 equalsBoundNode("var"), hasInitializer(ignoringParenImpCasts(
103 declRefExpr(to(equalsBoundNode("param"))))));
104 auto RefToParm = capturesVar(
105 varDecl(anyOf(hasSameNameAsBoundNode("param"), RefToParmImplicit)));
106
107 auto CaptureInRef =
108 allOf(hasCaptureDefaultKind(LambdaCaptureDefault::LCD_ByRef),
109 unless(hasAnyCapture(
110 capturesVar(varDecl(hasSameNameAsBoundNode("param"))))));
111 auto CaptureByRefExplicit = hasAnyCapture(
112 allOf(hasCaptureKind(LambdaCaptureKind::LCK_ByRef), RefToParm));
113
114 auto CapturedInBody = lambdaExpr(anyOf(CaptureInRef, CaptureByRefExplicit));
115 auto CapturedInCaptureList = hasAnyCapture(capturesVar(
116 varDecl(hasInitializer(ignoringParenImpCasts(equalsBoundNode("call"))))));
117
118 auto CapturedInLambda = hasDeclContext(cxxRecordDecl(
119 isLambda(),
120 hasParent(lambdaExpr(forCallable(equalsBoundNode("func")),
121 anyOf(CapturedInCaptureList, CapturedInBody)))));
122
123 auto ToParam = hasAnyParameter(parmVarDecl(equalsBoundNode("param")));
124
125 auto ForwardCallMatcher = callExpr(
126 callExpr().bind("call"), argumentCountIs(1),
127 hasArgument(0, declRefExpr(to(varDecl().bind("var")))),
128 forCallable(
129 anyOf(allOf(equalsBoundNode("func"),
130 functionDecl(hasAnyParameter(parmVarDecl(allOf(
131 equalsBoundNode("param"), equalsBoundNode("var")))))),
132 CapturedInLambda)),
133 callee(unresolvedLookupExpr(hasAnyDeclaration(
134 namedDecl(hasUnderlyingDecl(hasName(ForwardFunction)))))),
135
136 unless(anyOf(hasAncestor(typeLoc()),
137 hasAncestor(expr(hasUnevaluatedContext())))));
138
139 Finder->addMatcher(
140 parmVarDecl(
141 parmVarDecl().bind("param"), hasIdentifier(),
142 unless(hasAttr(attr::Kind::Unused)), isTemplateTypeParameter(),
143 hasAncestor(functionDecl().bind("func")),
144 hasAncestor(functionDecl(
145 isDefinition(), equalsBoundNode("func"), ToParam,
146 unless(anyOf(isDeleted(), hasDescendant(ForwardCallMatcher)))))),
147 this);
148}
149
150void MissingStdForwardCheck::check(const MatchFinder::MatchResult &Result) {
151 const auto *Param = Result.Nodes.getNodeAs<ParmVarDecl>("param");
152
153 if (!Param)
154 return;
155
156 diag(Param->getLocation(),
157 "forwarding reference parameter %0 is never forwarded "
158 "inside the function body")
159 << Param;
160}
161
163 ClangTidyContext *Context)
164 : ClangTidyCheck(Name, Context),
165 ForwardFunction(Options.get("ForwardFunction", "::std::forward")) {}
166
168 Options.store(Opts, "ForwardFunction", ForwardFunction);
169}
170
171} // namespace clang::tidy::cppcoreguidelines
Every ClangTidyCheck reports errors through a DiagnosticsEngine provided by this context.
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
void registerMatchers(ast_matchers::MatchFinder *Finder) override
MissingStdForwardCheck(StringRef Name, ClangTidyContext *Context)
void storeOptions(ClangTidyOptions::OptionMap &Opts) override
AST_MATCHER_P(Stmt, isStatementIdenticalToBoundNode, std::string, ID)
AST_MATCHER(BinaryOperator, isRelationalOperator)
llvm::StringMap< ClangTidyValue > OptionMap