1 //===--- FixItRewriter.cpp - Fix-It Rewriter Diagnostic Client --*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
14 //===----------------------------------------------------------------------===//
16 #include "clang/Rewrite/Frontend/FixItRewriter.h"
17 #include "clang/Basic/FileManager.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 "llvm/Support/Path.h"
24 #include "llvm/Support/raw_ostream.h"
28 using namespace clang;
30 FixItRewriter::FixItRewriter(DiagnosticsEngine &Diags, SourceManager &SourceMgr,
31 const LangOptions &LangOpts,
32 FixItOptions *FixItOpts)
34 Editor(SourceMgr, LangOpts),
35 Rewrite(SourceMgr, LangOpts),
38 PrevDiagSilenced(false) {
39 Owner = Diags.takeClient();
40 Client = Diags.getClient();
41 Diags.setClient(this, false);
44 FixItRewriter::~FixItRewriter() {
45 Diags.setClient(Client, Owner.release() != nullptr);
48 bool FixItRewriter::WriteFixedFile(FileID ID, raw_ostream &OS) {
49 const RewriteBuffer *RewriteBuf = Rewrite.getRewriteBufferFor(ID);
50 if (!RewriteBuf) return true;
51 RewriteBuf->write(OS);
58 class RewritesReceiver : public edit::EditsReceiver {
62 RewritesReceiver(Rewriter &Rewrite) : Rewrite(Rewrite) { }
64 void insert(SourceLocation loc, StringRef text) override {
65 Rewrite.InsertText(loc, text);
67 void replace(CharSourceRange range, StringRef text) override {
68 Rewrite.ReplaceText(range.getBegin(), Rewrite.getRangeSize(range), text);
74 bool FixItRewriter::WriteFixedFiles(
75 std::vector<std::pair<std::string, std::string> > *RewrittenFiles) {
76 if (NumFailures > 0 && !FixItOpts->FixWhatYouCan) {
77 Diag(FullSourceLoc(), diag::warn_fixit_no_changes);
81 RewritesReceiver Rec(Rewrite);
82 Editor.applyRewrites(Rec);
84 if (FixItOpts->InPlace) {
85 // Overwriting open files on Windows is tricky, but the rewriter can do it
87 Rewrite.overwriteChangedFiles();
91 for (iterator I = buffer_begin(), E = buffer_end(); I != E; ++I) {
92 const FileEntry *Entry = Rewrite.getSourceMgr().getFileEntryForID(I->first);
94 std::string Filename = FixItOpts->RewriteFilename(Entry->getName(), fd);
96 std::unique_ptr<llvm::raw_fd_ostream> OS;
98 OS.reset(new llvm::raw_fd_ostream(fd, /*shouldClose=*/true));
100 OS.reset(new llvm::raw_fd_ostream(Filename, EC, llvm::sys::fs::F_None));
103 Diags.Report(clang::diag::err_fe_unable_to_open_output) << Filename
107 RewriteBuffer &RewriteBuf = I->second;
108 RewriteBuf.write(*OS);
112 RewrittenFiles->push_back(std::make_pair(Entry->getName(), Filename));
118 bool FixItRewriter::IncludeInDiagnosticCounts() const {
119 return Client ? Client->IncludeInDiagnosticCounts() : true;
122 void FixItRewriter::HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
123 const Diagnostic &Info) {
124 // Default implementation (Warnings/errors count).
125 DiagnosticConsumer::HandleDiagnostic(DiagLevel, Info);
127 if (!FixItOpts->Silent ||
128 DiagLevel >= DiagnosticsEngine::Error ||
129 (DiagLevel == DiagnosticsEngine::Note && !PrevDiagSilenced) ||
130 (DiagLevel > DiagnosticsEngine::Note && Info.getNumFixItHints())) {
131 Client->HandleDiagnostic(DiagLevel, Info);
132 PrevDiagSilenced = false;
134 PrevDiagSilenced = true;
137 // Skip over any diagnostics that are ignored or notes.
138 if (DiagLevel <= DiagnosticsEngine::Note)
140 // Skip over errors if we are only fixing warnings.
141 if (DiagLevel >= DiagnosticsEngine::Error && FixItOpts->FixOnlyWarnings) {
146 // Make sure that we can perform all of the modifications we
147 // in this diagnostic.
148 edit::Commit commit(Editor);
149 for (unsigned Idx = 0, Last = Info.getNumFixItHints();
151 const FixItHint &Hint = Info.getFixItHint(Idx);
153 if (Hint.CodeToInsert.empty()) {
154 if (Hint.InsertFromRange.isValid())
155 commit.insertFromRange(Hint.RemoveRange.getBegin(),
156 Hint.InsertFromRange, /*afterToken=*/false,
157 Hint.BeforePreviousInsertions);
159 commit.remove(Hint.RemoveRange);
161 if (Hint.RemoveRange.isTokenRange() ||
162 Hint.RemoveRange.getBegin() != Hint.RemoveRange.getEnd())
163 commit.replace(Hint.RemoveRange, Hint.CodeToInsert);
165 commit.insert(Hint.RemoveRange.getBegin(), Hint.CodeToInsert,
166 /*afterToken=*/false, Hint.BeforePreviousInsertions);
169 bool CanRewrite = Info.getNumFixItHints() > 0 && commit.isCommitable();
172 if (Info.getNumFixItHints() > 0)
173 Diag(Info.getLocation(), diag::note_fixit_in_macro);
175 // If this was an error, refuse to perform any rewriting.
176 if (DiagLevel >= DiagnosticsEngine::Error) {
177 if (++NumFailures == 1)
178 Diag(Info.getLocation(), diag::note_fixit_unfixed_error);
183 if (!Editor.commit(commit)) {
185 Diag(Info.getLocation(), diag::note_fixit_failed);
189 Diag(Info.getLocation(), diag::note_fixit_applied);
192 /// \brief Emit a diagnostic via the adapted diagnostic client.
193 void FixItRewriter::Diag(SourceLocation Loc, unsigned DiagID) {
194 // When producing this diagnostic, we temporarily bypass ourselves,
195 // clear out any current diagnostic, and let the downstream client
196 // format the diagnostic.
197 Diags.setClient(Client, false);
199 Diags.Report(Loc, DiagID);
200 Diags.setClient(this, false);
203 FixItOptions::~FixItOptions() {}