clang-tools 22.0.0git
ProTypeStaticCastDowncastCheck.cpp
Go to the documentation of this file.
1//===----------------------------------------------------------------------===//
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 StringRef Name, ClangTidyContext *Context)
19 : ClangTidyCheck(Name, Context),
20 StrictMode(Options.get("StrictMode", true)) {}
21
24 Options.store(Opts, "StrictMode", StrictMode);
25}
26
28 Finder->addMatcher(
29 cxxStaticCastExpr(hasCastKind(CK_BaseToDerived)).bind("cast"), this);
30}
31
33 const MatchFinder::MatchResult &Result) {
34 const auto *MatchedCast = Result.Nodes.getNodeAs<CXXStaticCastExpr>("cast");
35
36 QualType SourceType = MatchedCast->getSubExpr()->getType();
37 const auto *SourceDecl = SourceType->getPointeeCXXRecordDecl();
38 if (!SourceDecl) // The cast is from object to reference
39 SourceDecl = SourceType->getAsCXXRecordDecl();
40 if (!SourceDecl)
41 return;
42
43 if (SourceDecl->isPolymorphic()) {
44 diag(MatchedCast->getOperatorLoc(),
45 "do not use static_cast to downcast from a base to a derived class; "
46 "use dynamic_cast instead")
47 << FixItHint::CreateReplacement(MatchedCast->getOperatorLoc(),
48 "dynamic_cast");
49 return;
50 }
51
52 if (!StrictMode)
53 return;
54
55 diag(MatchedCast->getOperatorLoc(),
56 "do not use static_cast to downcast from a base to a derived class");
57}
58
59} // namespace clang::tidy::cppcoreguidelines
Every ClangTidyCheck reports errors through a DiagnosticsEngine provided by this context.
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
llvm::StringMap< ClangTidyValue > OptionMap