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/SmallString.h"
26#include "llvm/ADT/SmallVector.h"
27#include "llvm/ADT/StringRef.h"
28#include "llvm/ADT/Twine.h"
29#include "llvm/Support/raw_ostream.h"
36static constexpr const char BoundCall[] =
"CallExpr";
37static constexpr const char FuncDecl[] =
"FuncDecl";
38static constexpr const char ArgName[] =
"ArgName";
46 OS << Item.BeginArg <<
":" << Item.EndArg <<
":"
47 << (Item.ReplaceArg == Item.First ?
'0' :
'1');
54 return Node.HasSideEffects(Finder->getASTContext());
60 ArrayRef<StringRef> MethodNames,
61 ArrayRef<StringRef> FreeNames) {
63 anyOf(cxxMemberCallExpr(argumentCountIs(0),
64 callee(cxxMethodDecl(hasAnyName(MethodNames))),
66 callExpr(argumentCountIs(1), hasArgument(0, ArgumentMatcher),
67 hasDeclaration(functionDecl(hasAnyName(FreeNames))))));
70static ast_matchers::internal::Matcher<CallExpr>
72 ArrayRef<StringRef> BeginFreeNames,
73 ArrayRef<StringRef> EndFreeNames,
74 const std::optional<UseRangesCheck::ReverseIteratorDescriptor>
78 ast_matchers::internal::Matcher<CallExpr> ArgumentMatcher = allOf(
81 {
"begin",
"cbegin"}, BeginFreeNames)),
82 hasArgument(Indexes.
EndArg,
84 expr(matchers::isStatementIdenticalToBoundNode(ArgBound)),
85 {
"end",
"cend"}, EndFreeNames)));
86 if (ReverseDescriptor) {
87 ArgBound.push_back(
'R');
88 SmallVector<StringRef> RBegin{
89 llvm::make_first_range(ReverseDescriptor->FreeReverseNames)};
90 SmallVector<StringRef> REnd{
91 llvm::make_second_range(ReverseDescriptor->FreeReverseNames)};
92 ArgumentMatcher = anyOf(
97 {
"rbegin",
"crbegin"}, RBegin)),
101 expr(matchers::isStatementIdenticalToBoundNode(ArgBound)),
102 {
"rend",
"crend"}, REnd))));
104 return callExpr(argumentCountAtLeast(
114 llvm::SmallVector<StringRef, 4> BeginNames{
115 llvm::make_first_range(BeginEndNames)};
116 llvm::SmallVector<StringRef, 4> EndNames{
117 llvm::make_second_range(BeginEndNames)};
119 llvm::DenseSet<Replacer *> SeenRepl;
122 if (!SeenRepl.insert(
Replacer.get()).second)
127 [](
auto Index) { return !Index.empty(); }));
128 std::vector<StringRef> Names(1, I->getKey());
129 for (
auto J = std::next(I); J !=
E; ++J)
131 Names.push_back(J->getKey());
133 std::vector<ast_matchers::internal::DynTypedMatcher> TotalMatchers;
139 llvm::sort(SigVec, [](
auto &L,
auto &R) {
return R.size() < L.size(); });
141 std::vector<ast_matchers::internal::DynTypedMatcher> Matchers;
144 BeginNames, EndNames,
146 TotalMatchers.push_back(
147 ast_matchers::internal::DynTypedMatcher::constructVariadic(
148 ast_matchers::internal::DynTypedMatcher::VO_AllOf,
149 ASTNodeKind::getFromNodeKind<CallExpr>(), std::move(Matchers)));
153 callee(functionDecl(hasAnyName(std::move(Names)))
154 .bind((
FuncDecl + Twine(Replacers.size() - 1).str()))),
155 ast_matchers::internal::DynTypedMatcher::constructVariadic(
156 ast_matchers::internal::DynTypedMatcher::VO_AnyOf,
157 ASTNodeKind::getFromNodeKind<CallExpr>(),
158 std::move(TotalMatchers))
159 .convertTo<CallExpr>()),
165 ArrayRef<unsigned> Indexes,
166 const ASTContext &Ctx) {
167 llvm::SmallVector<unsigned> Sorted(Indexes);
170 llvm::SmallBitVector Commas(Call.getNumArgs());
173 for (
unsigned Index : Sorted) {
174 const Expr *Arg = Call.getArg(Index);
176 if (Index >= Commas.size()) {
177 Diag << FixItHint::CreateRemoval(Arg->getSourceRange());
180 Commas[Index + 1] =
true;
181 Diag << FixItHint::CreateRemoval(CharSourceRange::getTokenRange(
183 Lexer::getLocForEndOfToken(
184 Arg->getEndLoc(), 0, Ctx.getSourceManager(), Ctx.getLangOpts())
185 .getLocWithOffset(1)}));
188 Diag << FixItHint::CreateRemoval(CharSourceRange::getTokenRange(
189 Arg->getBeginLoc().getLocWithOffset(-1), Arg->getEndLoc()));
190 Commas[Index] =
true;
197 const FunctionDecl *Function =
nullptr;
198 for (
auto [
Node, Value] : Result.Nodes.getMap()) {
199 StringRef NodeStr(
Node);
200 if (!NodeStr.consume_front(
FuncDecl))
202 Function = Value.get<FunctionDecl>();
204 if (NodeStr.getAsInteger(10, Index)) {
205 llvm_unreachable(
"Unable to extract replacer index");
207 assert(Index < Replacers.size());
212 SmallString<64> Buffer;
215 const auto *Call = Result.Nodes.getNodeAs<CallExpr>(Buffer);
220 Diag << FixItHint::CreateReplacement(Call->getCallee()->getSourceRange(),
224 Result.SourceManager->getFileID(Call->getBeginLoc()), *Include);
225 llvm::SmallVector<unsigned, 3> ToRemove;
226 for (
const auto &[First, Second, Replace] : Sig) {
227 auto ArgNode =
ArgName + std::to_string(First);
228 if (
const auto *ArgExpr = Result.Nodes.getNodeAs<Expr>(ArgNode)) {
229 Diag << FixItHint::CreateReplacement(
232 Lexer::getSourceText(
233 CharSourceRange::getTokenRange(ArgExpr->getSourceRange()),
234 Result.Context->getSourceManager(),
235 Result.Context->getLangOpts()));
237 assert(ReverseDescriptor &&
"Couldn't find forward argument");
238 ArgNode.push_back(
'R');
239 ArgExpr = Result.Nodes.getNodeAs<Expr>(ArgNode);
240 assert(ArgExpr &&
"Couldn't find forward or reverse argument");
241 if (ReverseDescriptor->ReverseHeader)
243 Result.SourceManager->getFileID(Call->getBeginLoc()),
244 *ReverseDescriptor->ReverseHeader);
245 StringRef ArgText = Lexer::getSourceText(
246 CharSourceRange::getTokenRange(ArgExpr->getSourceRange()),
247 Result.Context->getSourceManager(), Result.Context->getLangOpts());
248 SmallString<128> ReplaceText;
249 if (ReverseDescriptor->IsPipeSyntax)
251 {ArgText,
" | ", ReverseDescriptor->ReverseAdaptorName});
254 {ReverseDescriptor->ReverseAdaptorName,
"(", ArgText,
")"});
255 Diag << FixItHint::CreateReplacement(
265 llvm_unreachable(
"No valid signature found");
269 const LangOptions &LangOpts)
const {
270 return LangOpts.CPlusPlus11;
275 Inserter(Options.getLocalOrGlobal(
"IncludeStyle",
277 areDiagsSelfContained()) {}
280 Preprocessor *PP, Preprocessor *) {
288std::optional<std::string>
294 return diag(Call.getBeginLoc(),
"use a ranges version of this algorithm");
297std::optional<UseRangesCheck::ReverseIteratorDescriptor>
302ArrayRef<std::pair<StringRef, StringRef>>
308 return TK_IgnoreUnlessSpelledInSource;
llvm::SmallString< 256U > Name
::clang::DynTypedNode Node
llvm::raw_string_ostream OS
void store(ClangTidyOptions::OptionMap &Options, StringRef LocalName, StringRef Value) const
Stores an option with the check-local name LocalName with string value Value to Options.
Base class for all clang-tidy checks.
DiagnosticBuilder diag(SourceLocation Loc, StringRef Description, DiagnosticIDs::Level Level=DiagnosticIDs::Warning)
Add a diagnostic with the check's name.
Every ClangTidyCheck reports errors through a DiagnosticsEngine provided by this context.
void registerPreprocessor(Preprocessor *PP)
Registers this with the Preprocessor PP, must be called before this class is used.
std::optional< FixItHint > createIncludeInsertion(FileID FileID, llvm::StringRef Header)
Creates a Header inclusion directive fixit in the File FileID.
IncludeSorter::IncludeStyle getStyle() const
Class used by IncludeInserterCallback to record the names of the inclusions in a given source file be...
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 ...
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
Override this to register AST matchers with Finder.
std::optional< TraversalKind > getCheckTraversalKind() const override
void check(const ast_matchers::MatchFinder::MatchResult &Result) final
ClangTidyChecks that register ASTMatchers should do the actual work in here.
void registerPPCallbacks(const SourceManager &SM, Preprocessor *PP, Preprocessor *ModuleExpanderPP) final
Override this to register PPCallbacks in the preprocessor.
void storeOptions(ClangTidyOptions::OptionMap &Options) override
Should store all options supported by this check with their current values or default values for opti...
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
Override this to disable registering matchers and PP callbacks if an invalid language version is bein...
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
AST_MATCHER(Decl, declHasNoReturnAttr)
matches a Decl if it has a "no return" attribute of any kind
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 makeExprMatcher(ast_matchers::internal::Matcher< Expr > ArgumentMatcher, ArrayRef< StringRef > MethodNames, ArrayRef< StringRef > FreeNames)
static void removeFunctionArgs(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 FuncDecl[]