clang-tools 24.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(), references(templateTypeParmType()),
32 unless(references(qualType(isConstQualified())))));
33 if (!Inner.matches(Node.getType(), Finder, Builder))
34 return false;
35
36 const auto *Function = dyn_cast<FunctionDecl>(Node.getDeclContext());
37 if (!Function)
38 return false;
39
40 const FunctionTemplateDecl *FuncTemplate =
41 Function->getDescribedFunctionTemplate();
42 if (!FuncTemplate)
43 return false;
44
45 const QualType ParamType =
46 Node.getType().getNonPackExpansionType()->getPointeeType();
47
48 // Explicit object parameters with a type constraint are still forwarding
49 // references per [temp.deduct.call]. We conservatively suppress warnings
50 // here to avoid false positives when constraints restrict the deduced type,
51 // accepting false negatives as a trade-off.
52 if (Node.isExplicitObjectParameter())
53 if (const auto *TTPT = ParamType->getAs<TemplateTypeParmType>())
54 if (const auto *Decl = TTPT->getDecl(); Decl && Decl->hasTypeConstraint())
55 return false;
56
57 const auto *TemplateType = ParamType->getAsCanonical<TemplateTypeParmType>();
58 if (!TemplateType)
59 return false;
60
61 return TemplateType->getDepth() ==
62 FuncTemplate->getTemplateParameters()->getDepth();
63}
64
65AST_MATCHER_P(LambdaCapture, hasCaptureKind, LambdaCaptureKind, Kind) {
66 return Node.getCaptureKind() == Kind;
67}
68
69AST_MATCHER_P(LambdaExpr, hasCaptureDefaultKind, LambdaCaptureDefault, Kind) {
70 return Node.getCaptureDefault() == Kind;
71}
72
73AST_MATCHER(VarDecl, hasIdentifier) {
74 const IdentifierInfo *ID = Node.getIdentifier();
75 return ID != nullptr && !ID->isPlaceholder();
76}
77
78AST_MATCHER_P(ValueDecl, refersToBoundParm, std::string, ParamID) {
79 return Builder->removeBindings(
80 [&](const ast_matchers::internal::BoundNodesMap &Nodes) {
81 const auto *Param = Nodes.getNodeAs<ParmVarDecl>(ParamID);
82 if (!Param)
83 return true;
84
85 for (const ValueDecl *V = &Node; V;) {
86 if (V == Param)
87 return false;
88
89 const auto *VD = dyn_cast<VarDecl>(V);
90 const Expr *Init = (VD && VD->getType()->isReferenceType())
91 ? VD->getInit()
92 : nullptr;
93 const auto *DRE =
94 Init ? dyn_cast<DeclRefExpr>(Init->IgnoreParenImpCasts())
95 : nullptr;
96 V = DRE ? DRE->getDecl() : nullptr;
97 }
98 return true;
99 });
100}
101
102} // namespace
103
105 const auto CapturedVar = varDecl(refersToBoundParm("param"));
106
107 auto CaptureInRef =
108 allOf(hasCaptureDefaultKind(LambdaCaptureDefault::LCD_ByRef),
109 unless(hasAnyCapture(capturesVar(CapturedVar))));
110 auto CaptureByRefExplicit = hasAnyCapture(allOf(
111 hasCaptureKind(LambdaCaptureKind::LCK_ByRef), capturesVar(CapturedVar)));
112
113 auto CapturedInBody = lambdaExpr(anyOf(CaptureInRef, CaptureByRefExplicit));
114 auto IsBoundCall = ignoringParenImpCasts(equalsBoundNode("call"));
115 auto CapturedInCaptureList = hasAnyCapture(capturesVar(varDecl(
116 hasInitializer(anyOf(IsBoundCall, initListExpr(hasInit(0, IsBoundCall)),
117 parenListExpr(has(expr(IsBoundCall))))))));
118
119 auto CapturedInLambda = hasDeclContext(cxxRecordDecl(
120 isLambda(), hasParent(lambdaExpr(
121 anyOf(CapturedInCaptureList, CapturedInBody),
122 hasAncestor(functionDecl(equalsBoundNode("func")))))));
123
124 const auto ToParam = hasAnyParameter(parmVarDecl(equalsBoundNode("param")));
125
126 const auto ForwardCallMatcher =
127 callExpr(callExpr().bind("call"), argumentCountIs(1),
128 hasArgument(0, declRefExpr(to(CapturedVar)).bind("var")),
129 forCallable(anyOf(equalsBoundNode("func"), CapturedInLambda)),
130 callee(unresolvedLookupExpr(hasAnyDeclaration(
131 namedDecl(hasUnderlyingDecl(hasName(ForwardFunction)))))),
132
133 unless(anyOf(hasAncestor(typeLoc()),
134 hasAncestor(expr(hasUnevaluatedContext())))));
135
136 Finder->addMatcher(
137 parmVarDecl(
138 parmVarDecl().bind("param"), hasIdentifier(),
139 unless(hasAttr(attr::Kind::Unused)), isTemplateTypeParameter(),
140 hasAncestor(functionDecl().bind("func")),
141 hasAncestor(functionDecl(
142 isDefinition(), equalsBoundNode("func"), ToParam,
143 unless(anyOf(
144 isDeleted(),
145 traverse(TK_AsIs, hasDescendant(ForwardCallMatcher))))))),
146 this);
147}
148
149void MissingStdForwardCheck::check(const MatchFinder::MatchResult &Result) {
150 const auto *Param = Result.Nodes.getNodeAs<ParmVarDecl>("param");
151
152 if (!Param)
153 return;
154
155 diag(Param->getLocation(),
156 "forwarding reference parameter %0 is never forwarded "
157 "inside the function body")
158 << Param;
159}
160
162 ClangTidyContext *Context)
163 : ClangTidyCheck(Name, Context),
164 ForwardFunction(Options.get("ForwardFunction", "::std::forward")) {}
165
167 Options.store(Opts, "ForwardFunction", ForwardFunction);
168}
169
170} // 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