11 #include "../utils/Matchers.h"
12 #include "clang/AST/ASTContext.h"
13 #include "clang/ASTMatchers/ASTMatchFinder.h"
15 using namespace clang;
16 using namespace clang::ast_matchers;
38 static const TypeMatcher
AnyType = anything();
41 expr(ignoringParenImpCasts(
45 varDecl(hasInitializer(ignoringParenImpCasts(integerLiteral(equals(0)))))
70 StatementMatcher ArrayBoundMatcher =
74 unless(isInTemplateInstantiation()),
77 binaryOperator(hasOperatorName(
"<"),
79 hasRHS(ArrayBoundMatcher)),
80 binaryOperator(hasOperatorName(
">"), hasLHS(ArrayBoundMatcher),
82 hasIncrement(unaryOperator(hasOperatorName(
"++"),
115 StatementMatcher BeginCallMatcher =
118 callee(cxxMethodDecl(anyOf(hasName(
"begin"), hasName(
"cbegin")))))
121 DeclarationMatcher InitDeclMatcher =
122 varDecl(hasInitializer(anyOf(ignoringParenImpCasts(BeginCallMatcher),
123 materializeTemporaryExpr(
124 ignoringParenImpCasts(BeginCallMatcher)),
125 hasDescendant(BeginCallMatcher))))
128 DeclarationMatcher EndDeclMatcher =
129 varDecl(hasInitializer(anything())).bind(
EndVarName);
131 StatementMatcher EndCallMatcher = cxxMemberCallExpr(
133 callee(cxxMethodDecl(anyOf(hasName(
"end"), hasName(
"cend")))));
135 StatementMatcher IteratorBoundMatcher =
136 expr(anyOf(ignoringParenImpCasts(
138 ignoringParenImpCasts(expr(EndCallMatcher).bind(
EndCallName)),
139 materializeTemporaryExpr(ignoringParenImpCasts(
142 StatementMatcher IteratorComparisonMatcher = expr(
145 auto OverloadedNEQMatcher = ignoringImplicit(
146 cxxOperatorCallExpr(hasOverloadedOperatorName(
"!="), argumentCountIs(2),
147 hasArgument(0, IteratorComparisonMatcher),
148 hasArgument(1, IteratorBoundMatcher)));
153 internal::Matcher<VarDecl> TestDerefReturnsByValue =
154 hasType(cxxRecordDecl(hasMethod(allOf(
155 hasOverloadedOperatorName(
"*"),
158 returns(qualType(unless(hasCanonicalType(referenceType())))
163 qualType(unless(hasCanonicalType(rValueReferenceType())))
167 unless(isInTemplateInstantiation()),
168 hasLoopInit(anyOf(declStmt(declCountIs(2),
169 containsDeclaration(0, InitDeclMatcher),
170 containsDeclaration(1, EndDeclMatcher)),
171 declStmt(hasSingleDecl(InitDeclMatcher)))),
173 anyOf(binaryOperator(hasOperatorName(
"!="),
174 hasLHS(IteratorComparisonMatcher),
175 hasRHS(IteratorBoundMatcher)),
176 binaryOperator(hasOperatorName(
"!="),
177 hasLHS(IteratorBoundMatcher),
178 hasRHS(IteratorComparisonMatcher)),
179 OverloadedNEQMatcher)),
181 unaryOperator(hasOperatorName(
"++"),
182 hasUnaryOperand(declRefExpr(
183 to(varDecl(hasType(pointsTo(
AnyType)))
186 hasOverloadedOperatorName(
"++"),
188 0, declRefExpr(to(varDecl(TestDerefReturnsByValue)
234 TypeMatcher RecordWithBeginEnd = qualType(anyOf(
235 qualType(isConstQualified(),
236 hasDeclaration(cxxRecordDecl(
237 hasMethod(cxxMethodDecl(hasName(
"begin"), isConst())),
238 hasMethod(cxxMethodDecl(hasName(
"end"),
242 unless(isConstQualified()),
243 hasDeclaration(cxxRecordDecl(hasMethod(hasName(
"begin")),
244 hasMethod(hasName(
"end")))))
247 StatementMatcher SizeCallMatcher = cxxMemberCallExpr(
249 callee(cxxMethodDecl(anyOf(hasName(
"size"), hasName(
"length")))),
250 on(anyOf(hasType(pointsTo(RecordWithBeginEnd)),
251 hasType(RecordWithBeginEnd))));
253 StatementMatcher EndInitMatcher =
254 expr(anyOf(ignoringParenImpCasts(expr(SizeCallMatcher).bind(
EndCallName)),
255 explicitCastExpr(hasSourceExpression(ignoringParenImpCasts(
258 DeclarationMatcher EndDeclMatcher =
259 varDecl(hasInitializer(EndInitMatcher)).bind(
EndVarName);
261 StatementMatcher IndexBoundMatcher =
262 expr(anyOf(ignoringParenImpCasts(declRefExpr(to(
267 unless(isInTemplateInstantiation()),
269 anyOf(declStmt(declCountIs(2),
271 containsDeclaration(1, EndDeclMatcher)),
274 binaryOperator(hasOperatorName(
"<"),
276 hasRHS(IndexBoundMatcher)),
277 binaryOperator(hasOperatorName(
">"), hasLHS(IndexBoundMatcher),
279 hasIncrement(unaryOperator(hasOperatorName(
"++"),
292 const auto *TheCall =
294 if (!TheCall || TheCall->getNumArgs() != 0)
297 const auto *Member = dyn_cast<MemberExpr>(TheCall->getCallee());
300 StringRef
Name = Member->getMemberDecl()->getName();
301 StringRef TargetName = IsBegin ?
"begin" :
"end";
302 StringRef ConstTargetName = IsBegin ?
"cbegin" :
"cend";
303 if (Name != TargetName && Name != ConstTargetName)
306 const Expr *SourceExpr = Member->getBase();
310 *IsArrow = Member->isArrow();
321 bool *ContainerNeedsDereference) {
324 bool BeginIsArrow =
false;
325 bool EndIsArrow =
false;
326 const Expr *BeginContainerExpr =
328 if (!BeginContainerExpr)
331 const Expr *EndContainerExpr =
335 if (!EndContainerExpr || BeginIsArrow != EndIsArrow ||
336 !
areSameExpr(Context, EndContainerExpr, BeginContainerExpr))
339 *ContainerNeedsDereference = BeginIsArrow;
340 return BeginContainerExpr;
347 if (SourceMgr.getFileID(Range.getBegin()) !=
348 SourceMgr.getFileID(Range.getEnd())) {
352 return Lexer::getSourceText(CharSourceRange(Range,
true), SourceMgr,
360 return dyn_cast<VarDecl>(DRE->getDecl());
361 if (
const auto *Mem = dyn_cast<MemberExpr>(E->IgnoreParenImpCasts()))
362 return dyn_cast<FieldDecl>(Mem->getMemberDecl());
369 if (
const auto *Member = dyn_cast<MemberExpr>(E->IgnoreParenImpCasts()))
370 return isa<CXXThisExpr>(Member->getBase()->IgnoreParenImpCasts());
378 if (E->getType().isConstQualified())
380 auto Parents = Context->getParents(*E);
381 if (Parents.size() != 1)
383 if (
const auto *Cast = Parents[0].get<ImplicitCastExpr>()) {
384 if ((Cast->getCastKind() == CK_NoOp &&
385 Cast->getType() == E->getType().withConst()) ||
386 (Cast->getCastKind() == CK_LValueToRValue &&
387 !Cast->getType().isNull() && Cast->getType()->isFundamentalType()))
397 for (
const Usage &U : Usages) {
403 if (U.Kind != Usage::UK_CaptureByCopy && U.Kind != Usage::UK_CaptureByRef &&
413 for (
const auto &U : Usages) {
414 if (U.Expression && !U.Expression->isRValue())
423 QualType CType = VDec->getType();
425 if (!CType->isPointerType())
427 CType = CType->getPointeeType();
432 CType = CType.getNonReferenceType();
433 return CType.isConstQualified();
438 LoopConvertCheck::RangeDescriptor::RangeDescriptor()
439 : ContainerNeedsDereference(false), DerefByConstRef(false),
440 DerefByValue(false) {}
444 MaxCopySize(std::stoull(Options.get(
"MaxCopySize",
"16"))),
445 MinConfidence(StringSwitch<
Confidence::Level>(
446 Options.get(
"MinConfidence",
"reasonable"))
451 Options.get(
"NamingStyle",
"CamelCase"))
458 Options.
store(Opts,
"MaxCopySize", std::to_string(MaxCopySize));
459 SmallVector<std::string, 3> Confs{
"risky",
"reasonable",
"safe"};
460 Options.
store(Opts,
"MinConfidence", Confs[static_cast<int>(MinConfidence)]);
462 SmallVector<std::string, 4> Styles{
"camelBack",
"CamelCase",
"lower_case",
464 Options.
store(Opts,
"NamingStyle", Styles[static_cast<int>(NamingStyle)]);
492 void LoopConvertCheck::getAliasRange(SourceManager &
SM, SourceRange &
Range) {
493 bool Invalid =
false;
494 const char *TextAfter =
495 SM.getCharacterData(Range.getEnd().getLocWithOffset(1), &Invalid);
498 unsigned Offset = std::strspn(TextAfter,
" \t\r\n");
500 SourceRange(Range.getBegin(), Range.getEnd().getLocWithOffset(Offset));
505 void LoopConvertCheck::doConversion(
506 ASTContext *
Context,
const VarDecl *IndexVar,
507 const ValueDecl *MaybeContainer,
const UsageResult &Usages,
508 const DeclStmt *AliasDecl,
bool AliasUseRequired,
bool AliasFromForInit,
509 const ForStmt *Loop, RangeDescriptor Descriptor) {
510 auto Diag =
diag(Loop->getForLoc(),
"use range-based for loop instead");
513 bool VarNameFromAlias = (Usages.size() == 1) && AliasDecl;
514 bool AliasVarIsRef =
false;
517 if (VarNameFromAlias) {
518 const auto *AliasVar = cast<VarDecl>(AliasDecl->getSingleDecl());
519 VarName = AliasVar->getName().str();
520 AliasVarIsRef = AliasVar->getType()->isReferenceType();
523 SourceRange ReplaceRange = AliasDecl->getSourceRange();
525 std::string ReplacementText;
526 if (AliasUseRequired) {
527 ReplacementText = VarName;
528 }
else if (AliasFromForInit) {
532 ReplacementText =
";";
535 getAliasRange(Context->getSourceManager(), ReplaceRange);
538 Diag << FixItHint::CreateReplacement(
539 CharSourceRange::getTokenRange(ReplaceRange), ReplacementText);
543 VariableNamer Namer(&TUInfo->getGeneratedDecls(),
544 &TUInfo->getParentFinder().getStmtToParentStmtMap(),
545 Loop, IndexVar, MaybeContainer, Context, NamingStyle);
546 VarName = Namer.createIndexName();
549 for (
const auto &Usage : Usages) {
550 std::string ReplaceText;
551 SourceRange Range = Usage.Range;
552 if (Usage.Expression) {
557 auto Parents = Context->getParents(*Usage.Expression);
558 if (Parents.size() == 1) {
559 if (
const auto *Paren = Parents[0].get<ParenExpr>()) {
563 Range = Paren->getSourceRange();
564 }
else if (
const auto *UOP = Parents[0].get<UnaryOperator>()) {
572 if (UOP->getOpcode() == UO_AddrOf)
583 TUInfo->getReplacedVars().insert(std::make_pair(Loop, IndexVar));
584 Diag << FixItHint::CreateReplacement(
585 CharSourceRange::getTokenRange(Range), ReplaceText);
590 SourceRange ParenRange(Loop->getLParenLoc(), Loop->getRParenLoc());
592 QualType Type = Context->getAutoDeductType();
593 if (!Descriptor.ElemType.isNull() && Descriptor.ElemType->isFundamentalType())
594 Type = Descriptor.ElemType.getUnqualifiedType();
600 !Descriptor.ElemType.isNull() &&
601 Descriptor.ElemType.isTriviallyCopyableType(*Context) &&
603 Context->getTypeInfo(Descriptor.ElemType).Width <= 8 * MaxCopySize;
604 bool UseCopy = CanCopy && ((VarNameFromAlias && !AliasVarIsRef) ||
605 (Descriptor.DerefByConstRef && IsCheapToCopy));
608 if (Descriptor.DerefByConstRef) {
609 Type = Context->getLValueReferenceType(Context->getConstType(Type));
610 }
else if (Descriptor.DerefByValue) {
612 Type = Context->getRValueReferenceType(Type);
614 Type = Context->getLValueReferenceType(Type);
618 StringRef MaybeDereference = Descriptor.ContainerNeedsDereference ?
"*" :
"";
619 std::string TypeString = Type.getAsString(
getLangOpts());
620 std::string Range = (
"(" + TypeString +
" " + VarName +
" : " +
621 MaybeDereference + Descriptor.ContainerString +
")")
623 Diag << FixItHint::CreateReplacement(
624 CharSourceRange::getTokenRange(ParenRange), Range);
625 TUInfo->getGeneratedDecls().insert(make_pair(Loop, VarName));
629 StringRef LoopConvertCheck::getContainerString(ASTContext *Context,
631 const Expr *ContainerExpr) {
632 StringRef ContainerString;
633 if (isa<CXXThisExpr>(ContainerExpr->IgnoreParenImpCasts())) {
634 ContainerString =
"this";
638 ContainerExpr->getSourceRange());
641 return ContainerString;
646 void LoopConvertCheck::getArrayLoopQualifiers(ASTContext *Context,
647 const BoundNodes &Nodes,
648 const Expr *ContainerExpr,
650 RangeDescriptor &Descriptor) {
655 Descriptor.DerefByConstRef =
true;
661 Descriptor.DerefByValue =
true;
665 for (
const Usage &U : Usages) {
666 if (!U.Expression || U.Expression->getType().isNull())
668 QualType Type = U.Expression->getType().getCanonicalType();
670 if (!Type->isPointerType()) {
673 Type = Type->getPointeeType();
675 Descriptor.ElemType = Type;
681 void LoopConvertCheck::getIteratorLoopQualifiers(ASTContext *Context,
682 const BoundNodes &Nodes,
683 RangeDescriptor &Descriptor) {
686 const auto *InitVar = Nodes.getDeclAs<VarDecl>(
InitVarName);
687 QualType CanonicalInitVarType = InitVar->getType().getCanonicalType();
688 const auto *DerefByValueType =
690 Descriptor.DerefByValue = DerefByValueType;
692 if (Descriptor.DerefByValue) {
695 Descriptor.DerefByConstRef = CanonicalInitVarType.isConstQualified();
696 Descriptor.ElemType = *DerefByValueType;
698 if (
const auto *DerefType =
703 auto ValueType = DerefType->getNonReferenceType();
705 Descriptor.DerefByConstRef = ValueType.isConstQualified();
706 Descriptor.ElemType = ValueType;
710 assert(isa<PointerType>(CanonicalInitVarType) &&
711 "Non-class iterator type is not a pointer type");
714 Descriptor.DerefByConstRef =
715 CanonicalInitVarType->getPointeeType().isConstQualified();
716 Descriptor.ElemType = CanonicalInitVarType->getPointeeType();
722 void LoopConvertCheck::determineRangeDescriptor(
723 ASTContext *Context,
const BoundNodes &Nodes,
const ForStmt *Loop,
725 const UsageResult &Usages, RangeDescriptor &Descriptor) {
726 Descriptor.ContainerString = getContainerString(Context, Loop, ContainerExpr);
729 getIteratorLoopQualifiers(Context, Nodes, Descriptor);
731 getArrayLoopQualifiers(Context, Nodes, ContainerExpr, Usages, Descriptor);
736 bool LoopConvertCheck::isConvertible(ASTContext *Context,
737 const ast_matchers::BoundNodes &Nodes,
742 if (TUInfo->getReplacedVars().count(Loop))
748 const auto *InitVar = Nodes.getDeclAs<VarDecl>(
InitVarName);
751 const auto *EndVar = Nodes.getDeclAs<VarDecl>(
EndVarName);
758 QualType InitVarType = InitVar->getType();
759 QualType CanonicalInitVarType = InitVarType.getCanonicalType();
761 const auto *BeginCall = Nodes.getNodeAs<CXXMemberCallExpr>(
BeginCallName);
762 assert(BeginCall &&
"Bad Callback. No begin call expression");
763 QualType CanonicalBeginType =
764 BeginCall->getMethodDecl()->getReturnType().getCanonicalType();
765 if (CanonicalBeginType->isPointerType() &&
766 CanonicalInitVarType->isPointerType()) {
769 if (!Context->hasSameUnqualifiedType(
770 CanonicalBeginType->getPointeeType(),
771 CanonicalInitVarType->getPointeeType()))
773 }
else if (!Context->hasSameType(CanonicalInitVarType,
774 CanonicalBeginType)) {
781 const auto *EndCall = Nodes.getStmtAs<CXXMemberCallExpr>(
EndCallName);
782 if (!EndCall || !dyn_cast<MemberExpr>(EndCall->getCallee()))
789 const BoundNodes &Nodes = Result.Nodes;
791 ASTContext *Context = Result.Context;
795 RangeDescriptor Descriptor;
803 assert(Loop &&
"Bad Callback. No for statement");
807 if (!isConvertible(Context, Nodes, Loop, FixerKind))
811 const auto *EndVar = Nodes.getDeclAs<VarDecl>(
EndVarName);
820 const auto *EndCall = Nodes.getStmtAs<CXXMemberCallExpr>(
EndCallName);
827 const Expr *ContainerExpr =
nullptr;
830 EndVar ? EndVar->getInit() : EndCall,
831 &Descriptor.ContainerNeedsDereference);
833 ContainerExpr = EndCall->getImplicitObjectArgument();
834 Descriptor.ContainerNeedsDereference =
835 dyn_cast<MemberExpr>(EndCall->getCallee())->isArrow();
839 if (!ContainerExpr && !BoundExpr)
844 Descriptor.ContainerNeedsDereference);
873 determineRangeDescriptor(Context, Nodes, Loop, FixerKind, ContainerExpr,
880 TUInfo->getParentFinder().gatherAncestors(Context->getTranslationUnitDecl());
882 &TUInfo->getParentFinder().getStmtToParentStmtMap(),
883 &TUInfo->getParentFinder().getDeclToParentStmtMap(),
884 &TUInfo->getReplacedVars(), Loop);
886 if (DependencyFinder.dependsOnInsideVariable(ContainerExpr) ||
887 Descriptor.ContainerString.empty() || Usages.empty() ||
888 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.