clang-tools  14.0.0git
AvoidGotoCheck.cpp
Go to the documentation of this file.
1 //===--- AvoidGotoCheck.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 "AvoidGotoCheck.h"
10 #include "clang/AST/ASTContext.h"
11 #include "clang/ASTMatchers/ASTMatchFinder.h"
12 
13 using namespace clang::ast_matchers;
14 
15 namespace clang {
16 namespace tidy {
17 namespace cppcoreguidelines {
18 
19 namespace {
20 AST_MATCHER(GotoStmt, isForwardJumping) {
21  return Node.getBeginLoc() < Node.getLabel()->getBeginLoc();
22 }
23 } // namespace
24 
25 void AvoidGotoCheck::registerMatchers(MatchFinder *Finder) {
26  // TODO: This check does not recognize `IndirectGotoStmt` which is a
27  // GNU extension. These must be matched separately and an AST matcher
28  // is currently missing for them.
29 
30  // Check if the 'goto' is used for control flow other than jumping
31  // out of a nested loop.
32  auto Loop = mapAnyOf(forStmt, cxxForRangeStmt, whileStmt, doStmt);
33  auto NestedLoop = Loop.with(hasAncestor(Loop));
34 
35  Finder->addMatcher(gotoStmt(anyOf(unless(hasAncestor(NestedLoop)),
36  unless(isForwardJumping())))
37  .bind("goto"),
38  this);
39 }
40 
41 void AvoidGotoCheck::check(const MatchFinder::MatchResult &Result) {
42  const auto *Goto = Result.Nodes.getNodeAs<GotoStmt>("goto");
43 
44  diag(Goto->getGotoLoc(), "avoid using 'goto' for flow control")
45  << Goto->getSourceRange();
46  diag(Goto->getLabel()->getBeginLoc(), "label defined here",
47  DiagnosticIDs::Note);
48 }
49 } // namespace cppcoreguidelines
50 } // namespace tidy
51 } // namespace clang
AvoidGotoCheck.h
clang::ast_matchers
Definition: AbseilMatcher.h:14
clang::ast_matchers::AST_MATCHER
AST_MATCHER(Expr, isMacroID)
Definition: PreferIsaOrDynCastInConditionalsCheck.cpp:19
clang::clangd::check
bool check(llvm::StringRef File, llvm::function_ref< bool(const Position &)> ShouldCheckLine, const ThreadsafeFS &TFS, const ClangdLSPServer::Options &Opts, bool EnableCodeCompletion)
Definition: Check.cpp:253
clang
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
Definition: ApplyReplacements.h:27