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/AST/ASTContext.h" 11 #include "clang/ASTMatchers/ASTMatchFinder.h" 12 13 using namespace clang::ast_matchers; 14 15 namespace clang { 16 namespace tidy { 17 namespace google { 18 namespace objc { 19 20 void AvoidThrowingObjCExceptionCheck::registerMatchers(MatchFinder *Finder) { 21 // this check should only be applied to ObjC sources. 22 if (!getLangOpts().ObjC) 23 return; 24 25 Finder->addMatcher(objcThrowStmt().bind("throwStmt"), this); 26 Finder->addMatcher( 27 objcMessageExpr(anyOf(hasSelector("raise:format:"), 28 hasSelector("raise:format:arguments:")), 29 hasReceiverType(asString("NSException"))) 30 .bind("raiseException"), 31 this); 32 } 33 34 void AvoidThrowingObjCExceptionCheck::check( 35 const MatchFinder::MatchResult &Result) { 36 const auto *MatchedStmt = 37 Result.Nodes.getNodeAs<ObjCAtThrowStmt>("throwStmt"); 38 const auto *MatchedExpr = 39 Result.Nodes.getNodeAs<ObjCMessageExpr>("raiseException"); 40 auto SourceLoc = MatchedStmt == nullptr ? MatchedExpr->getSelectorStartLoc() 41 : MatchedStmt->getThrowLoc(); 42 diag(SourceLoc, 43 "pass in NSError ** instead of throwing exception to indicate " 44 "Objective-C errors"); 45 } 46 47 } // namespace objc 48 } // namespace google 49 } // namespace tidy 50 } // namespace clang 51