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 const auto BeginNameMatcher = IsReverse ? hasAnyName(
"rbegin",
"crbegin")
160 : hasAnyName(
"begin",
"cbegin");
161 const auto BeginNameMatcherStd =
162 IsReverse ? hasAnyName(
"::std::rbegin",
"::std::crbegin")
163 : hasAnyName(
"::std::begin",
"::std::cbegin");
165 const auto EndNameMatcher =
166 IsReverse ? hasAnyName(
"rend",
"crend") : hasAnyName(
"end",
"cend");
167 const auto EndNameMatcherStd = IsReverse
168 ? hasAnyName(
"::std::rend",
"::std::crend")
169 : hasAnyName(
"::std::end",
"::std::cend");
171 const StatementMatcher BeginCallMatcher =
172 expr(anyOf(cxxMemberCallExpr(argumentCountIs(0),
173 callee(cxxMethodDecl(BeginNameMatcher))),
174 callExpr(argumentCountIs(1),
175 callee(functionDecl(BeginNameMatcher)), usesADL()),
176 callExpr(argumentCountIs(1),
177 callee(functionDecl(BeginNameMatcherStd)))))
180 const DeclarationMatcher InitDeclMatcher =
181 varDecl(hasInitializer(anyOf(ignoringParenImpCasts(BeginCallMatcher),
182 materializeTemporaryExpr(
183 ignoringParenImpCasts(BeginCallMatcher)),
184 hasDescendant(BeginCallMatcher))))
187 const DeclarationMatcher EndDeclMatcher =
188 varDecl(hasInitializer(anything())).bind(
EndVarName);
190 const StatementMatcher EndCallMatcher = expr(anyOf(
191 cxxMemberCallExpr(argumentCountIs(0),
192 callee(cxxMethodDecl(EndNameMatcher))),
193 callExpr(argumentCountIs(1), callee(functionDecl(EndNameMatcher)),
195 callExpr(argumentCountIs(1), callee(functionDecl(EndNameMatcherStd)))));
197 const StatementMatcher IteratorBoundMatcher =
198 expr(anyOf(ignoringParenImpCasts(
199 declRefExpr(to(varDecl(equalsBoundNode(
EndVarName))))),
200 ignoringParenImpCasts(expr(EndCallMatcher).bind(
EndCallName)),
201 materializeTemporaryExpr(ignoringParenImpCasts(
204 const StatementMatcher IteratorComparisonMatcher = expr(ignoringParenImpCasts(
205 declRefExpr(to(varDecl(equalsBoundNode(
InitVarName))))));
210 const internal::Matcher<VarDecl> TestDerefReturnsByValue =
211 hasType(hasUnqualifiedDesugaredType(
212 recordType(hasDeclaration(cxxRecordDecl(hasMethod(cxxMethodDecl(
213 hasOverloadedOperatorName(
"*"),
216 returns(qualType(unless(hasCanonicalType(referenceType())))
221 qualType(unless(hasCanonicalType(rValueReferenceType())))
225 unless(isInTemplateInstantiation()),
226 hasLoopInit(anyOf(declStmt(declCountIs(2),
227 containsDeclaration(0, InitDeclMatcher),
228 containsDeclaration(1, EndDeclMatcher)),
229 declStmt(hasSingleDecl(InitDeclMatcher)))),
230 hasCondition(ignoringImplicit(binaryOperation(
231 hasOperatorName(
"!="), hasOperands(IteratorComparisonMatcher,
232 IteratorBoundMatcher)))),
234 unaryOperator(hasOperatorName(
"++"),
235 hasUnaryOperand(declRefExpr(
238 hasOverloadedOperatorName(
"++"),
239 hasArgument(0, declRefExpr(to(
241 TestDerefReturnsByValue))))))))
283 const TypeMatcher RecordWithBeginEnd = qualType(anyOf(
284 qualType(isConstQualified(),
285 hasUnqualifiedDesugaredType(recordType(hasDeclaration(
286 cxxRecordDecl(isSameOrDerivedFrom(cxxRecordDecl(
287 hasMethod(cxxMethodDecl(hasName(
"begin"), isConst())),
288 hasMethod(cxxMethodDecl(hasName(
"end"),
291 qualType(unless(isConstQualified()),
292 hasUnqualifiedDesugaredType(recordType(hasDeclaration(
293 cxxRecordDecl(isSameOrDerivedFrom(cxxRecordDecl(
294 hasMethod(hasName(
"begin")),
295 hasMethod(hasName(
"end")))))))))
298 const StatementMatcher SizeCallMatcher = expr(anyOf(
299 cxxMemberCallExpr(argumentCountIs(0),
300 callee(cxxMethodDecl(hasAnyName(
"size",
"length"))),
301 on(anyOf(hasType(pointsTo(RecordWithBeginEnd)),
302 hasType(RecordWithBeginEnd)))),
303 callExpr(argumentCountIs(1), callee(functionDecl(hasName(
"size"))),
305 callExpr(argumentCountIs(1),
306 callee(functionDecl(hasName(
"::std::size"))))));
308 StatementMatcher EndInitMatcher =
309 expr(anyOf(ignoringParenImpCasts(expr(SizeCallMatcher).bind(
EndCallName)),
310 explicitCastExpr(hasSourceExpression(ignoringParenImpCasts(
313 const DeclarationMatcher EndDeclMatcher =
314 varDecl(hasInitializer(EndInitMatcher)).bind(
EndVarName);
316 const StatementMatcher IndexBoundMatcher =
317 expr(anyOf(ignoringParenImpCasts(
318 declRefExpr(to(varDecl(equalsBoundNode(
EndVarName))))),
321 return forStmt(unless(isInTemplateInstantiation()),
323 anyOf(declStmt(declCountIs(2),
325 containsDeclaration(1, EndDeclMatcher)),
329 unaryOperator(hasOperatorName(
"++"),
336enum class IteratorCallKind {
342struct ContainerCall {
343 const Expr *Container;
346 IteratorCallKind CallKind;
362 IteratorCallKind CallKind = IteratorCallKind::ICK_Member;
364 if (
const auto *TheCall = dyn_cast_or_null<CXXMemberCallExpr>(Dug)) {
365 CallKind = IteratorCallKind::ICK_Member;
366 if (
const auto *Member = dyn_cast<MemberExpr>(TheCall->getCallee())) {
367 if (Member->getMemberDecl() ==
nullptr ||
368 !
MemberNames.contains(Member->getMemberDecl()->getName()))
370 return ContainerCall{TheCall->getImplicitObjectArgument(),
371 Member->getMemberDecl()->getName(),
372 Member->isArrow(), CallKind};
374 if (TheCall->getDirectCallee() ==
nullptr ||
375 !
MemberNames.contains(TheCall->getDirectCallee()->getName()))
377 return ContainerCall{TheCall->getArg(0),
378 TheCall->getDirectCallee()->getName(),
false,
381 if (
const auto *TheCall = dyn_cast_or_null<CallExpr>(Dug)) {
382 if (TheCall->getNumArgs() != 1)
385 if (TheCall->usesADL()) {
386 if (TheCall->getDirectCallee() ==
nullptr ||
387 !
ADLNames.contains(TheCall->getDirectCallee()->getName()))
389 CallKind = IteratorCallKind::ICK_ADL;
392 TheCall->getDirectCallee()->getQualifiedNameAsString()))
394 CallKind = IteratorCallKind::ICK_Std;
397 if (TheCall->getDirectCallee() ==
nullptr)
400 return ContainerCall{TheCall->getArg(0),
401 TheCall->getDirectCallee()->getName(),
false,
412static std::pair<const Expr *, IteratorCallKind>
421 *IsArrow = Call->IsArrow;
422 if (!Call->Name.consume_back(IsBegin ?
"begin" :
"end"))
424 if (IsReverse && !Call->Name.consume_back(
"r"))
426 if (!Call->Name.empty() && Call->Name !=
"c")
428 return {Call->Container, Call->CallKind};
437 const Expr *BeginExpr,
const Expr *EndExpr,
438 bool *ContainerNeedsDereference,
442 bool BeginIsArrow =
false;
443 bool EndIsArrow =
false;
445 BeginExpr,
true, &BeginIsArrow, IsReverse);
446 if (!BeginContainerExpr)
450 EndExpr,
false, &EndIsArrow, IsReverse);
451 if (BeginCallKind != EndCallKind)
456 if (!EndContainerExpr || BeginIsArrow != EndIsArrow ||
457 !
areSameExpr(Context, EndContainerExpr, BeginContainerExpr))
460 *ContainerNeedsDereference = BeginIsArrow;
461 return BeginContainerExpr;
466 const LangOptions &LangOpts,
468 if (SourceMgr.getFileID(Range.getBegin()) !=
469 SourceMgr.getFileID(Range.getEnd())) {
473 return Lexer::getSourceText(CharSourceRange(Range,
true), SourceMgr,
481 return dyn_cast<VarDecl>(DRE->getDecl());
482 if (
const auto *Mem = dyn_cast<MemberExpr>(E->IgnoreParenImpCasts()))
483 return dyn_cast<FieldDecl>(Mem->getMemberDecl());
490 if (
const auto *Member = dyn_cast<MemberExpr>(E->IgnoreParenImpCasts()))
491 return isa<CXXThisExpr>(Member->getBase()->IgnoreParenImpCasts());
499 if (E->getType().isConstQualified())
501 const auto Parents = Context->getParents(*E);
502 if (Parents.size() != 1)
504 if (
const auto *Cast = Parents[0].get<ImplicitCastExpr>();
506 ((Cast->getCastKind() == CK_NoOp &&
507 ASTContext::hasSameType(Cast->getType(), E->getType().withConst())) ||
508 (Cast->getCastKind() == CK_LValueToRValue && !Cast->getType().isNull() &&
509 Cast->getType()->isFundamentalType())))
519 return llvm::none_of(Usages, [&Context](
const Usage &U) {
534 return llvm::all_of(Usages, [](
const Usage &U) {
542 QualType CType = VDec->getType();
544 if (!CType->isPointerType())
546 CType = CType->getPointeeType();
551 CType = CType.getNonReferenceType();
552 return CType.isConstQualified();
561 const LangOptions &LangOpts,
562 SourceLocation BeginLocation) {
563 std::optional<Token> PrevToken =
564 Lexer::findPreviousToken(BeginLocation, SourceMgr, LangOpts,
true);
569 const bool IsAdjacentToPrevToken = PrevToken->getEndLoc() == BeginLocation;
570 return PrevToken->isAnyIdentifier() && IsAdjacentToPrevToken;
578 const LangOptions &LangOpts,
579 SourceLocation BeginLocation) {
581 if (!Lexer::getRawToken(BeginLocation, StarToken, SourceMgr, LangOpts,
583 StarToken.is(tok::star)) {
592 MaxCopySize(Options.get(
"MaxCopySize", 16ULL)),
593 MinConfidence(Options.get(
"MinConfidence",
Confidence::CL_Reasonable)),
594 NamingStyle(Options.get(
"NamingStyle",
VariableNamer::NS_CamelCase)),
595 Inserter(Options.getLocalOrGlobal(
"IncludeStyle",
596 utils::IncludeSorter::IS_LLVM),
597 areDiagsSelfContained()),
598 UseCxx20IfAvailable(Options.get(
"UseCxx20ReverseRanges", true)),
599 ReverseFunction(Options.get(
"MakeReverseRangeFunction",
"")),
600 ReverseHeader(Options.get(
"MakeReverseRangeHeader",
"")) {
601 if (ReverseFunction.empty() && !ReverseHeader.empty()) {
603 "modernize-loop-convert: 'MakeReverseRangeHeader' is set but "
604 "'MakeReverseRangeFunction' is not, disabling reverse loop "
606 UseReverseRanges = false;
607 }
else if (ReverseFunction.empty()) {
608 UseReverseRanges = UseCxx20IfAvailable && getLangOpts().CPlusPlus20;
610 UseReverseRanges = true;
615 Options.store(Opts,
"MaxCopySize", MaxCopySize);
616 Options.store(Opts,
"MinConfidence", MinConfidence);
617 Options.store(Opts,
"NamingStyle", NamingStyle);
618 Options.store(Opts,
"IncludeStyle", Inserter.getStyle());
619 Options.store(Opts,
"UseCxx20ReverseRanges", UseCxx20IfAvailable);
620 Options.store(Opts,
"MakeReverseRangeFunction", ReverseFunction);
621 Options.store(Opts,
"MakeReverseRangeHeader", ReverseHeader);
626 Preprocessor *ModuleExpanderPP) {
627 Inserter.registerPreprocessor(PP);
634 if (UseReverseRanges)
651void LoopConvertCheck::getAliasRange(SourceManager &SM, SourceRange &Range) {
652 bool Invalid =
false;
653 const char *TextAfter =
654 SM.getCharacterData(Range.getEnd().getLocWithOffset(1), &Invalid);
657 const unsigned Offset = std::strspn(TextAfter,
" \t\r\n");
659 SourceRange(Range.getBegin(), Range.getEnd().getLocWithOffset(Offset));
664void LoopConvertCheck::doConversion(
665 ASTContext *Context,
const VarDecl *IndexVar,
666 const ValueDecl *MaybeContainer,
const UsageResult &Usages,
667 const DeclStmt *AliasDecl,
bool AliasUseRequired,
bool AliasFromForInit,
668 const ForStmt *Loop, RangeDescriptor Descriptor) {
669 std::string VarNameOrStructuredBinding;
670 const bool VarNameFromAlias = (Usages.size() == 1) && AliasDecl;
671 bool AliasVarIsRef =
false;
673 std::vector<FixItHint> FixIts;
674 if (VarNameFromAlias) {
675 const auto *AliasVar = cast<VarDecl>(AliasDecl->getSingleDecl());
678 if (
const auto *AliasDecompositionDecl =
679 dyn_cast<DecompositionDecl>(AliasDecl->getSingleDecl())) {
680 VarNameOrStructuredBinding =
"[";
682 assert(!AliasDecompositionDecl->bindings().empty() &&
"No bindings");
683 for (
const BindingDecl *Binding : AliasDecompositionDecl->bindings())
684 VarNameOrStructuredBinding += Binding->getName().str() +
", ";
686 VarNameOrStructuredBinding.erase(VarNameOrStructuredBinding.size() - 2,
688 VarNameOrStructuredBinding +=
']';
690 VarNameOrStructuredBinding = AliasVar->getName().str();
693 QualType AliasVarType = AliasVar->getType();
694 assert(!AliasVarType.isNull() &&
"Type in VarDecl is null");
695 if (AliasVarType->isReferenceType()) {
696 AliasVarType = AliasVarType.getNonReferenceType();
697 AliasVarIsRef =
true;
699 if (Descriptor.ElemType.isNull() ||
700 !ASTContext::hasSameUnqualifiedType(AliasVarType,
701 Descriptor.ElemType))
702 Descriptor.ElemType = AliasVarType;
706 SourceRange ReplaceRange = AliasDecl->getSourceRange();
708 std::string ReplacementText;
709 if (AliasUseRequired) {
710 ReplacementText = VarNameOrStructuredBinding;
711 }
else if (AliasFromForInit) {
715 ReplacementText =
";";
718 getAliasRange(Context->getSourceManager(), ReplaceRange);
721 FixIts.push_back(FixItHint::CreateReplacement(
722 CharSourceRange::getTokenRange(ReplaceRange), ReplacementText));
726 VariableNamer Namer(&TUInfo->getGeneratedDecls(),
727 &TUInfo->getParentFinder().getStmtToParentStmtMap(),
728 Loop, IndexVar, MaybeContainer, Context, NamingStyle);
729 VarNameOrStructuredBinding = Namer.createIndexName();
732 for (
const auto &
Usage : Usages) {
733 std::string ReplaceText;
734 SourceRange Range =
Usage.Range;
735 if (
Usage.Expression) {
738 Usage.Range.getBegin()))
743 ? VarNameOrStructuredBinding +
"."
744 : VarNameOrStructuredBinding;
745 const DynTypedNodeList
Parents = Context->getParents(*
Usage.Expression);
747 if (
const auto *Paren = Parents[0].get<ParenExpr>()) {
751 const DynTypedNodeList GrandParents = Context->getParents(*Paren);
752 if (GrandParents.size() != 1 ||
753 (GrandParents[0].get<UnaryExprOrTypeTraitExpr>() ==
nullptr &&
755 Context->getSourceManager(), getLangOpts(),
756 Parents[0].getSourceRange().getBegin()))) {
757 Range = Paren->getSourceRange();
759 }
else if (
const auto *UOP = Parents[0].get<UnaryOperator>();
760 UOP && UOP->getOpcode() == UO_AddrOf) {
776 ?
"&" + VarNameOrStructuredBinding
777 : VarNameOrStructuredBinding;
779 TUInfo->getReplacedVars().try_emplace(Loop, IndexVar);
780 FixIts.push_back(FixItHint::CreateReplacement(
781 CharSourceRange::getTokenRange(Range), ReplaceText));
786 const SourceRange ParenRange(Loop->getLParenLoc(), Loop->getRParenLoc());
788 QualType
Type = Context->getAutoDeductType();
789 if (!Descriptor.ElemType.isNull() && Descriptor.ElemType->isFundamentalType())
790 Type = Descriptor.ElemType.getUnqualifiedType();
791 Type =
Type.getDesugaredType(*Context);
796 const bool IsCheapToCopy =
797 !Descriptor.ElemType.isNull() &&
798 Descriptor.ElemType.isTriviallyCopyableType(*Context) &&
799 !Descriptor.ElemType->isDependentSizedArrayType() &&
801 Context->getTypeInfo(Descriptor.ElemType).Width <= 8 * MaxCopySize;
803 CanCopy && ((VarNameFromAlias && !AliasVarIsRef) ||
804 (Descriptor.DerefByConstRef && IsCheapToCopy));
807 if (Descriptor.DerefByConstRef) {
808 Type = Context->getLValueReferenceType(Context->getConstType(Type));
809 }
else if (Descriptor.DerefByValue) {
811 Type = Context->getRValueReferenceType(Type);
813 Type = Context->getLValueReferenceType(Type);
817 SmallString<128> Range;
818 llvm::raw_svector_ostream Output(Range);
820 Type.print(Output, getLangOpts());
821 Output <<
' ' << VarNameOrStructuredBinding <<
" : ";
822 if (Descriptor.NeedsReverseCall)
823 Output << getReverseFunction() <<
'(';
824 if (Descriptor.ContainerNeedsDereference)
826 Output << Descriptor.ContainerString;
827 if (Descriptor.NeedsReverseCall)
831 FixIts.push_back(FixItHint::CreateReplacement(
832 CharSourceRange::getTokenRange(ParenRange), Range));
834 if (Descriptor.NeedsReverseCall && !getReverseHeader().
empty()) {
835 if (std::optional<FixItHint> Insertion = Inserter.createIncludeInsertion(
836 Context->getSourceManager().getFileID(Loop->getBeginLoc()),
838 FixIts.push_back(*Insertion);
840 diag(Loop->getForLoc(),
"use range-based for loop instead") << FixIts;
841 TUInfo->getGeneratedDecls().try_emplace(Loop, VarNameOrStructuredBinding);
845StringRef LoopConvertCheck::getContainerString(ASTContext *Context,
847 const Expr *ContainerExpr) {
848 StringRef ContainerString;
849 ContainerExpr = ContainerExpr->IgnoreParenImpCasts();
850 if (isa<CXXThisExpr>(ContainerExpr)) {
851 ContainerString =
"this";
855 if (
const auto *E = dyn_cast<CXXOperatorCallExpr>(ContainerExpr);
856 E && E->getOperator() != OO_Subscript)
857 ContainerExpr = E->getArg(0);
860 ContainerExpr->getSourceRange());
863 return ContainerString;
868void LoopConvertCheck::getArrayLoopQualifiers(ASTContext *Context,
869 const BoundNodes &Nodes,
870 const Expr *ContainerExpr,
872 RangeDescriptor &Descriptor) {
877 Descriptor.DerefByConstRef =
true;
883 Descriptor.DerefByValue =
true;
887 for (
const Usage &U : Usages) {
888 if (!U.Expression || U.Expression->getType().isNull())
890 QualType
Type = U.Expression->getType().getCanonicalType();
892 if (!
Type->isPointerType())
896 Descriptor.ElemType =
Type;
902void LoopConvertCheck::getIteratorLoopQualifiers(ASTContext *Context,
903 const BoundNodes &Nodes,
904 RangeDescriptor &Descriptor) {
907 const auto *InitVar = Nodes.getNodeAs<VarDecl>(
InitVarName);
908 const QualType CanonicalInitVarType = InitVar->getType().getCanonicalType();
909 const auto *DerefByValueType =
911 Descriptor.DerefByValue = DerefByValueType;
913 if (Descriptor.DerefByValue) {
916 Descriptor.DerefByConstRef = CanonicalInitVarType.isConstQualified();
917 Descriptor.ElemType = *DerefByValueType;
918 }
else if (
const auto *DerefType =
923 const auto ValueType = DerefType->getNonReferenceType();
925 Descriptor.DerefByConstRef = ValueType.isConstQualified();
926 Descriptor.ElemType = ValueType;
930 assert(isa<PointerType>(CanonicalInitVarType) &&
931 "Non-class iterator type is not a pointer type");
934 Descriptor.DerefByConstRef =
935 CanonicalInitVarType->getPointeeType().isConstQualified();
936 Descriptor.ElemType = CanonicalInitVarType->getPointeeType();
941void LoopConvertCheck::determineRangeDescriptor(
942 ASTContext *Context,
const BoundNodes &Nodes,
const ForStmt *Loop,
944 const UsageResult &Usages, RangeDescriptor &Descriptor) {
945 Descriptor.ContainerString =
946 std::string(getContainerString(Context, Loop, ContainerExpr));
950 getIteratorLoopQualifiers(Context, Nodes, Descriptor);
952 getArrayLoopQualifiers(Context, Nodes, ContainerExpr, Usages, Descriptor);
957bool LoopConvertCheck::isConvertible(ASTContext *Context,
958 const ast_matchers::BoundNodes &Nodes,
964 if (areDiagsSelfContained())
965 TUInfo = std::make_unique<TUTrackingInfo>();
966 else if (TUInfo->getReplacedVars().contains(Loop))
970 const auto *InitVar = Nodes.getNodeAs<VarDecl>(
InitVarName);
974 const QualType InitVarType = InitVar->getType();
975 const QualType CanonicalInitVarType = InitVarType.getCanonicalType();
977 const auto *BeginCall = Nodes.getNodeAs<CallExpr>(
BeginCallName);
978 assert(BeginCall &&
"Bad Callback. No begin call expression");
979 const QualType CanonicalBeginType =
980 BeginCall->getDirectCallee()->getReturnType().getCanonicalType();
981 if (CanonicalBeginType->isPointerType() &&
982 CanonicalInitVarType->isPointerType()) {
985 return ASTContext::hasSameUnqualifiedType(
986 CanonicalBeginType->getPointeeType(),
987 CanonicalInitVarType->getPointeeType());
990 if (CanonicalBeginType->isBuiltinType() ||
991 CanonicalInitVarType->isBuiltinType())
995 if (
const auto *EndCall = Nodes.getNodeAs<CXXMemberCallExpr>(
EndCallName);
996 EndCall && !isa<MemberExpr>(EndCall->getCallee()))
1000 return Nodes.getNodeAs<CallExpr>(
EndCallName) !=
nullptr;
1006 const BoundNodes &Nodes = Result.Nodes;
1008 ASTContext *Context = Result.Context;
1010 const ForStmt *Loop =
nullptr;
1012 RangeDescriptor Descriptor;
1022 assert(Loop &&
"Bad Callback. No for statement");
1026 if (!isConvertible(Context, Nodes, Loop, FixerKind))
1029 const auto *LoopVar = Nodes.getNodeAs<VarDecl>(
InitVarName);
1030 const auto *EndVar = Nodes.getNodeAs<VarDecl>(
EndVarName);
1039 const auto *EndCall = Nodes.getNodeAs<Expr>(
EndCallName);
1046 const Expr *ContainerExpr =
nullptr;
1049 Context, LoopVar->getInit(), EndVar ? EndVar->getInit() : EndCall,
1050 &Descriptor.ContainerNeedsDereference,
1055 ContainerExpr = Call->Container;
1056 Descriptor.ContainerNeedsDereference = Call->IsArrow;
1061 if (!ContainerExpr && !BoundExpr)
1066 Descriptor.ContainerNeedsDereference);
1069 if (ContainerExpr) {
1094 const TraversalKindScope RAII(*Context, TK_AsIs);
1096 determineRangeDescriptor(Context, Nodes, Loop, FixerKind, ContainerExpr,
1097 Usages, Descriptor);
1103 TUInfo->getParentFinder().gatherAncestors(*Context);
1105 &TUInfo->getParentFinder().getStmtToParentStmtMap(),
1106 &TUInfo->getParentFinder().getDeclToParentStmtMap(),
1107 &TUInfo->getReplacedVars(), Loop);
1110 Descriptor.ContainerString.empty() || Usages.empty() ||
1111 ConfidenceLevel.
getLevel() < MinConfidence)
1119StringRef LoopConvertCheck::getReverseFunction()
const {
1120 if (!ReverseFunction.empty())
1121 return ReverseFunction;
1122 if (UseReverseRanges)
1123 return "std::views::reverse";
1127StringRef LoopConvertCheck::getReverseHeader()
const {
1128 if (!ReverseHeader.empty())
1129 return ReverseHeader;
1130 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.