FixItRewriter.cpp 6.7 KB

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