1cb3e6188SDaniel Jasper //===--- Replacement.cpp - Framework for clang refactoring tools ----------===//
2cb3e6188SDaniel Jasper //
3cb3e6188SDaniel Jasper //                     The LLVM Compiler Infrastructure
4cb3e6188SDaniel Jasper //
5cb3e6188SDaniel Jasper // This file is distributed under the University of Illinois Open Source
6cb3e6188SDaniel Jasper // License. See LICENSE.TXT for details.
7cb3e6188SDaniel Jasper //
8cb3e6188SDaniel Jasper //===----------------------------------------------------------------------===//
9cb3e6188SDaniel Jasper //
10cb3e6188SDaniel Jasper //  Implements classes to support/store refactorings.
11cb3e6188SDaniel Jasper //
12cb3e6188SDaniel Jasper //===----------------------------------------------------------------------===//
13cb3e6188SDaniel Jasper 
14b12e5a5cSManuel Klimek #include "clang/Tooling/Core/Replacement.h"
15b12e5a5cSManuel Klimek 
16cb3e6188SDaniel Jasper #include "clang/Basic/Diagnostic.h"
17cb3e6188SDaniel Jasper #include "clang/Basic/DiagnosticIDs.h"
18cb3e6188SDaniel Jasper #include "clang/Basic/DiagnosticOptions.h"
19cb3e6188SDaniel Jasper #include "clang/Basic/FileManager.h"
20cb3e6188SDaniel Jasper #include "clang/Basic/SourceManager.h"
21cb3e6188SDaniel Jasper #include "clang/Lex/Lexer.h"
22cb3e6188SDaniel Jasper #include "clang/Rewrite/Core/Rewriter.h"
23*cf2913c6SEric Liu #include "llvm/ADT/SmallPtrSet.h"
24cb3e6188SDaniel Jasper #include "llvm/Support/FileSystem.h"
25cefe763dSEric Liu #include "llvm/Support/Path.h"
26cb3e6188SDaniel Jasper #include "llvm/Support/raw_os_ostream.h"
27cb3e6188SDaniel Jasper 
28cb3e6188SDaniel Jasper namespace clang {
29cb3e6188SDaniel Jasper namespace tooling {
30cb3e6188SDaniel Jasper 
31cb3e6188SDaniel Jasper static const char * const InvalidLocation = "";
32cb3e6188SDaniel Jasper 
33cb3e6188SDaniel Jasper Replacement::Replacement()
34cb3e6188SDaniel Jasper   : FilePath(InvalidLocation) {}
35cb3e6188SDaniel Jasper 
36cb3e6188SDaniel Jasper Replacement::Replacement(StringRef FilePath, unsigned Offset, unsigned Length,
37cb3e6188SDaniel Jasper                          StringRef ReplacementText)
38cb3e6188SDaniel Jasper     : FilePath(FilePath), ReplacementRange(Offset, Length),
39cb3e6188SDaniel Jasper       ReplacementText(ReplacementText) {}
40cb3e6188SDaniel Jasper 
41cb3e6188SDaniel Jasper Replacement::Replacement(const SourceManager &Sources, SourceLocation Start,
42cb3e6188SDaniel Jasper                          unsigned Length, StringRef ReplacementText) {
43cb3e6188SDaniel Jasper   setFromSourceLocation(Sources, Start, Length, ReplacementText);
44cb3e6188SDaniel Jasper }
45cb3e6188SDaniel Jasper 
46cb3e6188SDaniel Jasper Replacement::Replacement(const SourceManager &Sources,
47cb3e6188SDaniel Jasper                          const CharSourceRange &Range,
4894a89231SManuel Klimek                          StringRef ReplacementText,
4994a89231SManuel Klimek                          const LangOptions &LangOpts) {
5094a89231SManuel Klimek   setFromSourceRange(Sources, Range, ReplacementText, LangOpts);
51cb3e6188SDaniel Jasper }
52cb3e6188SDaniel Jasper 
53cb3e6188SDaniel Jasper bool Replacement::isApplicable() const {
54cb3e6188SDaniel Jasper   return FilePath != InvalidLocation;
55cb3e6188SDaniel Jasper }
56cb3e6188SDaniel Jasper 
57cb3e6188SDaniel Jasper bool Replacement::apply(Rewriter &Rewrite) const {
58cb3e6188SDaniel Jasper   SourceManager &SM = Rewrite.getSourceMgr();
59cb3e6188SDaniel Jasper   const FileEntry *Entry = SM.getFileManager().getFile(FilePath);
60cb3e6188SDaniel Jasper   if (!Entry)
61cb3e6188SDaniel Jasper     return false;
624c1ef97aSEric Liu 
634c1ef97aSEric Liu   FileID ID = SM.getOrCreateFileID(Entry, SrcMgr::C_User);
64cb3e6188SDaniel Jasper   const SourceLocation Start =
65cb3e6188SDaniel Jasper     SM.getLocForStartOfFile(ID).
66cb3e6188SDaniel Jasper     getLocWithOffset(ReplacementRange.getOffset());
67cb3e6188SDaniel Jasper   // ReplaceText returns false on success.
68cb3e6188SDaniel Jasper   // ReplaceText only fails if the source location is not a file location, in
69cb3e6188SDaniel Jasper   // which case we already returned false earlier.
70cb3e6188SDaniel Jasper   bool RewriteSucceeded = !Rewrite.ReplaceText(
71cb3e6188SDaniel Jasper       Start, ReplacementRange.getLength(), ReplacementText);
72cb3e6188SDaniel Jasper   assert(RewriteSucceeded);
73cb3e6188SDaniel Jasper   return RewriteSucceeded;
74cb3e6188SDaniel Jasper }
75cb3e6188SDaniel Jasper 
76cb3e6188SDaniel Jasper std::string Replacement::toString() const {
77b1223b1dSManuel Klimek   std::string Result;
78b1223b1dSManuel Klimek   llvm::raw_string_ostream Stream(Result);
79b1223b1dSManuel Klimek   Stream << FilePath << ": " << ReplacementRange.getOffset() << ":+"
80cb3e6188SDaniel Jasper          << ReplacementRange.getLength() << ":\"" << ReplacementText << "\"";
81b1223b1dSManuel Klimek   return Stream.str();
82cb3e6188SDaniel Jasper }
83cb3e6188SDaniel Jasper 
84cb3e6188SDaniel Jasper bool operator<(const Replacement &LHS, const Replacement &RHS) {
85cb3e6188SDaniel Jasper   if (LHS.getOffset() != RHS.getOffset())
86cb3e6188SDaniel Jasper     return LHS.getOffset() < RHS.getOffset();
870f291276SDaniel Jasper 
88cb3e6188SDaniel Jasper   if (LHS.getLength() != RHS.getLength())
89e9906525SEric Liu     return LHS.getLength() < RHS.getLength();
900f291276SDaniel Jasper 
91cb3e6188SDaniel Jasper   if (LHS.getFilePath() != RHS.getFilePath())
92cb3e6188SDaniel Jasper     return LHS.getFilePath() < RHS.getFilePath();
93cb3e6188SDaniel Jasper   return LHS.getReplacementText() < RHS.getReplacementText();
94cb3e6188SDaniel Jasper }
95cb3e6188SDaniel Jasper 
96cb3e6188SDaniel Jasper bool operator==(const Replacement &LHS, const Replacement &RHS) {
97cb3e6188SDaniel Jasper   return LHS.getOffset() == RHS.getOffset() &&
98cb3e6188SDaniel Jasper          LHS.getLength() == RHS.getLength() &&
99cb3e6188SDaniel Jasper          LHS.getFilePath() == RHS.getFilePath() &&
100cb3e6188SDaniel Jasper          LHS.getReplacementText() == RHS.getReplacementText();
101cb3e6188SDaniel Jasper }
102cb3e6188SDaniel Jasper 
103cb3e6188SDaniel Jasper void Replacement::setFromSourceLocation(const SourceManager &Sources,
104cb3e6188SDaniel Jasper                                         SourceLocation Start, unsigned Length,
105cb3e6188SDaniel Jasper                                         StringRef ReplacementText) {
106cb3e6188SDaniel Jasper   const std::pair<FileID, unsigned> DecomposedLocation =
107cb3e6188SDaniel Jasper       Sources.getDecomposedLoc(Start);
108cb3e6188SDaniel Jasper   const FileEntry *Entry = Sources.getFileEntryForID(DecomposedLocation.first);
109cac8fc23SBenjamin Kramer   this->FilePath = Entry ? Entry->getName() : InvalidLocation;
110cb3e6188SDaniel Jasper   this->ReplacementRange = Range(DecomposedLocation.second, Length);
111cb3e6188SDaniel Jasper   this->ReplacementText = ReplacementText;
112cb3e6188SDaniel Jasper }
113cb3e6188SDaniel Jasper 
114cb3e6188SDaniel Jasper // FIXME: This should go into the Lexer, but we need to figure out how
115cb3e6188SDaniel Jasper // to handle ranges for refactoring in general first - there is no obvious
116cb3e6188SDaniel Jasper // good way how to integrate this into the Lexer yet.
117cb3e6188SDaniel Jasper static int getRangeSize(const SourceManager &Sources,
11894a89231SManuel Klimek                         const CharSourceRange &Range,
11994a89231SManuel Klimek                         const LangOptions &LangOpts) {
120cb3e6188SDaniel Jasper   SourceLocation SpellingBegin = Sources.getSpellingLoc(Range.getBegin());
121cb3e6188SDaniel Jasper   SourceLocation SpellingEnd = Sources.getSpellingLoc(Range.getEnd());
122cb3e6188SDaniel Jasper   std::pair<FileID, unsigned> Start = Sources.getDecomposedLoc(SpellingBegin);
123cb3e6188SDaniel Jasper   std::pair<FileID, unsigned> End = Sources.getDecomposedLoc(SpellingEnd);
124cb3e6188SDaniel Jasper   if (Start.first != End.first) return -1;
125cb3e6188SDaniel Jasper   if (Range.isTokenRange())
12694a89231SManuel Klimek     End.second += Lexer::MeasureTokenLength(SpellingEnd, Sources, LangOpts);
127cb3e6188SDaniel Jasper   return End.second - Start.second;
128cb3e6188SDaniel Jasper }
129cb3e6188SDaniel Jasper 
130cb3e6188SDaniel Jasper void Replacement::setFromSourceRange(const SourceManager &Sources,
131cb3e6188SDaniel Jasper                                      const CharSourceRange &Range,
13294a89231SManuel Klimek                                      StringRef ReplacementText,
13394a89231SManuel Klimek                                      const LangOptions &LangOpts) {
134cb3e6188SDaniel Jasper   setFromSourceLocation(Sources, Sources.getSpellingLoc(Range.getBegin()),
13594a89231SManuel Klimek                         getRangeSize(Sources, Range, LangOpts),
13694a89231SManuel Klimek                         ReplacementText);
137cb3e6188SDaniel Jasper }
138cb3e6188SDaniel Jasper 
1396ef82b67SEric Liu Replacement
1406ef82b67SEric Liu Replacements::getReplacementInChangedCode(const Replacement &R) const {
1416ef82b67SEric Liu   unsigned NewStart = getShiftedCodePosition(R.getOffset());
1426ef82b67SEric Liu   unsigned NewEnd = getShiftedCodePosition(R.getOffset() + R.getLength());
1436ef82b67SEric Liu   return Replacement(R.getFilePath(), NewStart, NewEnd - NewStart,
1446ef82b67SEric Liu                      R.getReplacementText());
1456ef82b67SEric Liu }
1466ef82b67SEric Liu 
1476ef82b67SEric Liu static llvm::Error makeConflictReplacementsError(const Replacement &New,
1489df9b6fdSEric Liu                                                  const Replacement &Existing) {
1499df9b6fdSEric Liu   return llvm::make_error<llvm::StringError>(
1509df9b6fdSEric Liu       "New replacement:\n" + New.toString() +
1519df9b6fdSEric Liu           "\nconflicts with existing replacement:\n" + Existing.toString(),
1529df9b6fdSEric Liu       llvm::inconvertibleErrorCode());
1539df9b6fdSEric Liu }
1549df9b6fdSEric Liu 
1556ef82b67SEric Liu Replacements Replacements::getCanonicalReplacements() const {
1566ef82b67SEric Liu   std::vector<Replacement> NewReplaces;
1576ef82b67SEric Liu   // Merge adjacent replacements.
1586ef82b67SEric Liu   for (const auto &R : Replaces) {
1596ef82b67SEric Liu     if (NewReplaces.empty()) {
1606ef82b67SEric Liu       NewReplaces.push_back(R);
1616ef82b67SEric Liu       continue;
1626ef82b67SEric Liu     }
1636ef82b67SEric Liu     auto &Prev = NewReplaces.back();
1646ef82b67SEric Liu     unsigned PrevEnd = Prev.getOffset() + Prev.getLength();
1656ef82b67SEric Liu     if (PrevEnd < R.getOffset()) {
1666ef82b67SEric Liu       NewReplaces.push_back(R);
1676ef82b67SEric Liu     } else {
1686ef82b67SEric Liu       assert(PrevEnd == R.getOffset() &&
1696ef82b67SEric Liu              "Existing replacements must not overlap.");
1706ef82b67SEric Liu       Replacement NewR(
1716ef82b67SEric Liu           R.getFilePath(), Prev.getOffset(), Prev.getLength() + R.getLength(),
1726ef82b67SEric Liu           (Prev.getReplacementText() + R.getReplacementText()).str());
1736ef82b67SEric Liu       Prev = NewR;
1746ef82b67SEric Liu     }
1756ef82b67SEric Liu   }
1766ef82b67SEric Liu   ReplacementsImpl NewReplacesImpl(NewReplaces.begin(), NewReplaces.end());
1776ef82b67SEric Liu   return Replacements(NewReplacesImpl.begin(), NewReplacesImpl.end());
1786ef82b67SEric Liu }
1796ef82b67SEric Liu 
1806ef82b67SEric Liu // `R` and `Replaces` are order-independent if applying them in either order
1816ef82b67SEric Liu // has the same effect, so we need to compare replacements associated to
1826ef82b67SEric Liu // applying them in either order.
1836ef82b67SEric Liu llvm::Expected<Replacements>
1846ef82b67SEric Liu Replacements::mergeIfOrderIndependent(const Replacement &R) const {
1856ef82b67SEric Liu   Replacements Rs(R);
1866ef82b67SEric Liu   // A Replacements set containg a single replacement that is `R` referring to
1876ef82b67SEric Liu   // the code after the existing replacements `Replaces` are applied.
1886ef82b67SEric Liu   Replacements RsShiftedByReplaces(getReplacementInChangedCode(R));
1896ef82b67SEric Liu   // A Replacements set that is `Replaces` referring to the code after `R` is
1906ef82b67SEric Liu   // applied.
1916ef82b67SEric Liu   Replacements ReplacesShiftedByRs;
1926ef82b67SEric Liu   for (const auto &Replace : Replaces)
1936ef82b67SEric Liu     ReplacesShiftedByRs.Replaces.insert(
1946ef82b67SEric Liu         Rs.getReplacementInChangedCode(Replace));
1956ef82b67SEric Liu   // This is equivalent to applying `Replaces` first and then `R`.
1966ef82b67SEric Liu   auto MergeShiftedRs = merge(RsShiftedByReplaces);
1976ef82b67SEric Liu   // This is equivalent to applying `R` first and then `Replaces`.
1986ef82b67SEric Liu   auto MergeShiftedReplaces = Rs.merge(ReplacesShiftedByRs);
1996ef82b67SEric Liu 
2006ef82b67SEric Liu   // Since empty or segmented replacements around existing replacements might be
2016ef82b67SEric Liu   // produced above, we need to compare replacements in canonical forms.
2026ef82b67SEric Liu   if (MergeShiftedRs.getCanonicalReplacements() ==
2036ef82b67SEric Liu       MergeShiftedReplaces.getCanonicalReplacements())
2046ef82b67SEric Liu     return MergeShiftedRs;
2056ef82b67SEric Liu   return makeConflictReplacementsError(R, *Replaces.begin());
2066ef82b67SEric Liu }
2076ef82b67SEric Liu 
20840ef2fb3SEric Liu llvm::Error Replacements::add(const Replacement &R) {
209dcb910b1SManuel Klimek   // Check the file path.
210dcb910b1SManuel Klimek   if (!Replaces.empty() && R.getFilePath() != Replaces.begin()->getFilePath())
2114f8d9943SEric Liu     return llvm::make_error<llvm::StringError>(
21240ef2fb3SEric Liu         "All replacements must have the same file path. New replacement: " +
21340ef2fb3SEric Liu             R.getFilePath() + ", existing replacements: " +
214dcb910b1SManuel Klimek             Replaces.begin()->getFilePath() + "\n",
21540ef2fb3SEric Liu         llvm::inconvertibleErrorCode());
216cb3e6188SDaniel Jasper 
217dcb910b1SManuel Klimek   // Special-case header insertions.
218dcb910b1SManuel Klimek   if (R.getOffset() == UINT_MAX) {
21940ef2fb3SEric Liu     Replaces.insert(R);
22040ef2fb3SEric Liu     return llvm::Error::success();
221b12e5a5cSManuel Klimek   }
222b12e5a5cSManuel Klimek 
223dcb910b1SManuel Klimek   // This replacement cannot conflict with replacements that end before
224dcb910b1SManuel Klimek   // this replacement starts or start after this replacement ends.
225dcb910b1SManuel Klimek   // We also know that there currently are no overlapping replacements.
226dcb910b1SManuel Klimek   // Thus, we know that all replacements that start after the end of the current
227dcb910b1SManuel Klimek   // replacement cannot overlap.
228dcb910b1SManuel Klimek   Replacement AtEnd(R.getFilePath(), R.getOffset() + R.getLength(), 0, "");
229dcb910b1SManuel Klimek 
23016c6d0acSManuel Klimek   // Find the first entry that starts after or at the end of R. Note that
23116c6d0acSManuel Klimek   // entries that start at the end can still be conflicting if R is an
23216c6d0acSManuel Klimek   // insertion.
233dcb910b1SManuel Klimek   auto I = Replaces.lower_bound(AtEnd);
2349df9b6fdSEric Liu   // If `I` starts at the same offset as `R`, `R` must be an insertion.
2359df9b6fdSEric Liu   if (I != Replaces.end() && R.getOffset() == I->getOffset()) {
2369df9b6fdSEric Liu     assert(R.getLength() == 0);
2379df9b6fdSEric Liu     // `I` is also an insertion, `R` and `I` conflict.
2386ef82b67SEric Liu     if (I->getLength() == 0) {
2396ef82b67SEric Liu       // Check if two insertions are order-indepedent: if inserting them in
2406ef82b67SEric Liu       // either order produces the same text, they are order-independent.
2416ef82b67SEric Liu       if ((R.getReplacementText() + I->getReplacementText()).str() !=
2426ef82b67SEric Liu           (I->getReplacementText() + R.getReplacementText()).str()) {
2439df9b6fdSEric Liu         return makeConflictReplacementsError(R, *I);
2446ef82b67SEric Liu       }
2456ef82b67SEric Liu       // If insertions are order-independent, we can merge them.
2466ef82b67SEric Liu       Replacement NewR(
2476ef82b67SEric Liu           R.getFilePath(), R.getOffset(), 0,
2486ef82b67SEric Liu           (R.getReplacementText() + I->getReplacementText()).str());
2496ef82b67SEric Liu       Replaces.erase(I);
2506237a21dSAlexander Shaposhnikov       Replaces.insert(std::move(NewR));
2516ef82b67SEric Liu       return llvm::Error::success();
2526ef82b67SEric Liu     }
2539df9b6fdSEric Liu     // Insertion `R` is adjacent to a non-insertion replacement `I`, so they
2549df9b6fdSEric Liu     // are order-independent. It is safe to assume that `R` will not conflict
2559df9b6fdSEric Liu     // with any replacement before `I` since all replacements before `I` must
2569df9b6fdSEric Liu     // either end before `R` or end at `R` but has length > 0 (if the
2579df9b6fdSEric Liu     // replacement before `I` is an insertion at `R`, it would have been `I`
2589df9b6fdSEric Liu     // since it is a lower bound of `AtEnd` and ordered before the current `I`
2599df9b6fdSEric Liu     // in the set).
2609df9b6fdSEric Liu     Replaces.insert(R);
2619df9b6fdSEric Liu     return llvm::Error::success();
2629df9b6fdSEric Liu   }
26316c6d0acSManuel Klimek 
2649df9b6fdSEric Liu   // `I` is the smallest iterator (after `R`) whose entry cannot overlap.
265dcb910b1SManuel Klimek   // If that is begin(), there are no overlaps.
266dcb910b1SManuel Klimek   if (I == Replaces.begin()) {
267dcb910b1SManuel Klimek     Replaces.insert(R);
268dcb910b1SManuel Klimek     return llvm::Error::success();
269dcb910b1SManuel Klimek   }
270dcb910b1SManuel Klimek   --I;
2716ef82b67SEric Liu   auto Overlap = [](const Replacement &R1, const Replacement &R2) -> bool {
2726ef82b67SEric Liu     return Range(R1.getOffset(), R1.getLength())
2736ef82b67SEric Liu         .overlapsWith(Range(R2.getOffset(), R2.getLength()));
2746ef82b67SEric Liu   };
275dcb910b1SManuel Klimek   // If the previous entry does not overlap, we know that entries before it
276dcb910b1SManuel Klimek   // can also not overlap.
2776ef82b67SEric Liu   if (!Overlap(R, *I)) {
2789df9b6fdSEric Liu     // If `R` and `I` do not have the same offset, it is safe to add `R` since
2799df9b6fdSEric Liu     // it must come after `I`. Otherwise:
2809df9b6fdSEric Liu     //   - If `R` is an insertion, `I` must not be an insertion since it would
2819df9b6fdSEric Liu     //   have come after `AtEnd`.
2829df9b6fdSEric Liu     //   - If `R` is not an insertion, `I` must be an insertion; otherwise, `R`
2839df9b6fdSEric Liu     //   and `I` would have overlapped.
2849df9b6fdSEric Liu     // In either case, we can safely insert `R`.
285dcb910b1SManuel Klimek     Replaces.insert(R);
2866ef82b67SEric Liu   } else {
2876ef82b67SEric Liu     // `I` overlaps with `R`. We need to check `R` against all overlapping
2886ef82b67SEric Liu     // replacements to see if they are order-indepedent. If they are, merge `R`
2896ef82b67SEric Liu     // with them and replace them with the merged replacements.
2906ef82b67SEric Liu     auto MergeBegin = I;
2916ef82b67SEric Liu     auto MergeEnd = std::next(I);
292dd7faec9SEric Liu     while (I != Replaces.begin()) {
293dd7faec9SEric Liu       --I;
294dd7faec9SEric Liu       // If `I` doesn't overlap with `R`, don't merge it.
295dd7faec9SEric Liu       if (!Overlap(R, *I))
296dd7faec9SEric Liu         break;
2976ef82b67SEric Liu       MergeBegin = I;
298dd7faec9SEric Liu     }
2996ef82b67SEric Liu     Replacements OverlapReplaces(MergeBegin, MergeEnd);
3006ef82b67SEric Liu     llvm::Expected<Replacements> Merged =
3016ef82b67SEric Liu         OverlapReplaces.mergeIfOrderIndependent(R);
3026ef82b67SEric Liu     if (!Merged)
3036ef82b67SEric Liu       return Merged.takeError();
3046ef82b67SEric Liu     Replaces.erase(MergeBegin, MergeEnd);
3056ef82b67SEric Liu     Replaces.insert(Merged->begin(), Merged->end());
306dcb910b1SManuel Klimek   }
3076ef82b67SEric Liu   return llvm::Error::success();
308dcb910b1SManuel Klimek }
309dcb910b1SManuel Klimek 
310d89ae9d3SDaniel Jasper namespace {
31140ef2fb3SEric Liu 
312d89ae9d3SDaniel Jasper // Represents a merged replacement, i.e. a replacement consisting of multiple
313d89ae9d3SDaniel Jasper // overlapping replacements from 'First' and 'Second' in mergeReplacements.
314d89ae9d3SDaniel Jasper //
315d89ae9d3SDaniel Jasper // Position projection:
316d89ae9d3SDaniel Jasper // Offsets and lengths of the replacements can generally refer to two different
317d89ae9d3SDaniel Jasper // coordinate spaces. Replacements from 'First' refer to the original text
318d89ae9d3SDaniel Jasper // whereas replacements from 'Second' refer to the text after applying 'First'.
319d89ae9d3SDaniel Jasper //
320d89ae9d3SDaniel Jasper // MergedReplacement always operates in the coordinate space of the original
321d89ae9d3SDaniel Jasper // text, i.e. transforms elements from 'Second' to take into account what was
322d89ae9d3SDaniel Jasper // changed based on the elements from 'First'.
323d89ae9d3SDaniel Jasper //
324d89ae9d3SDaniel Jasper // We can correctly calculate this projection as we look at the replacements in
325d89ae9d3SDaniel Jasper // order of strictly increasing offsets.
326d89ae9d3SDaniel Jasper //
327d89ae9d3SDaniel Jasper // Invariants:
328d89ae9d3SDaniel Jasper // * We always merge elements from 'First' into elements from 'Second' and vice
329d89ae9d3SDaniel Jasper //   versa. Within each set, the replacements are non-overlapping.
330d89ae9d3SDaniel Jasper // * We only extend to the right, i.e. merge elements with strictly increasing
331d89ae9d3SDaniel Jasper //   offsets.
332d89ae9d3SDaniel Jasper class MergedReplacement {
333d89ae9d3SDaniel Jasper public:
334d89ae9d3SDaniel Jasper   MergedReplacement(const Replacement &R, bool MergeSecond, int D)
335d89ae9d3SDaniel Jasper       : MergeSecond(MergeSecond), Delta(D), FilePath(R.getFilePath()),
336d89ae9d3SDaniel Jasper         Offset(R.getOffset() + (MergeSecond ? 0 : Delta)), Length(R.getLength()),
337d89ae9d3SDaniel Jasper         Text(R.getReplacementText()) {
338d89ae9d3SDaniel Jasper     Delta += MergeSecond ? 0 : Text.size() - Length;
339d89ae9d3SDaniel Jasper     DeltaFirst = MergeSecond ? Text.size() - Length : 0;
340d89ae9d3SDaniel Jasper   }
341d89ae9d3SDaniel Jasper 
342d89ae9d3SDaniel Jasper   // Merges the next element 'R' into this merged element. As we always merge
343d89ae9d3SDaniel Jasper   // from 'First' into 'Second' or vice versa, the MergedReplacement knows what
344d89ae9d3SDaniel Jasper   // set the next element is coming from.
345d89ae9d3SDaniel Jasper   void merge(const Replacement &R) {
346d89ae9d3SDaniel Jasper     if (MergeSecond) {
347d89ae9d3SDaniel Jasper       unsigned REnd = R.getOffset() + Delta + R.getLength();
348d89ae9d3SDaniel Jasper       unsigned End = Offset + Text.size();
349d89ae9d3SDaniel Jasper       if (REnd > End) {
350d89ae9d3SDaniel Jasper         Length += REnd - End;
351d89ae9d3SDaniel Jasper         MergeSecond = false;
352d89ae9d3SDaniel Jasper       }
353d89ae9d3SDaniel Jasper       StringRef TextRef = Text;
354d89ae9d3SDaniel Jasper       StringRef Head = TextRef.substr(0, R.getOffset() + Delta - Offset);
355d89ae9d3SDaniel Jasper       StringRef Tail = TextRef.substr(REnd - Offset);
356d89ae9d3SDaniel Jasper       Text = (Head + R.getReplacementText() + Tail).str();
357d89ae9d3SDaniel Jasper       Delta += R.getReplacementText().size() - R.getLength();
358d89ae9d3SDaniel Jasper     } else {
359d89ae9d3SDaniel Jasper       unsigned End = Offset + Length;
360d89ae9d3SDaniel Jasper       StringRef RText = R.getReplacementText();
361d89ae9d3SDaniel Jasper       StringRef Tail = RText.substr(End - R.getOffset());
362d89ae9d3SDaniel Jasper       Text = (Text + Tail).str();
363d89ae9d3SDaniel Jasper       if (R.getOffset() + RText.size() > End) {
364d89ae9d3SDaniel Jasper         Length = R.getOffset() + R.getLength() - Offset;
365d89ae9d3SDaniel Jasper         MergeSecond = true;
366d89ae9d3SDaniel Jasper       } else {
367d89ae9d3SDaniel Jasper         Length += R.getLength() - RText.size();
368d89ae9d3SDaniel Jasper       }
369d89ae9d3SDaniel Jasper       DeltaFirst += RText.size() - R.getLength();
370d89ae9d3SDaniel Jasper     }
371d89ae9d3SDaniel Jasper   }
372d89ae9d3SDaniel Jasper 
373d89ae9d3SDaniel Jasper   // Returns 'true' if 'R' starts strictly after the MergedReplacement and thus
374d89ae9d3SDaniel Jasper   // doesn't need to be merged.
375d89ae9d3SDaniel Jasper   bool endsBefore(const Replacement &R) const {
376d89ae9d3SDaniel Jasper     if (MergeSecond)
377d89ae9d3SDaniel Jasper       return Offset + Text.size() < R.getOffset() + Delta;
378d89ae9d3SDaniel Jasper     return Offset + Length < R.getOffset();
379d89ae9d3SDaniel Jasper   }
380d89ae9d3SDaniel Jasper 
381d89ae9d3SDaniel Jasper   // Returns 'true' if an element from the second set should be merged next.
382d89ae9d3SDaniel Jasper   bool mergeSecond() const { return MergeSecond; }
383d89ae9d3SDaniel Jasper   int deltaFirst() const { return DeltaFirst; }
384d89ae9d3SDaniel Jasper   Replacement asReplacement() const { return {FilePath, Offset, Length, Text}; }
385d89ae9d3SDaniel Jasper 
386d89ae9d3SDaniel Jasper private:
387d89ae9d3SDaniel Jasper   bool MergeSecond;
388d89ae9d3SDaniel Jasper 
389d89ae9d3SDaniel Jasper   // Amount of characters that elements from 'Second' need to be shifted by in
390d89ae9d3SDaniel Jasper   // order to refer to the original text.
391d89ae9d3SDaniel Jasper   int Delta;
392d89ae9d3SDaniel Jasper 
393d89ae9d3SDaniel Jasper   // Sum of all deltas (text-length - length) of elements from 'First' merged
394d89ae9d3SDaniel Jasper   // into this element. This is used to update 'Delta' once the
395d89ae9d3SDaniel Jasper   // MergedReplacement is completed.
396d89ae9d3SDaniel Jasper   int DeltaFirst;
397d89ae9d3SDaniel Jasper 
398d89ae9d3SDaniel Jasper   // Data of the actually merged replacement. FilePath and Offset aren't changed
399d89ae9d3SDaniel Jasper   // as the element is only extended to the right.
400d89ae9d3SDaniel Jasper   const StringRef FilePath;
401d89ae9d3SDaniel Jasper   const unsigned Offset;
402d89ae9d3SDaniel Jasper   unsigned Length;
403d89ae9d3SDaniel Jasper   std::string Text;
404d89ae9d3SDaniel Jasper };
40540ef2fb3SEric Liu 
406d89ae9d3SDaniel Jasper } // namespace
407d89ae9d3SDaniel Jasper 
40840ef2fb3SEric Liu Replacements Replacements::merge(const Replacements &ReplacesToMerge) const {
40940ef2fb3SEric Liu   if (empty() || ReplacesToMerge.empty())
41040ef2fb3SEric Liu     return empty() ? ReplacesToMerge : *this;
4114c1ef97aSEric Liu 
41240ef2fb3SEric Liu   auto &First = Replaces;
41340ef2fb3SEric Liu   auto &Second = ReplacesToMerge.Replaces;
414d89ae9d3SDaniel Jasper   // Delta is the amount of characters that replacements from 'Second' need to
415d89ae9d3SDaniel Jasper   // be shifted so that their offsets refer to the original text.
416d89ae9d3SDaniel Jasper   int Delta = 0;
41740ef2fb3SEric Liu   ReplacementsImpl Result;
418d89ae9d3SDaniel Jasper 
419d89ae9d3SDaniel Jasper   // Iterate over both sets and always add the next element (smallest total
420d89ae9d3SDaniel Jasper   // Offset) from either 'First' or 'Second'. Merge that element with
421d89ae9d3SDaniel Jasper   // subsequent replacements as long as they overlap. See more details in the
422d89ae9d3SDaniel Jasper   // comment on MergedReplacement.
423d89ae9d3SDaniel Jasper   for (auto FirstI = First.begin(), SecondI = Second.begin();
424d89ae9d3SDaniel Jasper        FirstI != First.end() || SecondI != Second.end();) {
425d89ae9d3SDaniel Jasper     bool NextIsFirst = SecondI == Second.end() ||
426a3e553a2SDaniel Jasper                        (FirstI != First.end() &&
427a3e553a2SDaniel Jasper                         FirstI->getOffset() < SecondI->getOffset() + Delta);
428d89ae9d3SDaniel Jasper     MergedReplacement Merged(NextIsFirst ? *FirstI : *SecondI, NextIsFirst,
429d89ae9d3SDaniel Jasper                              Delta);
430d89ae9d3SDaniel Jasper     ++(NextIsFirst ? FirstI : SecondI);
431d89ae9d3SDaniel Jasper 
432d89ae9d3SDaniel Jasper     while ((Merged.mergeSecond() && SecondI != Second.end()) ||
433d89ae9d3SDaniel Jasper            (!Merged.mergeSecond() && FirstI != First.end())) {
434d89ae9d3SDaniel Jasper       auto &I = Merged.mergeSecond() ? SecondI : FirstI;
435d89ae9d3SDaniel Jasper       if (Merged.endsBefore(*I))
436d89ae9d3SDaniel Jasper         break;
437d89ae9d3SDaniel Jasper       Merged.merge(*I);
438d89ae9d3SDaniel Jasper       ++I;
439d89ae9d3SDaniel Jasper     }
440d89ae9d3SDaniel Jasper     Delta -= Merged.deltaFirst();
441d89ae9d3SDaniel Jasper     Result.insert(Merged.asReplacement());
442d89ae9d3SDaniel Jasper   }
44340ef2fb3SEric Liu   return Replacements(Result.begin(), Result.end());
44440ef2fb3SEric Liu }
44540ef2fb3SEric Liu 
44640ef2fb3SEric Liu // Combines overlapping ranges in \p Ranges and sorts the combined ranges.
44740ef2fb3SEric Liu // Returns a set of non-overlapping and sorted ranges that is equivalent to
44840ef2fb3SEric Liu // \p Ranges.
44940ef2fb3SEric Liu static std::vector<Range> combineAndSortRanges(std::vector<Range> Ranges) {
45040ef2fb3SEric Liu   std::sort(Ranges.begin(), Ranges.end(),
45140ef2fb3SEric Liu             [](const Range &LHS, const Range &RHS) {
45240ef2fb3SEric Liu               if (LHS.getOffset() != RHS.getOffset())
45340ef2fb3SEric Liu                 return LHS.getOffset() < RHS.getOffset();
45440ef2fb3SEric Liu               return LHS.getLength() < RHS.getLength();
45540ef2fb3SEric Liu             });
45640ef2fb3SEric Liu   std::vector<Range> Result;
45740ef2fb3SEric Liu   for (const auto &R : Ranges) {
45840ef2fb3SEric Liu     if (Result.empty() ||
45940ef2fb3SEric Liu         Result.back().getOffset() + Result.back().getLength() < R.getOffset()) {
46040ef2fb3SEric Liu       Result.push_back(R);
46140ef2fb3SEric Liu     } else {
46240ef2fb3SEric Liu       unsigned NewEnd =
46340ef2fb3SEric Liu           std::max(Result.back().getOffset() + Result.back().getLength(),
46440ef2fb3SEric Liu                    R.getOffset() + R.getLength());
46540ef2fb3SEric Liu       Result[Result.size() - 1] =
46640ef2fb3SEric Liu           Range(Result.back().getOffset(), NewEnd - Result.back().getOffset());
46740ef2fb3SEric Liu     }
46840ef2fb3SEric Liu   }
469d89ae9d3SDaniel Jasper   return Result;
470d89ae9d3SDaniel Jasper }
471d89ae9d3SDaniel Jasper 
47240ef2fb3SEric Liu std::vector<Range>
47340ef2fb3SEric Liu calculateRangesAfterReplacements(const Replacements &Replaces,
47440ef2fb3SEric Liu                                  const std::vector<Range> &Ranges) {
47540ef2fb3SEric Liu   // To calculate the new ranges,
47640ef2fb3SEric Liu   //   - Turn \p Ranges into Replacements at (offset, length) with an empty
47740ef2fb3SEric Liu   //     (unimportant) replacement text of length "length".
47840ef2fb3SEric Liu   //   - Merge with \p Replaces.
47940ef2fb3SEric Liu   //   - The new ranges will be the affected ranges of the merged replacements.
48040ef2fb3SEric Liu   auto MergedRanges = combineAndSortRanges(Ranges);
48173337f3dSEric Liu   if (Replaces.empty())
48273337f3dSEric Liu     return MergedRanges;
48340ef2fb3SEric Liu   tooling::Replacements FakeReplaces;
48440ef2fb3SEric Liu   for (const auto &R : MergedRanges) {
48540ef2fb3SEric Liu     auto Err = FakeReplaces.add(Replacement(Replaces.begin()->getFilePath(),
48640ef2fb3SEric Liu                                             R.getOffset(), R.getLength(),
48740ef2fb3SEric Liu                                             std::string(R.getLength(), ' ')));
48840ef2fb3SEric Liu     assert(!Err &&
48940ef2fb3SEric Liu            "Replacements must not conflict since ranges have been merged.");
49040ef2fb3SEric Liu     (void)Err;
49140ef2fb3SEric Liu   }
49240ef2fb3SEric Liu   return FakeReplaces.merge(Replaces).getAffectedRanges();
49340ef2fb3SEric Liu }
49440ef2fb3SEric Liu 
49540ef2fb3SEric Liu std::vector<Range> Replacements::getAffectedRanges() const {
49640ef2fb3SEric Liu   std::vector<Range> ChangedRanges;
49740ef2fb3SEric Liu   int Shift = 0;
49840ef2fb3SEric Liu   for (const Replacement &R : Replaces) {
49940ef2fb3SEric Liu     unsigned Offset = R.getOffset() + Shift;
50040ef2fb3SEric Liu     unsigned Length = R.getReplacementText().size();
50140ef2fb3SEric Liu     Shift += Length - R.getLength();
50240ef2fb3SEric Liu     ChangedRanges.push_back(Range(Offset, Length));
50340ef2fb3SEric Liu   }
50440ef2fb3SEric Liu   return combineAndSortRanges(ChangedRanges);
50540ef2fb3SEric Liu }
50640ef2fb3SEric Liu 
50740ef2fb3SEric Liu unsigned Replacements::getShiftedCodePosition(unsigned Position) const {
50840ef2fb3SEric Liu   unsigned Offset = 0;
50940ef2fb3SEric Liu   for (const auto& R : Replaces) {
51040ef2fb3SEric Liu     if (R.getOffset() + R.getLength() <= Position) {
51140ef2fb3SEric Liu       Offset += R.getReplacementText().size() - R.getLength();
51240ef2fb3SEric Liu       continue;
51340ef2fb3SEric Liu     }
51440ef2fb3SEric Liu     if (R.getOffset() < Position &&
51540ef2fb3SEric Liu         R.getOffset() + R.getReplacementText().size() <= Position) {
51640ef2fb3SEric Liu       Position = R.getOffset() + R.getReplacementText().size();
51740ef2fb3SEric Liu       if (R.getReplacementText().size() > 0)
51840ef2fb3SEric Liu         Position--;
51940ef2fb3SEric Liu     }
52040ef2fb3SEric Liu     break;
52140ef2fb3SEric Liu   }
52240ef2fb3SEric Liu   return Position + Offset;
52340ef2fb3SEric Liu }
52440ef2fb3SEric Liu 
52540ef2fb3SEric Liu bool applyAllReplacements(const Replacements &Replaces, Rewriter &Rewrite) {
52640ef2fb3SEric Liu   bool Result = true;
527e9906525SEric Liu   for (auto I = Replaces.rbegin(), E = Replaces.rend(); I != E; ++I) {
52840ef2fb3SEric Liu     if (I->isApplicable()) {
52940ef2fb3SEric Liu       Result = I->apply(Rewrite) && Result;
53040ef2fb3SEric Liu     } else {
53140ef2fb3SEric Liu       Result = false;
53240ef2fb3SEric Liu     }
53340ef2fb3SEric Liu   }
53440ef2fb3SEric Liu   return Result;
53540ef2fb3SEric Liu }
53640ef2fb3SEric Liu 
53740ef2fb3SEric Liu llvm::Expected<std::string> applyAllReplacements(StringRef Code,
53840ef2fb3SEric Liu                                                 const Replacements &Replaces) {
53940ef2fb3SEric Liu   if (Replaces.empty())
54040ef2fb3SEric Liu     return Code.str();
54140ef2fb3SEric Liu 
54240ef2fb3SEric Liu   IntrusiveRefCntPtr<vfs::InMemoryFileSystem> InMemoryFileSystem(
54340ef2fb3SEric Liu       new vfs::InMemoryFileSystem);
54440ef2fb3SEric Liu   FileManager Files(FileSystemOptions(), InMemoryFileSystem);
54540ef2fb3SEric Liu   DiagnosticsEngine Diagnostics(
54640ef2fb3SEric Liu       IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
54740ef2fb3SEric Liu       new DiagnosticOptions);
54840ef2fb3SEric Liu   SourceManager SourceMgr(Diagnostics, Files);
54940ef2fb3SEric Liu   Rewriter Rewrite(SourceMgr, LangOptions());
55040ef2fb3SEric Liu   InMemoryFileSystem->addFile(
55140ef2fb3SEric Liu       "<stdin>", 0, llvm::MemoryBuffer::getMemBuffer(Code, "<stdin>"));
55240ef2fb3SEric Liu   FileID ID = SourceMgr.createFileID(Files.getFile("<stdin>"), SourceLocation(),
55340ef2fb3SEric Liu                                      clang::SrcMgr::C_User);
554e9906525SEric Liu   for (auto I = Replaces.rbegin(), E = Replaces.rend(); I != E; ++I) {
55540ef2fb3SEric Liu     Replacement Replace("<stdin>", I->getOffset(), I->getLength(),
55640ef2fb3SEric Liu                         I->getReplacementText());
55740ef2fb3SEric Liu     if (!Replace.apply(Rewrite))
55840ef2fb3SEric Liu       return llvm::make_error<llvm::StringError>(
55940ef2fb3SEric Liu           "Failed to apply replacement: " + Replace.toString(),
56040ef2fb3SEric Liu           llvm::inconvertibleErrorCode());
56140ef2fb3SEric Liu   }
56240ef2fb3SEric Liu   std::string Result;
56340ef2fb3SEric Liu   llvm::raw_string_ostream OS(Result);
56440ef2fb3SEric Liu   Rewrite.getEditBuffer(ID).write(OS);
56540ef2fb3SEric Liu   OS.flush();
56640ef2fb3SEric Liu   return Result;
56740ef2fb3SEric Liu }
56840ef2fb3SEric Liu 
569cefe763dSEric Liu std::map<std::string, Replacements> groupReplacementsByFile(
570*cf2913c6SEric Liu     FileManager &FileMgr,
571cefe763dSEric Liu     const std::map<std::string, Replacements> &FileToReplaces) {
572cefe763dSEric Liu   std::map<std::string, Replacements> Result;
573*cf2913c6SEric Liu   llvm::SmallPtrSet<const FileEntry *, 16> ProcessedFileEntries;
574cefe763dSEric Liu   for (const auto &Entry : FileToReplaces) {
575*cf2913c6SEric Liu     const FileEntry *FE = FileMgr.getFile(Entry.first);
576*cf2913c6SEric Liu     if (!FE)
577*cf2913c6SEric Liu       llvm::errs() << "File path " << Entry.first << " is invalid.\n";
578*cf2913c6SEric Liu     else if (ProcessedFileEntries.insert(FE).second)
579*cf2913c6SEric Liu       Result[Entry.first] = std::move(Entry.second);
580cefe763dSEric Liu   }
581cefe763dSEric Liu   return Result;
58240ef2fb3SEric Liu }
58340ef2fb3SEric Liu 
584cb3e6188SDaniel Jasper } // end namespace tooling
585cb3e6188SDaniel Jasper } // end namespace clang
586