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(
"++"),
359 if (
const auto *TheCall = dyn_cast_or_null<CXXMemberCallExpr>(Dug)) {
361 if (
const auto *Member = dyn_cast<MemberExpr>(TheCall->getCallee())) {
362 if (Member->getMemberDecl() ==
nullptr ||
363 !
MemberNames.contains(Member->getMemberDecl()->getName()))
366 Member->getMemberDecl()->getName(),
367 Member->isArrow(), CallKind};
369 if (TheCall->getDirectCallee() ==
nullptr ||
370 !
MemberNames.contains(TheCall->getDirectCallee()->getName()))
373 TheCall->getDirectCallee()->getName(),
false,
376 if (
const auto *TheCall = dyn_cast_or_null<CallExpr>(Dug)) {
377 if (TheCall->getNumArgs() != 1)
380 if (TheCall->usesADL()) {
381 if (TheCall->getDirectCallee() ==
nullptr ||
382 !
ADLNames.contains(TheCall->getDirectCallee()->getName()))
387 TheCall->getDirectCallee()->getQualifiedNameAsString()))
392 if (TheCall->getDirectCallee() ==
nullptr)
396 TheCall->getDirectCallee()->getName(),
false,
407static std::pair<const Expr *, IteratorCallKind>
416 *IsArrow = Call->IsArrow;
417 if (!Call->Name.consume_back(IsBegin ?
"begin" :
"end"))
419 if (IsReverse && !Call->Name.consume_back(
"r"))
421 if (!Call->Name.empty() && Call->Name !=
"c")
423 return std::make_pair(Call->Container, Call->CallKind);
433 bool *ContainerNeedsDereference,
437 bool BeginIsArrow =
false;
438 bool EndIsArrow =
false;
440 BeginExpr,
true, &BeginIsArrow, IsReverse);
441 if (!BeginContainerExpr)
445 EndExpr,
false, &EndIsArrow, IsReverse);
446 if (BeginCallKind != EndCallKind)
451 if (!EndContainerExpr || BeginIsArrow != EndIsArrow ||
452 !
areSameExpr(Context, EndContainerExpr, BeginContainerExpr))
455 *ContainerNeedsDereference = BeginIsArrow;
456 return BeginContainerExpr;
461 const LangOptions &LangOpts,
463 if (SourceMgr.getFileID(Range.getBegin()) !=
464 SourceMgr.getFileID(Range.getEnd())) {
468 return Lexer::getSourceText(CharSourceRange(Range,
true), SourceMgr,
476 return dyn_cast<VarDecl>(DRE->getDecl());
477 if (
const auto *Mem = dyn_cast<MemberExpr>(E->IgnoreParenImpCasts()))
478 return dyn_cast<FieldDecl>(Mem->getMemberDecl());
485 if (
const auto *Member = dyn_cast<MemberExpr>(E->IgnoreParenImpCasts()))
486 return isa<CXXThisExpr>(Member->getBase()->IgnoreParenImpCasts());
494 if (E->getType().isConstQualified())
496 auto Parents = Context->getParents(*E);
497 if (Parents.size() != 1)
499 if (
const auto *Cast = Parents[0].get<ImplicitCastExpr>()) {
500 if ((Cast->getCastKind() == CK_NoOp &&
501 ASTContext::hasSameType(Cast->getType(), E->getType().withConst())) ||
502 (Cast->getCastKind() == CK_LValueToRValue &&
503 !Cast->getType().isNull() && Cast->getType()->isFundamentalType()))
513 return llvm::none_of(Usages, [&Context](
const Usage &U) {
528 return llvm::all_of(Usages, [](
const Usage &U) {
536 QualType CType = VDec->getType();
538 if (!CType->isPointerType())
540 CType = CType->getPointeeType();
545 CType = CType.getNonReferenceType();
546 return CType.isConstQualified();
553 MaxCopySize(Options.get(
"MaxCopySize", 16ULL)),
554 MinConfidence(Options.get(
"MinConfidence",
Confidence::CL_Reasonable)),
555 NamingStyle(Options.get(
"NamingStyle",
VariableNamer::NS_CamelCase)),
556 Inserter(Options.getLocalOrGlobal(
"IncludeStyle",
557 utils::IncludeSorter::IS_LLVM),
558 areDiagsSelfContained()),
559 UseCxx20IfAvailable(Options.get(
"UseCxx20ReverseRanges", true)),
560 ReverseFunction(Options.get(
"MakeReverseRangeFunction",
"")),
561 ReverseHeader(Options.get(
"MakeReverseRangeHeader",
"")) {
562 if (ReverseFunction.empty() && !ReverseHeader.empty()) {
564 "modernize-loop-convert: 'MakeReverseRangeHeader' is set but "
565 "'MakeReverseRangeFunction' is not, disabling reverse loop "
567 UseReverseRanges = false;
568 }
else if (ReverseFunction.empty()) {
569 UseReverseRanges = UseCxx20IfAvailable && getLangOpts().CPlusPlus20;
571 UseReverseRanges = true;
576 Options.store(Opts,
"MaxCopySize", MaxCopySize);
577 Options.store(Opts,
"MinConfidence", MinConfidence);
578 Options.store(Opts,
"NamingStyle", NamingStyle);
579 Options.store(Opts,
"IncludeStyle", Inserter.getStyle());
580 Options.store(Opts,
"UseCxx20ReverseRanges", UseCxx20IfAvailable);
581 Options.store(Opts,
"MakeReverseRangeFunction", ReverseFunction);
582 Options.store(Opts,
"MakeReverseRangeHeader", ReverseHeader);
587 Preprocessor *ModuleExpanderPP) {
588 Inserter.registerPreprocessor(PP);
595 if (UseReverseRanges)
612void LoopConvertCheck::getAliasRange(SourceManager &SM, SourceRange &Range) {
613 bool Invalid =
false;
614 const char *TextAfter =
615 SM.getCharacterData(Range.getEnd().getLocWithOffset(1), &Invalid);
618 const unsigned Offset = std::strspn(TextAfter,
" \t\r\n");
620 SourceRange(Range.getBegin(), Range.getEnd().getLocWithOffset(Offset));
625void LoopConvertCheck::doConversion(
626 ASTContext *Context,
const VarDecl *IndexVar,
627 const ValueDecl *MaybeContainer,
const UsageResult &Usages,
628 const DeclStmt *AliasDecl,
bool AliasUseRequired,
bool AliasFromForInit,
629 const ForStmt *Loop, RangeDescriptor Descriptor) {
630 std::string VarNameOrStructuredBinding;
631 const bool VarNameFromAlias = (Usages.size() == 1) && AliasDecl;
632 bool AliasVarIsRef =
false;
634 std::vector<FixItHint> FixIts;
635 if (VarNameFromAlias) {
636 const auto *AliasVar = cast<VarDecl>(AliasDecl->getSingleDecl());
639 if (
const auto *AliasDecompositionDecl =
640 dyn_cast<DecompositionDecl>(AliasDecl->getSingleDecl())) {
641 VarNameOrStructuredBinding =
"[";
643 assert(!AliasDecompositionDecl->bindings().empty() &&
"No bindings");
644 for (
const BindingDecl *Binding : AliasDecompositionDecl->bindings()) {
645 VarNameOrStructuredBinding += Binding->getName().str() +
", ";
648 VarNameOrStructuredBinding.erase(VarNameOrStructuredBinding.size() - 2,
650 VarNameOrStructuredBinding +=
"]";
652 VarNameOrStructuredBinding = AliasVar->getName().str();
655 QualType AliasVarType = AliasVar->getType();
656 assert(!AliasVarType.isNull() &&
"Type in VarDecl is null");
657 if (AliasVarType->isReferenceType()) {
658 AliasVarType = AliasVarType.getNonReferenceType();
659 AliasVarIsRef =
true;
661 if (Descriptor.ElemType.isNull() ||
662 !ASTContext::hasSameUnqualifiedType(AliasVarType,
663 Descriptor.ElemType))
664 Descriptor.ElemType = AliasVarType;
668 SourceRange ReplaceRange = AliasDecl->getSourceRange();
670 std::string ReplacementText;
671 if (AliasUseRequired) {
672 ReplacementText = VarNameOrStructuredBinding;
673 }
else if (AliasFromForInit) {
677 ReplacementText =
";";
680 getAliasRange(Context->getSourceManager(), ReplaceRange);
683 FixIts.push_back(FixItHint::CreateReplacement(
684 CharSourceRange::getTokenRange(ReplaceRange), ReplacementText));
688 VariableNamer Namer(&TUInfo->getGeneratedDecls(),
689 &TUInfo->getParentFinder().getStmtToParentStmtMap(),
690 Loop, IndexVar, MaybeContainer, Context, NamingStyle);
691 VarNameOrStructuredBinding = Namer.createIndexName();
694 for (
const auto &
Usage : Usages) {
695 std::string ReplaceText;
696 SourceRange Range =
Usage.Range;
697 if (
Usage.Expression) {
701 ? VarNameOrStructuredBinding +
"."
702 : VarNameOrStructuredBinding;
703 const DynTypedNodeList
Parents = Context->getParents(*
Usage.Expression);
705 if (
const auto *Paren = Parents[0].get<ParenExpr>()) {
709 const DynTypedNodeList GrandParents = Context->getParents(*Paren);
710 if (GrandParents.size() != 1 ||
711 GrandParents[0].get<UnaryExprOrTypeTraitExpr>() ==
nullptr) {
712 Range = Paren->getSourceRange();
714 }
else if (
const auto *UOP = Parents[0].get<UnaryOperator>()) {
722 if (UOP->getOpcode() == UO_AddrOf)
731 ?
"&" + VarNameOrStructuredBinding
732 : VarNameOrStructuredBinding;
734 TUInfo->getReplacedVars().insert(std::make_pair(Loop, IndexVar));
735 FixIts.push_back(FixItHint::CreateReplacement(
736 CharSourceRange::getTokenRange(Range), ReplaceText));
741 const SourceRange ParenRange(Loop->getLParenLoc(), Loop->getRParenLoc());
743 QualType
Type = Context->getAutoDeductType();
744 if (!Descriptor.ElemType.isNull() && Descriptor.ElemType->isFundamentalType())
745 Type = Descriptor.ElemType.getUnqualifiedType();
746 Type =
Type.getDesugaredType(*Context);
751 const bool IsCheapToCopy =
752 !Descriptor.ElemType.isNull() &&
753 Descriptor.ElemType.isTriviallyCopyableType(*Context) &&
754 !Descriptor.ElemType->isDependentSizedArrayType() &&
756 Context->getTypeInfo(Descriptor.ElemType).Width <= 8 * MaxCopySize;
758 CanCopy && ((VarNameFromAlias && !AliasVarIsRef) ||
759 (Descriptor.DerefByConstRef && IsCheapToCopy));
762 if (Descriptor.DerefByConstRef) {
763 Type = Context->getLValueReferenceType(Context->getConstType(Type));
764 }
else if (Descriptor.DerefByValue) {
766 Type = Context->getRValueReferenceType(Type);
768 Type = Context->getLValueReferenceType(Type);
772 SmallString<128> Range;
773 llvm::raw_svector_ostream Output(Range);
775 Type.print(Output, getLangOpts());
776 Output <<
' ' << VarNameOrStructuredBinding <<
" : ";
777 if (Descriptor.NeedsReverseCall)
778 Output << getReverseFunction() <<
'(';
779 if (Descriptor.ContainerNeedsDereference)
781 Output << Descriptor.ContainerString;
782 if (Descriptor.NeedsReverseCall)
786 FixIts.push_back(FixItHint::CreateReplacement(
787 CharSourceRange::getTokenRange(ParenRange), Range));
789 if (Descriptor.NeedsReverseCall && !getReverseHeader().
empty()) {
790 if (std::optional<FixItHint> Insertion = Inserter.createIncludeInsertion(
791 Context->getSourceManager().getFileID(Loop->getBeginLoc()),
793 FixIts.push_back(*Insertion);
795 diag(Loop->getForLoc(),
"use range-based for loop instead") << FixIts;
796 TUInfo->getGeneratedDecls().insert(
797 make_pair(Loop, VarNameOrStructuredBinding));
801StringRef LoopConvertCheck::getContainerString(ASTContext *Context,
803 const Expr *ContainerExpr) {
804 StringRef ContainerString;
805 ContainerExpr = ContainerExpr->IgnoreParenImpCasts();
806 if (isa<CXXThisExpr>(ContainerExpr)) {
807 ContainerString =
"this";
811 if (
const auto *E = dyn_cast<CXXOperatorCallExpr>(ContainerExpr))
812 if (E->getOperator() != OO_Subscript)
813 ContainerExpr = E->getArg(0);
816 ContainerExpr->getSourceRange());
819 return ContainerString;
824void LoopConvertCheck::getArrayLoopQualifiers(ASTContext *Context,
825 const BoundNodes &Nodes,
826 const Expr *ContainerExpr,
828 RangeDescriptor &Descriptor) {
833 Descriptor.DerefByConstRef =
true;
839 Descriptor.DerefByValue =
true;
843 for (
const Usage &U : Usages) {
844 if (!U.Expression || U.Expression->getType().isNull())
846 QualType
Type = U.Expression->getType().getCanonicalType();
848 if (!
Type->isPointerType()) {
853 Descriptor.ElemType =
Type;
859void LoopConvertCheck::getIteratorLoopQualifiers(ASTContext *Context,
860 const BoundNodes &Nodes,
861 RangeDescriptor &Descriptor) {
864 const auto *InitVar = Nodes.getNodeAs<VarDecl>(
InitVarName);
865 const QualType CanonicalInitVarType = InitVar->getType().getCanonicalType();
866 const auto *DerefByValueType =
868 Descriptor.DerefByValue = DerefByValueType;
870 if (Descriptor.DerefByValue) {
873 Descriptor.DerefByConstRef = CanonicalInitVarType.isConstQualified();
874 Descriptor.ElemType = *DerefByValueType;
876 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();
900void LoopConvertCheck::determineRangeDescriptor(
901 ASTContext *Context,
const BoundNodes &Nodes,
const ForStmt *Loop,
903 const UsageResult &Usages, RangeDescriptor &Descriptor) {
904 Descriptor.ContainerString =
905 std::string(getContainerString(Context, Loop, ContainerExpr));
909 getIteratorLoopQualifiers(Context, Nodes, Descriptor);
911 getArrayLoopQualifiers(Context, Nodes, ContainerExpr, Usages, Descriptor);
916bool LoopConvertCheck::isConvertible(ASTContext *Context,
917 const ast_matchers::BoundNodes &Nodes,
923 if (areDiagsSelfContained())
924 TUInfo = std::make_unique<TUTrackingInfo>();
925 else if (TUInfo->getReplacedVars().contains(Loop))
929 const auto *InitVar = Nodes.getNodeAs<VarDecl>(
InitVarName);
933 const QualType InitVarType = InitVar->getType();
934 const QualType CanonicalInitVarType = InitVarType.getCanonicalType();
936 const auto *BeginCall = Nodes.getNodeAs<CallExpr>(
BeginCallName);
937 assert(BeginCall &&
"Bad Callback. No begin call expression");
938 const QualType CanonicalBeginType =
939 BeginCall->getDirectCallee()->getReturnType().getCanonicalType();
940 if (CanonicalBeginType->isPointerType() &&
941 CanonicalInitVarType->isPointerType()) {
944 return ASTContext::hasSameUnqualifiedType(
945 CanonicalBeginType->getPointeeType(),
946 CanonicalInitVarType->getPointeeType());
949 if (CanonicalBeginType->isBuiltinType() ||
950 CanonicalInitVarType->isBuiltinType())
954 if (
const auto *EndCall = Nodes.getNodeAs<CXXMemberCallExpr>(
EndCallName)) {
956 if (!isa<MemberExpr>(EndCall->getCallee()))
959 return Nodes.getNodeAs<CallExpr>(
EndCallName) !=
nullptr;
965 const BoundNodes &Nodes = Result.Nodes;
967 ASTContext *Context = Result.Context;
969 const ForStmt *Loop =
nullptr;
971 RangeDescriptor Descriptor;
981 assert(Loop &&
"Bad Callback. No for statement");
985 if (!isConvertible(Context, Nodes, Loop, FixerKind))
988 const auto *LoopVar = Nodes.getNodeAs<VarDecl>(
InitVarName);
989 const auto *EndVar = Nodes.getNodeAs<VarDecl>(
EndVarName);
998 const auto *EndCall = Nodes.getNodeAs<Expr>(
EndCallName);
1005 const Expr *ContainerExpr =
nullptr;
1008 Context, LoopVar->getInit(), EndVar ? EndVar->getInit() : EndCall,
1009 &Descriptor.ContainerNeedsDereference,
1014 ContainerExpr = Call->Container;
1015 Descriptor.ContainerNeedsDereference = Call->IsArrow;
1020 if (!ContainerExpr && !BoundExpr)
1025 Descriptor.ContainerNeedsDereference);
1028 if (ContainerExpr) {
1053 const TraversalKindScope RAII(*Context, TK_AsIs);
1055 determineRangeDescriptor(Context, Nodes, Loop, FixerKind, ContainerExpr,
1056 Usages, Descriptor);
1062 TUInfo->getParentFinder().gatherAncestors(*Context);
1064 &TUInfo->getParentFinder().getStmtToParentStmtMap(),
1065 &TUInfo->getParentFinder().getDeclToParentStmtMap(),
1066 &TUInfo->getReplacedVars(), Loop);
1069 Descriptor.ContainerString.empty() || Usages.empty() ||
1070 ConfidenceLevel.
getLevel() < MinConfidence)
1078llvm::StringRef LoopConvertCheck::getReverseFunction()
const {
1079 if (!ReverseFunction.empty())
1080 return ReverseFunction;
1081 if (UseReverseRanges)
1082 return "std::ranges::reverse_view";
1086llvm::StringRef LoopConvertCheck::getReverseHeader()
const {
1087 if (!ReverseHeader.empty())
1088 return ReverseHeader;
1089 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.
llvm::SmallVector< Usage, 8 > UsageResult
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 StatementMatcher makePseudoArrayLoopMatcher()
The matcher used for array-like containers (pseudoarrays).
static StatementMatcher arrayConditionMatcher(const internal::Matcher< Expr > &LimitExpr)
static const char DerefByValueResultName[]
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 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 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 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[]
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[]
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 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.
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.