clang-tools  8.0.0
ApplyReplacements.cpp
Go to the documentation of this file.
1 //===-- ApplyReplacements.cpp - Apply and deduplicate replacements --------===//
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 /// \file
11 /// \brief This file provides the implementation for deduplicating, detecting
12 /// conflicts in, and applying collections of Replacements.
13 ///
14 /// FIXME: Use Diagnostics for output instead of llvm::errs().
15 ///
16 //===----------------------------------------------------------------------===//
18 #include "clang/Basic/LangOptions.h"
19 #include "clang/Basic/SourceManager.h"
20 #include "clang/Format/Format.h"
21 #include "clang/Lex/Lexer.h"
22 #include "clang/Rewrite/Core/Rewriter.h"
23 #include "clang/Tooling/DiagnosticsYaml.h"
24 #include "clang/Tooling/ReplacementsYaml.h"
25 #include "llvm/ADT/ArrayRef.h"
26 #include "llvm/Support/FileSystem.h"
27 #include "llvm/Support/MemoryBuffer.h"
28 #include "llvm/Support/Path.h"
29 #include "llvm/Support/raw_ostream.h"
30 
31 using namespace llvm;
32 using namespace clang;
33 
34 static void eatDiagnostics(const SMDiagnostic &, void *) {}
35 
36 namespace clang {
37 namespace replace {
38 
40  const llvm::StringRef Directory, TUReplacements &TUs,
41  TUReplacementFiles &TUFiles, clang::DiagnosticsEngine &Diagnostics) {
42  using namespace llvm::sys::fs;
43  using namespace llvm::sys::path;
44 
45  std::error_code ErrorCode;
46 
47  for (recursive_directory_iterator I(Directory, ErrorCode), E;
48  I != E && !ErrorCode; I.increment(ErrorCode)) {
49  if (filename(I->path())[0] == '.') {
50  // Indicate not to descend into directories beginning with '.'
51  I.no_push();
52  continue;
53  }
54 
55  if (extension(I->path()) != ".yaml")
56  continue;
57 
58  TUFiles.push_back(I->path());
59 
60  ErrorOr<std::unique_ptr<MemoryBuffer>> Out =
61  MemoryBuffer::getFile(I->path());
62  if (std::error_code BufferError = Out.getError()) {
63  errs() << "Error reading " << I->path() << ": " << BufferError.message()
64  << "\n";
65  continue;
66  }
67 
68  yaml::Input YIn(Out.get()->getBuffer(), nullptr, &eatDiagnostics);
69  tooling::TranslationUnitReplacements TU;
70  YIn >> TU;
71  if (YIn.error()) {
72  // File doesn't appear to be a header change description. Ignore it.
73  continue;
74  }
75 
76  // Only keep files that properly parse.
77  TUs.push_back(TU);
78  }
79 
80  return ErrorCode;
81 }
82 
84  const llvm::StringRef Directory, TUDiagnostics &TUs,
85  TUReplacementFiles &TUFiles, clang::DiagnosticsEngine &Diagnostics) {
86  using namespace llvm::sys::fs;
87  using namespace llvm::sys::path;
88 
89  std::error_code ErrorCode;
90 
91  for (recursive_directory_iterator I(Directory, ErrorCode), E;
92  I != E && !ErrorCode; I.increment(ErrorCode)) {
93  if (filename(I->path())[0] == '.') {
94  // Indicate not to descend into directories beginning with '.'
95  I.no_push();
96  continue;
97  }
98 
99  if (extension(I->path()) != ".yaml")
100  continue;
101 
102  TUFiles.push_back(I->path());
103 
104  ErrorOr<std::unique_ptr<MemoryBuffer>> Out =
105  MemoryBuffer::getFile(I->path());
106  if (std::error_code BufferError = Out.getError()) {
107  errs() << "Error reading " << I->path() << ": " << BufferError.message()
108  << "\n";
109  continue;
110  }
111 
112  yaml::Input YIn(Out.get()->getBuffer(), nullptr, &eatDiagnostics);
113  tooling::TranslationUnitDiagnostics TU;
114  YIn >> TU;
115  if (YIn.error()) {
116  // File doesn't appear to be a header change description. Ignore it.
117  continue;
118  }
119 
120  // Only keep files that properly parse.
121  TUs.push_back(TU);
122  }
123 
124  return ErrorCode;
125 }
126 
127 /// \brief Extract replacements from collected TranslationUnitReplacements and
128 /// TranslationUnitDiagnostics and group them per file. Identical replacements
129 /// from diagnostics are deduplicated.
130 ///
131 /// \param[in] TUs Collection of all found and deserialized
132 /// TranslationUnitReplacements.
133 /// \param[in] TUDs Collection of all found and deserialized
134 /// TranslationUnitDiagnostics.
135 /// \param[in] SM Used to deduplicate paths.
136 ///
137 /// \returns A map mapping FileEntry to a set of Replacement targeting that
138 /// file.
139 static llvm::DenseMap<const FileEntry *, std::vector<tooling::Replacement>>
141  const clang::SourceManager &SM) {
142  std::set<StringRef> Warned;
143  llvm::DenseMap<const FileEntry *, std::vector<tooling::Replacement>>
144  GroupedReplacements;
145 
146  // Deduplicate identical replacements in diagnostics.
147  // FIXME: Find an efficient way to deduplicate on diagnostics level.
148  llvm::DenseMap<const FileEntry *, std::set<tooling::Replacement>>
149  DiagReplacements;
150 
151  auto AddToGroup = [&](const tooling::Replacement &R, bool FromDiag) {
152  // Use the file manager to deduplicate paths. FileEntries are
153  // automatically canonicalized.
154  if (const FileEntry *Entry = SM.getFileManager().getFile(R.getFilePath())) {
155  if (FromDiag) {
156  auto &Replaces = DiagReplacements[Entry];
157  if (!Replaces.insert(R).second)
158  return;
159  }
160  GroupedReplacements[Entry].push_back(R);
161  } else if (Warned.insert(R.getFilePath()).second) {
162  errs() << "Described file '" << R.getFilePath()
163  << "' doesn't exist. Ignoring...\n";
164  }
165  };
166 
167  for (const auto &TU : TUs)
168  for (const tooling::Replacement &R : TU.Replacements)
169  AddToGroup(R, false);
170 
171  for (const auto &TU : TUDs)
172  for (const auto &D : TU.Diagnostics)
173  for (const auto &Fix : D.Fix)
174  for (const tooling::Replacement &R : Fix.second)
175  AddToGroup(R, true);
176 
177  // Sort replacements per file to keep consistent behavior when
178  // clang-apply-replacements run on differents machine.
179  for (auto &FileAndReplacements : GroupedReplacements) {
180  llvm::sort(FileAndReplacements.second.begin(),
181  FileAndReplacements.second.end());
182  }
183 
184  return GroupedReplacements;
185 }
186 
187 bool mergeAndDeduplicate(const TUReplacements &TUs, const TUDiagnostics &TUDs,
188  FileToChangesMap &FileChanges,
189  clang::SourceManager &SM) {
190  auto GroupedReplacements = groupReplacements(TUs, TUDs, SM);
191  bool ConflictDetected = false;
192 
193  // To report conflicting replacements on corresponding file, all replacements
194  // are stored into 1 big AtomicChange.
195  for (const auto &FileAndReplacements : GroupedReplacements) {
196  const FileEntry *Entry = FileAndReplacements.first;
197  const SourceLocation BeginLoc =
198  SM.getLocForStartOfFile(SM.getOrCreateFileID(Entry, SrcMgr::C_User));
199  tooling::AtomicChange FileChange(Entry->getName(), Entry->getName());
200  for (const auto &R : FileAndReplacements.second) {
201  llvm::Error Err =
202  FileChange.replace(SM, BeginLoc.getLocWithOffset(R.getOffset()),
203  R.getLength(), R.getReplacementText());
204  if (Err) {
205  // FIXME: This will report conflicts by pair using a file+offset format
206  // which is not so much human readable.
207  // A first improvement could be to translate offset to line+col. For
208  // this and without loosing error message some modifications arround
209  // `tooling::ReplacementError` are need (access to
210  // `getReplacementErrString`).
211  // A better strategy could be to add a pretty printer methods for
212  // conflict reporting. Methods that could be parameterized to report a
213  // conflict in different format, file+offset, file+line+col, or even
214  // more human readable using VCS conflict markers.
215  // For now, printing directly the error reported by `AtomicChange` is
216  // the easiest solution.
217  errs() << llvm::toString(std::move(Err)) << "\n";
218  ConflictDetected = true;
219  }
220  }
221  FileChanges.try_emplace(Entry,
222  std::vector<tooling::AtomicChange>{FileChange});
223  }
224 
225  return !ConflictDetected;
226 }
227 
228 llvm::Expected<std::string>
229 applyChanges(StringRef File, const std::vector<tooling::AtomicChange> &Changes,
230  const tooling::ApplyChangesSpec &Spec,
231  DiagnosticsEngine &Diagnostics) {
232  FileManager Files((FileSystemOptions()));
233  SourceManager SM(Diagnostics, Files);
234 
235  llvm::ErrorOr<std::unique_ptr<MemoryBuffer>> Buffer =
236  SM.getFileManager().getBufferForFile(File);
237  if (!Buffer)
238  return errorCodeToError(Buffer.getError());
239  return tooling::applyAtomicChanges(File, Buffer.get()->getBuffer(), Changes,
240  Spec);
241 }
242 
244  clang::DiagnosticsEngine &Diagnostics) {
245  bool Success = true;
246  for (const auto &Filename : Files) {
247  std::error_code Error = llvm::sys::fs::remove(Filename);
248  if (Error) {
249  Success = false;
250  // FIXME: Use Diagnostics for outputting errors.
251  errs() << "Error deleting file: " << Filename << "\n";
252  errs() << Error.message() << "\n";
253  errs() << "Please delete the file manually\n";
254  }
255  }
256  return Success;
257 }
258 
259 } // end namespace replace
260 } // end namespace clang
Some operations such as code completion produce a set of candidates.
bool deleteReplacementFiles(const TUReplacementFiles &Files, clang::DiagnosticsEngine &Diagnostics)
Delete the replacement files.
std::vector< clang::tooling::TranslationUnitReplacements > TUReplacements
Collection of TranslationUnitReplacements.
static llvm::StringRef toString(SpecialMemberFunctionsCheck::SpecialMemberFunctionKind K)
static void eatDiagnostics(const SMDiagnostic &, void *)
static llvm::DenseMap< const FileEntry *, std::vector< tooling::Replacement > > groupReplacements(const TUReplacements &TUs, const TUDiagnostics &TUDs, const clang::SourceManager &SM)
Extract replacements from collected TranslationUnitReplacements and TranslationUnitDiagnostics and gr...
static cl::opt< std::string > Directory(cl::Positional, cl::Required, cl::desc("<Search Root Directory>"))
std::string Filename
Filename as a string.
llvm::Expected< std::string > applyChanges(StringRef File, const std::vector< tooling::AtomicChange > &Changes, const tooling::ApplyChangesSpec &Spec, DiagnosticsEngine &Diagnostics)
Apply AtomicChange on File and rewrite it.
const Decl * D
Definition: XRefs.cpp:79
std::error_code collectReplacementsFromDirectory(const llvm::StringRef Directory, TUReplacements &TUs, TUReplacementFiles &TUFiles, clang::DiagnosticsEngine &Diagnostics)
Recursively descends through a directory structure rooted at Directory and attempts to deserialize *...
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
bool mergeAndDeduplicate(const TUReplacements &TUs, const TUDiagnostics &TUDs, FileToChangesMap &FileChanges, clang::SourceManager &SM)
Deduplicate, check for conflicts, and extract all Replacements stored in TUs.
This file provides the interface for deduplicating, detecting conflicts in, and applying collections ...
std::vector< clang::tooling::TranslationUnitDiagnostics > TUDiagnostics
Collection of TranslationUniDiagnostics.
std::vector< std::string > TUReplacementFiles
Collection of TranslationUnitReplacement files.
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))
llvm::DenseMap< const clang::FileEntry *, std::vector< tooling::AtomicChange > > FileToChangesMap
Map mapping file name to a set of AtomicChange targeting that file.