clang  9.0.0svn
Rewriter.cpp
Go to the documentation of this file.
1 //===- Rewriter.cpp - Code rewriting interface ----------------------------===//
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 file defines the Rewriter class, which is used for code
10 // transformations.
11 //
12 //===----------------------------------------------------------------------===//
13 
15 #include "clang/Basic/Diagnostic.h"
20 #include "clang/Lex/Lexer.h"
23 #include "llvm/ADT/SmallString.h"
24 #include "llvm/ADT/SmallVector.h"
25 #include "llvm/ADT/StringRef.h"
26 #include "llvm/Support/FileSystem.h"
27 #include "llvm/Support/raw_ostream.h"
28 #include <cassert>
29 #include <iterator>
30 #include <map>
31 #include <memory>
32 #include <system_error>
33 #include <utility>
34 
35 using namespace clang;
36 
37 raw_ostream &RewriteBuffer::write(raw_ostream &os) const {
38  // Walk RewriteRope chunks efficiently using MoveToNextPiece() instead of the
39  // character iterator.
40  for (RopePieceBTreeIterator I = begin(), E = end(); I != E;
41  I.MoveToNextPiece())
42  os << I.piece();
43  return os;
44 }
45 
46 /// Return true if this character is non-new-line whitespace:
47 /// ' ', '\\t', '\\f', '\\v', '\\r'.
48 static inline bool isWhitespaceExceptNL(unsigned char c) {
49  switch (c) {
50  case ' ':
51  case '\t':
52  case '\f':
53  case '\v':
54  case '\r':
55  return true;
56  default:
57  return false;
58  }
59 }
60 
61 void RewriteBuffer::RemoveText(unsigned OrigOffset, unsigned Size,
62  bool removeLineIfEmpty) {
63  // Nothing to remove, exit early.
64  if (Size == 0) return;
65 
66  unsigned RealOffset = getMappedOffset(OrigOffset, true);
67  assert(RealOffset+Size <= Buffer.size() && "Invalid location");
68 
69  // Remove the dead characters.
70  Buffer.erase(RealOffset, Size);
71 
72  // Add a delta so that future changes are offset correctly.
73  AddReplaceDelta(OrigOffset, -Size);
74 
75  if (removeLineIfEmpty) {
76  // Find the line that the remove occurred and if it is completely empty
77  // remove the line as well.
78 
79  iterator curLineStart = begin();
80  unsigned curLineStartOffs = 0;
81  iterator posI = begin();
82  for (unsigned i = 0; i != RealOffset; ++i) {
83  if (*posI == '\n') {
84  curLineStart = posI;
85  ++curLineStart;
86  curLineStartOffs = i + 1;
87  }
88  ++posI;
89  }
90 
91  unsigned lineSize = 0;
92  posI = curLineStart;
93  while (posI != end() && isWhitespaceExceptNL(*posI)) {
94  ++posI;
95  ++lineSize;
96  }
97  if (posI != end() && *posI == '\n') {
98  Buffer.erase(curLineStartOffs, lineSize + 1/* + '\n'*/);
99  AddReplaceDelta(curLineStartOffs, -(lineSize + 1/* + '\n'*/));
100  }
101  }
102 }
103 
104 void RewriteBuffer::InsertText(unsigned OrigOffset, StringRef Str,
105  bool InsertAfter) {
106  // Nothing to insert, exit early.
107  if (Str.empty()) return;
108 
109  unsigned RealOffset = getMappedOffset(OrigOffset, InsertAfter);
110  Buffer.insert(RealOffset, Str.begin(), Str.end());
111 
112  // Add a delta so that future changes are offset correctly.
113  AddInsertDelta(OrigOffset, Str.size());
114 }
115 
116 /// ReplaceText - This method replaces a range of characters in the input
117 /// buffer with a new string. This is effectively a combined "remove+insert"
118 /// operation.
119 void RewriteBuffer::ReplaceText(unsigned OrigOffset, unsigned OrigLength,
120  StringRef NewStr) {
121  unsigned RealOffset = getMappedOffset(OrigOffset, true);
122  Buffer.erase(RealOffset, OrigLength);
123  Buffer.insert(RealOffset, NewStr.begin(), NewStr.end());
124  if (OrigLength != NewStr.size())
125  AddReplaceDelta(OrigOffset, NewStr.size() - OrigLength);
126 }
127 
128 //===----------------------------------------------------------------------===//
129 // Rewriter class
130 //===----------------------------------------------------------------------===//
131 
132 /// getRangeSize - Return the size in bytes of the specified range if they
133 /// are in the same file. If not, this returns -1.
135  RewriteOptions opts) const {
136  if (!isRewritable(Range.getBegin()) ||
137  !isRewritable(Range.getEnd())) return -1;
138 
139  FileID StartFileID, EndFileID;
140  unsigned StartOff = getLocationOffsetAndFileID(Range.getBegin(), StartFileID);
141  unsigned EndOff = getLocationOffsetAndFileID(Range.getEnd(), EndFileID);
142 
143  if (StartFileID != EndFileID)
144  return -1;
145 
146  // If edits have been made to this buffer, the delta between the range may
147  // have changed.
148  std::map<FileID, RewriteBuffer>::const_iterator I =
149  RewriteBuffers.find(StartFileID);
150  if (I != RewriteBuffers.end()) {
151  const RewriteBuffer &RB = I->second;
152  EndOff = RB.getMappedOffset(EndOff, opts.IncludeInsertsAtEndOfRange);
153  StartOff = RB.getMappedOffset(StartOff, !opts.IncludeInsertsAtBeginOfRange);
154  }
155 
156  // Adjust the end offset to the end of the last token, instead of being the
157  // start of the last token if this is a token range.
158  if (Range.isTokenRange())
159  EndOff += Lexer::MeasureTokenLength(Range.getEnd(), *SourceMgr, *LangOpts);
160 
161  return EndOff-StartOff;
162 }
163 
165  return getRangeSize(CharSourceRange::getTokenRange(Range), opts);
166 }
167 
168 /// getRewrittenText - Return the rewritten form of the text in the specified
169 /// range. If the start or end of the range was unrewritable or if they are
170 /// in different buffers, this returns an empty string.
171 ///
172 /// Note that this method is not particularly efficient.
173 std::string Rewriter::getRewrittenText(SourceRange Range) const {
174  if (!isRewritable(Range.getBegin()) ||
175  !isRewritable(Range.getEnd()))
176  return {};
177 
178  FileID StartFileID, EndFileID;
179  unsigned StartOff, EndOff;
180  StartOff = getLocationOffsetAndFileID(Range.getBegin(), StartFileID);
181  EndOff = getLocationOffsetAndFileID(Range.getEnd(), EndFileID);
182 
183  if (StartFileID != EndFileID)
184  return {}; // Start and end in different buffers.
185 
186  // If edits have been made to this buffer, the delta between the range may
187  // have changed.
188  std::map<FileID, RewriteBuffer>::const_iterator I =
189  RewriteBuffers.find(StartFileID);
190  if (I == RewriteBuffers.end()) {
191  // If the buffer hasn't been rewritten, just return the text from the input.
192  const char *Ptr = SourceMgr->getCharacterData(Range.getBegin());
193 
194  // Adjust the end offset to the end of the last token, instead of being the
195  // start of the last token.
196  EndOff += Lexer::MeasureTokenLength(Range.getEnd(), *SourceMgr, *LangOpts);
197  return std::string(Ptr, Ptr+EndOff-StartOff);
198  }
199 
200  const RewriteBuffer &RB = I->second;
201  EndOff = RB.getMappedOffset(EndOff, true);
202  StartOff = RB.getMappedOffset(StartOff);
203 
204  // Adjust the end offset to the end of the last token, instead of being the
205  // start of the last token.
206  EndOff += Lexer::MeasureTokenLength(Range.getEnd(), *SourceMgr, *LangOpts);
207 
208  // Advance the iterators to the right spot, yay for linear time algorithms.
209  RewriteBuffer::iterator Start = RB.begin();
210  std::advance(Start, StartOff);
212  std::advance(End, EndOff-StartOff);
213 
214  return std::string(Start, End);
215 }
216 
217 unsigned Rewriter::getLocationOffsetAndFileID(SourceLocation Loc,
218  FileID &FID) const {
219  assert(Loc.isValid() && "Invalid location");
220  std::pair<FileID, unsigned> V = SourceMgr->getDecomposedLoc(Loc);
221  FID = V.first;
222  return V.second;
223 }
224 
225 /// getEditBuffer - Get or create a RewriteBuffer for the specified FileID.
227  std::map<FileID, RewriteBuffer>::iterator I =
228  RewriteBuffers.lower_bound(FID);
229  if (I != RewriteBuffers.end() && I->first == FID)
230  return I->second;
231  I = RewriteBuffers.insert(I, std::make_pair(FID, RewriteBuffer()));
232 
233  StringRef MB = SourceMgr->getBufferData(FID);
234  I->second.Initialize(MB.begin(), MB.end());
235 
236  return I->second;
237 }
238 
239 /// InsertText - Insert the specified string at the specified location in the
240 /// original buffer.
241 bool Rewriter::InsertText(SourceLocation Loc, StringRef Str,
242  bool InsertAfter, bool indentNewLines) {
243  if (!isRewritable(Loc)) return true;
244  FileID FID;
245  unsigned StartOffs = getLocationOffsetAndFileID(Loc, FID);
246 
247  SmallString<128> indentedStr;
248  if (indentNewLines && Str.find('\n') != StringRef::npos) {
249  StringRef MB = SourceMgr->getBufferData(FID);
250 
251  unsigned lineNo = SourceMgr->getLineNumber(FID, StartOffs) - 1;
252  const SrcMgr::ContentCache *
253  Content = SourceMgr->getSLocEntry(FID).getFile().getContentCache();
254  unsigned lineOffs = Content->SourceLineCache[lineNo];
255 
256  // Find the whitespace at the start of the line.
257  StringRef indentSpace;
258  {
259  unsigned i = lineOffs;
260  while (isWhitespaceExceptNL(MB[i]))
261  ++i;
262  indentSpace = MB.substr(lineOffs, i-lineOffs);
263  }
264 
266  Str.split(lines, "\n");
267 
268  for (unsigned i = 0, e = lines.size(); i != e; ++i) {
269  indentedStr += lines[i];
270  if (i < e-1) {
271  indentedStr += '\n';
272  indentedStr += indentSpace;
273  }
274  }
275  Str = indentedStr.str();
276  }
277 
278  getEditBuffer(FID).InsertText(StartOffs, Str, InsertAfter);
279  return false;
280 }
281 
283  if (!isRewritable(Loc)) return true;
284  FileID FID;
285  unsigned StartOffs = getLocationOffsetAndFileID(Loc, FID);
286  RewriteOptions rangeOpts;
287  rangeOpts.IncludeInsertsAtBeginOfRange = false;
288  StartOffs += getRangeSize(SourceRange(Loc, Loc), rangeOpts);
289  getEditBuffer(FID).InsertText(StartOffs, Str, /*InsertAfter*/true);
290  return false;
291 }
292 
293 /// RemoveText - Remove the specified text region.
294 bool Rewriter::RemoveText(SourceLocation Start, unsigned Length,
295  RewriteOptions opts) {
296  if (!isRewritable(Start)) return true;
297  FileID FID;
298  unsigned StartOffs = getLocationOffsetAndFileID(Start, FID);
299  getEditBuffer(FID).RemoveText(StartOffs, Length, opts.RemoveLineIfEmpty);
300  return false;
301 }
302 
303 /// ReplaceText - This method replaces a range of characters in the input
304 /// buffer with a new string. This is effectively a combined "remove/insert"
305 /// operation.
306 bool Rewriter::ReplaceText(SourceLocation Start, unsigned OrigLength,
307  StringRef NewStr) {
308  if (!isRewritable(Start)) return true;
309  FileID StartFileID;
310  unsigned StartOffs = getLocationOffsetAndFileID(Start, StartFileID);
311 
312  getEditBuffer(StartFileID).ReplaceText(StartOffs, OrigLength, NewStr);
313  return false;
314 }
315 
316 bool Rewriter::ReplaceText(SourceRange range, SourceRange replacementRange) {
317  if (!isRewritable(range.getBegin())) return true;
318  if (!isRewritable(range.getEnd())) return true;
319  if (replacementRange.isInvalid()) return true;
320  SourceLocation start = range.getBegin();
321  unsigned origLength = getRangeSize(range);
322  unsigned newLength = getRangeSize(replacementRange);
323  FileID FID;
324  unsigned newOffs = getLocationOffsetAndFileID(replacementRange.getBegin(),
325  FID);
326  StringRef MB = SourceMgr->getBufferData(FID);
327  return ReplaceText(start, origLength, MB.substr(newOffs, newLength));
328 }
329 
331  SourceLocation parentIndent) {
332  if (range.isInvalid()) return true;
333  if (!isRewritable(range.getBegin())) return true;
334  if (!isRewritable(range.getEnd())) return true;
335  if (!isRewritable(parentIndent)) return true;
336 
337  FileID StartFileID, EndFileID, parentFileID;
338  unsigned StartOff, EndOff, parentOff;
339 
340  StartOff = getLocationOffsetAndFileID(range.getBegin(), StartFileID);
341  EndOff = getLocationOffsetAndFileID(range.getEnd(), EndFileID);
342  parentOff = getLocationOffsetAndFileID(parentIndent, parentFileID);
343 
344  if (StartFileID != EndFileID || StartFileID != parentFileID)
345  return true;
346  if (StartOff > EndOff)
347  return true;
348 
349  FileID FID = StartFileID;
350  StringRef MB = SourceMgr->getBufferData(FID);
351 
352  unsigned parentLineNo = SourceMgr->getLineNumber(FID, parentOff) - 1;
353  unsigned startLineNo = SourceMgr->getLineNumber(FID, StartOff) - 1;
354  unsigned endLineNo = SourceMgr->getLineNumber(FID, EndOff) - 1;
355 
356  const SrcMgr::ContentCache *
357  Content = SourceMgr->getSLocEntry(FID).getFile().getContentCache();
358 
359  // Find where the lines start.
360  unsigned parentLineOffs = Content->SourceLineCache[parentLineNo];
361  unsigned startLineOffs = Content->SourceLineCache[startLineNo];
362 
363  // Find the whitespace at the start of each line.
364  StringRef parentSpace, startSpace;
365  {
366  unsigned i = parentLineOffs;
367  while (isWhitespaceExceptNL(MB[i]))
368  ++i;
369  parentSpace = MB.substr(parentLineOffs, i-parentLineOffs);
370 
371  i = startLineOffs;
372  while (isWhitespaceExceptNL(MB[i]))
373  ++i;
374  startSpace = MB.substr(startLineOffs, i-startLineOffs);
375  }
376  if (parentSpace.size() >= startSpace.size())
377  return true;
378  if (!startSpace.startswith(parentSpace))
379  return true;
380 
381  StringRef indent = startSpace.substr(parentSpace.size());
382 
383  // Indent the lines between start/end offsets.
384  RewriteBuffer &RB = getEditBuffer(FID);
385  for (unsigned lineNo = startLineNo; lineNo <= endLineNo; ++lineNo) {
386  unsigned offs = Content->SourceLineCache[lineNo];
387  unsigned i = offs;
388  while (isWhitespaceExceptNL(MB[i]))
389  ++i;
390  StringRef origIndent = MB.substr(offs, i-offs);
391  if (origIndent.startswith(startSpace))
392  RB.InsertText(offs, indent, /*InsertAfter=*/false);
393  }
394 
395  return false;
396 }
397 
398 namespace {
399 
400 // A wrapper for a file stream that atomically overwrites the target.
401 //
402 // Creates a file output stream for a temporary file in the constructor,
403 // which is later accessible via getStream() if ok() return true.
404 // Flushes the stream and moves the temporary file to the target location
405 // in the destructor.
406 class AtomicallyMovedFile {
407 public:
408  AtomicallyMovedFile(DiagnosticsEngine &Diagnostics, StringRef Filename,
409  bool &AllWritten)
410  : Diagnostics(Diagnostics), Filename(Filename), AllWritten(AllWritten) {
411  TempFilename = Filename;
412  TempFilename += "-%%%%%%%%";
413  int FD;
414  if (llvm::sys::fs::createUniqueFile(TempFilename, FD, TempFilename)) {
415  AllWritten = false;
416  Diagnostics.Report(clang::diag::err_unable_to_make_temp)
417  << TempFilename;
418  } else {
419  FileStream.reset(new llvm::raw_fd_ostream(FD, /*shouldClose=*/true));
420  }
421  }
422 
423  ~AtomicallyMovedFile() {
424  if (!ok()) return;
425 
426  // Close (will also flush) theFileStream.
427  FileStream->close();
428  if (std::error_code ec = llvm::sys::fs::rename(TempFilename, Filename)) {
429  AllWritten = false;
430  Diagnostics.Report(clang::diag::err_unable_to_rename_temp)
431  << TempFilename << Filename << ec.message();
432  // If the remove fails, there's not a lot we can do - this is already an
433  // error.
434  llvm::sys::fs::remove(TempFilename);
435  }
436  }
437 
438  bool ok() { return (bool)FileStream; }
439  raw_ostream &getStream() { return *FileStream; }
440 
441 private:
442  DiagnosticsEngine &Diagnostics;
443  StringRef Filename;
444  SmallString<128> TempFilename;
445  std::unique_ptr<llvm::raw_fd_ostream> FileStream;
446  bool &AllWritten;
447 };
448 
449 } // namespace
450 
452  bool AllWritten = true;
453  for (buffer_iterator I = buffer_begin(), E = buffer_end(); I != E; ++I) {
454  const FileEntry *Entry =
455  getSourceMgr().getFileEntryForID(I->first);
456  AtomicallyMovedFile File(getSourceMgr().getDiagnostics(), Entry->getName(),
457  AllWritten);
458  if (File.ok()) {
459  I->second.write(File.getStream());
460  }
461  }
462  return !AllWritten;
463 }
void insert(unsigned Offset, const char *Start, const char *End)
Definition: RewriteRope.h:196
bool IncreaseIndentation(CharSourceRange range, SourceLocation parentIndent)
Increase indentation for the lines between the given source range.
Definition: Rewriter.cpp:330
Defines the clang::FileManager interface and associated types.
Defines the SourceManager interface.
static CharSourceRange getTokenRange(SourceRange R)
void Initialize(const char *BufStart, const char *BufEnd)
Initialize - Start this rewrite buffer out with a copy of the unmodified input buffer.
Definition: RewriteBuffer.h:43
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
Definition: Diagnostic.h:1296
bool RemoveText(SourceLocation Start, unsigned Length, RewriteOptions opts=RewriteOptions())
RemoveText - Remove the specified text region.
Definition: Rewriter.cpp:294
void erase(unsigned Offset, unsigned NumBytes)
Definition: RewriteRope.h:202
RewriteBuffer & getEditBuffer(FileID FID)
getEditBuffer - This is like getRewriteBufferFor, but always returns a buffer, and allows you to writ...
Definition: Rewriter.cpp:226
RewriteBuffer - As code is rewritten, SourceBuffer&#39;s from the original input with modifications get a...
Definition: RewriteBuffer.h:25
iterator end() const
Definition: RewriteBuffer.h:38
std::string getRewrittenText(SourceRange Range) const
getRewrittenText - Return the rewritten form of the text in the specified range.
Definition: Rewriter.cpp:173
SourceLocation getBegin() const
One instance of this struct is kept for every file loaded or used.
Definition: SourceManager.h:94
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:306
Concrete class used by the front-end to report problems and issues.
Definition: Diagnostic.h:148
Defines the Diagnostic-related interfaces.
StringRef Filename
Definition: Format.cpp:1707
SourceLocation End
Represents a character-granular source range.
static unsigned MeasureTokenLength(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts)
MeasureTokenLength - Relex the token at the specified location and return its length in bytes in the ...
Definition: Lexer.cpp:435
bool isInvalid() const
SourceLocation getEnd() const
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:164
void InsertText(unsigned OrigOffset, StringRef Str, bool InsertAfter=true)
InsertText - Insert some text at the specified point, where the offset in the buffer is specified rel...
Definition: Rewriter.cpp:104
bool overwriteChangedFiles()
overwriteChangedFiles - Save all changed files to disk.
Definition: Rewriter.cpp:451
iterator begin() const
Definition: RewriteBuffer.h:37
void ReplaceText(unsigned OrigOffset, unsigned OrigLength, StringRef NewStr)
ReplaceText - This method replaces a range of characters in the input buffer with a new string...
Definition: Rewriter.cpp:119
Encodes a location in the source.
static bool isWhitespaceExceptNL(unsigned char c)
Return true if this character is non-new-line whitespace: &#39; &#39;, &#39;\t&#39;, &#39;\f&#39;, &#39;\v&#39;, &#39;\r&#39;.
Definition: Rewriter.cpp:48
raw_ostream & write(raw_ostream &Stream) const
Write to Stream the result of applying all changes to the original buffer.
Definition: Rewriter.cpp:37
StringRef getName() const
Definition: FileManager.h:83
unsigned size() const
Definition: RewriteRope.h:184
Cached information about one file (either on disk or in the virtual file system). ...
Definition: FileManager.h:59
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:241
bool RemoveLineIfEmpty
If true and removing some text leaves a blank line also remove the empty line (false by default)...
Definition: Rewriter.h:49
void RemoveText(unsigned OrigOffset, unsigned Size, bool removeLineIfEmpty=false)
RemoveText - Remove the specified text.
Definition: Rewriter.cpp:61
unsigned * SourceLineCache
A bump pointer allocated array of offsets for each source line.
std::map< FileID, RewriteBuffer >::iterator buffer_iterator
Definition: Rewriter.h:54
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...
Dataflow Directional Tag Classes.
bool isValid() const
Return true if this is a valid SourceLocation object.
RopePieceBTreeIterator - This class provides read-only forward iteration over bytes that are in a Rop...
Definition: RewriteRope.h:86
static int getRangeSize(const SourceManager &Sources, const CharSourceRange &Range, const LangOptions &LangOpts)
bool IncludeInsertsAtBeginOfRange
Given a source range, true to include previous inserts at the beginning of the range as part of the r...
Definition: Rewriter.h:41
SourceLocation getEnd() const
Defines the clang::SourceLocation class and associated facilities.
Defines the Diagnostic IDs-related interfaces.
A trivial tuple used to represent a source range.
bool InsertTextAfterToken(SourceLocation Loc, StringRef Str)
Insert the specified string after the token in the specified location.
Definition: Rewriter.cpp:282
SourceLocation getBegin() const
bool IncludeInsertsAtEndOfRange
Given a source range, true to include previous inserts at the end of the range as part of the range i...
Definition: Rewriter.h:45