clang-tools  9.0.0
ElseAfterReturnCheck.cpp
Go to the documentation of this file.
1 //===--- ElseAfterReturnCheck.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 "ElseAfterReturnCheck.h"
10 #include "clang/AST/ASTContext.h"
11 #include "clang/ASTMatchers/ASTMatchFinder.h"
12 #include "clang/Tooling/FixIt.h"
13 
14 using namespace clang::ast_matchers;
15 
16 namespace clang {
17 namespace tidy {
18 namespace readability {
19 
20 void ElseAfterReturnCheck::registerMatchers(MatchFinder *Finder) {
21  const auto InterruptsControlFlow =
22  stmt(anyOf(returnStmt().bind("return"), continueStmt().bind("continue"),
23  breakStmt().bind("break"),
24  expr(ignoringImplicit(cxxThrowExpr().bind("throw")))));
25  Finder->addMatcher(
26  compoundStmt(forEach(
27  ifStmt(unless(isConstexpr()),
28  // FIXME: Explore alternatives for the
29  // `if (T x = ...) {... return; } else { <use x> }`
30  // pattern:
31  // * warn, but don't fix;
32  // * fix by pulling out the variable declaration out of
33  // the condition.
34  unless(hasConditionVariableStatement(anything())),
35  hasThen(stmt(anyOf(InterruptsControlFlow,
36  compoundStmt(has(InterruptsControlFlow))))),
37  hasElse(stmt().bind("else")))
38  .bind("if"))),
39  this);
40 }
41 
42 void ElseAfterReturnCheck::check(const MatchFinder::MatchResult &Result) {
43  const auto *If = Result.Nodes.getNodeAs<IfStmt>("if");
44  SourceLocation ElseLoc = If->getElseLoc();
45  std::string ControlFlowInterruptor;
46  for (const auto *BindingName : {"return", "continue", "break", "throw"})
47  if (Result.Nodes.getNodeAs<Stmt>(BindingName))
48  ControlFlowInterruptor = BindingName;
49 
50  DiagnosticBuilder Diag = diag(ElseLoc, "do not use 'else' after '%0'")
51  << ControlFlowInterruptor;
52  Diag << tooling::fixit::createRemoval(ElseLoc);
53 
54  // FIXME: Removing the braces isn't always safe. Do a more careful analysis.
55  // FIXME: Change clang-format to correctly un-indent the code.
56  if (const auto *CS = Result.Nodes.getNodeAs<CompoundStmt>("else"))
57  Diag << tooling::fixit::createRemoval(CS->getLBracLoc())
58  << tooling::fixit::createRemoval(CS->getRBracLoc());
59 }
60 
61 } // namespace readability
62 } // namespace tidy
63 } // namespace clang
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
llvm::Optional< llvm::Expected< tooling::AtomicChanges > > Result
Definition: Rename.cpp:36