clang-tools  14.0.0git
UseAnyOfAllOfCheck.cpp
Go to the documentation of this file.
1 //===--- UseAnyOfAllOfCheck.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 "UseAnyOfAllOfCheck.h"
10 #include "clang/AST/ASTContext.h"
11 #include "clang/ASTMatchers/ASTMatchFinder.h"
12 #include "clang/Analysis/Analyses/ExprMutationAnalyzer.h"
13 #include "clang/Frontend/CompilerInstance.h"
14 
15 using namespace clang::ast_matchers;
16 
17 namespace clang {
18 namespace {
19 /// Matches a Stmt whose parent is a CompoundStmt, and which is directly
20 /// followed by a Stmt matching the inner matcher.
21 AST_MATCHER_P(Stmt, nextStmt, ast_matchers::internal::Matcher<Stmt>,
22  InnerMatcher) {
23  DynTypedNodeList Parents = Finder->getASTContext().getParents(Node);
24  if (Parents.size() != 1)
25  return false;
26 
27  auto *C = Parents[0].get<CompoundStmt>();
28  if (!C)
29  return false;
30 
31  const auto *I = llvm::find(C->body(), &Node);
32  assert(I != C->body_end() && "C is parent of Node");
33  if (++I == C->body_end())
34  return false; // Node is last statement.
35 
36  return InnerMatcher.matches(**I, Finder, Builder);
37 }
38 } // namespace
39 
40 namespace tidy {
41 namespace readability {
42 
43 void UseAnyOfAllOfCheck::registerMatchers(MatchFinder *Finder) {
44  auto Returns = [](bool V) {
45  return returnStmt(hasReturnValue(cxxBoolLiteral(equals(V))));
46  };
47 
48  auto ReturnsButNotTrue =
49  returnStmt(hasReturnValue(unless(cxxBoolLiteral(equals(true)))));
50  auto ReturnsButNotFalse =
51  returnStmt(hasReturnValue(unless(cxxBoolLiteral(equals(false)))));
52 
53  Finder->addMatcher(
54  cxxForRangeStmt(
55  nextStmt(Returns(false).bind("final_return")),
56  hasBody(allOf(hasDescendant(Returns(true)),
57  unless(anyOf(hasDescendant(breakStmt()),
58  hasDescendant(gotoStmt()),
59  hasDescendant(ReturnsButNotTrue))))))
60  .bind("any_of_loop"),
61  this);
62 
63  Finder->addMatcher(
64  cxxForRangeStmt(
65  nextStmt(Returns(true).bind("final_return")),
66  hasBody(allOf(hasDescendant(Returns(false)),
67  unless(anyOf(hasDescendant(breakStmt()),
68  hasDescendant(gotoStmt()),
69  hasDescendant(ReturnsButNotFalse))))))
70  .bind("all_of_loop"),
71  this);
72 }
73 
74 static bool isViableLoop(const CXXForRangeStmt &S, ASTContext &Context) {
75 
76  ExprMutationAnalyzer Mutations(*S.getBody(), Context);
77  if (Mutations.isMutated(S.getLoopVariable()))
78  return false;
79  const auto Matches =
80  match(findAll(declRefExpr().bind("decl_ref")), *S.getBody(), Context);
81 
82  return llvm::none_of(Matches, [&Mutations](auto &DeclRef) {
83  // TODO: allow modifications of loop-local variables
84  return Mutations.isMutated(
85  DeclRef.template getNodeAs<DeclRefExpr>("decl_ref")->getDecl());
86  });
87 }
88 
89 void UseAnyOfAllOfCheck::check(const MatchFinder::MatchResult &Result) {
90 
91  if (const auto *S = Result.Nodes.getNodeAs<CXXForRangeStmt>("any_of_loop")) {
92  if (!isViableLoop(*S, *Result.Context))
93  return;
94 
95  diag(S->getForLoc(), "replace loop by 'std%select{|::ranges}0::any_of()'")
96  << getLangOpts().CPlusPlus20;
97  } else if (const auto *S =
98  Result.Nodes.getNodeAs<CXXForRangeStmt>("all_of_loop")) {
99  if (!isViableLoop(*S, *Result.Context))
100  return;
101 
102  diag(S->getForLoc(), "replace loop by 'std%select{|::ranges}0::all_of()'")
103  << getLangOpts().CPlusPlus20;
104  }
105 }
106 
107 } // namespace readability
108 } // namespace tidy
109 } // namespace clang
clang::tidy::readability::isViableLoop
static bool isViableLoop(const CXXForRangeStmt &S, ASTContext &Context)
Definition: UseAnyOfAllOfCheck.cpp:74
clang::clangd::TypeHierarchyDirection::Parents
@ Parents
clang::ast_matchers
Definition: AbseilMatcher.h:14
clang::clangd::match
std::vector< std::string > match(const SymbolIndex &I, const FuzzyFindRequest &Req, bool *Incomplete)
Definition: TestIndex.cpp:94
Builder
CodeCompletionBuilder Builder
Definition: CodeCompletionStringsTests.cpp:36
UseAnyOfAllOfCheck.h
clang::clangd::check
bool check(llvm::StringRef File, llvm::function_ref< bool(const Position &)> ShouldCheckLine, const ThreadsafeFS &TFS, const ClangdLSPServer::Options &Opts, bool EnableCodeCompletion)
Definition: Check.cpp:259
DeclRef
const DeclRefExpr * DeclRef
Definition: UseAfterMoveCheck.cpp:50
C
const Criteria C
Definition: FunctionCognitiveComplexityCheck.cpp:93
clang
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
Definition: ApplyReplacements.h:27
clang::tidy::bugprone::AST_MATCHER_P
AST_MATCHER_P(FunctionDecl, parameterCountGE, unsigned, N)
Matches functions that have at least the specified amount of parameters.
Definition: EasilySwappableParametersCheck.cpp:1877