62 lines · cpp
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-exception6//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} // namespace25 26AvoidGotoCheck::AvoidGotoCheck(StringRef Name, ClangTidyContext *Context)27 : ClangTidyCheck(Name, Context),28 IgnoreMacros(Options.get("IgnoreMacros", false)) {}29 30void AvoidGotoCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) {31 Options.store(Opts, "IgnoreMacros", IgnoreMacros);32}33 34void AvoidGotoCheck::registerMatchers(MatchFinder *Finder) {35 // TODO: This check does not recognize `IndirectGotoStmt` which is a36 // GNU extension. These must be matched separately and an AST matcher37 // is currently missing for them.38 39 // Check if the 'goto' is used for control flow other than jumping40 // 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::cppcoreguidelines62