xref: /llvm-project/clang-tools-extra/clang-tidy/modernize/ReplaceRandomShuffleCheck.cpp (revision 8f73c4432b5fa8510c99a5053c07dc70a610e1fb)
1 //===--- ReplaceRandomShuffleCheck.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 "ReplaceRandomShuffleCheck.h"
10 #include "../utils/FixItHintUtils.h"
11 #include "clang/AST/ASTContext.h"
12 #include "clang/ASTMatchers/ASTMatchFinder.h"
13 #include "clang/Frontend/CompilerInstance.h"
14 #include "clang/Lex/Preprocessor.h"
15 #include "clang/Tooling/FixIt.h"
16 
17 using namespace clang::ast_matchers;
18 
19 namespace clang {
20 namespace tidy {
21 namespace modernize {
22 
23 ReplaceRandomShuffleCheck::ReplaceRandomShuffleCheck(StringRef Name,
24                                                      ClangTidyContext *Context)
25     : ClangTidyCheck(Name, Context),
26       IncludeStyle(Options.getLocalOrGlobal("IncludeStyle",
27                                             utils::IncludeSorter::getMapping(),
28                                             utils::IncludeSorter::IS_LLVM)) {}
29 
30 void ReplaceRandomShuffleCheck::registerMatchers(MatchFinder *Finder) {
31   const auto Begin = hasArgument(0, expr());
32   const auto End = hasArgument(1, expr());
33   const auto RandomFunc = hasArgument(2, expr().bind("randomFunc"));
34   Finder->addMatcher(
35       traverse(
36           ast_type_traits::TK_AsIs,
37           callExpr(
38               anyOf(allOf(Begin, End, argumentCountIs(2)),
39                     allOf(Begin, End, RandomFunc, argumentCountIs(3))),
40               hasDeclaration(functionDecl(hasName("::std::random_shuffle"))),
41               has(implicitCastExpr(has(declRefExpr().bind("name")))))
42               .bind("match")),
43       this);
44 }
45 
46 void ReplaceRandomShuffleCheck::registerPPCallbacks(
47     const SourceManager &SM, Preprocessor *PP, Preprocessor *ModuleExpanderPP) {
48   IncludeInserter = std::make_unique<utils::IncludeInserter>(SM, getLangOpts(),
49                                                               IncludeStyle);
50   PP->addPPCallbacks(IncludeInserter->CreatePPCallbacks());
51 }
52 
53 void ReplaceRandomShuffleCheck::storeOptions(
54     ClangTidyOptions::OptionMap &Opts) {
55   Options.store(Opts, "IncludeStyle", IncludeStyle,
56                 utils::IncludeSorter::getMapping());
57 }
58 
59 void ReplaceRandomShuffleCheck::check(const MatchFinder::MatchResult &Result) {
60   const auto *MatchedDecl = Result.Nodes.getNodeAs<DeclRefExpr>("name");
61   const auto *MatchedArgumentThree = Result.Nodes.getNodeAs<Expr>("randomFunc");
62   const auto *MatchedCallExpr = Result.Nodes.getNodeAs<CallExpr>("match");
63 
64   if (MatchedCallExpr->getBeginLoc().isMacroID())
65     return;
66 
67   auto Diag = [&] {
68     if (MatchedCallExpr->getNumArgs() == 3) {
69       auto DiagL =
70           diag(MatchedCallExpr->getBeginLoc(),
71                "'std::random_shuffle' has been removed in C++17; use "
72                "'std::shuffle' and an alternative random mechanism instead");
73       DiagL << FixItHint::CreateReplacement(
74           MatchedArgumentThree->getSourceRange(),
75           "std::mt19937(std::random_device()())");
76       return DiagL;
77     } else {
78       auto DiagL = diag(MatchedCallExpr->getBeginLoc(),
79                         "'std::random_shuffle' has been removed in C++17; use "
80                         "'std::shuffle' instead");
81       DiagL << FixItHint::CreateInsertion(
82           MatchedCallExpr->getRParenLoc(),
83           ", std::mt19937(std::random_device()())");
84       return DiagL;
85     }
86   }();
87 
88   std::string NewName = "shuffle";
89   StringRef ContainerText = Lexer::getSourceText(
90       CharSourceRange::getTokenRange(MatchedDecl->getSourceRange()),
91       *Result.SourceManager, getLangOpts());
92   if (ContainerText.startswith("std::"))
93     NewName = "std::" + NewName;
94 
95   Diag << FixItHint::CreateRemoval(MatchedDecl->getSourceRange());
96   Diag << FixItHint::CreateInsertion(MatchedDecl->getBeginLoc(), NewName);
97   Diag << IncludeInserter->CreateIncludeInsertion(
98       Result.Context->getSourceManager().getFileID(
99           MatchedCallExpr->getBeginLoc()),
100       "random", /*IsAngled=*/true);
101 }
102 
103 } // namespace modernize
104 } // namespace tidy
105 } // namespace clang
106