Coverage Report

Created: 2019-03-22 08:08

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/tools/clang/lib/Rewrite/Rewriter.cpp
Line
Count
Source (jump to first uncovered line)
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
14
#include "clang/Rewrite/Core/Rewriter.h"
15
#include "clang/Basic/Diagnostic.h"
16
#include "clang/Basic/DiagnosticIDs.h"
17
#include "clang/Basic/FileManager.h"
18
#include "clang/Basic/SourceLocation.h"
19
#include "clang/Basic/SourceManager.h"
20
#include "clang/Lex/Lexer.h"
21
#include "clang/Rewrite/Core/RewriteBuffer.h"
22
#include "clang/Rewrite/Core/RewriteRope.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
12.4k
raw_ostream &RewriteBuffer::write(raw_ostream &os) const {
38
12.4k
  // Walk RewriteRope chunks efficiently using MoveToNextPiece() instead of the
39
12.4k
  // character iterator.
40
99.3k
  for (RopePieceBTreeIterator I = begin(), E = end(); I != E;
41
86.8k
       I.MoveToNextPiece())
42
86.8k
    os << I.piece();
43
12.4k
  return os;
44
12.4k
}
45
46
/// Return true if this character is non-new-line whitespace:
47
/// ' ', '\\t', '\\f', '\\v', '\\r'.
48
1.70k
static inline bool isWhitespaceExceptNL(unsigned char c) {
49
1.70k
  switch (c) {
50
1.70k
  case ' ':
51
1.19k
  case '\t':
52
1.19k
  case '\f':
53
1.19k
  case '\v':
54
1.19k
  case '\r':
55
1.19k
    return true;
56
1.19k
  default:
57
504
    return false;
58
1.70k
  }
59
1.70k
}
60
61
void RewriteBuffer::RemoveText(unsigned OrigOffset, unsigned Size,
62
403
                               bool removeLineIfEmpty) {
63
403
  // Nothing to remove, exit early.
64
403
  if (Size == 0) 
return0
;
65
403
66
403
  unsigned RealOffset = getMappedOffset(OrigOffset, true);
67
403
  assert(RealOffset+Size <= Buffer.size() && "Invalid location");
68
403
69
403
  // Remove the dead characters.
70
403
  Buffer.erase(RealOffset, Size);
71
403
72
403
  // Add a delta so that future changes are offset correctly.
73
403
  AddReplaceDelta(OrigOffset, -Size);
74
403
75
403
  if (removeLineIfEmpty) {
76
402
    // Find the line that the remove occurred and if it is completely empty
77
402
    // remove the line as well.
78
402
79
402
    iterator curLineStart = begin();
80
402
    unsigned curLineStartOffs = 0;
81
402
    iterator posI = begin();
82
349k
    for (unsigned i = 0; i != RealOffset; 
++i349k
) {
83
349k
      if (*posI == '\n') {
84
16.6k
        curLineStart = posI;
85
16.6k
        ++curLineStart;
86
16.6k
        curLineStartOffs = i + 1;
87
16.6k
      }
88
349k
      ++posI;
89
349k
    }
90
402
91
402
    unsigned lineSize = 0;
92
402
    posI = curLineStart;
93
1.31k
    while (posI != end() && isWhitespaceExceptNL(*posI)) {
94
910
      ++posI;
95
910
      ++lineSize;
96
910
    }
97
402
    if (posI != end() && *posI == '\n') {
98
74
      Buffer.erase(curLineStartOffs, lineSize + 1/* + '\n'*/);
99
74
      AddReplaceDelta(curLineStartOffs, -(lineSize + 1/* + '\n'*/));
100
74
    }
101
402
  }
102
403
}
103
104
void RewriteBuffer::InsertText(unsigned OrigOffset, StringRef Str,
105
76.0k
                               bool InsertAfter) {
106
76.0k
  // Nothing to insert, exit early.
107
76.0k
  if (Str.empty()) 
return0
;
108
76.0k
109
76.0k
  unsigned RealOffset = getMappedOffset(OrigOffset, InsertAfter);
110
76.0k
  Buffer.insert(RealOffset, Str.begin(), Str.end());
111
76.0k
112
76.0k
  // Add a delta so that future changes are offset correctly.
113
76.0k
  AddInsertDelta(OrigOffset, Str.size());
114
76.0k
}
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
44.2k
                                StringRef NewStr) {
121
44.2k
  unsigned RealOffset = getMappedOffset(OrigOffset, true);
122
44.2k
  Buffer.erase(RealOffset, OrigLength);
123
44.2k
  Buffer.insert(RealOffset, NewStr.begin(), NewStr.end());
124
44.2k
  if (OrigLength != NewStr.size())
125
34.5k
    AddReplaceDelta(OrigOffset, NewStr.size() - OrigLength);
126
44.2k
}
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.
134
int Rewriter::getRangeSize(const CharSourceRange &Range,
135
2.68k
                           RewriteOptions opts) const {
136
2.68k
  if (!isRewritable(Range.getBegin()) ||
137
2.68k
      !isRewritable(Range.getEnd())) 
return -10
;
138
2.68k
139
2.68k
  FileID StartFileID, EndFileID;
140
2.68k
  unsigned StartOff = getLocationOffsetAndFileID(Range.getBegin(), StartFileID);
141
2.68k
  unsigned EndOff = getLocationOffsetAndFileID(Range.getEnd(), EndFileID);
142
2.68k
143
2.68k
  if (StartFileID != EndFileID)
144
0
    return -1;
145
2.68k
146
2.68k
  // If edits have been made to this buffer, the delta between the range may
147
2.68k
  // have changed.
148
2.68k
  std::map<FileID, RewriteBuffer>::const_iterator I =
149
2.68k
    RewriteBuffers.find(StartFileID);
150
2.68k
  if (I != RewriteBuffers.end()) {
151
2.56k
    const RewriteBuffer &RB = I->second;
152
2.56k
    EndOff = RB.getMappedOffset(EndOff, opts.IncludeInsertsAtEndOfRange);
153
2.56k
    StartOff = RB.getMappedOffset(StartOff, !opts.IncludeInsertsAtBeginOfRange);
154
2.56k
  }
155
2.68k
156
2.68k
  // Adjust the end offset to the end of the last token, instead of being the
157
2.68k
  // start of the last token if this is a token range.
158
2.68k
  if (Range.isTokenRange())
159
674
    EndOff += Lexer::MeasureTokenLength(Range.getEnd(), *SourceMgr, *LangOpts);
160
2.68k
161
2.68k
  return EndOff-StartOff;
162
2.68k
}
163
164
674
int Rewriter::getRangeSize(SourceRange Range, RewriteOptions opts) const {
165
674
  return getRangeSize(CharSourceRange::getTokenRange(Range), opts);
166
674
}
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
172
std::string Rewriter::getRewrittenText(SourceRange Range) const {
174
172
  if (!isRewritable(Range.getBegin()) ||
175
172
      !isRewritable(Range.getEnd()))
176
0
    return {};
177
172
178
172
  FileID StartFileID, EndFileID;
179
172
  unsigned StartOff, EndOff;
180
172
  StartOff = getLocationOffsetAndFileID(Range.getBegin(), StartFileID);
181
172
  EndOff   = getLocationOffsetAndFileID(Range.getEnd(), EndFileID);
182
172
183
172
  if (StartFileID != EndFileID)
184
0
    return {}; // Start and end in different buffers.
185
172
186
172
  // If edits have been made to this buffer, the delta between the range may
187
172
  // have changed.
188
172
  std::map<FileID, RewriteBuffer>::const_iterator I =
189
172
    RewriteBuffers.find(StartFileID);
190
172
  if (I == RewriteBuffers.end()) {
191
24
    // If the buffer hasn't been rewritten, just return the text from the input.
192
24
    const char *Ptr = SourceMgr->getCharacterData(Range.getBegin());
193
24
194
24
    // Adjust the end offset to the end of the last token, instead of being the
195
24
    // start of the last token.
196
24
    EndOff += Lexer::MeasureTokenLength(Range.getEnd(), *SourceMgr, *LangOpts);
197
24
    return std::string(Ptr, Ptr+EndOff-StartOff);
198
24
  }
199
148
200
148
  const RewriteBuffer &RB = I->second;
201
148
  EndOff = RB.getMappedOffset(EndOff, true);
202
148
  StartOff = RB.getMappedOffset(StartOff);
203
148
204
148
  // Adjust the end offset to the end of the last token, instead of being the
205
148
  // start of the last token.
206
148
  EndOff += Lexer::MeasureTokenLength(Range.getEnd(), *SourceMgr, *LangOpts);
207
148
208
148
  // Advance the iterators to the right spot, yay for linear time algorithms.
209
148
  RewriteBuffer::iterator Start = RB.begin();
210
148
  std::advance(Start, StartOff);
211
148
  RewriteBuffer::iterator End = Start;
212
148
  std::advance(End, EndOff-StartOff);
213
148
214
148
  return std::string(Start, End);
215
148
}
216
217
unsigned Rewriter::getLocationOffsetAndFileID(SourceLocation Loc,
218
50.2k
                                              FileID &FID) const {
219
50.2k
  assert(Loc.isValid() && "Invalid location");
220
50.2k
  std::pair<FileID, unsigned> V = SourceMgr->getDecomposedLoc(Loc);
221
50.2k
  FID = V.first;
222
50.2k
  return V.second;
223
50.2k
}
224
225
/// getEditBuffer - Get or create a RewriteBuffer for the specified FileID.
226
57.6k
RewriteBuffer &Rewriter::getEditBuffer(FileID FID) {
227
57.6k
  std::map<FileID, RewriteBuffer>::iterator I =
228
57.6k
    RewriteBuffers.lower_bound(FID);
229
57.6k
  if (I != RewriteBuffers.end() && 
I->first == FID44.6k
)
230
44.6k
    return I->second;
231
12.9k
  I = RewriteBuffers.insert(I, std::make_pair(FID, RewriteBuffer()));
232
12.9k
233
12.9k
  StringRef MB = SourceMgr->getBufferData(FID);
234
12.9k
  I->second.Initialize(MB.begin(), MB.end());
235
12.9k
236
12.9k
  return I->second;
237
12.9k
}
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
3.14k
                          bool InsertAfter, bool indentNewLines) {
243
3.14k
  if (!isRewritable(Loc)) 
return true0
;
244
3.14k
  FileID FID;
245
3.14k
  unsigned StartOffs = getLocationOffsetAndFileID(Loc, FID);
246
3.14k
247
3.14k
  SmallString<128> indentedStr;
248
3.14k
  if (indentNewLines && 
Str.find('\n') != StringRef::npos313
) {
249
12
    StringRef MB = SourceMgr->getBufferData(FID);
250
12
251
12
    unsigned lineNo = SourceMgr->getLineNumber(FID, StartOffs) - 1;
252
12
    const SrcMgr::ContentCache *
253
12
        Content = SourceMgr->getSLocEntry(FID).getFile().getContentCache();
254
12
    unsigned lineOffs = Content->SourceLineCache[lineNo];
255
12
256
12
    // Find the whitespace at the start of the line.
257
12
    StringRef indentSpace;
258
12
    {
259
12
      unsigned i = lineOffs;
260
22
      while (isWhitespaceExceptNL(MB[i]))
261
10
        ++i;
262
12
      indentSpace = MB.substr(lineOffs, i-lineOffs);
263
12
    }
264
12
265
12
    SmallVector<StringRef, 4> lines;
266
12
    Str.split(lines, "\n");
267
12
268
54
    for (unsigned i = 0, e = lines.size(); i != e; 
++i42
) {
269
42
      indentedStr += lines[i];
270
42
      if (i < e-1) {
271
30
        indentedStr += '\n';
272
30
        indentedStr += indentSpace;
273
30
      }
274
42
    }
275
12
    Str = indentedStr.str();
276
12
  }
277
3.14k
278
3.14k
  getEditBuffer(FID).InsertText(StartOffs, Str, InsertAfter);
279
3.14k
  return false;
280
3.14k
}
281
282
0
bool Rewriter::InsertTextAfterToken(SourceLocation Loc, StringRef Str) {
283
0
  if (!isRewritable(Loc)) return true;
284
0
  FileID FID;
285
0
  unsigned StartOffs = getLocationOffsetAndFileID(Loc, FID);
286
0
  RewriteOptions rangeOpts;
287
0
  rangeOpts.IncludeInsertsAtBeginOfRange = false;
288
0
  StartOffs += getRangeSize(SourceRange(Loc, Loc), rangeOpts);
289
0
  getEditBuffer(FID).InsertText(StartOffs, Str, /*InsertAfter*/true);
290
0
  return false;
291
0
}
292
293
/// RemoveText - Remove the specified text region.
294
bool Rewriter::RemoveText(SourceLocation Start, unsigned Length,
295
402
                          RewriteOptions opts) {
296
402
  if (!isRewritable(Start)) 
return true0
;
297
402
  FileID FID;
298
402
  unsigned StartOffs = getLocationOffsetAndFileID(Start, FID);
299
402
  getEditBuffer(FID).RemoveText(StartOffs, Length, opts.RemoveLineIfEmpty);
300
402
  return false;
301
402
}
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
40.9k
                           StringRef NewStr) {
308
40.9k
  if (!isRewritable(Start)) 
return true0
;
309
40.9k
  FileID StartFileID;
310
40.9k
  unsigned StartOffs = getLocationOffsetAndFileID(Start, StartFileID);
311
40.9k
312
40.9k
  getEditBuffer(StartFileID).ReplaceText(StartOffs, OrigLength, NewStr);
313
40.9k
  return false;
314
40.9k
}
315
316
0
bool Rewriter::ReplaceText(SourceRange range, SourceRange replacementRange) {
317
0
  if (!isRewritable(range.getBegin())) return true;
318
0
  if (!isRewritable(range.getEnd())) return true;
319
0
  if (replacementRange.isInvalid()) return true;
320
0
  SourceLocation start = range.getBegin();
321
0
  unsigned origLength = getRangeSize(range);
322
0
  unsigned newLength = getRangeSize(replacementRange);
323
0
  FileID FID;
324
0
  unsigned newOffs = getLocationOffsetAndFileID(replacementRange.getBegin(),
325
0
                                                FID);
326
0
  StringRef MB = SourceMgr->getBufferData(FID);
327
0
  return ReplaceText(start, origLength, MB.substr(newOffs, newLength));
328
0
}
329
330
bool Rewriter::IncreaseIndentation(CharSourceRange range,
331
16
                                   SourceLocation parentIndent) {
332
16
  if (range.isInvalid()) 
return true0
;
333
16
  if (!isRewritable(range.getBegin())) 
return true0
;
334
16
  if (!isRewritable(range.getEnd())) 
return true0
;
335
16
  if (!isRewritable(parentIndent)) 
return true0
;
336
16
337
16
  FileID StartFileID, EndFileID, parentFileID;
338
16
  unsigned StartOff, EndOff, parentOff;
339
16
340
16
  StartOff = getLocationOffsetAndFileID(range.getBegin(), StartFileID);
341
16
  EndOff   = getLocationOffsetAndFileID(range.getEnd(), EndFileID);
342
16
  parentOff = getLocationOffsetAndFileID(parentIndent, parentFileID);
343
16
344
16
  if (StartFileID != EndFileID || StartFileID != parentFileID)
345
0
    return true;
346
16
  if (StartOff > EndOff)
347
0
    return true;
348
16
349
16
  FileID FID = StartFileID;
350
16
  StringRef MB = SourceMgr->getBufferData(FID);
351
16
352
16
  unsigned parentLineNo = SourceMgr->getLineNumber(FID, parentOff) - 1;
353
16
  unsigned startLineNo = SourceMgr->getLineNumber(FID, StartOff) - 1;
354
16
  unsigned endLineNo = SourceMgr->getLineNumber(FID, EndOff) - 1;
355
16
356
16
  const SrcMgr::ContentCache *
357
16
      Content = SourceMgr->getSLocEntry(FID).getFile().getContentCache();
358
16
359
16
  // Find where the lines start.
360
16
  unsigned parentLineOffs = Content->SourceLineCache[parentLineNo];
361
16
  unsigned startLineOffs = Content->SourceLineCache[startLineNo];
362
16
363
16
  // Find the whitespace at the start of each line.
364
16
  StringRef parentSpace, startSpace;
365
16
  {
366
16
    unsigned i = parentLineOffs;
367
26
    while (isWhitespaceExceptNL(MB[i]))
368
10
      ++i;
369
16
    parentSpace = MB.substr(parentLineOffs, i-parentLineOffs);
370
16
371
16
    i = startLineOffs;
372
76
    while (isWhitespaceExceptNL(MB[i]))
373
60
      ++i;
374
16
    startSpace = MB.substr(startLineOffs, i-startLineOffs);
375
16
  }
376
16
  if (parentSpace.size() >= startSpace.size())
377
0
    return true;
378
16
  if (!startSpace.startswith(parentSpace))
379
0
    return true;
380
16
381
16
  StringRef indent = startSpace.substr(parentSpace.size());
382
16
383
16
  // Indent the lines between start/end offsets.
384
16
  RewriteBuffer &RB = getEditBuffer(FID);
385
74
  for (unsigned lineNo = startLineNo; lineNo <= endLineNo; 
++lineNo58
) {
386
58
    unsigned offs = Content->SourceLineCache[lineNo];
387
58
    unsigned i = offs;
388
264
    while (isWhitespaceExceptNL(MB[i]))
389
206
      ++i;
390
58
    StringRef origIndent = MB.substr(offs, i-offs);
391
58
    if (origIndent.startswith(startSpace))
392
53
      RB.InsertText(offs, indent, /*InsertAfter=*/false);
393
58
  }
394
16
395
16
  return false;
396
16
}
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
59
      : Diagnostics(Diagnostics), Filename(Filename), AllWritten(AllWritten) {
411
59
    TempFilename = Filename;
412
59
    TempFilename += "-%%%%%%%%";
413
59
    int FD;
414
59
    if (llvm::sys::fs::createUniqueFile(TempFilename, FD, TempFilename)) {
415
1
      AllWritten = false;
416
1
      Diagnostics.Report(clang::diag::err_unable_to_make_temp)
417
1
        << TempFilename;
418
58
    } else {
419
58
      FileStream.reset(new llvm::raw_fd_ostream(FD, /*shouldClose=*/true));
420
58
    }
421
59
  }
422
423
59
  ~AtomicallyMovedFile() {
424
59
    if (!ok()) 
return1
;
425
58
426
58
    // Close (will also flush) theFileStream.
427
58
    FileStream->close();
428
58
    if (std::error_code ec = llvm::sys::fs::rename(TempFilename, Filename)) {
429
0
      AllWritten = false;
430
0
      Diagnostics.Report(clang::diag::err_unable_to_rename_temp)
431
0
        << TempFilename << Filename << ec.message();
432
0
      // If the remove fails, there's not a lot we can do - this is already an
433
0
      // error.
434
0
      llvm::sys::fs::remove(TempFilename);
435
0
    }
436
58
  }
437
438
118
  bool ok() { return (bool)FileStream; }
439
58
  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
451
66
bool Rewriter::overwriteChangedFiles() {
452
66
  bool AllWritten = true;
453
125
  for (buffer_iterator I = buffer_begin(), E = buffer_end(); I != E; 
++I59
) {
454
59
    const FileEntry *Entry =
455
59
        getSourceMgr().getFileEntryForID(I->first);
456
59
    AtomicallyMovedFile File(getSourceMgr().getDiagnostics(), Entry->getName(),
457
59
                             AllWritten);
458
59
    if (File.ok()) {
459
58
      I->second.write(File.getStream());
460
58
    }
461
59
  }
462
66
  return !AllWritten;
463
66
}