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"
35static constexpr const char BoundCall[] =
"CallExpr";
36static constexpr const char FuncDecl[] =
"FuncDecl";
37static constexpr const char ArgName[] =
"ArgName";
42static std::string
getFullPrefix(ArrayRef<UseRangesCheck::Indexes> Signature) {
44 llvm::raw_string_ostream OS(Output);
46 OS << Item.BeginArg <<
":" << Item.EndArg <<
":"
53AST_MATCHER(Expr, hasSideEffects) {
54 return Node.HasSideEffects(Finder->getASTContext());
60 anyOf(hasParent(decompositionDecl()),
61 hasParent(exprWithCleanups(hasParent(decompositionDecl())))));
70 ArrayRef<StringRef> MethodNames,
71 ArrayRef<StringRef> FreeNames) {
73 anyOf(cxxMemberCallExpr(argumentCountIs(0),
74 callee(cxxMethodDecl(hasAnyName(MethodNames))),
76 callExpr(argumentCountIs(1), hasArgument(0, ArgumentMatcher),
77 hasDeclaration(functionDecl(hasAnyName(FreeNames))))));
80static ast_matchers::internal::Matcher<CallExpr>
82 ArrayRef<StringRef> BeginFreeNames,
83 ArrayRef<StringRef> EndFreeNames,
84 const std::optional<UseRangesCheck::ReverseIteratorDescriptor>
87 const SmallString<64> ID = {
BoundCall, State};
88 ast_matchers::internal::Matcher<CallExpr> ArgumentMatcher = allOf(
91 {
"begin",
"cbegin"}, BeginFreeNames)),
92 hasArgument(Indexes.
EndArg,
94 expr(matchers::isStatementIdenticalToBoundNode(ArgBound)),
95 {
"end",
"cend"}, EndFreeNames)));
96 if (ReverseDescriptor) {
97 ArgBound.push_back(
'R');
99 llvm::make_first_range(ReverseDescriptor->FreeReverseNames)};
101 llvm::make_second_range(ReverseDescriptor->FreeReverseNames)};
102 ArgumentMatcher = anyOf(
107 {
"rbegin",
"crbegin"}, RBegin)),
111 expr(matchers::isStatementIdenticalToBoundNode(ArgBound)),
112 {
"rend",
"crend"}, REnd))));
114 return callExpr(argumentCountAtLeast(
125 llvm::make_first_range(BeginEndNames)};
127 llvm::make_second_range(BeginEndNames)};
129 llvm::DenseSet<Replacer *> SeenRepl;
130 for (
auto I = Replaces.begin(), E = Replaces.end(); I != E; ++I) {
131 const auto Replacer = I->getValue();
132 if (!SeenRepl.insert(
Replacer.get()).second)
137 [](
const Signature &Index) { return !Index.empty(); }));
138 std::vector<StringRef> Names(1, I->getKey());
139 for (
auto J = std::next(I); J != E; ++J)
141 Names.push_back(J->getKey());
143 std::vector<ast_matchers::internal::DynTypedMatcher> TotalMatchers;
149 llvm::sort(SigVec, [](
auto &L,
auto &R) {
return R.size() < L.size(); });
151 std::vector<ast_matchers::internal::DynTypedMatcher> Matchers;
154 BeginNames, EndNames,
156 TotalMatchers.push_back(
157 ast_matchers::internal::DynTypedMatcher::constructVariadic(
158 ast_matchers::internal::DynTypedMatcher::VO_AllOf,
159 ASTNodeKind::getFromNodeKind<CallExpr>(), std::move(Matchers)));
163 callee(functionDecl(hasAnyName(Names))
164 .bind((
FuncDecl + Twine(Replacers.size() - 1).str()))),
165 ast_matchers::internal::DynTypedMatcher::constructVariadic(
166 ast_matchers::internal::DynTypedMatcher::VO_AnyOf,
167 ASTNodeKind::getFromNodeKind<CallExpr>(),
168 std::move(TotalMatchers))
169 .convertTo<CallExpr>(),
176 const CallExpr &Call, ArrayRef<unsigned> Indexes,
177 const ASTContext &Ctx) {
181 llvm::SmallBitVector Commas(Call.getNumArgs());
184 for (
const unsigned Index : Sorted) {
185 const Expr *Arg = Call.getArg(Index);
187 if (Index >= Commas.size()) {
188 Diag << FixItHint::CreateRemoval(Arg->getSourceRange());
191 Commas[Index + 1] =
true;
192 Diag << FixItHint::CreateRemoval(CharSourceRange::getTokenRange(
194 Lexer::getLocForEndOfToken(
195 Arg->getEndLoc(), 0, Ctx.getSourceManager(), Ctx.getLangOpts())
196 .getLocWithOffset(1)}));
199 Diag << FixItHint::CreateRemoval(CharSourceRange::getTokenRange(
200 Arg->getBeginLoc().getLocWithOffset(-1), Arg->getEndLoc()));
201 Commas[Index] =
true;
207 const ast_matchers::MatchFinder::MatchResult &Result) {
208 const DynTypedNodeList Parents = Result.Context->getParents(Node);
209 assert(Parents.size() == 1 &&
210 "Expected exactly one parent for a matched algorithm call");
211 const DynTypedNode &Parent = Parents[0];
212 if (Parent.get<CompoundStmt>())
214 if (
const auto *Cleanups = Parent.get<ExprWithCleanups>())
215 return isResultUsed(DynTypedNode::create(*Cleanups), Result);
216 if (
const auto *Temporary = Parent.get<CXXBindTemporaryExpr>())
217 return isResultUsed(DynTypedNode::create(*Temporary), Result);
222 const ast_matchers::MatchFinder::MatchResult &Result) {
223 return isResultUsed(DynTypedNode::create(Call), Result);
227 bool ResultUsed,
bool IsStructuredBinding) {
233 case Kind::AppendAccessorForUsedResult:
235 case Kind::KeepFixItOnlyForStructuredBinding:
236 return IsStructuredBinding;
237 case Kind::SuppressFixItForUsedResult:
240 llvm_unreachable(
"Unhandled result use policy");
244 StringRef Accessor,
const ASTContext &Ctx) {
245 const SourceLocation End = Lexer::getLocForEndOfToken(
246 Call.getEndLoc(), 0, Ctx.getSourceManager(), Ctx.getLangOpts());
248 Diag << FixItHint::CreateInsertion(End, Accessor);
253 const FunctionDecl *Function =
nullptr;
254 for (
const auto &[Node, Value] : Result.Nodes.getMap()) {
255 StringRef NodeStr(Node);
256 if (!NodeStr.consume_front(
FuncDecl))
258 Function = Value.get<FunctionDecl>();
260 if (NodeStr.getAsInteger(10, Index))
261 llvm_unreachable(
"Unable to extract replacer index");
262 assert(Index < Replacers.size());
267 SmallString<64> Buffer;
270 const auto *Call = Result.Nodes.getNodeAs<CallExpr>(Buffer);
276 if (Function->getName() ==
"find") {
277 const unsigned ValueArgIndex = 2;
278 if (Call->getNumArgs() <= ValueArgIndex)
280 const Expr *ValueExpr =
281 Call->getArg(ValueArgIndex)->IgnoreParenImpCasts();
282 if (isa<CXXNullPtrLiteralExpr>(ValueExpr))
286 const bool IsStructuredBinding =
289 const auto ResultPolicy =
297 Diag << FixItHint::CreateReplacement(Call->getCallee()->getSourceRange(),
300 Diag << Inserter.createIncludeInsertion(
301 Result.SourceManager->getFileID(Call->getBeginLoc()), *Include);
303 for (
const auto &[First, Second, Replace] : Sig) {
304 auto ArgNode =
ArgName + std::to_string(First);
305 if (
const auto *ArgExpr = Result.Nodes.getNodeAs<Expr>(ArgNode)) {
306 Diag << FixItHint::CreateReplacement(
309 Lexer::getSourceText(
310 CharSourceRange::getTokenRange(ArgExpr->getSourceRange()),
311 Result.Context->getSourceManager(),
312 Result.Context->getLangOpts()));
314 assert(ReverseDescriptor &&
"Couldn't find forward argument");
315 ArgNode.push_back(
'R');
316 ArgExpr = Result.Nodes.getNodeAs<Expr>(ArgNode);
317 assert(ArgExpr &&
"Couldn't find forward or reverse argument");
318 if (ReverseDescriptor->ReverseHeader)
319 Diag << Inserter.createIncludeInsertion(
320 Result.SourceManager->getFileID(Call->getBeginLoc()),
321 *ReverseDescriptor->ReverseHeader);
322 const StringRef ArgText = Lexer::getSourceText(
323 CharSourceRange::getTokenRange(ArgExpr->getSourceRange()),
324 Result.Context->getSourceManager(), Result.Context->getLangOpts());
325 SmallString<128> ReplaceText;
326 if (ReverseDescriptor->IsPipeSyntax)
328 {ArgText,
" | ", ReverseDescriptor->ReverseAdaptorName});
331 {ReverseDescriptor->ReverseAdaptorName,
"(", ArgText,
")"});
332 Diag << FixItHint::CreateReplacement(
341 if (ResultUsed && ResultPolicy.PolicyKind ==
342 ResultPolicyKind::AppendAccessorForUsedResult) {
343 insertAccessor(Diag, *Call, ResultPolicy.Accessor, *Result.Context);
347 llvm_unreachable(
"No valid signature found");
351 const LangOptions &LangOpts)
const {
352 return LangOpts.CPlusPlus11;
357 Inserter(Options.getLocalOrGlobal(
"IncludeStyle",
359 areDiagsSelfContained()) {}
362 Preprocessor *PP, Preprocessor *) {
363 Inserter.registerPreprocessor(PP);
367 Options.store(Opts,
"IncludeStyle", Inserter.getStyle());
370std::optional<std::string>
381 return diag(Call.getBeginLoc(),
"use a ranges version of this algorithm");
384std::optional<UseRangesCheck::ReverseIteratorDescriptor>
389ArrayRef<std::pair<StringRef, StringRef>>
395 return TK_IgnoreUnlessSpelledInSource;
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.
SmallVector< Indexes, 2 > Signature
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[]