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
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(utils::IncludeSorter::parseIncludeStyle(
27 Options.getLocalOrGlobal("IncludeStyle", "llvm"))) {}
28
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
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
52 void ReplaceRandomShuffleCheck::storeOptions(
53 ClangTidyOptions::OptionMap &Opts) {
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
clang::ast_matchers
Definition: AbseilMatcher.h:14
clang::tidy::utils::IncludeSorter::toString
static StringRef toString(IncludeStyle Style)
Converts IncludeStyle to string representation.
Definition: IncludeSorter.cpp:283
clang::tidy::ClangTidyCheck
Base class for all clang-tidy checks.
Definition: ClangTidyCheck.h:47
clang::tidy::ClangTidyCheck::getLangOpts
const LangOptions & getLangOpts() const
Returns the language options from the context.
Definition: ClangTidyCheck.h:188
clang::tidy::modernize::ReplaceRandomShuffleCheck::storeOptions
void storeOptions(ClangTidyOptions::OptionMap &Opts) override
Should store all options supported by this check with their current values or default values for opti...
Definition: ReplaceRandomShuffleCheck.cpp:52
clang::tidy::ClangTidyCheck::Options
OptionsView Options
Definition: ClangTidyCheck.h:184
clang::tidy::ClangTidyCheck::OptionsView::store
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.
Definition: ClangTidyCheck.cpp:58
ReplaceRandomShuffleCheck.h
Name
static constexpr llvm::StringLiteral Name
Definition: UppercaseLiteralSuffixCheck.cpp:27
clang::tidy::ClangTidyOptions::OptionMap
std::map< std::string, std::string > OptionMap
Definition: ClangTidyOptions.h:97
clang::clangd::getTokenRange
llvm::Optional< Range > getTokenRange(const SourceManager &SM, const LangOptions &LangOpts, SourceLocation TokLoc)
Returns the taken range at TokLoc.
Definition: SourceCode.cpp:227
clang::tidy::modernize::ReplaceRandomShuffleCheck::registerMatchers
void registerMatchers(ast_matchers::MatchFinder *Finder) override
Override this to register AST matchers with Finder.
Definition: ReplaceRandomShuffleCheck.cpp:29
clang::tidy::modernize::ReplaceRandomShuffleCheck::registerPPCallbacks
void registerPPCallbacks(const SourceManager &SM, Preprocessor *PP, Preprocessor *ModuleExpanderPP) override
Override this to register PPCallbacks in the preprocessor.
Definition: ReplaceRandomShuffleCheck.cpp:45
clang
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
Definition: ApplyReplacements.h:27
clang::tidy::bugprone::PP
static Preprocessor * PP
Definition: BadSignalToKillThreadCheck.cpp:28
clang::tidy::ClangTidyContext
Every ClangTidyCheck reports errors through a DiagnosticsEngine provided by this context.
Definition: ClangTidyDiagnosticConsumer.h:77
clang::tidy::modernize::ReplaceRandomShuffleCheck::check
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
ClangTidyChecks that register ASTMatchers should do the actual work in here.
Definition: ReplaceRandomShuffleCheck.cpp:58
clang::tidy::ClangTidyCheck::diag
DiagnosticBuilder diag(SourceLocation Loc, StringRef Description, DiagnosticIDs::Level Level=DiagnosticIDs::Warning)
Add a diagnostic with the check&#39;s name.
Definition: ClangTidyCheck.cpp:21