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