clang-tools 22.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 "Matchers.h"
11#include "clang/AST/ASTContext.h"
12#include "clang/AST/Decl.h"
13#include "clang/AST/Expr.h"
14#include "clang/ASTMatchers/ASTMatchFinder.h"
15#include "clang/ASTMatchers/ASTMatchers.h"
16#include "clang/ASTMatchers/ASTMatchersInternal.h"
17#include "clang/Basic/Diagnostic.h"
18#include "clang/Basic/LLVM.h"
19#include "clang/Basic/SourceLocation.h"
20#include "clang/Basic/SourceManager.h"
21#include "clang/Lex/Lexer.h"
22#include "llvm/ADT/ArrayRef.h"
23#include "llvm/ADT/STLExtras.h"
24#include "llvm/ADT/SmallBitVector.h"
25#include "llvm/ADT/SmallVector.h"
26#include "llvm/ADT/StringRef.h"
27#include "llvm/ADT/Twine.h"
28#include "llvm/Support/raw_ostream.h"
29#include <cassert>
30#include <optional>
31#include <string>
32
33using namespace clang::ast_matchers;
34
35static constexpr const char BoundCall[] = "CallExpr";
36static constexpr const char FuncDecl[] = "FuncDecl";
37static constexpr const char ArgName[] = "ArgName";
38
39namespace clang::tidy::utils {
40
41static std::string getFullPrefix(ArrayRef<UseRangesCheck::Indexes> Signature) {
42 std::string Output;
43 llvm::raw_string_ostream OS(Output);
44 for (const UseRangesCheck::Indexes &Item : Signature)
45 OS << Item.BeginArg << ":" << Item.EndArg << ":"
46 << (Item.ReplaceArg == UseRangesCheck::Indexes::First ? '0' : '1');
47 return Output;
48}
49
50namespace {
51
52AST_MATCHER(Expr, hasSideEffects) {
53 return Node.HasSideEffects(Finder->getASTContext());
54}
55} // namespace
56
57static auto
58makeExprMatcher(const ast_matchers::internal::Matcher<Expr> &ArgumentMatcher,
59 ArrayRef<StringRef> MethodNames,
60 ArrayRef<StringRef> FreeNames) {
61 return expr(
62 anyOf(cxxMemberCallExpr(argumentCountIs(0),
63 callee(cxxMethodDecl(hasAnyName(MethodNames))),
64 on(ArgumentMatcher)),
65 callExpr(argumentCountIs(1), hasArgument(0, ArgumentMatcher),
66 hasDeclaration(functionDecl(hasAnyName(FreeNames))))));
67}
68
69static ast_matchers::internal::Matcher<CallExpr>
70makeMatcherPair(StringRef State, const UseRangesCheck::Indexes &Indexes,
71 ArrayRef<StringRef> BeginFreeNames,
72 ArrayRef<StringRef> EndFreeNames,
73 const std::optional<UseRangesCheck::ReverseIteratorDescriptor>
74 &ReverseDescriptor) {
75 std::string ArgBound = (ArgName + llvm::Twine(Indexes.BeginArg)).str();
76 const SmallString<64> ID = {BoundCall, State};
77 ast_matchers::internal::Matcher<CallExpr> ArgumentMatcher = allOf(
78 hasArgument(Indexes.BeginArg,
79 makeExprMatcher(expr(unless(hasSideEffects())).bind(ArgBound),
80 {"begin", "cbegin"}, BeginFreeNames)),
81 hasArgument(Indexes.EndArg,
83 expr(matchers::isStatementIdenticalToBoundNode(ArgBound)),
84 {"end", "cend"}, EndFreeNames)));
85 if (ReverseDescriptor) {
86 ArgBound.push_back('R');
87 const SmallVector<StringRef> RBegin{
88 llvm::make_first_range(ReverseDescriptor->FreeReverseNames)};
89 const SmallVector<StringRef> REnd{
90 llvm::make_second_range(ReverseDescriptor->FreeReverseNames)};
91 ArgumentMatcher = anyOf(
92 ArgumentMatcher,
93 allOf(hasArgument(
94 Indexes.BeginArg,
95 makeExprMatcher(expr(unless(hasSideEffects())).bind(ArgBound),
96 {"rbegin", "crbegin"}, RBegin)),
97 hasArgument(
98 Indexes.EndArg,
100 expr(matchers::isStatementIdenticalToBoundNode(ArgBound)),
101 {"rend", "crend"}, REnd))));
102 }
103 return callExpr(argumentCountAtLeast(
104 std::max(Indexes.BeginArg, Indexes.EndArg) + 1),
105 ArgumentMatcher)
106 .bind(ID);
107}
108
109void UseRangesCheck::registerMatchers(MatchFinder *Finder) {
110 auto Replaces = getReplacerMap();
111 ReverseDescriptor = getReverseDescriptor();
112 auto BeginEndNames = getFreeBeginEndMethods();
113 const llvm::SmallVector<StringRef, 4> BeginNames{
114 llvm::make_first_range(BeginEndNames)};
115 const llvm::SmallVector<StringRef, 4> EndNames{
116 llvm::make_second_range(BeginEndNames)};
117 Replacers.clear();
118 llvm::DenseSet<Replacer *> SeenRepl;
119 for (auto I = Replaces.begin(), E = Replaces.end(); I != E; ++I) {
120 auto Replacer = I->getValue();
121 if (!SeenRepl.insert(Replacer.get()).second)
122 continue;
123 Replacers.push_back(Replacer);
124 assert(!Replacer->getReplacementSignatures().empty() &&
125 llvm::all_of(Replacer->getReplacementSignatures(),
126 [](auto Index) { return !Index.empty(); }));
127 std::vector<StringRef> Names(1, I->getKey());
128 for (auto J = std::next(I); J != E; ++J)
129 if (J->getValue() == Replacer)
130 Names.push_back(J->getKey());
131
132 std::vector<ast_matchers::internal::DynTypedMatcher> TotalMatchers;
133 // As we match on the first matched signature, we need to sort the
134 // signatures in order of length(longest to shortest). This way any
135 // signature that is a subset of another signature will be matched after the
136 // other.
137 SmallVector<Signature> SigVec(Replacer->getReplacementSignatures());
138 llvm::sort(SigVec, [](auto &L, auto &R) { return R.size() < L.size(); });
139 for (const auto &Signature : SigVec) {
140 std::vector<ast_matchers::internal::DynTypedMatcher> Matchers;
141 for (const auto &ArgPair : Signature)
142 Matchers.push_back(makeMatcherPair(getFullPrefix(Signature), ArgPair,
143 BeginNames, EndNames,
144 ReverseDescriptor));
145 TotalMatchers.push_back(
146 ast_matchers::internal::DynTypedMatcher::constructVariadic(
147 ast_matchers::internal::DynTypedMatcher::VO_AllOf,
148 ASTNodeKind::getFromNodeKind<CallExpr>(), std::move(Matchers)));
149 }
150 Finder->addMatcher(
151 callExpr(
152 callee(functionDecl(hasAnyName(Names))
153 .bind((FuncDecl + Twine(Replacers.size() - 1).str()))),
154 ast_matchers::internal::DynTypedMatcher::constructVariadic(
155 ast_matchers::internal::DynTypedMatcher::VO_AnyOf,
156 ASTNodeKind::getFromNodeKind<CallExpr>(),
157 std::move(TotalMatchers))
158 .convertTo<CallExpr>()),
159 this);
160 }
161}
162
163static void removeFunctionArgs(DiagnosticBuilder &Diag, const CallExpr &Call,
164 ArrayRef<unsigned> Indexes,
165 const ASTContext &Ctx) {
166 llvm::SmallVector<unsigned> Sorted(Indexes);
167 llvm::sort(Sorted);
168 // Keep track of commas removed
169 llvm::SmallBitVector Commas(Call.getNumArgs());
170 // The first comma is actually the '(' which we can't remove
171 Commas[0] = true;
172 for (const unsigned Index : Sorted) {
173 const Expr *Arg = Call.getArg(Index);
174 if (Commas[Index]) {
175 if (Index >= Commas.size()) {
176 Diag << FixItHint::CreateRemoval(Arg->getSourceRange());
177 } else {
178 // Remove the next comma
179 Commas[Index + 1] = true;
180 Diag << FixItHint::CreateRemoval(CharSourceRange::getTokenRange(
181 {Arg->getBeginLoc(),
182 Lexer::getLocForEndOfToken(
183 Arg->getEndLoc(), 0, Ctx.getSourceManager(), Ctx.getLangOpts())
184 .getLocWithOffset(1)}));
185 }
186 } else {
187 Diag << FixItHint::CreateRemoval(CharSourceRange::getTokenRange(
188 Arg->getBeginLoc().getLocWithOffset(-1), Arg->getEndLoc()));
189 Commas[Index] = true;
190 }
191 }
192}
193
194void UseRangesCheck::check(const MatchFinder::MatchResult &Result) {
195 const Replacer *Replacer = nullptr;
196 const FunctionDecl *Function = nullptr;
197 for (const auto &[Node, Value] : Result.Nodes.getMap()) {
198 StringRef NodeStr(Node);
199 if (!NodeStr.consume_front(FuncDecl))
200 continue;
201 Function = Value.get<FunctionDecl>();
202 size_t Index = 0;
203 if (NodeStr.getAsInteger(10, Index))
204 llvm_unreachable("Unable to extract replacer index");
205 assert(Index < Replacers.size());
206 Replacer = Replacers[Index].get();
207 break;
208 }
209 assert(Replacer && Function);
210 SmallString<64> Buffer;
211 for (const Signature &Sig : Replacer->getReplacementSignatures()) {
212 Buffer.assign({BoundCall, getFullPrefix(Sig)});
213 const auto *Call = Result.Nodes.getNodeAs<CallExpr>(Buffer);
214 if (!Call)
215 continue;
216
217 // FIXME: This check specifically handles `CXXNullPtrLiteralExpr`, but
218 // a more general solution might be needed.
219 if (Function->getName() == "find") {
220 const unsigned ValueArgIndex = 2;
221 if (Call->getNumArgs() <= ValueArgIndex)
222 continue;
223 const Expr *ValueExpr =
224 Call->getArg(ValueArgIndex)->IgnoreParenImpCasts();
225 if (isa<CXXNullPtrLiteralExpr>(ValueExpr))
226 return;
227 }
228
229 auto Diag = createDiag(*Call);
230 if (auto ReplaceName = Replacer->getReplaceName(*Function))
231 Diag << FixItHint::CreateReplacement(Call->getCallee()->getSourceRange(),
232 *ReplaceName);
233 if (auto Include = Replacer->getHeaderInclusion(*Function))
234 Diag << Inserter.createIncludeInsertion(
235 Result.SourceManager->getFileID(Call->getBeginLoc()), *Include);
236 llvm::SmallVector<unsigned, 3> ToRemove;
237 for (const auto &[First, Second, Replace] : Sig) {
238 auto ArgNode = ArgName + std::to_string(First);
239 if (const auto *ArgExpr = Result.Nodes.getNodeAs<Expr>(ArgNode)) {
240 Diag << FixItHint::CreateReplacement(
241 Call->getArg(Replace == Indexes::Second ? Second : First)
242 ->getSourceRange(),
243 Lexer::getSourceText(
244 CharSourceRange::getTokenRange(ArgExpr->getSourceRange()),
245 Result.Context->getSourceManager(),
246 Result.Context->getLangOpts()));
247 } else {
248 assert(ReverseDescriptor && "Couldn't find forward argument");
249 ArgNode.push_back('R');
250 ArgExpr = Result.Nodes.getNodeAs<Expr>(ArgNode);
251 assert(ArgExpr && "Couldn't find forward or reverse argument");
252 if (ReverseDescriptor->ReverseHeader)
253 Diag << Inserter.createIncludeInsertion(
254 Result.SourceManager->getFileID(Call->getBeginLoc()),
255 *ReverseDescriptor->ReverseHeader);
256 const StringRef ArgText = Lexer::getSourceText(
257 CharSourceRange::getTokenRange(ArgExpr->getSourceRange()),
258 Result.Context->getSourceManager(), Result.Context->getLangOpts());
259 SmallString<128> ReplaceText;
260 if (ReverseDescriptor->IsPipeSyntax)
261 ReplaceText.assign(
262 {ArgText, " | ", ReverseDescriptor->ReverseAdaptorName});
263 else
264 ReplaceText.assign(
265 {ReverseDescriptor->ReverseAdaptorName, "(", ArgText, ")"});
266 Diag << FixItHint::CreateReplacement(
267 Call->getArg(Replace == Indexes::Second ? Second : First)
268 ->getSourceRange(),
269 ReplaceText);
270 }
271 ToRemove.push_back(Replace == Indexes::Second ? First : Second);
272 }
273 removeFunctionArgs(Diag, *Call, ToRemove, *Result.Context);
274 return;
275 }
276 llvm_unreachable("No valid signature found");
277}
278
280 const LangOptions &LangOpts) const {
281 return LangOpts.CPlusPlus11;
282}
283
285 : ClangTidyCheck(Name, Context),
286 Inserter(Options.getLocalOrGlobal("IncludeStyle",
287 utils::IncludeSorter::IS_LLVM),
288 areDiagsSelfContained()) {}
289
290void UseRangesCheck::registerPPCallbacks(const SourceManager &,
291 Preprocessor *PP, Preprocessor *) {
292 Inserter.registerPreprocessor(PP);
293}
294
296 Options.store(Opts, "IncludeStyle", Inserter.getStyle());
297}
298
299std::optional<std::string>
301 return std::nullopt;
302}
303
304DiagnosticBuilder UseRangesCheck::createDiag(const CallExpr &Call) {
305 return diag(Call.getBeginLoc(), "use a ranges version of this algorithm");
306}
307
308std::optional<UseRangesCheck::ReverseIteratorDescriptor>
310 return std::nullopt;
311}
312
313ArrayRef<std::pair<StringRef, StringRef>>
315 return {};
316}
317
318std::optional<TraversalKind> UseRangesCheck::getCheckTraversalKind() const {
319 return TK_IgnoreUnlessSpelledInSource;
320}
321} // 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 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.
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 void removeFunctionArgs(DiagnosticBuilder &Diag, const CallExpr &Call, ArrayRef< unsigned > Indexes, const ASTContext &Ctx)
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 auto makeExprMatcher(const ast_matchers::internal::Matcher< Expr > &ArgumentMatcher, ArrayRef< StringRef > MethodNames, ArrayRef< StringRef > FreeNames)
llvm::StringMap< ClangTidyValue > OptionMap
static constexpr const char ArgName[]
static constexpr const char BoundCall[]
static constexpr const char FuncDecl[]