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