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
13using namespace clang::ast_matchers;
14
15namespace clang::tidy::cppcoreguidelines {
16
17namespace {
18AST_MATCHER(GotoStmt, isForwardJumping) {
19 return Node.getBeginLoc() < Node.getLabel()->getBeginLoc();
20}
21} // namespace
22
23void 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(NodeMatch: gotoStmt(anyOf(unless(hasAncestor(NestedLoop)),
34 unless(isForwardJumping())))
35 .bind(ID: "goto"),
36 Action: this);
37}
38
39void AvoidGotoCheck::check(const MatchFinder::MatchResult &Result) {
40 const auto *Goto = Result.Nodes.getNodeAs<GotoStmt>(ID: "goto");
41
42 diag(Loc: Goto->getGotoLoc(), Description: "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

source code of clang-tools-extra/clang-tidy/cppcoreguidelines/AvoidGotoCheck.cpp