11 #include "clang/AST/ASTContext.h"
12 #include "clang/ASTMatchers/ASTMatchFinder.h"
14 using namespace clang::ast_matchers;
18 namespace cppcoreguidelines {
20 void ProTypeStaticCastDowncastCheck::registerMatchers(MatchFinder *
Finder) {
21 if (!getLangOpts().CPlusPlus)
25 cxxStaticCastExpr(unless(isInTemplateInstantiation())).bind(
"cast"),
29 void ProTypeStaticCastDowncastCheck::check(
const MatchFinder::MatchResult &
Result) {
30 const auto *MatchedCast = Result.Nodes.getNodeAs<CXXStaticCastExpr>(
"cast");
31 if (MatchedCast->getCastKind() != CK_BaseToDerived)
34 QualType SourceType = MatchedCast->getSubExpr()->getType();
35 const auto *SourceDecl = SourceType->getPointeeCXXRecordDecl();
37 SourceDecl = SourceType->getAsCXXRecordDecl();
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(),
48 diag(MatchedCast->getOperatorLoc(),
49 "do not use static_cast to downcast from a base to a derived class");
std::unique_ptr< ast_matchers::MatchFinder > Finder