clang-tools  9.0.0
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  if (!getLangOpts().CPlusPlus)
21  return;
22 
23  Finder->addMatcher(
24  cxxStaticCastExpr(unless(isInTemplateInstantiation())).bind("cast"),
25  this);
26 }
27 
28 void ProTypeStaticCastDowncastCheck::check(
29  const MatchFinder::MatchResult &Result) {
30  const auto *MatchedCast = Result.Nodes.getNodeAs<CXXStaticCastExpr>("cast");
31  if (MatchedCast->getCastKind() != CK_BaseToDerived)
32  return;
33 
34  QualType SourceType = MatchedCast->getSubExpr()->getType();
35  const auto *SourceDecl = SourceType->getPointeeCXXRecordDecl();
36  if (!SourceDecl) // The cast is from object to reference
37  SourceDecl = SourceType->getAsCXXRecordDecl();
38  if (!SourceDecl)
39  return;
40 
41  if (SourceDecl->isPolymorphic())
42  diag(MatchedCast->getOperatorLoc(),
43  "do not use static_cast to downcast from a base to a derived class; "
44  "use dynamic_cast instead")
45  << FixItHint::CreateReplacement(MatchedCast->getOperatorLoc(),
46  "dynamic_cast");
47  else
48  diag(MatchedCast->getOperatorLoc(),
49  "do not use static_cast to downcast from a base to a derived class");
50 }
51 
52 } // namespace cppcoreguidelines
53 } // namespace tidy
54 } // namespace clang
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
llvm::Optional< llvm::Expected< tooling::AtomicChanges > > Result
Definition: Rename.cpp:36