| 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 | |
| 15 | #include "clang/Rewrite/Frontend/FixItRewriter.h" |
| 16 | #include "clang/Basic/Diagnostic.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/Rewriter.h" |
| 24 | #include "llvm/ADT/RewriteBuffer.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 | |
| 34 | using namespace clang; |
| 35 | using llvm::RewriteBuffer; |
| 36 | |
| 37 | FixItRewriter::FixItRewriter(DiagnosticsEngine &Diags, SourceManager &SourceMgr, |
| 38 | const LangOptions &LangOpts, |
| 39 | FixItOptions *FixItOpts) |
| 40 | : Diags(Diags), Editor(SourceMgr, LangOpts), Rewrite(SourceMgr, LangOpts), |
| 41 | FixItOpts(FixItOpts) { |
| 42 | Owner = Diags.takeClient(); |
| 43 | Client = Diags.getClient(); |
| 44 | Diags.setClient(client: this, ShouldOwnClient: false); |
| 45 | } |
| 46 | |
| 47 | FixItRewriter::~FixItRewriter() { |
| 48 | Diags.setClient(client: Client, ShouldOwnClient: Owner.release() != nullptr); |
| 49 | } |
| 50 | |
| 51 | bool FixItRewriter::WriteFixedFile(FileID ID, raw_ostream &OS) { |
| 52 | const RewriteBuffer *RewriteBuf = Rewrite.getRewriteBufferFor(FID: ID); |
| 53 | if (!RewriteBuf) return true; |
| 54 | RewriteBuf->write(Stream&: OS); |
| 55 | OS.flush(); |
| 56 | return false; |
| 57 | } |
| 58 | |
| 59 | namespace { |
| 60 | |
| 61 | class RewritesReceiver : public edit::EditsReceiver { |
| 62 | Rewriter &Rewrite; |
| 63 | |
| 64 | public: |
| 65 | RewritesReceiver(Rewriter &Rewrite) : Rewrite(Rewrite) {} |
| 66 | |
| 67 | void insert(SourceLocation loc, StringRef text) override { |
| 68 | Rewrite.InsertText(Loc: loc, Str: text); |
| 69 | } |
| 70 | |
| 71 | void replace(CharSourceRange range, StringRef text) override { |
| 72 | Rewrite.ReplaceText(Start: range.getBegin(), OrigLength: Rewrite.getRangeSize(Range: range), NewStr: text); |
| 73 | } |
| 74 | }; |
| 75 | |
| 76 | } // namespace |
| 77 | |
| 78 | bool FixItRewriter::WriteFixedFiles( |
| 79 | std::vector<std::pair<std::string, std::string>> *RewrittenFiles) { |
| 80 | if (NumFailures > 0 && !FixItOpts->FixWhatYouCan) { |
| 81 | Diag(Loc: FullSourceLoc(), DiagID: diag::warn_fixit_no_changes); |
| 82 | return true; |
| 83 | } |
| 84 | |
| 85 | RewritesReceiver Rec(Rewrite); |
| 86 | Editor.applyRewrites(receiver&: Rec); |
| 87 | |
| 88 | if (FixItOpts->InPlace) { |
| 89 | // Overwriting open files on Windows is tricky, but the rewriter can do it |
| 90 | // for us. |
| 91 | Rewrite.overwriteChangedFiles(); |
| 92 | return false; |
| 93 | } |
| 94 | |
| 95 | for (iterator I = buffer_begin(), E = buffer_end(); I != E; ++I) { |
| 96 | OptionalFileEntryRef Entry = |
| 97 | Rewrite.getSourceMgr().getFileEntryRefForID(FID: I->first); |
| 98 | int fd; |
| 99 | std::string Filename = |
| 100 | FixItOpts->RewriteFilename(Filename: std::string(Entry->getName()), fd); |
| 101 | std::error_code EC; |
| 102 | std::unique_ptr<llvm::raw_fd_ostream> OS; |
| 103 | if (fd != -1) { |
| 104 | OS.reset(p: new llvm::raw_fd_ostream(fd, /*shouldClose=*/true)); |
| 105 | } else { |
| 106 | OS.reset(p: new llvm::raw_fd_ostream(Filename, EC, llvm::sys::fs::OF_None)); |
| 107 | } |
| 108 | if (EC) { |
| 109 | Diags.Report(DiagID: clang::diag::err_fe_unable_to_open_output) << Filename |
| 110 | << EC.message(); |
| 111 | continue; |
| 112 | } |
| 113 | RewriteBuffer &RewriteBuf = I->second; |
| 114 | RewriteBuf.write(Stream&: *OS); |
| 115 | OS->flush(); |
| 116 | |
| 117 | if (RewrittenFiles) |
| 118 | RewrittenFiles->push_back( |
| 119 | x: std::make_pair(x: std::string(Entry->getName()), y&: Filename)); |
| 120 | } |
| 121 | |
| 122 | return false; |
| 123 | } |
| 124 | |
| 125 | bool FixItRewriter::IncludeInDiagnosticCounts() const { |
| 126 | return Client ? Client->IncludeInDiagnosticCounts() : true; |
| 127 | } |
| 128 | |
| 129 | void FixItRewriter::HandleDiagnostic(DiagnosticsEngine::Level DiagLevel, |
| 130 | const Diagnostic &Info) { |
| 131 | // Default implementation (Warnings/errors count). |
| 132 | DiagnosticConsumer::HandleDiagnostic(DiagLevel, Info); |
| 133 | |
| 134 | if (!FixItOpts->Silent || |
| 135 | DiagLevel >= DiagnosticsEngine::Error || |
| 136 | (DiagLevel == DiagnosticsEngine::Note && !PrevDiagSilenced) || |
| 137 | (DiagLevel > DiagnosticsEngine::Note && Info.getNumFixItHints())) { |
| 138 | Client->HandleDiagnostic(DiagLevel, Info); |
| 139 | PrevDiagSilenced = false; |
| 140 | } else { |
| 141 | PrevDiagSilenced = true; |
| 142 | } |
| 143 | |
| 144 | // Skip over any diagnostics that are ignored or notes. |
| 145 | if (DiagLevel <= DiagnosticsEngine::Note) |
| 146 | return; |
| 147 | // Skip over errors if we are only fixing warnings. |
| 148 | if (DiagLevel >= DiagnosticsEngine::Error && FixItOpts->FixOnlyWarnings) { |
| 149 | ++NumFailures; |
| 150 | return; |
| 151 | } |
| 152 | |
| 153 | // Make sure that we can perform all of the modifications we |
| 154 | // in this diagnostic. |
| 155 | edit::Commit commit(Editor); |
| 156 | for (unsigned Idx = 0, Last = Info.getNumFixItHints(); |
| 157 | Idx < Last; ++Idx) { |
| 158 | const FixItHint &Hint = Info.getFixItHint(Idx); |
| 159 | |
| 160 | if (Hint.CodeToInsert.empty()) { |
| 161 | if (Hint.InsertFromRange.isValid()) |
| 162 | commit.insertFromRange(loc: Hint.RemoveRange.getBegin(), |
| 163 | range: Hint.InsertFromRange, /*afterToken=*/false, |
| 164 | beforePreviousInsertions: Hint.BeforePreviousInsertions); |
| 165 | else |
| 166 | commit.remove(range: Hint.RemoveRange); |
| 167 | } else { |
| 168 | if (Hint.RemoveRange.isTokenRange() || |
| 169 | Hint.RemoveRange.getBegin() != Hint.RemoveRange.getEnd()) |
| 170 | commit.replace(range: Hint.RemoveRange, text: Hint.CodeToInsert); |
| 171 | else |
| 172 | commit.insert(loc: Hint.RemoveRange.getBegin(), text: Hint.CodeToInsert, |
| 173 | /*afterToken=*/false, beforePreviousInsertions: Hint.BeforePreviousInsertions); |
| 174 | } |
| 175 | } |
| 176 | bool CanRewrite = Info.getNumFixItHints() > 0 && commit.isCommitable(); |
| 177 | |
| 178 | if (!CanRewrite) { |
| 179 | if (Info.getNumFixItHints() > 0) |
| 180 | Diag(Loc: Info.getLocation(), DiagID: diag::note_fixit_in_macro); |
| 181 | |
| 182 | // If this was an error, refuse to perform any rewriting. |
| 183 | if (DiagLevel >= DiagnosticsEngine::Error) { |
| 184 | if (++NumFailures == 1) |
| 185 | Diag(Loc: Info.getLocation(), DiagID: diag::note_fixit_unfixed_error); |
| 186 | } |
| 187 | return; |
| 188 | } |
| 189 | |
| 190 | if (!Editor.commit(commit)) { |
| 191 | ++NumFailures; |
| 192 | Diag(Loc: Info.getLocation(), DiagID: diag::note_fixit_failed); |
| 193 | return; |
| 194 | } |
| 195 | |
| 196 | Diag(Loc: Info.getLocation(), DiagID: diag::note_fixit_applied); |
| 197 | } |
| 198 | |
| 199 | /// Emit a diagnostic via the adapted diagnostic client. |
| 200 | void FixItRewriter::Diag(SourceLocation Loc, unsigned DiagID) { |
| 201 | // When producing this diagnostic, we temporarily bypass ourselves, |
| 202 | // and let the downstream client format the diagnostic. |
| 203 | Diags.setClient(client: Client, ShouldOwnClient: false); |
| 204 | Diags.Report(Loc, DiagID); |
| 205 | Diags.setClient(client: this, ShouldOwnClient: false); |
| 206 | } |
| 207 | |
| 208 | FixItOptions::~FixItOptions() = default; |
| 209 | |