16366efedSEugene Zelenko //===- Replacement.cpp - Framework for clang refactoring tools ------------===//
2cb3e6188SDaniel Jasper //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6cb3e6188SDaniel Jasper //
7cb3e6188SDaniel Jasper //===----------------------------------------------------------------------===//
8cb3e6188SDaniel Jasper //
9cb3e6188SDaniel Jasper // Implements classes to support/store refactorings.
10cb3e6188SDaniel Jasper //
11cb3e6188SDaniel Jasper //===----------------------------------------------------------------------===//
12cb3e6188SDaniel Jasper
13b12e5a5cSManuel Klimek #include "clang/Tooling/Core/Replacement.h"
14cb3e6188SDaniel Jasper #include "clang/Basic/Diagnostic.h"
15cb3e6188SDaniel Jasper #include "clang/Basic/DiagnosticIDs.h"
16cb3e6188SDaniel Jasper #include "clang/Basic/DiagnosticOptions.h"
17cb3e6188SDaniel Jasper #include "clang/Basic/FileManager.h"
186366efedSEugene Zelenko #include "clang/Basic/FileSystemOptions.h"
196366efedSEugene Zelenko #include "clang/Basic/SourceLocation.h"
20cb3e6188SDaniel Jasper #include "clang/Basic/SourceManager.h"
21cb3e6188SDaniel Jasper #include "clang/Lex/Lexer.h"
226366efedSEugene Zelenko #include "clang/Rewrite/Core/RewriteBuffer.h"
23cb3e6188SDaniel Jasper #include "clang/Rewrite/Core/Rewriter.h"
246366efedSEugene Zelenko #include "llvm/ADT/IntrusiveRefCntPtr.h"
25cf2913c6SEric Liu #include "llvm/ADT/SmallPtrSet.h"
266366efedSEugene Zelenko #include "llvm/ADT/StringRef.h"
276366efedSEugene Zelenko #include "llvm/Support/Error.h"
286366efedSEugene Zelenko #include "llvm/Support/ErrorHandling.h"
296366efedSEugene Zelenko #include "llvm/Support/MemoryBuffer.h"
30fc51490bSJonas Devlieghere #include "llvm/Support/VirtualFileSystem.h"
316366efedSEugene Zelenko #include "llvm/Support/raw_ostream.h"
326366efedSEugene Zelenko #include <algorithm>
336366efedSEugene Zelenko #include <cassert>
346366efedSEugene Zelenko #include <limits>
356366efedSEugene Zelenko #include <map>
366366efedSEugene Zelenko #include <string>
376366efedSEugene Zelenko #include <utility>
386366efedSEugene Zelenko #include <vector>
39cb3e6188SDaniel Jasper
406366efedSEugene Zelenko using namespace clang;
416366efedSEugene Zelenko using namespace tooling;
42cb3e6188SDaniel Jasper
43cb3e6188SDaniel Jasper static const char * const InvalidLocation = "";
44cb3e6188SDaniel Jasper
Replacement()45e86a5f4cSEric Liu Replacement::Replacement() : FilePath(InvalidLocation) {}
46cb3e6188SDaniel Jasper
Replacement(StringRef FilePath,unsigned Offset,unsigned Length,StringRef ReplacementText)47cb3e6188SDaniel Jasper Replacement::Replacement(StringRef FilePath, unsigned Offset, unsigned Length,
48cb3e6188SDaniel Jasper StringRef ReplacementText)
49adcd0268SBenjamin Kramer : FilePath(std::string(FilePath)), ReplacementRange(Offset, Length),
50adcd0268SBenjamin Kramer ReplacementText(std::string(ReplacementText)) {}
51cb3e6188SDaniel Jasper
Replacement(const SourceManager & Sources,SourceLocation Start,unsigned Length,StringRef ReplacementText)52cb3e6188SDaniel Jasper Replacement::Replacement(const SourceManager &Sources, SourceLocation Start,
53cb3e6188SDaniel Jasper unsigned Length, StringRef ReplacementText) {
54cb3e6188SDaniel Jasper setFromSourceLocation(Sources, Start, Length, ReplacementText);
55cb3e6188SDaniel Jasper }
56cb3e6188SDaniel Jasper
Replacement(const SourceManager & Sources,const CharSourceRange & Range,StringRef ReplacementText,const LangOptions & LangOpts)57cb3e6188SDaniel Jasper Replacement::Replacement(const SourceManager &Sources,
58cb3e6188SDaniel Jasper const CharSourceRange &Range,
5994a89231SManuel Klimek StringRef ReplacementText,
6094a89231SManuel Klimek const LangOptions &LangOpts) {
6194a89231SManuel Klimek setFromSourceRange(Sources, Range, ReplacementText, LangOpts);
62cb3e6188SDaniel Jasper }
63cb3e6188SDaniel Jasper
isApplicable() const64cb3e6188SDaniel Jasper bool Replacement::isApplicable() const {
65cb3e6188SDaniel Jasper return FilePath != InvalidLocation;
66cb3e6188SDaniel Jasper }
67cb3e6188SDaniel Jasper
apply(Rewriter & Rewrite) const68cb3e6188SDaniel Jasper bool Replacement::apply(Rewriter &Rewrite) const {
69cb3e6188SDaniel Jasper SourceManager &SM = Rewrite.getSourceMgr();
708d323d15SHarlan Haskins auto Entry = SM.getFileManager().getFile(FilePath);
71cb3e6188SDaniel Jasper if (!Entry)
72cb3e6188SDaniel Jasper return false;
734c1ef97aSEric Liu
748d323d15SHarlan Haskins FileID ID = SM.getOrCreateFileID(*Entry, SrcMgr::C_User);
75cb3e6188SDaniel Jasper const SourceLocation Start =
76cb3e6188SDaniel Jasper SM.getLocForStartOfFile(ID).
77cb3e6188SDaniel Jasper getLocWithOffset(ReplacementRange.getOffset());
78cb3e6188SDaniel Jasper // ReplaceText returns false on success.
79cb3e6188SDaniel Jasper // ReplaceText only fails if the source location is not a file location, in
80cb3e6188SDaniel Jasper // which case we already returned false earlier.
81cb3e6188SDaniel Jasper bool RewriteSucceeded = !Rewrite.ReplaceText(
82cb3e6188SDaniel Jasper Start, ReplacementRange.getLength(), ReplacementText);
83cb3e6188SDaniel Jasper assert(RewriteSucceeded);
84cb3e6188SDaniel Jasper return RewriteSucceeded;
85cb3e6188SDaniel Jasper }
86cb3e6188SDaniel Jasper
toString() const87cb3e6188SDaniel Jasper std::string Replacement::toString() const {
88b1223b1dSManuel Klimek std::string Result;
89b1223b1dSManuel Klimek llvm::raw_string_ostream Stream(Result);
90b1223b1dSManuel Klimek Stream << FilePath << ": " << ReplacementRange.getOffset() << ":+"
91cb3e6188SDaniel Jasper << ReplacementRange.getLength() << ":\"" << ReplacementText << "\"";
92b1223b1dSManuel Klimek return Stream.str();
93cb3e6188SDaniel Jasper }
94cb3e6188SDaniel Jasper
956366efedSEugene Zelenko namespace clang {
966366efedSEugene Zelenko namespace tooling {
976366efedSEugene Zelenko
operator <(const Replacement & LHS,const Replacement & RHS)98cb3e6188SDaniel Jasper bool operator<(const Replacement &LHS, const Replacement &RHS) {
99cb3e6188SDaniel Jasper if (LHS.getOffset() != RHS.getOffset())
100cb3e6188SDaniel Jasper return LHS.getOffset() < RHS.getOffset();
1010f291276SDaniel Jasper
102cb3e6188SDaniel Jasper if (LHS.getLength() != RHS.getLength())
103e9906525SEric Liu return LHS.getLength() < RHS.getLength();
1040f291276SDaniel Jasper
105cb3e6188SDaniel Jasper if (LHS.getFilePath() != RHS.getFilePath())
106cb3e6188SDaniel Jasper return LHS.getFilePath() < RHS.getFilePath();
107cb3e6188SDaniel Jasper return LHS.getReplacementText() < RHS.getReplacementText();
108cb3e6188SDaniel Jasper }
109cb3e6188SDaniel Jasper
operator ==(const Replacement & LHS,const Replacement & RHS)110cb3e6188SDaniel Jasper bool operator==(const Replacement &LHS, const Replacement &RHS) {
111cb3e6188SDaniel Jasper return LHS.getOffset() == RHS.getOffset() &&
112cb3e6188SDaniel Jasper LHS.getLength() == RHS.getLength() &&
113cb3e6188SDaniel Jasper LHS.getFilePath() == RHS.getFilePath() &&
114cb3e6188SDaniel Jasper LHS.getReplacementText() == RHS.getReplacementText();
115cb3e6188SDaniel Jasper }
116cb3e6188SDaniel Jasper
1176366efedSEugene Zelenko } // namespace tooling
1186366efedSEugene Zelenko } // namespace clang
1196366efedSEugene Zelenko
setFromSourceLocation(const SourceManager & Sources,SourceLocation Start,unsigned Length,StringRef ReplacementText)120cb3e6188SDaniel Jasper void Replacement::setFromSourceLocation(const SourceManager &Sources,
121cb3e6188SDaniel Jasper SourceLocation Start, unsigned Length,
122cb3e6188SDaniel Jasper StringRef ReplacementText) {
123cb3e6188SDaniel Jasper const std::pair<FileID, unsigned> DecomposedLocation =
124cb3e6188SDaniel Jasper Sources.getDecomposedLoc(Start);
125cb3e6188SDaniel Jasper const FileEntry *Entry = Sources.getFileEntryForID(DecomposedLocation.first);
126adcd0268SBenjamin Kramer this->FilePath = std::string(Entry ? Entry->getName() : InvalidLocation);
127cb3e6188SDaniel Jasper this->ReplacementRange = Range(DecomposedLocation.second, Length);
128adcd0268SBenjamin Kramer this->ReplacementText = std::string(ReplacementText);
129cb3e6188SDaniel Jasper }
130cb3e6188SDaniel Jasper
131cb3e6188SDaniel Jasper // FIXME: This should go into the Lexer, but we need to figure out how
132cb3e6188SDaniel Jasper // to handle ranges for refactoring in general first - there is no obvious
133cb3e6188SDaniel Jasper // good way how to integrate this into the Lexer yet.
getRangeSize(const SourceManager & Sources,const CharSourceRange & Range,const LangOptions & LangOpts)134cb3e6188SDaniel Jasper static int getRangeSize(const SourceManager &Sources,
13594a89231SManuel Klimek const CharSourceRange &Range,
13694a89231SManuel Klimek const LangOptions &LangOpts) {
137cb3e6188SDaniel Jasper SourceLocation SpellingBegin = Sources.getSpellingLoc(Range.getBegin());
138cb3e6188SDaniel Jasper SourceLocation SpellingEnd = Sources.getSpellingLoc(Range.getEnd());
139cb3e6188SDaniel Jasper std::pair<FileID, unsigned> Start = Sources.getDecomposedLoc(SpellingBegin);
140cb3e6188SDaniel Jasper std::pair<FileID, unsigned> End = Sources.getDecomposedLoc(SpellingEnd);
141cb3e6188SDaniel Jasper if (Start.first != End.first) return -1;
142cb3e6188SDaniel Jasper if (Range.isTokenRange())
14394a89231SManuel Klimek End.second += Lexer::MeasureTokenLength(SpellingEnd, Sources, LangOpts);
144cb3e6188SDaniel Jasper return End.second - Start.second;
145cb3e6188SDaniel Jasper }
146cb3e6188SDaniel Jasper
setFromSourceRange(const SourceManager & Sources,const CharSourceRange & Range,StringRef ReplacementText,const LangOptions & LangOpts)147cb3e6188SDaniel Jasper void Replacement::setFromSourceRange(const SourceManager &Sources,
148cb3e6188SDaniel Jasper const CharSourceRange &Range,
14994a89231SManuel Klimek StringRef ReplacementText,
15094a89231SManuel Klimek const LangOptions &LangOpts) {
151cb3e6188SDaniel Jasper setFromSourceLocation(Sources, Sources.getSpellingLoc(Range.getBegin()),
15294a89231SManuel Klimek getRangeSize(Sources, Range, LangOpts),
15394a89231SManuel Klimek ReplacementText);
154cb3e6188SDaniel Jasper }
155cb3e6188SDaniel Jasper
1566ef82b67SEric Liu Replacement
getReplacementInChangedCode(const Replacement & R) const1576ef82b67SEric Liu Replacements::getReplacementInChangedCode(const Replacement &R) const {
1586ef82b67SEric Liu unsigned NewStart = getShiftedCodePosition(R.getOffset());
1596ef82b67SEric Liu unsigned NewEnd = getShiftedCodePosition(R.getOffset() + R.getLength());
1606ef82b67SEric Liu return Replacement(R.getFilePath(), NewStart, NewEnd - NewStart,
1616ef82b67SEric Liu R.getReplacementText());
1626ef82b67SEric Liu }
1636ef82b67SEric Liu
getReplacementErrString(replacement_error Err)164e86a5f4cSEric Liu static std::string getReplacementErrString(replacement_error Err) {
165e86a5f4cSEric Liu switch (Err) {
166e86a5f4cSEric Liu case replacement_error::fail_to_apply:
167e86a5f4cSEric Liu return "Failed to apply a replacement.";
168e86a5f4cSEric Liu case replacement_error::wrong_file_path:
169e86a5f4cSEric Liu return "The new replacement's file path is different from the file path of "
170e86a5f4cSEric Liu "existing replacements";
171e86a5f4cSEric Liu case replacement_error::overlap_conflict:
172e86a5f4cSEric Liu return "The new replacement overlaps with an existing replacement.";
173e86a5f4cSEric Liu case replacement_error::insert_conflict:
174e86a5f4cSEric Liu return "The new insertion has the same insert location as an existing "
175e86a5f4cSEric Liu "replacement.";
1769df9b6fdSEric Liu }
177e86a5f4cSEric Liu llvm_unreachable("A value of replacement_error has no message.");
178e86a5f4cSEric Liu }
179e86a5f4cSEric Liu
message() const180e86a5f4cSEric Liu std::string ReplacementError::message() const {
181e86a5f4cSEric Liu std::string Message = getReplacementErrString(Err);
182*97afce08SKazu Hirata if (NewReplacement)
183e86a5f4cSEric Liu Message += "\nNew replacement: " + NewReplacement->toString();
184*97afce08SKazu Hirata if (ExistingReplacement)
185e86a5f4cSEric Liu Message += "\nExisting replacement: " + ExistingReplacement->toString();
186e86a5f4cSEric Liu return Message;
187e86a5f4cSEric Liu }
188e86a5f4cSEric Liu
189e86a5f4cSEric Liu char ReplacementError::ID = 0;
1909df9b6fdSEric Liu
getCanonicalReplacements() const1916ef82b67SEric Liu Replacements Replacements::getCanonicalReplacements() const {
1926ef82b67SEric Liu std::vector<Replacement> NewReplaces;
1936ef82b67SEric Liu // Merge adjacent replacements.
1946ef82b67SEric Liu for (const auto &R : Replaces) {
1956ef82b67SEric Liu if (NewReplaces.empty()) {
1966ef82b67SEric Liu NewReplaces.push_back(R);
1976ef82b67SEric Liu continue;
1986ef82b67SEric Liu }
1996ef82b67SEric Liu auto &Prev = NewReplaces.back();
2006ef82b67SEric Liu unsigned PrevEnd = Prev.getOffset() + Prev.getLength();
2016ef82b67SEric Liu if (PrevEnd < R.getOffset()) {
2026ef82b67SEric Liu NewReplaces.push_back(R);
2036ef82b67SEric Liu } else {
2046ef82b67SEric Liu assert(PrevEnd == R.getOffset() &&
2056ef82b67SEric Liu "Existing replacements must not overlap.");
2066ef82b67SEric Liu Replacement NewR(
2076ef82b67SEric Liu R.getFilePath(), Prev.getOffset(), Prev.getLength() + R.getLength(),
2086ef82b67SEric Liu (Prev.getReplacementText() + R.getReplacementText()).str());
2096ef82b67SEric Liu Prev = NewR;
2106ef82b67SEric Liu }
2116ef82b67SEric Liu }
2126ef82b67SEric Liu ReplacementsImpl NewReplacesImpl(NewReplaces.begin(), NewReplaces.end());
2136ef82b67SEric Liu return Replacements(NewReplacesImpl.begin(), NewReplacesImpl.end());
2146ef82b67SEric Liu }
2156ef82b67SEric Liu
2166ef82b67SEric Liu // `R` and `Replaces` are order-independent if applying them in either order
2176ef82b67SEric Liu // has the same effect, so we need to compare replacements associated to
2186ef82b67SEric Liu // applying them in either order.
2196ef82b67SEric Liu llvm::Expected<Replacements>
mergeIfOrderIndependent(const Replacement & R) const2206ef82b67SEric Liu Replacements::mergeIfOrderIndependent(const Replacement &R) const {
2216ef82b67SEric Liu Replacements Rs(R);
2222a8c18d9SAlexander Kornienko // A Replacements set containing a single replacement that is `R` referring to
2236ef82b67SEric Liu // the code after the existing replacements `Replaces` are applied.
2246ef82b67SEric Liu Replacements RsShiftedByReplaces(getReplacementInChangedCode(R));
2256ef82b67SEric Liu // A Replacements set that is `Replaces` referring to the code after `R` is
2266ef82b67SEric Liu // applied.
2276ef82b67SEric Liu Replacements ReplacesShiftedByRs;
2286ef82b67SEric Liu for (const auto &Replace : Replaces)
2296ef82b67SEric Liu ReplacesShiftedByRs.Replaces.insert(
2306ef82b67SEric Liu Rs.getReplacementInChangedCode(Replace));
2316ef82b67SEric Liu // This is equivalent to applying `Replaces` first and then `R`.
2326ef82b67SEric Liu auto MergeShiftedRs = merge(RsShiftedByReplaces);
2336ef82b67SEric Liu // This is equivalent to applying `R` first and then `Replaces`.
2346ef82b67SEric Liu auto MergeShiftedReplaces = Rs.merge(ReplacesShiftedByRs);
2356ef82b67SEric Liu
2366ef82b67SEric Liu // Since empty or segmented replacements around existing replacements might be
2376ef82b67SEric Liu // produced above, we need to compare replacements in canonical forms.
2386ef82b67SEric Liu if (MergeShiftedRs.getCanonicalReplacements() ==
2396ef82b67SEric Liu MergeShiftedReplaces.getCanonicalReplacements())
2406ef82b67SEric Liu return MergeShiftedRs;
241e86a5f4cSEric Liu return llvm::make_error<ReplacementError>(replacement_error::overlap_conflict,
242e86a5f4cSEric Liu R, *Replaces.begin());
2436ef82b67SEric Liu }
2446ef82b67SEric Liu
add(const Replacement & R)24540ef2fb3SEric Liu llvm::Error Replacements::add(const Replacement &R) {
246dcb910b1SManuel Klimek // Check the file path.
247dcb910b1SManuel Klimek if (!Replaces.empty() && R.getFilePath() != Replaces.begin()->getFilePath())
248e86a5f4cSEric Liu return llvm::make_error<ReplacementError>(
249e86a5f4cSEric Liu replacement_error::wrong_file_path, R, *Replaces.begin());
250cb3e6188SDaniel Jasper
251dcb910b1SManuel Klimek // Special-case header insertions.
2526366efedSEugene Zelenko if (R.getOffset() == std::numeric_limits<unsigned>::max()) {
25340ef2fb3SEric Liu Replaces.insert(R);
25440ef2fb3SEric Liu return llvm::Error::success();
255b12e5a5cSManuel Klimek }
256b12e5a5cSManuel Klimek
257dcb910b1SManuel Klimek // This replacement cannot conflict with replacements that end before
258dcb910b1SManuel Klimek // this replacement starts or start after this replacement ends.
259dcb910b1SManuel Klimek // We also know that there currently are no overlapping replacements.
260dcb910b1SManuel Klimek // Thus, we know that all replacements that start after the end of the current
261dcb910b1SManuel Klimek // replacement cannot overlap.
262dcb910b1SManuel Klimek Replacement AtEnd(R.getFilePath(), R.getOffset() + R.getLength(), 0, "");
263dcb910b1SManuel Klimek
26416c6d0acSManuel Klimek // Find the first entry that starts after or at the end of R. Note that
26516c6d0acSManuel Klimek // entries that start at the end can still be conflicting if R is an
26616c6d0acSManuel Klimek // insertion.
267dcb910b1SManuel Klimek auto I = Replaces.lower_bound(AtEnd);
2689df9b6fdSEric Liu // If `I` starts at the same offset as `R`, `R` must be an insertion.
2699df9b6fdSEric Liu if (I != Replaces.end() && R.getOffset() == I->getOffset()) {
2709df9b6fdSEric Liu assert(R.getLength() == 0);
2719df9b6fdSEric Liu // `I` is also an insertion, `R` and `I` conflict.
2726ef82b67SEric Liu if (I->getLength() == 0) {
2736ef82b67SEric Liu // Check if two insertions are order-indepedent: if inserting them in
2746ef82b67SEric Liu // either order produces the same text, they are order-independent.
2756ef82b67SEric Liu if ((R.getReplacementText() + I->getReplacementText()).str() !=
276e86a5f4cSEric Liu (I->getReplacementText() + R.getReplacementText()).str())
277e86a5f4cSEric Liu return llvm::make_error<ReplacementError>(
278e86a5f4cSEric Liu replacement_error::insert_conflict, R, *I);
2796ef82b67SEric Liu // If insertions are order-independent, we can merge them.
2806ef82b67SEric Liu Replacement NewR(
2816ef82b67SEric Liu R.getFilePath(), R.getOffset(), 0,
2826ef82b67SEric Liu (R.getReplacementText() + I->getReplacementText()).str());
2836ef82b67SEric Liu Replaces.erase(I);
2846237a21dSAlexander Shaposhnikov Replaces.insert(std::move(NewR));
2856ef82b67SEric Liu return llvm::Error::success();
2866ef82b67SEric Liu }
2879df9b6fdSEric Liu // Insertion `R` is adjacent to a non-insertion replacement `I`, so they
2889df9b6fdSEric Liu // are order-independent. It is safe to assume that `R` will not conflict
2899df9b6fdSEric Liu // with any replacement before `I` since all replacements before `I` must
2909df9b6fdSEric Liu // either end before `R` or end at `R` but has length > 0 (if the
2919df9b6fdSEric Liu // replacement before `I` is an insertion at `R`, it would have been `I`
2929df9b6fdSEric Liu // since it is a lower bound of `AtEnd` and ordered before the current `I`
2939df9b6fdSEric Liu // in the set).
2949df9b6fdSEric Liu Replaces.insert(R);
2959df9b6fdSEric Liu return llvm::Error::success();
2969df9b6fdSEric Liu }
29716c6d0acSManuel Klimek
2989df9b6fdSEric Liu // `I` is the smallest iterator (after `R`) whose entry cannot overlap.
299dcb910b1SManuel Klimek // If that is begin(), there are no overlaps.
300dcb910b1SManuel Klimek if (I == Replaces.begin()) {
301dcb910b1SManuel Klimek Replaces.insert(R);
302dcb910b1SManuel Klimek return llvm::Error::success();
303dcb910b1SManuel Klimek }
304dcb910b1SManuel Klimek --I;
3056ef82b67SEric Liu auto Overlap = [](const Replacement &R1, const Replacement &R2) -> bool {
3066ef82b67SEric Liu return Range(R1.getOffset(), R1.getLength())
3076ef82b67SEric Liu .overlapsWith(Range(R2.getOffset(), R2.getLength()));
3086ef82b67SEric Liu };
309dcb910b1SManuel Klimek // If the previous entry does not overlap, we know that entries before it
310dcb910b1SManuel Klimek // can also not overlap.
3116ef82b67SEric Liu if (!Overlap(R, *I)) {
3129df9b6fdSEric Liu // If `R` and `I` do not have the same offset, it is safe to add `R` since
3139df9b6fdSEric Liu // it must come after `I`. Otherwise:
3149df9b6fdSEric Liu // - If `R` is an insertion, `I` must not be an insertion since it would
3159df9b6fdSEric Liu // have come after `AtEnd`.
3169df9b6fdSEric Liu // - If `R` is not an insertion, `I` must be an insertion; otherwise, `R`
3179df9b6fdSEric Liu // and `I` would have overlapped.
3189df9b6fdSEric Liu // In either case, we can safely insert `R`.
319dcb910b1SManuel Klimek Replaces.insert(R);
3206ef82b67SEric Liu } else {
3216ef82b67SEric Liu // `I` overlaps with `R`. We need to check `R` against all overlapping
3226ef82b67SEric Liu // replacements to see if they are order-indepedent. If they are, merge `R`
3236ef82b67SEric Liu // with them and replace them with the merged replacements.
3246ef82b67SEric Liu auto MergeBegin = I;
3256ef82b67SEric Liu auto MergeEnd = std::next(I);
326dd7faec9SEric Liu while (I != Replaces.begin()) {
327dd7faec9SEric Liu --I;
328dd7faec9SEric Liu // If `I` doesn't overlap with `R`, don't merge it.
329dd7faec9SEric Liu if (!Overlap(R, *I))
330dd7faec9SEric Liu break;
3316ef82b67SEric Liu MergeBegin = I;
332dd7faec9SEric Liu }
3336ef82b67SEric Liu Replacements OverlapReplaces(MergeBegin, MergeEnd);
3346ef82b67SEric Liu llvm::Expected<Replacements> Merged =
3356ef82b67SEric Liu OverlapReplaces.mergeIfOrderIndependent(R);
3366ef82b67SEric Liu if (!Merged)
3376ef82b67SEric Liu return Merged.takeError();
3386ef82b67SEric Liu Replaces.erase(MergeBegin, MergeEnd);
3396ef82b67SEric Liu Replaces.insert(Merged->begin(), Merged->end());
340dcb910b1SManuel Klimek }
3416ef82b67SEric Liu return llvm::Error::success();
342dcb910b1SManuel Klimek }
343dcb910b1SManuel Klimek
344d89ae9d3SDaniel Jasper namespace {
34540ef2fb3SEric Liu
346d89ae9d3SDaniel Jasper // Represents a merged replacement, i.e. a replacement consisting of multiple
347d89ae9d3SDaniel Jasper // overlapping replacements from 'First' and 'Second' in mergeReplacements.
348d89ae9d3SDaniel Jasper //
349d89ae9d3SDaniel Jasper // Position projection:
350d89ae9d3SDaniel Jasper // Offsets and lengths of the replacements can generally refer to two different
351d89ae9d3SDaniel Jasper // coordinate spaces. Replacements from 'First' refer to the original text
352d89ae9d3SDaniel Jasper // whereas replacements from 'Second' refer to the text after applying 'First'.
353d89ae9d3SDaniel Jasper //
354d89ae9d3SDaniel Jasper // MergedReplacement always operates in the coordinate space of the original
355d89ae9d3SDaniel Jasper // text, i.e. transforms elements from 'Second' to take into account what was
356d89ae9d3SDaniel Jasper // changed based on the elements from 'First'.
357d89ae9d3SDaniel Jasper //
358d89ae9d3SDaniel Jasper // We can correctly calculate this projection as we look at the replacements in
359d89ae9d3SDaniel Jasper // order of strictly increasing offsets.
360d89ae9d3SDaniel Jasper //
361d89ae9d3SDaniel Jasper // Invariants:
362d89ae9d3SDaniel Jasper // * We always merge elements from 'First' into elements from 'Second' and vice
363d89ae9d3SDaniel Jasper // versa. Within each set, the replacements are non-overlapping.
364d89ae9d3SDaniel Jasper // * We only extend to the right, i.e. merge elements with strictly increasing
365d89ae9d3SDaniel Jasper // offsets.
366d89ae9d3SDaniel Jasper class MergedReplacement {
367d89ae9d3SDaniel Jasper public:
MergedReplacement(const Replacement & R,bool MergeSecond,int D)368d89ae9d3SDaniel Jasper MergedReplacement(const Replacement &R, bool MergeSecond, int D)
369d89ae9d3SDaniel Jasper : MergeSecond(MergeSecond), Delta(D), FilePath(R.getFilePath()),
370adcd0268SBenjamin Kramer Offset(R.getOffset() + (MergeSecond ? 0 : Delta)),
371adcd0268SBenjamin Kramer Length(R.getLength()), Text(std::string(R.getReplacementText())) {
372d89ae9d3SDaniel Jasper Delta += MergeSecond ? 0 : Text.size() - Length;
373d89ae9d3SDaniel Jasper DeltaFirst = MergeSecond ? Text.size() - Length : 0;
374d89ae9d3SDaniel Jasper }
375d89ae9d3SDaniel Jasper
376d89ae9d3SDaniel Jasper // Merges the next element 'R' into this merged element. As we always merge
377d89ae9d3SDaniel Jasper // from 'First' into 'Second' or vice versa, the MergedReplacement knows what
378d89ae9d3SDaniel Jasper // set the next element is coming from.
merge(const Replacement & R)379d89ae9d3SDaniel Jasper void merge(const Replacement &R) {
380d89ae9d3SDaniel Jasper if (MergeSecond) {
381d89ae9d3SDaniel Jasper unsigned REnd = R.getOffset() + Delta + R.getLength();
382d89ae9d3SDaniel Jasper unsigned End = Offset + Text.size();
383d89ae9d3SDaniel Jasper if (REnd > End) {
384d89ae9d3SDaniel Jasper Length += REnd - End;
385d89ae9d3SDaniel Jasper MergeSecond = false;
386d89ae9d3SDaniel Jasper }
387d89ae9d3SDaniel Jasper StringRef TextRef = Text;
388d89ae9d3SDaniel Jasper StringRef Head = TextRef.substr(0, R.getOffset() + Delta - Offset);
389d89ae9d3SDaniel Jasper StringRef Tail = TextRef.substr(REnd - Offset);
390d89ae9d3SDaniel Jasper Text = (Head + R.getReplacementText() + Tail).str();
391d89ae9d3SDaniel Jasper Delta += R.getReplacementText().size() - R.getLength();
392d89ae9d3SDaniel Jasper } else {
393d89ae9d3SDaniel Jasper unsigned End = Offset + Length;
394d89ae9d3SDaniel Jasper StringRef RText = R.getReplacementText();
395d89ae9d3SDaniel Jasper StringRef Tail = RText.substr(End - R.getOffset());
396d89ae9d3SDaniel Jasper Text = (Text + Tail).str();
397d89ae9d3SDaniel Jasper if (R.getOffset() + RText.size() > End) {
398d89ae9d3SDaniel Jasper Length = R.getOffset() + R.getLength() - Offset;
399d89ae9d3SDaniel Jasper MergeSecond = true;
400d89ae9d3SDaniel Jasper } else {
401d89ae9d3SDaniel Jasper Length += R.getLength() - RText.size();
402d89ae9d3SDaniel Jasper }
403d89ae9d3SDaniel Jasper DeltaFirst += RText.size() - R.getLength();
404d89ae9d3SDaniel Jasper }
405d89ae9d3SDaniel Jasper }
406d89ae9d3SDaniel Jasper
407d89ae9d3SDaniel Jasper // Returns 'true' if 'R' starts strictly after the MergedReplacement and thus
408d89ae9d3SDaniel Jasper // doesn't need to be merged.
endsBefore(const Replacement & R) const409d89ae9d3SDaniel Jasper bool endsBefore(const Replacement &R) const {
410d89ae9d3SDaniel Jasper if (MergeSecond)
411d89ae9d3SDaniel Jasper return Offset + Text.size() < R.getOffset() + Delta;
412d89ae9d3SDaniel Jasper return Offset + Length < R.getOffset();
413d89ae9d3SDaniel Jasper }
414d89ae9d3SDaniel Jasper
415d89ae9d3SDaniel Jasper // Returns 'true' if an element from the second set should be merged next.
mergeSecond() const416d89ae9d3SDaniel Jasper bool mergeSecond() const { return MergeSecond; }
4176366efedSEugene Zelenko
deltaFirst() const418d89ae9d3SDaniel Jasper int deltaFirst() const { return DeltaFirst; }
asReplacement() const419d89ae9d3SDaniel Jasper Replacement asReplacement() const { return {FilePath, Offset, Length, Text}; }
420d89ae9d3SDaniel Jasper
421d89ae9d3SDaniel Jasper private:
422d89ae9d3SDaniel Jasper bool MergeSecond;
423d89ae9d3SDaniel Jasper
424d89ae9d3SDaniel Jasper // Amount of characters that elements from 'Second' need to be shifted by in
425d89ae9d3SDaniel Jasper // order to refer to the original text.
426d89ae9d3SDaniel Jasper int Delta;
427d89ae9d3SDaniel Jasper
428d89ae9d3SDaniel Jasper // Sum of all deltas (text-length - length) of elements from 'First' merged
429d89ae9d3SDaniel Jasper // into this element. This is used to update 'Delta' once the
430d89ae9d3SDaniel Jasper // MergedReplacement is completed.
431d89ae9d3SDaniel Jasper int DeltaFirst;
432d89ae9d3SDaniel Jasper
433d89ae9d3SDaniel Jasper // Data of the actually merged replacement. FilePath and Offset aren't changed
434d89ae9d3SDaniel Jasper // as the element is only extended to the right.
435d89ae9d3SDaniel Jasper const StringRef FilePath;
436d89ae9d3SDaniel Jasper const unsigned Offset;
437d89ae9d3SDaniel Jasper unsigned Length;
438d89ae9d3SDaniel Jasper std::string Text;
439d89ae9d3SDaniel Jasper };
44040ef2fb3SEric Liu
441d89ae9d3SDaniel Jasper } // namespace
442d89ae9d3SDaniel Jasper
merge(const Replacements & ReplacesToMerge) const44340ef2fb3SEric Liu Replacements Replacements::merge(const Replacements &ReplacesToMerge) const {
44440ef2fb3SEric Liu if (empty() || ReplacesToMerge.empty())
44540ef2fb3SEric Liu return empty() ? ReplacesToMerge : *this;
4464c1ef97aSEric Liu
44740ef2fb3SEric Liu auto &First = Replaces;
44840ef2fb3SEric Liu auto &Second = ReplacesToMerge.Replaces;
449d89ae9d3SDaniel Jasper // Delta is the amount of characters that replacements from 'Second' need to
450d89ae9d3SDaniel Jasper // be shifted so that their offsets refer to the original text.
451d89ae9d3SDaniel Jasper int Delta = 0;
45240ef2fb3SEric Liu ReplacementsImpl Result;
453d89ae9d3SDaniel Jasper
454d89ae9d3SDaniel Jasper // Iterate over both sets and always add the next element (smallest total
455d89ae9d3SDaniel Jasper // Offset) from either 'First' or 'Second'. Merge that element with
456d89ae9d3SDaniel Jasper // subsequent replacements as long as they overlap. See more details in the
457d89ae9d3SDaniel Jasper // comment on MergedReplacement.
458d89ae9d3SDaniel Jasper for (auto FirstI = First.begin(), SecondI = Second.begin();
459d89ae9d3SDaniel Jasper FirstI != First.end() || SecondI != Second.end();) {
460d89ae9d3SDaniel Jasper bool NextIsFirst = SecondI == Second.end() ||
461a3e553a2SDaniel Jasper (FirstI != First.end() &&
462a3e553a2SDaniel Jasper FirstI->getOffset() < SecondI->getOffset() + Delta);
463d89ae9d3SDaniel Jasper MergedReplacement Merged(NextIsFirst ? *FirstI : *SecondI, NextIsFirst,
464d89ae9d3SDaniel Jasper Delta);
465d89ae9d3SDaniel Jasper ++(NextIsFirst ? FirstI : SecondI);
466d89ae9d3SDaniel Jasper
467d89ae9d3SDaniel Jasper while ((Merged.mergeSecond() && SecondI != Second.end()) ||
468d89ae9d3SDaniel Jasper (!Merged.mergeSecond() && FirstI != First.end())) {
469d89ae9d3SDaniel Jasper auto &I = Merged.mergeSecond() ? SecondI : FirstI;
470d89ae9d3SDaniel Jasper if (Merged.endsBefore(*I))
471d89ae9d3SDaniel Jasper break;
472d89ae9d3SDaniel Jasper Merged.merge(*I);
473d89ae9d3SDaniel Jasper ++I;
474d89ae9d3SDaniel Jasper }
475d89ae9d3SDaniel Jasper Delta -= Merged.deltaFirst();
476d89ae9d3SDaniel Jasper Result.insert(Merged.asReplacement());
477d89ae9d3SDaniel Jasper }
47840ef2fb3SEric Liu return Replacements(Result.begin(), Result.end());
47940ef2fb3SEric Liu }
48040ef2fb3SEric Liu
48140ef2fb3SEric Liu // Combines overlapping ranges in \p Ranges and sorts the combined ranges.
48240ef2fb3SEric Liu // Returns a set of non-overlapping and sorted ranges that is equivalent to
48340ef2fb3SEric Liu // \p Ranges.
combineAndSortRanges(std::vector<Range> Ranges)48440ef2fb3SEric Liu static std::vector<Range> combineAndSortRanges(std::vector<Range> Ranges) {
48555fab260SFangrui Song llvm::sort(Ranges, [](const Range &LHS, const Range &RHS) {
48640ef2fb3SEric Liu if (LHS.getOffset() != RHS.getOffset())
48740ef2fb3SEric Liu return LHS.getOffset() < RHS.getOffset();
48840ef2fb3SEric Liu return LHS.getLength() < RHS.getLength();
48940ef2fb3SEric Liu });
49040ef2fb3SEric Liu std::vector<Range> Result;
49140ef2fb3SEric Liu for (const auto &R : Ranges) {
49240ef2fb3SEric Liu if (Result.empty() ||
49340ef2fb3SEric Liu Result.back().getOffset() + Result.back().getLength() < R.getOffset()) {
49440ef2fb3SEric Liu Result.push_back(R);
49540ef2fb3SEric Liu } else {
49640ef2fb3SEric Liu unsigned NewEnd =
49740ef2fb3SEric Liu std::max(Result.back().getOffset() + Result.back().getLength(),
49840ef2fb3SEric Liu R.getOffset() + R.getLength());
49940ef2fb3SEric Liu Result[Result.size() - 1] =
50040ef2fb3SEric Liu Range(Result.back().getOffset(), NewEnd - Result.back().getOffset());
50140ef2fb3SEric Liu }
50240ef2fb3SEric Liu }
503d89ae9d3SDaniel Jasper return Result;
504d89ae9d3SDaniel Jasper }
505d89ae9d3SDaniel Jasper
5066366efedSEugene Zelenko namespace clang {
5076366efedSEugene Zelenko namespace tooling {
5086366efedSEugene Zelenko
50940ef2fb3SEric Liu std::vector<Range>
calculateRangesAfterReplacements(const Replacements & Replaces,const std::vector<Range> & Ranges)51040ef2fb3SEric Liu calculateRangesAfterReplacements(const Replacements &Replaces,
51140ef2fb3SEric Liu const std::vector<Range> &Ranges) {
51240ef2fb3SEric Liu // To calculate the new ranges,
51340ef2fb3SEric Liu // - Turn \p Ranges into Replacements at (offset, length) with an empty
51440ef2fb3SEric Liu // (unimportant) replacement text of length "length".
51540ef2fb3SEric Liu // - Merge with \p Replaces.
51640ef2fb3SEric Liu // - The new ranges will be the affected ranges of the merged replacements.
51740ef2fb3SEric Liu auto MergedRanges = combineAndSortRanges(Ranges);
51873337f3dSEric Liu if (Replaces.empty())
51973337f3dSEric Liu return MergedRanges;
52040ef2fb3SEric Liu tooling::Replacements FakeReplaces;
52140ef2fb3SEric Liu for (const auto &R : MergedRanges) {
522e0a89091SStephen Hines llvm::cantFail(
523e0a89091SStephen Hines FakeReplaces.add(Replacement(Replaces.begin()->getFilePath(),
52440ef2fb3SEric Liu R.getOffset(), R.getLength(),
525e0a89091SStephen Hines std::string(R.getLength(), ' '))),
52640ef2fb3SEric Liu "Replacements must not conflict since ranges have been merged.");
52740ef2fb3SEric Liu }
52840ef2fb3SEric Liu return FakeReplaces.merge(Replaces).getAffectedRanges();
52940ef2fb3SEric Liu }
53040ef2fb3SEric Liu
5316366efedSEugene Zelenko } // namespace tooling
5326366efedSEugene Zelenko } // namespace clang
5336366efedSEugene Zelenko
getAffectedRanges() const53440ef2fb3SEric Liu std::vector<Range> Replacements::getAffectedRanges() const {
53540ef2fb3SEric Liu std::vector<Range> ChangedRanges;
53640ef2fb3SEric Liu int Shift = 0;
5376366efedSEugene Zelenko for (const auto &R : Replaces) {
53840ef2fb3SEric Liu unsigned Offset = R.getOffset() + Shift;
53940ef2fb3SEric Liu unsigned Length = R.getReplacementText().size();
54040ef2fb3SEric Liu Shift += Length - R.getLength();
54140ef2fb3SEric Liu ChangedRanges.push_back(Range(Offset, Length));
54240ef2fb3SEric Liu }
54340ef2fb3SEric Liu return combineAndSortRanges(ChangedRanges);
54440ef2fb3SEric Liu }
54540ef2fb3SEric Liu
getShiftedCodePosition(unsigned Position) const54640ef2fb3SEric Liu unsigned Replacements::getShiftedCodePosition(unsigned Position) const {
54740ef2fb3SEric Liu unsigned Offset = 0;
54840ef2fb3SEric Liu for (const auto &R : Replaces) {
54940ef2fb3SEric Liu if (R.getOffset() + R.getLength() <= Position) {
55040ef2fb3SEric Liu Offset += R.getReplacementText().size() - R.getLength();
55140ef2fb3SEric Liu continue;
55240ef2fb3SEric Liu }
55340ef2fb3SEric Liu if (R.getOffset() < Position &&
55440ef2fb3SEric Liu R.getOffset() + R.getReplacementText().size() <= Position) {
55540ef2fb3SEric Liu Position = R.getOffset() + R.getReplacementText().size();
5566366efedSEugene Zelenko if (!R.getReplacementText().empty())
55740ef2fb3SEric Liu Position--;
55840ef2fb3SEric Liu }
55940ef2fb3SEric Liu break;
56040ef2fb3SEric Liu }
56140ef2fb3SEric Liu return Position + Offset;
56240ef2fb3SEric Liu }
56340ef2fb3SEric Liu
5646366efedSEugene Zelenko namespace clang {
5656366efedSEugene Zelenko namespace tooling {
5666366efedSEugene Zelenko
applyAllReplacements(const Replacements & Replaces,Rewriter & Rewrite)56740ef2fb3SEric Liu bool applyAllReplacements(const Replacements &Replaces, Rewriter &Rewrite) {
56840ef2fb3SEric Liu bool Result = true;
569e9906525SEric Liu for (auto I = Replaces.rbegin(), E = Replaces.rend(); I != E; ++I) {
57040ef2fb3SEric Liu if (I->isApplicable()) {
57140ef2fb3SEric Liu Result = I->apply(Rewrite) && Result;
57240ef2fb3SEric Liu } else {
57340ef2fb3SEric Liu Result = false;
57440ef2fb3SEric Liu }
57540ef2fb3SEric Liu }
57640ef2fb3SEric Liu return Result;
57740ef2fb3SEric Liu }
57840ef2fb3SEric Liu
applyAllReplacements(StringRef Code,const Replacements & Replaces)57940ef2fb3SEric Liu llvm::Expected<std::string> applyAllReplacements(StringRef Code,
58040ef2fb3SEric Liu const Replacements &Replaces) {
58140ef2fb3SEric Liu if (Replaces.empty())
58240ef2fb3SEric Liu return Code.str();
58340ef2fb3SEric Liu
584fc51490bSJonas Devlieghere IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem> InMemoryFileSystem(
585fc51490bSJonas Devlieghere new llvm::vfs::InMemoryFileSystem);
58640ef2fb3SEric Liu FileManager Files(FileSystemOptions(), InMemoryFileSystem);
58740ef2fb3SEric Liu DiagnosticsEngine Diagnostics(
58840ef2fb3SEric Liu IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
58940ef2fb3SEric Liu new DiagnosticOptions);
59040ef2fb3SEric Liu SourceManager SourceMgr(Diagnostics, Files);
59140ef2fb3SEric Liu Rewriter Rewrite(SourceMgr, LangOptions());
59240ef2fb3SEric Liu InMemoryFileSystem->addFile(
59340ef2fb3SEric Liu "<stdin>", 0, llvm::MemoryBuffer::getMemBuffer(Code, "<stdin>"));
5942ea8c69eSDuncan P. N. Exon Smith FileID ID = SourceMgr.createFileID(*Files.getOptionalFileRef("<stdin>"),
5958d323d15SHarlan Haskins SourceLocation(),
59640ef2fb3SEric Liu clang::SrcMgr::C_User);
597e9906525SEric Liu for (auto I = Replaces.rbegin(), E = Replaces.rend(); I != E; ++I) {
59840ef2fb3SEric Liu Replacement Replace("<stdin>", I->getOffset(), I->getLength(),
59940ef2fb3SEric Liu I->getReplacementText());
60040ef2fb3SEric Liu if (!Replace.apply(Rewrite))
601e86a5f4cSEric Liu return llvm::make_error<ReplacementError>(
602e86a5f4cSEric Liu replacement_error::fail_to_apply, Replace);
60340ef2fb3SEric Liu }
60440ef2fb3SEric Liu std::string Result;
60540ef2fb3SEric Liu llvm::raw_string_ostream OS(Result);
60640ef2fb3SEric Liu Rewrite.getEditBuffer(ID).write(OS);
60740ef2fb3SEric Liu OS.flush();
60840ef2fb3SEric Liu return Result;
60940ef2fb3SEric Liu }
61040ef2fb3SEric Liu
groupReplacementsByFile(FileManager & FileMgr,const std::map<std::string,Replacements> & FileToReplaces)611cefe763dSEric Liu std::map<std::string, Replacements> groupReplacementsByFile(
612cf2913c6SEric Liu FileManager &FileMgr,
613cefe763dSEric Liu const std::map<std::string, Replacements> &FileToReplaces) {
614cefe763dSEric Liu std::map<std::string, Replacements> Result;
615cf2913c6SEric Liu llvm::SmallPtrSet<const FileEntry *, 16> ProcessedFileEntries;
616cefe763dSEric Liu for (const auto &Entry : FileToReplaces) {
6178d323d15SHarlan Haskins auto FE = FileMgr.getFile(Entry.first);
618cf2913c6SEric Liu if (!FE)
619cf2913c6SEric Liu llvm::errs() << "File path " << Entry.first << " is invalid.\n";
6208d323d15SHarlan Haskins else if (ProcessedFileEntries.insert(*FE).second)
621cf2913c6SEric Liu Result[Entry.first] = std::move(Entry.second);
622cefe763dSEric Liu }
623cefe763dSEric Liu return Result;
62440ef2fb3SEric Liu }
62540ef2fb3SEric Liu
6266366efedSEugene Zelenko } // namespace tooling
6276366efedSEugene Zelenko } // namespace clang
628