1 //===--- ElseAfterReturnCheck.cpp - clang-tidy-----------------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 10 #include "ElseAfterReturnCheck.h" 11 #include "clang/AST/ASTContext.h" 12 #include "clang/ASTMatchers/ASTMatchFinder.h" 13 #include "clang/Tooling/FixIt.h" 14 15 using namespace clang::ast_matchers; 16 17 namespace clang { 18 namespace tidy { 19 namespace readability { 20 21 void ElseAfterReturnCheck::registerMatchers(MatchFinder *Finder) { 22 const auto ControlFlowInterruptorMatcher = 23 stmt(anyOf(returnStmt().bind("return"), continueStmt().bind("continue"), 24 breakStmt().bind("break"), 25 expr(ignoringImplicit(cxxThrowExpr().bind("throw"))))); 26 Finder->addMatcher( 27 compoundStmt(forEach( 28 ifStmt(unless(isConstexpr()), 29 hasThen(stmt( 30 anyOf(ControlFlowInterruptorMatcher, 31 compoundStmt(has(ControlFlowInterruptorMatcher))))), 32 hasElse(stmt().bind("else"))) 33 .bind("if"))), 34 this); 35 } 36 37 void ElseAfterReturnCheck::check(const MatchFinder::MatchResult &Result) { 38 const auto *If = Result.Nodes.getNodeAs<IfStmt>("if"); 39 SourceLocation ElseLoc = If->getElseLoc(); 40 std::string ControlFlowInterruptor; 41 for (const auto *BindingName : {"return", "continue", "break", "throw"}) 42 if (Result.Nodes.getNodeAs<Stmt>(BindingName)) 43 ControlFlowInterruptor = BindingName; 44 45 DiagnosticBuilder Diag = diag(ElseLoc, "do not use 'else' after '%0'") 46 << ControlFlowInterruptor; 47 Diag << tooling::fixit::createRemoval(ElseLoc); 48 49 // FIXME: Removing the braces isn't always safe. Do a more careful analysis. 50 // FIXME: Change clang-format to correctly un-indent the code. 51 if (const auto *CS = Result.Nodes.getNodeAs<CompoundStmt>("else")) 52 Diag << tooling::fixit::createRemoval(CS->getLBracLoc()) 53 << tooling::fixit::createRemoval(CS->getRBracLoc()); 54 } 55 56 } // namespace readability 57 } // namespace tidy 58 } // namespace clang 59