clang-tools 22.0.0git
AvoidGotoCheck.cpp
Go to the documentation of this file.
1//===----------------------------------------------------------------------===//
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
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
27 : ClangTidyCheck(Name, Context),
28 IgnoreMacros(Options.get("IgnoreMacros", false)) {}
29
31 Options.store(Opts, "IgnoreMacros", 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(gotoStmt(IgnoreMacros ? unless(isInMacro()) : Anything,
47 anyOf(unless(hasAncestor(NestedLoop)),
48 unless(isForwardJumping())))
49 .bind("goto"),
50 this);
51}
52
53void AvoidGotoCheck::check(const MatchFinder::MatchResult &Result) {
54 const auto *Goto = Result.Nodes.getNodeAs<GotoStmt>("goto");
55
56 diag(Goto->getGotoLoc(), "avoid using 'goto' for flow control")
57 << Goto->getSourceRange();
58 diag(Goto->getLabel()->getBeginLoc(), "label defined here",
59 DiagnosticIDs::Note);
60}
61} // namespace clang::tidy::cppcoreguidelines
Every ClangTidyCheck reports errors through a DiagnosticsEngine provided by this context.
void registerMatchers(ast_matchers::MatchFinder *Finder) override
void storeOptions(ClangTidyOptions::OptionMap &Opts) override
AvoidGotoCheck(StringRef Name, ClangTidyContext *Context)
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
AST_MATCHER(BinaryOperator, isRelationalOperator)
llvm::StringMap< ClangTidyValue > OptionMap