reference, declarationdefinition
definition → references, declarations, derived classes, virtual overrides
reference to multiple definitions → definitions
unreferenced
    1
    2
    3
    4
    5
    6
    7
    8
    9
   10
   11
   12
   13
   14
   15
   16
   17
   18
   19
   20
   21
   22
   23
   24
   25
   26
   27
   28
   29
   30
   31
   32
   33
   34
   35
   36
   37
   38
   39
   40
   41
   42
   43
   44
   45
   46
   47
   48
   49
   50
   51
   52
   53
   54
   55
   56
   57
   58
   59
   60
   61
   62
   63
   64
   65
   66
   67
   68
   69
   70
   71
   72
   73
   74
   75
   76
   77
   78
   79
   80
   81
   82
   83
   84
   85
   86
   87
   88
   89
   90
   91
   92
   93
   94
   95
   96
   97
   98
   99
  100
  101
  102
  103
  104
  105
  106
  107
//===--- ProTypeCstyleCastCheck.cpp - clang-tidy---------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//

#include "ProTypeCstyleCastCheck.h"
#include "clang/AST/ASTContext.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"
#include "clang/Lex/Lexer.h"

using namespace clang::ast_matchers;

namespace clang {
namespace tidy {
namespace cppcoreguidelines {

static bool needsConstCast(QualType SourceType, QualType DestType) {
  SourceType = SourceType.getNonReferenceType();
  DestType = DestType.getNonReferenceType();
  while (SourceType->isPointerType() && DestType->isPointerType()) {
    SourceType = SourceType->getPointeeType();
    DestType = DestType->getPointeeType();
    if (SourceType.isConstQualified() && !DestType.isConstQualified())
      return true;
  }
  return false;
}

void ProTypeCstyleCastCheck::registerMatchers(MatchFinder *Finder) {
  if (!getLangOpts().CPlusPlus)
    return;

  Finder->addMatcher(
      cStyleCastExpr(unless(isInTemplateInstantiation())).bind("cast"), this);
}

void ProTypeCstyleCastCheck::check(const MatchFinder::MatchResult &Result) {
  const auto *MatchedCast = Result.Nodes.getNodeAs<CStyleCastExpr>("cast");

  if (MatchedCast->getCastKind() == CK_BitCast ||
      MatchedCast->getCastKind() == CK_LValueBitCast ||
      MatchedCast->getCastKind() == CK_IntegralToPointer ||
      MatchedCast->getCastKind() == CK_PointerToIntegral ||
      MatchedCast->getCastKind() == CK_ReinterpretMemberPointer) {
    diag(MatchedCast->getBeginLoc(),
         "do not use C-style cast to convert between unrelated types");
    return;
  }

  QualType SourceType = MatchedCast->getSubExpr()->getType();

  if (MatchedCast->getCastKind() == CK_BaseToDerived) {
    const auto *SourceDecl = SourceType->getPointeeCXXRecordDecl();
    if (!SourceDecl) // The cast is from object to reference.
      SourceDecl = SourceType->getAsCXXRecordDecl();
    if (!SourceDecl)
      return;

    if (SourceDecl->isPolymorphic()) {
      // Leave type spelling exactly as it was (unlike
      // getTypeAsWritten().getAsString() which would spell enum types 'enum
      // X').
      StringRef DestTypeString = Lexer::getSourceText(
          CharSourceRange::getTokenRange(
              MatchedCast->getLParenLoc().getLocWithOffset(1),
              MatchedCast->getRParenLoc().getLocWithOffset(-1)),
          *Result.SourceManager, getLangOpts());

      auto diag_builder = diag(
          MatchedCast->getBeginLoc(),
          "do not use C-style cast to downcast from a base to a derived class; "
          "use dynamic_cast instead");

      const Expr *SubExpr =
          MatchedCast->getSubExprAsWritten()->IgnoreImpCasts();
      std::string CastText = ("dynamic_cast<" + DestTypeString + ">").str();
      if (!isa<ParenExpr>(SubExpr)) {
        CastText.push_back('(');
        diag_builder << FixItHint::CreateInsertion(
            Lexer::getLocForEndOfToken(SubExpr->getEndLoc(), 0,
                                       *Result.SourceManager, getLangOpts()),
            ")");
      }
      auto ParenRange = CharSourceRange::getTokenRange(
          MatchedCast->getLParenLoc(), MatchedCast->getRParenLoc());
      diag_builder << FixItHint::CreateReplacement(ParenRange, CastText);
    } else {
      diag(
          MatchedCast->getBeginLoc(),
          "do not use C-style cast to downcast from a base to a derived class");
    }
    return;
  }

  if (MatchedCast->getCastKind() == CK_NoOp &&
      needsConstCast(SourceType, MatchedCast->getType())) {
    diag(MatchedCast->getBeginLoc(),
         "do not use C-style cast to cast away constness");
  }
}

} // namespace cppcoreguidelines
} // namespace tidy
} // namespace clang