Coverage Report

Created: 2019-07-24 05:18

/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
13.0k
raw_ostream &RewriteBuffer::write(raw_ostream &os) const {
38
13.0k
  // Walk RewriteRope chunks efficiently using MoveToNextPiece() instead of the
39
13.0k
  // character iterator.
40
103k
  for (RopePieceBTreeIterator I = begin(), E = end(); I != E;
41
90.4k
       I.MoveToNextPiece())
42
90.4k
    os << I.piece();
43
13.0k
  return os;
44
13.0k
}
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()) 
return2
;
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
45.7k
                                StringRef NewStr) {
121
45.7k
  unsigned RealOffset = getMappedOffset(OrigOffset, true);
122
45.7k
  Buffer.erase(RealOffset, OrigLength);
123
45.7k
  Buffer.insert(RealOffset, NewStr.begin(), NewStr.end());
124
45.7k
  if (OrigLength != NewStr.size())
125
35.6k
    AddReplaceDelta(OrigOffset, NewStr.size() - OrigLength);
126
45.7k
}
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.69k
                           RewriteOptions opts) const {
136
2.69k
  if (!isRewritable(Range.getBegin()) ||
137
2.69k
      !isRewritable(Range.getEnd())) 
return -10
;
138
2.69k
139
2.69k
  FileID StartFileID, EndFileID;
140
2.69k
  unsigned StartOff = getLocationOffsetAndFileID(Range.getBegin(), StartFileID);
141
2.69k
  unsigned EndOff = getLocationOffsetAndFileID(Range.getEnd(), EndFileID);
142
2.69k
143
2.69k
  if (StartFileID != EndFileID)
144
0
    return -1;
145
2.69k
146
2.69k
  // If edits have been made to this buffer, the delta between the range may
147
2.69k
  // have changed.
148
2.69k
  std::map<FileID, RewriteBuffer>::const_iterator I =
149
2.69k
    RewriteBuffers.find(StartFileID);
150
2.69k
  if (I != RewriteBuffers.end()) {
151
2.57k
    const RewriteBuffer &RB = I->second;
152
2.57k
    EndOff = RB.getMappedOffset(EndOff, opts.IncludeInsertsAtEndOfRange);
153
2.57k
    StartOff = RB.getMappedOffset(StartOff, !opts.IncludeInsertsAtBeginOfRange);
154
2.57k
  }
155
2.69k
156
2.69k
  // Adjust the end offset to the end of the last token, instead of being the
157
2.69k
  // start of the last token if this is a token range.
158
2.69k
  if (Range.isTokenRange())
159
676
    EndOff += Lexer::MeasureTokenLength(Range.getEnd(), *SourceMgr, *LangOpts);
160
2.69k
161
2.69k
  return EndOff-StartOff;
162
2.69k
}
163
164
675
int Rewriter::getRangeSize(SourceRange Range, RewriteOptions opts) const {
165
675
  return getRangeSize(CharSourceRange::getTokenRange(Range), opts);
166
675
}
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
181
std::string Rewriter::getRewrittenText(CharSourceRange Range) const {
174
181
  if (!isRewritable(Range.getBegin()) ||
175
181
      !isRewritable(Range.getEnd()))
176
0
    return {};
177
181
178
181
  FileID StartFileID, EndFileID;
179
181
  unsigned StartOff, EndOff;
180
181
  StartOff = getLocationOffsetAndFileID(Range.getBegin(), StartFileID);
181
181
  EndOff   = getLocationOffsetAndFileID(Range.getEnd(), EndFileID);
182
181
183
181
  if (StartFileID != EndFileID)
184
0
    return {}; // Start and end in different buffers.
185
181
186
181
  // If edits have been made to this buffer, the delta between the range may
187
181
  // have changed.
188
181
  std::map<FileID, RewriteBuffer>::const_iterator I =
189
181
    RewriteBuffers.find(StartFileID);
190
181
  if (I == RewriteBuffers.end()) {
191
27
    // If the buffer hasn't been rewritten, just return the text from the input.
192
27
    const char *Ptr = SourceMgr->getCharacterData(Range.getBegin());
193
27
194
27
    // Adjust the end offset to the end of the last token, instead of being the
195
27
    // start of the last token.
196
27
    if (Range.isTokenRange())
197
26
      EndOff +=
198
26
          Lexer::MeasureTokenLength(Range.getEnd(), *SourceMgr, *LangOpts);
199
27
    return std::string(Ptr, Ptr+EndOff-StartOff);
200
27
  }
201
154
202
154
  const RewriteBuffer &RB = I->second;
203
154
  EndOff = RB.getMappedOffset(EndOff, true);
204
154
  StartOff = RB.getMappedOffset(StartOff);
205
154
206
154
  // Adjust the end offset to the end of the last token, instead of being the
207
154
  // start of the last token.
208
154
  if (Range.isTokenRange())
209
150
    EndOff += Lexer::MeasureTokenLength(Range.getEnd(), *SourceMgr, *LangOpts);
210
154
211
154
  // Advance the iterators to the right spot, yay for linear time algorithms.
212
154
  RewriteBuffer::iterator Start = RB.begin();
213
154
  std::advance(Start, StartOff);
214
154
  RewriteBuffer::iterator End = Start;
215
154
  std::advance(End, EndOff-StartOff);
216
154
217
154
  return std::string(Start, End);
218
154
}
219
220
unsigned Rewriter::getLocationOffsetAndFileID(SourceLocation Loc,
221
51.8k
                                              FileID &FID) const {
222
51.8k
  assert(Loc.isValid() && "Invalid location");
223
51.8k
  std::pair<FileID, unsigned> V = SourceMgr->getDecomposedLoc(Loc);
224
51.8k
  FID = V.first;
225
51.8k
  return V.second;
226
51.8k
}
227
228
/// getEditBuffer - Get or create a RewriteBuffer for the specified FileID.
229
59.6k
RewriteBuffer &Rewriter::getEditBuffer(FileID FID) {
230
59.6k
  std::map<FileID, RewriteBuffer>::iterator I =
231
59.6k
    RewriteBuffers.lower_bound(FID);
232
59.6k
  if (I != RewriteBuffers.end() && 
I->first == FID46.2k
)
233
46.1k
    return I->second;
234
13.5k
  I = RewriteBuffers.insert(I, std::make_pair(FID, RewriteBuffer()));
235
13.5k
236
13.5k
  StringRef MB = SourceMgr->getBufferData(FID);
237
13.5k
  I->second.Initialize(MB.begin(), MB.end());
238
13.5k
239
13.5k
  return I->second;
240
13.5k
}
241
242
/// InsertText - Insert the specified string at the specified location in the
243
/// original buffer.
244
bool Rewriter::InsertText(SourceLocation Loc, StringRef Str,
245
3.15k
                          bool InsertAfter, bool indentNewLines) {
246
3.15k
  if (!isRewritable(Loc)) 
return true0
;
247
3.15k
  FileID FID;
248
3.15k
  unsigned StartOffs = getLocationOffsetAndFileID(Loc, FID);
249
3.15k
250
3.15k
  SmallString<128> indentedStr;
251
3.15k
  if (indentNewLines && 
Str.find('\n') != StringRef::npos313
) {
252
12
    StringRef MB = SourceMgr->getBufferData(FID);
253
12
254
12
    unsigned lineNo = SourceMgr->getLineNumber(FID, StartOffs) - 1;
255
12
    const SrcMgr::ContentCache *
256
12
        Content = SourceMgr->getSLocEntry(FID).getFile().getContentCache();
257
12
    unsigned lineOffs = Content->SourceLineCache[lineNo];
258
12
259
12
    // Find the whitespace at the start of the line.
260
12
    StringRef indentSpace;
261
12
    {
262
12
      unsigned i = lineOffs;
263
22
      while (isWhitespaceExceptNL(MB[i]))
264
10
        ++i;
265
12
      indentSpace = MB.substr(lineOffs, i-lineOffs);
266
12
    }
267
12
268
12
    SmallVector<StringRef, 4> lines;
269
12
    Str.split(lines, "\n");
270
12
271
54
    for (unsigned i = 0, e = lines.size(); i != e; 
++i42
) {
272
42
      indentedStr += lines[i];
273
42
      if (i < e-1) {
274
30
        indentedStr += '\n';
275
30
        indentedStr += indentSpace;
276
30
      }
277
42
    }
278
12
    Str = indentedStr.str();
279
12
  }
280
3.15k
281
3.15k
  getEditBuffer(FID).InsertText(StartOffs, Str, InsertAfter);
282
3.15k
  return false;
283
3.15k
}
284
285
0
bool Rewriter::InsertTextAfterToken(SourceLocation Loc, StringRef Str) {
286
0
  if (!isRewritable(Loc)) return true;
287
0
  FileID FID;
288
0
  unsigned StartOffs = getLocationOffsetAndFileID(Loc, FID);
289
0
  RewriteOptions rangeOpts;
290
0
  rangeOpts.IncludeInsertsAtBeginOfRange = false;
291
0
  StartOffs += getRangeSize(SourceRange(Loc, Loc), rangeOpts);
292
0
  getEditBuffer(FID).InsertText(StartOffs, Str, /*InsertAfter*/true);
293
0
  return false;
294
0
}
295
296
/// RemoveText - Remove the specified text region.
297
bool Rewriter::RemoveText(SourceLocation Start, unsigned Length,
298
402
                          RewriteOptions opts) {
299
402
  if (!isRewritable(Start)) 
return true0
;
300
402
  FileID FID;
301
402
  unsigned StartOffs = getLocationOffsetAndFileID(Start, FID);
302
402
  getEditBuffer(FID).RemoveText(StartOffs, Length, opts.RemoveLineIfEmpty);
303
402
  return false;
304
402
}
305
306
/// ReplaceText - This method replaces a range of characters in the input
307
/// buffer with a new string.  This is effectively a combined "remove/insert"
308
/// operation.
309
bool Rewriter::ReplaceText(SourceLocation Start, unsigned OrigLength,
310
42.4k
                           StringRef NewStr) {
311
42.4k
  if (!isRewritable(Start)) 
return true0
;
312
42.4k
  FileID StartFileID;
313
42.4k
  unsigned StartOffs = getLocationOffsetAndFileID(Start, StartFileID);
314
42.4k
315
42.4k
  getEditBuffer(StartFileID).ReplaceText(StartOffs, OrigLength, NewStr);
316
42.4k
  return false;
317
42.4k
}
318
319
0
bool Rewriter::ReplaceText(SourceRange range, SourceRange replacementRange) {
320
0
  if (!isRewritable(range.getBegin())) return true;
321
0
  if (!isRewritable(range.getEnd())) return true;
322
0
  if (replacementRange.isInvalid()) return true;
323
0
  SourceLocation start = range.getBegin();
324
0
  unsigned origLength = getRangeSize(range);
325
0
  unsigned newLength = getRangeSize(replacementRange);
326
0
  FileID FID;
327
0
  unsigned newOffs = getLocationOffsetAndFileID(replacementRange.getBegin(),
328
0
                                                FID);
329
0
  StringRef MB = SourceMgr->getBufferData(FID);
330
0
  return ReplaceText(start, origLength, MB.substr(newOffs, newLength));
331
0
}
332
333
bool Rewriter::IncreaseIndentation(CharSourceRange range,
334
16
                                   SourceLocation parentIndent) {
335
16
  if (range.isInvalid()) 
return true0
;
336
16
  if (!isRewritable(range.getBegin())) 
return true0
;
337
16
  if (!isRewritable(range.getEnd())) 
return true0
;
338
16
  if (!isRewritable(parentIndent)) 
return true0
;
339
16
340
16
  FileID StartFileID, EndFileID, parentFileID;
341
16
  unsigned StartOff, EndOff, parentOff;
342
16
343
16
  StartOff = getLocationOffsetAndFileID(range.getBegin(), StartFileID);
344
16
  EndOff   = getLocationOffsetAndFileID(range.getEnd(), EndFileID);
345
16
  parentOff = getLocationOffsetAndFileID(parentIndent, parentFileID);
346
16
347
16
  if (StartFileID != EndFileID || StartFileID != parentFileID)
348
0
    return true;
349
16
  if (StartOff > EndOff)
350
0
    return true;
351
16
352
16
  FileID FID = StartFileID;
353
16
  StringRef MB = SourceMgr->getBufferData(FID);
354
16
355
16
  unsigned parentLineNo = SourceMgr->getLineNumber(FID, parentOff) - 1;
356
16
  unsigned startLineNo = SourceMgr->getLineNumber(FID, StartOff) - 1;
357
16
  unsigned endLineNo = SourceMgr->getLineNumber(FID, EndOff) - 1;
358
16
359
16
  const SrcMgr::ContentCache *
360
16
      Content = SourceMgr->getSLocEntry(FID).getFile().getContentCache();
361
16
362
16
  // Find where the lines start.
363
16
  unsigned parentLineOffs = Content->SourceLineCache[parentLineNo];
364
16
  unsigned startLineOffs = Content->SourceLineCache[startLineNo];
365
16
366
16
  // Find the whitespace at the start of each line.
367
16
  StringRef parentSpace, startSpace;
368
16
  {
369
16
    unsigned i = parentLineOffs;
370
26
    while (isWhitespaceExceptNL(MB[i]))
371
10
      ++i;
372
16
    parentSpace = MB.substr(parentLineOffs, i-parentLineOffs);
373
16
374
16
    i = startLineOffs;
375
76
    while (isWhitespaceExceptNL(MB[i]))
376
60
      ++i;
377
16
    startSpace = MB.substr(startLineOffs, i-startLineOffs);
378
16
  }
379
16
  if (parentSpace.size() >= startSpace.size())
380
0
    return true;
381
16
  if (!startSpace.startswith(parentSpace))
382
0
    return true;
383
16
384
16
  StringRef indent = startSpace.substr(parentSpace.size());
385
16
386
16
  // Indent the lines between start/end offsets.
387
16
  RewriteBuffer &RB = getEditBuffer(FID);
388
74
  for (unsigned lineNo = startLineNo; lineNo <= endLineNo; 
++lineNo58
) {
389
58
    unsigned offs = Content->SourceLineCache[lineNo];
390
58
    unsigned i = offs;
391
264
    while (isWhitespaceExceptNL(MB[i]))
392
206
      ++i;
393
58
    StringRef origIndent = MB.substr(offs, i-offs);
394
58
    if (origIndent.startswith(startSpace))
395
53
      RB.InsertText(offs, indent, /*InsertAfter=*/false);
396
58
  }
397
16
398
16
  return false;
399
16
}
400
401
namespace {
402
403
// A wrapper for a file stream that atomically overwrites the target.
404
//
405
// Creates a file output stream for a temporary file in the constructor,
406
// which is later accessible via getStream() if ok() return true.
407
// Flushes the stream and moves the temporary file to the target location
408
// in the destructor.
409
class AtomicallyMovedFile {
410
public:
411
  AtomicallyMovedFile(DiagnosticsEngine &Diagnostics, StringRef Filename,
412
                      bool &AllWritten)
413
60
      : Diagnostics(Diagnostics), Filename(Filename), AllWritten(AllWritten) {
414
60
    TempFilename = Filename;
415
60
    TempFilename += "-%%%%%%%%";
416
60
    int FD;
417
60
    if (llvm::sys::fs::createUniqueFile(TempFilename, FD, TempFilename)) {
418
1
      AllWritten = false;
419
1
      Diagnostics.Report(clang::diag::err_unable_to_make_temp)
420
1
        << TempFilename;
421
59
    } else {
422
59
      FileStream.reset(new llvm::raw_fd_ostream(FD, /*shouldClose=*/true));
423
59
    }
424
60
  }
425
426
60
  ~AtomicallyMovedFile() {
427
60
    if (!ok()) 
return1
;
428
59
429
59
    // Close (will also flush) theFileStream.
430
59
    FileStream->close();
431
59
    if (std::error_code ec = llvm::sys::fs::rename(TempFilename, Filename)) {
432
0
      AllWritten = false;
433
0
      Diagnostics.Report(clang::diag::err_unable_to_rename_temp)
434
0
        << TempFilename << Filename << ec.message();
435
0
      // If the remove fails, there's not a lot we can do - this is already an
436
0
      // error.
437
0
      llvm::sys::fs::remove(TempFilename);
438
0
    }
439
59
  }
440
441
120
  bool ok() { return (bool)FileStream; }
442
59
  raw_ostream &getStream() { return *FileStream; }
443
444
private:
445
  DiagnosticsEngine &Diagnostics;
446
  StringRef Filename;
447
  SmallString<128> TempFilename;
448
  std::unique_ptr<llvm::raw_fd_ostream> FileStream;
449
  bool &AllWritten;
450
};
451
452
} // namespace
453
454
67
bool Rewriter::overwriteChangedFiles() {
455
67
  bool AllWritten = true;
456
127
  for (buffer_iterator I = buffer_begin(), E = buffer_end(); I != E; 
++I60
) {
457
60
    const FileEntry *Entry =
458
60
        getSourceMgr().getFileEntryForID(I->first);
459
60
    AtomicallyMovedFile File(getSourceMgr().getDiagnostics(), Entry->getName(),
460
60
                             AllWritten);
461
60
    if (File.ok()) {
462
59
      I->second.write(File.getStream());
463
59
    }
464
60
  }
465
67
  return !AllWritten;
466
67
}