clang-tools 24.0.0git
utils/UseRangesCheck.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
9#include "UseRangesCheck.h"
10#include "FixItHintUtils.h"
11#include "Matchers.h"
12#include "clang/AST/ASTContext.h"
13#include "clang/AST/Decl.h"
14#include "clang/AST/Expr.h"
15#include "clang/ASTMatchers/ASTMatchFinder.h"
16#include "clang/ASTMatchers/ASTMatchers.h"
17#include "clang/ASTMatchers/ASTMatchersInternal.h"
18#include "clang/Basic/Diagnostic.h"
19#include "clang/Basic/LLVM.h"
20#include "clang/Basic/SourceLocation.h"
21#include "clang/Basic/SourceManager.h"
22#include "clang/Lex/Lexer.h"
23#include "clang/Tooling/FixIt.h"
24#include "llvm/ADT/ArrayRef.h"
25#include "llvm/ADT/STLExtras.h"
26#include "llvm/ADT/SmallBitVector.h"
27#include "llvm/ADT/SmallVector.h"
28#include "llvm/ADT/StringRef.h"
29#include "llvm/ADT/Twine.h"
30#include "llvm/Support/raw_ostream.h"
31#include <cassert>
32#include <optional>
33#include <string>
34
35using namespace clang::ast_matchers;
36
37static constexpr const char BoundCall[] = "CallExpr";
38static constexpr const char FuncDecl[] = "FuncDecl";
39static constexpr const char ArgName[] = "ArgName";
40static constexpr const char StructuredBindingResult[] = "StructuredBinding";
41
42namespace clang::tidy::utils {
43
44static std::string getFullPrefix(ArrayRef<UseRangesCheck::Indexes> Signature) {
45 std::string Output;
46 llvm::raw_string_ostream OS(Output);
47 for (const UseRangesCheck::Indexes &Item : Signature)
48 OS << Item.BeginArg << ":" << Item.EndArg << ":"
49 << (Item.ReplaceArg == UseRangesCheck::Indexes::First ? '0' : '1');
50 return Output;
51}
52
53namespace {
54
55AST_MATCHER(Expr, hasSideEffects) {
56 return Node.HasSideEffects(Finder->getASTContext());
57}
58} // namespace
59
61 return callExpr(
62 anyOf(hasParent(decompositionDecl()),
63 hasParent(exprWithCleanups(hasParent(decompositionDecl())))));
64}
65
66static auto hasStructuredBindingResult(StringRef ID) {
67 return hasStructuredBindingResult().bind(ID);
68}
69
70static auto
71makeExprMatcher(const ast_matchers::internal::Matcher<Expr> &ArgumentMatcher,
72 ArrayRef<StringRef> MethodNames,
73 ArrayRef<StringRef> FreeNames) {
74 return expr(
75 anyOf(cxxMemberCallExpr(argumentCountIs(0),
76 callee(cxxMethodDecl(hasAnyName(MethodNames))),
77 on(ArgumentMatcher)),
78 callExpr(argumentCountIs(1), hasArgument(0, ArgumentMatcher),
79 hasDeclaration(functionDecl(hasAnyName(FreeNames))))));
80}
81
82static ast_matchers::internal::Matcher<CallExpr>
83makeMatcherPair(StringRef State, const UseRangesCheck::Indexes &Indexes,
84 ArrayRef<StringRef> BeginFreeNames,
85 ArrayRef<StringRef> EndFreeNames,
86 const std::optional<UseRangesCheck::ReverseIteratorDescriptor>
87 &ReverseDescriptor) {
88 std::string ArgBound = (ArgName + llvm::Twine(Indexes.BeginArg)).str();
89 const SmallString<64> ID = {BoundCall, State};
90 ast_matchers::internal::Matcher<CallExpr> ArgumentMatcher = allOf(
91 hasArgument(Indexes.BeginArg,
92 makeExprMatcher(expr(unless(hasSideEffects())).bind(ArgBound),
93 {"begin", "cbegin"}, BeginFreeNames)),
94 hasArgument(Indexes.EndArg,
96 expr(matchers::isStatementIdenticalToBoundNode(ArgBound)),
97 {"end", "cend"}, EndFreeNames)));
98 if (ReverseDescriptor) {
99 ArgBound.push_back('R');
100 const SmallVector<StringRef> RBegin{
101 llvm::make_first_range(ReverseDescriptor->FreeReverseNames)};
102 const SmallVector<StringRef> REnd{
103 llvm::make_second_range(ReverseDescriptor->FreeReverseNames)};
104 ArgumentMatcher = anyOf(
105 ArgumentMatcher,
106 allOf(hasArgument(
107 Indexes.BeginArg,
108 makeExprMatcher(expr(unless(hasSideEffects())).bind(ArgBound),
109 {"rbegin", "crbegin"}, RBegin)),
110 hasArgument(
111 Indexes.EndArg,
113 expr(matchers::isStatementIdenticalToBoundNode(ArgBound)),
114 {"rend", "crend"}, REnd))));
115 }
116 return callExpr(argumentCountAtLeast(
117 std::max(Indexes.BeginArg, Indexes.EndArg) + 1),
118 ArgumentMatcher)
119 .bind(ID);
120}
121
122void UseRangesCheck::registerMatchers(MatchFinder *Finder) {
123 auto Replaces = getReplacerMap();
124 ReverseDescriptor = getReverseDescriptor();
125 auto BeginEndNames = getFreeBeginEndMethods();
126 const SmallVector<StringRef, 4> BeginNames{
127 llvm::make_first_range(BeginEndNames)};
128 const SmallVector<StringRef, 4> EndNames{
129 llvm::make_second_range(BeginEndNames)};
130 Replacers.clear();
131 llvm::DenseSet<Replacer *> SeenRepl;
132 for (auto I = Replaces.begin(), E = Replaces.end(); I != E; ++I) {
133 const auto Replacer = I->getValue();
134 if (!SeenRepl.insert(Replacer.get()).second)
135 continue;
136 Replacers.push_back(Replacer);
137 assert(!Replacer->getReplacementSignatures().empty() &&
138 llvm::all_of(Replacer->getReplacementSignatures(),
139 [](const Signature &Index) { return !Index.empty(); }));
140 std::vector<StringRef> Names(1, I->getKey());
141 for (auto J = std::next(I); J != E; ++J)
142 if (J->getValue() == Replacer)
143 Names.push_back(J->getKey());
144
145 std::vector<ast_matchers::internal::DynTypedMatcher> TotalMatchers;
146 // As we match on the first matched signature, we need to sort the
147 // signatures in order of length(longest to shortest). This way any
148 // signature that is a subset of another signature will be matched after the
149 // other.
151 llvm::sort(SigVec, [](auto &L, auto &R) { return R.size() < L.size(); });
152 for (const auto &Signature : SigVec) {
153 std::vector<ast_matchers::internal::DynTypedMatcher> Matchers;
154 for (const auto &ArgPair : Signature)
155 Matchers.push_back(makeMatcherPair(getFullPrefix(Signature), ArgPair,
156 BeginNames, EndNames,
157 ReverseDescriptor));
158 TotalMatchers.push_back(
159 ast_matchers::internal::DynTypedMatcher::constructVariadic(
160 ast_matchers::internal::DynTypedMatcher::VO_AllOf,
161 ASTNodeKind::getFromNodeKind<CallExpr>(), std::move(Matchers)));
162 }
163 Finder->addMatcher(
164 callExpr(
165 callee(functionDecl(hasAnyName(Names))
166 .bind((FuncDecl + Twine(Replacers.size() - 1).str()))),
167 ast_matchers::internal::DynTypedMatcher::constructVariadic(
168 ast_matchers::internal::DynTypedMatcher::VO_AnyOf,
169 ASTNodeKind::getFromNodeKind<CallExpr>(),
170 std::move(TotalMatchers))
171 .convertTo<CallExpr>(),
173 this);
174 }
175}
176
177static void removeFunctionArgs(const DiagnosticBuilder &Diag,
178 const CallExpr &Call, ArrayRef<unsigned> Indexes,
179 const ASTContext &Ctx) {
180 SmallVector<unsigned> Sorted(Indexes);
181 llvm::sort(Sorted);
182 // Keep track of commas removed
183 llvm::SmallBitVector Commas(Call.getNumArgs());
184 // The first comma is actually the '(' which we can't remove
185 Commas[0] = true;
186 for (const unsigned Index : Sorted) {
187 const Expr *Arg = Call.getArg(Index);
188 if (Commas[Index]) {
189 if (Index >= Commas.size()) {
190 Diag << FixItHint::CreateRemoval(Arg->getSourceRange());
191 } else {
192 // Remove the next comma
193 Commas[Index + 1] = true;
194 Diag << FixItHint::CreateRemoval(CharSourceRange::getTokenRange(
195 {Arg->getBeginLoc(),
196 Lexer::getLocForEndOfToken(
197 Arg->getEndLoc(), 0, Ctx.getSourceManager(), Ctx.getLangOpts())
198 .getLocWithOffset(1)}));
199 }
200 } else {
201 Diag << FixItHint::CreateRemoval(CharSourceRange::getTokenRange(
202 Arg->getBeginLoc().getLocWithOffset(-1), Arg->getEndLoc()));
203 Commas[Index] = true;
204 }
205 }
206}
207
208static bool isResultUsed(const DynTypedNode &Node,
209 const ast_matchers::MatchFinder::MatchResult &Result) {
210 const DynTypedNodeList Parents = Result.Context->getParents(Node);
211 assert(Parents.size() == 1 &&
212 "Expected exactly one parent for a matched algorithm call");
213 const DynTypedNode &Parent = Parents[0];
214 if (Parent.get<CompoundStmt>())
215 return false;
216 if (const auto *Cleanups = Parent.get<ExprWithCleanups>())
217 return isResultUsed(DynTypedNode::create(*Cleanups), Result);
218 if (const auto *Temporary = Parent.get<CXXBindTemporaryExpr>())
219 return isResultUsed(DynTypedNode::create(*Temporary), Result);
220 return true;
221}
222
223static bool isResultUsed(const CallExpr &Call,
224 const ast_matchers::MatchFinder::MatchResult &Result) {
225 return isResultUsed(DynTypedNode::create(Call), Result);
226}
227
229 bool ResultUsed, bool IsStructuredBinding) {
231 if (!ResultUsed)
232 return true;
233 switch (Policy.PolicyKind) {
234 case Kind::Preserve:
235 case Kind::AppendAccessorForUsedResult:
236 return true;
237 case Kind::KeepFixItOnlyForStructuredBinding:
238 return IsStructuredBinding;
239 case Kind::SuppressFixItForUsedResult:
240 return false;
241 }
242 llvm_unreachable("Unhandled result use policy");
243}
244
245static void insertAccessor(const DiagnosticBuilder &Diag, const CallExpr &Call,
246 StringRef Accessor, const ASTContext &Ctx) {
247 const SourceLocation End = Lexer::getLocForEndOfToken(
248 Call.getEndLoc(), 0, Ctx.getSourceManager(), Ctx.getLangOpts());
249 if (End.isValid())
250 Diag << FixItHint::CreateInsertion(End, Accessor);
251}
252
253void UseRangesCheck::check(const MatchFinder::MatchResult &Result) {
254 const Replacer *Replacer = nullptr;
255 const FunctionDecl *Function = nullptr;
256 for (const auto &[Node, Value] : Result.Nodes.getMap()) {
257 StringRef NodeStr(Node);
258 if (!NodeStr.consume_front(FuncDecl))
259 continue;
260 Function = Value.get<FunctionDecl>();
261 size_t Index = 0;
262 if (NodeStr.getAsInteger(10, Index))
263 llvm_unreachable("Unable to extract replacer index");
264 assert(Index < Replacers.size());
265 Replacer = Replacers[Index].get();
266 break;
267 }
268 assert(Replacer && Function);
269 SmallString<64> Buffer;
270 for (const Signature &Sig : Replacer->getReplacementSignatures()) {
271 Buffer.assign({BoundCall, getFullPrefix(Sig)});
272 const auto *Call = Result.Nodes.getNodeAs<CallExpr>(Buffer);
273 if (!Call)
274 continue;
275
276 // FIXME: This check specifically handles `CXXNullPtrLiteralExpr`, but
277 // a more general solution might be needed.
278 if (Function->getName() == "find") {
279 const unsigned ValueArgIndex = 2;
280 if (Call->getNumArgs() <= ValueArgIndex)
281 continue;
282 const Expr *ValueExpr =
283 Call->getArg(ValueArgIndex)->IgnoreParenImpCasts();
284 if (isa<CXXNullPtrLiteralExpr>(ValueExpr))
285 return;
286 }
287
288 const bool IsStructuredBinding =
289 Result.Nodes.getNodeAs<CallExpr>(StructuredBindingResult) != nullptr;
290 const bool ResultUsed = isResultUsed(*Call, Result);
291 const auto ResultPolicy =
292 Replacer->getResultUsePolicy(*Function, IsStructuredBinding);
293
294 const auto Diag = createDiag(*Call);
295 if (!shouldEmitFixIts(ResultPolicy, ResultUsed, IsStructuredBinding))
296 return;
297
298 if (auto ReplaceName = Replacer->getReplaceName(*Function))
299 Diag << FixItHint::CreateReplacement(Call->getCallee()->getSourceRange(),
300 *ReplaceName);
301 if (auto Include = Replacer->getHeaderInclusion(*Function))
302 Diag << Inserter.createIncludeInsertion(
303 Result.SourceManager->getFileID(Call->getBeginLoc()), *Include);
305 for (const auto &[First, Second, Replace] : Sig) {
306 auto ArgNode = ArgName + std::to_string(First);
307 if (const auto *ArgExpr = Result.Nodes.getNodeAs<Expr>(ArgNode)) {
308 const Expr *RangeArg =
309 Call->getArg(Replace == Indexes::Second ? Second : First);
310 const bool NeedsDereference =
311 (ArgExpr->getType()->isPointerType() ||
312 ArgExpr->getType()->isArrayType()) &&
313 isa<CXXMemberCallExpr>(RangeArg->IgnoreParenImpCasts());
314 const std::string ReplaceText =
315 NeedsDereference
316 ? fixit::formatDereference(*ArgExpr, *Result.Context)
317 : tooling::fixit::getText(*ArgExpr, *Result.Context).str();
318 Diag << FixItHint::CreateReplacement(RangeArg->getSourceRange(),
319 ReplaceText);
320 } else {
321 assert(ReverseDescriptor && "Couldn't find forward argument");
322 ArgNode.push_back('R');
323 ArgExpr = Result.Nodes.getNodeAs<Expr>(ArgNode);
324 assert(ArgExpr && "Couldn't find forward or reverse argument");
325 if (ReverseDescriptor->ReverseHeader)
326 Diag << Inserter.createIncludeInsertion(
327 Result.SourceManager->getFileID(Call->getBeginLoc()),
328 *ReverseDescriptor->ReverseHeader);
329 const StringRef ArgText = Lexer::getSourceText(
330 CharSourceRange::getTokenRange(ArgExpr->getSourceRange()),
331 Result.Context->getSourceManager(), Result.Context->getLangOpts());
332 SmallString<128> ReplaceText;
333 if (ReverseDescriptor->IsPipeSyntax)
334 ReplaceText.assign(
335 {ArgText, " | ", ReverseDescriptor->ReverseAdaptorName});
336 else
337 ReplaceText.assign(
338 {ReverseDescriptor->ReverseAdaptorName, "(", ArgText, ")"});
339 Diag << FixItHint::CreateReplacement(
340 Call->getArg(Replace == Indexes::Second ? Second : First)
341 ->getSourceRange(),
342 ReplaceText);
343 }
344 ToRemove.push_back(Replace == Indexes::Second ? First : Second);
345 }
346 removeFunctionArgs(Diag, *Call, ToRemove, *Result.Context);
347 using ResultPolicyKind = Replacer::ResultUsePolicy::Kind;
348 if (ResultUsed && ResultPolicy.PolicyKind ==
349 ResultPolicyKind::AppendAccessorForUsedResult) {
350 insertAccessor(Diag, *Call, ResultPolicy.Accessor, *Result.Context);
351 }
352 return;
353 }
354 llvm_unreachable("No valid signature found");
355}
356
358 const LangOptions &LangOpts) const {
359 return LangOpts.CPlusPlus11;
360}
361
363 : ClangTidyCheck(Name, Context),
364 Inserter(Options.getLocalOrGlobal("IncludeStyle",
365 utils::IncludeSorter::IS_LLVM),
366 areDiagsSelfContained()) {}
367
368void UseRangesCheck::registerPPCallbacks(const SourceManager &,
369 Preprocessor *PP, Preprocessor *) {
370 Inserter.registerPreprocessor(PP);
371}
372
374 Options.store(Opts, "IncludeStyle", Inserter.getStyle());
375}
376
377std::optional<std::string>
379 return std::nullopt;
380}
381
383UseRangesCheck::Replacer::getResultUsePolicy(const NamedDecl &, bool) const {
384 return {};
385}
386
387DiagnosticBuilder UseRangesCheck::createDiag(const CallExpr &Call) {
388 return diag(Call.getBeginLoc(), "use a ranges version of this algorithm");
389}
390
391std::optional<UseRangesCheck::ReverseIteratorDescriptor>
393 return std::nullopt;
394}
395
396ArrayRef<std::pair<StringRef, StringRef>>
398 return {};
399}
400
401std::optional<TraversalKind> UseRangesCheck::getCheckTraversalKind() const {
402 return TK_IgnoreUnlessSpelledInSource;
403}
404} // namespace clang::tidy::utils
Every ClangTidyCheck reports errors through a DiagnosticsEngine provided by this context.
virtual ArrayRef< Signature > getReplacementSignatures() const =0
Gets an array of all the possible overloads for a function with indexes where begin and end arguments...
virtual ResultUsePolicy getResultUsePolicy(const NamedDecl &OriginalName, bool IsStructuredBinding) const
Gets how to handle fix-its when the original algorithm result is used.
virtual std::optional< std::string > getHeaderInclusion(const NamedDecl &OriginalName) const
Gets the header needed to access the replaced function Return std::nullopt if no new header is needed...
virtual std::optional< std::string > getReplaceName(const NamedDecl &OriginalName) const =0
Gets the name to replace a function with, return std::nullopt for a replacement where we just call a ...
void storeOptions(ClangTidyOptions::OptionMap &Opts) override
virtual DiagnosticBuilder createDiag(const CallExpr &Call)
Create a diagnostic for the CallExpr Override this to support custom diagnostic messages.
void registerMatchers(ast_matchers::MatchFinder *Finder) final
std::optional< TraversalKind > getCheckTraversalKind() const override
void check(const ast_matchers::MatchFinder::MatchResult &Result) final
void registerPPCallbacks(const SourceManager &SM, Preprocessor *PP, Preprocessor *ModuleExpanderPP) final
virtual ReplacerMap getReplacerMap() const =0
Gets a map of function to replace and methods to create the replacements.
bool isLanguageVersionSupported(const LangOptions &LangOpts) const override
UseRangesCheck(StringRef Name, ClangTidyContext *Context)
virtual std::optional< ReverseIteratorDescriptor > getReverseDescriptor() const
virtual ArrayRef< std::pair< StringRef, StringRef > > getFreeBeginEndMethods() const
Gets the fully qualified names of begin and end functions.
std::string formatDereference(const Expr &ExprNode, const ASTContext &Context)
static std::string getFullPrefix(ArrayRef< UseRangesCheck::Indexes > Signature)
static ast_matchers::internal::Matcher< CallExpr > makeMatcherPair(StringRef State, const UseRangesCheck::Indexes &Indexes, ArrayRef< StringRef > BeginFreeNames, ArrayRef< StringRef > EndFreeNames, const std::optional< UseRangesCheck::ReverseIteratorDescriptor > &ReverseDescriptor)
static auto hasStructuredBindingResult()
static bool shouldEmitFixIts(UseRangesCheck::Replacer::ResultUsePolicy Policy, bool ResultUsed, bool IsStructuredBinding)
static bool isResultUsed(const DynTypedNode &Node, const ast_matchers::MatchFinder::MatchResult &Result)
IncludeSorter(const SourceManager *SourceMgr, FileID FileID, StringRef FileName, IncludeStyle Style)
Class used by IncludeInserterCallback to record the names of the / inclusions in a given source file ...
static void insertAccessor(const DiagnosticBuilder &Diag, const CallExpr &Call, StringRef Accessor, const ASTContext &Ctx)
static auto makeExprMatcher(const ast_matchers::internal::Matcher< Expr > &ArgumentMatcher, ArrayRef< StringRef > MethodNames, ArrayRef< StringRef > FreeNames)
static void removeFunctionArgs(const DiagnosticBuilder &Diag, const CallExpr &Call, ArrayRef< unsigned > Indexes, const ASTContext &Ctx)
llvm::StringMap< ClangTidyValue > OptionMap
static constexpr const char ArgName[]
static constexpr const char BoundCall[]
static constexpr const char StructuredBindingResult[]
static constexpr const char FuncDecl[]