xref: /llvm-project/clang-tools-extra/clang-tidy/cppcoreguidelines/AvoidDoWhileCheck.cpp (revision 7d2ea6c422d3f5712b7253407005e1a465a76946)
1 //===--- AvoidDoWhileCheck.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 "AvoidDoWhileCheck.h"
10 #include "clang/AST/ASTContext.h"
11 #include "clang/ASTMatchers/ASTMatchFinder.h"
12 
13 using namespace clang::ast_matchers;
14 
15 namespace clang::tidy::cppcoreguidelines {
16 
AvoidDoWhileCheck(StringRef Name,ClangTidyContext * Context)17 AvoidDoWhileCheck::AvoidDoWhileCheck(StringRef Name, ClangTidyContext *Context)
18     : ClangTidyCheck(Name, Context),
19       IgnoreMacros(Options.getLocalOrGlobal("IgnoreMacros", false)) {}
20 
storeOptions(ClangTidyOptions::OptionMap & Opts)21 void AvoidDoWhileCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) {
22   Options.store(Opts, "IgnoreMacros", IgnoreMacros);
23 }
24 
registerMatchers(MatchFinder * Finder)25 void AvoidDoWhileCheck::registerMatchers(MatchFinder *Finder) {
26   Finder->addMatcher(doStmt().bind("x"), this);
27 }
28 
check(const MatchFinder::MatchResult & Result)29 void AvoidDoWhileCheck::check(const MatchFinder::MatchResult &Result) {
30   if (const auto *MatchedDecl = Result.Nodes.getNodeAs<DoStmt>("x")) {
31     if (IgnoreMacros && MatchedDecl->getBeginLoc().isMacroID())
32       return;
33     diag(MatchedDecl->getBeginLoc(), "avoid do-while loops");
34   }
35 }
36 
37 } // namespace clang::tidy::cppcoreguidelines
38