Coverage Report

Created: 2020-02-15 09:57

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/Tooling/Core/Replacement.cpp
Line
Count
Source (jump to first uncovered line)
1
//===- Replacement.cpp - Framework for clang refactoring tools ------------===//
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
//  Implements classes to support/store refactorings.
10
//
11
//===----------------------------------------------------------------------===//
12
13
#include "clang/Tooling/Core/Replacement.h"
14
#include "clang/Basic/Diagnostic.h"
15
#include "clang/Basic/DiagnosticIDs.h"
16
#include "clang/Basic/DiagnosticOptions.h"
17
#include "clang/Basic/FileManager.h"
18
#include "clang/Basic/FileSystemOptions.h"
19
#include "clang/Basic/SourceLocation.h"
20
#include "clang/Basic/SourceManager.h"
21
#include "clang/Lex/Lexer.h"
22
#include "clang/Rewrite/Core/RewriteBuffer.h"
23
#include "clang/Rewrite/Core/Rewriter.h"
24
#include "llvm/ADT/IntrusiveRefCntPtr.h"
25
#include "llvm/ADT/SmallPtrSet.h"
26
#include "llvm/ADT/StringRef.h"
27
#include "llvm/Support/Error.h"
28
#include "llvm/Support/ErrorHandling.h"
29
#include "llvm/Support/MemoryBuffer.h"
30
#include "llvm/Support/VirtualFileSystem.h"
31
#include "llvm/Support/raw_ostream.h"
32
#include <algorithm>
33
#include <cassert>
34
#include <limits>
35
#include <map>
36
#include <string>
37
#include <utility>
38
#include <vector>
39
40
using namespace clang;
41
using namespace tooling;
42
43
static const char * const InvalidLocation = "";
44
45
13
Replacement::Replacement() : FilePath(InvalidLocation) {}
46
47
Replacement::Replacement(StringRef FilePath, unsigned Offset, unsigned Length,
48
                         StringRef ReplacementText)
49
    : FilePath(std::string(FilePath)), ReplacementRange(Offset, Length),
50
104k
      ReplacementText(std::string(ReplacementText)) {}
51
52
Replacement::Replacement(const SourceManager &Sources, SourceLocation Start,
53
369
                         unsigned Length, StringRef ReplacementText) {
54
369
  setFromSourceLocation(Sources, Start, Length, ReplacementText);
55
369
}
56
57
Replacement::Replacement(const SourceManager &Sources,
58
                         const CharSourceRange &Range,
59
                         StringRef ReplacementText,
60
20.5k
                         const LangOptions &LangOpts) {
61
20.5k
  setFromSourceRange(Sources, Range, ReplacementText, LangOpts);
62
20.5k
}
63
64
2.56k
bool Replacement::isApplicable() const {
65
2.56k
  return FilePath != InvalidLocation;
66
2.56k
}
67
68
41.4k
bool Replacement::apply(Rewriter &Rewrite) const {
69
41.4k
  SourceManager &SM = Rewrite.getSourceMgr();
70
41.4k
  auto Entry = SM.getFileManager().getFile(FilePath);
71
41.4k
  if (!Entry)
72
1
    return false;
73
41.4k
74
41.4k
  FileID ID = SM.getOrCreateFileID(*Entry, SrcMgr::C_User);
75
41.4k
  const SourceLocation Start =
76
41.4k
    SM.getLocForStartOfFile(ID).
77
41.4k
    getLocWithOffset(ReplacementRange.getOffset());
78
41.4k
  // ReplaceText returns false on success.
79
41.4k
  // ReplaceText only fails if the source location is not a file location, in
80
41.4k
  // which case we already returned false earlier.
81
41.4k
  bool RewriteSucceeded = !Rewrite.ReplaceText(
82
41.4k
      Start, ReplacementRange.getLength(), ReplacementText);
83
41.4k
  assert(RewriteSucceeded);
84
41.4k
  return RewriteSucceeded;
85
41.4k
}
86
87
6
std::string Replacement::toString() const {
88
6
  std::string Result;
89
6
  llvm::raw_string_ostream Stream(Result);
90
6
  Stream << FilePath << ": " << ReplacementRange.getOffset() << ":+"
91
6
         << ReplacementRange.getLength() << ":\"" << ReplacementText << "\"";
92
6
  return Stream.str();
93
6
}
94
95
namespace clang {
96
namespace tooling {
97
98
379k
bool operator<(const Replacement &LHS, const Replacement &RHS) {
99
379k
  if (LHS.getOffset() != RHS.getOffset())
100
379k
    return LHS.getOffset() < RHS.getOffset();
101
296
102
296
  if (LHS.getLength() != RHS.getLength())
103
50
    return LHS.getLength() < RHS.getLength();
104
246
105
246
  if (LHS.getFilePath() != RHS.getFilePath())
106
0
    return LHS.getFilePath() < RHS.getFilePath();
107
246
  return LHS.getReplacementText() < RHS.getReplacementText();
108
246
}
109
110
138
bool operator==(const Replacement &LHS, const Replacement &RHS) {
111
138
  return LHS.getOffset() == RHS.getOffset() &&
112
138
         LHS.getLength() == RHS.getLength() &&
113
138
         LHS.getFilePath() == RHS.getFilePath() &&
114
138
         LHS.getReplacementText() == RHS.getReplacementText();
115
138
}
116
117
} // namespace tooling
118
} // namespace clang
119
120
void Replacement::setFromSourceLocation(const SourceManager &Sources,
121
                                        SourceLocation Start, unsigned Length,
122
20.9k
                                        StringRef ReplacementText) {
123
20.9k
  const std::pair<FileID, unsigned> DecomposedLocation =
124
20.9k
      Sources.getDecomposedLoc(Start);
125
20.9k
  const FileEntry *Entry = Sources.getFileEntryForID(DecomposedLocation.first);
126
20.9k
  this->FilePath = std::string(Entry ? 
Entry->getName()20.9k
:
InvalidLocation6
);
127
20.9k
  this->ReplacementRange = Range(DecomposedLocation.second, Length);
128
20.9k
  this->ReplacementText = std::string(ReplacementText);
129
20.9k
}
130
131
// FIXME: This should go into the Lexer, but we need to figure out how
132
// to handle ranges for refactoring in general first - there is no obvious
133
// good way how to integrate this into the Lexer yet.
134
static int getRangeSize(const SourceManager &Sources,
135
                        const CharSourceRange &Range,
136
20.5k
                        const LangOptions &LangOpts) {
137
20.5k
  SourceLocation SpellingBegin = Sources.getSpellingLoc(Range.getBegin());
138
20.5k
  SourceLocation SpellingEnd = Sources.getSpellingLoc(Range.getEnd());
139
20.5k
  std::pair<FileID, unsigned> Start = Sources.getDecomposedLoc(SpellingBegin);
140
20.5k
  std::pair<FileID, unsigned> End = Sources.getDecomposedLoc(SpellingEnd);
141
20.5k
  if (Start.first != End.first) 
return -10
;
142
20.5k
  if (Range.isTokenRange())
143
733
    End.second += Lexer::MeasureTokenLength(SpellingEnd, Sources, LangOpts);
144
20.5k
  return End.second - Start.second;
145
20.5k
}
146
147
void Replacement::setFromSourceRange(const SourceManager &Sources,
148
                                     const CharSourceRange &Range,
149
                                     StringRef ReplacementText,
150
20.5k
                                     const LangOptions &LangOpts) {
151
20.5k
  setFromSourceLocation(Sources, Sources.getSpellingLoc(Range.getBegin()),
152
20.5k
                        getRangeSize(Sources, Range, LangOpts),
153
20.5k
                        ReplacementText);
154
20.5k
}
155
156
Replacement
157
168
Replacements::getReplacementInChangedCode(const Replacement &R) const {
158
168
  unsigned NewStart = getShiftedCodePosition(R.getOffset());
159
168
  unsigned NewEnd = getShiftedCodePosition(R.getOffset() + R.getLength());
160
168
  return Replacement(R.getFilePath(), NewStart, NewEnd - NewStart,
161
168
                     R.getReplacementText());
162
168
}
163
164
3
static std::string getReplacementErrString(replacement_error Err) {
165
3
  switch (Err) {
166
0
  case replacement_error::fail_to_apply:
167
0
    return "Failed to apply a replacement.";
168
0
  case replacement_error::wrong_file_path:
169
0
    return "The new replacement's file path is different from the file path of "
170
0
           "existing replacements";
171
2
  case replacement_error::overlap_conflict:
172
2
    return "The new replacement overlaps with an existing replacement.";
173
1
  case replacement_error::insert_conflict:
174
1
    return "The new insertion has the same insert location as an existing "
175
1
           "replacement.";
176
0
  }
177
0
  llvm_unreachable("A value of replacement_error has no message.");
178
0
}
179
180
3
std::string ReplacementError::message() const {
181
3
  std::string Message = getReplacementErrString(Err);
182
3
  if (NewReplacement.hasValue())
183
3
    Message += "\nNew replacement: " + NewReplacement->toString();
184
3
  if (ExistingReplacement.hasValue())
185
3
    Message += "\nExisting replacement: " + ExistingReplacement->toString();
186
3
  return Message;
187
3
}
188
189
char ReplacementError::ID = 0;
190
191
166
Replacements Replacements::getCanonicalReplacements() const {
192
166
  std::vector<Replacement> NewReplaces;
193
166
  // Merge adjacent replacements.
194
167
  for (const auto &R : Replaces) {
195
167
    if (NewReplaces.empty()) {
196
166
      NewReplaces.push_back(R);
197
166
      continue;
198
166
    }
199
1
    auto &Prev = NewReplaces.back();
200
1
    unsigned PrevEnd = Prev.getOffset() + Prev.getLength();
201
1
    if (PrevEnd < R.getOffset()) {
202
0
      NewReplaces.push_back(R);
203
1
    } else {
204
1
      assert(PrevEnd == R.getOffset() &&
205
1
             "Existing replacements must not overlap.");
206
1
      Replacement NewR(
207
1
          R.getFilePath(), Prev.getOffset(), Prev.getLength() + R.getLength(),
208
1
          (Prev.getReplacementText() + R.getReplacementText()).str());
209
1
      Prev = NewR;
210
1
    }
211
1
  }
212
166
  ReplacementsImpl NewReplacesImpl(NewReplaces.begin(), NewReplaces.end());
213
166
  return Replacements(NewReplacesImpl.begin(), NewReplacesImpl.end());
214
166
}
215
216
// `R` and `Replaces` are order-independent if applying them in either order
217
// has the same effect, so we need to compare replacements associated to
218
// applying them in either order.
219
llvm::Expected<Replacements>
220
83
Replacements::mergeIfOrderIndependent(const Replacement &R) const {
221
83
  Replacements Rs(R);
222
83
  // A Replacements set containing a single replacement that is `R` referring to
223
83
  // the code after the existing replacements `Replaces` are applied.
224
83
  Replacements RsShiftedByReplaces(getReplacementInChangedCode(R));
225
83
  // A Replacements set that is `Replaces` referring to the code after `R` is
226
83
  // applied.
227
83
  Replacements ReplacesShiftedByRs;
228
83
  for (const auto &Replace : Replaces)
229
85
    ReplacesShiftedByRs.Replaces.insert(
230
85
        Rs.getReplacementInChangedCode(Replace));
231
83
  // This is equivalent to applying `Replaces` first and then `R`.
232
83
  auto MergeShiftedRs = merge(RsShiftedByReplaces);
233
83
  // This is equivalent to applying `R` first and then `Replaces`.
234
83
  auto MergeShiftedReplaces = Rs.merge(ReplacesShiftedByRs);
235
83
236
83
  // Since empty or segmented replacements around existing replacements might be
237
83
  // produced above, we need to compare replacements in canonical forms.
238
83
  if (MergeShiftedRs.getCanonicalReplacements() ==
239
83
      MergeShiftedReplaces.getCanonicalReplacements())
240
75
    return MergeShiftedRs;
241
8
  return llvm::make_error<ReplacementError>(replacement_error::overlap_conflict,
242
8
                                            R, *Replaces.begin());
243
8
}
244
245
61.6k
llvm::Error Replacements::add(const Replacement &R) {
246
61.6k
  // Check the file path.
247
61.6k
  if (!Replaces.empty() && 
R.getFilePath() != Replaces.begin()->getFilePath()41.0k
)
248
4
    return llvm::make_error<ReplacementError>(
249
4
        replacement_error::wrong_file_path, R, *Replaces.begin());
250
61.6k
251
61.6k
  // Special-case header insertions.
252
61.6k
  if (R.getOffset() == std::numeric_limits<unsigned>::max()) {
253
74
    Replaces.insert(R);
254
74
    return llvm::Error::success();
255
74
  }
256
61.6k
257
61.6k
  // This replacement cannot conflict with replacements that end before
258
61.6k
  // this replacement starts or start after this replacement ends.
259
61.6k
  // We also know that there currently are no overlapping replacements.
260
61.6k
  // Thus, we know that all replacements that start after the end of the current
261
61.6k
  // replacement cannot overlap.
262
61.6k
  Replacement AtEnd(R.getFilePath(), R.getOffset() + R.getLength(), 0, "");
263
61.6k
264
61.6k
  // Find the first entry that starts after or at the end of R. Note that
265
61.6k
  // entries that start at the end can still be conflicting if R is an
266
61.6k
  // insertion.
267
61.6k
  auto I = Replaces.lower_bound(AtEnd);
268
61.6k
  // If `I` starts at the same offset as `R`, `R` must be an insertion.
269
61.6k
  if (I != Replaces.end() && 
R.getOffset() == I->getOffset()184
) {
270
30
    assert(R.getLength() == 0);
271
30
    // `I` is also an insertion, `R` and `I` conflict.
272
30
    if (I->getLength() == 0) {
273
25
      // Check if two insertions are order-indepedent: if inserting them in
274
25
      // either order produces the same text, they are order-independent.
275
25
      if ((R.getReplacementText() + I->getReplacementText()).str() !=
276
25
          (I->getReplacementText() + R.getReplacementText()).str())
277
21
        return llvm::make_error<ReplacementError>(
278
21
            replacement_error::insert_conflict, R, *I);
279
4
      // If insertions are order-independent, we can merge them.
280
4
      Replacement NewR(
281
4
          R.getFilePath(), R.getOffset(), 0,
282
4
          (R.getReplacementText() + I->getReplacementText()).str());
283
4
      Replaces.erase(I);
284
4
      Replaces.insert(std::move(NewR));
285
4
      return llvm::Error::success();
286
4
    }
287
5
    // Insertion `R` is adjacent to a non-insertion replacement `I`, so they
288
5
    // are order-independent. It is safe to assume that `R` will not conflict
289
5
    // with any replacement before `I` since all replacements before `I` must
290
5
    // either end before `R` or end at `R` but has length > 0 (if the
291
5
    // replacement before `I` is an insertion at `R`, it would have been `I`
292
5
    // since it is a lower bound of `AtEnd` and ordered before the current `I`
293
5
    // in the set).
294
5
    Replaces.insert(R);
295
5
    return llvm::Error::success();
296
5
  }
297
61.5k
298
61.5k
  // `I` is the smallest iterator (after `R`) whose entry cannot overlap.
299
61.5k
  // If that is begin(), there are no overlaps.
300
61.5k
  if (I == Replaces.begin()) {
301
20.6k
    Replaces.insert(R);
302
20.6k
    return llvm::Error::success();
303
20.6k
  }
304
40.9k
  --I;
305
40.9k
  auto Overlap = [](const Replacement &R1, const Replacement &R2) -> bool {
306
40.9k
    return Range(R1.getOffset(), R1.getLength())
307
40.9k
        .overlapsWith(Range(R2.getOffset(), R2.getLength()));
308
40.9k
  };
309
40.9k
  // If the previous entry does not overlap, we know that entries before it
310
40.9k
  // can also not overlap.
311
40.9k
  if (!Overlap(R, *I)) {
312
40.8k
    // If `R` and `I` do not have the same offset, it is safe to add `R` since
313
40.8k
    // it must come after `I`. Otherwise:
314
40.8k
    //   - If `R` is an insertion, `I` must not be an insertion since it would
315
40.8k
    //   have come after `AtEnd`.
316
40.8k
    //   - If `R` is not an insertion, `I` must be an insertion; otherwise, `R`
317
40.8k
    //   and `I` would have overlapped.
318
40.8k
    // In either case, we can safely insert `R`.
319
40.8k
    Replaces.insert(R);
320
40.8k
  } else {
321
83
    // `I` overlaps with `R`. We need to check `R` against all overlapping
322
83
    // replacements to see if they are order-indepedent. If they are, merge `R`
323
83
    // with them and replace them with the merged replacements.
324
83
    auto MergeBegin = I;
325
83
    auto MergeEnd = std::next(I);
326
85
    while (I != Replaces.begin()) {
327
22
      --I;
328
22
      // If `I` doesn't overlap with `R`, don't merge it.
329
22
      if (!Overlap(R, *I))
330
20
        break;
331
2
      MergeBegin = I;
332
2
    }
333
83
    Replacements OverlapReplaces(MergeBegin, MergeEnd);
334
83
    llvm::Expected<Replacements> Merged =
335
83
        OverlapReplaces.mergeIfOrderIndependent(R);
336
83
    if (!Merged)
337
8
      return Merged.takeError();
338
75
    Replaces.erase(MergeBegin, MergeEnd);
339
75
    Replaces.insert(Merged->begin(), Merged->end());
340
75
  }
341
40.9k
  
return llvm::Error::success()40.9k
;
342
40.9k
}
343
344
namespace {
345
346
// Represents a merged replacement, i.e. a replacement consisting of multiple
347
// overlapping replacements from 'First' and 'Second' in mergeReplacements.
348
//
349
// Position projection:
350
// Offsets and lengths of the replacements can generally refer to two different
351
// coordinate spaces. Replacements from 'First' refer to the original text
352
// whereas replacements from 'Second' refer to the text after applying 'First'.
353
//
354
// MergedReplacement always operates in the coordinate space of the original
355
// text, i.e. transforms elements from 'Second' to take into account what was
356
// changed based on the elements from 'First'.
357
//
358
// We can correctly calculate this projection as we look at the replacements in
359
// order of strictly increasing offsets.
360
//
361
// Invariants:
362
// * We always merge elements from 'First' into elements from 'Second' and vice
363
//   versa. Within each set, the replacements are non-overlapping.
364
// * We only extend to the right, i.e. merge elements with strictly increasing
365
//   offsets.
366
class MergedReplacement {
367
public:
368
  MergedReplacement(const Replacement &R, bool MergeSecond, int D)
369
      : MergeSecond(MergeSecond), Delta(D), FilePath(R.getFilePath()),
370
        Offset(R.getOffset() + (MergeSecond ? 0 : Delta)),
371
2.78k
        Length(R.getLength()), Text(std::string(R.getReplacementText())) {
372
2.78k
    Delta += MergeSecond ? 
0721
:
Text.size() - Length2.06k
;
373
2.78k
    DeltaFirst = MergeSecond ? 
Text.size() - Length721
:
02.06k
;
374
2.78k
  }
375
376
  // Merges the next element 'R' into this merged element. As we always merge
377
  // from 'First' into 'Second' or vice versa, the MergedReplacement knows what
378
  // set the next element is coming from.
379
908
  void merge(const Replacement &R) {
380
908
    if (MergeSecond) {
381
405
      unsigned REnd = R.getOffset() + Delta + R.getLength();
382
405
      unsigned End = Offset + Text.size();
383
405
      if (REnd > End) {
384
64
        Length += REnd - End;
385
64
        MergeSecond = false;
386
64
      }
387
405
      StringRef TextRef = Text;
388
405
      StringRef Head = TextRef.substr(0, R.getOffset() + Delta - Offset);
389
405
      StringRef Tail = TextRef.substr(REnd - Offset);
390
405
      Text = (Head + R.getReplacementText() + Tail).str();
391
405
      Delta += R.getReplacementText().size() - R.getLength();
392
503
    } else {
393
503
      unsigned End = Offset + Length;
394
503
      StringRef RText = R.getReplacementText();
395
503
      StringRef Tail = RText.substr(End - R.getOffset());
396
503
      Text = (Text + Tail).str();
397
503
      if (R.getOffset() + RText.size() > End) {
398
295
        Length = R.getOffset() + R.getLength() - Offset;
399
295
        MergeSecond = true;
400
295
      } else {
401
208
        Length += R.getLength() - RText.size();
402
208
      }
403
503
      DeltaFirst += RText.size() - R.getLength();
404
503
    }
405
908
  }
406
407
  // Returns 'true' if 'R' starts strictly after the MergedReplacement and thus
408
  // doesn't need to be merged.
409
2.56k
  bool endsBefore(const Replacement &R) const {
410
2.56k
    if (MergeSecond)
411
825
      return Offset + Text.size() < R.getOffset() + Delta;
412
1.73k
    return Offset + Length < R.getOffset();
413
1.73k
  }
414
415
  // Returns 'true' if an element from the second set should be merged next.
416
9.12k
  bool mergeSecond() const { return MergeSecond; }
417
418
2.78k
  int deltaFirst() const { return DeltaFirst; }
419
2.78k
  Replacement asReplacement() const { return {FilePath, Offset, Length, Text}; }
420
421
private:
422
  bool MergeSecond;
423
424
  // Amount of characters that elements from 'Second' need to be shifted by in
425
  // order to refer to the original text.
426
  int Delta;
427
428
  // Sum of all deltas (text-length - length) of elements from 'First' merged
429
  // into this element. This is used to update 'Delta' once the
430
  // MergedReplacement is completed.
431
  int DeltaFirst;
432
433
  // Data of the actually merged replacement. FilePath and Offset aren't changed
434
  // as the element is only extended to the right.
435
  const StringRef FilePath;
436
  const unsigned Offset;
437
  unsigned Length;
438
  std::string Text;
439
};
440
441
} // namespace
442
443
33.9k
Replacements Replacements::merge(const Replacements &ReplacesToMerge) const {
444
33.9k
  if (empty() || 
ReplacesToMerge.empty()1.93k
)
445
32.9k
    return empty() ? 
ReplacesToMerge31.9k
:
*this1.01k
;
446
921
447
921
  auto &First = Replaces;
448
921
  auto &Second = ReplacesToMerge.Replaces;
449
921
  // Delta is the amount of characters that replacements from 'Second' need to
450
921
  // be shifted so that their offsets refer to the original text.
451
921
  int Delta = 0;
452
921
  ReplacementsImpl Result;
453
921
454
921
  // Iterate over both sets and always add the next element (smallest total
455
921
  // Offset) from either 'First' or 'Second'. Merge that element with
456
921
  // subsequent replacements as long as they overlap. See more details in the
457
921
  // comment on MergedReplacement.
458
921
  for (auto FirstI = First.begin(), SecondI = Second.begin();
459
3.70k
       FirstI != First.end() || 
SecondI != Second.end()1.31k
;) {
460
2.78k
    bool NextIsFirst = SecondI == Second.end() ||
461
2.78k
                       
(2.65k
FirstI != First.end()2.65k
&&
462
2.65k
                        
FirstI->getOffset() < SecondI->getOffset() + Delta2.25k
);
463
2.78k
    MergedReplacement Merged(NextIsFirst ? 
*FirstI721
:
*SecondI2.06k
, NextIsFirst,
464
2.78k
                             Delta);
465
2.78k
    ++(NextIsFirst ? 
FirstI721
:
SecondI2.06k
);
466
2.78k
467
3.69k
    while ((Merged.mergeSecond() && 
SecondI != Second.end()1.35k
) ||
468
3.69k
           
(2.86k
!Merged.mergeSecond()2.86k
&&
FirstI != First.end()2.33k
)) {
469
2.56k
      auto &I = Merged.mergeSecond() ? 
SecondI825
:
FirstI1.73k
;
470
2.56k
      if (Merged.endsBefore(*I))
471
1.65k
        break;
472
908
      Merged.merge(*I);
473
908
      ++I;
474
908
    }
475
2.78k
    Delta -= Merged.deltaFirst();
476
2.78k
    Result.insert(Merged.asReplacement());
477
2.78k
  }
478
921
  return Replacements(Result.begin(), Result.end());
479
921
}
480
481
// Combines overlapping ranges in \p Ranges and sorts the combined ranges.
482
// Returns a set of non-overlapping and sorted ranges that is equivalent to
483
// \p Ranges.
484
19.1k
static std::vector<Range> combineAndSortRanges(std::vector<Range> Ranges) {
485
19.1k
  llvm::sort(Ranges, [](const Range &LHS, const Range &RHS) {
486
1.13k
    if (LHS.getOffset() != RHS.getOffset())
487
1.13k
      return LHS.getOffset() < RHS.getOffset();
488
1
    return LHS.getLength() < RHS.getLength();
489
1
  });
490
19.1k
  std::vector<Range> Result;
491
20.2k
  for (const auto &R : Ranges) {
492
20.2k
    if (Result.empty() ||
493
20.2k
        
Result.back().getOffset() + Result.back().getLength() < R.getOffset()1.13k
) {
494
20.2k
      Result.push_back(R);
495
20.2k
    } else {
496
15
      unsigned NewEnd =
497
15
          std::max(Result.back().getOffset() + Result.back().getLength(),
498
15
                   R.getOffset() + R.getLength());
499
15
      Result[Result.size() - 1] =
500
15
          Range(Result.back().getOffset(), NewEnd - Result.back().getOffset());
501
15
    }
502
20.2k
  }
503
19.1k
  return Result;
504
19.1k
}
505
506
namespace clang {
507
namespace tooling {
508
509
std::vector<Range>
510
calculateRangesAfterReplacements(const Replacements &Replaces,
511
17.6k
                                 const std::vector<Range> &Ranges) {
512
17.6k
  // To calculate the new ranges,
513
17.6k
  //   - Turn \p Ranges into Replacements at (offset, length) with an empty
514
17.6k
  //     (unimportant) replacement text of length "length".
515
17.6k
  //   - Merge with \p Replaces.
516
17.6k
  //   - The new ranges will be the affected ranges of the merged replacements.
517
17.6k
  auto MergedRanges = combineAndSortRanges(Ranges);
518
17.6k
  if (Replaces.empty())
519
17.3k
    return MergedRanges;
520
339
  tooling::Replacements FakeReplaces;
521
390
  for (const auto &R : MergedRanges) {
522
390
    llvm::cantFail(
523
390
        FakeReplaces.add(Replacement(Replaces.begin()->getFilePath(),
524
390
                                     R.getOffset(), R.getLength(),
525
390
                                     std::string(R.getLength(), ' '))),
526
390
        "Replacements must not conflict since ranges have been merged.");
527
390
  }
528
339
  return FakeReplaces.merge(Replaces).getAffectedRanges();
529
339
}
530
531
} // namespace tooling
532
} // namespace clang
533
534
1.47k
std::vector<Range> Replacements::getAffectedRanges() const {
535
1.47k
  std::vector<Range> ChangedRanges;
536
1.47k
  int Shift = 0;
537
2.13k
  for (const auto &R : Replaces) {
538
2.13k
    unsigned Offset = R.getOffset() + Shift;
539
2.13k
    unsigned Length = R.getReplacementText().size();
540
2.13k
    Shift += Length - R.getLength();
541
2.13k
    ChangedRanges.push_back(Range(Offset, Length));
542
2.13k
  }
543
1.47k
  return combineAndSortRanges(ChangedRanges);
544
1.47k
}
545
546
376
unsigned Replacements::getShiftedCodePosition(unsigned Position) const {
547
376
  unsigned Offset = 0;
548
391
  for (const auto &R : Replaces) {
549
391
    if (R.getOffset() + R.getLength() <= Position) {
550
190
      Offset += R.getReplacementText().size() - R.getLength();
551
190
      continue;
552
190
    }
553
201
    if (R.getOffset() < Position &&
554
201
        
R.getOffset() + R.getReplacementText().size() <= Position34
) {
555
25
      Position = R.getOffset() + R.getReplacementText().size();
556
25
      if (!R.getReplacementText().empty())
557
11
        Position--;
558
25
    }
559
201
    break;
560
201
  }
561
376
  return Position + Offset;
562
376
}
563
564
namespace clang {
565
namespace tooling {
566
567
591
bool applyAllReplacements(const Replacements &Replaces, Rewriter &Rewrite) {
568
591
  bool Result = true;
569
3.15k
  for (auto I = Replaces.rbegin(), E = Replaces.rend(); I != E; 
++I2.56k
) {
570
2.56k
    if (I->isApplicable()) {
571
2.56k
      Result = I->apply(Rewrite) && Result;
572
2.56k
    } else {
573
1
      Result = false;
574
1
    }
575
2.56k
  }
576
591
  return Result;
577
591
}
578
579
llvm::Expected<std::string> applyAllReplacements(StringRef Code,
580
47.9k
                                                const Replacements &Replaces) {
581
47.9k
  if (Replaces.empty())
582
34.9k
    return Code.str();
583
12.9k
584
12.9k
  IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem> InMemoryFileSystem(
585
12.9k
      new llvm::vfs::InMemoryFileSystem);
586
12.9k
  FileManager Files(FileSystemOptions(), InMemoryFileSystem);
587
12.9k
  DiagnosticsEngine Diagnostics(
588
12.9k
      IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
589
12.9k
      new DiagnosticOptions);
590
12.9k
  SourceManager SourceMgr(Diagnostics, Files);
591
12.9k
  Rewriter Rewrite(SourceMgr, LangOptions());
592
12.9k
  InMemoryFileSystem->addFile(
593
12.9k
      "<stdin>", 0, llvm::MemoryBuffer::getMemBuffer(Code, "<stdin>"));
594
12.9k
  FileID ID = SourceMgr.createFileID(*Files.getFile("<stdin>"),
595
12.9k
                                     SourceLocation(),
596
12.9k
                                     clang::SrcMgr::C_User);
597
51.8k
  for (auto I = Replaces.rbegin(), E = Replaces.rend(); I != E; 
++I38.8k
) {
598
38.8k
    Replacement Replace("<stdin>", I->getOffset(), I->getLength(),
599
38.8k
                        I->getReplacementText());
600
38.8k
    if (!Replace.apply(Rewrite))
601
0
      return llvm::make_error<ReplacementError>(
602
0
          replacement_error::fail_to_apply, Replace);
603
38.8k
  }
604
12.9k
  std::string Result;
605
12.9k
  llvm::raw_string_ostream OS(Result);
606
12.9k
  Rewrite.getEditBuffer(ID).write(OS);
607
12.9k
  OS.flush();
608
12.9k
  return Result;
609
12.9k
}
610
611
std::map<std::string, Replacements> groupReplacementsByFile(
612
    FileManager &FileMgr,
613
325
    const std::map<std::string, Replacements> &FileToReplaces) {
614
325
  std::map<std::string, Replacements> Result;
615
325
  llvm::SmallPtrSet<const FileEntry *, 16> ProcessedFileEntries;
616
548
  for (const auto &Entry : FileToReplaces) {
617
548
    auto FE = FileMgr.getFile(Entry.first);
618
548
    if (!FE)
619
2
      llvm::errs() << "File path " << Entry.first << " is invalid.\n";
620
546
    else if (ProcessedFileEntries.insert(*FE).second)
621
544
      Result[Entry.first] = std::move(Entry.second);
622
548
  }
623
325
  return Result;
624
325
}
625
626
} // namespace tooling
627
} // namespace clang