clang-tools  3.9.0
ProTypeStaticCastDowncastCheck.cpp
Go to the documentation of this file.
1 //===--- ProTypeStaticCastDowncastCheck.cpp - clang-tidy-------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
11 #include "clang/AST/ASTContext.h"
12 #include "clang/ASTMatchers/ASTMatchFinder.h"
13 
14 using namespace clang::ast_matchers;
15 
16 namespace clang {
17 namespace tidy {
18 namespace cppcoreguidelines {
19 
20 void ProTypeStaticCastDowncastCheck::registerMatchers(MatchFinder *Finder) {
21  if (!getLangOpts().CPlusPlus)
22  return;
23 
24  Finder->addMatcher(
25  cxxStaticCastExpr(unless(isInTemplateInstantiation())).bind("cast"),
26  this);
27 }
28 
29 void ProTypeStaticCastDowncastCheck::check(const MatchFinder::MatchResult &Result) {
30  const auto *MatchedCast = Result.Nodes.getNodeAs<CXXStaticCastExpr>("cast");
31  if (MatchedCast->getCastKind() != CK_BaseToDerived)
32  return;
33 
34  QualType SourceType = MatchedCast->getSubExpr()->getType();
35  const auto *SourceDecl = SourceType->getPointeeCXXRecordDecl();
36  if (!SourceDecl) // The cast is from object to reference
37  SourceDecl = SourceType->getAsCXXRecordDecl();
38  if (!SourceDecl)
39  return;
40 
41  if (SourceDecl->isPolymorphic())
42  diag(MatchedCast->getOperatorLoc(),
43  "do not use static_cast to downcast from a base to a derived class; "
44  "use dynamic_cast instead")
45  << FixItHint::CreateReplacement(MatchedCast->getOperatorLoc(),
46  "dynamic_cast");
47  else
48  diag(MatchedCast->getOperatorLoc(),
49  "do not use static_cast to downcast from a base to a derived class");
50 }
51 
52 } // namespace cppcoreguidelines
53 } // namespace tidy
54 } // namespace clang
std::unique_ptr< ast_matchers::MatchFinder > Finder
Definition: ClangTidy.cpp:210
const NamedDecl * Result
Definition: USRFinder.cpp:137