10#include "clang/AST/ASTContext.h"
11#include "clang/ASTMatchers/ASTMatchFinder.h"
12#include "clang/Basic/LLVM.h"
13#include "clang/Basic/LangOptions.h"
14#include "clang/Basic/SourceLocation.h"
15#include "clang/Basic/SourceManager.h"
16#include "clang/Lex/Lexer.h"
17#include "llvm/ADT/ArrayRef.h"
18#include "llvm/ADT/SmallVector.h"
19#include "llvm/ADT/StringRef.h"
20#include "llvm/ADT/StringSet.h"
21#include "llvm/Support/Casting.h"
22#include "llvm/Support/raw_ostream.h"
35 static llvm::ArrayRef<std::pair<modernize::Confidence::Level, StringRef>>
37 static constexpr std::pair<modernize::Confidence::Level, StringRef>
46 static llvm::ArrayRef<
47 std::pair<modernize::VariableNamer::NamingStyle, StringRef>>
49 static constexpr std::pair<modernize::VariableNamer::NamingStyle, StringRef>
71static const llvm::StringSet<>
MemberNames{
"begin",
"cbegin",
"rbegin",
72 "crbegin",
"end",
"cend",
73 "rend",
"crend",
"size"};
74static const llvm::StringSet<>
ADLNames{
"begin",
"cbegin",
"rbegin",
75 "crbegin",
"end",
"cend",
76 "rend",
"crend",
"size"};
78 "std::begin",
"std::cbegin",
"std::rbegin",
"std::crbegin",
"std::end",
79 "std::cend",
"std::rend",
"std::crend",
"std::size"};
82 return expr(ignoringParenImpCasts(
83 declRefExpr(to(varDecl(equalsBoundNode(
InitVarName))))));
88 hasInitializer(ignoringParenImpCasts(integerLiteral(equals(0)))))
93 return declRefExpr(to(varDecl(equalsBoundNode(
InitVarName))));
96static StatementMatcher
98 return binaryOperator(
101 allOf(hasOperatorName(
">"), hasLHS(LimitExpr),
103 allOf(hasOperatorName(
"!="),
120 StatementMatcher ArrayBoundMatcher =
123 return forStmt(unless(isInTemplateInstantiation()),
127 unaryOperator(hasOperatorName(
"++"),
162 auto BeginNameMatcher = IsReverse ? hasAnyName(
"rbegin",
"crbegin")
163 : hasAnyName(
"begin",
"cbegin");
164 auto BeginNameMatcherStd = IsReverse
165 ? hasAnyName(
"::std::rbegin",
"::std::crbegin")
166 : hasAnyName(
"::std::begin",
"::std::cbegin");
168 auto EndNameMatcher =
169 IsReverse ? hasAnyName(
"rend",
"crend") : hasAnyName(
"end",
"cend");
170 auto EndNameMatcherStd = IsReverse ? hasAnyName(
"::std::rend",
"::std::crend")
171 : hasAnyName(
"::std::end",
"::std::cend");
173 StatementMatcher BeginCallMatcher =
174 expr(anyOf(cxxMemberCallExpr(argumentCountIs(0),
175 callee(cxxMethodDecl(BeginNameMatcher))),
176 callExpr(argumentCountIs(1),
177 callee(functionDecl(BeginNameMatcher)), usesADL()),
178 callExpr(argumentCountIs(1),
179 callee(functionDecl(BeginNameMatcherStd)))))
182 DeclarationMatcher InitDeclMatcher =
183 varDecl(hasInitializer(anyOf(ignoringParenImpCasts(BeginCallMatcher),
184 materializeTemporaryExpr(
185 ignoringParenImpCasts(BeginCallMatcher)),
186 hasDescendant(BeginCallMatcher))))
189 DeclarationMatcher EndDeclMatcher =
190 varDecl(hasInitializer(anything())).bind(
EndVarName);
192 StatementMatcher EndCallMatcher = expr(anyOf(
193 cxxMemberCallExpr(argumentCountIs(0),
194 callee(cxxMethodDecl(EndNameMatcher))),
195 callExpr(argumentCountIs(1), callee(functionDecl(EndNameMatcher)),
197 callExpr(argumentCountIs(1), callee(functionDecl(EndNameMatcherStd)))));
199 StatementMatcher IteratorBoundMatcher =
200 expr(anyOf(ignoringParenImpCasts(
201 declRefExpr(to(varDecl(equalsBoundNode(
EndVarName))))),
202 ignoringParenImpCasts(expr(EndCallMatcher).bind(
EndCallName)),
203 materializeTemporaryExpr(ignoringParenImpCasts(
206 StatementMatcher IteratorComparisonMatcher = expr(ignoringParenImpCasts(
207 declRefExpr(to(varDecl(equalsBoundNode(
InitVarName))))));
212 internal::Matcher<VarDecl> TestDerefReturnsByValue =
213 hasType(hasUnqualifiedDesugaredType(
214 recordType(hasDeclaration(cxxRecordDecl(hasMethod(cxxMethodDecl(
215 hasOverloadedOperatorName(
"*"),
218 returns(qualType(unless(hasCanonicalType(referenceType())))
223 qualType(unless(hasCanonicalType(rValueReferenceType())))
227 unless(isInTemplateInstantiation()),
228 hasLoopInit(anyOf(declStmt(declCountIs(2),
229 containsDeclaration(0, InitDeclMatcher),
230 containsDeclaration(1, EndDeclMatcher)),
231 declStmt(hasSingleDecl(InitDeclMatcher)))),
232 hasCondition(ignoringImplicit(binaryOperation(
233 hasOperatorName(
"!="), hasOperands(IteratorComparisonMatcher,
234 IteratorBoundMatcher)))),
236 unaryOperator(hasOperatorName(
"++"),
237 hasUnaryOperand(declRefExpr(
240 hasOverloadedOperatorName(
"++"),
241 hasArgument(0, declRefExpr(to(
243 TestDerefReturnsByValue))))))))
285 TypeMatcher RecordWithBeginEnd = qualType(anyOf(
286 qualType(isConstQualified(),
287 hasUnqualifiedDesugaredType(recordType(hasDeclaration(
288 cxxRecordDecl(isSameOrDerivedFrom(cxxRecordDecl(
289 hasMethod(cxxMethodDecl(hasName(
"begin"), isConst())),
290 hasMethod(cxxMethodDecl(hasName(
"end"),
293 qualType(unless(isConstQualified()),
294 hasUnqualifiedDesugaredType(recordType(hasDeclaration(
295 cxxRecordDecl(isSameOrDerivedFrom(cxxRecordDecl(
296 hasMethod(hasName(
"begin")),
297 hasMethod(hasName(
"end")))))))))
300 StatementMatcher SizeCallMatcher = expr(anyOf(
301 cxxMemberCallExpr(argumentCountIs(0),
302 callee(cxxMethodDecl(hasAnyName(
"size",
"length"))),
303 on(anyOf(hasType(pointsTo(RecordWithBeginEnd)),
304 hasType(RecordWithBeginEnd)))),
305 callExpr(argumentCountIs(1), callee(functionDecl(hasName(
"size"))),
307 callExpr(argumentCountIs(1),
308 callee(functionDecl(hasName(
"::std::size"))))));
310 StatementMatcher EndInitMatcher =
311 expr(anyOf(ignoringParenImpCasts(expr(SizeCallMatcher).bind(
EndCallName)),
312 explicitCastExpr(hasSourceExpression(ignoringParenImpCasts(
315 DeclarationMatcher EndDeclMatcher =
316 varDecl(hasInitializer(EndInitMatcher)).bind(
EndVarName);
318 StatementMatcher IndexBoundMatcher =
319 expr(anyOf(ignoringParenImpCasts(
320 declRefExpr(to(varDecl(equalsBoundNode(
EndVarName))))),
323 return forStmt(unless(isInTemplateInstantiation()),
325 anyOf(declStmt(declCountIs(2),
327 containsDeclaration(1, EndDeclMatcher)),
331 unaryOperator(hasOperatorName(
"++"),
362 if (
const auto *TheCall = dyn_cast_or_null<CXXMemberCallExpr>(Dug)) {
364 if (
const auto *Member = dyn_cast<MemberExpr>(TheCall->getCallee())) {
365 if (Member->getMemberDecl() ==
nullptr ||
366 !
MemberNames.contains(Member->getMemberDecl()->getName()))
369 Member->getMemberDecl()->getName(),
370 Member->isArrow(), CallKind};
372 if (TheCall->getDirectCallee() ==
nullptr ||
373 !
MemberNames.contains(TheCall->getDirectCallee()->getName()))
376 TheCall->getDirectCallee()->getName(),
false,
379 if (
const auto *TheCall = dyn_cast_or_null<CallExpr>(Dug)) {
380 if (TheCall->getNumArgs() != 1)
383 if (TheCall->usesADL()) {
384 if (TheCall->getDirectCallee() ==
nullptr ||
385 !
ADLNames.contains(TheCall->getDirectCallee()->getName()))
390 TheCall->getDirectCallee()->getQualifiedNameAsString()))
395 if (TheCall->getDirectCallee() ==
nullptr)
399 TheCall->getDirectCallee()->getName(),
false,
410static std::pair<const Expr *, IteratorCallKind>
419 *IsArrow = Call->IsArrow;
420 if (!Call->Name.consume_back(IsBegin ?
"begin" :
"end"))
422 if (IsReverse && !Call->Name.consume_back(
"r"))
424 if (!Call->Name.empty() && Call->Name !=
"c")
426 return std::make_pair(Call->Container, Call->CallKind);
436 bool *ContainerNeedsDereference,
440 bool BeginIsArrow =
false;
441 bool EndIsArrow =
false;
443 BeginExpr,
true, &BeginIsArrow, IsReverse);
444 if (!BeginContainerExpr)
448 EndExpr,
false, &EndIsArrow, IsReverse);
449 if (BeginCallKind != EndCallKind)
454 if (!EndContainerExpr || BeginIsArrow != EndIsArrow ||
455 !
areSameExpr(Context, EndContainerExpr, BeginContainerExpr))
458 *ContainerNeedsDereference = BeginIsArrow;
459 return BeginContainerExpr;
464 const LangOptions &LangOpts,
466 if (SourceMgr.getFileID(
Range.getBegin()) !=
467 SourceMgr.getFileID(
Range.getEnd())) {
471 return Lexer::getSourceText(CharSourceRange(
Range,
true), SourceMgr,
479 return dyn_cast<VarDecl>(DRE->getDecl());
480 if (
const auto *Mem = dyn_cast<MemberExpr>(
E->IgnoreParenImpCasts()))
481 return dyn_cast<FieldDecl>(Mem->getMemberDecl());
488 if (
const auto *Member = dyn_cast<MemberExpr>(
E->IgnoreParenImpCasts()))
489 return isa<CXXThisExpr>(Member->getBase()->IgnoreParenImpCasts());
497 if (
E->getType().isConstQualified())
499 auto Parents = Context->getParents(*
E);
500 if (Parents.size() != 1)
502 if (
const auto *Cast = Parents[0].get<ImplicitCastExpr>()) {
503 if ((Cast->getCastKind() == CK_NoOp &&
504 Context->hasSameType(Cast->getType(),
E->getType().withConst())) ||
505 (Cast->getCastKind() == CK_LValueToRValue &&
506 !Cast->getType().isNull() && Cast->getType()->isFundamentalType()))
516 for (
const Usage &U : Usages) {
532 for (
const auto &U : Usages) {
533 if (U.Expression && !U.Expression->isPRValue())
542 QualType CType = VDec->getType();
544 if (!CType->isPointerType())
546 CType = CType->getPointeeType();
551 CType = CType.getNonReferenceType();
552 return CType.isConstQualified();
559 MaxCopySize(Options.get(
"MaxCopySize", 16ULL)),
560 MinConfidence(Options.get(
"MinConfidence",
Confidence::CL_Reasonable)),
561 NamingStyle(Options.get(
"NamingStyle",
VariableNamer::NS_CamelCase)),
562 Inserter(Options.getLocalOrGlobal(
"IncludeStyle",
563 utils::IncludeSorter::IS_LLVM),
564 areDiagsSelfContained()),
565 UseCxx20IfAvailable(Options.get(
"UseCxx20ReverseRanges", true)),
566 ReverseFunction(Options.get(
"MakeReverseRangeFunction",
"")),
567 ReverseHeader(Options.get(
"MakeReverseRangeHeader",
"")) {
569 if (ReverseFunction.empty() && !ReverseHeader.empty()) {
571 "modernize-loop-convert: 'MakeReverseRangeHeader' is set but "
572 "'MakeReverseRangeFunction' is not, disabling reverse loop "
574 UseReverseRanges =
false;
575 }
else if (ReverseFunction.empty()) {
576 UseReverseRanges = UseCxx20IfAvailable &&
getLangOpts().CPlusPlus20;
578 UseReverseRanges =
true;
587 Options.
store(Opts,
"UseCxx20ReverseRanges", UseCxx20IfAvailable);
588 Options.
store(Opts,
"MakeReverseRangeFunction", ReverseFunction);
589 Options.
store(Opts,
"MakeReverseRangeHeader", ReverseHeader);
594 Preprocessor *ModuleExpanderPP) {
602 if (UseReverseRanges)
619void LoopConvertCheck::getAliasRange(SourceManager &SM, SourceRange &Range) {
620 bool Invalid =
false;
621 const char *TextAfter =
622 SM.getCharacterData(
Range.getEnd().getLocWithOffset(1), &Invalid);
625 unsigned Offset = std::strspn(TextAfter,
" \t\r\n");
632void LoopConvertCheck::doConversion(
633 ASTContext *Context,
const VarDecl *IndexVar,
634 const ValueDecl *MaybeContainer,
const UsageResult &Usages,
635 const DeclStmt *AliasDecl,
bool AliasUseRequired,
bool AliasFromForInit,
636 const ForStmt *Loop, RangeDescriptor Descriptor) {
637 std::string VarNameOrStructuredBinding;
638 bool VarNameFromAlias = (Usages.size() == 1) && AliasDecl;
639 bool AliasVarIsRef =
false;
641 std::vector<FixItHint> FixIts;
642 if (VarNameFromAlias) {
643 const auto *AliasVar = cast<VarDecl>(AliasDecl->getSingleDecl());
646 if (
const auto *AliasDecompositionDecl =
647 dyn_cast<DecompositionDecl>(AliasDecl->getSingleDecl())) {
648 VarNameOrStructuredBinding =
"[";
650 assert(!AliasDecompositionDecl->bindings().empty() &&
"No bindings");
651 for (
const BindingDecl *Binding : AliasDecompositionDecl->bindings()) {
652 VarNameOrStructuredBinding += Binding->getName().str() +
", ";
655 VarNameOrStructuredBinding.erase(VarNameOrStructuredBinding.size() - 2,
657 VarNameOrStructuredBinding +=
"]";
659 VarNameOrStructuredBinding = AliasVar->getName().str();
662 QualType AliasVarType = AliasVar->getType();
663 assert(!AliasVarType.isNull() &&
"Type in VarDecl is null");
664 if (AliasVarType->isReferenceType()) {
665 AliasVarType = AliasVarType.getNonReferenceType();
666 AliasVarIsRef =
true;
668 if (Descriptor.ElemType.isNull() ||
669 !Context->hasSameUnqualifiedType(AliasVarType, Descriptor.ElemType))
670 Descriptor.ElemType = AliasVarType;
674 SourceRange ReplaceRange = AliasDecl->getSourceRange();
676 std::string ReplacementText;
677 if (AliasUseRequired) {
678 ReplacementText = VarNameOrStructuredBinding;
679 }
else if (AliasFromForInit) {
683 ReplacementText =
";";
686 getAliasRange(Context->getSourceManager(), ReplaceRange);
689 FixIts.push_back(FixItHint::CreateReplacement(
690 CharSourceRange::getTokenRange(ReplaceRange), ReplacementText));
694 VariableNamer Namer(&TUInfo->getGeneratedDecls(),
695 &TUInfo->getParentFinder().getStmtToParentStmtMap(),
696 Loop, IndexVar, MaybeContainer, Context, NamingStyle);
697 VarNameOrStructuredBinding = Namer.createIndexName();
700 for (
const auto &Usage : Usages) {
701 std::string ReplaceText;
703 if (
Usage.Expression) {
707 ? VarNameOrStructuredBinding +
"."
708 : VarNameOrStructuredBinding;
709 const DynTypedNodeList
Parents = Context->getParents(*
Usage.Expression);
711 if (
const auto *Paren = Parents[0].get<ParenExpr>()) {
715 const DynTypedNodeList GrandParents = Context->getParents(*Paren);
716 if (GrandParents.size() != 1 ||
717 GrandParents[0].get<UnaryExprOrTypeTraitExpr>() ==
nullptr) {
718 Range = Paren->getSourceRange();
720 }
else if (
const auto *UOP = Parents[0].get<UnaryOperator>()) {
728 if (UOP->getOpcode() == UO_AddrOf)
737 ?
"&" + VarNameOrStructuredBinding
738 : VarNameOrStructuredBinding;
740 TUInfo->getReplacedVars().insert(std::make_pair(Loop, IndexVar));
741 FixIts.push_back(FixItHint::CreateReplacement(
742 CharSourceRange::getTokenRange(Range), ReplaceText));
747 SourceRange ParenRange(Loop->getLParenLoc(), Loop->getRParenLoc());
749 QualType
Type = Context->getAutoDeductType();
750 if (!Descriptor.ElemType.isNull() && Descriptor.ElemType->isFundamentalType())
751 Type = Descriptor.ElemType.getUnqualifiedType();
752 Type =
Type.getDesugaredType(*Context);
758 !Descriptor.ElemType.isNull() &&
759 Descriptor.ElemType.isTriviallyCopyableType(*Context) &&
760 !Descriptor.ElemType->isDependentSizedArrayType() &&
762 Context->getTypeInfo(Descriptor.ElemType).Width <= 8 * MaxCopySize;
763 bool UseCopy = CanCopy && ((VarNameFromAlias && !AliasVarIsRef) ||
764 (Descriptor.DerefByConstRef && IsCheapToCopy));
767 if (Descriptor.DerefByConstRef) {
768 Type = Context->getLValueReferenceType(Context->getConstType(
Type));
769 }
else if (Descriptor.DerefByValue) {
771 Type = Context->getRValueReferenceType(
Type);
773 Type = Context->getLValueReferenceType(
Type);
777 SmallString<128>
Range;
778 llvm::raw_svector_ostream
Output(Range);
781 Output <<
' ' << VarNameOrStructuredBinding <<
" : ";
782 if (Descriptor.NeedsReverseCall)
783 Output << getReverseFunction() <<
'(';
784 if (Descriptor.ContainerNeedsDereference)
786 Output << Descriptor.ContainerString;
787 if (Descriptor.NeedsReverseCall)
791 FixIts.push_back(FixItHint::CreateReplacement(
792 CharSourceRange::getTokenRange(ParenRange), Range));
794 if (Descriptor.NeedsReverseCall && !getReverseHeader().
empty()) {
796 Context->getSourceManager().getFileID(Loop->getBeginLoc()),
798 FixIts.push_back(*Insertion);
800 diag(Loop->getForLoc(),
"use range-based for loop instead") << FixIts;
801 TUInfo->getGeneratedDecls().insert(
802 make_pair(Loop, VarNameOrStructuredBinding));
806StringRef LoopConvertCheck::getContainerString(ASTContext *Context,
808 const Expr *ContainerExpr) {
809 StringRef ContainerString;
810 ContainerExpr = ContainerExpr->IgnoreParenImpCasts();
811 if (isa<CXXThisExpr>(ContainerExpr)) {
812 ContainerString =
"this";
816 if (
const auto *
E = dyn_cast<CXXOperatorCallExpr>(ContainerExpr))
817 if (
E->getOperator() != OO_Subscript)
818 ContainerExpr =
E->getArg(0);
821 ContainerExpr->getSourceRange());
824 return ContainerString;
829void LoopConvertCheck::getArrayLoopQualifiers(ASTContext *Context,
830 const BoundNodes &Nodes,
831 const Expr *ContainerExpr,
833 RangeDescriptor &Descriptor) {
838 Descriptor.DerefByConstRef =
true;
844 Descriptor.DerefByValue =
true;
848 for (
const Usage &U : Usages) {
849 if (!U.Expression || U.Expression->getType().isNull())
851 QualType
Type = U.Expression->getType().getCanonicalType();
853 if (!
Type->isPointerType()) {
858 Descriptor.ElemType =
Type;
864void LoopConvertCheck::getIteratorLoopQualifiers(ASTContext *Context,
865 const BoundNodes &Nodes,
866 RangeDescriptor &Descriptor) {
869 const auto *InitVar = Nodes.getNodeAs<VarDecl>(
InitVarName);
870 QualType CanonicalInitVarType = InitVar->getType().getCanonicalType();
871 const auto *DerefByValueType =
873 Descriptor.DerefByValue = DerefByValueType;
875 if (Descriptor.DerefByValue) {
878 Descriptor.DerefByConstRef = CanonicalInitVarType.isConstQualified();
879 Descriptor.ElemType = *DerefByValueType;
881 if (
const auto *DerefType =
886 auto ValueType = DerefType->getNonReferenceType();
888 Descriptor.DerefByConstRef = ValueType.isConstQualified();
889 Descriptor.ElemType = ValueType;
893 assert(isa<PointerType>(CanonicalInitVarType) &&
894 "Non-class iterator type is not a pointer type");
897 Descriptor.DerefByConstRef =
898 CanonicalInitVarType->getPointeeType().isConstQualified();
899 Descriptor.ElemType = CanonicalInitVarType->getPointeeType();
905void LoopConvertCheck::determineRangeDescriptor(
906 ASTContext *Context,
const BoundNodes &Nodes,
const ForStmt *Loop,
908 const UsageResult &Usages, RangeDescriptor &Descriptor) {
909 Descriptor.ContainerString =
910 std::string(getContainerString(Context, Loop, ContainerExpr));
914 getIteratorLoopQualifiers(Context, Nodes, Descriptor);
916 getArrayLoopQualifiers(Context, Nodes, ContainerExpr, Usages, Descriptor);
921bool LoopConvertCheck::isConvertible(ASTContext *Context,
922 const ast_matchers::BoundNodes &Nodes,
929 TUInfo = std::make_unique<TUTrackingInfo>();
930 else if (TUInfo->getReplacedVars().count(Loop))
934 const auto *InitVar = Nodes.getNodeAs<VarDecl>(
InitVarName);
938 QualType InitVarType = InitVar->getType();
939 QualType CanonicalInitVarType = InitVarType.getCanonicalType();
941 const auto *BeginCall = Nodes.getNodeAs<CallExpr>(
BeginCallName);
942 assert(BeginCall &&
"Bad Callback. No begin call expression");
943 QualType CanonicalBeginType =
944 BeginCall->getDirectCallee()->getReturnType().getCanonicalType();
945 if (CanonicalBeginType->isPointerType() &&
946 CanonicalInitVarType->isPointerType()) {
949 return Context->hasSameUnqualifiedType(
950 CanonicalBeginType->getPointeeType(),
951 CanonicalInitVarType->getPointeeType());
954 if (CanonicalBeginType->isBuiltinType() ||
955 CanonicalInitVarType->isBuiltinType())
959 if (
const auto *EndCall = Nodes.getNodeAs<CXXMemberCallExpr>(
EndCallName)) {
961 if (!isa<MemberExpr>(EndCall->getCallee()))
964 return Nodes.getNodeAs<CallExpr>(
EndCallName) !=
nullptr;
970 const BoundNodes &Nodes = Result.Nodes;
972 ASTContext *Context = Result.Context;
974 const ForStmt *Loop =
nullptr;
976 RangeDescriptor Descriptor;
986 assert(Loop &&
"Bad Callback. No for statement");
990 if (!isConvertible(Context, Nodes, Loop, FixerKind))
993 const auto *LoopVar = Nodes.getNodeAs<VarDecl>(
InitVarName);
994 const auto *EndVar = Nodes.getNodeAs<VarDecl>(
EndVarName);
1003 const auto *EndCall = Nodes.getNodeAs<Expr>(
EndCallName);
1010 const Expr *ContainerExpr =
nullptr;
1013 Context, LoopVar->getInit(), EndVar ? EndVar->getInit() : EndCall,
1014 &Descriptor.ContainerNeedsDereference,
1019 ContainerExpr = Call->Container;
1020 Descriptor.ContainerNeedsDereference = Call->IsArrow;
1025 if (!ContainerExpr && !BoundExpr)
1030 Descriptor.ContainerNeedsDereference);
1033 if (ContainerExpr) {
1041 if (!Finder.findAndVerifyUsages(Loop->getBody()))
1043 ConfidenceLevel.
lowerTo(Finder.getConfidenceLevel());
1047 ContainerExpr = Finder.getContainerIndexed()->IgnoreParenImpCasts();
1058 TraversalKindScope RAII(*Context, TK_AsIs);
1060 determineRangeDescriptor(Context, Nodes, Loop, FixerKind, ContainerExpr,
1061 Usages, Descriptor);
1067 TUInfo->getParentFinder().gatherAncestors(*Context);
1069 &TUInfo->getParentFinder().getStmtToParentStmtMap(),
1070 &TUInfo->getParentFinder().getDeclToParentStmtMap(),
1071 &TUInfo->getReplacedVars(), Loop);
1074 Descriptor.ContainerString.empty() || Usages.empty() ||
1075 ConfidenceLevel.
getLevel() < MinConfidence)
1079 Finder.getAliasDecl(), Finder.aliasUseRequired(),
1080 Finder.aliasFromForInit(), Loop, Descriptor);
1083llvm::StringRef LoopConvertCheck::getReverseFunction()
const {
1084 if (!ReverseFunction.empty())
1085 return ReverseFunction;
1086 if (UseReverseRanges)
1087 return "std::ranges::reverse_view";
1091llvm::StringRef LoopConvertCheck::getReverseHeader()
const {
1092 if (!ReverseHeader.empty())
1093 return ReverseHeader;
1094 if (UseReverseRanges && ReverseFunction.empty()) {
llvm::SmallString< 256U > Name
CharSourceRange Range
SourceRange for the file name.
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.
DiagnosticBuilder configurationDiag(StringRef Description, DiagnosticIDs::Level Level=DiagnosticIDs::Warning) const
Adds a diagnostic to report errors in the check's configuration.
bool areDiagsSelfContained() const
Returns true when the check is run in a use case when only 1 fix will be applied at a time.
const LangOptions & getLangOpts() const
Returns the language options from the context.
Every ClangTidyCheck reports errors through a DiagnosticsEngine provided by this context.
Class used to find the variables and member expressions on which an arbitrary expression depends.
void findExprComponents(const clang::Expr *SourceExpr)
Find the components of an expression and place them in a ComponentVector.
const ComponentVector & getComponents()
Accessor for Components.
A class to encapsulate lowering of the tool's confidence level.
Level getLevel() const
Return the internal confidence level.
void lowerTo(Confidence::Level Level)
Lower the internal confidence level to Level, but do not raise it.
Class used to determine if an expression is dependent on a variable declared inside of the loop where...
bool dependsOnInsideVariable(const clang::Stmt *Body)
Run the analysis on Body, and return true iff the expression depends on some variable declared within...
Discover usages of expressions consisting of index or iterator access.
void registerPPCallbacks(const SourceManager &SM, Preprocessor *PP, Preprocessor *ModuleExpanderPP) override
Override this to register PPCallbacks in the preprocessor.
void storeOptions(ClangTidyOptions::OptionMap &Opts) override
Should store all options supported by this check with their current values or default values for opti...
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
ClangTidyChecks that register ASTMatchers should do the actual work in here.
LoopConvertCheck(StringRef Name, ClangTidyContext *Context)
void registerMatchers(ast_matchers::MatchFinder *Finder) override
Override this to register AST matchers with Finder.
Create names for generated variables within a particular statement.
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
static const char EndCallName[]
static StringRef getStringFromRange(SourceManager &SourceMgr, const LangOptions &LangOpts, SourceRange Range)
Obtain the original source code text from a SourceRange.
static bool empty(SourceRange Range)
static const llvm::StringSet StdNames
static DeclarationMatcher initToZeroMatcher()
static StatementMatcher incrementVarMatcher()
static const char DerefByValueResultName[]
static bool canBeModified(ASTContext *Context, const Expr *E)
Given an expression that represents an usage of an element from the containter that we are iterating ...
static const char LoopNamePseudoArray[]
static const char BeginCallName[]
static std::optional< ContainerCall > getContainerExpr(const Expr *Call)
static const char ConditionBoundName[]
const DeclRefExpr * getDeclRef(const Expr *E)
Returns the DeclRefExpr represented by E, or NULL if there isn't one.
static const llvm::StringSet MemberNames
static const llvm::StringSet ADLNames
static bool usagesReturnRValues(const UsageResult &Usages)
Returns true if the elements of the container are never accessed by reference.
static const ValueDecl * getReferencedVariable(const Expr *E)
If the given expression is actually a DeclRefExpr or a MemberExpr, find and return the underlying Val...
StatementMatcher makeArrayLoopMatcher()
The matcher for loops over arrays.
static StatementMatcher integerComparisonMatcher()
const Expr * digThroughConstructorsConversions(const Expr *E)
Look through conversion/copy constructors and member functions to find the explicit initialization ex...
static const char DerefByRefResultName[]
static bool containerIsConst(const Expr *ContainerExpr, bool Dereference)
Returns true if the container is const-qualified.
static const Expr * findContainer(ASTContext *Context, const Expr *BeginExpr, const Expr *EndExpr, bool *ContainerNeedsDereference, bool IsReverse)
Determines the container whose begin() and end() functions are called for an iterator-based loop.
static std::pair< const Expr *, IteratorCallKind > getContainerFromBeginEndCall(const Expr *Init, bool IsBegin, bool *IsArrow, bool IsReverse)
Determine whether Init appears to be an initializing an iterator.
static const char LoopNameIterator[]
llvm::SmallVector< Usage, 8 > UsageResult
static const char InitVarName[]
bool areSameExpr(ASTContext *Context, const Expr *First, const Expr *Second)
Returns true when two Exprs are equivalent.
static const char EndVarName[]
StatementMatcher makeIteratorLoopMatcher(bool IsReverse)
The matcher used for iterator-based for loops.
static bool isDirectMemberExpr(const Expr *E)
Returns true when the given expression is a member expression whose base is this (implicitly or not).
static const char LoopNameReverseIterator[]
static const char LoopNameArray[]
static bool usagesAreConst(ASTContext *Context, const UsageResult &Usages)
Returns true when it can be guaranteed that the elements of the container are not being modified.
static StatementMatcher arrayConditionMatcher(internal::Matcher< Expr > LimitExpr)
StatementMatcher makePseudoArrayLoopMatcher()
The matcher used for array-like containers (pseudoarrays).
Some operations such as code completion produce a set of candidates.
llvm::StringMap< ClangTidyValue > OptionMap
static llvm::ArrayRef< std::pair< modernize::Confidence::Level, StringRef > > getEnumMapping()
static llvm::ArrayRef< std::pair< modernize::VariableNamer::NamingStyle, StringRef > > getEnumMapping()
This class should be specialized by any enum type that needs to be converted to and from an llvm::Str...
IteratorCallKind CallKind
The information needed to describe a valid convertible usage of an array index or iterator.