xref: /llvm-project/clang-tools-extra/clang-tidy/cppcoreguidelines/AvoidGotoCheck.cpp (revision 7d2ea6c422d3f5712b7253407005e1a465a76946)
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::tidy::cppcoreguidelines {
16 
17 namespace {
AST_MATCHER(GotoStmt,isForwardJumping)18 AST_MATCHER(GotoStmt, isForwardJumping) {
19   return Node.getBeginLoc() < Node.getLabel()->getBeginLoc();
20 }
21 } // namespace
22 
registerMatchers(MatchFinder * Finder)23 void AvoidGotoCheck::registerMatchers(MatchFinder *Finder) {
24   // TODO: This check does not recognize `IndirectGotoStmt` which is a
25   // GNU extension. These must be matched separately and an AST matcher
26   // is currently missing for them.
27 
28   // Check if the 'goto' is used for control flow other than jumping
29   // out of a nested loop.
30   auto Loop = mapAnyOf(forStmt, cxxForRangeStmt, whileStmt, doStmt);
31   auto NestedLoop = Loop.with(hasAncestor(Loop));
32 
33   Finder->addMatcher(gotoStmt(anyOf(unless(hasAncestor(NestedLoop)),
34                                     unless(isForwardJumping())))
35                          .bind("goto"),
36                      this);
37 }
38 
check(const MatchFinder::MatchResult & Result)39 void AvoidGotoCheck::check(const MatchFinder::MatchResult &Result) {
40   const auto *Goto = Result.Nodes.getNodeAs<GotoStmt>("goto");
41 
42   diag(Goto->getGotoLoc(), "avoid using 'goto' for flow control")
43       << Goto->getSourceRange();
44   diag(Goto->getLabel()->getBeginLoc(), "label defined here",
45        DiagnosticIDs::Note);
46 }
47 } // namespace clang::tidy::cppcoreguidelines
48