clang-tools 20.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 StringRef Name, ClangTidyContext *Context)
19 : ClangTidyCheck(Name, Context),
20 StrictMode(Options.getLocalOrGlobal("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
llvm::SmallString< 256U > Name
void store(ClangTidyOptions::OptionMap &Options, StringRef LocalName, StringRef Value) const
Stores an option with the check-local name LocalName with string value Value to Options.
Base class for all clang-tidy checks.
DiagnosticBuilder diag(SourceLocation Loc, StringRef Description, DiagnosticIDs::Level Level=DiagnosticIDs::Warning)
Add a diagnostic with the check's name.
Every ClangTidyCheck reports errors through a DiagnosticsEngine provided by this context.
void registerMatchers(ast_matchers::MatchFinder *Finder) override
Override this to register AST matchers with Finder.
void storeOptions(ClangTidyOptions::OptionMap &Opts) override
Should store all options supported by this check with their current values or default values for opti...
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
ClangTidyChecks that register ASTMatchers should do the actual work in here.
llvm::StringMap< ClangTidyValue > OptionMap