Coverage Report

Created: 2021-08-24 07:12

/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
137k
      ReplacementText(std::string(ReplacementText)) {}
51
52
Replacement::Replacement(const SourceManager &Sources, SourceLocation Start,
53
372
                         unsigned Length, StringRef ReplacementText) {
54
372
  setFromSourceLocation(Sources, Start, Length, ReplacementText);
55
372
}
56
57
Replacement::Replacement(const SourceManager &Sources,
58
                         const CharSourceRange &Range,
59
                         StringRef ReplacementText,
60
27.0k
                         const LangOptions &LangOpts) {
61
27.0k
  setFromSourceRange(Sources, Range, ReplacementText, LangOpts);
62
27.0k
}
63
64
2.60k
bool Replacement::isApplicable() const {
65
2.60k
  return FilePath != InvalidLocation;
66
2.60k
}
67
68
54.5k
bool Replacement::apply(Rewriter &Rewrite) const {
69
54.5k
  SourceManager &SM = Rewrite.getSourceMgr();
70
54.5k
  auto Entry = SM.getFileManager().getFile(FilePath);
71
54.5k
  if (!Entry)
72
1
    return false;
73
74
54.5k
  FileID ID = SM.getOrCreateFileID(*Entry, SrcMgr::C_User);
75
54.5k
  const SourceLocation Start =
76
54.5k
    SM.getLocForStartOfFile(ID).
77
54.5k
    getLocWithOffset(ReplacementRange.getOffset());
78
  // ReplaceText returns false on success.
79
  // ReplaceText only fails if the source location is not a file location, in
80
  // which case we already returned false earlier.
81
54.5k
  bool RewriteSucceeded = !Rewrite.ReplaceText(
82
54.5k
      Start, ReplacementRange.getLength(), ReplacementText);
83
54.5k
  assert(RewriteSucceeded);
84
0
  return RewriteSucceeded;
85
54.5k
}
86
87
8
std::string Replacement::toString() const {
88
8
  std::string Result;
89
8
  llvm::raw_string_ostream Stream(Result);
90
8
  Stream << FilePath << ": " << ReplacementRange.getOffset() << ":+"
91
8
         << ReplacementRange.getLength() << ":\"" << ReplacementText << "\"";
92
8
  return Stream.str();
93
8
}
94
95
namespace clang {
96
namespace tooling {
97
98
520k
bool operator<(const Replacement &LHS, const Replacement &RHS) {
99
520k
  if (LHS.getOffset() != RHS.getOffset())
100
520k
    return LHS.getOffset() < RHS.getOffset();
101
102
298
  if (LHS.getLength() != RHS.getLength())
103
50
    return LHS.getLength() < RHS.getLength();
104
105
248
  if (LHS.getFilePath() != RHS.getFilePath())
106
0
    return LHS.getFilePath() < RHS.getFilePath();
107
248
  return LHS.getReplacementText() < RHS.getReplacementText();
108
248
}
109
110
154
bool operator==(const Replacement &LHS, const Replacement &RHS) {
111
154
  return LHS.getOffset() == RHS.getOffset() &&
112
154
         LHS.getLength() == RHS.getLength() &&
113
154
         LHS.getFilePath() == RHS.getFilePath() &&
114
154
         LHS.getReplacementText() == RHS.getReplacementText();
115
154
}
116
117
} // namespace tooling
118
} // namespace clang
119
120
void Replacement::setFromSourceLocation(const SourceManager &Sources,
121
                                        SourceLocation Start, unsigned Length,
122
27.4k
                                        StringRef ReplacementText) {
123
27.4k
  const std::pair<FileID, unsigned> DecomposedLocation =
124
27.4k
      Sources.getDecomposedLoc(Start);
125
27.4k
  const FileEntry *Entry = Sources.getFileEntryForID(DecomposedLocation.first);
126
27.4k
  this->FilePath = std::string(Entry ? 
Entry->getName()27.4k
:
InvalidLocation6
);
127
27.4k
  this->ReplacementRange = Range(DecomposedLocation.second, Length);
128
27.4k
  this->ReplacementText = std::string(ReplacementText);
129
27.4k
}
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
27.0k
                        const LangOptions &LangOpts) {
137
27.0k
  SourceLocation SpellingBegin = Sources.getSpellingLoc(Range.getBegin());
138
27.0k
  SourceLocation SpellingEnd = Sources.getSpellingLoc(Range.getEnd());
139
27.0k
  std::pair<FileID, unsigned> Start = Sources.getDecomposedLoc(SpellingBegin);
140
27.0k
  std::pair<FileID, unsigned> End = Sources.getDecomposedLoc(SpellingEnd);
141
27.0k
  if (Start.first != End.first) 
return -10
;
142
27.0k
  if (Range.isTokenRange())
143
742
    End.second += Lexer::MeasureTokenLength(SpellingEnd, Sources, LangOpts);
144
27.0k
  return End.second - Start.second;
145
27.0k
}
146
147
void Replacement::setFromSourceRange(const SourceManager &Sources,
148
                                     const CharSourceRange &Range,
149
                                     StringRef ReplacementText,
150
27.0k
                                     const LangOptions &LangOpts) {
151
27.0k
  setFromSourceLocation(Sources, Sources.getSpellingLoc(Range.getBegin()),
152
27.0k
                        getRangeSize(Sources, Range, LangOpts),
153
27.0k
                        ReplacementText);
154
27.0k
}
155
156
Replacement
157
200
Replacements::getReplacementInChangedCode(const Replacement &R) const {
158
200
  unsigned NewStart = getShiftedCodePosition(R.getOffset());
159
200
  unsigned NewEnd = getShiftedCodePosition(R.getOffset() + R.getLength());
160
200
  return Replacement(R.getFilePath(), NewStart, NewEnd - NewStart,
161
200
                     R.getReplacementText());
162
200
}
163
164
4
static std::string getReplacementErrString(replacement_error Err) {
165
4
  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
3
  case replacement_error::overlap_conflict:
172
3
    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
4
  }
177
0
  llvm_unreachable("A value of replacement_error has no message.");
178
0
}
179
180
4
std::string ReplacementError::message() const {
181
4
  std::string Message = getReplacementErrString(Err);
182
4
  if (NewReplacement.hasValue())
183
4
    Message += "\nNew replacement: " + NewReplacement->toString();
184
4
  if (ExistingReplacement.hasValue())
185
4
    Message += "\nExisting replacement: " + ExistingReplacement->toString();
186
4
  return Message;
187
4
}
188
189
char ReplacementError::ID = 0;
190
191
198
Replacements Replacements::getCanonicalReplacements() const {
192
198
  std::vector<Replacement> NewReplaces;
193
  // Merge adjacent replacements.
194
199
  for (const auto &R : Replaces) {
195
199
    if (NewReplaces.empty()) {
196
198
      NewReplaces.push_back(R);
197
198
      continue;
198
198
    }
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
0
      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
198
  ReplacementsImpl NewReplacesImpl(NewReplaces.begin(), NewReplaces.end());
213
198
  return Replacements(NewReplacesImpl.begin(), NewReplacesImpl.end());
214
198
}
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
99
Replacements::mergeIfOrderIndependent(const Replacement &R) const {
221
99
  Replacements Rs(R);
222
  // A Replacements set containing a single replacement that is `R` referring to
223
  // the code after the existing replacements `Replaces` are applied.
224
99
  Replacements RsShiftedByReplaces(getReplacementInChangedCode(R));
225
  // A Replacements set that is `Replaces` referring to the code after `R` is
226
  // applied.
227
99
  Replacements ReplacesShiftedByRs;
228
99
  for (const auto &Replace : Replaces)
229
101
    ReplacesShiftedByRs.Replaces.insert(
230
101
        Rs.getReplacementInChangedCode(Replace));
231
  // This is equivalent to applying `Replaces` first and then `R`.
232
99
  auto MergeShiftedRs = merge(RsShiftedByReplaces);
233
  // This is equivalent to applying `R` first and then `Replaces`.
234
99
  auto MergeShiftedReplaces = Rs.merge(ReplacesShiftedByRs);
235
236
  // Since empty or segmented replacements around existing replacements might be
237
  // produced above, we need to compare replacements in canonical forms.
238
99
  if (MergeShiftedRs.getCanonicalReplacements() ==
239
99
      MergeShiftedReplaces.getCanonicalReplacements())
240
91
    return MergeShiftedRs;
241
8
  return llvm::make_error<ReplacementError>(replacement_error::overlap_conflict,
242
8
                                            R, *Replaces.begin());
243
99
}
244
245
81.2k
llvm::Error Replacements::add(const Replacement &R) {
246
  // Check the file path.
247
81.2k
  if (!Replaces.empty() && 
R.getFilePath() != Replaces.begin()->getFilePath()56.1k
)
248
4
    return llvm::make_error<ReplacementError>(
249
4
        replacement_error::wrong_file_path, R, *Replaces.begin());
250
251
  // Special-case header insertions.
252
81.2k
  if (R.getOffset() == std::numeric_limits<unsigned>::max()) {
253
78
    Replaces.insert(R);
254
78
    return llvm::Error::success();
255
78
  }
256
257
  // This replacement cannot conflict with replacements that end before
258
  // this replacement starts or start after this replacement ends.
259
  // We also know that there currently are no overlapping replacements.
260
  // Thus, we know that all replacements that start after the end of the current
261
  // replacement cannot overlap.
262
81.1k
  Replacement AtEnd(R.getFilePath(), R.getOffset() + R.getLength(), 0, "");
263
264
  // Find the first entry that starts after or at the end of R. Note that
265
  // entries that start at the end can still be conflicting if R is an
266
  // insertion.
267
81.1k
  auto I = Replaces.lower_bound(AtEnd);
268
  // If `I` starts at the same offset as `R`, `R` must be an insertion.
269
81.1k
  if (I != Replaces.end() && 
R.getOffset() == I->getOffset()208
) {
270
32
    assert(R.getLength() == 0);
271
    // `I` is also an insertion, `R` and `I` conflict.
272
32
    if (I->getLength() == 0) {
273
      // Check if two insertions are order-indepedent: if inserting them in
274
      // either order produces the same text, they are order-independent.
275
27
      if ((R.getReplacementText() + I->getReplacementText()).str() !=
276
27
          (I->getReplacementText() + R.getReplacementText()).str())
277
21
        return llvm::make_error<ReplacementError>(
278
21
            replacement_error::insert_conflict, R, *I);
279
      // If insertions are order-independent, we can merge them.
280
6
      Replacement NewR(
281
6
          R.getFilePath(), R.getOffset(), 0,
282
6
          (R.getReplacementText() + I->getReplacementText()).str());
283
6
      Replaces.erase(I);
284
6
      Replaces.insert(std::move(NewR));
285
6
      return llvm::Error::success();
286
27
    }
287
    // Insertion `R` is adjacent to a non-insertion replacement `I`, so they
288
    // are order-independent. It is safe to assume that `R` will not conflict
289
    // with any replacement before `I` since all replacements before `I` must
290
    // either end before `R` or end at `R` but has length > 0 (if the
291
    // replacement before `I` is an insertion at `R`, it would have been `I`
292
    // since it is a lower bound of `AtEnd` and ordered before the current `I`
293
    // in the set).
294
5
    Replaces.insert(R);
295
5
    return llvm::Error::success();
296
32
  }
297
298
  // `I` is the smallest iterator (after `R`) whose entry cannot overlap.
299
  // If that is begin(), there are no overlaps.
300
81.1k
  if (I == Replaces.begin()) {
301
25.1k
    Replaces.insert(R);
302
25.1k
    return llvm::Error::success();
303
25.1k
  }
304
56.0k
  --I;
305
56.0k
  auto Overlap = [](const Replacement &R1, const Replacement &R2) -> bool {
306
56.0k
    return Range(R1.getOffset(), R1.getLength())
307
56.0k
        .overlapsWith(Range(R2.getOffset(), R2.getLength()));
308
56.0k
  };
309
  // If the previous entry does not overlap, we know that entries before it
310
  // can also not overlap.
311
56.0k
  if (!Overlap(R, *I)) {
312
    // If `R` and `I` do not have the same offset, it is safe to add `R` since
313
    // it must come after `I`. Otherwise:
314
    //   - If `R` is an insertion, `I` must not be an insertion since it would
315
    //   have come after `AtEnd`.
316
    //   - If `R` is not an insertion, `I` must be an insertion; otherwise, `R`
317
    //   and `I` would have overlapped.
318
    // In either case, we can safely insert `R`.
319
55.9k
    Replaces.insert(R);
320
55.9k
  } else {
321
    // `I` overlaps with `R`. We need to check `R` against all overlapping
322
    // replacements to see if they are order-indepedent. If they are, merge `R`
323
    // with them and replace them with the merged replacements.
324
99
    auto MergeBegin = I;
325
99
    auto MergeEnd = std::next(I);
326
101
    while (I != Replaces.begin()) {
327
22
      --I;
328
      // 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
99
    Replacements OverlapReplaces(MergeBegin, MergeEnd);
334
99
    llvm::Expected<Replacements> Merged =
335
99
        OverlapReplaces.mergeIfOrderIndependent(R);
336
99
    if (!Merged)
337
8
      return Merged.takeError();
338
91
    Replaces.erase(MergeBegin, MergeEnd);
339
91
    Replaces.insert(Merged->begin(), Merged->end());
340
91
  }
341
55.9k
  return llvm::Error::success();
342
56.0k
}
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.99k
        Length(R.getLength()), Text(std::string(R.getReplacementText())) {
372
2.99k
    Delta += MergeSecond ? 
0742
:
Text.size() - Length2.24k
;
373
2.99k
    DeltaFirst = MergeSecond ? 
Text.size() - Length742
:
02.24k
;
374
2.99k
  }
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
999
  void merge(const Replacement &R) {
380
999
    if (MergeSecond) {
381
437
      unsigned REnd = R.getOffset() + Delta + R.getLength();
382
437
      unsigned End = Offset + Text.size();
383
437
      if (REnd > End) {
384
63
        Length += REnd - End;
385
63
        MergeSecond = false;
386
63
      }
387
437
      StringRef TextRef = Text;
388
437
      StringRef Head = TextRef.substr(0, R.getOffset() + Delta - Offset);
389
437
      StringRef Tail = TextRef.substr(REnd - Offset);
390
437
      Text = (Head + R.getReplacementText() + Tail).str();
391
437
      Delta += R.getReplacementText().size() - R.getLength();
392
562
    } else {
393
562
      unsigned End = Offset + Length;
394
562
      StringRef RText = R.getReplacementText();
395
562
      StringRef Tail = RText.substr(End - R.getOffset());
396
562
      Text = (Text + Tail).str();
397
562
      if (R.getOffset() + RText.size() > End) {
398
322
        Length = R.getOffset() + R.getLength() - Offset;
399
322
        MergeSecond = true;
400
322
      } else {
401
240
        Length += R.getLength() - RText.size();
402
240
      }
403
562
      DeltaFirst += RText.size() - R.getLength();
404
562
    }
405
999
  }
406
407
  // Returns 'true' if 'R' starts strictly after the MergedReplacement and thus
408
  // doesn't need to be merged.
409
2.76k
  bool endsBefore(const Replacement &R) const {
410
2.76k
    if (MergeSecond)
411
863
      return Offset + Text.size() < R.getOffset() + Delta;
412
1.90k
    return Offset + Length < R.getOffset();
413
2.76k
  }
414
415
  // Returns 'true' if an element from the second set should be merged next.
416
9.88k
  bool mergeSecond() const { return MergeSecond; }
417
418
2.99k
  int deltaFirst() const { return DeltaFirst; }
419
2.99k
  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
42.3k
Replacements Replacements::merge(const Replacements &ReplacesToMerge) const {
444
42.3k
  if (empty() || 
ReplacesToMerge.empty()2.08k
)
445
41.3k
    return empty() ? 
ReplacesToMerge40.2k
:
*this1.08k
;
446
447
1.00k
  auto &First = Replaces;
448
1.00k
  auto &Second = ReplacesToMerge.Replaces;
449
  // Delta is the amount of characters that replacements from 'Second' need to
450
  // be shifted so that their offsets refer to the original text.
451
1.00k
  int Delta = 0;
452
1.00k
  ReplacementsImpl Result;
453
454
  // Iterate over both sets and always add the next element (smallest total
455
  // Offset) from either 'First' or 'Second'. Merge that element with
456
  // subsequent replacements as long as they overlap. See more details in the
457
  // comment on MergedReplacement.
458
1.00k
  for (auto FirstI = First.begin(), SecondI = Second.begin();
459
3.99k
       FirstI != First.end() || 
SecondI != Second.end()1.42k
;) {
460
2.99k
    bool NextIsFirst = SecondI == Second.end() ||
461
2.99k
                       
(2.86k
FirstI != First.end()2.86k
&&
462
2.86k
                        
FirstI->getOffset() < SecondI->getOffset() + Delta2.44k
);
463
2.99k
    MergedReplacement Merged(NextIsFirst ? 
*FirstI742
:
*SecondI2.24k
, NextIsFirst,
464
2.99k
                             Delta);
465
2.99k
    ++(NextIsFirst ? 
FirstI742
:
SecondI2.24k
);
466
467
3.98k
    while ((Merged.mergeSecond() && 
SecondI != Second.end()1.43k
) ||
468
3.98k
           
(3.12k
!Merged.mergeSecond()3.12k
&&
FirstI != First.end()2.55k
)) {
469
2.76k
      auto &I = Merged.mergeSecond() ? 
SecondI863
:
FirstI1.90k
;
470
2.76k
      if (Merged.endsBefore(*I))
471
1.76k
        break;
472
999
      Merged.merge(*I);
473
999
      ++I;
474
999
    }
475
2.99k
    Delta -= Merged.deltaFirst();
476
2.99k
    Result.insert(Merged.asReplacement());
477
2.99k
  }
478
1.00k
  return Replacements(Result.begin(), Result.end());
479
42.3k
}
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
23.9k
static std::vector<Range> combineAndSortRanges(std::vector<Range> Ranges) {
485
23.9k
  llvm::sort(Ranges, [](const Range &LHS, const Range &RHS) {
486
1.20k
    if (LHS.getOffset() != RHS.getOffset())
487
1.20k
      return LHS.getOffset() < RHS.getOffset();
488
1
    return LHS.getLength() < RHS.getLength();
489
1.20k
  });
490
23.9k
  std::vector<Range> Result;
491
25.1k
  for (const auto &R : Ranges) {
492
25.1k
    if (Result.empty() ||
493
25.1k
        
Result.back().getOffset() + Result.back().getLength() < R.getOffset()1.20k
) {
494
25.1k
      Result.push_back(R);
495
25.1k
    } 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
25.1k
  }
503
23.9k
  return Result;
504
23.9k
}
505
506
namespace clang {
507
namespace tooling {
508
509
std::vector<Range>
510
calculateRangesAfterReplacements(const Replacements &Replaces,
511
22.3k
                                 const std::vector<Range> &Ranges) {
512
  // To calculate the new ranges,
513
  //   - Turn \p Ranges into Replacements at (offset, length) with an empty
514
  //     (unimportant) replacement text of length "length".
515
  //   - Merge with \p Replaces.
516
  //   - The new ranges will be the affected ranges of the merged replacements.
517
22.3k
  auto MergedRanges = combineAndSortRanges(Ranges);
518
22.3k
  if (Replaces.empty())
519
21.9k
    return MergedRanges;
520
379
  tooling::Replacements FakeReplaces;
521
426
  for (const auto &R : MergedRanges) {
522
426
    llvm::cantFail(
523
426
        FakeReplaces.add(Replacement(Replaces.begin()->getFilePath(),
524
426
                                     R.getOffset(), R.getLength(),
525
426
                                     std::string(R.getLength(), ' '))),
526
426
        "Replacements must not conflict since ranges have been merged.");
527
426
  }
528
379
  return FakeReplaces.merge(Replaces).getAffectedRanges();
529
22.3k
}
530
531
} // namespace tooling
532
} // namespace clang
533
534
1.57k
std::vector<Range> Replacements::getAffectedRanges() const {
535
1.57k
  std::vector<Range> ChangedRanges;
536
1.57k
  int Shift = 0;
537
2.30k
  for (const auto &R : Replaces) {
538
2.30k
    unsigned Offset = R.getOffset() + Shift;
539
2.30k
    unsigned Length = R.getReplacementText().size();
540
2.30k
    Shift += Length - R.getLength();
541
2.30k
    ChangedRanges.push_back(Range(Offset, Length));
542
2.30k
  }
543
1.57k
  return combineAndSortRanges(ChangedRanges);
544
1.57k
}
545
546
440
unsigned Replacements::getShiftedCodePosition(unsigned Position) const {
547
440
  unsigned Offset = 0;
548
455
  for (const auto &R : Replaces) {
549
455
    if (R.getOffset() + R.getLength() <= Position) {
550
222
      Offset += R.getReplacementText().size() - R.getLength();
551
222
      continue;
552
222
    }
553
233
    if (R.getOffset() < Position &&
554
233
        
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
233
    break;
560
455
  }
561
440
  return Position + Offset;
562
440
}
563
564
namespace clang {
565
namespace tooling {
566
567
605
bool applyAllReplacements(const Replacements &Replaces, Rewriter &Rewrite) {
568
605
  bool Result = true;
569
3.20k
  for (auto I = Replaces.rbegin(), E = Replaces.rend(); I != E; 
++I2.59k
) {
570
2.59k
    if (I->isApplicable()) {
571
2.59k
      Result = I->apply(Rewrite) && Result;
572
2.59k
    } else {
573
1
      Result = false;
574
1
    }
575
2.59k
  }
576
605
  return Result;
577
605
}
578
579
llvm::Expected<std::string> applyAllReplacements(StringRef Code,
580
60.2k
                                                const Replacements &Replaces) {
581
60.2k
  if (Replaces.empty())
582
44.2k
    return Code.str();
583
584
15.9k
  IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem> InMemoryFileSystem(
585
15.9k
      new llvm::vfs::InMemoryFileSystem);
586
15.9k
  FileManager Files(FileSystemOptions(), InMemoryFileSystem);
587
15.9k
  DiagnosticsEngine Diagnostics(
588
15.9k
      IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
589
15.9k
      new DiagnosticOptions);
590
15.9k
  SourceManager SourceMgr(Diagnostics, Files);
591
15.9k
  Rewriter Rewrite(SourceMgr, LangOptions());
592
15.9k
  InMemoryFileSystem->addFile(
593
15.9k
      "<stdin>", 0, llvm::MemoryBuffer::getMemBuffer(Code, "<stdin>"));
594
15.9k
  FileID ID = SourceMgr.createFileID(*Files.getOptionalFileRef("<stdin>"),
595
15.9k
                                     SourceLocation(),
596
15.9k
                                     clang::SrcMgr::C_User);
597
67.8k
  for (auto I = Replaces.rbegin(), E = Replaces.rend(); I != E; 
++I51.9k
) {
598
51.9k
    Replacement Replace("<stdin>", I->getOffset(), I->getLength(),
599
51.9k
                        I->getReplacementText());
600
51.9k
    if (!Replace.apply(Rewrite))
601
0
      return llvm::make_error<ReplacementError>(
602
0
          replacement_error::fail_to_apply, Replace);
603
51.9k
  }
604
15.9k
  std::string Result;
605
15.9k
  llvm::raw_string_ostream OS(Result);
606
15.9k
  Rewrite.getEditBuffer(ID).write(OS);
607
15.9k
  OS.flush();
608
15.9k
  return Result;
609
15.9k
}
610
611
std::map<std::string, Replacements> groupReplacementsByFile(
612
    FileManager &FileMgr,
613
333
    const std::map<std::string, Replacements> &FileToReplaces) {
614
333
  std::map<std::string, Replacements> Result;
615
333
  llvm::SmallPtrSet<const FileEntry *, 16> ProcessedFileEntries;
616
556
  for (const auto &Entry : FileToReplaces) {
617
556
    auto FE = FileMgr.getFile(Entry.first);
618
556
    if (!FE)
619
2
      llvm::errs() << "File path " << Entry.first << " is invalid.\n";
620
554
    else if (ProcessedFileEntries.insert(*FE).second)
621
552
      Result[Entry.first] = std::move(Entry.second);
622
556
  }
623
333
  return Result;
624
333
}
625
626
} // namespace tooling
627
} // namespace clang