clang-tools  3.9.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  // FIXME: Support continue, break and throw.
23  Finder->addMatcher(
24  compoundStmt(
25  forEach(ifStmt(hasThen(stmt(anyOf(returnStmt(),
26  compoundStmt(has(returnStmt()))))),
27  hasElse(stmt().bind("else")))
28  .bind("if"))),
29  this);
30 }
31 
32 void ElseAfterReturnCheck::check(const MatchFinder::MatchResult &Result) {
33  const auto *If = Result.Nodes.getNodeAs<IfStmt>("if");
34  SourceLocation ElseLoc = If->getElseLoc();
35  DiagnosticBuilder Diag = diag(ElseLoc, "don't use else after return");
36  Diag << tooling::fixit::createRemoval(ElseLoc);
37 
38  // FIXME: Removing the braces isn't always safe. Do a more careful analysis.
39  // FIXME: Change clang-format to correctly un-indent the code.
40  if (const auto *CS = Result.Nodes.getNodeAs<CompoundStmt>("else"))
41  Diag << tooling::fixit::createRemoval(CS->getLBracLoc())
42  << tooling::fixit::createRemoval(CS->getRBracLoc());
43 }
44 
45 } // namespace readability
46 } // namespace tidy
47 } // namespace clang
std::unique_ptr< ast_matchers::MatchFinder > Finder
Definition: ClangTidy.cpp:210
const NamedDecl * Result
Definition: USRFinder.cpp:137