clang-tools 22.0.0git
UnhandledExceptionAtNewCheck.cpp
Go to the documentation of this file.
1//===----------------------------------------------------------------------===//
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/ASTMatchers/ASTMatchFinder.h"
11
12using namespace clang::ast_matchers;
13
14namespace clang::tidy::bugprone {
15namespace {
16
17AST_MATCHER_P(CXXTryStmt, hasHandlerFor,
18 ast_matchers::internal::Matcher<QualType>, InnerMatcher) {
19 for (unsigned NH = Node.getNumHandlers(), I = 0; I < NH; ++I) {
20 const CXXCatchStmt *CatchS = Node.getHandler(I);
21 // Check for generic catch handler (match anything).
22 if (CatchS->getCaughtType().isNull())
23 return true;
24 ast_matchers::internal::BoundNodesTreeBuilder Result(*Builder);
25 if (InnerMatcher.matches(CatchS->getCaughtType(), Finder, &Result)) {
26 *Builder = std::move(Result);
27 return true;
28 }
29 }
30 return false;
31}
32
33AST_MATCHER(CXXNewExpr, mayThrow) {
34 FunctionDecl *OperatorNew = Node.getOperatorNew();
35 if (!OperatorNew)
36 return false;
37 return !OperatorNew->getType()->castAs<FunctionProtoType>()->isNothrow();
38}
39
40} // namespace
41
45
47 auto BadAllocType =
48 recordType(hasDeclaration(cxxRecordDecl(hasName("::std::bad_alloc"))));
49 auto ExceptionType =
50 recordType(hasDeclaration(cxxRecordDecl(hasName("::std::exception"))));
51 auto BadAllocReferenceType = referenceType(pointee(BadAllocType));
52 auto ExceptionReferenceType = referenceType(pointee(ExceptionType));
53
54 auto CatchBadAllocType =
55 qualType(hasCanonicalType(anyOf(BadAllocType, BadAllocReferenceType,
56 ExceptionType, ExceptionReferenceType)));
57 auto BadAllocCatchingTryBlock = cxxTryStmt(hasHandlerFor(CatchBadAllocType));
58
59 auto FunctionMayNotThrow = functionDecl(isNoThrow());
60
61 Finder->addMatcher(cxxNewExpr(mayThrow(),
62 unless(hasAncestor(BadAllocCatchingTryBlock)),
63 hasAncestor(FunctionMayNotThrow))
64 .bind("new-expr"),
65 this);
66}
67
69 const MatchFinder::MatchResult &Result) {
70 const auto *MatchedExpr = Result.Nodes.getNodeAs<CXXNewExpr>("new-expr");
71 if (MatchedExpr)
72 diag(MatchedExpr->getBeginLoc(),
73 "missing exception handler for allocation failure at 'new'");
74}
75
76} // namespace clang::tidy::bugprone
Every ClangTidyCheck reports errors through a DiagnosticsEngine provided by this context.
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
UnhandledExceptionAtNewCheck(StringRef Name, ClangTidyContext *Context)
void registerMatchers(ast_matchers::MatchFinder *Finder) override
AST_MATCHER_P(Stmt, isStatementIdenticalToBoundNode, std::string, ID)
AST_MATCHER(BinaryOperator, isRelationalOperator)