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};
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();
557 MaxCopySize(Options.get(
"MaxCopySize", 16ULL)),
558 MinConfidence(Options.get(
"MinConfidence",
Confidence::CL_Reasonable)),
559 NamingStyle(Options.get(
"NamingStyle",
VariableNamer::NS_CamelCase)),
560 Inserter(Options.getLocalOrGlobal(
"IncludeStyle",
561 utils::IncludeSorter::IS_LLVM),
562 areDiagsSelfContained()),
563 UseCxx20IfAvailable(Options.get(
"UseCxx20ReverseRanges", true)),
564 ReverseFunction(Options.get(
"MakeReverseRangeFunction",
"")),
565 ReverseHeader(Options.get(
"MakeReverseRangeHeader",
"")) {
566 if (ReverseFunction.empty() && !ReverseHeader.empty()) {
568 "modernize-loop-convert: 'MakeReverseRangeHeader' is set but "
569 "'MakeReverseRangeFunction' is not, disabling reverse loop "
571 UseReverseRanges = false;
572 }
else if (ReverseFunction.empty()) {
573 UseReverseRanges = UseCxx20IfAvailable && getLangOpts().CPlusPlus20;
575 UseReverseRanges = true;
580 Options.store(Opts,
"MaxCopySize", MaxCopySize);
581 Options.store(Opts,
"MinConfidence", MinConfidence);
582 Options.store(Opts,
"NamingStyle", NamingStyle);
583 Options.store(Opts,
"IncludeStyle", Inserter.getStyle());
584 Options.store(Opts,
"UseCxx20ReverseRanges", UseCxx20IfAvailable);
585 Options.store(Opts,
"MakeReverseRangeFunction", ReverseFunction);
586 Options.store(Opts,
"MakeReverseRangeHeader", ReverseHeader);
591 Preprocessor *ModuleExpanderPP) {
592 Inserter.registerPreprocessor(PP);
599 if (UseReverseRanges)
616void LoopConvertCheck::getAliasRange(SourceManager &SM, SourceRange &Range) {
617 bool Invalid =
false;
618 const char *TextAfter =
619 SM.getCharacterData(Range.getEnd().getLocWithOffset(1), &Invalid);
622 const unsigned Offset = std::strspn(TextAfter,
" \t\r\n");
624 SourceRange(Range.getBegin(), Range.getEnd().getLocWithOffset(Offset));
629void LoopConvertCheck::doConversion(
630 ASTContext *Context,
const VarDecl *IndexVar,
631 const ValueDecl *MaybeContainer,
const UsageResult &Usages,
632 const DeclStmt *AliasDecl,
bool AliasUseRequired,
bool AliasFromForInit,
633 const ForStmt *Loop, RangeDescriptor Descriptor) {
634 std::string VarNameOrStructuredBinding;
635 const bool VarNameFromAlias = (Usages.size() == 1) && AliasDecl;
636 bool AliasVarIsRef =
false;
638 std::vector<FixItHint> FixIts;
639 if (VarNameFromAlias) {
640 const auto *AliasVar = cast<VarDecl>(AliasDecl->getSingleDecl());
643 if (
const auto *AliasDecompositionDecl =
644 dyn_cast<DecompositionDecl>(AliasDecl->getSingleDecl())) {
645 VarNameOrStructuredBinding =
"[";
647 assert(!AliasDecompositionDecl->bindings().empty() &&
"No bindings");
648 for (
const BindingDecl *Binding : AliasDecompositionDecl->bindings())
649 VarNameOrStructuredBinding += Binding->getName().str() +
", ";
651 VarNameOrStructuredBinding.erase(VarNameOrStructuredBinding.size() - 2,
653 VarNameOrStructuredBinding +=
"]";
655 VarNameOrStructuredBinding = AliasVar->getName().str();
658 QualType AliasVarType = AliasVar->getType();
659 assert(!AliasVarType.isNull() &&
"Type in VarDecl is null");
660 if (AliasVarType->isReferenceType()) {
661 AliasVarType = AliasVarType.getNonReferenceType();
662 AliasVarIsRef =
true;
664 if (Descriptor.ElemType.isNull() ||
665 !ASTContext::hasSameUnqualifiedType(AliasVarType,
666 Descriptor.ElemType))
667 Descriptor.ElemType = AliasVarType;
671 SourceRange ReplaceRange = AliasDecl->getSourceRange();
673 std::string ReplacementText;
674 if (AliasUseRequired) {
675 ReplacementText = VarNameOrStructuredBinding;
676 }
else if (AliasFromForInit) {
680 ReplacementText =
";";
683 getAliasRange(Context->getSourceManager(), ReplaceRange);
686 FixIts.push_back(FixItHint::CreateReplacement(
687 CharSourceRange::getTokenRange(ReplaceRange), ReplacementText));
691 VariableNamer Namer(&TUInfo->getGeneratedDecls(),
692 &TUInfo->getParentFinder().getStmtToParentStmtMap(),
693 Loop, IndexVar, MaybeContainer, Context, NamingStyle);
694 VarNameOrStructuredBinding = Namer.createIndexName();
697 for (
const auto &
Usage : Usages) {
698 std::string ReplaceText;
699 SourceRange Range =
Usage.Range;
700 if (
Usage.Expression) {
704 ? VarNameOrStructuredBinding +
"."
705 : VarNameOrStructuredBinding;
706 const DynTypedNodeList
Parents = Context->getParents(*
Usage.Expression);
708 if (
const auto *Paren = Parents[0].get<ParenExpr>()) {
712 const DynTypedNodeList GrandParents = Context->getParents(*Paren);
713 if (GrandParents.size() != 1 ||
714 GrandParents[0].get<UnaryExprOrTypeTraitExpr>() ==
nullptr) {
715 Range = Paren->getSourceRange();
717 }
else if (
const auto *UOP = Parents[0].get<UnaryOperator>()) {
725 if (UOP->getOpcode() == UO_AddrOf)
734 ?
"&" + VarNameOrStructuredBinding
735 : VarNameOrStructuredBinding;
737 TUInfo->getReplacedVars().try_emplace(Loop, IndexVar);
738 FixIts.push_back(FixItHint::CreateReplacement(
739 CharSourceRange::getTokenRange(Range), ReplaceText));
744 const SourceRange ParenRange(Loop->getLParenLoc(), Loop->getRParenLoc());
746 QualType
Type = Context->getAutoDeductType();
747 if (!Descriptor.ElemType.isNull() && Descriptor.ElemType->isFundamentalType())
748 Type = Descriptor.ElemType.getUnqualifiedType();
749 Type =
Type.getDesugaredType(*Context);
754 const bool IsCheapToCopy =
755 !Descriptor.ElemType.isNull() &&
756 Descriptor.ElemType.isTriviallyCopyableType(*Context) &&
757 !Descriptor.ElemType->isDependentSizedArrayType() &&
759 Context->getTypeInfo(Descriptor.ElemType).Width <= 8 * MaxCopySize;
761 CanCopy && ((VarNameFromAlias && !AliasVarIsRef) ||
762 (Descriptor.DerefByConstRef && IsCheapToCopy));
765 if (Descriptor.DerefByConstRef) {
766 Type = Context->getLValueReferenceType(Context->getConstType(Type));
767 }
else if (Descriptor.DerefByValue) {
769 Type = Context->getRValueReferenceType(Type);
771 Type = Context->getLValueReferenceType(Type);
775 SmallString<128> Range;
776 llvm::raw_svector_ostream Output(Range);
778 Type.print(Output, getLangOpts());
779 Output <<
' ' << VarNameOrStructuredBinding <<
" : ";
780 if (Descriptor.NeedsReverseCall)
781 Output << getReverseFunction() <<
'(';
782 if (Descriptor.ContainerNeedsDereference)
784 Output << Descriptor.ContainerString;
785 if (Descriptor.NeedsReverseCall)
789 FixIts.push_back(FixItHint::CreateReplacement(
790 CharSourceRange::getTokenRange(ParenRange), Range));
792 if (Descriptor.NeedsReverseCall && !getReverseHeader().
empty()) {
793 if (std::optional<FixItHint> Insertion = Inserter.createIncludeInsertion(
794 Context->getSourceManager().getFileID(Loop->getBeginLoc()),
796 FixIts.push_back(*Insertion);
798 diag(Loop->getForLoc(),
"use range-based for loop instead") << FixIts;
799 TUInfo->getGeneratedDecls().try_emplace(Loop, VarNameOrStructuredBinding);
803StringRef LoopConvertCheck::getContainerString(ASTContext *Context,
805 const Expr *ContainerExpr) {
806 StringRef ContainerString;
807 ContainerExpr = ContainerExpr->IgnoreParenImpCasts();
808 if (isa<CXXThisExpr>(ContainerExpr)) {
809 ContainerString =
"this";
813 if (
const auto *E = dyn_cast<CXXOperatorCallExpr>(ContainerExpr))
814 if (E->getOperator() != OO_Subscript)
815 ContainerExpr = E->getArg(0);
818 ContainerExpr->getSourceRange());
821 return ContainerString;
826void LoopConvertCheck::getArrayLoopQualifiers(ASTContext *Context,
827 const BoundNodes &Nodes,
828 const Expr *ContainerExpr,
830 RangeDescriptor &Descriptor) {
835 Descriptor.DerefByConstRef =
true;
841 Descriptor.DerefByValue =
true;
845 for (
const Usage &U : Usages) {
846 if (!U.Expression || U.Expression->getType().isNull())
848 QualType
Type = U.Expression->getType().getCanonicalType();
850 if (!
Type->isPointerType())
854 Descriptor.ElemType =
Type;
860void LoopConvertCheck::getIteratorLoopQualifiers(ASTContext *Context,
861 const BoundNodes &Nodes,
862 RangeDescriptor &Descriptor) {
865 const auto *InitVar = Nodes.getNodeAs<VarDecl>(
InitVarName);
866 const QualType CanonicalInitVarType = InitVar->getType().getCanonicalType();
867 const auto *DerefByValueType =
869 Descriptor.DerefByValue = DerefByValueType;
871 if (Descriptor.DerefByValue) {
874 Descriptor.DerefByConstRef = CanonicalInitVarType.isConstQualified();
875 Descriptor.ElemType = *DerefByValueType;
876 }
else if (
const auto *DerefType =
881 auto ValueType = DerefType->getNonReferenceType();
883 Descriptor.DerefByConstRef = ValueType.isConstQualified();
884 Descriptor.ElemType = ValueType;
888 assert(isa<PointerType>(CanonicalInitVarType) &&
889 "Non-class iterator type is not a pointer type");
892 Descriptor.DerefByConstRef =
893 CanonicalInitVarType->getPointeeType().isConstQualified();
894 Descriptor.ElemType = CanonicalInitVarType->getPointeeType();
899void LoopConvertCheck::determineRangeDescriptor(
900 ASTContext *Context,
const BoundNodes &Nodes,
const ForStmt *Loop,
902 const UsageResult &Usages, RangeDescriptor &Descriptor) {
903 Descriptor.ContainerString =
904 std::string(getContainerString(Context, Loop, ContainerExpr));
908 getIteratorLoopQualifiers(Context, Nodes, Descriptor);
910 getArrayLoopQualifiers(Context, Nodes, ContainerExpr, Usages, Descriptor);
915bool LoopConvertCheck::isConvertible(ASTContext *Context,
916 const ast_matchers::BoundNodes &Nodes,
922 if (areDiagsSelfContained())
923 TUInfo = std::make_unique<TUTrackingInfo>();
924 else if (TUInfo->getReplacedVars().contains(Loop))
928 const auto *InitVar = Nodes.getNodeAs<VarDecl>(
InitVarName);
932 const QualType InitVarType = InitVar->getType();
933 const QualType CanonicalInitVarType = InitVarType.getCanonicalType();
935 const auto *BeginCall = Nodes.getNodeAs<CallExpr>(
BeginCallName);
936 assert(BeginCall &&
"Bad Callback. No begin call expression");
937 const QualType CanonicalBeginType =
938 BeginCall->getDirectCallee()->getReturnType().getCanonicalType();
939 if (CanonicalBeginType->isPointerType() &&
940 CanonicalInitVarType->isPointerType()) {
943 return ASTContext::hasSameUnqualifiedType(
944 CanonicalBeginType->getPointeeType(),
945 CanonicalInitVarType->getPointeeType());
948 if (CanonicalBeginType->isBuiltinType() ||
949 CanonicalInitVarType->isBuiltinType())
953 if (
const auto *EndCall = Nodes.getNodeAs<CXXMemberCallExpr>(
EndCallName)) {
955 if (!isa<MemberExpr>(EndCall->getCallee()))
958 return Nodes.getNodeAs<CallExpr>(
EndCallName) !=
nullptr;
964 const BoundNodes &Nodes = Result.Nodes;
966 ASTContext *Context = Result.Context;
968 const ForStmt *Loop =
nullptr;
970 RangeDescriptor Descriptor;
980 assert(Loop &&
"Bad Callback. No for statement");
984 if (!isConvertible(Context, Nodes, Loop, FixerKind))
987 const auto *LoopVar = Nodes.getNodeAs<VarDecl>(
InitVarName);
988 const auto *EndVar = Nodes.getNodeAs<VarDecl>(
EndVarName);
997 const auto *EndCall = Nodes.getNodeAs<Expr>(
EndCallName);
1004 const Expr *ContainerExpr =
nullptr;
1007 Context, LoopVar->getInit(), EndVar ? EndVar->getInit() : EndCall,
1008 &Descriptor.ContainerNeedsDereference,
1013 ContainerExpr = Call->Container;
1014 Descriptor.ContainerNeedsDereference = Call->IsArrow;
1019 if (!ContainerExpr && !BoundExpr)
1024 Descriptor.ContainerNeedsDereference);
1027 if (ContainerExpr) {
1052 const TraversalKindScope RAII(*Context, TK_AsIs);
1054 determineRangeDescriptor(Context, Nodes, Loop, FixerKind, ContainerExpr,
1055 Usages, Descriptor);
1061 TUInfo->getParentFinder().gatherAncestors(*Context);
1063 &TUInfo->getParentFinder().getStmtToParentStmtMap(),
1064 &TUInfo->getParentFinder().getDeclToParentStmtMap(),
1065 &TUInfo->getReplacedVars(), Loop);
1068 Descriptor.ContainerString.empty() || Usages.empty() ||
1069 ConfidenceLevel.
getLevel() < MinConfidence)
1077llvm::StringRef LoopConvertCheck::getReverseFunction()
const {
1078 if (!ReverseFunction.empty())
1079 return ReverseFunction;
1080 if (UseReverseRanges)
1081 return "std::views::reverse";
1085llvm::StringRef LoopConvertCheck::getReverseHeader()
const {
1086 if (!ReverseHeader.empty())
1087 return ReverseHeader;
1088 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 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.
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[]
llvm::SmallVector< Usage, 8 > UsageResult
static StringRef getStringFromRange(SourceManager &SourceMgr, const LangOptions &LangOpts, SourceRange Range)
Obtain the original source code text from a SourceRange.
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 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()
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 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 constexpr char InitVarName[]
static constexpr char LoopNameIterator[]
static constexpr char DerefByValueResultName[]
bool areSameExpr(ASTContext *Context, const Expr *First, const Expr *Second)
Returns true when two Exprs are equivalent.
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.
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.