FixItRewriter.cpp 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  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 = FixItOpts->RewriteFilename(Entry->getName(), fd);
  84. std::error_code EC;
  85. std::unique_ptr<llvm::raw_fd_ostream> OS;
  86. if (fd != -1) {
  87. OS.reset(new llvm::raw_fd_ostream(fd, /*shouldClose=*/true));
  88. } else {
  89. OS.reset(new llvm::raw_fd_ostream(Filename, EC, llvm::sys::fs::OF_None));
  90. }
  91. if (EC) {
  92. Diags.Report(clang::diag::err_fe_unable_to_open_output) << Filename
  93. << EC.message();
  94. continue;
  95. }
  96. RewriteBuffer &RewriteBuf = I->second;
  97. RewriteBuf.write(*OS);
  98. OS->flush();
  99. if (RewrittenFiles)
  100. RewrittenFiles->push_back(std::make_pair(Entry->getName(), Filename));
  101. }
  102. return false;
  103. }
  104. bool FixItRewriter::IncludeInDiagnosticCounts() const {
  105. return Client ? Client->IncludeInDiagnosticCounts() : true;
  106. }
  107. void FixItRewriter::HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
  108. const Diagnostic &Info) {
  109. // Default implementation (Warnings/errors count).
  110. DiagnosticConsumer::HandleDiagnostic(DiagLevel, Info);
  111. if (!FixItOpts->Silent ||
  112. DiagLevel >= DiagnosticsEngine::Error ||
  113. (DiagLevel == DiagnosticsEngine::Note && !PrevDiagSilenced) ||
  114. (DiagLevel > DiagnosticsEngine::Note && Info.getNumFixItHints())) {
  115. Client->HandleDiagnostic(DiagLevel, Info);
  116. PrevDiagSilenced = false;
  117. } else {
  118. PrevDiagSilenced = true;
  119. }
  120. // Skip over any diagnostics that are ignored or notes.
  121. if (DiagLevel <= DiagnosticsEngine::Note)
  122. return;
  123. // Skip over errors if we are only fixing warnings.
  124. if (DiagLevel >= DiagnosticsEngine::Error && FixItOpts->FixOnlyWarnings) {
  125. ++NumFailures;
  126. return;
  127. }
  128. // Make sure that we can perform all of the modifications we
  129. // in this diagnostic.
  130. edit::Commit commit(Editor);
  131. for (unsigned Idx = 0, Last = Info.getNumFixItHints();
  132. Idx < Last; ++Idx) {
  133. const FixItHint &Hint = Info.getFixItHint(Idx);
  134. if (Hint.CodeToInsert.empty()) {
  135. if (Hint.InsertFromRange.isValid())
  136. commit.insertFromRange(Hint.RemoveRange.getBegin(),
  137. Hint.InsertFromRange, /*afterToken=*/false,
  138. Hint.BeforePreviousInsertions);
  139. else
  140. commit.remove(Hint.RemoveRange);
  141. } else {
  142. if (Hint.RemoveRange.isTokenRange() ||
  143. Hint.RemoveRange.getBegin() != Hint.RemoveRange.getEnd())
  144. commit.replace(Hint.RemoveRange, Hint.CodeToInsert);
  145. else
  146. commit.insert(Hint.RemoveRange.getBegin(), Hint.CodeToInsert,
  147. /*afterToken=*/false, Hint.BeforePreviousInsertions);
  148. }
  149. }
  150. bool CanRewrite = Info.getNumFixItHints() > 0 && commit.isCommitable();
  151. if (!CanRewrite) {
  152. if (Info.getNumFixItHints() > 0)
  153. Diag(Info.getLocation(), diag::note_fixit_in_macro);
  154. // If this was an error, refuse to perform any rewriting.
  155. if (DiagLevel >= DiagnosticsEngine::Error) {
  156. if (++NumFailures == 1)
  157. Diag(Info.getLocation(), diag::note_fixit_unfixed_error);
  158. }
  159. return;
  160. }
  161. if (!Editor.commit(commit)) {
  162. ++NumFailures;
  163. Diag(Info.getLocation(), diag::note_fixit_failed);
  164. return;
  165. }
  166. Diag(Info.getLocation(), diag::note_fixit_applied);
  167. }
  168. /// Emit a diagnostic via the adapted diagnostic client.
  169. void FixItRewriter::Diag(SourceLocation Loc, unsigned DiagID) {
  170. // When producing this diagnostic, we temporarily bypass ourselves,
  171. // clear out any current diagnostic, and let the downstream client
  172. // format the diagnostic.
  173. Diags.setClient(Client, false);
  174. Diags.Clear();
  175. Diags.Report(Loc, DiagID);
  176. Diags.setClient(this, false);
  177. }
  178. FixItOptions::~FixItOptions() = default;