clang-tools 22.0.0git
AvoidThrowingObjCExceptionCheck.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
15
17
18 Finder->addMatcher(objcThrowStmt().bind("throwStmt"), this);
19 Finder->addMatcher(
20 objcMessageExpr(anyOf(hasSelector("raise:format:"),
21 hasSelector("raise:format:arguments:")),
22 hasReceiverType(asString("NSException")))
23 .bind("raiseException"),
24 this);
25}
26
28 const MatchFinder::MatchResult &Result) {
29 const auto *MatchedStmt =
30 Result.Nodes.getNodeAs<ObjCAtThrowStmt>("throwStmt");
31 const auto *MatchedExpr =
32 Result.Nodes.getNodeAs<ObjCMessageExpr>("raiseException");
33 auto SourceLoc = MatchedStmt == nullptr ? MatchedExpr->getSelectorStartLoc()
34 : MatchedStmt->getThrowLoc();
35
36 // Early return on invalid locations.
37 if (SourceLoc.isInvalid())
38 return;
39
40 // If the match location was in a macro, check if the macro was in a system
41 // header.
42 if (SourceLoc.isMacroID()) {
43 SourceManager &SM = *Result.SourceManager;
44 auto MacroLoc = SM.getImmediateMacroCallerLoc(SourceLoc);
45
46 // Matches in system header macros should be ignored.
47 if (SM.isInSystemHeader(MacroLoc))
48 return;
49 }
50
51 diag(SourceLoc,
52 "pass in NSError ** instead of throwing exception to indicate "
53 "Objective-C errors");
54}
55
56} // namespace clang::tidy::google::objc
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
void registerMatchers(ast_matchers::MatchFinder *Finder) override