1 //===--- ImplicitConversionInLoopCheck.cpp - clang-tidy--------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "ImplicitConversionInLoopCheck.h"
10 
11 #include "clang/AST/ASTContext.h"
12 #include "clang/AST/Decl.h"
13 #include "clang/ASTMatchers/ASTMatchFinder.h"
14 #include "clang/ASTMatchers/ASTMatchers.h"
15 #include "clang/Lex/Lexer.h"
16 
17 using namespace clang::ast_matchers;
18 
19 namespace clang {
20 namespace tidy {
21 namespace performance {
22 
23 // Checks if the stmt is a ImplicitCastExpr with a CastKind that is not a NoOp.
24 // The subtelty is that in some cases (user defined conversions), we can
25 // get to ImplicitCastExpr inside each other, with the outer one a NoOp. In this
26 // case we skip the first cast expr.
IsNonTrivialImplicitCast(const Stmt * ST)27 static bool IsNonTrivialImplicitCast(const Stmt *ST) {
28   if (const auto *ICE = dyn_cast<ImplicitCastExpr>(ST)) {
29     return (ICE->getCastKind() != CK_NoOp) ||
30             IsNonTrivialImplicitCast(ICE->getSubExpr());
31   }
32   return false;
33 }
34 
registerMatchers(MatchFinder * Finder)35 void ImplicitConversionInLoopCheck::registerMatchers(MatchFinder *Finder) {
36   // We look for const ref loop variables that (optionally inside an
37   // ExprWithCleanup) materialize a temporary, and contain a implicit
38   // conversion. The check on the implicit conversion is done in check() because
39   // we can't access implicit conversion subnode via matchers: has() skips casts
40   // and materialize! We also bind on the call to operator* to get the proper
41   // type in the diagnostic message. We use both cxxOperatorCallExpr for user
42   // defined operator and unaryOperator when the iterator is a pointer, like
43   // for arrays or std::array.
44   //
45   // Note that when the implicit conversion is done through a user defined
46   // conversion operator, the node is a CXXMemberCallExpr, not a
47   // CXXOperatorCallExpr, so it should not get caught by the
48   // cxxOperatorCallExpr() matcher.
49   Finder->addMatcher(
50       traverse(
51           ast_type_traits::TK_AsIs,
52           cxxForRangeStmt(hasLoopVariable(
53               varDecl(
54                   hasType(qualType(references(qualType(isConstQualified())))),
55                   hasInitializer(
56                       expr(anyOf(
57                                hasDescendant(
58                                    cxxOperatorCallExpr().bind("operator-call")),
59                                hasDescendant(unaryOperator(hasOperatorName("*"))
60                                                  .bind("operator-call"))))
61                           .bind("init")))
62                   .bind("faulty-var")))),
63       this);
64 }
65 
check(const MatchFinder::MatchResult & Result)66 void ImplicitConversionInLoopCheck::check(
67     const MatchFinder::MatchResult &Result) {
68   const auto *VD = Result.Nodes.getNodeAs<VarDecl>("faulty-var");
69   const auto *Init = Result.Nodes.getNodeAs<Expr>("init");
70   const auto *OperatorCall =
71       Result.Nodes.getNodeAs<Expr>("operator-call");
72 
73   if (const auto *Cleanup = dyn_cast<ExprWithCleanups>(Init))
74     Init = Cleanup->getSubExpr();
75 
76   const auto *Materialized = dyn_cast<MaterializeTemporaryExpr>(Init);
77   if (!Materialized)
78     return;
79 
80   // We ignore NoOp casts. Those are generated if the * operator on the
81   // iterator returns a value instead of a reference, and the loop variable
82   // is a reference. This situation is fine (it probably produces the same
83   // code at the end).
84   if (IsNonTrivialImplicitCast(Materialized->getSubExpr()))
85     ReportAndFix(Result.Context, VD, OperatorCall);
86 }
87 
ReportAndFix(const ASTContext * Context,const VarDecl * VD,const Expr * OperatorCall)88 void ImplicitConversionInLoopCheck::ReportAndFix(
89     const ASTContext *Context, const VarDecl *VD,
90     const Expr *OperatorCall) {
91   // We only match on const ref, so we should print a const ref version of the
92   // type.
93   QualType ConstType = OperatorCall->getType().withConst();
94   QualType ConstRefType = Context->getLValueReferenceType(ConstType);
95   const char Message[] =
96       "the type of the loop variable %0 is different from the one returned "
97       "by the iterator and generates an implicit conversion; you can either "
98       "change the type to the matching one (%1 but 'const auto&' is always a "
99       "valid option) or remove the reference to make it explicit that you are "
100       "creating a new value";
101   diag(VD->getBeginLoc(), Message) << VD << ConstRefType;
102 }
103 
104 } // namespace performance
105 } // namespace tidy
106 } // namespace clang
107