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 Context->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 !Context->hasSameUnqualifiedType(AliasVarType, Descriptor.ElemType))
668 Descriptor.ElemType = AliasVarType;
672 SourceRange ReplaceRange = AliasDecl->getSourceRange();
674 std::string ReplacementText;
675 if (AliasUseRequired) {
676 ReplacementText = VarNameOrStructuredBinding;
677 }
else if (AliasFromForInit) {
681 ReplacementText =
";";
684 getAliasRange(Context->getSourceManager(), ReplaceRange);
687 FixIts.push_back(FixItHint::CreateReplacement(
688 CharSourceRange::getTokenRange(ReplaceRange), ReplacementText));
692 VariableNamer Namer(&TUInfo->getGeneratedDecls(),
693 &TUInfo->getParentFinder().getStmtToParentStmtMap(),
694 Loop, IndexVar, MaybeContainer, Context, NamingStyle);
695 VarNameOrStructuredBinding = Namer.createIndexName();
698 for (
const auto &
Usage : Usages) {
699 std::string ReplaceText;
700 SourceRange Range =
Usage.Range;
701 if (
Usage.Expression) {
705 ? VarNameOrStructuredBinding +
"."
706 : VarNameOrStructuredBinding;
707 const DynTypedNodeList
Parents = Context->getParents(*
Usage.Expression);
709 if (
const auto *Paren = Parents[0].get<ParenExpr>()) {
713 const DynTypedNodeList GrandParents = Context->getParents(*Paren);
714 if (GrandParents.size() != 1 ||
715 GrandParents[0].get<UnaryExprOrTypeTraitExpr>() ==
nullptr) {
716 Range = Paren->getSourceRange();
718 }
else if (
const auto *UOP = Parents[0].get<UnaryOperator>()) {
726 if (UOP->getOpcode() == UO_AddrOf)
735 ?
"&" + VarNameOrStructuredBinding
736 : VarNameOrStructuredBinding;
738 TUInfo->getReplacedVars().insert(std::make_pair(Loop, IndexVar));
739 FixIts.push_back(FixItHint::CreateReplacement(
740 CharSourceRange::getTokenRange(Range), ReplaceText));
745 SourceRange ParenRange(Loop->getLParenLoc(), Loop->getRParenLoc());
747 QualType
Type = Context->getAutoDeductType();
748 if (!Descriptor.ElemType.isNull() && Descriptor.ElemType->isFundamentalType())
749 Type = Descriptor.ElemType.getUnqualifiedType();
750 Type =
Type.getDesugaredType(*Context);
756 !Descriptor.ElemType.isNull() &&
757 Descriptor.ElemType.isTriviallyCopyableType(*Context) &&
758 !Descriptor.ElemType->isDependentSizedArrayType() &&
760 Context->getTypeInfo(Descriptor.ElemType).Width <= 8 * MaxCopySize;
761 bool UseCopy = 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().insert(
800 make_pair(Loop, VarNameOrStructuredBinding));
804StringRef LoopConvertCheck::getContainerString(ASTContext *Context,
806 const Expr *ContainerExpr) {
807 StringRef ContainerString;
808 ContainerExpr = ContainerExpr->IgnoreParenImpCasts();
809 if (isa<CXXThisExpr>(ContainerExpr)) {
810 ContainerString =
"this";
814 if (
const auto *E = dyn_cast<CXXOperatorCallExpr>(ContainerExpr))
815 if (E->getOperator() != OO_Subscript)
816 ContainerExpr = E->getArg(0);
819 ContainerExpr->getSourceRange());
822 return ContainerString;
827void LoopConvertCheck::getArrayLoopQualifiers(ASTContext *Context,
828 const BoundNodes &Nodes,
829 const Expr *ContainerExpr,
831 RangeDescriptor &Descriptor) {
836 Descriptor.DerefByConstRef =
true;
842 Descriptor.DerefByValue =
true;
846 for (
const Usage &U : Usages) {
847 if (!U.Expression || U.Expression->getType().isNull())
849 QualType
Type = U.Expression->getType().getCanonicalType();
851 if (!
Type->isPointerType()) {
856 Descriptor.ElemType =
Type;
862void LoopConvertCheck::getIteratorLoopQualifiers(ASTContext *Context,
863 const BoundNodes &Nodes,
864 RangeDescriptor &Descriptor) {
867 const auto *InitVar = Nodes.getNodeAs<VarDecl>(
InitVarName);
868 QualType CanonicalInitVarType = InitVar->getType().getCanonicalType();
869 const auto *DerefByValueType =
871 Descriptor.DerefByValue = DerefByValueType;
873 if (Descriptor.DerefByValue) {
876 Descriptor.DerefByConstRef = CanonicalInitVarType.isConstQualified();
877 Descriptor.ElemType = *DerefByValueType;
879 if (
const auto *DerefType =
884 auto ValueType = DerefType->getNonReferenceType();
886 Descriptor.DerefByConstRef = ValueType.isConstQualified();
887 Descriptor.ElemType = ValueType;
891 assert(isa<PointerType>(CanonicalInitVarType) &&
892 "Non-class iterator type is not a pointer type");
895 Descriptor.DerefByConstRef =
896 CanonicalInitVarType->getPointeeType().isConstQualified();
897 Descriptor.ElemType = CanonicalInitVarType->getPointeeType();
903void LoopConvertCheck::determineRangeDescriptor(
904 ASTContext *Context,
const BoundNodes &Nodes,
const ForStmt *Loop,
906 const UsageResult &Usages, RangeDescriptor &Descriptor) {
907 Descriptor.ContainerString =
908 std::string(getContainerString(Context, Loop, ContainerExpr));
912 getIteratorLoopQualifiers(Context, Nodes, Descriptor);
914 getArrayLoopQualifiers(Context, Nodes, ContainerExpr, Usages, Descriptor);
919bool LoopConvertCheck::isConvertible(ASTContext *Context,
920 const ast_matchers::BoundNodes &Nodes,
926 if (areDiagsSelfContained())
927 TUInfo = std::make_unique<TUTrackingInfo>();
928 else if (TUInfo->getReplacedVars().contains(Loop))
932 const auto *InitVar = Nodes.getNodeAs<VarDecl>(
InitVarName);
936 QualType InitVarType = InitVar->getType();
937 QualType CanonicalInitVarType = InitVarType.getCanonicalType();
939 const auto *BeginCall = Nodes.getNodeAs<CallExpr>(
BeginCallName);
940 assert(BeginCall &&
"Bad Callback. No begin call expression");
941 QualType CanonicalBeginType =
942 BeginCall->getDirectCallee()->getReturnType().getCanonicalType();
943 if (CanonicalBeginType->isPointerType() &&
944 CanonicalInitVarType->isPointerType()) {
947 return Context->hasSameUnqualifiedType(
948 CanonicalBeginType->getPointeeType(),
949 CanonicalInitVarType->getPointeeType());
952 if (CanonicalBeginType->isBuiltinType() ||
953 CanonicalInitVarType->isBuiltinType())
957 if (
const auto *EndCall = Nodes.getNodeAs<CXXMemberCallExpr>(
EndCallName)) {
959 if (!isa<MemberExpr>(EndCall->getCallee()))
962 return Nodes.getNodeAs<CallExpr>(
EndCallName) !=
nullptr;
968 const BoundNodes &Nodes = Result.Nodes;
970 ASTContext *Context = Result.Context;
972 const ForStmt *Loop =
nullptr;
974 RangeDescriptor Descriptor;
984 assert(Loop &&
"Bad Callback. No for statement");
988 if (!isConvertible(Context, Nodes, Loop, FixerKind))
991 const auto *LoopVar = Nodes.getNodeAs<VarDecl>(
InitVarName);
992 const auto *EndVar = Nodes.getNodeAs<VarDecl>(
EndVarName);
1001 const auto *EndCall = Nodes.getNodeAs<Expr>(
EndCallName);
1008 const Expr *ContainerExpr =
nullptr;
1011 Context, LoopVar->getInit(), EndVar ? EndVar->getInit() : EndCall,
1012 &Descriptor.ContainerNeedsDereference,
1017 ContainerExpr = Call->Container;
1018 Descriptor.ContainerNeedsDereference = Call->IsArrow;
1023 if (!ContainerExpr && !BoundExpr)
1028 Descriptor.ContainerNeedsDereference);
1031 if (ContainerExpr) {
1056 TraversalKindScope RAII(*Context, TK_AsIs);
1058 determineRangeDescriptor(Context, Nodes, Loop, FixerKind, ContainerExpr,
1059 Usages, Descriptor);
1065 TUInfo->getParentFinder().gatherAncestors(*Context);
1067 &TUInfo->getParentFinder().getStmtToParentStmtMap(),
1068 &TUInfo->getParentFinder().getDeclToParentStmtMap(),
1069 &TUInfo->getReplacedVars(), Loop);
1072 Descriptor.ContainerString.empty() || Usages.empty() ||
1073 ConfidenceLevel.
getLevel() < MinConfidence)
1081llvm::StringRef LoopConvertCheck::getReverseFunction()
const {
1082 if (!ReverseFunction.empty())
1083 return ReverseFunction;
1084 if (UseReverseRanges)
1085 return "std::ranges::reverse_view";
1089llvm::StringRef LoopConvertCheck::getReverseHeader()
const {
1090 if (!ReverseHeader.empty())
1091 return ReverseHeader;
1092 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.