llvm-project
74 строки · 2.8 Кб
1//===--- UnhandledExceptionAtNewCheck.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 "UnhandledExceptionAtNewCheck.h"
10#include "clang/AST/ASTContext.h"
11#include "clang/ASTMatchers/ASTMatchFinder.h"
12
13using namespace clang::ast_matchers;
14
15namespace clang::tidy::bugprone {
16
17AST_MATCHER_P(CXXTryStmt, hasHandlerFor,
18ast_matchers::internal::Matcher<QualType>, InnerMatcher) {
19for (unsigned NH = Node.getNumHandlers(), I = 0; I < NH; ++I) {
20const CXXCatchStmt *CatchS = Node.getHandler(I);
21// Check for generic catch handler (match anything).
22if (CatchS->getCaughtType().isNull())
23return true;
24ast_matchers::internal::BoundNodesTreeBuilder Result(*Builder);
25if (InnerMatcher.matches(CatchS->getCaughtType(), Finder, &Result)) {
26*Builder = std::move(Result);
27return true;
28}
29}
30return false;
31}
32
33AST_MATCHER(CXXNewExpr, mayThrow) {
34FunctionDecl *OperatorNew = Node.getOperatorNew();
35if (!OperatorNew)
36return false;
37return !OperatorNew->getType()->castAs<FunctionProtoType>()->isNothrow();
38}
39
40UnhandledExceptionAtNewCheck::UnhandledExceptionAtNewCheck(
41StringRef Name, ClangTidyContext *Context)
42: ClangTidyCheck(Name, Context) {}
43
44void UnhandledExceptionAtNewCheck::registerMatchers(MatchFinder *Finder) {
45auto BadAllocType =
46recordType(hasDeclaration(cxxRecordDecl(hasName("::std::bad_alloc"))));
47auto ExceptionType =
48recordType(hasDeclaration(cxxRecordDecl(hasName("::std::exception"))));
49auto BadAllocReferenceType = referenceType(pointee(BadAllocType));
50auto ExceptionReferenceType = referenceType(pointee(ExceptionType));
51
52auto CatchBadAllocType =
53qualType(hasCanonicalType(anyOf(BadAllocType, BadAllocReferenceType,
54ExceptionType, ExceptionReferenceType)));
55auto BadAllocCatchingTryBlock = cxxTryStmt(hasHandlerFor(CatchBadAllocType));
56
57auto FunctionMayNotThrow = functionDecl(isNoThrow());
58
59Finder->addMatcher(cxxNewExpr(mayThrow(),
60unless(hasAncestor(BadAllocCatchingTryBlock)),
61hasAncestor(FunctionMayNotThrow))
62.bind("new-expr"),
63this);
64}
65
66void UnhandledExceptionAtNewCheck::check(
67const MatchFinder::MatchResult &Result) {
68const auto *MatchedExpr = Result.Nodes.getNodeAs<CXXNewExpr>("new-expr");
69if (MatchedExpr)
70diag(MatchedExpr->getBeginLoc(),
71"missing exception handler for allocation failure at 'new'");
72}
73
74} // namespace clang::tidy::bugprone
75