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/raw_ostream.h"
33 static llvm::ArrayRef<std::pair<modernize::Confidence::Level, StringRef>>
35 static constexpr std::pair<modernize::Confidence::Level, StringRef>
44 static llvm::ArrayRef<
45 std::pair<modernize::VariableNamer::NamingStyle, StringRef>>
47 static constexpr std::pair<modernize::VariableNamer::NamingStyle, StringRef>
69static const llvm::StringSet<>
MemberNames{
"begin",
"cbegin",
"rbegin",
70 "crbegin",
"end",
"cend",
71 "rend",
"crend",
"size"};
72static const llvm::StringSet<>
ADLNames{
"begin",
"cbegin",
"rbegin",
73 "crbegin",
"end",
"cend",
74 "rend",
"crend",
"size"};
76 "std::begin",
"std::cbegin",
"std::rbegin",
"std::crbegin",
"std::end",
77 "std::cend",
"std::rend",
"std::crend",
"std::size"};
80 return expr(ignoringParenImpCasts(
81 declRefExpr(to(varDecl(equalsBoundNode(
InitVarName))))));
86 hasInitializer(ignoringParenImpCasts(integerLiteral(equals(0)))))
91 return declRefExpr(to(varDecl(equalsBoundNode(
InitVarName))));
94static StatementMatcher
96 return binaryOperator(
99 allOf(hasOperatorName(
">"), hasLHS(LimitExpr),
101 allOf(hasOperatorName(
"!="),
118 const StatementMatcher ArrayBoundMatcher =
121 return forStmt(unless(isInTemplateInstantiation()),
125 unaryOperator(hasOperatorName(
"++"),
159 auto BeginNameMatcher = IsReverse ? hasAnyName(
"rbegin",
"crbegin")
160 : hasAnyName(
"begin",
"cbegin");
161 auto BeginNameMatcherStd = IsReverse
162 ? hasAnyName(
"::std::rbegin",
"::std::crbegin")
163 : hasAnyName(
"::std::begin",
"::std::cbegin");
165 auto EndNameMatcher =
166 IsReverse ? hasAnyName(
"rend",
"crend") : hasAnyName(
"end",
"cend");
167 auto EndNameMatcherStd = IsReverse ? hasAnyName(
"::std::rend",
"::std::crend")
168 : hasAnyName(
"::std::end",
"::std::cend");
170 const StatementMatcher BeginCallMatcher =
171 expr(anyOf(cxxMemberCallExpr(argumentCountIs(0),
172 callee(cxxMethodDecl(BeginNameMatcher))),
173 callExpr(argumentCountIs(1),
174 callee(functionDecl(BeginNameMatcher)), usesADL()),
175 callExpr(argumentCountIs(1),
176 callee(functionDecl(BeginNameMatcherStd)))))
179 const DeclarationMatcher InitDeclMatcher =
180 varDecl(hasInitializer(anyOf(ignoringParenImpCasts(BeginCallMatcher),
181 materializeTemporaryExpr(
182 ignoringParenImpCasts(BeginCallMatcher)),
183 hasDescendant(BeginCallMatcher))))
186 const DeclarationMatcher EndDeclMatcher =
187 varDecl(hasInitializer(anything())).bind(
EndVarName);
189 const StatementMatcher EndCallMatcher = expr(anyOf(
190 cxxMemberCallExpr(argumentCountIs(0),
191 callee(cxxMethodDecl(EndNameMatcher))),
192 callExpr(argumentCountIs(1), callee(functionDecl(EndNameMatcher)),
194 callExpr(argumentCountIs(1), callee(functionDecl(EndNameMatcherStd)))));
196 const StatementMatcher IteratorBoundMatcher =
197 expr(anyOf(ignoringParenImpCasts(
198 declRefExpr(to(varDecl(equalsBoundNode(
EndVarName))))),
199 ignoringParenImpCasts(expr(EndCallMatcher).bind(
EndCallName)),
200 materializeTemporaryExpr(ignoringParenImpCasts(
203 const StatementMatcher IteratorComparisonMatcher = expr(ignoringParenImpCasts(
204 declRefExpr(to(varDecl(equalsBoundNode(
InitVarName))))));
209 const internal::Matcher<VarDecl> TestDerefReturnsByValue =
210 hasType(hasUnqualifiedDesugaredType(
211 recordType(hasDeclaration(cxxRecordDecl(hasMethod(cxxMethodDecl(
212 hasOverloadedOperatorName(
"*"),
215 returns(qualType(unless(hasCanonicalType(referenceType())))
220 qualType(unless(hasCanonicalType(rValueReferenceType())))
224 unless(isInTemplateInstantiation()),
225 hasLoopInit(anyOf(declStmt(declCountIs(2),
226 containsDeclaration(0, InitDeclMatcher),
227 containsDeclaration(1, EndDeclMatcher)),
228 declStmt(hasSingleDecl(InitDeclMatcher)))),
229 hasCondition(ignoringImplicit(binaryOperation(
230 hasOperatorName(
"!="), hasOperands(IteratorComparisonMatcher,
231 IteratorBoundMatcher)))),
233 unaryOperator(hasOperatorName(
"++"),
234 hasUnaryOperand(declRefExpr(
237 hasOverloadedOperatorName(
"++"),
238 hasArgument(0, declRefExpr(to(
240 TestDerefReturnsByValue))))))))
282 const TypeMatcher RecordWithBeginEnd = qualType(anyOf(
283 qualType(isConstQualified(),
284 hasUnqualifiedDesugaredType(recordType(hasDeclaration(
285 cxxRecordDecl(isSameOrDerivedFrom(cxxRecordDecl(
286 hasMethod(cxxMethodDecl(hasName(
"begin"), isConst())),
287 hasMethod(cxxMethodDecl(hasName(
"end"),
290 qualType(unless(isConstQualified()),
291 hasUnqualifiedDesugaredType(recordType(hasDeclaration(
292 cxxRecordDecl(isSameOrDerivedFrom(cxxRecordDecl(
293 hasMethod(hasName(
"begin")),
294 hasMethod(hasName(
"end")))))))))
297 const StatementMatcher SizeCallMatcher = expr(anyOf(
298 cxxMemberCallExpr(argumentCountIs(0),
299 callee(cxxMethodDecl(hasAnyName(
"size",
"length"))),
300 on(anyOf(hasType(pointsTo(RecordWithBeginEnd)),
301 hasType(RecordWithBeginEnd)))),
302 callExpr(argumentCountIs(1), callee(functionDecl(hasName(
"size"))),
304 callExpr(argumentCountIs(1),
305 callee(functionDecl(hasName(
"::std::size"))))));
307 StatementMatcher EndInitMatcher =
308 expr(anyOf(ignoringParenImpCasts(expr(SizeCallMatcher).bind(
EndCallName)),
309 explicitCastExpr(hasSourceExpression(ignoringParenImpCasts(
312 const DeclarationMatcher EndDeclMatcher =
313 varDecl(hasInitializer(EndInitMatcher)).bind(
EndVarName);
315 const StatementMatcher IndexBoundMatcher =
316 expr(anyOf(ignoringParenImpCasts(
317 declRefExpr(to(varDecl(equalsBoundNode(
EndVarName))))),
320 return forStmt(unless(isInTemplateInstantiation()),
322 anyOf(declStmt(declCountIs(2),
324 containsDeclaration(1, EndDeclMatcher)),
328 unaryOperator(hasOperatorName(
"++"),
335enum class IteratorCallKind {
341struct ContainerCall {
342 const Expr *Container;
345 IteratorCallKind CallKind;
361 IteratorCallKind CallKind = IteratorCallKind::ICK_Member;
363 if (
const auto *TheCall = dyn_cast_or_null<CXXMemberCallExpr>(Dug)) {
364 CallKind = IteratorCallKind::ICK_Member;
365 if (
const auto *Member = dyn_cast<MemberExpr>(TheCall->getCallee())) {
366 if (Member->getMemberDecl() ==
nullptr ||
367 !
MemberNames.contains(Member->getMemberDecl()->getName()))
369 return ContainerCall{TheCall->getImplicitObjectArgument(),
370 Member->getMemberDecl()->getName(),
371 Member->isArrow(), CallKind};
373 if (TheCall->getDirectCallee() ==
nullptr ||
374 !
MemberNames.contains(TheCall->getDirectCallee()->getName()))
376 return ContainerCall{TheCall->getArg(0),
377 TheCall->getDirectCallee()->getName(),
false,
380 if (
const auto *TheCall = dyn_cast_or_null<CallExpr>(Dug)) {
381 if (TheCall->getNumArgs() != 1)
384 if (TheCall->usesADL()) {
385 if (TheCall->getDirectCallee() ==
nullptr ||
386 !
ADLNames.contains(TheCall->getDirectCallee()->getName()))
388 CallKind = IteratorCallKind::ICK_ADL;
391 TheCall->getDirectCallee()->getQualifiedNameAsString()))
393 CallKind = IteratorCallKind::ICK_Std;
396 if (TheCall->getDirectCallee() ==
nullptr)
399 return ContainerCall{TheCall->getArg(0),
400 TheCall->getDirectCallee()->getName(),
false,
411static std::pair<const Expr *, IteratorCallKind>
420 *IsArrow = Call->IsArrow;
421 if (!Call->Name.consume_back(IsBegin ?
"begin" :
"end"))
423 if (IsReverse && !Call->Name.consume_back(
"r"))
425 if (!Call->Name.empty() && Call->Name !=
"c")
427 return {Call->Container, Call->CallKind};
436 const Expr *BeginExpr,
const Expr *EndExpr,
437 bool *ContainerNeedsDereference,
441 bool BeginIsArrow =
false;
442 bool EndIsArrow =
false;
444 BeginExpr,
true, &BeginIsArrow, IsReverse);
445 if (!BeginContainerExpr)
449 EndExpr,
false, &EndIsArrow, IsReverse);
450 if (BeginCallKind != EndCallKind)
455 if (!EndContainerExpr || BeginIsArrow != EndIsArrow ||
456 !
areSameExpr(Context, EndContainerExpr, BeginContainerExpr))
459 *ContainerNeedsDereference = BeginIsArrow;
460 return BeginContainerExpr;
465 const LangOptions &LangOpts,
467 if (SourceMgr.getFileID(Range.getBegin()) !=
468 SourceMgr.getFileID(Range.getEnd())) {
472 return Lexer::getSourceText(CharSourceRange(Range,
true), SourceMgr,
480 return dyn_cast<VarDecl>(DRE->getDecl());
481 if (
const auto *Mem = dyn_cast<MemberExpr>(E->IgnoreParenImpCasts()))
482 return dyn_cast<FieldDecl>(Mem->getMemberDecl());
489 if (
const auto *Member = dyn_cast<MemberExpr>(E->IgnoreParenImpCasts()))
490 return isa<CXXThisExpr>(Member->getBase()->IgnoreParenImpCasts());
498 if (E->getType().isConstQualified())
500 auto Parents = Context->getParents(*E);
501 if (Parents.size() != 1)
503 if (
const auto *Cast = Parents[0].get<ImplicitCastExpr>()) {
504 if ((Cast->getCastKind() == CK_NoOp &&
505 ASTContext::hasSameType(Cast->getType(), E->getType().withConst())) ||
506 (Cast->getCastKind() == CK_LValueToRValue &&
507 !Cast->getType().isNull() && Cast->getType()->isFundamentalType()))
517 return llvm::none_of(Usages, [&Context](
const Usage &U) {
532 return llvm::all_of(Usages, [](
const Usage &U) {
540 QualType CType = VDec->getType();
542 if (!CType->isPointerType())
544 CType = CType->getPointeeType();
549 CType = CType.getNonReferenceType();
550 return CType.isConstQualified();
559 const LangOptions &LangOpts,
560 SourceLocation BeginLocation) {
561 std::optional<Token> PrevToken =
562 Lexer::findPreviousToken(BeginLocation, SourceMgr, LangOpts,
true);
567 const bool IsAdjacentToPrevToken = PrevToken->getEndLoc() == BeginLocation;
568 return PrevToken->isAnyIdentifier() && IsAdjacentToPrevToken;
576 const LangOptions &LangOpts,
577 SourceLocation BeginLocation) {
579 if (!Lexer::getRawToken(BeginLocation, StarToken, SourceMgr, LangOpts,
581 StarToken.is(tok::star)) {
590 MaxCopySize(Options.get(
"MaxCopySize", 16ULL)),
591 MinConfidence(Options.get(
"MinConfidence",
Confidence::CL_Reasonable)),
592 NamingStyle(Options.get(
"NamingStyle",
VariableNamer::NS_CamelCase)),
593 Inserter(Options.getLocalOrGlobal(
"IncludeStyle",
594 utils::IncludeSorter::IS_LLVM),
595 areDiagsSelfContained()),
596 UseCxx20IfAvailable(Options.get(
"UseCxx20ReverseRanges", true)),
597 ReverseFunction(Options.get(
"MakeReverseRangeFunction",
"")),
598 ReverseHeader(Options.get(
"MakeReverseRangeHeader",
"")) {
599 if (ReverseFunction.empty() && !ReverseHeader.empty()) {
601 "modernize-loop-convert: 'MakeReverseRangeHeader' is set but "
602 "'MakeReverseRangeFunction' is not, disabling reverse loop "
604 UseReverseRanges = false;
605 }
else if (ReverseFunction.empty()) {
606 UseReverseRanges = UseCxx20IfAvailable && getLangOpts().CPlusPlus20;
608 UseReverseRanges = true;
613 Options.store(Opts,
"MaxCopySize", MaxCopySize);
614 Options.store(Opts,
"MinConfidence", MinConfidence);
615 Options.store(Opts,
"NamingStyle", NamingStyle);
616 Options.store(Opts,
"IncludeStyle", Inserter.getStyle());
617 Options.store(Opts,
"UseCxx20ReverseRanges", UseCxx20IfAvailable);
618 Options.store(Opts,
"MakeReverseRangeFunction", ReverseFunction);
619 Options.store(Opts,
"MakeReverseRangeHeader", ReverseHeader);
624 Preprocessor *ModuleExpanderPP) {
625 Inserter.registerPreprocessor(PP);
632 if (UseReverseRanges)
649void LoopConvertCheck::getAliasRange(SourceManager &SM, SourceRange &Range) {
650 bool Invalid =
false;
651 const char *TextAfter =
652 SM.getCharacterData(Range.getEnd().getLocWithOffset(1), &Invalid);
655 const unsigned Offset = std::strspn(TextAfter,
" \t\r\n");
657 SourceRange(Range.getBegin(), Range.getEnd().getLocWithOffset(Offset));
662void LoopConvertCheck::doConversion(
663 ASTContext *Context,
const VarDecl *IndexVar,
664 const ValueDecl *MaybeContainer,
const UsageResult &Usages,
665 const DeclStmt *AliasDecl,
bool AliasUseRequired,
bool AliasFromForInit,
666 const ForStmt *Loop, RangeDescriptor Descriptor) {
667 std::string VarNameOrStructuredBinding;
668 const bool VarNameFromAlias = (Usages.size() == 1) && AliasDecl;
669 bool AliasVarIsRef =
false;
671 std::vector<FixItHint> FixIts;
672 if (VarNameFromAlias) {
673 const auto *AliasVar = cast<VarDecl>(AliasDecl->getSingleDecl());
676 if (
const auto *AliasDecompositionDecl =
677 dyn_cast<DecompositionDecl>(AliasDecl->getSingleDecl())) {
678 VarNameOrStructuredBinding =
"[";
680 assert(!AliasDecompositionDecl->bindings().empty() &&
"No bindings");
681 for (
const BindingDecl *Binding : AliasDecompositionDecl->bindings())
682 VarNameOrStructuredBinding += Binding->getName().str() +
", ";
684 VarNameOrStructuredBinding.erase(VarNameOrStructuredBinding.size() - 2,
686 VarNameOrStructuredBinding +=
']';
688 VarNameOrStructuredBinding = AliasVar->getName().str();
691 QualType AliasVarType = AliasVar->getType();
692 assert(!AliasVarType.isNull() &&
"Type in VarDecl is null");
693 if (AliasVarType->isReferenceType()) {
694 AliasVarType = AliasVarType.getNonReferenceType();
695 AliasVarIsRef =
true;
697 if (Descriptor.ElemType.isNull() ||
698 !ASTContext::hasSameUnqualifiedType(AliasVarType,
699 Descriptor.ElemType))
700 Descriptor.ElemType = AliasVarType;
704 SourceRange ReplaceRange = AliasDecl->getSourceRange();
706 std::string ReplacementText;
707 if (AliasUseRequired) {
708 ReplacementText = VarNameOrStructuredBinding;
709 }
else if (AliasFromForInit) {
713 ReplacementText =
";";
716 getAliasRange(Context->getSourceManager(), ReplaceRange);
719 FixIts.push_back(FixItHint::CreateReplacement(
720 CharSourceRange::getTokenRange(ReplaceRange), ReplacementText));
724 VariableNamer Namer(&TUInfo->getGeneratedDecls(),
725 &TUInfo->getParentFinder().getStmtToParentStmtMap(),
726 Loop, IndexVar, MaybeContainer, Context, NamingStyle);
727 VarNameOrStructuredBinding = Namer.createIndexName();
730 for (
const auto &
Usage : Usages) {
731 std::string ReplaceText;
732 SourceRange Range =
Usage.Range;
733 if (
Usage.Expression) {
736 Usage.Range.getBegin()))
741 ? VarNameOrStructuredBinding +
"."
742 : VarNameOrStructuredBinding;
743 const DynTypedNodeList
Parents = Context->getParents(*
Usage.Expression);
745 if (
const auto *Paren = Parents[0].get<ParenExpr>()) {
749 const DynTypedNodeList GrandParents = Context->getParents(*Paren);
750 if (GrandParents.size() != 1 ||
751 (GrandParents[0].get<UnaryExprOrTypeTraitExpr>() ==
nullptr &&
753 Context->getSourceManager(), getLangOpts(),
754 Parents[0].getSourceRange().getBegin()))) {
755 Range = Paren->getSourceRange();
757 }
else if (
const auto *UOP = Parents[0].get<UnaryOperator>()) {
765 if (UOP->getOpcode() == UO_AddrOf)
774 ?
"&" + VarNameOrStructuredBinding
775 : VarNameOrStructuredBinding;
777 TUInfo->getReplacedVars().try_emplace(Loop, IndexVar);
778 FixIts.push_back(FixItHint::CreateReplacement(
779 CharSourceRange::getTokenRange(Range), ReplaceText));
784 const SourceRange ParenRange(Loop->getLParenLoc(), Loop->getRParenLoc());
786 QualType
Type = Context->getAutoDeductType();
787 if (!Descriptor.ElemType.isNull() && Descriptor.ElemType->isFundamentalType())
788 Type = Descriptor.ElemType.getUnqualifiedType();
789 Type =
Type.getDesugaredType(*Context);
794 const bool IsCheapToCopy =
795 !Descriptor.ElemType.isNull() &&
796 Descriptor.ElemType.isTriviallyCopyableType(*Context) &&
797 !Descriptor.ElemType->isDependentSizedArrayType() &&
799 Context->getTypeInfo(Descriptor.ElemType).Width <= 8 * MaxCopySize;
801 CanCopy && ((VarNameFromAlias && !AliasVarIsRef) ||
802 (Descriptor.DerefByConstRef && IsCheapToCopy));
805 if (Descriptor.DerefByConstRef) {
806 Type = Context->getLValueReferenceType(Context->getConstType(Type));
807 }
else if (Descriptor.DerefByValue) {
809 Type = Context->getRValueReferenceType(Type);
811 Type = Context->getLValueReferenceType(Type);
815 SmallString<128> Range;
816 llvm::raw_svector_ostream Output(Range);
818 Type.print(Output, getLangOpts());
819 Output <<
' ' << VarNameOrStructuredBinding <<
" : ";
820 if (Descriptor.NeedsReverseCall)
821 Output << getReverseFunction() <<
'(';
822 if (Descriptor.ContainerNeedsDereference)
824 Output << Descriptor.ContainerString;
825 if (Descriptor.NeedsReverseCall)
829 FixIts.push_back(FixItHint::CreateReplacement(
830 CharSourceRange::getTokenRange(ParenRange), Range));
832 if (Descriptor.NeedsReverseCall && !getReverseHeader().
empty()) {
833 if (std::optional<FixItHint> Insertion = Inserter.createIncludeInsertion(
834 Context->getSourceManager().getFileID(Loop->getBeginLoc()),
836 FixIts.push_back(*Insertion);
838 diag(Loop->getForLoc(),
"use range-based for loop instead") << FixIts;
839 TUInfo->getGeneratedDecls().try_emplace(Loop, VarNameOrStructuredBinding);
843StringRef LoopConvertCheck::getContainerString(ASTContext *Context,
845 const Expr *ContainerExpr) {
846 StringRef ContainerString;
847 ContainerExpr = ContainerExpr->IgnoreParenImpCasts();
848 if (isa<CXXThisExpr>(ContainerExpr)) {
849 ContainerString =
"this";
853 if (
const auto *E = dyn_cast<CXXOperatorCallExpr>(ContainerExpr))
854 if (E->getOperator() != OO_Subscript)
855 ContainerExpr = E->getArg(0);
858 ContainerExpr->getSourceRange());
861 return ContainerString;
866void LoopConvertCheck::getArrayLoopQualifiers(ASTContext *Context,
867 const BoundNodes &Nodes,
868 const Expr *ContainerExpr,
870 RangeDescriptor &Descriptor) {
875 Descriptor.DerefByConstRef =
true;
881 Descriptor.DerefByValue =
true;
885 for (
const Usage &U : Usages) {
886 if (!U.Expression || U.Expression->getType().isNull())
888 QualType
Type = U.Expression->getType().getCanonicalType();
890 if (!
Type->isPointerType())
894 Descriptor.ElemType =
Type;
900void LoopConvertCheck::getIteratorLoopQualifiers(ASTContext *Context,
901 const BoundNodes &Nodes,
902 RangeDescriptor &Descriptor) {
905 const auto *InitVar = Nodes.getNodeAs<VarDecl>(
InitVarName);
906 const QualType CanonicalInitVarType = InitVar->getType().getCanonicalType();
907 const auto *DerefByValueType =
909 Descriptor.DerefByValue = DerefByValueType;
911 if (Descriptor.DerefByValue) {
914 Descriptor.DerefByConstRef = CanonicalInitVarType.isConstQualified();
915 Descriptor.ElemType = *DerefByValueType;
916 }
else if (
const auto *DerefType =
921 auto ValueType = DerefType->getNonReferenceType();
923 Descriptor.DerefByConstRef = ValueType.isConstQualified();
924 Descriptor.ElemType = ValueType;
928 assert(isa<PointerType>(CanonicalInitVarType) &&
929 "Non-class iterator type is not a pointer type");
932 Descriptor.DerefByConstRef =
933 CanonicalInitVarType->getPointeeType().isConstQualified();
934 Descriptor.ElemType = CanonicalInitVarType->getPointeeType();
939void LoopConvertCheck::determineRangeDescriptor(
940 ASTContext *Context,
const BoundNodes &Nodes,
const ForStmt *Loop,
942 const UsageResult &Usages, RangeDescriptor &Descriptor) {
943 Descriptor.ContainerString =
944 std::string(getContainerString(Context, Loop, ContainerExpr));
948 getIteratorLoopQualifiers(Context, Nodes, Descriptor);
950 getArrayLoopQualifiers(Context, Nodes, ContainerExpr, Usages, Descriptor);
955bool LoopConvertCheck::isConvertible(ASTContext *Context,
956 const ast_matchers::BoundNodes &Nodes,
962 if (areDiagsSelfContained())
963 TUInfo = std::make_unique<TUTrackingInfo>();
964 else if (TUInfo->getReplacedVars().contains(Loop))
968 const auto *InitVar = Nodes.getNodeAs<VarDecl>(
InitVarName);
972 const QualType InitVarType = InitVar->getType();
973 const QualType CanonicalInitVarType = InitVarType.getCanonicalType();
975 const auto *BeginCall = Nodes.getNodeAs<CallExpr>(
BeginCallName);
976 assert(BeginCall &&
"Bad Callback. No begin call expression");
977 const QualType CanonicalBeginType =
978 BeginCall->getDirectCallee()->getReturnType().getCanonicalType();
979 if (CanonicalBeginType->isPointerType() &&
980 CanonicalInitVarType->isPointerType()) {
983 return ASTContext::hasSameUnqualifiedType(
984 CanonicalBeginType->getPointeeType(),
985 CanonicalInitVarType->getPointeeType());
988 if (CanonicalBeginType->isBuiltinType() ||
989 CanonicalInitVarType->isBuiltinType())
993 if (
const auto *EndCall = Nodes.getNodeAs<CXXMemberCallExpr>(
EndCallName)) {
995 if (!isa<MemberExpr>(EndCall->getCallee()))
998 return Nodes.getNodeAs<CallExpr>(
EndCallName) !=
nullptr;
1004 const BoundNodes &Nodes = Result.Nodes;
1006 ASTContext *Context = Result.Context;
1008 const ForStmt *Loop =
nullptr;
1010 RangeDescriptor Descriptor;
1020 assert(Loop &&
"Bad Callback. No for statement");
1024 if (!isConvertible(Context, Nodes, Loop, FixerKind))
1027 const auto *LoopVar = Nodes.getNodeAs<VarDecl>(
InitVarName);
1028 const auto *EndVar = Nodes.getNodeAs<VarDecl>(
EndVarName);
1037 const auto *EndCall = Nodes.getNodeAs<Expr>(
EndCallName);
1044 const Expr *ContainerExpr =
nullptr;
1047 Context, LoopVar->getInit(), EndVar ? EndVar->getInit() : EndCall,
1048 &Descriptor.ContainerNeedsDereference,
1053 ContainerExpr = Call->Container;
1054 Descriptor.ContainerNeedsDereference = Call->IsArrow;
1059 if (!ContainerExpr && !BoundExpr)
1064 Descriptor.ContainerNeedsDereference);
1067 if (ContainerExpr) {
1092 const TraversalKindScope RAII(*Context, TK_AsIs);
1094 determineRangeDescriptor(Context, Nodes, Loop, FixerKind, ContainerExpr,
1095 Usages, Descriptor);
1101 TUInfo->getParentFinder().gatherAncestors(*Context);
1103 &TUInfo->getParentFinder().getStmtToParentStmtMap(),
1104 &TUInfo->getParentFinder().getDeclToParentStmtMap(),
1105 &TUInfo->getReplacedVars(), Loop);
1108 Descriptor.ContainerString.empty() || Usages.empty() ||
1109 ConfidenceLevel.
getLevel() < MinConfidence)
1117StringRef LoopConvertCheck::getReverseFunction()
const {
1118 if (!ReverseFunction.empty())
1119 return ReverseFunction;
1120 if (UseReverseRanges)
1121 return "std::views::reverse";
1125StringRef LoopConvertCheck::getReverseHeader()
const {
1126 if (!ReverseHeader.empty())
1127 return ReverseHeader;
1128 if (UseReverseRanges && ReverseFunction.empty())
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 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 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.
const UsageResult & getUsages() const
Accessor for Usages.
bool aliasFromForInit() const
Indicates if the alias declaration came from the init clause of a nested for loop.
const DeclStmt * getAliasDecl() const
Returns the statement declaring the variable created as an alias for the loop element,...
bool aliasUseRequired() const
Indicates if the alias declaration was in a place where it cannot simply be removed but rather replac...
bool findAndVerifyUsages(const Stmt *Body)
Finds all uses of IndexVar in Body, placing all usages in Usages, and returns true if IndexVar was on...
Confidence::Level getConfidenceLevel() const
Accessor for ConfidenceLevel.
void addComponents(const ComponentVector &Components)
Add a set of components that we should consider relevant to the container.
const Expr * getContainerIndexed() const
Get the container indexed by IndexVar, if any.
void registerPPCallbacks(const SourceManager &SM, Preprocessor *PP, Preprocessor *ModuleExpanderPP) override
void storeOptions(ClangTidyOptions::OptionMap &Opts) override
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
LoopConvertCheck(StringRef Name, ClangTidyContext *Context)
void registerMatchers(ast_matchers::MatchFinder *Finder) override
Create names for generated variables within a particular statement.
@ Type
An inlay hint that for a type annotation.
static constexpr char BeginCallName[]
static constexpr char DerefByRefResultName[]
static bool empty(SourceRange Range)
static constexpr char LoopNameReverseIterator[]
static const llvm::StringSet StdNames
static DeclarationMatcher initToZeroMatcher()
static StatementMatcher incrementVarMatcher()
static constexpr char EndCallName[]
static StatementMatcher makePseudoArrayLoopMatcher()
The matcher used for array-like containers (pseudoarrays).
static StatementMatcher arrayConditionMatcher(const internal::Matcher< Expr > &LimitExpr)
static constexpr char ConditionBoundName[]
static bool canBeModified(ASTContext *Context, const Expr *E)
Given an expression that represents an usage of an element from the container that we are iterating o...
static StringRef getStringFromRange(const SourceManager &SourceMgr, const LangOptions &LangOpts, SourceRange Range)
Obtain the original source code text from a SourceRange.
static std::optional< ContainerCall > getContainerExpr(const Expr *Call)
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 StatementMatcher makeArrayLoopMatcher()
The matcher for loops over arrays.
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...
static constexpr char EndVarName[]
static StatementMatcher integerComparisonMatcher()
static const Expr * findContainer(const 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.
bool areSameExpr(const ASTContext *Context, const Expr *First, const Expr *Second)
Returns true when two Exprs are equivalent.
const Expr * digThroughConstructorsConversions(const Expr *E)
Look through conversion/copy constructors and member functions to find the explicit initialization ex...
static bool containerIsConst(const Expr *ContainerExpr, bool Dereference)
Returns true if the container is const-qualified.
static constexpr char LoopNamePseudoArray[]
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 constexpr char InitVarName[]
static constexpr char LoopNameIterator[]
static constexpr char DerefByValueResultName[]
SmallVector< Usage, 8 > UsageResult
static bool isDirectMemberExpr(const Expr *E)
Returns true when the given expression is a member expression whose base is this (implicitly or not).
static StatementMatcher makeIteratorLoopMatcher(bool IsReverse)
The matcher used for iterator-based for loops.
static constexpr 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 bool requiresLeadingSpace(const SourceManager &SourceMgr, const LangOptions &LangOpts, SourceLocation BeginLocation)
static bool isPrecededByAdjacentIdentifierOrKeyword(const SourceManager &SourceMgr, const LangOptions &LangOpts, SourceLocation BeginLocation)
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...
The information needed to describe a valid convertible usage of an array index or iterator.