1 | //===--- TerminatingContinueCheck.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 "TerminatingContinueCheck.h" |
10 | #include "clang/AST/ASTContext.h" |
11 | #include "clang/ASTMatchers/ASTMatchFinder.h" |
12 | #include "clang/Lex/Lexer.h" |
13 | #include "clang/Tooling/FixIt.h" |
14 | |
15 | using namespace clang::ast_matchers; |
16 | |
17 | namespace clang::tidy::bugprone { |
18 | |
19 | void TerminatingContinueCheck::registerMatchers(MatchFinder *Finder) { |
20 | const auto DoWithFalse = |
21 | doStmt(hasCondition(InnerMatcher: ignoringImpCasts( |
22 | InnerMatcher: anyOf(cxxBoolLiteral(equals(Value: false)), integerLiteral(equals(Value: 0)), |
23 | cxxNullPtrLiteralExpr(), gnuNullExpr()))), |
24 | equalsBoundNode(ID: "closestLoop" )); |
25 | |
26 | Finder->addMatcher( |
27 | NodeMatch: continueStmt( |
28 | hasAncestor(stmt(anyOf(forStmt(), whileStmt(), cxxForRangeStmt(), |
29 | doStmt(), switchStmt())) |
30 | .bind(ID: "closestLoop" )), |
31 | hasAncestor(DoWithFalse)) |
32 | .bind(ID: "continue" ), |
33 | Action: this); |
34 | } |
35 | |
36 | void TerminatingContinueCheck::check(const MatchFinder::MatchResult &Result) { |
37 | const auto *ContStmt = Result.Nodes.getNodeAs<ContinueStmt>(ID: "continue" ); |
38 | |
39 | auto Diag = |
40 | diag(Loc: ContStmt->getBeginLoc(), |
41 | Description: "'continue' in loop with false condition is equivalent to 'break'" ) |
42 | << tooling::fixit::createReplacement(Destination: *ContStmt, Source: "break" ); |
43 | } |
44 | |
45 | } // namespace clang::tidy::bugprone |
46 | |