1 | //===--- AvoidThrowingObjCExceptionCheck.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 "AvoidThrowingObjCExceptionCheck.h" |
10 | #include "clang/ASTMatchers/ASTMatchFinder.h" |
11 | |
12 | using namespace clang::ast_matchers; |
13 | |
14 | namespace clang::tidy::google::objc { |
15 | |
16 | void AvoidThrowingObjCExceptionCheck::registerMatchers(MatchFinder *Finder) { |
17 | |
18 | Finder->addMatcher(NodeMatch: objcThrowStmt().bind(ID: "throwStmt"), Action: this); |
19 | Finder->addMatcher( |
20 | NodeMatch: objcMessageExpr(anyOf(hasSelector(BaseName: "raise:format:"), |
21 | hasSelector(BaseName: "raise:format:arguments:")), |
22 | hasReceiverType(InnerMatcher: asString(Name: "NSException"))) |
23 | .bind(ID: "raiseException"), |
24 | Action: this); |
25 | } |
26 | |
27 | void AvoidThrowingObjCExceptionCheck::check( |
28 | const MatchFinder::MatchResult &Result) { |
29 | const auto *MatchedStmt = |
30 | Result.Nodes.getNodeAs<ObjCAtThrowStmt>(ID: "throwStmt"); |
31 | const auto *MatchedExpr = |
32 | Result.Nodes.getNodeAs<ObjCMessageExpr>(ID: "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(Loc: SourceLoc); |
45 | |
46 | // Matches in system header macros should be ignored. |
47 | if (SM.isInSystemHeader(Loc: MacroLoc)) |
48 | return; |
49 | } |
50 | |
51 | diag(Loc: SourceLoc, |
52 | Description: "pass in NSError ** instead of throwing exception to indicate " |
53 | "Objective-C errors"); |
54 | } |
55 | |
56 | } // namespace clang::tidy::google::objc |
57 |