clang-tools  10.0.0
ReplaceRandomShuffleCheck.cpp
Go to the documentation of this file.
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 
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(utils::IncludeSorter::parseIncludeStyle(
27  Options.getLocalOrGlobal("IncludeStyle", "llvm"))) {}
28 
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 
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 
54  Options.store(Opts, "IncludeStyle",
55  utils::IncludeSorter::toString(IncludeStyle));
56 }
57 
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
static StringRef toString(IncludeStyle Style)
Converts IncludeStyle to string representation.
Base class for all clang-tidy checks.
const LangOptions & getLangOpts() const
Returns the language options from the context.
void storeOptions(ClangTidyOptions::OptionMap &Opts) override
Should store all options supported by this check with their current values or default values for opti...
void store(ClangTidyOptions::OptionMap &Options, StringRef LocalName, StringRef Value) const
Stores an option with the check-local name LocalName with string value Value to Options.
static constexpr llvm::StringLiteral Name
std::map< std::string, std::string > OptionMap
llvm::Optional< Range > getTokenRange(const SourceManager &SM, const LangOptions &LangOpts, SourceLocation TokLoc)
Returns the taken range at TokLoc.
Definition: SourceCode.cpp:227
void registerMatchers(ast_matchers::MatchFinder *Finder) override
Override this to register AST matchers with Finder.
void registerPPCallbacks(const SourceManager &SM, Preprocessor *PP, Preprocessor *ModuleExpanderPP) override
Override this to register PPCallbacks in the preprocessor.
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
Every ClangTidyCheck reports errors through a DiagnosticsEngine provided by this context.
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
ClangTidyChecks that register ASTMatchers should do the actual work in here.
DiagnosticBuilder diag(SourceLocation Loc, StringRef Description, DiagnosticIDs::Level Level=DiagnosticIDs::Warning)
Add a diagnostic with the check&#39;s name.