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 StatementMatcher ArrayBoundMatcher =
121 return forStmt(unless(isInTemplateInstantiation()),
125 unaryOperator(hasOperatorName(
"++"),
160 auto BeginNameMatcher = IsReverse ? hasAnyName(
"rbegin",
"crbegin")
161 : hasAnyName(
"begin",
"cbegin");
162 auto BeginNameMatcherStd = IsReverse
163 ? hasAnyName(
"::std::rbegin",
"::std::crbegin")
164 : hasAnyName(
"::std::begin",
"::std::cbegin");
166 auto EndNameMatcher =
167 IsReverse ? hasAnyName(
"rend",
"crend") : hasAnyName(
"end",
"cend");
168 auto EndNameMatcherStd = IsReverse ? hasAnyName(
"::std::rend",
"::std::crend")
169 : hasAnyName(
"::std::end",
"::std::cend");
171 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 DeclarationMatcher InitDeclMatcher =
181 varDecl(hasInitializer(anyOf(ignoringParenImpCasts(BeginCallMatcher),
182 materializeTemporaryExpr(
183 ignoringParenImpCasts(BeginCallMatcher)),
184 hasDescendant(BeginCallMatcher))))
187 DeclarationMatcher EndDeclMatcher =
188 varDecl(hasInitializer(anything())).bind(
EndVarName);
190 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 StatementMatcher IteratorBoundMatcher =
198 expr(anyOf(ignoringParenImpCasts(
199 declRefExpr(to(varDecl(equalsBoundNode(
EndVarName))))),
200 ignoringParenImpCasts(expr(EndCallMatcher).bind(
EndCallName)),
201 materializeTemporaryExpr(ignoringParenImpCasts(
204 StatementMatcher IteratorComparisonMatcher = expr(ignoringParenImpCasts(
205 declRefExpr(to(varDecl(equalsBoundNode(
InitVarName))))));
210 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 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 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 DeclarationMatcher EndDeclMatcher =
314 varDecl(hasInitializer(EndInitMatcher)).bind(
EndVarName);
316 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(
"++"),
360 if (
const auto *TheCall = dyn_cast_or_null<CXXMemberCallExpr>(Dug)) {
362 if (
const auto *Member = dyn_cast<MemberExpr>(TheCall->getCallee())) {
363 if (Member->getMemberDecl() ==
nullptr ||
364 !
MemberNames.contains(Member->getMemberDecl()->getName()))
367 Member->getMemberDecl()->getName(),
368 Member->isArrow(), CallKind};
370 if (TheCall->getDirectCallee() ==
nullptr ||
371 !
MemberNames.contains(TheCall->getDirectCallee()->getName()))
374 TheCall->getDirectCallee()->getName(),
false,
377 if (
const auto *TheCall = dyn_cast_or_null<CallExpr>(Dug)) {
378 if (TheCall->getNumArgs() != 1)
381 if (TheCall->usesADL()) {
382 if (TheCall->getDirectCallee() ==
nullptr ||
383 !
ADLNames.contains(TheCall->getDirectCallee()->getName()))
388 TheCall->getDirectCallee()->getQualifiedNameAsString()))
393 if (TheCall->getDirectCallee() ==
nullptr)
397 TheCall->getDirectCallee()->getName(),
false,
408static std::pair<const Expr *, IteratorCallKind>
417 *IsArrow = Call->IsArrow;
418 if (!Call->Name.consume_back(IsBegin ?
"begin" :
"end"))
420 if (IsReverse && !Call->Name.consume_back(
"r"))
422 if (!Call->Name.empty() && Call->Name !=
"c")
424 return std::make_pair(Call->Container, Call->CallKind);
434 bool *ContainerNeedsDereference,
438 bool BeginIsArrow =
false;
439 bool EndIsArrow =
false;
441 BeginExpr,
true, &BeginIsArrow, IsReverse);
442 if (!BeginContainerExpr)
446 EndExpr,
false, &EndIsArrow, IsReverse);
447 if (BeginCallKind != EndCallKind)
452 if (!EndContainerExpr || BeginIsArrow != EndIsArrow ||
453 !
areSameExpr(Context, EndContainerExpr, BeginContainerExpr))
456 *ContainerNeedsDereference = BeginIsArrow;
457 return BeginContainerExpr;
462 const LangOptions &LangOpts,
464 if (SourceMgr.getFileID(Range.getBegin()) !=
465 SourceMgr.getFileID(Range.getEnd())) {
469 return Lexer::getSourceText(CharSourceRange(Range,
true), SourceMgr,
477 return dyn_cast<VarDecl>(DRE->getDecl());
478 if (
const auto *Mem = dyn_cast<MemberExpr>(E->IgnoreParenImpCasts()))
479 return dyn_cast<FieldDecl>(Mem->getMemberDecl());
486 if (
const auto *Member = dyn_cast<MemberExpr>(E->IgnoreParenImpCasts()))
487 return isa<CXXThisExpr>(Member->getBase()->IgnoreParenImpCasts());
495 if (E->getType().isConstQualified())
497 auto Parents = Context->getParents(*E);
498 if (Parents.size() != 1)
500 if (
const auto *Cast = Parents[0].get<ImplicitCastExpr>()) {
501 if ((Cast->getCastKind() == CK_NoOp &&
502 ASTContext::hasSameType(Cast->getType(), E->getType().withConst())) ||
503 (Cast->getCastKind() == CK_LValueToRValue &&
504 !Cast->getType().isNull() && Cast->getType()->isFundamentalType()))
514 for (
const Usage &U : Usages) {
530 for (
const auto &U : Usages) {
531 if (U.Expression && !U.Expression->isPRValue())
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",
"")) {
567 if (ReverseFunction.empty() && !ReverseHeader.empty()) {
569 "modernize-loop-convert: 'MakeReverseRangeHeader' is set but "
570 "'MakeReverseRangeFunction' is not, disabling reverse loop "
572 UseReverseRanges = false;
573 }
else if (ReverseFunction.empty()) {
574 UseReverseRanges = UseCxx20IfAvailable && getLangOpts().CPlusPlus20;
576 UseReverseRanges = true;
581 Options.store(Opts,
"MaxCopySize", MaxCopySize);
582 Options.store(Opts,
"MinConfidence", MinConfidence);
583 Options.store(Opts,
"NamingStyle", NamingStyle);
584 Options.store(Opts,
"IncludeStyle", Inserter.getStyle());
585 Options.store(Opts,
"UseCxx20ReverseRanges", UseCxx20IfAvailable);
586 Options.store(Opts,
"MakeReverseRangeFunction", ReverseFunction);
587 Options.store(Opts,
"MakeReverseRangeHeader", ReverseHeader);
592 Preprocessor *ModuleExpanderPP) {
593 Inserter.registerPreprocessor(PP);
600 if (UseReverseRanges)
617void LoopConvertCheck::getAliasRange(SourceManager &SM, SourceRange &Range) {
618 bool Invalid =
false;
619 const char *TextAfter =
620 SM.getCharacterData(Range.getEnd().getLocWithOffset(1), &Invalid);
623 unsigned Offset = std::strspn(TextAfter,
" \t\r\n");
625 SourceRange(Range.getBegin(), Range.getEnd().getLocWithOffset(Offset));
630void LoopConvertCheck::doConversion(
631 ASTContext *Context,
const VarDecl *IndexVar,
632 const ValueDecl *MaybeContainer,
const UsageResult &Usages,
633 const DeclStmt *AliasDecl,
bool AliasUseRequired,
bool AliasFromForInit,
634 const ForStmt *Loop, RangeDescriptor Descriptor) {
635 std::string VarNameOrStructuredBinding;
636 bool VarNameFromAlias = (Usages.size() == 1) && AliasDecl;
637 bool AliasVarIsRef =
false;
639 std::vector<FixItHint> FixIts;
640 if (VarNameFromAlias) {
641 const auto *AliasVar = cast<VarDecl>(AliasDecl->getSingleDecl());
644 if (
const auto *AliasDecompositionDecl =
645 dyn_cast<DecompositionDecl>(AliasDecl->getSingleDecl())) {
646 VarNameOrStructuredBinding =
"[";
648 assert(!AliasDecompositionDecl->bindings().empty() &&
"No bindings");
649 for (
const BindingDecl *Binding : AliasDecompositionDecl->bindings()) {
650 VarNameOrStructuredBinding += Binding->getName().str() +
", ";
653 VarNameOrStructuredBinding.erase(VarNameOrStructuredBinding.size() - 2,
655 VarNameOrStructuredBinding +=
"]";
657 VarNameOrStructuredBinding = AliasVar->getName().str();
660 QualType AliasVarType = AliasVar->getType();
661 assert(!AliasVarType.isNull() &&
"Type in VarDecl is null");
662 if (AliasVarType->isReferenceType()) {
663 AliasVarType = AliasVarType.getNonReferenceType();
664 AliasVarIsRef =
true;
666 if (Descriptor.ElemType.isNull() ||
667 !ASTContext::hasSameUnqualifiedType(AliasVarType,
668 Descriptor.ElemType))
669 Descriptor.ElemType = AliasVarType;
673 SourceRange ReplaceRange = AliasDecl->getSourceRange();
675 std::string ReplacementText;
676 if (AliasUseRequired) {
677 ReplacementText = VarNameOrStructuredBinding;
678 }
else if (AliasFromForInit) {
682 ReplacementText =
";";
685 getAliasRange(Context->getSourceManager(), ReplaceRange);
688 FixIts.push_back(FixItHint::CreateReplacement(
689 CharSourceRange::getTokenRange(ReplaceRange), ReplacementText));
693 VariableNamer Namer(&TUInfo->getGeneratedDecls(),
694 &TUInfo->getParentFinder().getStmtToParentStmtMap(),
695 Loop, IndexVar, MaybeContainer, Context, NamingStyle);
696 VarNameOrStructuredBinding = Namer.createIndexName();
699 for (
const auto &
Usage : Usages) {
700 std::string ReplaceText;
701 SourceRange Range =
Usage.Range;
702 if (
Usage.Expression) {
706 ? VarNameOrStructuredBinding +
"."
707 : VarNameOrStructuredBinding;
708 const DynTypedNodeList
Parents = Context->getParents(*
Usage.Expression);
710 if (
const auto *Paren = Parents[0].get<ParenExpr>()) {
714 const DynTypedNodeList GrandParents = Context->getParents(*Paren);
715 if (GrandParents.size() != 1 ||
716 GrandParents[0].get<UnaryExprOrTypeTraitExpr>() ==
nullptr) {
717 Range = Paren->getSourceRange();
719 }
else if (
const auto *UOP = Parents[0].get<UnaryOperator>()) {
727 if (UOP->getOpcode() == UO_AddrOf)
736 ?
"&" + VarNameOrStructuredBinding
737 : VarNameOrStructuredBinding;
739 TUInfo->getReplacedVars().insert(std::make_pair(Loop, IndexVar));
740 FixIts.push_back(FixItHint::CreateReplacement(
741 CharSourceRange::getTokenRange(Range), ReplaceText));
746 SourceRange ParenRange(Loop->getLParenLoc(), Loop->getRParenLoc());
748 QualType
Type = Context->getAutoDeductType();
749 if (!Descriptor.ElemType.isNull() && Descriptor.ElemType->isFundamentalType())
750 Type = Descriptor.ElemType.getUnqualifiedType();
751 Type =
Type.getDesugaredType(*Context);
757 !Descriptor.ElemType.isNull() &&
758 Descriptor.ElemType.isTriviallyCopyableType(*Context) &&
759 !Descriptor.ElemType->isDependentSizedArrayType() &&
761 Context->getTypeInfo(Descriptor.ElemType).Width <= 8 * MaxCopySize;
762 bool UseCopy = CanCopy && ((VarNameFromAlias && !AliasVarIsRef) ||
763 (Descriptor.DerefByConstRef && IsCheapToCopy));
766 if (Descriptor.DerefByConstRef) {
767 Type = Context->getLValueReferenceType(Context->getConstType(Type));
768 }
else if (Descriptor.DerefByValue) {
770 Type = Context->getRValueReferenceType(Type);
772 Type = Context->getLValueReferenceType(Type);
776 SmallString<128> Range;
777 llvm::raw_svector_ostream Output(Range);
779 Type.print(Output, getLangOpts());
780 Output <<
' ' << VarNameOrStructuredBinding <<
" : ";
781 if (Descriptor.NeedsReverseCall)
782 Output << getReverseFunction() <<
'(';
783 if (Descriptor.ContainerNeedsDereference)
785 Output << Descriptor.ContainerString;
786 if (Descriptor.NeedsReverseCall)
790 FixIts.push_back(FixItHint::CreateReplacement(
791 CharSourceRange::getTokenRange(ParenRange), Range));
793 if (Descriptor.NeedsReverseCall && !getReverseHeader().
empty()) {
794 if (std::optional<FixItHint> Insertion = Inserter.createIncludeInsertion(
795 Context->getSourceManager().getFileID(Loop->getBeginLoc()),
797 FixIts.push_back(*Insertion);
799 diag(Loop->getForLoc(),
"use range-based for loop instead") << FixIts;
800 TUInfo->getGeneratedDecls().insert(
801 make_pair(Loop, VarNameOrStructuredBinding));
805StringRef LoopConvertCheck::getContainerString(ASTContext *Context,
807 const Expr *ContainerExpr) {
808 StringRef ContainerString;
809 ContainerExpr = ContainerExpr->IgnoreParenImpCasts();
810 if (isa<CXXThisExpr>(ContainerExpr)) {
811 ContainerString =
"this";
815 if (
const auto *E = dyn_cast<CXXOperatorCallExpr>(ContainerExpr))
816 if (E->getOperator() != OO_Subscript)
817 ContainerExpr = E->getArg(0);
820 ContainerExpr->getSourceRange());
823 return ContainerString;
828void LoopConvertCheck::getArrayLoopQualifiers(ASTContext *Context,
829 const BoundNodes &Nodes,
830 const Expr *ContainerExpr,
832 RangeDescriptor &Descriptor) {
837 Descriptor.DerefByConstRef =
true;
843 Descriptor.DerefByValue =
true;
847 for (
const Usage &U : Usages) {
848 if (!U.Expression || U.Expression->getType().isNull())
850 QualType
Type = U.Expression->getType().getCanonicalType();
852 if (!
Type->isPointerType()) {
857 Descriptor.ElemType =
Type;
863void LoopConvertCheck::getIteratorLoopQualifiers(ASTContext *Context,
864 const BoundNodes &Nodes,
865 RangeDescriptor &Descriptor) {
868 const auto *InitVar = Nodes.getNodeAs<VarDecl>(
InitVarName);
869 QualType CanonicalInitVarType = InitVar->getType().getCanonicalType();
870 const auto *DerefByValueType =
872 Descriptor.DerefByValue = DerefByValueType;
874 if (Descriptor.DerefByValue) {
877 Descriptor.DerefByConstRef = CanonicalInitVarType.isConstQualified();
878 Descriptor.ElemType = *DerefByValueType;
880 if (
const auto *DerefType =
885 auto ValueType = DerefType->getNonReferenceType();
887 Descriptor.DerefByConstRef = ValueType.isConstQualified();
888 Descriptor.ElemType = ValueType;
892 assert(isa<PointerType>(CanonicalInitVarType) &&
893 "Non-class iterator type is not a pointer type");
896 Descriptor.DerefByConstRef =
897 CanonicalInitVarType->getPointeeType().isConstQualified();
898 Descriptor.ElemType = CanonicalInitVarType->getPointeeType();
904void LoopConvertCheck::determineRangeDescriptor(
905 ASTContext *Context,
const BoundNodes &Nodes,
const ForStmt *Loop,
907 const UsageResult &Usages, RangeDescriptor &Descriptor) {
908 Descriptor.ContainerString =
909 std::string(getContainerString(Context, Loop, ContainerExpr));
913 getIteratorLoopQualifiers(Context, Nodes, Descriptor);
915 getArrayLoopQualifiers(Context, Nodes, ContainerExpr, Usages, Descriptor);
920bool LoopConvertCheck::isConvertible(ASTContext *Context,
921 const ast_matchers::BoundNodes &Nodes,
927 if (areDiagsSelfContained())
928 TUInfo = std::make_unique<TUTrackingInfo>();
929 else if (TUInfo->getReplacedVars().contains(Loop))
933 const auto *InitVar = Nodes.getNodeAs<VarDecl>(
InitVarName);
937 QualType InitVarType = InitVar->getType();
938 QualType CanonicalInitVarType = InitVarType.getCanonicalType();
940 const auto *BeginCall = Nodes.getNodeAs<CallExpr>(
BeginCallName);
941 assert(BeginCall &&
"Bad Callback. No begin call expression");
942 QualType CanonicalBeginType =
943 BeginCall->getDirectCallee()->getReturnType().getCanonicalType();
944 if (CanonicalBeginType->isPointerType() &&
945 CanonicalInitVarType->isPointerType()) {
948 return ASTContext::hasSameUnqualifiedType(
949 CanonicalBeginType->getPointeeType(),
950 CanonicalInitVarType->getPointeeType());
953 if (CanonicalBeginType->isBuiltinType() ||
954 CanonicalInitVarType->isBuiltinType())
958 if (
const auto *EndCall = Nodes.getNodeAs<CXXMemberCallExpr>(
EndCallName)) {
960 if (!isa<MemberExpr>(EndCall->getCallee()))
963 return Nodes.getNodeAs<CallExpr>(
EndCallName) !=
nullptr;
969 const BoundNodes &Nodes = Result.Nodes;
971 ASTContext *Context = Result.Context;
973 const ForStmt *Loop =
nullptr;
975 RangeDescriptor Descriptor;
985 assert(Loop &&
"Bad Callback. No for statement");
989 if (!isConvertible(Context, Nodes, Loop, FixerKind))
992 const auto *LoopVar = Nodes.getNodeAs<VarDecl>(
InitVarName);
993 const auto *EndVar = Nodes.getNodeAs<VarDecl>(
EndVarName);
1002 const auto *EndCall = Nodes.getNodeAs<Expr>(
EndCallName);
1009 const Expr *ContainerExpr =
nullptr;
1012 Context, LoopVar->getInit(), EndVar ? EndVar->getInit() : EndCall,
1013 &Descriptor.ContainerNeedsDereference,
1018 ContainerExpr = Call->Container;
1019 Descriptor.ContainerNeedsDereference = Call->IsArrow;
1024 if (!ContainerExpr && !BoundExpr)
1029 Descriptor.ContainerNeedsDereference);
1032 if (ContainerExpr) {
1057 TraversalKindScope RAII(*Context, TK_AsIs);
1059 determineRangeDescriptor(Context, Nodes, Loop, FixerKind, ContainerExpr,
1060 Usages, Descriptor);
1066 TUInfo->getParentFinder().gatherAncestors(*Context);
1068 &TUInfo->getParentFinder().getStmtToParentStmtMap(),
1069 &TUInfo->getParentFinder().getDeclToParentStmtMap(),
1070 &TUInfo->getReplacedVars(), Loop);
1073 Descriptor.ContainerString.empty() || Usages.empty() ||
1074 ConfidenceLevel.
getLevel() < MinConfidence)
1082llvm::StringRef LoopConvertCheck::getReverseFunction()
const {
1083 if (!ReverseFunction.empty())
1084 return ReverseFunction;
1085 if (UseReverseRanges)
1086 return "std::ranges::reverse_view";
1090llvm::StringRef LoopConvertCheck::getReverseHeader()
const {
1091 if (!ReverseHeader.empty())
1092 return ReverseHeader;
1093 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 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.
static StatementMatcher arrayConditionMatcher(internal::Matcher< Expr > LimitExpr)
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.