FixItRewriter.cpp 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. //===--- FixItRewriter.cpp - Fix-It Rewriter Diagnostic Client --*- C++ -*-===//
  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. // This is a diagnostic client adaptor that performs rewrites as
  11. // suggested by code modification hints attached to diagnostics. It
  12. // then forwards any diagnostics to the adapted diagnostic client.
  13. //
  14. //===----------------------------------------------------------------------===//
  15. #include "clang/Rewrite/Frontend/FixItRewriter.h"
  16. #include "clang/Basic/FileManager.h"
  17. #include "clang/Basic/SourceLocation.h"
  18. #include "clang/Basic/SourceManager.h"
  19. #include "clang/Edit/Commit.h"
  20. #include "clang/Edit/EditsReceiver.h"
  21. #include "clang/Frontend/FrontendDiagnostic.h"
  22. #include "llvm/Support/Path.h"
  23. #include "llvm/Support/raw_ostream.h"
  24. #include <cstdio>
  25. #include <memory>
  26. using namespace clang;
  27. FixItRewriter::FixItRewriter(DiagnosticsEngine &Diags, SourceManager &SourceMgr,
  28. const LangOptions &LangOpts,
  29. FixItOptions *FixItOpts)
  30. : Diags(Diags),
  31. Editor(SourceMgr, LangOpts),
  32. Rewrite(SourceMgr, LangOpts),
  33. FixItOpts(FixItOpts),
  34. NumFailures(0),
  35. PrevDiagSilenced(false) {
  36. Owner = Diags.takeClient();
  37. Client = Diags.getClient();
  38. Diags.setClient(this, false);
  39. }
  40. FixItRewriter::~FixItRewriter() {
  41. Diags.setClient(Client, Owner.release() != nullptr);
  42. }
  43. bool FixItRewriter::WriteFixedFile(FileID ID, raw_ostream &OS) {
  44. const RewriteBuffer *RewriteBuf = Rewrite.getRewriteBufferFor(ID);
  45. if (!RewriteBuf) return true;
  46. RewriteBuf->write(OS);
  47. OS.flush();
  48. return false;
  49. }
  50. namespace {
  51. class RewritesReceiver : public edit::EditsReceiver {
  52. Rewriter &Rewrite;
  53. public:
  54. RewritesReceiver(Rewriter &Rewrite) : Rewrite(Rewrite) { }
  55. void insert(SourceLocation loc, StringRef text) override {
  56. Rewrite.InsertText(loc, text);
  57. }
  58. void replace(CharSourceRange range, StringRef text) override {
  59. Rewrite.ReplaceText(range.getBegin(), Rewrite.getRangeSize(range), text);
  60. }
  61. };
  62. }
  63. bool FixItRewriter::WriteFixedFiles(
  64. std::vector<std::pair<std::string, std::string> > *RewrittenFiles) {
  65. if (NumFailures > 0 && !FixItOpts->FixWhatYouCan) {
  66. Diag(FullSourceLoc(), diag::warn_fixit_no_changes);
  67. return true;
  68. }
  69. RewritesReceiver Rec(Rewrite);
  70. Editor.applyRewrites(Rec);
  71. if (FixItOpts->InPlace) {
  72. // Overwriting open files on Windows is tricky, but the rewriter can do it
  73. // for us.
  74. Rewrite.overwriteChangedFiles();
  75. return false;
  76. }
  77. for (iterator I = buffer_begin(), E = buffer_end(); I != E; ++I) {
  78. const FileEntry *Entry = Rewrite.getSourceMgr().getFileEntryForID(I->first);
  79. int fd;
  80. std::string Filename = FixItOpts->RewriteFilename(Entry->getName(), fd);
  81. std::error_code EC;
  82. std::unique_ptr<llvm::raw_fd_ostream> OS;
  83. if (fd != -1) {
  84. OS.reset(new llvm::raw_fd_ostream(fd, /*shouldClose=*/true));
  85. } else {
  86. OS.reset(new llvm::raw_fd_ostream(Filename, EC, llvm::sys::fs::F_None));
  87. }
  88. if (EC) {
  89. Diags.Report(clang::diag::err_fe_unable_to_open_output) << Filename
  90. << EC.message();
  91. continue;
  92. }
  93. RewriteBuffer &RewriteBuf = I->second;
  94. RewriteBuf.write(*OS);
  95. OS->flush();
  96. if (RewrittenFiles)
  97. RewrittenFiles->push_back(std::make_pair(Entry->getName(), Filename));
  98. }
  99. return false;
  100. }
  101. bool FixItRewriter::IncludeInDiagnosticCounts() const {
  102. return Client ? Client->IncludeInDiagnosticCounts() : true;
  103. }
  104. void FixItRewriter::HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
  105. const Diagnostic &Info) {
  106. // Default implementation (Warnings/errors count).
  107. DiagnosticConsumer::HandleDiagnostic(DiagLevel, Info);
  108. if (!FixItOpts->Silent ||
  109. DiagLevel >= DiagnosticsEngine::Error ||
  110. (DiagLevel == DiagnosticsEngine::Note && !PrevDiagSilenced) ||
  111. (DiagLevel > DiagnosticsEngine::Note && Info.getNumFixItHints())) {
  112. Client->HandleDiagnostic(DiagLevel, Info);
  113. PrevDiagSilenced = false;
  114. } else {
  115. PrevDiagSilenced = true;
  116. }
  117. // Skip over any diagnostics that are ignored or notes.
  118. if (DiagLevel <= DiagnosticsEngine::Note)
  119. return;
  120. // Skip over errors if we are only fixing warnings.
  121. if (DiagLevel >= DiagnosticsEngine::Error && FixItOpts->FixOnlyWarnings) {
  122. ++NumFailures;
  123. return;
  124. }
  125. // Make sure that we can perform all of the modifications we
  126. // in this diagnostic.
  127. edit::Commit commit(Editor);
  128. for (unsigned Idx = 0, Last = Info.getNumFixItHints();
  129. Idx < Last; ++Idx) {
  130. const FixItHint &Hint = Info.getFixItHint(Idx);
  131. if (Hint.CodeToInsert.empty()) {
  132. if (Hint.InsertFromRange.isValid())
  133. commit.insertFromRange(Hint.RemoveRange.getBegin(),
  134. Hint.InsertFromRange, /*afterToken=*/false,
  135. Hint.BeforePreviousInsertions);
  136. else
  137. commit.remove(Hint.RemoveRange);
  138. } else {
  139. if (Hint.RemoveRange.isTokenRange() ||
  140. Hint.RemoveRange.getBegin() != Hint.RemoveRange.getEnd())
  141. commit.replace(Hint.RemoveRange, Hint.CodeToInsert);
  142. else
  143. commit.insert(Hint.RemoveRange.getBegin(), Hint.CodeToInsert,
  144. /*afterToken=*/false, Hint.BeforePreviousInsertions);
  145. }
  146. }
  147. bool CanRewrite = Info.getNumFixItHints() > 0 && commit.isCommitable();
  148. if (!CanRewrite) {
  149. if (Info.getNumFixItHints() > 0)
  150. Diag(Info.getLocation(), diag::note_fixit_in_macro);
  151. // If this was an error, refuse to perform any rewriting.
  152. if (DiagLevel >= DiagnosticsEngine::Error) {
  153. if (++NumFailures == 1)
  154. Diag(Info.getLocation(), diag::note_fixit_unfixed_error);
  155. }
  156. return;
  157. }
  158. if (!Editor.commit(commit)) {
  159. ++NumFailures;
  160. Diag(Info.getLocation(), diag::note_fixit_failed);
  161. return;
  162. }
  163. Diag(Info.getLocation(), diag::note_fixit_applied);
  164. }
  165. /// \brief Emit a diagnostic via the adapted diagnostic client.
  166. void FixItRewriter::Diag(SourceLocation Loc, unsigned DiagID) {
  167. // When producing this diagnostic, we temporarily bypass ourselves,
  168. // clear out any current diagnostic, and let the downstream client
  169. // format the diagnostic.
  170. Diags.setClient(Client, false);
  171. Diags.Clear();
  172. Diags.Report(Loc, DiagID);
  173. Diags.setClient(this, false);
  174. }
  175. FixItOptions::~FixItOptions() {}