11 #include "clang/AST/ASTContext.h"
12 #include "clang/ASTMatchers/ASTMatchFinder.h"
14 using namespace clang;
15 using namespace clang::ast_matchers;
37 static const TypeMatcher
AnyType = anything();
40 expr(ignoringParenImpCasts(
44 varDecl(hasInitializer(ignoringParenImpCasts(integerLiteral(equals(0)))))
69 StatementMatcher ArrayBoundMatcher =
73 unless(isInTemplateInstantiation()),
76 binaryOperator(hasOperatorName(
"<"),
78 hasRHS(ArrayBoundMatcher)),
79 binaryOperator(hasOperatorName(
">"), hasLHS(ArrayBoundMatcher),
81 hasIncrement(unaryOperator(hasOperatorName(
"++"),
114 StatementMatcher BeginCallMatcher =
117 callee(cxxMethodDecl(anyOf(hasName(
"begin"), hasName(
"cbegin")))))
120 DeclarationMatcher InitDeclMatcher =
121 varDecl(hasInitializer(anyOf(ignoringParenImpCasts(BeginCallMatcher),
122 materializeTemporaryExpr(
123 ignoringParenImpCasts(BeginCallMatcher)),
124 hasDescendant(BeginCallMatcher))))
127 DeclarationMatcher EndDeclMatcher =
128 varDecl(hasInitializer(anything())).bind(
EndVarName);
130 StatementMatcher EndCallMatcher = cxxMemberCallExpr(
132 callee(cxxMethodDecl(anyOf(hasName(
"end"), hasName(
"cend")))));
134 StatementMatcher IteratorBoundMatcher =
135 expr(anyOf(ignoringParenImpCasts(
137 ignoringParenImpCasts(expr(EndCallMatcher).bind(
EndCallName)),
138 materializeTemporaryExpr(ignoringParenImpCasts(
141 StatementMatcher IteratorComparisonMatcher = expr(
144 StatementMatcher OverloadedNEQMatcher =
145 cxxOperatorCallExpr(hasOverloadedOperatorName(
"!="), argumentCountIs(2),
146 hasArgument(0, IteratorComparisonMatcher),
147 hasArgument(1, IteratorBoundMatcher));
152 internal::Matcher<VarDecl> TestDerefReturnsByValue =
153 hasType(cxxRecordDecl(hasMethod(allOf(
154 hasOverloadedOperatorName(
"*"),
157 returns(qualType(unless(hasCanonicalType(referenceType())))
162 qualType(unless(hasCanonicalType(rValueReferenceType())))
166 unless(isInTemplateInstantiation()),
167 hasLoopInit(anyOf(declStmt(declCountIs(2),
168 containsDeclaration(0, InitDeclMatcher),
169 containsDeclaration(1, EndDeclMatcher)),
170 declStmt(hasSingleDecl(InitDeclMatcher)))),
172 anyOf(binaryOperator(hasOperatorName(
"!="),
173 hasLHS(IteratorComparisonMatcher),
174 hasRHS(IteratorBoundMatcher)),
175 binaryOperator(hasOperatorName(
"!="),
176 hasLHS(IteratorBoundMatcher),
177 hasRHS(IteratorComparisonMatcher)),
178 OverloadedNEQMatcher)),
180 unaryOperator(hasOperatorName(
"++"),
181 hasUnaryOperand(declRefExpr(
182 to(varDecl(hasType(pointsTo(
AnyType)))
185 hasOverloadedOperatorName(
"++"),
187 0, declRefExpr(to(varDecl(TestDerefReturnsByValue)
233 TypeMatcher RecordWithBeginEnd = qualType(anyOf(
234 qualType(isConstQualified(),
235 hasDeclaration(cxxRecordDecl(
236 hasMethod(cxxMethodDecl(hasName(
"begin"), isConst())),
237 hasMethod(cxxMethodDecl(hasName(
"end"),
241 unless(isConstQualified()),
242 hasDeclaration(cxxRecordDecl(hasMethod(hasName(
"begin")),
243 hasMethod(hasName(
"end")))))
246 StatementMatcher SizeCallMatcher = cxxMemberCallExpr(
248 callee(cxxMethodDecl(anyOf(hasName(
"size"), hasName(
"length")))),
249 on(anyOf(hasType(pointsTo(RecordWithBeginEnd)),
250 hasType(RecordWithBeginEnd))));
252 StatementMatcher EndInitMatcher =
253 expr(anyOf(ignoringParenImpCasts(expr(SizeCallMatcher).bind(
EndCallName)),
254 explicitCastExpr(hasSourceExpression(ignoringParenImpCasts(
257 DeclarationMatcher EndDeclMatcher =
258 varDecl(hasInitializer(EndInitMatcher)).bind(
EndVarName);
260 StatementMatcher IndexBoundMatcher =
261 expr(anyOf(ignoringParenImpCasts(declRefExpr(to(
266 unless(isInTemplateInstantiation()),
268 anyOf(declStmt(declCountIs(2),
270 containsDeclaration(1, EndDeclMatcher)),
273 binaryOperator(hasOperatorName(
"<"),
275 hasRHS(IndexBoundMatcher)),
276 binaryOperator(hasOperatorName(
">"), hasLHS(IndexBoundMatcher),
278 hasIncrement(unaryOperator(hasOperatorName(
"++"),
291 const auto *TheCall =
293 if (!TheCall || TheCall->getNumArgs() != 0)
296 const auto *Member = dyn_cast<MemberExpr>(TheCall->getCallee());
299 StringRef
Name = Member->getMemberDecl()->getName();
300 StringRef TargetName = IsBegin ?
"begin" :
"end";
301 StringRef ConstTargetName = IsBegin ?
"cbegin" :
"cend";
302 if (Name != TargetName && Name != ConstTargetName)
305 const Expr *SourceExpr = Member->getBase();
309 *IsArrow = Member->isArrow();
320 bool *ContainerNeedsDereference) {
323 bool BeginIsArrow =
false;
324 bool EndIsArrow =
false;
325 const Expr *BeginContainerExpr =
327 if (!BeginContainerExpr)
330 const Expr *EndContainerExpr =
334 if (!EndContainerExpr || BeginIsArrow != EndIsArrow ||
335 !
areSameExpr(Context, EndContainerExpr, BeginContainerExpr))
338 *ContainerNeedsDereference = BeginIsArrow;
339 return BeginContainerExpr;
346 if (SourceMgr.getFileID(Range.getBegin()) !=
347 SourceMgr.getFileID(Range.getEnd())) {
351 return Lexer::getSourceText(CharSourceRange(Range,
true), SourceMgr,
359 return dyn_cast<VarDecl>(DRE->getDecl());
360 if (
const auto *Mem = dyn_cast<MemberExpr>(E->IgnoreParenImpCasts()))
361 return dyn_cast<FieldDecl>(Mem->getMemberDecl());
368 if (
const auto *Member = dyn_cast<MemberExpr>(E->IgnoreParenImpCasts()))
369 return isa<CXXThisExpr>(Member->getBase()->IgnoreParenImpCasts());
377 if (E->getType().isConstQualified())
379 auto Parents = Context->getParents(*E);
380 if (Parents.size() != 1)
382 if (
const auto *Cast = Parents[0].get<ImplicitCastExpr>()) {
383 if ((Cast->getCastKind() == CK_NoOp &&
384 Cast->getType() == E->getType().withConst()) ||
385 (Cast->getCastKind() == CK_LValueToRValue &&
386 !Cast->getType().isNull() && Cast->getType()->isFundamentalType()))
396 for (
const Usage &U : Usages) {
402 if (U.Kind != Usage::UK_CaptureByCopy && U.Kind != Usage::UK_CaptureByRef &&
412 for (
const auto &U : Usages) {
413 if (U.Expression && !U.Expression->isRValue())
422 QualType CType = VDec->getType();
424 if (!CType->isPointerType())
426 CType = CType->getPointeeType();
431 CType = CType.getNonReferenceType();
432 return CType.isConstQualified();
437 LoopConvertCheck::RangeDescriptor::RangeDescriptor()
438 : ContainerNeedsDereference(false), DerefByConstRef(false),
439 DerefByValue(false) {}
443 MaxCopySize(std::stoull(Options.get(
"MaxCopySize",
"16"))),
444 MinConfidence(StringSwitch<
Confidence::Level>(
445 Options.get(
"MinConfidence",
"reasonable"))
450 Options.get(
"NamingStyle",
"CamelCase"))
457 Options.
store(Opts,
"MaxCopySize", std::to_string(MaxCopySize));
458 SmallVector<std::string, 3> Confs{
"risky",
"reasonable",
"safe"};
459 Options.
store(Opts,
"MinConfidence", Confs[static_cast<int>(MinConfidence)]);
461 SmallVector<std::string, 4> Styles{
"camelBack",
"CamelCase",
"lower_case",
463 Options.
store(Opts,
"NamingStyle", Styles[static_cast<int>(NamingStyle)]);
491 void LoopConvertCheck::getAliasRange(SourceManager &
SM, SourceRange &
Range) {
492 bool Invalid =
false;
493 const char *TextAfter =
494 SM.getCharacterData(Range.getEnd().getLocWithOffset(1), &Invalid);
497 unsigned Offset = std::strspn(TextAfter,
" \t\r\n");
499 SourceRange(Range.getBegin(), Range.getEnd().getLocWithOffset(Offset));
504 void LoopConvertCheck::doConversion(
505 ASTContext *
Context,
const VarDecl *IndexVar,
506 const ValueDecl *MaybeContainer,
const UsageResult &Usages,
507 const DeclStmt *AliasDecl,
bool AliasUseRequired,
bool AliasFromForInit,
508 const ForStmt *Loop, RangeDescriptor Descriptor) {
509 auto Diag =
diag(Loop->getForLoc(),
"use range-based for loop instead");
512 bool VarNameFromAlias = (Usages.size() == 1) && AliasDecl;
513 bool AliasVarIsRef =
false;
516 if (VarNameFromAlias) {
517 const auto *AliasVar = cast<VarDecl>(AliasDecl->getSingleDecl());
518 VarName = AliasVar->getName().str();
519 AliasVarIsRef = AliasVar->getType()->isReferenceType();
522 SourceRange ReplaceRange = AliasDecl->getSourceRange();
524 std::string ReplacementText;
525 if (AliasUseRequired) {
526 ReplacementText = VarName;
527 }
else if (AliasFromForInit) {
531 ReplacementText =
";";
534 getAliasRange(Context->getSourceManager(), ReplaceRange);
537 Diag << FixItHint::CreateReplacement(
538 CharSourceRange::getTokenRange(ReplaceRange), ReplacementText);
542 VariableNamer Namer(&TUInfo->getGeneratedDecls(),
543 &TUInfo->getParentFinder().getStmtToParentStmtMap(),
544 Loop, IndexVar, MaybeContainer, Context, NamingStyle);
545 VarName = Namer.createIndexName();
548 for (
const auto &Usage : Usages) {
549 std::string ReplaceText;
550 SourceRange Range = Usage.Range;
551 if (Usage.Expression) {
556 auto Parents = Context->getParents(*Usage.Expression);
557 if (Parents.size() == 1) {
558 if (
const auto *Paren = Parents[0].get<ParenExpr>()) {
562 Range = Paren->getSourceRange();
563 }
else if (
const auto *UOP = Parents[0].get<UnaryOperator>()) {
571 if (UOP->getOpcode() == UO_AddrOf)
582 TUInfo->getReplacedVars().insert(std::make_pair(Loop, IndexVar));
583 Diag << FixItHint::CreateReplacement(
584 CharSourceRange::getTokenRange(Range), ReplaceText);
589 SourceRange ParenRange(Loop->getLParenLoc(), Loop->getRParenLoc());
591 QualType Type = Context->getAutoDeductType();
592 if (!Descriptor.ElemType.isNull() && Descriptor.ElemType->isFundamentalType())
593 Type = Descriptor.ElemType.getUnqualifiedType();
599 !Descriptor.ElemType.isNull() &&
600 Descriptor.ElemType.isTriviallyCopyableType(*Context) &&
602 Context->getTypeInfo(Descriptor.ElemType).Width <= 8 * MaxCopySize;
603 bool UseCopy = CanCopy && ((VarNameFromAlias && !AliasVarIsRef) ||
604 (Descriptor.DerefByConstRef && IsCheapToCopy));
607 if (Descriptor.DerefByConstRef) {
608 Type = Context->getLValueReferenceType(Context->getConstType(Type));
609 }
else if (Descriptor.DerefByValue) {
611 Type = Context->getRValueReferenceType(Type);
613 Type = Context->getLValueReferenceType(Type);
617 StringRef MaybeDereference = Descriptor.ContainerNeedsDereference ?
"*" :
"";
618 std::string TypeString = Type.getAsString(
getLangOpts());
619 std::string Range = (
"(" + TypeString +
" " + VarName +
" : " +
620 MaybeDereference + Descriptor.ContainerString +
")")
622 Diag << FixItHint::CreateReplacement(
623 CharSourceRange::getTokenRange(ParenRange), Range);
624 TUInfo->getGeneratedDecls().insert(make_pair(Loop, VarName));
628 StringRef LoopConvertCheck::getContainerString(ASTContext *Context,
630 const Expr *ContainerExpr) {
631 StringRef ContainerString;
632 if (isa<CXXThisExpr>(ContainerExpr->IgnoreParenImpCasts())) {
633 ContainerString =
"this";
637 ContainerExpr->getSourceRange());
640 return ContainerString;
645 void LoopConvertCheck::getArrayLoopQualifiers(ASTContext *Context,
646 const BoundNodes &Nodes,
647 const Expr *ContainerExpr,
649 RangeDescriptor &Descriptor) {
654 Descriptor.DerefByConstRef =
true;
660 Descriptor.DerefByValue =
true;
664 for (
const Usage &U : Usages) {
665 if (!U.Expression || U.Expression->getType().isNull())
667 QualType Type = U.Expression->getType().getCanonicalType();
669 if (!Type->isPointerType()) {
672 Type = Type->getPointeeType();
674 Descriptor.ElemType = Type;
680 void LoopConvertCheck::getIteratorLoopQualifiers(ASTContext *Context,
681 const BoundNodes &Nodes,
682 RangeDescriptor &Descriptor) {
685 const auto *InitVar = Nodes.getDeclAs<VarDecl>(
InitVarName);
686 QualType CanonicalInitVarType = InitVar->getType().getCanonicalType();
687 const auto *DerefByValueType =
689 Descriptor.DerefByValue = DerefByValueType;
691 if (Descriptor.DerefByValue) {
694 Descriptor.DerefByConstRef = CanonicalInitVarType.isConstQualified();
695 Descriptor.ElemType = *DerefByValueType;
697 if (
const auto *DerefType =
702 auto ValueType = DerefType->getNonReferenceType();
704 Descriptor.DerefByConstRef = ValueType.isConstQualified();
705 Descriptor.ElemType = ValueType;
709 assert(isa<PointerType>(CanonicalInitVarType) &&
710 "Non-class iterator type is not a pointer type");
713 Descriptor.DerefByConstRef =
714 CanonicalInitVarType->getPointeeType().isConstQualified();
715 Descriptor.ElemType = CanonicalInitVarType->getPointeeType();
721 void LoopConvertCheck::determineRangeDescriptor(
722 ASTContext *Context,
const BoundNodes &Nodes,
const ForStmt *Loop,
724 const UsageResult &Usages, RangeDescriptor &Descriptor) {
725 Descriptor.ContainerString = getContainerString(Context, Loop, ContainerExpr);
728 getIteratorLoopQualifiers(Context, Nodes, Descriptor);
730 getArrayLoopQualifiers(Context, Nodes, ContainerExpr, Usages, Descriptor);
735 bool LoopConvertCheck::isConvertible(ASTContext *Context,
736 const ast_matchers::BoundNodes &Nodes,
741 if (TUInfo->getReplacedVars().count(Loop))
747 const auto *InitVar = Nodes.getDeclAs<VarDecl>(
InitVarName);
750 const auto *EndVar = Nodes.getDeclAs<VarDecl>(
EndVarName);
757 QualType InitVarType = InitVar->getType();
758 QualType CanonicalInitVarType = InitVarType.getCanonicalType();
760 const auto *BeginCall = Nodes.getNodeAs<CXXMemberCallExpr>(
BeginCallName);
761 assert(BeginCall &&
"Bad Callback. No begin call expression");
762 QualType CanonicalBeginType =
763 BeginCall->getMethodDecl()->getReturnType().getCanonicalType();
764 if (CanonicalBeginType->isPointerType() &&
765 CanonicalInitVarType->isPointerType()) {
768 if (!Context->hasSameUnqualifiedType(
769 CanonicalBeginType->getPointeeType(),
770 CanonicalInitVarType->getPointeeType()))
772 }
else if (!Context->hasSameType(CanonicalInitVarType,
773 CanonicalBeginType)) {
780 const auto *EndCall = Nodes.getStmtAs<CXXMemberCallExpr>(
EndCallName);
781 if (!EndCall || !dyn_cast<MemberExpr>(EndCall->getCallee()))
788 const BoundNodes &Nodes = Result.Nodes;
790 ASTContext *Context = Result.Context;
794 RangeDescriptor Descriptor;
802 assert(Loop &&
"Bad Callback. No for statement");
806 if (!isConvertible(Context, Nodes, Loop, FixerKind))
810 const auto *EndVar = Nodes.getDeclAs<VarDecl>(
EndVarName);
819 const auto *EndCall = Nodes.getStmtAs<CXXMemberCallExpr>(
EndCallName);
826 const Expr *ContainerExpr =
nullptr;
829 EndVar ? EndVar->getInit() : EndCall,
830 &Descriptor.ContainerNeedsDereference);
832 ContainerExpr = EndCall->getImplicitObjectArgument();
833 Descriptor.ContainerNeedsDereference =
834 dyn_cast<MemberExpr>(EndCall->getCallee())->isArrow();
838 if (!ContainerExpr && !BoundExpr)
843 Descriptor.ContainerNeedsDereference);
872 determineRangeDescriptor(Context, Nodes, Loop, FixerKind, ContainerExpr,
879 TUInfo->getParentFinder().gatherAncestors(Context->getTranslationUnitDecl());
881 &TUInfo->getParentFinder().getStmtToParentStmtMap(),
882 &TUInfo->getParentFinder().getDeclToParentStmtMap(),
883 &TUInfo->getReplacedVars(), Loop);
885 if (DependencyFinder.dependsOnInsideVariable(ContainerExpr) ||
886 Descriptor.ContainerString.empty() || Usages.empty() ||
887 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 ASTMatchers 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.