clang-tools  5.0.0
ElseAfterReturnCheck.cpp
Go to the documentation of this file.
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"), cxxThrowExpr().bind("throw")));
25  Finder->addMatcher(
26  compoundStmt(forEach(
27  ifStmt(hasThen(stmt(
28  anyOf(ControlFlowInterruptorMatcher,
29  compoundStmt(has(ControlFlowInterruptorMatcher))))),
30  hasElse(stmt().bind("else")))
31  .bind("if"))),
32  this);
33 }
34 
35 void ElseAfterReturnCheck::check(const MatchFinder::MatchResult &Result) {
36  const auto *If = Result.Nodes.getNodeAs<IfStmt>("if");
37  SourceLocation ElseLoc = If->getElseLoc();
38  std::string ControlFlowInterruptor;
39  for (const auto *BindingName : {"return", "continue", "break", "throw"})
40  if (Result.Nodes.getNodeAs<Stmt>(BindingName))
41  ControlFlowInterruptor = BindingName;
42 
43  DiagnosticBuilder Diag = diag(ElseLoc, "do not use 'else' after '%0'")
44  << ControlFlowInterruptor;
45  Diag << tooling::fixit::createRemoval(ElseLoc);
46 
47  // FIXME: Removing the braces isn't always safe. Do a more careful analysis.
48  // FIXME: Change clang-format to correctly un-indent the code.
49  if (const auto *CS = Result.Nodes.getNodeAs<CompoundStmt>("else"))
50  Diag << tooling::fixit::createRemoval(CS->getLBracLoc())
51  << tooling::fixit::createRemoval(CS->getRBracLoc());
52 }
53 
54 } // namespace readability
55 } // namespace tidy
56 } // namespace clang
std::unique_ptr< ast_matchers::MatchFinder > Finder
Definition: ClangTidy.cpp:275