1 //===--- ReplaceRandomShuffleCheck.cpp - clang-tidy------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "ReplaceRandomShuffleCheck.h"
11 #include "../utils/FixItHintUtils.h"
12 #include "clang/AST/ASTContext.h"
13 #include "clang/ASTMatchers/ASTMatchFinder.h"
14 #include "clang/Frontend/CompilerInstance.h"
15 #include "clang/Lex/Preprocessor.h"
16 #include "clang/Tooling/FixIt.h"
17 
18 using namespace clang::ast_matchers;
19 
20 namespace clang {
21 namespace tidy {
22 namespace modernize {
23 
ReplaceRandomShuffleCheck(StringRef Name,ClangTidyContext * Context)24 ReplaceRandomShuffleCheck::ReplaceRandomShuffleCheck(StringRef Name,
25                                                      ClangTidyContext *Context)
26     : ClangTidyCheck(Name, Context),
27       IncludeStyle(utils::IncludeSorter::parseIncludeStyle(
28           Options.getLocalOrGlobal("IncludeStyle", "llvm"))) {}
29 
registerMatchers(MatchFinder * Finder)30 void ReplaceRandomShuffleCheck::registerMatchers(MatchFinder *Finder) {
31   if (!getLangOpts().CPlusPlus11)
32     return;
33 
34   const auto Begin = hasArgument(0, expr());
35   const auto End = hasArgument(1, expr());
36   const auto RandomFunc = hasArgument(2, expr().bind("randomFunc"));
37   Finder->addMatcher(
38       callExpr(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 
registerPPCallbacks(CompilerInstance & Compiler)46 void ReplaceRandomShuffleCheck::registerPPCallbacks(
47     CompilerInstance &Compiler) {
48   IncludeInserter = llvm::make_unique<utils::IncludeInserter>(
49       Compiler.getSourceManager(), Compiler.getLangOpts(), IncludeStyle);
50   Compiler.getPreprocessor().addPPCallbacks(
51       IncludeInserter->CreatePPCallbacks());
52 }
53 
storeOptions(ClangTidyOptions::OptionMap & Opts)54 void ReplaceRandomShuffleCheck::storeOptions(
55     ClangTidyOptions::OptionMap &Opts) {
56   Options.store(Opts, "IncludeStyle",
57                 utils::IncludeSorter::toString(IncludeStyle));
58 }
59 
check(const MatchFinder::MatchResult & Result)60 void ReplaceRandomShuffleCheck::check(const MatchFinder::MatchResult &Result) {
61   const auto *MatchedDecl = Result.Nodes.getNodeAs<DeclRefExpr>("name");
62   const auto *MatchedArgumentThree = Result.Nodes.getNodeAs<Expr>("randomFunc");
63   const auto *MatchedCallExpr = Result.Nodes.getNodeAs<CallExpr>("match");
64 
65   if (MatchedCallExpr->getBeginLoc().isMacroID())
66     return;
67 
68   auto Diag = [&] {
69     if (MatchedCallExpr->getNumArgs() == 3) {
70       auto DiagL =
71           diag(MatchedCallExpr->getBeginLoc(),
72                "'std::random_shuffle' has been removed in C++17; use "
73                "'std::shuffle' and an alternative random mechanism instead");
74       DiagL << FixItHint::CreateReplacement(
75           MatchedArgumentThree->getSourceRange(),
76           "std::mt19937(std::random_device()())");
77       return DiagL;
78     } else {
79       auto DiagL = diag(MatchedCallExpr->getBeginLoc(),
80                         "'std::random_shuffle' has been removed in C++17; use "
81                         "'std::shuffle' instead");
82       DiagL << FixItHint::CreateInsertion(
83           MatchedCallExpr->getRParenLoc(),
84           ", std::mt19937(std::random_device()())");
85       return DiagL;
86     }
87   }();
88 
89   std::string NewName = "shuffle";
90   StringRef ContainerText = Lexer::getSourceText(
91       CharSourceRange::getTokenRange(MatchedDecl->getSourceRange()),
92       *Result.SourceManager, getLangOpts());
93   if (ContainerText.startswith("std::"))
94     NewName = "std::" + NewName;
95 
96   Diag << FixItHint::CreateRemoval(MatchedDecl->getSourceRange());
97   Diag << FixItHint::CreateInsertion(MatchedDecl->getBeginLoc(), NewName);
98 
99   if (Optional<FixItHint> IncludeFixit =
100           IncludeInserter->CreateIncludeInsertion(
101               Result.Context->getSourceManager().getFileID(
102                   MatchedCallExpr->getBeginLoc()),
103               "random", /*IsAngled=*/true))
104     Diag << IncludeFixit.getValue();
105 }
106 
107 } // namespace modernize
108 } // namespace tidy
109 } // namespace clang
110