clang-tools 20.0.0git
AvoidGotoCheck.cpp
Go to the documentation of this file.
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
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(gotoStmt(anyOf(unless(hasAncestor(NestedLoop)),
34 unless(isForwardJumping())))
35 .bind("goto"),
36 this);
37}
38
39void 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
::clang::DynTypedNode Node
DiagnosticBuilder diag(SourceLocation Loc, StringRef Description, DiagnosticIDs::Level Level=DiagnosticIDs::Warning)
Add a diagnostic with the check's name.
void registerMatchers(ast_matchers::MatchFinder *Finder) override
Override this to register AST matchers with Finder.
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
ClangTidyChecks that register ASTMatchers should do the actual work in here.
AST_MATCHER(CXXRecordDecl, hasPublicVirtualOrProtectedNonVirtualDestructor)