10 #include "clang/AST/ASTContext.h"
11 #include "clang/ASTMatchers/ASTMatchFinder.h"
17 namespace cppcoreguidelines {
19 void ProTypeStaticCastDowncastCheck::registerMatchers(MatchFinder *Finder) {
21 cxxStaticCastExpr(unless(isInTemplateInstantiation())).bind(
"cast"),
25 void ProTypeStaticCastDowncastCheck::check(
26 const MatchFinder::MatchResult &Result) {
27 const auto *MatchedCast = Result.Nodes.getNodeAs<CXXStaticCastExpr>(
"cast");
28 if (MatchedCast->getCastKind() != CK_BaseToDerived)
31 QualType SourceType = MatchedCast->getSubExpr()->getType();
32 const auto *SourceDecl = SourceType->getPointeeCXXRecordDecl();
34 SourceDecl = SourceType->getAsCXXRecordDecl();
38 if (SourceDecl->isPolymorphic())
39 diag(MatchedCast->getOperatorLoc(),
40 "do not use static_cast to downcast from a base to a derived class; "
41 "use dynamic_cast instead")
42 << FixItHint::CreateReplacement(MatchedCast->getOperatorLoc(),
45 diag(MatchedCast->getOperatorLoc(),
46 "do not use static_cast to downcast from a base to a derived class");