summaryrefslogtreecommitdiffstats
path: root/clang-tidy/cppcoreguidelines/ProTypeStaticCastDowncastCheck.cpp
blob: f43e4fa1ad1fd27798261e9f4711ebf420386fb1 (plain)
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
//===--- ProTypeStaticCastDowncastCheck.cpp - clang-tidy-------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "ProTypeStaticCastDowncastCheck.h"
#include "clang/AST/ASTContext.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"

using namespace clang::ast_matchers;

namespace clang {
namespace tidy {
namespace cppcoreguidelines {

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

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

void ProTypeStaticCastDowncastCheck::check(
    const MatchFinder::MatchResult &Result) {
  const auto *MatchedCast = Result.Nodes.getNodeAs<CXXStaticCastExpr>("cast");
  if (MatchedCast->getCastKind() != CK_BaseToDerived)
    return;

  QualType SourceType = MatchedCast->getSubExpr()->getType();
  const auto *SourceDecl = SourceType->getPointeeCXXRecordDecl();
  if (!SourceDecl) // The cast is from object to reference
    SourceDecl = SourceType->getAsCXXRecordDecl();
  if (!SourceDecl)
    return;

  if (SourceDecl->isPolymorphic())
    diag(MatchedCast->getOperatorLoc(),
         "do not use static_cast to downcast from a base to a derived class; "
         "use dynamic_cast instead")
        << FixItHint::CreateReplacement(MatchedCast->getOperatorLoc(),
                                        "dynamic_cast");
  else
    diag(MatchedCast->getOperatorLoc(),
         "do not use static_cast to downcast from a base to a derived class");
}

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