| 1 | //===--- ExceptionBaseclassCheck.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 | |
| 9 | #include "ExceptionBaseclassCheck.h" |
| 10 | #include "clang/AST/ASTContext.h" |
| 11 | #include "clang/ASTMatchers/ASTMatchFinder.h" |
| 12 | |
| 13 | using namespace clang::ast_matchers; |
| 14 | |
| 15 | namespace clang::tidy::hicpp { |
| 16 | |
| 17 | void ExceptionBaseclassCheck::registerMatchers(MatchFinder *Finder) { |
| 18 | Finder->addMatcher( |
| 19 | NodeMatch: cxxThrowExpr( |
| 20 | unless(has(expr(anyOf(isTypeDependent(), isValueDependent())))), |
| 21 | // The thrown value is not derived from 'std::exception'. |
| 22 | has(expr(unless( |
| 23 | hasType(InnerMatcher: qualType(hasCanonicalType(InnerMatcher: hasDeclaration(InnerMatcher: cxxRecordDecl( |
| 24 | isSameOrDerivedFrom(Base: hasName(Name: "::std::exception" )))))))))), |
| 25 | // This condition is always true, but will bind to the |
| 26 | // template value if the thrown type is templated. |
| 27 | optionally(has( |
| 28 | expr(hasType(InnerMatcher: substTemplateTypeParmType().bind(ID: "templ_type" ))))), |
| 29 | // Bind to the declaration of the type of the value that |
| 30 | // is thrown. 'optionally' is necessary because builtin types |
| 31 | // are not 'namedDecl'. |
| 32 | optionally(has(expr(hasType(InnerMatcher: namedDecl().bind(ID: "decl" )))))) |
| 33 | .bind(ID: "bad_throw" ), |
| 34 | Action: this); |
| 35 | } |
| 36 | |
| 37 | void ExceptionBaseclassCheck::check(const MatchFinder::MatchResult &Result) { |
| 38 | const auto *BadThrow = Result.Nodes.getNodeAs<CXXThrowExpr>(ID: "bad_throw" ); |
| 39 | assert(BadThrow && "Did not match the throw expression" ); |
| 40 | |
| 41 | diag(Loc: BadThrow->getSubExpr()->getBeginLoc(), Description: "throwing an exception whose " |
| 42 | "type %0 is not derived from " |
| 43 | "'std::exception'" ) |
| 44 | << BadThrow->getSubExpr()->getType() << BadThrow->getSourceRange(); |
| 45 | |
| 46 | if (const auto *Template = |
| 47 | Result.Nodes.getNodeAs<SubstTemplateTypeParmType>(ID: "templ_type" )) |
| 48 | diag(Loc: BadThrow->getSubExpr()->getBeginLoc(), |
| 49 | Description: "type %0 is a template instantiation of %1" , Level: DiagnosticIDs::Note) |
| 50 | << BadThrow->getSubExpr()->getType() |
| 51 | << Template->getReplacedParameter(); |
| 52 | |
| 53 | if (const auto *TypeDecl = Result.Nodes.getNodeAs<NamedDecl>(ID: "decl" )) |
| 54 | diag(Loc: TypeDecl->getBeginLoc(), Description: "type defined here" , Level: DiagnosticIDs::Note); |
| 55 | } |
| 56 | |
| 57 | } // namespace clang::tidy::hicpp |
| 58 | |