blob: 3ea56d2f734383ae5cc833e371cd03bb9033af1d [file] [log] [blame]
Aaron Ballmana3274e52017-08-11 16:31:51 +00001//===--- ExceptionBaseclassCheck.cpp - clang-tidy--------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "ExceptionBaseclassCheck.h"
11#include "clang/AST/ASTContext.h"
12#include "clang/ASTMatchers/ASTMatchFinder.h"
13
Aaron Ballmana3274e52017-08-11 16:31:51 +000014using namespace clang::ast_matchers;
15
16namespace clang {
17namespace tidy {
18namespace hicpp {
19
20void ExceptionBaseclassCheck::registerMatchers(MatchFinder *Finder) {
21 if (!getLangOpts().CPlusPlus)
22 return;
23
24 Finder->addMatcher(
Jonas Toth673dbd12017-08-30 15:59:01 +000025 cxxThrowExpr(allOf(has(expr(unless(hasType(qualType(hasCanonicalType(
26 hasDeclaration(cxxRecordDecl(isSameOrDerivedFrom(
27 hasName("std::exception")))))))))),
28 has(expr(unless(cxxUnresolvedConstructExpr()))),
29 eachOf(has(expr(hasType(namedDecl().bind("decl")))),
30 anything())))
Aaron Ballmana3274e52017-08-11 16:31:51 +000031 .bind("bad_throw"),
32 this);
33}
34
35void ExceptionBaseclassCheck::check(const MatchFinder::MatchResult &Result) {
36 const auto *BadThrow = Result.Nodes.getNodeAs<CXXThrowExpr>("bad_throw");
Jonas Toth673dbd12017-08-30 15:59:01 +000037
Stephen Kelly43465bf2018-08-09 22:42:26 +000038 diag(BadThrow->getSubExpr()->getBeginLoc(), "throwing an exception whose "
Jonas Toth673dbd12017-08-30 15:59:01 +000039 "type %0 is not derived from "
40 "'std::exception'")
41 << BadThrow->getSubExpr()->getType() << BadThrow->getSourceRange();
Aaron Ballmana3274e52017-08-11 16:31:51 +000042
43 const auto *TypeDecl = Result.Nodes.getNodeAs<NamedDecl>("decl");
44 if (TypeDecl != nullptr)
Stephen Kelly43465bf2018-08-09 22:42:26 +000045 diag(TypeDecl->getBeginLoc(), "type defined here", DiagnosticIDs::Note);
Aaron Ballmana3274e52017-08-11 16:31:51 +000046}
47
48} // namespace hicpp
49} // namespace tidy
50} // namespace clang