clang-tools  16.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 
13 using namespace clang::ast_matchers;
14 
15 namespace clang {
16 namespace tidy {
17 namespace cppcoreguidelines {
18 
19 void ProTypeStaticCastDowncastCheck::registerMatchers(MatchFinder *Finder) {
20  Finder->addMatcher(
21  cxxStaticCastExpr(unless(isInTemplateInstantiation())).bind("cast"),
22  this);
23 }
24 
26  const MatchFinder::MatchResult &Result) {
27  const auto *MatchedCast = Result.Nodes.getNodeAs<CXXStaticCastExpr>("cast");
28  if (MatchedCast->getCastKind() != CK_BaseToDerived)
29  return;
30 
31  QualType SourceType = MatchedCast->getSubExpr()->getType();
32  const auto *SourceDecl = SourceType->getPointeeCXXRecordDecl();
33  if (!SourceDecl) // The cast is from object to reference
34  SourceDecl = SourceType->getAsCXXRecordDecl();
35  if (!SourceDecl)
36  return;
37 
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(),
43  "dynamic_cast");
44  else
45  diag(MatchedCast->getOperatorLoc(),
46  "do not use static_cast to downcast from a base to a derived class");
47 }
48 
49 } // namespace cppcoreguidelines
50 } // namespace tidy
51 } // namespace clang
clang::ast_matchers
Definition: AbseilMatcher.h:14
ProTypeStaticCastDowncastCheck.h
clang
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
Definition: ApplyReplacements.h:27
clang::clangd::check
bool check(llvm::StringRef File, const ThreadsafeFS &TFS, const ClangdLSPServer::Options &Opts)
Definition: Check.cpp:415