clang  6.0.0svn
FixItRewriter.cpp
Go to the documentation of this file.
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 
20 #include "clang/Edit/Commit.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 
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 
45  Diags.setClient(Client, Owner.release() != nullptr);
46 }
47 
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:
62  RewritesReceiver(Rewriter &Rewrite) : Rewrite(Rewrite) { }
63 
64  void insert(SourceLocation loc, StringRef text) override {
65  Rewrite.InsertText(loc, text);
66  }
67  void replace(CharSourceRange range, StringRef text) override {
68  Rewrite.ReplaceText(range.getBegin(), Rewrite.getRangeSize(range), text);
69  }
70 };
71 
72 }
73 
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  if (FixItOpts->InPlace) {
85  // Overwriting open files on Windows is tricky, but the rewriter can do it
86  // for us.
87  Rewrite.overwriteChangedFiles();
88  return false;
89  }
90 
91  for (iterator I = buffer_begin(), E = buffer_end(); I != E; ++I) {
92  const FileEntry *Entry = Rewrite.getSourceMgr().getFileEntryForID(I->first);
93  int fd;
94  std::string Filename = FixItOpts->RewriteFilename(Entry->getName(), fd);
95  std::error_code EC;
96  std::unique_ptr<llvm::raw_fd_ostream> OS;
97  if (fd != -1) {
98  OS.reset(new llvm::raw_fd_ostream(fd, /*shouldClose=*/true));
99  } else {
100  OS.reset(new llvm::raw_fd_ostream(Filename, EC, llvm::sys::fs::F_None));
101  }
102  if (EC) {
103  Diags.Report(clang::diag::err_fe_unable_to_open_output) << Filename
104  << EC.message();
105  continue;
106  }
107  RewriteBuffer &RewriteBuf = I->second;
108  RewriteBuf.write(*OS);
109  OS->flush();
110 
111  if (RewrittenFiles)
112  RewrittenFiles->push_back(std::make_pair(Entry->getName(), Filename));
113  }
114 
115  return false;
116 }
117 
119  return Client ? Client->IncludeInDiagnosticCounts() : true;
120 }
121 
123  const Diagnostic &Info) {
124  // Default implementation (Warnings/errors count).
125  DiagnosticConsumer::HandleDiagnostic(DiagLevel, Info);
126 
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;
133  } else {
134  PrevDiagSilenced = true;
135  }
136 
137  // Skip over any diagnostics that are ignored or notes.
138  if (DiagLevel <= DiagnosticsEngine::Note)
139  return;
140  // Skip over errors if we are only fixing warnings.
141  if (DiagLevel >= DiagnosticsEngine::Error && FixItOpts->FixOnlyWarnings) {
142  ++NumFailures;
143  return;
144  }
145 
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();
150  Idx < Last; ++Idx) {
151  const FixItHint &Hint = Info.getFixItHint(Idx);
152 
153  if (Hint.CodeToInsert.empty()) {
154  if (Hint.InsertFromRange.isValid())
155  commit.insertFromRange(Hint.RemoveRange.getBegin(),
156  Hint.InsertFromRange, /*afterToken=*/false,
158  else
159  commit.remove(Hint.RemoveRange);
160  } else {
161  if (Hint.RemoveRange.isTokenRange() ||
162  Hint.RemoveRange.getBegin() != Hint.RemoveRange.getEnd())
163  commit.replace(Hint.RemoveRange, Hint.CodeToInsert);
164  else
165  commit.insert(Hint.RemoveRange.getBegin(), Hint.CodeToInsert,
166  /*afterToken=*/false, Hint.BeforePreviousInsertions);
167  }
168  }
169  bool CanRewrite = Info.getNumFixItHints() > 0 && commit.isCommitable();
170 
171  if (!CanRewrite) {
172  if (Info.getNumFixItHints() > 0)
173  Diag(Info.getLocation(), diag::note_fixit_in_macro);
174 
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);
179  }
180  return;
181  }
182 
183  if (!Editor.commit(commit)) {
184  ++NumFailures;
185  Diag(Info.getLocation(), diag::note_fixit_failed);
186  return;
187  }
188 
189  Diag(Info.getLocation(), diag::note_fixit_applied);
190 }
191 
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);
198  Diags.Clear();
199  Diags.Report(Loc, DiagID);
200  Diags.setClient(this, false);
201 }
202 
bool remove(CharSourceRange range)
Definition: Commit.cpp:86
DiagnosticConsumer * getClient()
Definition: Diagnostic.h:427
Defines the clang::FileManager interface and associated types.
Defines the SourceManager interface.
std::string CodeToInsert
The actual code to insert at the insertion location, as a string.
Definition: Diagnostic.h:76
bool insertFromRange(SourceLocation loc, CharSourceRange range, bool afterToken=false, bool beforePreviousInsertions=false)
Definition: Commit.cpp:59
std::unique_ptr< DiagnosticConsumer > takeClient()
Return the current diagnostic client along with ownership of that client.
Definition: Diagnostic.h:435
bool WriteFixedFiles(std::vector< std::pair< std::string, std::string > > *RewrittenFiles=nullptr)
Write the modified source files.
RewriteBuffer - As code is rewritten, SourceBuffer&#39;s from the original input with modifications get a...
Definition: RewriteBuffer.h:27
bool insert(SourceLocation loc, StringRef text, bool afterToken=false, bool beforePreviousInsertions=false)
Definition: Commit.cpp:43
void setClient(DiagnosticConsumer *client, bool ShouldOwnClient=true)
Set the diagnostic client associated with this diagnostic object.
Definition: Diagnostic.cpp:91
SourceLocation getBegin() const
const FixItHint & getFixItHint(unsigned Idx) const
Definition: Diagnostic.h:1323
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:303
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:48
bool replace(CharSourceRange range, StringRef text)
Definition: Commit.cpp:111
const SourceLocation & getLocation() const
Definition: Diagnostic.h:1238
Concrete class used by the front-end to report problems and issues.
Definition: Diagnostic.h:147
~FixItRewriter() override
Destroy the fix-it rewriter.
StringRef Filename
Definition: Format.cpp:1345
Represents a character-granular source range.
bool BeforePreviousInsertions
Definition: Diagnostic.h:78
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:157
CharSourceRange InsertFromRange
Code in the specific range that should be inserted in the insertion location.
Definition: Diagnostic.h:72
bool WriteFixedFile(FileID ID, raw_ostream &OS)
Write a single modified source file.
CharSourceRange RemoveRange
Code that should be replaced to correct the error.
Definition: Diagnostic.h:68
#define false
Definition: stdbool.h:33
FixItRewriter(DiagnosticsEngine &Diags, SourceManager &SourceMgr, const LangOptions &LangOpts, FixItOptions *FixItOpts)
Initialize a new fix-it rewriter.
Encodes a location in the source.
raw_ostream & write(raw_ostream &Stream) const
Write to Stream the result of applying all changes to the original buffer.
Definition: Rewriter.cpp:25
StringRef getName() const
Definition: FileManager.h:84
Cached information about one file (either on disk or in the virtual file system). ...
Definition: FileManager.h:59
const RewriteBuffer * getRewriteBufferFor(FileID FID) const
getRewriteBufferFor - Return the rewrite buffer for the specified FileID.
Definition: Rewriter.h:170
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...
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:238
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:435
bool isTokenRange() const
Return true if the end of this range specifies the start of the last token.
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
Rewriter::buffer_iterator iterator
Definition: FixItRewriter.h:86
Dataflow Directional Tag Classes.
bool isCommitable() const
Definition: Commit.h:65
void Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic via the adapted diagnostic client.
unsigned getNumFixItHints() const
Definition: Diagnostic.h:1319
SourceLocation getEnd() const
Rewriter - This is the main interface to the rewrite buffers.
Definition: Rewriter.h:31
Defines the clang::SourceLocation class and associated facilities.
Level
The level of the diagnostic, after it has been through mapping.
Definition: Diagnostic.h:150
A little helper class (which is basically a smart pointer that forwards info from DiagnosticsEngine) ...
Definition: Diagnostic.h:1227
A SourceLocation and its associated SourceManager.
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition: Diagnostic.h:64
This class handles loading and caching of source files into memory.
bool IncludeInDiagnosticCounts() const override
IncludeInDiagnosticCounts - This method (whose default implementation returns true) indicates whether...