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"
37static constexpr const char BoundCall[] =
"CallExpr";
38static constexpr const char FuncDecl[] =
"FuncDecl";
39static constexpr const char ArgName[] =
"ArgName";
44static std::string
getFullPrefix(ArrayRef<UseRangesCheck::Indexes> Signature) {
46 llvm::raw_string_ostream OS(Output);
48 OS << Item.BeginArg <<
":" << Item.EndArg <<
":"
55AST_MATCHER(Expr, hasSideEffects) {
56 return Node.HasSideEffects(Finder->getASTContext());
62 anyOf(hasParent(decompositionDecl()),
63 hasParent(exprWithCleanups(hasParent(decompositionDecl())))));
72 ArrayRef<StringRef> MethodNames,
73 ArrayRef<StringRef> FreeNames) {
75 anyOf(cxxMemberCallExpr(argumentCountIs(0),
76 callee(cxxMethodDecl(hasAnyName(MethodNames))),
78 callExpr(argumentCountIs(1), hasArgument(0, ArgumentMatcher),
79 hasDeclaration(functionDecl(hasAnyName(FreeNames))))));
82static ast_matchers::internal::Matcher<CallExpr>
84 ArrayRef<StringRef> BeginFreeNames,
85 ArrayRef<StringRef> EndFreeNames,
86 const std::optional<UseRangesCheck::ReverseIteratorDescriptor>
89 const SmallString<64> ID = {
BoundCall, State};
90 ast_matchers::internal::Matcher<CallExpr> ArgumentMatcher = allOf(
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');
101 llvm::make_first_range(ReverseDescriptor->FreeReverseNames)};
103 llvm::make_second_range(ReverseDescriptor->FreeReverseNames)};
104 ArgumentMatcher = anyOf(
109 {
"rbegin",
"crbegin"}, RBegin)),
113 expr(matchers::isStatementIdenticalToBoundNode(ArgBound)),
114 {
"rend",
"crend"}, REnd))));
116 return callExpr(argumentCountAtLeast(
127 llvm::make_first_range(BeginEndNames)};
129 llvm::make_second_range(BeginEndNames)};
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)
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)
143 Names.push_back(J->getKey());
145 std::vector<ast_matchers::internal::DynTypedMatcher> TotalMatchers;
151 llvm::sort(SigVec, [](
auto &L,
auto &R) {
return R.size() < L.size(); });
153 std::vector<ast_matchers::internal::DynTypedMatcher> Matchers;
156 BeginNames, EndNames,
158 TotalMatchers.push_back(
159 ast_matchers::internal::DynTypedMatcher::constructVariadic(
160 ast_matchers::internal::DynTypedMatcher::VO_AllOf,
161 ASTNodeKind::getFromNodeKind<CallExpr>(), std::move(Matchers)));
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>(),
178 const CallExpr &Call, ArrayRef<unsigned> Indexes,
179 const ASTContext &Ctx) {
183 llvm::SmallBitVector Commas(Call.getNumArgs());
186 for (
const unsigned Index : Sorted) {
187 const Expr *Arg = Call.getArg(Index);
189 if (Index >= Commas.size()) {
190 Diag << FixItHint::CreateRemoval(Arg->getSourceRange());
193 Commas[Index + 1] =
true;
194 Diag << FixItHint::CreateRemoval(CharSourceRange::getTokenRange(
196 Lexer::getLocForEndOfToken(
197 Arg->getEndLoc(), 0, Ctx.getSourceManager(), Ctx.getLangOpts())
198 .getLocWithOffset(1)}));
201 Diag << FixItHint::CreateRemoval(CharSourceRange::getTokenRange(
202 Arg->getBeginLoc().getLocWithOffset(-1), Arg->getEndLoc()));
203 Commas[Index] =
true;
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>())
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);
224 const ast_matchers::MatchFinder::MatchResult &Result) {
225 return isResultUsed(DynTypedNode::create(Call), Result);
229 bool ResultUsed,
bool IsStructuredBinding) {
235 case Kind::AppendAccessorForUsedResult:
237 case Kind::KeepFixItOnlyForStructuredBinding:
238 return IsStructuredBinding;
239 case Kind::SuppressFixItForUsedResult:
242 llvm_unreachable(
"Unhandled result use policy");
246 StringRef Accessor,
const ASTContext &Ctx) {
247 const SourceLocation End = Lexer::getLocForEndOfToken(
248 Call.getEndLoc(), 0, Ctx.getSourceManager(), Ctx.getLangOpts());
250 Diag << FixItHint::CreateInsertion(End, Accessor);
255 const FunctionDecl *Function =
nullptr;
256 for (
const auto &[Node, Value] : Result.Nodes.getMap()) {
257 StringRef NodeStr(Node);
258 if (!NodeStr.consume_front(
FuncDecl))
260 Function = Value.get<FunctionDecl>();
262 if (NodeStr.getAsInteger(10, Index))
263 llvm_unreachable(
"Unable to extract replacer index");
264 assert(Index < Replacers.size());
269 SmallString<64> Buffer;
272 const auto *Call = Result.Nodes.getNodeAs<CallExpr>(Buffer);
278 if (Function->getName() ==
"find") {
279 const unsigned ValueArgIndex = 2;
280 if (Call->getNumArgs() <= ValueArgIndex)
282 const Expr *ValueExpr =
283 Call->getArg(ValueArgIndex)->IgnoreParenImpCasts();
284 if (isa<CXXNullPtrLiteralExpr>(ValueExpr))
288 const bool IsStructuredBinding =
291 const auto ResultPolicy =
299 Diag << FixItHint::CreateReplacement(Call->getCallee()->getSourceRange(),
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 =
310 const bool NeedsDereference =
311 (ArgExpr->getType()->isPointerType() ||
312 ArgExpr->getType()->isArrayType()) &&
313 isa<CXXMemberCallExpr>(RangeArg->IgnoreParenImpCasts());
314 const std::string ReplaceText =
317 : tooling::fixit::getText(*ArgExpr, *Result.Context).str();
318 Diag << FixItHint::CreateReplacement(RangeArg->getSourceRange(),
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)
335 {ArgText,
" | ", ReverseDescriptor->ReverseAdaptorName});
338 {ReverseDescriptor->ReverseAdaptorName,
"(", ArgText,
")"});
339 Diag << FixItHint::CreateReplacement(
348 if (ResultUsed && ResultPolicy.PolicyKind ==
349 ResultPolicyKind::AppendAccessorForUsedResult) {
350 insertAccessor(Diag, *Call, ResultPolicy.Accessor, *Result.Context);
354 llvm_unreachable(
"No valid signature found");
358 const LangOptions &LangOpts)
const {
359 return LangOpts.CPlusPlus11;
364 Inserter(Options.getLocalOrGlobal(
"IncludeStyle",
366 areDiagsSelfContained()) {}
369 Preprocessor *PP, Preprocessor *) {
370 Inserter.registerPreprocessor(PP);
374 Options.store(Opts,
"IncludeStyle", Inserter.getStyle());
377std::optional<std::string>
388 return diag(Call.getBeginLoc(),
"use a ranges version of this algorithm");
391std::optional<UseRangesCheck::ReverseIteratorDescriptor>
396ArrayRef<std::pair<StringRef, StringRef>>
402 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
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[]