11 #include "clang/AST/ASTContext.h"
12 #include "clang/ASTMatchers/ASTMatchFinder.h"
13 #include "clang/Basic/LLVM.h"
14 #include "clang/Basic/LangOptions.h"
15 #include "clang/Basic/SourceLocation.h"
16 #include "clang/Basic/SourceManager.h"
17 #include "clang/Lex/Lexer.h"
18 #include "llvm/ADT/SmallVector.h"
19 #include "llvm/ADT/StringRef.h"
20 #include "llvm/ADT/StringSwitch.h"
21 #include "llvm/Support/Casting.h"
26 using namespace clang::ast_matchers;
48 static const TypeMatcher
AnyType = anything();
51 expr(ignoringParenImpCasts(
55 varDecl(hasInitializer(ignoringParenImpCasts(integerLiteral(equals(0)))))
80 StatementMatcher ArrayBoundMatcher =
84 unless(isInTemplateInstantiation()),
87 binaryOperator(hasOperatorName(
"<"),
89 hasRHS(ArrayBoundMatcher)),
90 binaryOperator(hasOperatorName(
">"), hasLHS(ArrayBoundMatcher),
92 hasIncrement(unaryOperator(hasOperatorName(
"++"),
125 StatementMatcher BeginCallMatcher =
128 callee(cxxMethodDecl(anyOf(hasName(
"begin"), hasName(
"cbegin")))))
131 DeclarationMatcher InitDeclMatcher =
132 varDecl(hasInitializer(anyOf(ignoringParenImpCasts(BeginCallMatcher),
133 materializeTemporaryExpr(
134 ignoringParenImpCasts(BeginCallMatcher)),
135 hasDescendant(BeginCallMatcher))))
138 DeclarationMatcher EndDeclMatcher =
139 varDecl(hasInitializer(anything())).bind(
EndVarName);
141 StatementMatcher EndCallMatcher = cxxMemberCallExpr(
143 callee(cxxMethodDecl(anyOf(hasName(
"end"), hasName(
"cend")))));
145 StatementMatcher IteratorBoundMatcher =
146 expr(anyOf(ignoringParenImpCasts(
148 ignoringParenImpCasts(expr(EndCallMatcher).bind(
EndCallName)),
149 materializeTemporaryExpr(ignoringParenImpCasts(
152 StatementMatcher IteratorComparisonMatcher = expr(
155 auto OverloadedNEQMatcher = ignoringImplicit(
156 cxxOperatorCallExpr(hasOverloadedOperatorName(
"!="), argumentCountIs(2),
157 hasArgument(0, IteratorComparisonMatcher),
158 hasArgument(1, IteratorBoundMatcher)));
163 internal::Matcher<VarDecl> TestDerefReturnsByValue =
164 hasType(cxxRecordDecl(hasMethod(allOf(
165 hasOverloadedOperatorName(
"*"),
168 returns(qualType(unless(hasCanonicalType(referenceType())))
173 qualType(unless(hasCanonicalType(rValueReferenceType())))
177 unless(isInTemplateInstantiation()),
178 hasLoopInit(anyOf(declStmt(declCountIs(2),
179 containsDeclaration(0, InitDeclMatcher),
180 containsDeclaration(1, EndDeclMatcher)),
181 declStmt(hasSingleDecl(InitDeclMatcher)))),
183 anyOf(binaryOperator(hasOperatorName(
"!="),
184 hasLHS(IteratorComparisonMatcher),
185 hasRHS(IteratorBoundMatcher)),
186 binaryOperator(hasOperatorName(
"!="),
187 hasLHS(IteratorBoundMatcher),
188 hasRHS(IteratorComparisonMatcher)),
189 OverloadedNEQMatcher)),
191 unaryOperator(hasOperatorName(
"++"),
192 hasUnaryOperand(declRefExpr(
193 to(varDecl(hasType(pointsTo(
AnyType)))
196 hasOverloadedOperatorName(
"++"),
198 0, declRefExpr(to(varDecl(TestDerefReturnsByValue)
244 TypeMatcher RecordWithBeginEnd = qualType(anyOf(
245 qualType(isConstQualified(),
246 hasDeclaration(cxxRecordDecl(
247 hasMethod(cxxMethodDecl(hasName(
"begin"), isConst())),
248 hasMethod(cxxMethodDecl(hasName(
"end"),
252 unless(isConstQualified()),
253 hasDeclaration(cxxRecordDecl(hasMethod(hasName(
"begin")),
254 hasMethod(hasName(
"end")))))
257 StatementMatcher SizeCallMatcher = cxxMemberCallExpr(
259 callee(cxxMethodDecl(anyOf(hasName(
"size"), hasName(
"length")))),
260 on(anyOf(hasType(pointsTo(RecordWithBeginEnd)),
261 hasType(RecordWithBeginEnd))));
263 StatementMatcher EndInitMatcher =
264 expr(anyOf(ignoringParenImpCasts(expr(SizeCallMatcher).bind(
EndCallName)),
265 explicitCastExpr(hasSourceExpression(ignoringParenImpCasts(
268 DeclarationMatcher EndDeclMatcher =
269 varDecl(hasInitializer(EndInitMatcher)).bind(
EndVarName);
271 StatementMatcher IndexBoundMatcher =
272 expr(anyOf(ignoringParenImpCasts(declRefExpr(to(
277 unless(isInTemplateInstantiation()),
279 anyOf(declStmt(declCountIs(2),
281 containsDeclaration(1, EndDeclMatcher)),
284 binaryOperator(hasOperatorName(
"<"),
286 hasRHS(IndexBoundMatcher)),
287 binaryOperator(hasOperatorName(
">"), hasLHS(IndexBoundMatcher),
289 hasIncrement(unaryOperator(hasOperatorName(
"++"),
302 const auto *TheCall =
304 if (!TheCall || TheCall->getNumArgs() != 0)
307 const auto *Member = dyn_cast<MemberExpr>(TheCall->getCallee());
310 StringRef
Name = Member->getMemberDecl()->getName();
311 StringRef TargetName = IsBegin ?
"begin" :
"end";
312 StringRef ConstTargetName = IsBegin ?
"cbegin" :
"cend";
313 if (Name != TargetName && Name != ConstTargetName)
316 const Expr *SourceExpr = Member->getBase();
320 *IsArrow = Member->isArrow();
331 bool *ContainerNeedsDereference) {
334 bool BeginIsArrow =
false;
335 bool EndIsArrow =
false;
336 const Expr *BeginContainerExpr =
338 if (!BeginContainerExpr)
341 const Expr *EndContainerExpr =
345 if (!EndContainerExpr || BeginIsArrow != EndIsArrow ||
346 !
areSameExpr(Context, EndContainerExpr, BeginContainerExpr))
349 *ContainerNeedsDereference = BeginIsArrow;
350 return BeginContainerExpr;
357 if (SourceMgr.getFileID(Range.getBegin()) !=
358 SourceMgr.getFileID(Range.getEnd())) {
362 return Lexer::getSourceText(CharSourceRange(Range,
true), SourceMgr,
370 return dyn_cast<VarDecl>(DRE->getDecl());
371 if (
const auto *Mem = dyn_cast<MemberExpr>(E->IgnoreParenImpCasts()))
372 return dyn_cast<FieldDecl>(Mem->getMemberDecl());
379 if (
const auto *Member = dyn_cast<MemberExpr>(E->IgnoreParenImpCasts()))
380 return isa<CXXThisExpr>(Member->getBase()->IgnoreParenImpCasts());
388 if (E->getType().isConstQualified())
390 auto Parents = Context->getParents(*E);
391 if (Parents.size() != 1)
393 if (
const auto *Cast = Parents[0].get<ImplicitCastExpr>()) {
394 if ((Cast->getCastKind() == CK_NoOp &&
395 Cast->getType() == E->getType().withConst()) ||
396 (Cast->getCastKind() == CK_LValueToRValue &&
397 !Cast->getType().isNull() && Cast->getType()->isFundamentalType()))
407 for (
const Usage &U : Usages) {
413 if (U.Kind != Usage::UK_CaptureByCopy && U.Kind != Usage::UK_CaptureByRef &&
423 for (
const auto &U : Usages) {
424 if (U.Expression && !U.Expression->isRValue())
433 QualType CType = VDec->getType();
435 if (!CType->isPointerType())
437 CType = CType->getPointeeType();
442 CType = CType.getNonReferenceType();
443 return CType.isConstQualified();
448 LoopConvertCheck::RangeDescriptor::RangeDescriptor()
449 : ContainerNeedsDereference(false), DerefByConstRef(false),
450 DerefByValue(false) {}
454 MaxCopySize(std::stoull(Options.get(
"MaxCopySize",
"16"))),
455 MinConfidence(StringSwitch<
Confidence::Level>(
456 Options.get(
"MinConfidence",
"reasonable"))
461 Options.get(
"NamingStyle",
"CamelCase"))
468 Options.
store(Opts,
"MaxCopySize", std::to_string(MaxCopySize));
469 SmallVector<std::string, 3> Confs{
"risky",
"reasonable",
"safe"};
470 Options.
store(Opts,
"MinConfidence", Confs[static_cast<int>(MinConfidence)]);
472 SmallVector<std::string, 4> Styles{
"camelBack",
"CamelCase",
"lower_case",
474 Options.
store(Opts,
"NamingStyle", Styles[static_cast<int>(NamingStyle)]);
502 void LoopConvertCheck::getAliasRange(SourceManager &
SM, SourceRange &
Range) {
503 bool Invalid =
false;
504 const char *TextAfter =
505 SM.getCharacterData(Range.getEnd().getLocWithOffset(1), &Invalid);
508 unsigned Offset = std::strspn(TextAfter,
" \t\r\n");
510 SourceRange(Range.getBegin(), Range.getEnd().getLocWithOffset(Offset));
515 void LoopConvertCheck::doConversion(
516 ASTContext *
Context,
const VarDecl *IndexVar,
517 const ValueDecl *MaybeContainer,
const UsageResult &Usages,
518 const DeclStmt *AliasDecl,
bool AliasUseRequired,
bool AliasFromForInit,
519 const ForStmt *Loop, RangeDescriptor Descriptor) {
520 auto Diag =
diag(Loop->getForLoc(),
"use range-based for loop instead");
523 bool VarNameFromAlias = (Usages.size() == 1) && AliasDecl;
524 bool AliasVarIsRef =
false;
527 if (VarNameFromAlias) {
528 const auto *AliasVar = cast<VarDecl>(AliasDecl->getSingleDecl());
529 VarName = AliasVar->getName().str();
532 QualType AliasVarType = AliasVar->getType();
533 assert(!AliasVarType.isNull() &&
"Type in VarDecl is null");
534 if (AliasVarType->isReferenceType()) {
535 AliasVarType = AliasVarType.getNonReferenceType();
536 AliasVarIsRef =
true;
538 if (Descriptor.ElemType.isNull() ||
539 !Context->hasSameUnqualifiedType(AliasVarType, Descriptor.ElemType))
540 Descriptor.ElemType = AliasVarType;
543 SourceRange ReplaceRange = AliasDecl->getSourceRange();
545 std::string ReplacementText;
546 if (AliasUseRequired) {
547 ReplacementText = VarName;
548 }
else if (AliasFromForInit) {
552 ReplacementText =
";";
555 getAliasRange(Context->getSourceManager(), ReplaceRange);
558 Diag << FixItHint::CreateReplacement(
559 CharSourceRange::getTokenRange(ReplaceRange), ReplacementText);
563 VariableNamer Namer(&TUInfo->getGeneratedDecls(),
564 &TUInfo->getParentFinder().getStmtToParentStmtMap(),
565 Loop, IndexVar, MaybeContainer, Context, NamingStyle);
566 VarName = Namer.createIndexName();
569 for (
const auto &Usage : Usages) {
570 std::string ReplaceText;
571 SourceRange Range = Usage.Range;
572 if (Usage.Expression) {
577 auto Parents = Context->getParents(*Usage.Expression);
578 if (Parents.size() == 1) {
579 if (
const auto *Paren = Parents[0].get<ParenExpr>()) {
583 Range = Paren->getSourceRange();
584 }
else if (
const auto *UOP = Parents[0].get<UnaryOperator>()) {
592 if (UOP->getOpcode() == UO_AddrOf)
603 TUInfo->getReplacedVars().insert(std::make_pair(Loop, IndexVar));
604 Diag << FixItHint::CreateReplacement(
605 CharSourceRange::getTokenRange(Range), ReplaceText);
610 SourceRange ParenRange(Loop->getLParenLoc(), Loop->getRParenLoc());
612 QualType Type = Context->getAutoDeductType();
613 if (!Descriptor.ElemType.isNull() && Descriptor.ElemType->isFundamentalType())
614 Type = Descriptor.ElemType.getUnqualifiedType();
620 !Descriptor.ElemType.isNull() &&
621 Descriptor.ElemType.isTriviallyCopyableType(*Context) &&
623 Context->getTypeInfo(Descriptor.ElemType).Width <= 8 * MaxCopySize;
624 bool UseCopy = CanCopy && ((VarNameFromAlias && !AliasVarIsRef) ||
625 (Descriptor.DerefByConstRef && IsCheapToCopy));
628 if (Descriptor.DerefByConstRef) {
629 Type = Context->getLValueReferenceType(Context->getConstType(Type));
630 }
else if (Descriptor.DerefByValue) {
632 Type = Context->getRValueReferenceType(Type);
634 Type = Context->getLValueReferenceType(Type);
638 StringRef MaybeDereference = Descriptor.ContainerNeedsDereference ?
"*" :
"";
639 std::string TypeString = Type.getAsString(
getLangOpts());
640 std::string Range = (
"(" + TypeString +
" " + VarName +
" : " +
641 MaybeDereference + Descriptor.ContainerString +
")")
643 Diag << FixItHint::CreateReplacement(
644 CharSourceRange::getTokenRange(ParenRange), Range);
645 TUInfo->getGeneratedDecls().insert(make_pair(Loop, VarName));
649 StringRef LoopConvertCheck::getContainerString(ASTContext *Context,
651 const Expr *ContainerExpr) {
652 StringRef ContainerString;
653 if (isa<CXXThisExpr>(ContainerExpr->IgnoreParenImpCasts())) {
654 ContainerString =
"this";
658 ContainerExpr->getSourceRange());
661 return ContainerString;
666 void LoopConvertCheck::getArrayLoopQualifiers(ASTContext *Context,
667 const BoundNodes &Nodes,
668 const Expr *ContainerExpr,
670 RangeDescriptor &Descriptor) {
675 Descriptor.DerefByConstRef =
true;
681 Descriptor.DerefByValue =
true;
685 for (
const Usage &U : Usages) {
686 if (!U.Expression || U.Expression->getType().isNull())
688 QualType Type = U.Expression->getType().getCanonicalType();
690 if (!Type->isPointerType()) {
693 Type = Type->getPointeeType();
695 Descriptor.ElemType = Type;
701 void LoopConvertCheck::getIteratorLoopQualifiers(ASTContext *Context,
702 const BoundNodes &Nodes,
703 RangeDescriptor &Descriptor) {
706 const auto *InitVar = Nodes.getNodeAs<VarDecl>(
InitVarName);
707 QualType CanonicalInitVarType = InitVar->getType().getCanonicalType();
708 const auto *DerefByValueType =
710 Descriptor.DerefByValue = DerefByValueType;
712 if (Descriptor.DerefByValue) {
715 Descriptor.DerefByConstRef = CanonicalInitVarType.isConstQualified();
716 Descriptor.ElemType = *DerefByValueType;
718 if (
const auto *DerefType =
723 auto ValueType = DerefType->getNonReferenceType();
725 Descriptor.DerefByConstRef = ValueType.isConstQualified();
726 Descriptor.ElemType = ValueType;
730 assert(isa<PointerType>(CanonicalInitVarType) &&
731 "Non-class iterator type is not a pointer type");
734 Descriptor.DerefByConstRef =
735 CanonicalInitVarType->getPointeeType().isConstQualified();
736 Descriptor.ElemType = CanonicalInitVarType->getPointeeType();
742 void LoopConvertCheck::determineRangeDescriptor(
743 ASTContext *Context,
const BoundNodes &Nodes,
const ForStmt *Loop,
745 const UsageResult &Usages, RangeDescriptor &Descriptor) {
746 Descriptor.ContainerString = getContainerString(Context, Loop, ContainerExpr);
749 getIteratorLoopQualifiers(Context, Nodes, Descriptor);
751 getArrayLoopQualifiers(Context, Nodes, ContainerExpr, Usages, Descriptor);
756 bool LoopConvertCheck::isConvertible(ASTContext *Context,
757 const ast_matchers::BoundNodes &Nodes,
762 if (TUInfo->getReplacedVars().count(Loop))
768 const auto *InitVar = Nodes.getNodeAs<VarDecl>(
InitVarName);
771 const auto *EndVar = Nodes.getNodeAs<VarDecl>(
EndVarName);
778 QualType InitVarType = InitVar->getType();
779 QualType CanonicalInitVarType = InitVarType.getCanonicalType();
781 const auto *BeginCall = Nodes.getNodeAs<CXXMemberCallExpr>(
BeginCallName);
782 assert(BeginCall &&
"Bad Callback. No begin call expression");
783 QualType CanonicalBeginType =
784 BeginCall->getMethodDecl()->getReturnType().getCanonicalType();
785 if (CanonicalBeginType->isPointerType() &&
786 CanonicalInitVarType->isPointerType()) {
789 if (!Context->hasSameUnqualifiedType(
790 CanonicalBeginType->getPointeeType(),
791 CanonicalInitVarType->getPointeeType()))
793 }
else if (!Context->hasSameType(CanonicalInitVarType,
794 CanonicalBeginType)) {
801 const auto *EndCall = Nodes.getNodeAs<CXXMemberCallExpr>(
EndCallName);
802 if (!EndCall || !dyn_cast<MemberExpr>(EndCall->getCallee()))
809 const BoundNodes &Nodes = Result.Nodes;
811 ASTContext *Context = Result.Context;
815 RangeDescriptor Descriptor;
823 assert(Loop &&
"Bad Callback. No for statement");
827 if (!isConvertible(Context, Nodes, Loop, FixerKind))
831 const auto *EndVar = Nodes.getNodeAs<VarDecl>(
EndVarName);
840 const auto *EndCall = Nodes.getNodeAs<CXXMemberCallExpr>(
EndCallName);
847 const Expr *ContainerExpr =
nullptr;
850 EndVar ? EndVar->getInit() : EndCall,
851 &Descriptor.ContainerNeedsDereference);
853 ContainerExpr = EndCall->getImplicitObjectArgument();
854 Descriptor.ContainerNeedsDereference =
855 dyn_cast<MemberExpr>(EndCall->getCallee())->isArrow();
859 if (!ContainerExpr && !BoundExpr)
864 Descriptor.ContainerNeedsDereference);
893 determineRangeDescriptor(Context, Nodes, Loop, FixerKind, ContainerExpr,
900 TUInfo->getParentFinder().gatherAncestors(Context->getTranslationUnitDecl());
902 &TUInfo->getParentFinder().getStmtToParentStmtMap(),
903 &TUInfo->getParentFinder().getDeclToParentStmtMap(),
904 &TUInfo->getReplacedVars(), Loop);
906 if (DependencyFinder.dependsOnInsideVariable(ContainerExpr) ||
907 Descriptor.ContainerString.empty() || Usages.empty() ||
908 ConfidenceLevel.
getLevel() < MinConfidence)
static const char DerefByRefResultName[]
Discover usages of expressions consisting of index or iterator access.
LangOptions getLangOpts() const
Returns the language options from the context.
StatementMatcher makeIteratorLoopMatcher()
The matcher used for iterator-based for loops.
void storeOptions(ClangTidyOptions::OptionMap &Opts) override
Should store all options supported by this check with their current values or default values for opti...
static const char ConditionVarName[]
static const Expr * getContainerFromBeginEndCall(const Expr *Init, bool IsBegin, bool *IsArrow)
Determine whether Init appears to be an initializing an iterator.
StatementMatcher makeArrayLoopMatcher()
The matcher for loops over arrays.
llvm::SmallVector< Usage, 8 > UsageResult
std::unique_ptr< ast_matchers::MatchFinder > Finder
bool aliasFromForInit() const
Indicates if the alias declaration came from the init clause of a nested for loop.
static const char EndCallName[]
A class to encapsulate lowering of the tool's confidence level.
static const StatementMatcher IntegerComparisonMatcher
static const DeclarationMatcher InitToZeroMatcher
Class used to determine if an expression is dependent on a variable declared inside of the loop where...
Base class for all clang-tidy checks.
const Expr * digThroughConstructors(const Expr *E)
Look through conversion/copy constructors to find the explicit initialization expression, returning it is found.
static const Expr * findContainer(ASTContext *Context, const Expr *BeginExpr, const Expr *EndExpr, bool *ContainerNeedsDereference)
Determines the container whose begin() and end() functions are called for an iterator-based loop...
const Expr * getContainerIndexed() const
Get the container indexed by IndexVar, if any.
static const char InitVarName[]
Level getLevel() const
Return the internal confidence level.
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 const char EndVarName[]
Confidence::Level getConfidenceLevel() const
Accessor for ConfidenceLevel.
void registerMatchers(ast_matchers::MatchFinder *Finder) override
Override this to register AST matchers with Finder.
const DeclRefExpr * getDeclRef(const Expr *E)
Returns the DeclRefExpr represented by E, or NULL if there isn't one.
void findExprComponents(const clang::Expr *SourceExpr)
Find the components of an expression and place them in a ComponentVector.
const ComponentVector & getComponents()
Accessor for Components.
const DeclStmt * getAliasDecl() const
Returns the statement declaring the variable created as an alias for the loop element, if any.
bool areSameVariable(const ValueDecl *First, const ValueDecl *Second)
Returns true when two ValueDecls are the same variable.
static bool usagesReturnRValues(const UsageResult &Usages)
Returns true if the elements of the container are never accessed by reference.
static const char ConditionBoundName[]
static const StatementMatcher IncrementVarMatcher
Create names for generated variables within a particular statement.
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 const char IncrementVarName[]
void store(ClangTidyOptions::OptionMap &Options, StringRef LocalName, StringRef Value) const
Stores an option with the check-local name LocalName with string value Value to Options.
bool areSameExpr(ASTContext *Context, const Expr *First, const Expr *Second)
Returns true when two Exprs are equivalent.
static bool canBeModified(ASTContext *Context, const Expr *E)
Given an expression that represents an usage of an element from the containter that we are iterating ...
std::map< std::string, std::string > OptionMap
static const char ConditionEndVarName[]
static const char LoopNameArray[]
static StringRef getStringFromRange(SourceManager &SourceMgr, const LangOptions &LangOpts, SourceRange Range)
Obtain the original source code text from a SourceRange.
static const char DerefByValueResultName[]
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
ClangTidyChecks that register ASTMatchers should do the actual work in here.
static bool isDirectMemberExpr(const Expr *E)
Returns true when the given expression is a member expression whose base is this (implicitly or not)...
const UsageResult & getUsages() const
Accessor for Usages.
static const char LoopNamePseudoArray[]
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...
The information needed to describe a valid convertible usage of an array index or iterator...
CharSourceRange Range
SourceRange for the file name.
void addComponents(const ComponentVector &Components)
Add a set of components that we should consider relevant to the container.
void lowerTo(Confidence::Level Level)
Lower the internal confidence level to Level, but do not raise it.
ClangTidyContext & Context
static const char BeginCallName[]
Every ClangTidyCheck reports errors through a DiagnosticsEngine provided by this context.
static const TypeMatcher AnyType
Class used to find the variables and member expressions on which an arbitrary expression depends...
static const char LoopNameIterator[]
static bool containerIsConst(const Expr *ContainerExpr, bool Dereference)
Returns true if the container is const-qualified.
StatementMatcher makePseudoArrayLoopMatcher()
The matcher used for array-like containers (pseudoarrays).
DiagnosticBuilder diag(SourceLocation Loc, StringRef Description, DiagnosticIDs::Level Level=DiagnosticIDs::Warning)
Add a diagnostic with the check's name.