clang-tools  7.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.
129 ///
130 /// \param[in] TUs Collection of all found and deserialized
131 /// TranslationUnitReplacements.
132 /// \param[in] TUDs Collection of all found and deserialized
133 /// TranslationUnitDiagnostics.
134 /// \param[in] SM Used to deduplicate paths.
135 ///
136 /// \returns A map mapping FileEntry to a set of Replacement targeting that
137 /// file.
138 static llvm::DenseMap<const FileEntry *, std::vector<tooling::Replacement>>
140  const clang::SourceManager &SM) {
141  std::set<StringRef> Warned;
142  llvm::DenseMap<const FileEntry *, std::vector<tooling::Replacement>>
143  GroupedReplacements;
144 
145  auto AddToGroup = [&](const tooling::Replacement &R) {
146  // Use the file manager to deduplicate paths. FileEntries are
147  // automatically canonicalized.
148  if (const FileEntry *Entry = SM.getFileManager().getFile(R.getFilePath())) {
149  GroupedReplacements[Entry].push_back(R);
150  } else if (Warned.insert(R.getFilePath()).second) {
151  errs() << "Described file '" << R.getFilePath()
152  << "' doesn't exist. Ignoring...\n";
153  }
154  };
155 
156  for (const auto &TU : TUs)
157  for (const tooling::Replacement &R : TU.Replacements)
158  AddToGroup(R);
159 
160  for (const auto &TU : TUDs)
161  for (const auto &D : TU.Diagnostics)
162  for (const auto &Fix : D.Fix)
163  for (const tooling::Replacement &R : Fix.second)
164  AddToGroup(R);
165 
166  // Sort replacements per file to keep consistent behavior when
167  // clang-apply-replacements run on differents machine.
168  for (auto &FileAndReplacements : GroupedReplacements) {
169  llvm::sort(FileAndReplacements.second.begin(),
170  FileAndReplacements.second.end());
171  }
172 
173  return GroupedReplacements;
174 }
175 
176 bool mergeAndDeduplicate(const TUReplacements &TUs, const TUDiagnostics &TUDs,
177  FileToChangesMap &FileChanges,
178  clang::SourceManager &SM) {
179  auto GroupedReplacements = groupReplacements(TUs, TUDs, SM);
180  bool ConflictDetected = false;
181 
182  // To report conflicting replacements on corresponding file, all replacements
183  // are stored into 1 big AtomicChange.
184  for (const auto &FileAndReplacements : GroupedReplacements) {
185  const FileEntry *Entry = FileAndReplacements.first;
186  const SourceLocation BeginLoc =
187  SM.getLocForStartOfFile(SM.getOrCreateFileID(Entry, SrcMgr::C_User));
188  tooling::AtomicChange FileChange(Entry->getName(), Entry->getName());
189  for (const auto &R : FileAndReplacements.second) {
190  llvm::Error Err =
191  FileChange.replace(SM, BeginLoc.getLocWithOffset(R.getOffset()),
192  R.getLength(), R.getReplacementText());
193  if (Err) {
194  // FIXME: This will report conflicts by pair using a file+offset format
195  // which is not so much human readable.
196  // A first improvement could be to translate offset to line+col. For
197  // this and without loosing error message some modifications arround
198  // `tooling::ReplacementError` are need (access to
199  // `getReplacementErrString`).
200  // A better strategy could be to add a pretty printer methods for
201  // conflict reporting. Methods that could be parameterized to report a
202  // conflict in different format, file+offset, file+line+col, or even
203  // more human readable using VCS conflict markers.
204  // For now, printing directly the error reported by `AtomicChange` is
205  // the easiest solution.
206  errs() << llvm::toString(std::move(Err)) << "\n";
207  ConflictDetected = true;
208  }
209  }
210  FileChanges.try_emplace(Entry,
211  std::vector<tooling::AtomicChange>{FileChange});
212  }
213 
214  return !ConflictDetected;
215 }
216 
217 llvm::Expected<std::string>
218 applyChanges(StringRef File, const std::vector<tooling::AtomicChange> &Changes,
219  const tooling::ApplyChangesSpec &Spec,
220  DiagnosticsEngine &Diagnostics) {
221  FileManager Files((FileSystemOptions()));
222  SourceManager SM(Diagnostics, Files);
223 
224  llvm::ErrorOr<std::unique_ptr<MemoryBuffer>> Buffer =
225  SM.getFileManager().getBufferForFile(File);
226  if (!Buffer)
227  return errorCodeToError(Buffer.getError());
228  return tooling::applyAtomicChanges(File, Buffer.get()->getBuffer(), Changes,
229  Spec);
230 }
231 
233  clang::DiagnosticsEngine &Diagnostics) {
234  bool Success = true;
235  for (const auto &Filename : Files) {
236  std::error_code Error = llvm::sys::fs::remove(Filename);
237  if (Error) {
238  Success = false;
239  // FIXME: Use Diagnostics for outputting errors.
240  errs() << "Error deleting file: " << Filename << "\n";
241  errs() << Error.message() << "\n";
242  errs() << "Please delete the file manually\n";
243  }
244  }
245  return Success;
246 }
247 
248 } // end namespace replace
249 } // 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.
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.