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