1 //===--- AvoidGotoCheck.cpp - clang-tidy-----------------------------------===//
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
7 //===----------------------------------------------------------------------===//
9 #include "AvoidGotoCheck.h"
10 #include "clang/AST/ASTContext.h"
11 #include "clang/ASTMatchers/ASTMatchFinder.h"
13 using namespace clang::ast_matchers
;
15 namespace clang::tidy::cppcoreguidelines
{
18 AST_MATCHER(GotoStmt
, isForwardJumping
) {
19 return Node
.getBeginLoc() < Node
.getLabel()->getBeginLoc();
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.
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
));
33 Finder
->addMatcher(gotoStmt(anyOf(unless(hasAncestor(NestedLoop
)),
34 unless(isForwardJumping())))
39 void AvoidGotoCheck::check(const MatchFinder::MatchResult
&Result
) {
40 const auto *Goto
= Result
.Nodes
.getNodeAs
<GotoStmt
>("goto");
42 diag(Goto
->getGotoLoc(), "avoid using 'goto' for flow control")
43 << Goto
->getSourceRange();
44 diag(Goto
->getLabel()->getBeginLoc(), "label defined here",
47 } // namespace clang::tidy::cppcoreguidelines