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