clang-tools  9.0.0
TransformerClangTidyCheck.cpp
Go to the documentation of this file.
1 //===---------- TransformerClangTidyCheck.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 "llvm/ADT/STLExtras.h"
11 
12 namespace clang {
13 namespace tidy {
14 namespace utils {
15 using tooling::RewriteRule;
16 
17 #ifndef NDEBUG
18 static bool hasExplanation(const RewriteRule::Case &C) {
19  return C.Explanation != nullptr;
20 }
21 #endif
22 
23 // This constructor cannot dispatch to the simpler one (below), because, in
24 // order to get meaningful results from `getLangOpts` and `Options`, we need the
25 // `ClangTidyCheck()` constructor to have been called. If we were to dispatch,
26 // we would be accessing `getLangOpts` and `Options` before the underlying
27 // `ClangTidyCheck` instance was properly initialized.
29  std::function<Optional<RewriteRule>(const LangOptions &,
30  const OptionsView &)>
31  MakeRule,
32  StringRef Name, ClangTidyContext *Context)
33  : ClangTidyCheck(Name, Context), Rule(MakeRule(getLangOpts(), Options)) {
34  if (Rule)
35  assert(llvm::all_of(Rule->Cases, hasExplanation) &&
36  "clang-tidy checks must have an explanation by default;"
37  " explicitly provide an empty explanation if none is desired");
38 }
39 
41  StringRef Name,
42  ClangTidyContext *Context)
43  : ClangTidyCheck(Name, Context), Rule(std::move(R)) {
44  assert(llvm::all_of(Rule->Cases, hasExplanation) &&
45  "clang-tidy checks must have an explanation by default;"
46  " explicitly provide an empty explanation if none is desired");
47 }
48 
50  const SourceManager &SM, Preprocessor *PP, Preprocessor *ModuleExpanderPP) {
51  // Only allocate and register the IncludeInsert when some `Case` will add
52  // includes.
53  if (Rule && llvm::any_of(Rule->Cases, [](const RewriteRule::Case &C) {
54  return !C.AddedIncludes.empty();
55  })) {
56  Inserter = llvm::make_unique<IncludeInserter>(
58  PP->addPPCallbacks(Inserter->CreatePPCallbacks());
59  }
60 }
61 
63  ast_matchers::MatchFinder *Finder) {
64  if (Rule)
65  Finder->addDynamicMatcher(tooling::detail::buildMatcher(*Rule), this);
66 }
67 
69  const ast_matchers::MatchFinder::MatchResult &Result) {
70  if (Result.Context->getDiagnostics().hasErrorOccurred())
71  return;
72 
73  // Verify the existence and validity of the AST node that roots this rule.
74  const ast_matchers::BoundNodes::IDToNodeMap &NodesMap = Result.Nodes.getMap();
75  auto Root = NodesMap.find(RewriteRule::RootID);
76  assert(Root != NodesMap.end() && "Transformation failed: missing root node.");
77  SourceLocation RootLoc = Result.SourceManager->getExpansionLoc(
78  Root->second.getSourceRange().getBegin());
79  assert(RootLoc.isValid() && "Invalid location for Root node of match.");
80 
81  assert(Rule && "check() should not fire if Rule is None");
82  RewriteRule::Case Case = tooling::detail::findSelectedCase(Result, *Rule);
83  Expected<SmallVector<tooling::detail::Transformation, 1>> Transformations =
84  tooling::detail::translateEdits(Result, Case.Edits);
85  if (!Transformations) {
86  llvm::errs() << "Rewrite failed: "
87  << llvm::toString(Transformations.takeError()) << "\n";
88  return;
89  }
90 
91  // No rewrite applied, but no error encountered either.
92  if (Transformations->empty())
93  return;
94 
95  Expected<std::string> Explanation = Case.Explanation(Result);
96  if (!Explanation) {
97  llvm::errs() << "Error in explanation: "
98  << llvm::toString(Explanation.takeError()) << "\n";
99  return;
100  }
101  DiagnosticBuilder Diag = diag(RootLoc, *Explanation);
102  for (const auto &T : *Transformations) {
103  Diag << FixItHint::CreateReplacement(T.Range, T.Replacement);
104  }
105 
106  for (const auto &I : Case.AddedIncludes) {
107  auto &Header = I.first;
108  if (Optional<FixItHint> Fix = Inserter->CreateIncludeInsertion(
109  Result.SourceManager->getMainFileID(), Header,
110  /*IsAngled=*/I.second == tooling::IncludeFormat::Angled)) {
111  Diag << *Fix;
112  }
113  }
114 }
115 
116 } // namespace utils
117 } // namespace tidy
118 } // namespace clang
TransformerClangTidyCheck(std::function< Optional< tooling::RewriteRule >(const LangOptions &, const OptionsView &)> MakeRule, StringRef Name, ClangTidyContext *Context)
static llvm::StringRef toString(SpecialMemberFunctionsCheck::SpecialMemberFunctionKind K)
Base class for all clang-tidy checks.
const LangOptions & getLangOpts() const
Returns the language options from the context.
void registerPPCallbacks(const SourceManager &SM, Preprocessor *PP, Preprocessor *ModuleExpanderPP) override
Override this to register PPCallbacks in the preprocessor.
void check(const ast_matchers::MatchFinder::MatchResult &Result) final
ClangTidyChecks that register ASTMatchers should do the actual work in here.
static bool hasExplanation(const RewriteRule::Case &C)
void registerMatchers(ast_matchers::MatchFinder *Finder) final
Override this to register AST matchers with Finder.
static constexpr llvm::StringLiteral Name
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
Every ClangTidyCheck reports errors through a DiagnosticsEngine provided by this context.
llvm::Optional< llvm::Expected< tooling::AtomicChanges > > Result
Definition: Rename.cpp:36
static cl::opt< bool > Fix("fix", cl::desc(R"( Apply suggested fixes. Without -fix-errors clang-tidy will bail out if any compilation errors were found. )"), cl::init(false), cl::cat(ClangTidyCategory))
DiagnosticBuilder diag(SourceLocation Loc, StringRef Description, DiagnosticIDs::Level Level=DiagnosticIDs::Warning)
Add a diagnostic with the check&#39;s name.