clang-tools 18.0.0git
ProTypeStaticCastDowncastCheck.cpp
Go to the documentation of this file.
1//===--- ProTypeStaticCastDowncastCheck.cpp - clang-tidy-------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
10#include "clang/AST/ASTContext.h"
11#include "clang/ASTMatchers/ASTMatchFinder.h"
12
13using namespace clang::ast_matchers;
14
16
18 Finder->addMatcher(
19 cxxStaticCastExpr(unless(isInTemplateInstantiation())).bind("cast"),
20 this);
21}
22
24 const MatchFinder::MatchResult &Result) {
25 const auto *MatchedCast = Result.Nodes.getNodeAs<CXXStaticCastExpr>("cast");
26 if (MatchedCast->getCastKind() != CK_BaseToDerived)
27 return;
28
29 QualType SourceType = MatchedCast->getSubExpr()->getType();
30 const auto *SourceDecl = SourceType->getPointeeCXXRecordDecl();
31 if (!SourceDecl) // The cast is from object to reference
32 SourceDecl = SourceType->getAsCXXRecordDecl();
33 if (!SourceDecl)
34 return;
35
36 if (SourceDecl->isPolymorphic())
37 diag(MatchedCast->getOperatorLoc(),
38 "do not use static_cast to downcast from a base to a derived class; "
39 "use dynamic_cast instead")
40 << FixItHint::CreateReplacement(MatchedCast->getOperatorLoc(),
41 "dynamic_cast");
42 else
43 diag(MatchedCast->getOperatorLoc(),
44 "do not use static_cast to downcast from a base to a derived class");
45}
46
47} // namespace clang::tidy::cppcoreguidelines
DiagnosticBuilder diag(SourceLocation Loc, StringRef Description, DiagnosticIDs::Level Level=DiagnosticIDs::Warning)
Add a diagnostic with the check's name.
void registerMatchers(ast_matchers::MatchFinder *Finder) override
Override this to register AST matchers with Finder.
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
ClangTidyChecks that register ASTMatchers should do the actual work in here.