FixItRewriter.cpp 6.3 KB

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