clang 24.0.0git
FixItRewriter.cpp
Go to the documentation of this file.
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
18#include "clang/Basic/LLVM.h"
21#include "clang/Edit/Commit.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 <memory>
29#include <string>
30#include <system_error>
31#include <utility>
32
33using namespace clang;
34using llvm::RewriteBuffer;
35
37 const LangOptions &LangOpts,
38 FixItOptions *FixItOpts)
39 : Diags(Diags), Editor(SourceMgr, LangOpts), Rewrite(SourceMgr, LangOpts),
40 FixItOpts(FixItOpts) {
41 Owner = Diags.takeClient();
42 Client = Diags.getClient();
43 Diags.setClient(this, false);
44}
45
47 Diags.setClient(Client, Owner.release() != nullptr);
48}
49
50bool FixItRewriter::WriteFixedFile(FileID ID, raw_ostream &OS) {
51 const RewriteBuffer *RewriteBuf = Rewrite.getRewriteBufferFor(ID);
52 if (!RewriteBuf) return true;
53 RewriteBuf->write(OS);
54 OS.flush();
55 return false;
56}
57
58namespace {
59
60class RewritesReceiver : public edit::EditsReceiver {
62
63public:
64 RewritesReceiver(Rewriter &Rewrite) : Rewrite(Rewrite) {}
65
66 void insert(SourceLocation loc, StringRef text) override {
67 Rewrite.InsertText(loc, text);
68 }
69
70 void replace(CharSourceRange range, StringRef text) override {
71 Rewrite.ReplaceText(range.getBegin(), Rewrite.getRangeSize(range), text);
72 }
73};
74
75} // namespace
76
78 std::vector<std::pair<std::string, std::string>> *RewrittenFiles) {
79 if (NumFailures > 0 && !FixItOpts->FixWhatYouCan) {
80 Diag(FullSourceLoc(), diag::warn_fixit_no_changes);
81 return true;
82 }
83
84 RewritesReceiver Rec(Rewrite);
85 Editor.applyRewrites(Rec);
86
87 if (FixItOpts->InPlace) {
88 // Overwriting open files on Windows is tricky, but the rewriter can do it
89 // for us.
90 Rewrite.overwriteChangedFiles();
91 return false;
92 }
93
94 for (iterator I = buffer_begin(), E = buffer_end(); I != E; ++I) {
96 Rewrite.getSourceMgr().getFileEntryRefForID(I->first);
97 int fd;
98 std::string Filename =
99 FixItOpts->RewriteFilename(std::string(Entry->getName()), fd);
100 std::error_code EC;
101 std::unique_ptr<llvm::raw_fd_ostream> OS;
102 if (fd != -1) {
103 OS.reset(new llvm::raw_fd_ostream(fd, /*shouldClose=*/true));
104 } else {
105 OS.reset(new llvm::raw_fd_ostream(Filename, EC, llvm::sys::fs::OF_None));
106 }
107 if (EC) {
108 Diags.Report(clang::diag::err_fe_unable_to_open_output) << Filename
109 << EC.message();
110 continue;
111 }
112 RewriteBuffer &RewriteBuf = I->second;
113 RewriteBuf.write(*OS);
114 OS->flush();
115
116 if (RewrittenFiles)
117 RewrittenFiles->push_back(
118 std::make_pair(std::string(Entry->getName()), Filename));
119 }
120
121 return false;
122}
123
125 return Client ? Client->IncludeInDiagnosticCounts() : true;
126}
127
129 const Diagnostic &Info) {
130 // Default implementation (Warnings/errors count).
132
133 if (!FixItOpts->Silent ||
134 DiagLevel >= DiagnosticsEngine::Error ||
135 (DiagLevel == DiagnosticsEngine::Note && !PrevDiagSilenced) ||
136 (DiagLevel > DiagnosticsEngine::Note && Info.getNumFixItHints())) {
137 Client->HandleDiagnostic(DiagLevel, Info);
138 PrevDiagSilenced = false;
139 } else {
140 PrevDiagSilenced = true;
141 }
142
143 // Skip over any diagnostics that are ignored or notes.
144 if (DiagLevel <= DiagnosticsEngine::Note)
145 return;
146 // Skip over errors if we are only fixing warnings.
147 if (DiagLevel >= DiagnosticsEngine::Error && FixItOpts->FixOnlyWarnings) {
148 ++NumFailures;
149 return;
150 }
151
152 // Make sure that we can perform all of the modifications we
153 // in this diagnostic.
154 edit::Commit commit(Editor);
155 for (unsigned Idx = 0, Last = Info.getNumFixItHints();
156 Idx < Last; ++Idx) {
157 const FixItHint &Hint = Info.getFixItHint(Idx);
158
159 if (Hint.CodeToInsert.empty()) {
160 if (Hint.InsertFromRange.isValid())
162 Hint.InsertFromRange, /*afterToken=*/false,
164 else
165 commit.remove(Hint.RemoveRange);
166 } else {
167 if (Hint.RemoveRange.isTokenRange() ||
168 Hint.RemoveRange.getBegin() != Hint.RemoveRange.getEnd())
169 commit.replace(Hint.RemoveRange, Hint.CodeToInsert);
170 else
171 commit.insert(Hint.RemoveRange.getBegin(), Hint.CodeToInsert,
172 /*afterToken=*/false, Hint.BeforePreviousInsertions);
173 }
174 }
175 bool CanRewrite = Info.getNumFixItHints() > 0 && commit.isCommitable();
176
177 if (!CanRewrite) {
178 if (Info.getNumFixItHints() > 0)
179 Diag(Info.getLocation(), diag::note_fixit_in_macro);
180
181 // If this was an error, refuse to perform any rewriting.
182 if (DiagLevel >= DiagnosticsEngine::Error) {
183 if (++NumFailures == 1)
184 Diag(Info.getLocation(), diag::note_fixit_unfixed_error);
185 }
186 return;
187 }
188
189 if (!Editor.commit(commit)) {
190 ++NumFailures;
191 Diag(Info.getLocation(), diag::note_fixit_failed);
192 return;
193 }
194
195 Diag(Info.getLocation(), diag::note_fixit_applied);
196}
197
198/// Emit a diagnostic via the adapted diagnostic client.
199void FixItRewriter::Diag(SourceLocation Loc, unsigned DiagID) {
200 // When producing this diagnostic, we temporarily bypass ourselves,
201 // and let the downstream client format the diagnostic.
202 Diags.setClient(Client, false);
203 Diags.Report(Loc, DiagID);
204 Diags.setClient(this, false);
205}
206
Defines the Diagnostic-related interfaces.
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
Defines the clang::SourceLocation class and associated facilities.
Defines the SourceManager interface.
bool isTokenRange() const
Return true if the end of this range specifies the start of the last token.
SourceLocation getEnd() const
SourceLocation getBegin() const
virtual void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel, const Diagnostic &Info)
Handle this diagnostic, reporting it to the user or capturing it to a log as needed.
A little helper class (which is basically a smart pointer that forwards info from DiagnosticsEngine a...
const SourceLocation & getLocation() const
unsigned getNumFixItHints() const
const FixItHint & getFixItHint(unsigned Idx) const
Concrete class used by the front-end to report problems and issues.
Definition Diagnostic.h:240
Level
The level of the diagnostic, after it has been through mapping.
Definition Diagnostic.h:245
StringRef getName() const
The name of this FileEntry.
Definition FileEntry.h:61
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition Diagnostic.h:78
bool BeforePreviousInsertions
Definition Diagnostic.h:92
CharSourceRange RemoveRange
Code that should be replaced to correct the error.
Definition Diagnostic.h:82
CharSourceRange InsertFromRange
Code in the specific range that should be inserted in the insertion location.
Definition Diagnostic.h:86
std::string CodeToInsert
The actual code to insert at the insertion location, as a string.
Definition Diagnostic.h:90
virtual ~FixItOptions()
Rewriter::buffer_iterator iterator
void Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic via the adapted diagnostic client.
bool WriteFixedFiles(std::vector< std::pair< std::string, std::string > > *RewrittenFiles=nullptr)
Write the modified source files.
bool WriteFixedFile(FileID ID, raw_ostream &OS)
Write a single modified source file.
void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel, const Diagnostic &Info) override
HandleDiagnostic - Handle this diagnostic, reporting it to the user or capturing it to a log as neede...
FixItRewriter(DiagnosticsEngine &Diags, SourceManager &SourceMgr, const LangOptions &LangOpts, FixItOptions *FixItOpts)
Initialize a new fix-it rewriter.
~FixItRewriter() override
Destroy the fix-it rewriter.
bool IncludeInDiagnosticCounts() const override
IncludeInDiagnosticCounts - This method (whose default implementation returns true) indicates whether...
A SourceLocation and its associated SourceManager.
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Rewriter - This is the main interface to the rewrite buffers.
Definition Rewriter.h:32
Encodes a location in the source.
This class handles loading and caching of source files into memory.
bool insertFromRange(SourceLocation loc, CharSourceRange range, bool afterToken=false, bool beforePreviousInsertions=false)
Definition Commit.cpp:63
bool insert(SourceLocation loc, StringRef text, bool afterToken=false, bool beforePreviousInsertions=false)
Definition Commit.cpp:47
bool isCommitable() const
Definition Commit.h:68
bool remove(CharSourceRange range)
Definition Commit.cpp:90
bool replace(CharSourceRange range, StringRef text)
Definition Commit.cpp:115
RangeSelector range(RangeSelector Begin, RangeSelector End)
DEPRECATED. Use enclose.
Top level wrappers for InstallAPI frontend operations.
CustomizableOptional< FileEntryRef > OptionalFileEntryRef
Definition FileEntry.h:196
@ Rewrite
We are substituting template parameters for (typically) other template parameters in order to rewrite...
Definition Template.h:54