clang-tools  3.8.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 
19 void ProTypeStaticCastDowncastCheck::registerMatchers(MatchFinder *Finder) {
20  if (!getLangOpts().CPlusPlus)
21  return;
22 
23  Finder->addMatcher(
24  cxxStaticCastExpr(unless(isInTemplateInstantiation())).bind("cast"),
25  this);
26 }
27 
28 void ProTypeStaticCastDowncastCheck::check(const MatchFinder::MatchResult &Result) {
29  const auto *MatchedCast = Result.Nodes.getNodeAs<CXXStaticCastExpr>("cast");
30  if (MatchedCast->getCastKind() != CK_BaseToDerived)
31  return;
32 
33  QualType SourceType = MatchedCast->getSubExpr()->getType();
34  const auto *SourceDecl = SourceType->getPointeeCXXRecordDecl();
35  if (!SourceDecl) // The cast is from object to reference
36  SourceDecl = SourceType->getAsCXXRecordDecl();
37  if (!SourceDecl)
38  return;
39 
40  if (SourceDecl->isPolymorphic())
41  diag(MatchedCast->getOperatorLoc(),
42  "do not use static_cast to downcast from a base to a derived class; "
43  "use dynamic_cast instead")
44  << FixItHint::CreateReplacement(MatchedCast->getOperatorLoc(),
45  "dynamic_cast");
46  else
47  diag(MatchedCast->getOperatorLoc(),
48  "do not use static_cast to downcast from a base to a derived class");
49 }
50 
51 } // namespace tidy
52 } // namespace clang
std::unique_ptr< ast_matchers::MatchFinder > Finder
Definition: ClangTidy.cpp:188
const NamedDecl * Result
Definition: USRFinder.cpp:121