| 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 | |
| 12 | using namespace clang::ast_matchers; |
| 13 | |
| 14 | namespace clang::tidy::cppcoreguidelines { |
| 15 | |
| 16 | namespace { |
| 17 | AST_MATCHER(GotoStmt, isForwardJumping) { |
| 18 | return Node.getBeginLoc() < Node.getLabel()->getBeginLoc(); |
| 19 | } |
| 20 | } // namespace |
| 21 | |
| 22 | void AvoidGotoCheck::registerMatchers(MatchFinder *Finder) { |
| 23 | // TODO: This check does not recognize `IndirectGotoStmt` which is a |
| 24 | // GNU extension. These must be matched separately and an AST matcher |
| 25 | // is currently missing for them. |
| 26 | |
| 27 | // Check if the 'goto' is used for control flow other than jumping |
| 28 | // out of a nested loop. |
| 29 | auto Loop = mapAnyOf(forStmt, cxxForRangeStmt, whileStmt, doStmt); |
| 30 | auto NestedLoop = Loop.with(hasAncestor(Loop)); |
| 31 | |
| 32 | Finder->addMatcher(NodeMatch: gotoStmt(anyOf(unless(hasAncestor(NestedLoop)), |
| 33 | unless(isForwardJumping()))) |
| 34 | .bind(ID: "goto" ), |
| 35 | Action: this); |
| 36 | } |
| 37 | |
| 38 | void AvoidGotoCheck::check(const MatchFinder::MatchResult &Result) { |
| 39 | const auto *Goto = Result.Nodes.getNodeAs<GotoStmt>(ID: "goto" ); |
| 40 | |
| 41 | diag(Loc: Goto->getGotoLoc(), Description: "avoid using 'goto' for flow control" ) |
| 42 | << Goto->getSourceRange(); |
| 43 | diag(Goto->getLabel()->getBeginLoc(), "label defined here" , |
| 44 | DiagnosticIDs::Note); |
| 45 | } |
| 46 | } // namespace clang::tidy::cppcoreguidelines |
| 47 | |