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