clang 10.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
15 #include "clang/Rewrite/Frontend/FixItRewriter.h"
16 #include "clang/Basic/Diagnostic.h"
17 #include "clang/Basic/FileManager.h"
18 #include "clang/Basic/LLVM.h"
19 #include "clang/Basic/SourceLocation.h"
20 #include "clang/Basic/SourceManager.h"
21 #include "clang/Edit/Commit.h"
22 #include "clang/Edit/EditsReceiver.h"
23 #include "clang/Frontend/FrontendDiagnostic.h"
24 #include "clang/Rewrite/Core/RewriteBuffer.h"
25 #include "clang/Rewrite/Core/Rewriter.h"
26 #include "llvm/ADT/StringRef.h"
27 #include "llvm/Support/FileSystem.h"
28 #include "llvm/Support/raw_ostream.h"
29 #include <cstdio>
30 #include <memory>
31 #include <string>
32 #include <system_error>
33 #include <utility>
34
35 using namespace clang;
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(this, false);
45 }
46
47 FixItRewriter::~FixItRewriter() {
48 Diags.setClient(Client, Owner.release() != nullptr);
49 }
50
51 bool FixItRewriter::WriteFixedFile(FileID ID, raw_ostream &OS) {
52 const RewriteBuffer *RewriteBuf = Rewrite.getRewriteBufferFor(ID);
53 if (!RewriteBuf) return true;
54 RewriteBuf->write(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, text);
69 }
70
71 void replace(CharSourceRange range, StringRef text) override {
72 Rewrite.ReplaceText(range.getBegin(), Rewrite.getRangeSize(range), 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(FullSourceLoc(), diag::warn_fixit_no_changes);
82 return true;
83 }
84
85 RewritesReceiver Rec(Rewrite);
86 Editor.applyRewrites(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 const FileEntry *Entry = Rewrite.getSourceMgr().getFileEntryForID(I->first);
97 int fd;
98 std::string Filename = FixItOpts->RewriteFilename(Entry->getName(), fd);
99 std::error_code EC;
100 std::unique_ptr<llvm::raw_fd_ostream> OS;
101 if (fd != -1) {
102 OS.reset(new llvm::raw_fd_ostream(fd, /*shouldClose=*/true));
103 } else {
104 OS.reset(new llvm::raw_fd_ostream(Filename, EC, llvm::sys::fs::OF_None));
105 }
106 if (EC) {
107 Diags.Report(clang::diag::err_fe_unable_to_open_output) << Filename
108 << EC.message();
109 continue;
110 }
111 RewriteBuffer &RewriteBuf = I->second;
112 RewriteBuf.write(*OS);
113 OS->flush();
114
115 if (RewrittenFiles)
116 RewrittenFiles->push_back(std::make_pair(Entry->getName(), Filename));
117 }
118
119 return false;
120 }
121
122 bool FixItRewriter::IncludeInDiagnosticCounts() const {
123 return Client ? Client->IncludeInDiagnosticCounts() : true;
124 }
125
126 void FixItRewriter::HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
127 const Diagnostic &Info) {
128 // Default implementation (Warnings/errors count).
129 DiagnosticConsumer::HandleDiagnostic(DiagLevel, Info);
130
131 if (!FixItOpts->Silent ||
132 DiagLevel >= DiagnosticsEngine::Error ||
133 (DiagLevel == DiagnosticsEngine::Note && !PrevDiagSilenced) ||
134 (DiagLevel > DiagnosticsEngine::Note && Info.getNumFixItHints())) {
135 Client->HandleDiagnostic(DiagLevel, Info);
136 PrevDiagSilenced = false;
137 } else {
138 PrevDiagSilenced = true;
139 }
140
141 // Skip over any diagnostics that are ignored or notes.
142 if (DiagLevel <= DiagnosticsEngine::Note)
143 return;
144 // Skip over errors if we are only fixing warnings.
145 if (DiagLevel >= DiagnosticsEngine::Error && FixItOpts->FixOnlyWarnings) {
146 ++NumFailures;
147 return;
148 }
149
150 // Make sure that we can perform all of the modifications we
151 // in this diagnostic.
152 edit::Commit commit(Editor);
153 for (unsigned Idx = 0, Last = Info.getNumFixItHints();
154 Idx < Last; ++Idx) {
155 const FixItHint &Hint = Info.getFixItHint(Idx);
156
157 if (Hint.CodeToInsert.empty()) {
158 if (Hint.InsertFromRange.isValid())
159 commit.insertFromRange(Hint.RemoveRange.getBegin(),
160 Hint.InsertFromRange, /*afterToken=*/false,
161 Hint.BeforePreviousInsertions);
162 else
163 commit.remove(Hint.RemoveRange);
164 } else {
165 if (Hint.RemoveRange.isTokenRange() ||
166 Hint.RemoveRange.getBegin() != Hint.RemoveRange.getEnd())
167 commit.replace(Hint.RemoveRange, Hint.CodeToInsert);
168 else
169 commit.insert(Hint.RemoveRange.getBegin(), Hint.CodeToInsert,
170 /*afterToken=*/false, Hint.BeforePreviousInsertions);
171 }
172 }
173 bool CanRewrite = Info.getNumFixItHints() > 0 && commit.isCommitable();
174
175 if (!CanRewrite) {
176 if (Info.getNumFixItHints() > 0)
177 Diag(Info.getLocation(), diag::note_fixit_in_macro);
178
179 // If this was an error, refuse to perform any rewriting.
180 if (DiagLevel >= DiagnosticsEngine::Error) {
181 if (++NumFailures == 1)
182 Diag(Info.getLocation(), diag::note_fixit_unfixed_error);
183 }
184 return;
185 }
186
187 if (!Editor.commit(commit)) {
188 ++NumFailures;
189 Diag(Info.getLocation(), diag::note_fixit_failed);
190 return;
191 }
192
193 Diag(Info.getLocation(), diag::note_fixit_applied);
194 }
195
196 /// Emit a diagnostic via the adapted diagnostic client.
197 void FixItRewriter::Diag(SourceLocation Loc, unsigned DiagID) {
198 // When producing this diagnostic, we temporarily bypass ourselves,
199 // clear out any current diagnostic, and let the downstream client
200 // format the diagnostic.
201 Diags.setClient(Client, false);
202 Diags.Clear();
203 Diags.Report(Loc, DiagID);
204 Diags.setClient(this, false);
205 }
206
207 FixItOptions::~FixItOptions() = default;
clang::FixItRewriter::buffer_begin
iterator buffer_begin()
Definition: FixItRewriter.h:103
clang::Builtin::ID
ID
Definition: Builtins.h:46
Rewriter.h
clang::edit::Commit::remove
bool remove(CharSourceRange range)
Definition: Commit.cpp:91
clang::DiagnosticsEngine::getClient
DiagnosticConsumer * getClient()
Definition: Diagnostic.h:516
FileManager.h
Defines the clang::FileManager interface and associated types.
Commit.h
SourceManager.h
Defines the SourceManager interface.
clang::FixItHint::CodeToInsert
std::string CodeToInsert
The actual code to insert at the insertion location, as a string.
Definition: Diagnostic.h:78
clang::edit::Commit::insertFromRange
bool insertFromRange(SourceLocation loc, CharSourceRange range, bool afterToken=false, bool beforePreviousInsertions=false)
Definition: Commit.cpp:64
clang::DiagnosticsEngine::takeClient
std::unique_ptr< DiagnosticConsumer > takeClient()
Return the current diagnostic client along with ownership of that client.
Definition: Diagnostic.h:524
clang::transformer::range
RangeSelector range(RangeSelector Begin, RangeSelector End)
Selects from the start of Begin and to the end of End.
Definition: RangeSelector.cpp:151
clang::RewriteBuffer
RewriteBuffer - As code is rewritten, SourceBuffer&#39;s from the original input with modifications get a...
Definition: RewriteBuffer.h:25
clang::FixItRewriter::WriteFixedFiles
bool WriteFixedFiles(std::vector< std::pair< std::string, std::string >> *RewrittenFiles=nullptr)
Write the modified source files.
Definition: FixItRewriter.cpp:78
FixItRewriter.h
clang::edit::Commit::insert
bool insert(SourceLocation loc, StringRef text, bool afterToken=false, bool beforePreviousInsertions=false)
Definition: Commit.cpp:48
clang::DiagnosticsEngine::setClient
void setClient(DiagnosticConsumer *client, bool ShouldOwnClient=true)
Set the diagnostic client associated with this diagnostic object.
Definition: Diagnostic.cpp:99
clang::CharSourceRange::getBegin
SourceLocation getBegin() const
Definition: SourceLocation.h:280
clang::DiagnosticsEngine::Note
Definition: Diagnostic.h:154
clang::edit::EditsReceiver
Definition: EditsReceiver.h:19
clang::Diagnostic::getFixItHint
const FixItHint & getFixItHint(unsigned Idx) const
Definition: Diagnostic.h:1423
clang::Rewriter::ReplaceText
bool ReplaceText(SourceLocation Start, unsigned OrigLength, StringRef NewStr)
ReplaceText - This method replaces a range of characters in the input buffer with a new string...
Definition: Rewriter.cpp:320
clang::LangOptions
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:53
clang::CharSourceRange::isValid
bool isValid() const
Definition: SourceLocation.h:288
clang::edit::Commit::replace
bool replace(CharSourceRange range, StringRef text)
Definition: Commit.cpp:116
RewriteBuffer.h
clang::Diagnostic::getLocation
const SourceLocation & getLocation() const
Definition: Diagnostic.h:1338
LLVM.h
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified...
clang::DiagnosticsEngine
Concrete class used by the front-end to report problems and issues.
Definition: Diagnostic.h:149
clang::FixItRewriter::~FixItRewriter
~FixItRewriter() override
Destroy the fix-it rewriter.
Definition: FixItRewriter.cpp:47
Diagnostic.h
Defines the Diagnostic-related interfaces.
EditsReceiver.h
FrontendDiagnostic.h
Filename
StringRef Filename
Definition: Format.cpp:1825
clang::CharSourceRange
Represents a character-granular source range.
Definition: SourceLocation.h:250
clang::FixItHint::BeforePreviousInsertions
bool BeforePreviousInsertions
Definition: Diagnostic.h:80
clang::Rewriter::getRangeSize
int getRangeSize(SourceRange Range, RewriteOptions opts=RewriteOptions()) const
getRangeSize - Return the size in bytes of the specified range if they are in the same file...
Definition: Rewriter.cpp:175
clang::ComparisonCategoryType::Last
clang::FixItRewriter::buffer_end
iterator buffer_end()
Definition: FixItRewriter.h:104
clang::FixItHint::InsertFromRange
CharSourceRange InsertFromRange
Code in the specific range that should be inserted in the insertion location.
Definition: Diagnostic.h:74
clang::FixItRewriter::WriteFixedFile
bool WriteFixedFile(FileID ID, raw_ostream &OS)
Write a single modified source file.
Definition: FixItRewriter.cpp:51
clang::FixItHint::RemoveRange
CharSourceRange RemoveRange
Code that should be replaced to correct the error.
Definition: Diagnostic.h:70
clang::FixItRewriter::FixItRewriter
FixItRewriter(DiagnosticsEngine &Diags, SourceManager &SourceMgr, const LangOptions &LangOpts, FixItOptions *FixItOpts)
Initialize a new fix-it rewriter.
Definition: FixItRewriter.cpp:37
clang::SourceLocation
Encodes a location in the source.
Definition: SourceLocation.h:86
clang::RewriteBuffer::write
raw_ostream & write(raw_ostream &Stream) const
Write to Stream the result of applying all changes to the original buffer.
Definition: Rewriter.cpp:37
clang::FileEntry::getName
StringRef getName() const
Definition: FileManager.h:102
clang::FileEntry
Cached information about one file (either on disk or in the virtual file system). ...
Definition: FileManager.h:78
clang::Rewriter::getRewriteBufferFor
const RewriteBuffer * getRewriteBufferFor(FileID FID) const
getRewriteBufferFor - Return the rewrite buffer for the specified FileID.
Definition: Rewriter.h:198
clang::FixItRewriter::HandleDiagnostic
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...
Definition: FixItRewriter.cpp:126
clang::Rewriter::InsertText
bool InsertText(SourceLocation Loc, StringRef Str, bool InsertAfter=true, bool indentNewLines=false)
InsertText - Insert the specified string at the specified location in the original buffer...
Definition: Rewriter.cpp:255
clang::DiagnosticConsumer::HandleDiagnostic
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.
Definition: Diagnostic.cpp:532
clang::CharSourceRange::isTokenRange
bool isTokenRange() const
Return true if the end of this range specifies the start of the last token.
Definition: SourceLocation.h:277
clang::FileID
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
Definition: SourceLocation.h:38
clang
Dataflow Directional Tag Classes.
Definition: CFGReachabilityAnalysis.h:21
clang::edit::Commit::isCommitable
bool isCommitable() const
Definition: Commit.h:68
clang::comments::tok::text
Definition: CommentLexer.h:35
clang::edit::Commit
Definition: Commit.h:29
clang::FixItOptions
Definition: FixItRewriter.h:33
clang::FixItRewriter::Diag
void Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic via the adapted diagnostic client.
Definition: FixItRewriter.cpp:197
clang::Diagnostic::getNumFixItHints
unsigned getNumFixItHints() const
Definition: Diagnostic.h:1419
clang::DiagnosticsEngine::Error
Definition: Diagnostic.h:157
clang::CharSourceRange::getEnd
SourceLocation getEnd() const
Definition: SourceLocation.h:281
clang::FixItOptions::~FixItOptions
virtual ~FixItOptions()
clang::Rewriter
Rewriter - This is the main interface to the rewrite buffers.
Definition: Rewriter.h:32
SourceLocation.h
Defines the clang::SourceLocation class and associated facilities.
clang::DiagnosticsEngine::Level
Level
The level of the diagnostic, after it has been through mapping.
Definition: Diagnostic.h:152
iterator
clang::Diagnostic
A little helper class (which is basically a smart pointer that forwards info from DiagnosticsEngine) ...
Definition: Diagnostic.h:1327
clang::FullSourceLoc
A SourceLocation and its associated SourceManager.
Definition: SourceLocation.h:361
clang::FixItHint
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition: Diagnostic.h:66
clang::SourceManager
This class handles loading and caching of source files into memory.
Definition: SourceManager.h:596
clang::FixItRewriter::IncludeInDiagnosticCounts
bool IncludeInDiagnosticCounts() const override
IncludeInDiagnosticCounts - This method (whose default implementation returns true) indicates whether...
Definition: FixItRewriter.cpp:122