150
|
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 {
|
|
16 namespace tidy {
|
|
17 namespace hicpp {
|
|
18
|
|
19 void ExceptionBaseclassCheck::registerMatchers(MatchFinder *Finder) {
|
|
20 if (!getLangOpts().CPlusPlus)
|
|
21 return;
|
|
22
|
|
23 Finder->addMatcher(
|
|
24 cxxThrowExpr(
|
|
25 unless(has(expr(anyOf(isTypeDependent(), isValueDependent())))),
|
|
26 // The thrown value is not derived from 'std::exception'.
|
|
27 has(expr(unless(
|
|
28 hasType(qualType(hasCanonicalType(hasDeclaration(cxxRecordDecl(
|
|
29 isSameOrDerivedFrom(hasName("::std::exception")))))))))),
|
|
30 // This condition is always true, but will bind to the
|
|
31 // template value if the thrown type is templated.
|
|
32 anyOf(has(expr(
|
|
33 hasType(substTemplateTypeParmType().bind("templ_type")))),
|
|
34 anything()),
|
|
35 // Bind to the declaration of the type of the value that
|
|
36 // is thrown. 'anything()' is necessary to always suceed
|
|
37 // in the 'eachOf' because builtin types are not
|
|
38 // 'namedDecl'.
|
|
39 eachOf(has(expr(hasType(namedDecl().bind("decl")))), anything()))
|
|
40 .bind("bad_throw"),
|
|
41 this);
|
|
42 }
|
|
43
|
|
44 void ExceptionBaseclassCheck::check(const MatchFinder::MatchResult &Result) {
|
|
45 const auto *BadThrow = Result.Nodes.getNodeAs<CXXThrowExpr>("bad_throw");
|
|
46 assert(BadThrow && "Did not match the throw expression");
|
|
47
|
|
48 diag(BadThrow->getSubExpr()->getBeginLoc(), "throwing an exception whose "
|
|
49 "type %0 is not derived from "
|
|
50 "'std::exception'")
|
|
51 << BadThrow->getSubExpr()->getType() << BadThrow->getSourceRange();
|
|
52
|
|
53 if (const auto *Template =
|
|
54 Result.Nodes.getNodeAs<SubstTemplateTypeParmType>("templ_type"))
|
|
55 diag(BadThrow->getSubExpr()->getBeginLoc(),
|
|
56 "type %0 is a template instantiation of %1", DiagnosticIDs::Note)
|
|
57 << BadThrow->getSubExpr()->getType()
|
|
58 << Template->getReplacedParameter()->getDecl();
|
|
59
|
|
60 if (const auto *TypeDecl = Result.Nodes.getNodeAs<NamedDecl>("decl"))
|
|
61 diag(TypeDecl->getBeginLoc(), "type defined here", DiagnosticIDs::Note);
|
|
62 }
|
|
63
|
|
64 } // namespace hicpp
|
|
65 } // namespace tidy
|
|
66 } // namespace clang
|