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/ASTMatchers/ASTMatchFinder.h"
11
12using namespace clang::ast_matchers;
13
14namespace clang::tidy::cppcoreguidelines {
15
16namespace {
17AST_MATCHER(GotoStmt, isForwardJumping) {
18 return Node.getBeginLoc() < Node.getLabel()->getBeginLoc();
19}
20
21AST_MATCHER(GotoStmt, isInMacro) {
22 return Node.getBeginLoc().isMacroID() && Node.getEndLoc().isMacroID();
23}
24} // namespace
25
26AvoidGotoCheck::AvoidGotoCheck(StringRef Name, ClangTidyContext *Context)
27 : ClangTidyCheck(Name, Context),
28 IgnoreMacros(Options.get(LocalName: "IgnoreMacros", Default: false)) {}
29
30void AvoidGotoCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) {
31 Options.store(Options&: Opts, LocalName: "IgnoreMacros", Value: IgnoreMacros);
32}
33
34void AvoidGotoCheck::registerMatchers(MatchFinder *Finder) {
35 // TODO: This check does not recognize `IndirectGotoStmt` which is a
36 // GNU extension. These must be matched separately and an AST matcher
37 // is currently missing for them.
38
39 // Check if the 'goto' is used for control flow other than jumping
40 // out of a nested loop.
41 auto Loop = mapAnyOf(forStmt, cxxForRangeStmt, whileStmt, doStmt);
42 auto NestedLoop = Loop.with(hasAncestor(Loop));
43
44 const ast_matchers::internal::Matcher<GotoStmt> Anything = anything();
45
46 Finder->addMatcher(NodeMatch: gotoStmt(IgnoreMacros ? unless(isInMacro()) : Anything,
47 anyOf(unless(hasAncestor(NestedLoop)),
48 unless(isForwardJumping())))
49 .bind(ID: "goto"),
50 Action: this);
51}
52
53void AvoidGotoCheck::check(const MatchFinder::MatchResult &Result) {
54 const auto *Goto = Result.Nodes.getNodeAs<GotoStmt>(ID: "goto");
55
56 diag(Loc: Goto->getGotoLoc(), Description: "avoid using 'goto' for flow control")
57 << Goto->getSourceRange();
58 diag(Loc: Goto->getLabel()->getBeginLoc(), Description: "label defined here",
59 Level: DiagnosticIDs::Note);
60}
61} // namespace clang::tidy::cppcoreguidelines
62

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