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" 23cb3e6188SDaniel Jasper #include "llvm/Support/FileSystem.h" 24cb3e6188SDaniel Jasper #include "llvm/Support/raw_os_ostream.h" 25cb3e6188SDaniel Jasper 26cb3e6188SDaniel Jasper namespace clang { 27cb3e6188SDaniel Jasper namespace tooling { 28cb3e6188SDaniel Jasper 29cb3e6188SDaniel Jasper static const char * const InvalidLocation = ""; 30cb3e6188SDaniel Jasper 31cb3e6188SDaniel Jasper Replacement::Replacement() 32cb3e6188SDaniel Jasper : FilePath(InvalidLocation) {} 33cb3e6188SDaniel Jasper 34cb3e6188SDaniel Jasper Replacement::Replacement(StringRef FilePath, unsigned Offset, unsigned Length, 35cb3e6188SDaniel Jasper StringRef ReplacementText) 36cb3e6188SDaniel Jasper : FilePath(FilePath), ReplacementRange(Offset, Length), 37cb3e6188SDaniel Jasper ReplacementText(ReplacementText) {} 38cb3e6188SDaniel Jasper 39cb3e6188SDaniel Jasper Replacement::Replacement(const SourceManager &Sources, SourceLocation Start, 40cb3e6188SDaniel Jasper unsigned Length, StringRef ReplacementText) { 41cb3e6188SDaniel Jasper setFromSourceLocation(Sources, Start, Length, ReplacementText); 42cb3e6188SDaniel Jasper } 43cb3e6188SDaniel Jasper 44cb3e6188SDaniel Jasper Replacement::Replacement(const SourceManager &Sources, 45cb3e6188SDaniel Jasper const CharSourceRange &Range, 4694a89231SManuel Klimek StringRef ReplacementText, 4794a89231SManuel Klimek const LangOptions &LangOpts) { 4894a89231SManuel Klimek setFromSourceRange(Sources, Range, ReplacementText, LangOpts); 49cb3e6188SDaniel Jasper } 50cb3e6188SDaniel Jasper 51cb3e6188SDaniel Jasper bool Replacement::isApplicable() const { 52cb3e6188SDaniel Jasper return FilePath != InvalidLocation; 53cb3e6188SDaniel Jasper } 54cb3e6188SDaniel Jasper 55cb3e6188SDaniel Jasper bool Replacement::apply(Rewriter &Rewrite) const { 56cb3e6188SDaniel Jasper SourceManager &SM = Rewrite.getSourceMgr(); 57cb3e6188SDaniel Jasper const FileEntry *Entry = SM.getFileManager().getFile(FilePath); 58cb3e6188SDaniel Jasper if (!Entry) 59cb3e6188SDaniel Jasper return false; 604c1ef97aSEric Liu 614c1ef97aSEric Liu FileID ID = SM.getOrCreateFileID(Entry, SrcMgr::C_User); 62cb3e6188SDaniel Jasper const SourceLocation Start = 63cb3e6188SDaniel Jasper SM.getLocForStartOfFile(ID). 64cb3e6188SDaniel Jasper getLocWithOffset(ReplacementRange.getOffset()); 65cb3e6188SDaniel Jasper // ReplaceText returns false on success. 66cb3e6188SDaniel Jasper // ReplaceText only fails if the source location is not a file location, in 67cb3e6188SDaniel Jasper // which case we already returned false earlier. 68cb3e6188SDaniel Jasper bool RewriteSucceeded = !Rewrite.ReplaceText( 69cb3e6188SDaniel Jasper Start, ReplacementRange.getLength(), ReplacementText); 70cb3e6188SDaniel Jasper assert(RewriteSucceeded); 71cb3e6188SDaniel Jasper return RewriteSucceeded; 72cb3e6188SDaniel Jasper } 73cb3e6188SDaniel Jasper 74cb3e6188SDaniel Jasper std::string Replacement::toString() const { 75b1223b1dSManuel Klimek std::string Result; 76b1223b1dSManuel Klimek llvm::raw_string_ostream Stream(Result); 77b1223b1dSManuel Klimek Stream << FilePath << ": " << ReplacementRange.getOffset() << ":+" 78cb3e6188SDaniel Jasper << ReplacementRange.getLength() << ":\"" << ReplacementText << "\""; 79b1223b1dSManuel Klimek return Stream.str(); 80cb3e6188SDaniel Jasper } 81cb3e6188SDaniel Jasper 82cb3e6188SDaniel Jasper bool operator<(const Replacement &LHS, const Replacement &RHS) { 83cb3e6188SDaniel Jasper if (LHS.getOffset() != RHS.getOffset()) 84cb3e6188SDaniel Jasper return LHS.getOffset() < RHS.getOffset(); 850f291276SDaniel Jasper 86cb3e6188SDaniel Jasper if (LHS.getLength() != RHS.getLength()) 87e9906525SEric Liu return LHS.getLength() < RHS.getLength(); 880f291276SDaniel Jasper 89cb3e6188SDaniel Jasper if (LHS.getFilePath() != RHS.getFilePath()) 90cb3e6188SDaniel Jasper return LHS.getFilePath() < RHS.getFilePath(); 91cb3e6188SDaniel Jasper return LHS.getReplacementText() < RHS.getReplacementText(); 92cb3e6188SDaniel Jasper } 93cb3e6188SDaniel Jasper 94cb3e6188SDaniel Jasper bool operator==(const Replacement &LHS, const Replacement &RHS) { 95cb3e6188SDaniel Jasper return LHS.getOffset() == RHS.getOffset() && 96cb3e6188SDaniel Jasper LHS.getLength() == RHS.getLength() && 97cb3e6188SDaniel Jasper LHS.getFilePath() == RHS.getFilePath() && 98cb3e6188SDaniel Jasper LHS.getReplacementText() == RHS.getReplacementText(); 99cb3e6188SDaniel Jasper } 100cb3e6188SDaniel Jasper 101cb3e6188SDaniel Jasper void Replacement::setFromSourceLocation(const SourceManager &Sources, 102cb3e6188SDaniel Jasper SourceLocation Start, unsigned Length, 103cb3e6188SDaniel Jasper StringRef ReplacementText) { 104cb3e6188SDaniel Jasper const std::pair<FileID, unsigned> DecomposedLocation = 105cb3e6188SDaniel Jasper Sources.getDecomposedLoc(Start); 106cb3e6188SDaniel Jasper const FileEntry *Entry = Sources.getFileEntryForID(DecomposedLocation.first); 107cac8fc23SBenjamin Kramer this->FilePath = Entry ? Entry->getName() : InvalidLocation; 108cb3e6188SDaniel Jasper this->ReplacementRange = Range(DecomposedLocation.second, Length); 109cb3e6188SDaniel Jasper this->ReplacementText = ReplacementText; 110cb3e6188SDaniel Jasper } 111cb3e6188SDaniel Jasper 112cb3e6188SDaniel Jasper // FIXME: This should go into the Lexer, but we need to figure out how 113cb3e6188SDaniel Jasper // to handle ranges for refactoring in general first - there is no obvious 114cb3e6188SDaniel Jasper // good way how to integrate this into the Lexer yet. 115cb3e6188SDaniel Jasper static int getRangeSize(const SourceManager &Sources, 11694a89231SManuel Klimek const CharSourceRange &Range, 11794a89231SManuel Klimek const LangOptions &LangOpts) { 118cb3e6188SDaniel Jasper SourceLocation SpellingBegin = Sources.getSpellingLoc(Range.getBegin()); 119cb3e6188SDaniel Jasper SourceLocation SpellingEnd = Sources.getSpellingLoc(Range.getEnd()); 120cb3e6188SDaniel Jasper std::pair<FileID, unsigned> Start = Sources.getDecomposedLoc(SpellingBegin); 121cb3e6188SDaniel Jasper std::pair<FileID, unsigned> End = Sources.getDecomposedLoc(SpellingEnd); 122cb3e6188SDaniel Jasper if (Start.first != End.first) return -1; 123cb3e6188SDaniel Jasper if (Range.isTokenRange()) 12494a89231SManuel Klimek End.second += Lexer::MeasureTokenLength(SpellingEnd, Sources, LangOpts); 125cb3e6188SDaniel Jasper return End.second - Start.second; 126cb3e6188SDaniel Jasper } 127cb3e6188SDaniel Jasper 128cb3e6188SDaniel Jasper void Replacement::setFromSourceRange(const SourceManager &Sources, 129cb3e6188SDaniel Jasper const CharSourceRange &Range, 13094a89231SManuel Klimek StringRef ReplacementText, 13194a89231SManuel Klimek const LangOptions &LangOpts) { 132cb3e6188SDaniel Jasper setFromSourceLocation(Sources, Sources.getSpellingLoc(Range.getBegin()), 13394a89231SManuel Klimek getRangeSize(Sources, Range, LangOpts), 13494a89231SManuel Klimek ReplacementText); 135cb3e6188SDaniel Jasper } 136cb3e6188SDaniel Jasper 137*9df9b6fdSEric Liu llvm::Error makeConflictReplacementsError(const Replacement &New, 138*9df9b6fdSEric Liu const Replacement &Existing) { 139*9df9b6fdSEric Liu return llvm::make_error<llvm::StringError>( 140*9df9b6fdSEric Liu "New replacement:\n" + New.toString() + 141*9df9b6fdSEric Liu "\nconflicts with existing replacement:\n" + Existing.toString(), 142*9df9b6fdSEric Liu llvm::inconvertibleErrorCode()); 143*9df9b6fdSEric Liu } 144*9df9b6fdSEric Liu 14540ef2fb3SEric Liu llvm::Error Replacements::add(const Replacement &R) { 146dcb910b1SManuel Klimek // Check the file path. 147dcb910b1SManuel Klimek if (!Replaces.empty() && R.getFilePath() != Replaces.begin()->getFilePath()) 1484f8d9943SEric Liu return llvm::make_error<llvm::StringError>( 14940ef2fb3SEric Liu "All replacements must have the same file path. New replacement: " + 15040ef2fb3SEric Liu R.getFilePath() + ", existing replacements: " + 151dcb910b1SManuel Klimek Replaces.begin()->getFilePath() + "\n", 15240ef2fb3SEric Liu llvm::inconvertibleErrorCode()); 153cb3e6188SDaniel Jasper 154dcb910b1SManuel Klimek // Special-case header insertions. 155dcb910b1SManuel Klimek if (R.getOffset() == UINT_MAX) { 15640ef2fb3SEric Liu Replaces.insert(R); 15740ef2fb3SEric Liu return llvm::Error::success(); 158b12e5a5cSManuel Klimek } 159b12e5a5cSManuel Klimek 160dcb910b1SManuel Klimek // This replacement cannot conflict with replacements that end before 161dcb910b1SManuel Klimek // this replacement starts or start after this replacement ends. 162dcb910b1SManuel Klimek // We also know that there currently are no overlapping replacements. 163dcb910b1SManuel Klimek // Thus, we know that all replacements that start after the end of the current 164dcb910b1SManuel Klimek // replacement cannot overlap. 165dcb910b1SManuel Klimek Replacement AtEnd(R.getFilePath(), R.getOffset() + R.getLength(), 0, ""); 166dcb910b1SManuel Klimek 16716c6d0acSManuel Klimek // Find the first entry that starts after or at the end of R. Note that 16816c6d0acSManuel Klimek // entries that start at the end can still be conflicting if R is an 16916c6d0acSManuel Klimek // insertion. 170dcb910b1SManuel Klimek auto I = Replaces.lower_bound(AtEnd); 171*9df9b6fdSEric Liu // If `I` starts at the same offset as `R`, `R` must be an insertion. 172*9df9b6fdSEric Liu if (I != Replaces.end() && R.getOffset() == I->getOffset()) { 173*9df9b6fdSEric Liu assert(R.getLength() == 0); 174*9df9b6fdSEric Liu // `I` is also an insertion, `R` and `I` conflict. 175*9df9b6fdSEric Liu if (I->getLength() == 0) 176*9df9b6fdSEric Liu return makeConflictReplacementsError(R, *I); 177*9df9b6fdSEric Liu // Insertion `R` is adjacent to a non-insertion replacement `I`, so they 178*9df9b6fdSEric Liu // are order-independent. It is safe to assume that `R` will not conflict 179*9df9b6fdSEric Liu // with any replacement before `I` since all replacements before `I` must 180*9df9b6fdSEric Liu // either end before `R` or end at `R` but has length > 0 (if the 181*9df9b6fdSEric Liu // replacement before `I` is an insertion at `R`, it would have been `I` 182*9df9b6fdSEric Liu // since it is a lower bound of `AtEnd` and ordered before the current `I` 183*9df9b6fdSEric Liu // in the set). 184*9df9b6fdSEric Liu Replaces.insert(R); 185*9df9b6fdSEric Liu return llvm::Error::success(); 186*9df9b6fdSEric Liu } 18716c6d0acSManuel Klimek 188*9df9b6fdSEric Liu // `I` is the smallest iterator (after `R`) whose entry cannot overlap. 189dcb910b1SManuel Klimek // If that is begin(), there are no overlaps. 190dcb910b1SManuel Klimek if (I == Replaces.begin()) { 191dcb910b1SManuel Klimek Replaces.insert(R); 192dcb910b1SManuel Klimek return llvm::Error::success(); 193dcb910b1SManuel Klimek } 194dcb910b1SManuel Klimek --I; 195dcb910b1SManuel Klimek // If the previous entry does not overlap, we know that entries before it 196dcb910b1SManuel Klimek // can also not overlap. 197*9df9b6fdSEric Liu if (!Range(R.getOffset(), R.getLength()) 198dcb910b1SManuel Klimek .overlapsWith(Range(I->getOffset(), I->getLength()))) { 199*9df9b6fdSEric Liu // If `R` and `I` do not have the same offset, it is safe to add `R` since 200*9df9b6fdSEric Liu // it must come after `I`. Otherwise: 201*9df9b6fdSEric Liu // - If `R` is an insertion, `I` must not be an insertion since it would 202*9df9b6fdSEric Liu // have come after `AtEnd`. 203*9df9b6fdSEric Liu // - If `R` is not an insertion, `I` must be an insertion; otherwise, `R` 204*9df9b6fdSEric Liu // and `I` would have overlapped. 205*9df9b6fdSEric Liu // In either case, we can safely insert `R`. 206dcb910b1SManuel Klimek Replaces.insert(R); 207dcb910b1SManuel Klimek return llvm::Error::success(); 208dcb910b1SManuel Klimek } 209*9df9b6fdSEric Liu return makeConflictReplacementsError(R, *I); 210dcb910b1SManuel Klimek } 211dcb910b1SManuel Klimek 212d89ae9d3SDaniel Jasper namespace { 21340ef2fb3SEric Liu 214d89ae9d3SDaniel Jasper // Represents a merged replacement, i.e. a replacement consisting of multiple 215d89ae9d3SDaniel Jasper // overlapping replacements from 'First' and 'Second' in mergeReplacements. 216d89ae9d3SDaniel Jasper // 217d89ae9d3SDaniel Jasper // Position projection: 218d89ae9d3SDaniel Jasper // Offsets and lengths of the replacements can generally refer to two different 219d89ae9d3SDaniel Jasper // coordinate spaces. Replacements from 'First' refer to the original text 220d89ae9d3SDaniel Jasper // whereas replacements from 'Second' refer to the text after applying 'First'. 221d89ae9d3SDaniel Jasper // 222d89ae9d3SDaniel Jasper // MergedReplacement always operates in the coordinate space of the original 223d89ae9d3SDaniel Jasper // text, i.e. transforms elements from 'Second' to take into account what was 224d89ae9d3SDaniel Jasper // changed based on the elements from 'First'. 225d89ae9d3SDaniel Jasper // 226d89ae9d3SDaniel Jasper // We can correctly calculate this projection as we look at the replacements in 227d89ae9d3SDaniel Jasper // order of strictly increasing offsets. 228d89ae9d3SDaniel Jasper // 229d89ae9d3SDaniel Jasper // Invariants: 230d89ae9d3SDaniel Jasper // * We always merge elements from 'First' into elements from 'Second' and vice 231d89ae9d3SDaniel Jasper // versa. Within each set, the replacements are non-overlapping. 232d89ae9d3SDaniel Jasper // * We only extend to the right, i.e. merge elements with strictly increasing 233d89ae9d3SDaniel Jasper // offsets. 234d89ae9d3SDaniel Jasper class MergedReplacement { 235d89ae9d3SDaniel Jasper public: 236d89ae9d3SDaniel Jasper MergedReplacement(const Replacement &R, bool MergeSecond, int D) 237d89ae9d3SDaniel Jasper : MergeSecond(MergeSecond), Delta(D), FilePath(R.getFilePath()), 238d89ae9d3SDaniel Jasper Offset(R.getOffset() + (MergeSecond ? 0 : Delta)), Length(R.getLength()), 239d89ae9d3SDaniel Jasper Text(R.getReplacementText()) { 240d89ae9d3SDaniel Jasper Delta += MergeSecond ? 0 : Text.size() - Length; 241d89ae9d3SDaniel Jasper DeltaFirst = MergeSecond ? Text.size() - Length : 0; 242d89ae9d3SDaniel Jasper } 243d89ae9d3SDaniel Jasper 244d89ae9d3SDaniel Jasper // Merges the next element 'R' into this merged element. As we always merge 245d89ae9d3SDaniel Jasper // from 'First' into 'Second' or vice versa, the MergedReplacement knows what 246d89ae9d3SDaniel Jasper // set the next element is coming from. 247d89ae9d3SDaniel Jasper void merge(const Replacement &R) { 248d89ae9d3SDaniel Jasper if (MergeSecond) { 249d89ae9d3SDaniel Jasper unsigned REnd = R.getOffset() + Delta + R.getLength(); 250d89ae9d3SDaniel Jasper unsigned End = Offset + Text.size(); 251d89ae9d3SDaniel Jasper if (REnd > End) { 252d89ae9d3SDaniel Jasper Length += REnd - End; 253d89ae9d3SDaniel Jasper MergeSecond = false; 254d89ae9d3SDaniel Jasper } 255d89ae9d3SDaniel Jasper StringRef TextRef = Text; 256d89ae9d3SDaniel Jasper StringRef Head = TextRef.substr(0, R.getOffset() + Delta - Offset); 257d89ae9d3SDaniel Jasper StringRef Tail = TextRef.substr(REnd - Offset); 258d89ae9d3SDaniel Jasper Text = (Head + R.getReplacementText() + Tail).str(); 259d89ae9d3SDaniel Jasper Delta += R.getReplacementText().size() - R.getLength(); 260d89ae9d3SDaniel Jasper } else { 261d89ae9d3SDaniel Jasper unsigned End = Offset + Length; 262d89ae9d3SDaniel Jasper StringRef RText = R.getReplacementText(); 263d89ae9d3SDaniel Jasper StringRef Tail = RText.substr(End - R.getOffset()); 264d89ae9d3SDaniel Jasper Text = (Text + Tail).str(); 265d89ae9d3SDaniel Jasper if (R.getOffset() + RText.size() > End) { 266d89ae9d3SDaniel Jasper Length = R.getOffset() + R.getLength() - Offset; 267d89ae9d3SDaniel Jasper MergeSecond = true; 268d89ae9d3SDaniel Jasper } else { 269d89ae9d3SDaniel Jasper Length += R.getLength() - RText.size(); 270d89ae9d3SDaniel Jasper } 271d89ae9d3SDaniel Jasper DeltaFirst += RText.size() - R.getLength(); 272d89ae9d3SDaniel Jasper } 273d89ae9d3SDaniel Jasper } 274d89ae9d3SDaniel Jasper 275d89ae9d3SDaniel Jasper // Returns 'true' if 'R' starts strictly after the MergedReplacement and thus 276d89ae9d3SDaniel Jasper // doesn't need to be merged. 277d89ae9d3SDaniel Jasper bool endsBefore(const Replacement &R) const { 278d89ae9d3SDaniel Jasper if (MergeSecond) 279d89ae9d3SDaniel Jasper return Offset + Text.size() < R.getOffset() + Delta; 280d89ae9d3SDaniel Jasper return Offset + Length < R.getOffset(); 281d89ae9d3SDaniel Jasper } 282d89ae9d3SDaniel Jasper 283d89ae9d3SDaniel Jasper // Returns 'true' if an element from the second set should be merged next. 284d89ae9d3SDaniel Jasper bool mergeSecond() const { return MergeSecond; } 285d89ae9d3SDaniel Jasper int deltaFirst() const { return DeltaFirst; } 286d89ae9d3SDaniel Jasper Replacement asReplacement() const { return {FilePath, Offset, Length, Text}; } 287d89ae9d3SDaniel Jasper 288d89ae9d3SDaniel Jasper private: 289d89ae9d3SDaniel Jasper bool MergeSecond; 290d89ae9d3SDaniel Jasper 291d89ae9d3SDaniel Jasper // Amount of characters that elements from 'Second' need to be shifted by in 292d89ae9d3SDaniel Jasper // order to refer to the original text. 293d89ae9d3SDaniel Jasper int Delta; 294d89ae9d3SDaniel Jasper 295d89ae9d3SDaniel Jasper // Sum of all deltas (text-length - length) of elements from 'First' merged 296d89ae9d3SDaniel Jasper // into this element. This is used to update 'Delta' once the 297d89ae9d3SDaniel Jasper // MergedReplacement is completed. 298d89ae9d3SDaniel Jasper int DeltaFirst; 299d89ae9d3SDaniel Jasper 300d89ae9d3SDaniel Jasper // Data of the actually merged replacement. FilePath and Offset aren't changed 301d89ae9d3SDaniel Jasper // as the element is only extended to the right. 302d89ae9d3SDaniel Jasper const StringRef FilePath; 303d89ae9d3SDaniel Jasper const unsigned Offset; 304d89ae9d3SDaniel Jasper unsigned Length; 305d89ae9d3SDaniel Jasper std::string Text; 306d89ae9d3SDaniel Jasper }; 30740ef2fb3SEric Liu 308d89ae9d3SDaniel Jasper } // namespace 309d89ae9d3SDaniel Jasper 31040ef2fb3SEric Liu Replacements Replacements::merge(const Replacements &ReplacesToMerge) const { 31140ef2fb3SEric Liu if (empty() || ReplacesToMerge.empty()) 31240ef2fb3SEric Liu return empty() ? ReplacesToMerge : *this; 3134c1ef97aSEric Liu 31440ef2fb3SEric Liu auto &First = Replaces; 31540ef2fb3SEric Liu auto &Second = ReplacesToMerge.Replaces; 316d89ae9d3SDaniel Jasper // Delta is the amount of characters that replacements from 'Second' need to 317d89ae9d3SDaniel Jasper // be shifted so that their offsets refer to the original text. 318d89ae9d3SDaniel Jasper int Delta = 0; 31940ef2fb3SEric Liu ReplacementsImpl Result; 320d89ae9d3SDaniel Jasper 321d89ae9d3SDaniel Jasper // Iterate over both sets and always add the next element (smallest total 322d89ae9d3SDaniel Jasper // Offset) from either 'First' or 'Second'. Merge that element with 323d89ae9d3SDaniel Jasper // subsequent replacements as long as they overlap. See more details in the 324d89ae9d3SDaniel Jasper // comment on MergedReplacement. 325d89ae9d3SDaniel Jasper for (auto FirstI = First.begin(), SecondI = Second.begin(); 326d89ae9d3SDaniel Jasper FirstI != First.end() || SecondI != Second.end();) { 327d89ae9d3SDaniel Jasper bool NextIsFirst = SecondI == Second.end() || 328a3e553a2SDaniel Jasper (FirstI != First.end() && 329a3e553a2SDaniel Jasper FirstI->getOffset() < SecondI->getOffset() + Delta); 330d89ae9d3SDaniel Jasper MergedReplacement Merged(NextIsFirst ? *FirstI : *SecondI, NextIsFirst, 331d89ae9d3SDaniel Jasper Delta); 332d89ae9d3SDaniel Jasper ++(NextIsFirst ? FirstI : SecondI); 333d89ae9d3SDaniel Jasper 334d89ae9d3SDaniel Jasper while ((Merged.mergeSecond() && SecondI != Second.end()) || 335d89ae9d3SDaniel Jasper (!Merged.mergeSecond() && FirstI != First.end())) { 336d89ae9d3SDaniel Jasper auto &I = Merged.mergeSecond() ? SecondI : FirstI; 337d89ae9d3SDaniel Jasper if (Merged.endsBefore(*I)) 338d89ae9d3SDaniel Jasper break; 339d89ae9d3SDaniel Jasper Merged.merge(*I); 340d89ae9d3SDaniel Jasper ++I; 341d89ae9d3SDaniel Jasper } 342d89ae9d3SDaniel Jasper Delta -= Merged.deltaFirst(); 343d89ae9d3SDaniel Jasper Result.insert(Merged.asReplacement()); 344d89ae9d3SDaniel Jasper } 34540ef2fb3SEric Liu return Replacements(Result.begin(), Result.end()); 34640ef2fb3SEric Liu } 34740ef2fb3SEric Liu 34840ef2fb3SEric Liu // Combines overlapping ranges in \p Ranges and sorts the combined ranges. 34940ef2fb3SEric Liu // Returns a set of non-overlapping and sorted ranges that is equivalent to 35040ef2fb3SEric Liu // \p Ranges. 35140ef2fb3SEric Liu static std::vector<Range> combineAndSortRanges(std::vector<Range> Ranges) { 35240ef2fb3SEric Liu std::sort(Ranges.begin(), Ranges.end(), 35340ef2fb3SEric Liu [](const Range &LHS, const Range &RHS) { 35440ef2fb3SEric Liu if (LHS.getOffset() != RHS.getOffset()) 35540ef2fb3SEric Liu return LHS.getOffset() < RHS.getOffset(); 35640ef2fb3SEric Liu return LHS.getLength() < RHS.getLength(); 35740ef2fb3SEric Liu }); 35840ef2fb3SEric Liu std::vector<Range> Result; 35940ef2fb3SEric Liu for (const auto &R : Ranges) { 36040ef2fb3SEric Liu if (Result.empty() || 36140ef2fb3SEric Liu Result.back().getOffset() + Result.back().getLength() < R.getOffset()) { 36240ef2fb3SEric Liu Result.push_back(R); 36340ef2fb3SEric Liu } else { 36440ef2fb3SEric Liu unsigned NewEnd = 36540ef2fb3SEric Liu std::max(Result.back().getOffset() + Result.back().getLength(), 36640ef2fb3SEric Liu R.getOffset() + R.getLength()); 36740ef2fb3SEric Liu Result[Result.size() - 1] = 36840ef2fb3SEric Liu Range(Result.back().getOffset(), NewEnd - Result.back().getOffset()); 36940ef2fb3SEric Liu } 37040ef2fb3SEric Liu } 371d89ae9d3SDaniel Jasper return Result; 372d89ae9d3SDaniel Jasper } 373d89ae9d3SDaniel Jasper 37440ef2fb3SEric Liu std::vector<Range> 37540ef2fb3SEric Liu calculateRangesAfterReplacements(const Replacements &Replaces, 37640ef2fb3SEric Liu const std::vector<Range> &Ranges) { 37740ef2fb3SEric Liu // To calculate the new ranges, 37840ef2fb3SEric Liu // - Turn \p Ranges into Replacements at (offset, length) with an empty 37940ef2fb3SEric Liu // (unimportant) replacement text of length "length". 38040ef2fb3SEric Liu // - Merge with \p Replaces. 38140ef2fb3SEric Liu // - The new ranges will be the affected ranges of the merged replacements. 38240ef2fb3SEric Liu auto MergedRanges = combineAndSortRanges(Ranges); 38373337f3dSEric Liu if (Replaces.empty()) 38473337f3dSEric Liu return MergedRanges; 38540ef2fb3SEric Liu tooling::Replacements FakeReplaces; 38640ef2fb3SEric Liu for (const auto &R : MergedRanges) { 38740ef2fb3SEric Liu auto Err = FakeReplaces.add(Replacement(Replaces.begin()->getFilePath(), 38840ef2fb3SEric Liu R.getOffset(), R.getLength(), 38940ef2fb3SEric Liu std::string(R.getLength(), ' '))); 39040ef2fb3SEric Liu assert(!Err && 39140ef2fb3SEric Liu "Replacements must not conflict since ranges have been merged."); 39240ef2fb3SEric Liu (void)Err; 39340ef2fb3SEric Liu } 39440ef2fb3SEric Liu return FakeReplaces.merge(Replaces).getAffectedRanges(); 39540ef2fb3SEric Liu } 39640ef2fb3SEric Liu 39740ef2fb3SEric Liu std::vector<Range> Replacements::getAffectedRanges() const { 39840ef2fb3SEric Liu std::vector<Range> ChangedRanges; 39940ef2fb3SEric Liu int Shift = 0; 40040ef2fb3SEric Liu for (const Replacement &R : Replaces) { 40140ef2fb3SEric Liu unsigned Offset = R.getOffset() + Shift; 40240ef2fb3SEric Liu unsigned Length = R.getReplacementText().size(); 40340ef2fb3SEric Liu Shift += Length - R.getLength(); 40440ef2fb3SEric Liu ChangedRanges.push_back(Range(Offset, Length)); 40540ef2fb3SEric Liu } 40640ef2fb3SEric Liu return combineAndSortRanges(ChangedRanges); 40740ef2fb3SEric Liu } 40840ef2fb3SEric Liu 40940ef2fb3SEric Liu unsigned Replacements::getShiftedCodePosition(unsigned Position) const { 41040ef2fb3SEric Liu unsigned Offset = 0; 41140ef2fb3SEric Liu for (const auto& R : Replaces) { 41240ef2fb3SEric Liu if (R.getOffset() + R.getLength() <= Position) { 41340ef2fb3SEric Liu Offset += R.getReplacementText().size() - R.getLength(); 41440ef2fb3SEric Liu continue; 41540ef2fb3SEric Liu } 41640ef2fb3SEric Liu if (R.getOffset() < Position && 41740ef2fb3SEric Liu R.getOffset() + R.getReplacementText().size() <= Position) { 41840ef2fb3SEric Liu Position = R.getOffset() + R.getReplacementText().size(); 41940ef2fb3SEric Liu if (R.getReplacementText().size() > 0) 42040ef2fb3SEric Liu Position--; 42140ef2fb3SEric Liu } 42240ef2fb3SEric Liu break; 42340ef2fb3SEric Liu } 42440ef2fb3SEric Liu return Position + Offset; 42540ef2fb3SEric Liu } 42640ef2fb3SEric Liu 42740ef2fb3SEric Liu bool applyAllReplacements(const Replacements &Replaces, Rewriter &Rewrite) { 42840ef2fb3SEric Liu bool Result = true; 429e9906525SEric Liu for (auto I = Replaces.rbegin(), E = Replaces.rend(); I != E; ++I) { 43040ef2fb3SEric Liu if (I->isApplicable()) { 43140ef2fb3SEric Liu Result = I->apply(Rewrite) && Result; 43240ef2fb3SEric Liu } else { 43340ef2fb3SEric Liu Result = false; 43440ef2fb3SEric Liu } 43540ef2fb3SEric Liu } 43640ef2fb3SEric Liu return Result; 43740ef2fb3SEric Liu } 43840ef2fb3SEric Liu 43940ef2fb3SEric Liu llvm::Expected<std::string> applyAllReplacements(StringRef Code, 44040ef2fb3SEric Liu const Replacements &Replaces) { 44140ef2fb3SEric Liu if (Replaces.empty()) 44240ef2fb3SEric Liu return Code.str(); 44340ef2fb3SEric Liu 44440ef2fb3SEric Liu IntrusiveRefCntPtr<vfs::InMemoryFileSystem> InMemoryFileSystem( 44540ef2fb3SEric Liu new vfs::InMemoryFileSystem); 44640ef2fb3SEric Liu FileManager Files(FileSystemOptions(), InMemoryFileSystem); 44740ef2fb3SEric Liu DiagnosticsEngine Diagnostics( 44840ef2fb3SEric Liu IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs), 44940ef2fb3SEric Liu new DiagnosticOptions); 45040ef2fb3SEric Liu SourceManager SourceMgr(Diagnostics, Files); 45140ef2fb3SEric Liu Rewriter Rewrite(SourceMgr, LangOptions()); 45240ef2fb3SEric Liu InMemoryFileSystem->addFile( 45340ef2fb3SEric Liu "<stdin>", 0, llvm::MemoryBuffer::getMemBuffer(Code, "<stdin>")); 45440ef2fb3SEric Liu FileID ID = SourceMgr.createFileID(Files.getFile("<stdin>"), SourceLocation(), 45540ef2fb3SEric Liu clang::SrcMgr::C_User); 456e9906525SEric Liu for (auto I = Replaces.rbegin(), E = Replaces.rend(); I != E; ++I) { 45740ef2fb3SEric Liu Replacement Replace("<stdin>", I->getOffset(), I->getLength(), 45840ef2fb3SEric Liu I->getReplacementText()); 45940ef2fb3SEric Liu if (!Replace.apply(Rewrite)) 46040ef2fb3SEric Liu return llvm::make_error<llvm::StringError>( 46140ef2fb3SEric Liu "Failed to apply replacement: " + Replace.toString(), 46240ef2fb3SEric Liu llvm::inconvertibleErrorCode()); 46340ef2fb3SEric Liu } 46440ef2fb3SEric Liu std::string Result; 46540ef2fb3SEric Liu llvm::raw_string_ostream OS(Result); 46640ef2fb3SEric Liu Rewrite.getEditBuffer(ID).write(OS); 46740ef2fb3SEric Liu OS.flush(); 46840ef2fb3SEric Liu return Result; 46940ef2fb3SEric Liu } 47040ef2fb3SEric Liu 47140ef2fb3SEric Liu std::map<std::string, Replacements> 47240ef2fb3SEric Liu groupReplacementsByFile(const Replacements &Replaces) { 47340ef2fb3SEric Liu std::map<std::string, Replacements> FileToReplaces; 47440ef2fb3SEric Liu for (const auto &Replace : Replaces) 47540ef2fb3SEric Liu // We can ignore the Error here since \p Replaces is already conflict-free. 47640ef2fb3SEric Liu FileToReplaces[Replace.getFilePath()].add(Replace); 47740ef2fb3SEric Liu return FileToReplaces; 47840ef2fb3SEric Liu } 47940ef2fb3SEric Liu 480cb3e6188SDaniel Jasper } // end namespace tooling 481cb3e6188SDaniel Jasper } // end namespace clang 482