| 1 | //===--- AvoidCStyleCastsCheck.cpp - clang-tidy -----------------*- C++ -*-===// |
| 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 "AvoidCStyleCastsCheck.h" |
| 10 | #include "clang/AST/ASTContext.h" |
| 11 | #include "clang/ASTMatchers/ASTMatchFinder.h" |
| 12 | #include "clang/ASTMatchers/ASTMatchers.h" |
| 13 | #include "clang/Lex/Lexer.h" |
| 14 | |
| 15 | using namespace clang::ast_matchers; |
| 16 | |
| 17 | namespace clang::tidy::google::readability { |
| 18 | |
| 19 | void AvoidCStyleCastsCheck::registerMatchers( |
| 20 | ast_matchers::MatchFinder *Finder) { |
| 21 | Finder->addMatcher( |
| 22 | cStyleCastExpr( |
| 23 | // Filter out (EnumType)IntegerLiteral construct, which is generated |
| 24 | // for non-type template arguments of enum types. |
| 25 | // FIXME: Remove this once this is fixed in the AST. |
| 26 | unless(hasParent(substNonTypeTemplateParmExpr())), |
| 27 | // Avoid matches in template instantiations. |
| 28 | unless(isInTemplateInstantiation())) |
| 29 | .bind("cast"), |
| 30 | this); |
| 31 | Finder->addMatcher( |
| 32 | cxxFunctionalCastExpr(unless(hasDescendant(cxxConstructExpr())), |
| 33 | unless(hasDescendant(initListExpr()))) |
| 34 | .bind("cast"), |
| 35 | this); |
| 36 | } |
| 37 | |
| 38 | static bool needsConstCast(QualType SourceType, QualType DestType) { |
| 39 | while ((SourceType->isPointerType() && DestType->isPointerType()) || |
| 40 | (SourceType->isReferenceType() && DestType->isReferenceType())) { |
| 41 | SourceType = SourceType->getPointeeType(); |
| 42 | DestType = DestType->getPointeeType(); |
| 43 | if (SourceType.isConstQualified() && !DestType.isConstQualified()) { |
| 44 | return (SourceType->isPointerType() == DestType->isPointerType()) && |
| 45 | (SourceType->isReferenceType() == DestType->isReferenceType()); |
| 46 | } |
| 47 | } |
| 48 | return false; |
| 49 | } |
| 50 | |
| 51 | static bool pointedUnqualifiedTypesAreEqual(QualType T1, QualType T2) { |
| 52 | while ((T1->isPointerType() && T2->isPointerType()) || |
| 53 | (T1->isReferenceType() && T2->isReferenceType())) { |
| 54 | T1 = T1->getPointeeType(); |
| 55 | T2 = T2->getPointeeType(); |
| 56 | } |
| 57 | return T1.getUnqualifiedType() == T2.getUnqualifiedType(); |
| 58 | } |
| 59 | |
| 60 | static clang::CharSourceRange getReplaceRange(const ExplicitCastExpr *Expr) { |
| 61 | if (const auto *CastExpr = dyn_cast<CStyleCastExpr>(Expr)) { |
| 62 | return CharSourceRange::getCharRange( |
| 63 | CastExpr->getLParenLoc(), |
| 64 | CastExpr->getSubExprAsWritten()->getBeginLoc()); |
| 65 | } else if (const auto *CastExpr = dyn_cast<CXXFunctionalCastExpr>(Expr)) { |
| 66 | return CharSourceRange::getCharRange(CastExpr->getBeginLoc(), |
| 67 | CastExpr->getLParenLoc()); |
| 68 | } else |
| 69 | llvm_unreachable("Unsupported CastExpr"); |
| 70 | } |
| 71 | |
| 72 | static StringRef getDestTypeString(const SourceManager &SM, |
| 73 | const LangOptions &LangOpts, |
| 74 | const ExplicitCastExpr *Expr) { |
| 75 | SourceLocation BeginLoc; |
| 76 | SourceLocation EndLoc; |
| 77 | |
| 78 | if (const auto *CastExpr = dyn_cast<CStyleCastExpr>(Expr)) { |
| 79 | BeginLoc = CastExpr->getLParenLoc().getLocWithOffset(1); |
| 80 | EndLoc = CastExpr->getRParenLoc().getLocWithOffset(-1); |
| 81 | } else if (const auto *CastExpr = dyn_cast<CXXFunctionalCastExpr>(Expr)) { |
| 82 | BeginLoc = CastExpr->getBeginLoc(); |
| 83 | EndLoc = CastExpr->getLParenLoc().getLocWithOffset(-1); |
| 84 | } else |
| 85 | llvm_unreachable("Unsupported CastExpr"); |
| 86 | |
| 87 | return Lexer::getSourceText(CharSourceRange::getTokenRange(BeginLoc, EndLoc), |
| 88 | SM, LangOpts); |
| 89 | } |
| 90 | |
| 91 | void AvoidCStyleCastsCheck::check(const MatchFinder::MatchResult &Result) { |
| 92 | const auto *CastExpr = Result.Nodes.getNodeAs<ExplicitCastExpr>("cast"); |
| 93 | |
| 94 | // Ignore casts in macros. |
| 95 | if (CastExpr->getExprLoc().isMacroID()) |
| 96 | return; |
| 97 | |
| 98 | // Casting to void is an idiomatic way to mute "unused variable" and similar |
| 99 | // warnings. |
| 100 | if (CastExpr->getCastKind() == CK_ToVoid) |
| 101 | return; |
| 102 | |
| 103 | auto IsFunction = [](QualType T) { |
| 104 | T = T.getCanonicalType().getNonReferenceType(); |
| 105 | return T->isFunctionType() || T->isFunctionPointerType() || |
| 106 | T->isMemberFunctionPointerType(); |
| 107 | }; |
| 108 | |
| 109 | const QualType DestTypeAsWritten = |
| 110 | CastExpr->getTypeAsWritten().getUnqualifiedType(); |
| 111 | const QualType SourceTypeAsWritten = |
| 112 | CastExpr->getSubExprAsWritten()->getType().getUnqualifiedType(); |
| 113 | const QualType SourceType = SourceTypeAsWritten.getCanonicalType(); |
| 114 | const QualType DestType = DestTypeAsWritten.getCanonicalType(); |
| 115 | |
| 116 | CharSourceRange ReplaceRange = getReplaceRange(CastExpr); |
| 117 | |
| 118 | bool FnToFnCast = |
| 119 | IsFunction(SourceTypeAsWritten) && IsFunction(DestTypeAsWritten); |
| 120 | |
| 121 | const bool ConstructorCast = !CastExpr->getTypeAsWritten().hasQualifiers() && |
| 122 | DestTypeAsWritten->isRecordType() && |
| 123 | !DestTypeAsWritten->isElaboratedTypeSpecifier(); |
| 124 | |
| 125 | if (CastExpr->getCastKind() == CK_NoOp && !FnToFnCast) { |
| 126 | // Function pointer/reference casts may be needed to resolve ambiguities in |
| 127 | // case of overloaded functions, so detection of redundant casts is trickier |
| 128 | // in this case. Don't emit "redundant cast" warnings for function |
| 129 | // pointer/reference types. |
| 130 | QualType Src = SourceTypeAsWritten, Dst = DestTypeAsWritten; |
| 131 | if (const auto *ElTy = dyn_cast<ElaboratedType>(Src)) |
| 132 | Src = ElTy->getNamedType(); |
| 133 | if (const auto *ElTy = dyn_cast<ElaboratedType>(Dst)) |
| 134 | Dst = ElTy->getNamedType(); |
| 135 | if (Src == Dst) { |
| 136 | diag(CastExpr->getBeginLoc(), "redundant cast to the same type") |
| 137 | << FixItHint::CreateRemoval(ReplaceRange); |
| 138 | return; |
| 139 | } |
| 140 | } |
| 141 | |
| 142 | // The rest of this check is only relevant to C++. |
| 143 | // We also disable it for Objective-C++. |
| 144 | if (!getLangOpts().CPlusPlus || getLangOpts().ObjC) |
| 145 | return; |
| 146 | // Ignore code inside extern "C" {} blocks. |
| 147 | if (!match(expr(hasAncestor(linkageSpecDecl())), *CastExpr, *Result.Context) |
| 148 | .empty()) |
| 149 | return; |
| 150 | // Ignore code in .c files and headers included from them, even if they are |
| 151 | // compiled as C++. |
| 152 | if (getCurrentMainFile().endswith(".c")) |
| 153 | return; |
| 154 | |
| 155 | SourceManager &SM = *Result.SourceManager; |
| 156 | |
| 157 | // Ignore code in .c files #included in other files (which shouldn't be done, |
| 158 | // but people still do this for test and other purposes). |
| 159 | if (SM.getFilename(SM.getSpellingLoc(CastExpr->getBeginLoc())).endswith(".c")) |
| 160 | return; |
| 161 | |
| 162 | // Leave type spelling exactly as it was (unlike |
| 163 | // getTypeAsWritten().getAsString() which would spell enum types 'enum X'). |
| 164 | StringRef DestTypeString = getDestTypeString(SM, getLangOpts(), CastExpr); |
| 165 | |
| 166 | auto Diag = |
| 167 | diag(CastExpr->getBeginLoc(), "C-style casts are discouraged; use %0"); |
| 168 | |
| 169 | auto ReplaceWithCast = [&](std::string CastText) { |
| 170 | const Expr *SubExpr = CastExpr->getSubExprAsWritten()->IgnoreImpCasts(); |
| 171 | if (!isa<ParenExpr>(SubExpr) && !isa<CXXFunctionalCastExpr>(CastExpr)) { |
| 172 | CastText.push_back('('); |
| 173 | Diag << FixItHint::CreateInsertion( |
| 174 | Lexer::getLocForEndOfToken(SubExpr->getEndLoc(), 0, SM, |
| 175 | getLangOpts()), |
| 176 | ")"); |
| 177 | } |
| 178 | Diag << FixItHint::CreateReplacement(ReplaceRange, CastText); |
| 179 | }; |
| 180 | auto ReplaceWithNamedCast = [&](StringRef CastType) { |
| 181 | Diag << CastType; |
| 182 | ReplaceWithCast((CastType + "<" + DestTypeString + ">").str()); |
| 183 | }; |
| 184 | auto ReplaceWithConstructorCall = [&]() { |
| 185 | Diag << "constructor call syntax"; |
| 186 | // FIXME: Validate DestTypeString, maybe. |
| 187 | ReplaceWithCast(DestTypeString.str()); |
| 188 | }; |
| 189 | // Suggest appropriate C++ cast. See [expr.cast] for cast notation semantics. |
| 190 | switch (CastExpr->getCastKind()) { |
| 191 | case CK_FunctionToPointerDecay: |
| 192 | ReplaceWithNamedCast("static_cast"); |
| 193 | return; |
| 194 | case CK_ConstructorConversion: |
| 195 | if (ConstructorCast) { |
| 196 | ReplaceWithConstructorCall(); |
| 197 | } else { |
| 198 | ReplaceWithNamedCast("static_cast"); |
| 199 | } |
| 200 | return; |
| 201 | case CK_NoOp: |
| 202 | if (FnToFnCast) { |
| 203 | ReplaceWithNamedCast("static_cast"); |
| 204 | return; |
| 205 | } |
| 206 | if (SourceType == DestType) { |
| 207 | Diag << "static_cast (if needed, the cast may be redundant)"; |
| 208 | ReplaceWithCast(("static_cast<" + DestTypeString + ">").str()); |
| 209 | return; |
| 210 | } |
| 211 | if (needsConstCast(SourceType, DestType) && |
| 212 | pointedUnqualifiedTypesAreEqual(SourceType, DestType)) { |
| 213 | ReplaceWithNamedCast("const_cast"); |
| 214 | return; |
| 215 | } |
| 216 | if (ConstructorCast) { |
| 217 | ReplaceWithConstructorCall(); |
| 218 | return; |
| 219 | } |
| 220 | if (DestType->isReferenceType()) { |
| 221 | QualType Dest = DestType.getNonReferenceType(); |
| 222 | QualType Source = SourceType.getNonReferenceType(); |
| 223 | if (Source == Dest.withConst() || |
| 224 | SourceType.getNonReferenceType() == DestType.getNonReferenceType()) { |
| 225 | ReplaceWithNamedCast("const_cast"); |
| 226 | return; |
| 227 | } |
| 228 | break; |
| 229 | } |
| 230 | [[fallthrough]]; |
| 231 | case clang::CK_IntegralCast: |
| 232 | // Convert integral and no-op casts between builtin types and enums to |
| 233 | // static_cast. A cast from enum to integer may be unnecessary, but it's |
| 234 | // still retained. |
| 235 | if ((SourceType->isBuiltinType() || SourceType->isEnumeralType()) && |
| 236 | (DestType->isBuiltinType() || DestType->isEnumeralType())) { |
| 237 | ReplaceWithNamedCast("static_cast"); |
| 238 | return; |
| 239 | } |
| 240 | break; |
| 241 | case CK_BitCast: |
| 242 | // FIXME: Suggest const_cast<...>(reinterpret_cast<...>(...)) replacement. |
| 243 | if (!needsConstCast(SourceType, DestType)) { |
| 244 | if (SourceType->isVoidPointerType()) |
| 245 | ReplaceWithNamedCast("static_cast"); |
| 246 | else |
| 247 | ReplaceWithNamedCast("reinterpret_cast"); |
| 248 | return; |
| 249 | } |
| 250 | break; |
| 251 | default: |
| 252 | break; |
| 253 | } |
| 254 | |
| 255 | Diag << "static_cast/const_cast/reinterpret_cast"; |
| 256 | } |
| 257 | |
| 258 | } // namespace clang::tidy::google::readability |