clang-tools 6.0.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
10 #include "ProTypeStaticCastDowncastCheck.h"
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(
30 const MatchFinder::MatchResult &Result) {
31 const auto *MatchedCast = Result.Nodes.getNodeAs<CXXStaticCastExpr>("cast");
32 if (MatchedCast->getCastKind() != CK_BaseToDerived)
33 return;
34
35 QualType SourceType = MatchedCast->getSubExpr()->getType();
36 const auto *SourceDecl = SourceType->getPointeeCXXRecordDecl();
37 if (!SourceDecl) // The cast is from object to reference
38 SourceDecl = SourceType->getAsCXXRecordDecl();
39 if (!SourceDecl)
40 return;
41
42 if (SourceDecl->isPolymorphic())
43 diag(MatchedCast->getOperatorLoc(),
44 "do not use static_cast to downcast from a base to a derived class; "
45 "use dynamic_cast instead")
46 << FixItHint::CreateReplacement(MatchedCast->getOperatorLoc(),
47 "dynamic_cast");
48 else
49 diag(MatchedCast->getOperatorLoc(),
50 "do not use static_cast to downcast from a base to a derived class");
51 }
52
53 } // namespace cppcoreguidelines
54 } // namespace tidy
55 } // namespace clang
clang::ast_matchers
Definition: ClangTidyDiagnosticConsumer.h:27
ProTypeStaticCastDowncastCheck.h
clang
Definition: AndroidTidyModule.cpp:28