1 //===--- Replacement.cpp - Framework for clang refactoring tools ----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  Implements classes to support/store refactorings.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/Tooling/Core/Replacement.h"
15 
16 #include "clang/Basic/Diagnostic.h"
17 #include "clang/Basic/DiagnosticIDs.h"
18 #include "clang/Basic/DiagnosticOptions.h"
19 #include "clang/Basic/FileManager.h"
20 #include "clang/Basic/SourceManager.h"
21 #include "clang/Lex/Lexer.h"
22 #include "clang/Rewrite/Core/Rewriter.h"
23 #include "llvm/Support/FileSystem.h"
24 #include "llvm/Support/raw_os_ostream.h"
25 
26 namespace clang {
27 namespace tooling {
28 
29 static const char * const InvalidLocation = "";
30 
31 Replacement::Replacement()
32   : FilePath(InvalidLocation) {}
33 
34 Replacement::Replacement(StringRef FilePath, unsigned Offset, unsigned Length,
35                          StringRef ReplacementText)
36     : FilePath(FilePath), ReplacementRange(Offset, Length),
37       ReplacementText(ReplacementText) {}
38 
39 Replacement::Replacement(const SourceManager &Sources, SourceLocation Start,
40                          unsigned Length, StringRef ReplacementText) {
41   setFromSourceLocation(Sources, Start, Length, ReplacementText);
42 }
43 
44 Replacement::Replacement(const SourceManager &Sources,
45                          const CharSourceRange &Range,
46                          StringRef ReplacementText,
47                          const LangOptions &LangOpts) {
48   setFromSourceRange(Sources, Range, ReplacementText, LangOpts);
49 }
50 
51 bool Replacement::isApplicable() const {
52   return FilePath != InvalidLocation;
53 }
54 
55 bool Replacement::apply(Rewriter &Rewrite) const {
56   SourceManager &SM = Rewrite.getSourceMgr();
57   const FileEntry *Entry = SM.getFileManager().getFile(FilePath);
58   if (!Entry)
59     return false;
60 
61   FileID ID = SM.getOrCreateFileID(Entry, SrcMgr::C_User);
62   const SourceLocation Start =
63     SM.getLocForStartOfFile(ID).
64     getLocWithOffset(ReplacementRange.getOffset());
65   // ReplaceText returns false on success.
66   // ReplaceText only fails if the source location is not a file location, in
67   // which case we already returned false earlier.
68   bool RewriteSucceeded = !Rewrite.ReplaceText(
69       Start, ReplacementRange.getLength(), ReplacementText);
70   assert(RewriteSucceeded);
71   return RewriteSucceeded;
72 }
73 
74 std::string Replacement::toString() const {
75   std::string Result;
76   llvm::raw_string_ostream Stream(Result);
77   Stream << FilePath << ": " << ReplacementRange.getOffset() << ":+"
78          << ReplacementRange.getLength() << ":\"" << ReplacementText << "\"";
79   return Stream.str();
80 }
81 
82 bool operator<(const Replacement &LHS, const Replacement &RHS) {
83   if (LHS.getOffset() != RHS.getOffset())
84     return LHS.getOffset() < RHS.getOffset();
85 
86   // Apply longer replacements first, specifically so that deletions are
87   // executed before insertions. It is (hopefully) never the intention to
88   // delete parts of newly inserted code.
89   if (LHS.getLength() != RHS.getLength())
90     return LHS.getLength() > RHS.getLength();
91 
92   if (LHS.getFilePath() != RHS.getFilePath())
93     return LHS.getFilePath() < RHS.getFilePath();
94   return LHS.getReplacementText() < RHS.getReplacementText();
95 }
96 
97 bool operator==(const Replacement &LHS, const Replacement &RHS) {
98   return LHS.getOffset() == RHS.getOffset() &&
99          LHS.getLength() == RHS.getLength() &&
100          LHS.getFilePath() == RHS.getFilePath() &&
101          LHS.getReplacementText() == RHS.getReplacementText();
102 }
103 
104 void Replacement::setFromSourceLocation(const SourceManager &Sources,
105                                         SourceLocation Start, unsigned Length,
106                                         StringRef ReplacementText) {
107   const std::pair<FileID, unsigned> DecomposedLocation =
108       Sources.getDecomposedLoc(Start);
109   const FileEntry *Entry = Sources.getFileEntryForID(DecomposedLocation.first);
110   this->FilePath = Entry ? Entry->getName() : InvalidLocation;
111   this->ReplacementRange = Range(DecomposedLocation.second, Length);
112   this->ReplacementText = ReplacementText;
113 }
114 
115 // FIXME: This should go into the Lexer, but we need to figure out how
116 // to handle ranges for refactoring in general first - there is no obvious
117 // good way how to integrate this into the Lexer yet.
118 static int getRangeSize(const SourceManager &Sources,
119                         const CharSourceRange &Range,
120                         const LangOptions &LangOpts) {
121   SourceLocation SpellingBegin = Sources.getSpellingLoc(Range.getBegin());
122   SourceLocation SpellingEnd = Sources.getSpellingLoc(Range.getEnd());
123   std::pair<FileID, unsigned> Start = Sources.getDecomposedLoc(SpellingBegin);
124   std::pair<FileID, unsigned> End = Sources.getDecomposedLoc(SpellingEnd);
125   if (Start.first != End.first) return -1;
126   if (Range.isTokenRange())
127     End.second += Lexer::MeasureTokenLength(SpellingEnd, Sources, LangOpts);
128   return End.second - Start.second;
129 }
130 
131 void Replacement::setFromSourceRange(const SourceManager &Sources,
132                                      const CharSourceRange &Range,
133                                      StringRef ReplacementText,
134                                      const LangOptions &LangOpts) {
135   setFromSourceLocation(Sources, Sources.getSpellingLoc(Range.getBegin()),
136                         getRangeSize(Sources, Range, LangOpts),
137                         ReplacementText);
138 }
139 
140 template <typename T>
141 unsigned shiftedCodePositionInternal(const T &Replaces, unsigned Position) {
142   unsigned Offset = 0;
143   for (const auto& R : Replaces) {
144     if (R.getOffset() + R.getLength() <= Position) {
145       Offset += R.getReplacementText().size() - R.getLength();
146       continue;
147     }
148     if (R.getOffset() < Position &&
149         R.getOffset() + R.getReplacementText().size() <= Position) {
150       Position = R.getOffset() + R.getReplacementText().size() - 1;
151     }
152     break;
153   }
154   return Position + Offset;
155 }
156 
157 unsigned shiftedCodePosition(const Replacements &Replaces, unsigned Position) {
158   return shiftedCodePositionInternal(Replaces, Position);
159 }
160 
161 // FIXME: Remove this function when Replacements is implemented as std::vector
162 // instead of std::set.
163 unsigned shiftedCodePosition(const std::vector<Replacement> &Replaces,
164                              unsigned Position) {
165   return shiftedCodePositionInternal(Replaces, Position);
166 }
167 
168 void deduplicate(std::vector<Replacement> &Replaces,
169                  std::vector<Range> &Conflicts) {
170   if (Replaces.empty())
171     return;
172 
173   auto LessNoPath = [](const Replacement &LHS, const Replacement &RHS) {
174     if (LHS.getOffset() != RHS.getOffset())
175       return LHS.getOffset() < RHS.getOffset();
176     if (LHS.getLength() != RHS.getLength())
177       return LHS.getLength() < RHS.getLength();
178     return LHS.getReplacementText() < RHS.getReplacementText();
179   };
180 
181   auto EqualNoPath = [](const Replacement &LHS, const Replacement &RHS) {
182     return LHS.getOffset() == RHS.getOffset() &&
183            LHS.getLength() == RHS.getLength() &&
184            LHS.getReplacementText() == RHS.getReplacementText();
185   };
186 
187   // Deduplicate. We don't want to deduplicate based on the path as we assume
188   // that all replacements refer to the same file (or are symlinks).
189   std::sort(Replaces.begin(), Replaces.end(), LessNoPath);
190   Replaces.erase(std::unique(Replaces.begin(), Replaces.end(), EqualNoPath),
191                  Replaces.end());
192 
193   // Detect conflicts
194   Range ConflictRange(Replaces.front().getOffset(),
195                       Replaces.front().getLength());
196   unsigned ConflictStart = 0;
197   unsigned ConflictLength = 1;
198   for (unsigned i = 1; i < Replaces.size(); ++i) {
199     Range Current(Replaces[i].getOffset(), Replaces[i].getLength());
200     if (ConflictRange.overlapsWith(Current)) {
201       // Extend conflicted range
202       ConflictRange = Range(ConflictRange.getOffset(),
203                             std::max(ConflictRange.getLength(),
204                                      Current.getOffset() + Current.getLength() -
205                                          ConflictRange.getOffset()));
206       ++ConflictLength;
207     } else {
208       if (ConflictLength > 1)
209         Conflicts.push_back(Range(ConflictStart, ConflictLength));
210       ConflictRange = Current;
211       ConflictStart = i;
212       ConflictLength = 1;
213     }
214   }
215 
216   if (ConflictLength > 1)
217     Conflicts.push_back(Range(ConflictStart, ConflictLength));
218 }
219 
220 bool applyAllReplacements(const Replacements &Replaces, Rewriter &Rewrite) {
221   bool Result = true;
222   for (Replacements::const_iterator I = Replaces.begin(),
223                                     E = Replaces.end();
224        I != E; ++I) {
225     if (I->isApplicable()) {
226       Result = I->apply(Rewrite) && Result;
227     } else {
228       Result = false;
229     }
230   }
231   return Result;
232 }
233 
234 // FIXME: Remove this function when Replacements is implemented as std::vector
235 // instead of std::set.
236 bool applyAllReplacements(const std::vector<Replacement> &Replaces,
237                           Rewriter &Rewrite) {
238   bool Result = true;
239   for (std::vector<Replacement>::const_iterator I = Replaces.begin(),
240                                                 E = Replaces.end();
241        I != E; ++I) {
242     if (I->isApplicable()) {
243       Result = I->apply(Rewrite) && Result;
244     } else {
245       Result = false;
246     }
247   }
248   return Result;
249 }
250 
251 llvm::Expected<std::string> applyAllReplacements(StringRef Code,
252                                                 const Replacements &Replaces) {
253   if (Replaces.empty())
254     return Code.str();
255 
256   IntrusiveRefCntPtr<vfs::InMemoryFileSystem> InMemoryFileSystem(
257       new vfs::InMemoryFileSystem);
258   FileManager Files(FileSystemOptions(), InMemoryFileSystem);
259   DiagnosticsEngine Diagnostics(
260       IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
261       new DiagnosticOptions);
262   SourceManager SourceMgr(Diagnostics, Files);
263   Rewriter Rewrite(SourceMgr, LangOptions());
264   InMemoryFileSystem->addFile(
265       "<stdin>", 0, llvm::MemoryBuffer::getMemBuffer(Code, "<stdin>"));
266   FileID ID = SourceMgr.createFileID(Files.getFile("<stdin>"), SourceLocation(),
267                                      clang::SrcMgr::C_User);
268   for (Replacements::const_iterator I = Replaces.begin(), E = Replaces.end();
269        I != E; ++I) {
270     Replacement Replace("<stdin>", I->getOffset(), I->getLength(),
271                         I->getReplacementText());
272     if (!Replace.apply(Rewrite))
273       return llvm::make_error<llvm::StringError>(
274           "Failed to apply replacement: " + Replace.toString(),
275           llvm::inconvertibleErrorCode());
276   }
277   std::string Result;
278   llvm::raw_string_ostream OS(Result);
279   Rewrite.getEditBuffer(ID).write(OS);
280   OS.flush();
281   return Result;
282 }
283 
284 // Merge and sort overlapping ranges in \p Ranges.
285 static std::vector<Range> mergeAndSortRanges(std::vector<Range> Ranges) {
286   std::sort(Ranges.begin(), Ranges.end(),
287             [](const Range &LHS, const Range &RHS) {
288               if (LHS.getOffset() != RHS.getOffset())
289                 return LHS.getOffset() < RHS.getOffset();
290               return LHS.getLength() < RHS.getLength();
291             });
292   std::vector<Range> Result;
293   for (const auto &R : Ranges) {
294     if (Result.empty() ||
295         Result.back().getOffset() + Result.back().getLength() < R.getOffset()) {
296       Result.push_back(R);
297     } else {
298       unsigned NewEnd =
299           std::max(Result.back().getOffset() + Result.back().getLength(),
300                    R.getOffset() + R.getLength());
301       Result[Result.size() - 1] =
302           Range(Result.back().getOffset(), NewEnd - Result.back().getOffset());
303     }
304   }
305   return Result;
306 }
307 
308 std::vector<Range> calculateChangedRanges(const Replacements &Replaces) {
309   std::vector<Range> ChangedRanges;
310   int Shift = 0;
311   for (const Replacement &R : Replaces) {
312     unsigned Offset = R.getOffset() + Shift;
313     unsigned Length = R.getReplacementText().size();
314     Shift += Length - R.getLength();
315     ChangedRanges.push_back(Range(Offset, Length));
316   }
317   return mergeAndSortRanges(ChangedRanges);
318 }
319 
320 std::vector<Range>
321 calculateRangesAfterReplacements(const Replacements &Replaces,
322                                  const std::vector<Range> &Ranges) {
323   auto MergedRanges = mergeAndSortRanges(Ranges);
324   tooling::Replacements FakeReplaces;
325   for (const auto &R : MergedRanges)
326     FakeReplaces.insert(Replacement(Replaces.begin()->getFilePath(),
327                                     R.getOffset(), R.getLength(),
328                                     std::string(R.getLength(), ' ')));
329   tooling::Replacements NewReplaces = mergeReplacements(FakeReplaces, Replaces);
330   return calculateChangedRanges(NewReplaces);
331 }
332 
333 namespace {
334 // Represents a merged replacement, i.e. a replacement consisting of multiple
335 // overlapping replacements from 'First' and 'Second' in mergeReplacements.
336 //
337 // Position projection:
338 // Offsets and lengths of the replacements can generally refer to two different
339 // coordinate spaces. Replacements from 'First' refer to the original text
340 // whereas replacements from 'Second' refer to the text after applying 'First'.
341 //
342 // MergedReplacement always operates in the coordinate space of the original
343 // text, i.e. transforms elements from 'Second' to take into account what was
344 // changed based on the elements from 'First'.
345 //
346 // We can correctly calculate this projection as we look at the replacements in
347 // order of strictly increasing offsets.
348 //
349 // Invariants:
350 // * We always merge elements from 'First' into elements from 'Second' and vice
351 //   versa. Within each set, the replacements are non-overlapping.
352 // * We only extend to the right, i.e. merge elements with strictly increasing
353 //   offsets.
354 class MergedReplacement {
355 public:
356   MergedReplacement(const Replacement &R, bool MergeSecond, int D)
357       : MergeSecond(MergeSecond), Delta(D), FilePath(R.getFilePath()),
358         Offset(R.getOffset() + (MergeSecond ? 0 : Delta)), Length(R.getLength()),
359         Text(R.getReplacementText()) {
360     Delta += MergeSecond ? 0 : Text.size() - Length;
361     DeltaFirst = MergeSecond ? Text.size() - Length : 0;
362   }
363 
364   // Merges the next element 'R' into this merged element. As we always merge
365   // from 'First' into 'Second' or vice versa, the MergedReplacement knows what
366   // set the next element is coming from.
367   void merge(const Replacement &R) {
368     if (MergeSecond) {
369       unsigned REnd = R.getOffset() + Delta + R.getLength();
370       unsigned End = Offset + Text.size();
371       if (REnd > End) {
372         Length += REnd - End;
373         MergeSecond = false;
374       }
375       StringRef TextRef = Text;
376       StringRef Head = TextRef.substr(0, R.getOffset() + Delta - Offset);
377       StringRef Tail = TextRef.substr(REnd - Offset);
378       Text = (Head + R.getReplacementText() + Tail).str();
379       Delta += R.getReplacementText().size() - R.getLength();
380     } else {
381       unsigned End = Offset + Length;
382       StringRef RText = R.getReplacementText();
383       StringRef Tail = RText.substr(End - R.getOffset());
384       Text = (Text + Tail).str();
385       if (R.getOffset() + RText.size() > End) {
386         Length = R.getOffset() + R.getLength() - Offset;
387         MergeSecond = true;
388       } else {
389         Length += R.getLength() - RText.size();
390       }
391       DeltaFirst += RText.size() - R.getLength();
392     }
393   }
394 
395   // Returns 'true' if 'R' starts strictly after the MergedReplacement and thus
396   // doesn't need to be merged.
397   bool endsBefore(const Replacement &R) const {
398     if (MergeSecond)
399       return Offset + Text.size() < R.getOffset() + Delta;
400     return Offset + Length < R.getOffset();
401   }
402 
403   // Returns 'true' if an element from the second set should be merged next.
404   bool mergeSecond() const { return MergeSecond; }
405   int deltaFirst() const { return DeltaFirst; }
406   Replacement asReplacement() const { return {FilePath, Offset, Length, Text}; }
407 
408 private:
409   bool MergeSecond;
410 
411   // Amount of characters that elements from 'Second' need to be shifted by in
412   // order to refer to the original text.
413   int Delta;
414 
415   // Sum of all deltas (text-length - length) of elements from 'First' merged
416   // into this element. This is used to update 'Delta' once the
417   // MergedReplacement is completed.
418   int DeltaFirst;
419 
420   // Data of the actually merged replacement. FilePath and Offset aren't changed
421   // as the element is only extended to the right.
422   const StringRef FilePath;
423   const unsigned Offset;
424   unsigned Length;
425   std::string Text;
426 };
427 } // namespace
428 
429 std::map<std::string, Replacements>
430 groupReplacementsByFile(const Replacements &Replaces) {
431   std::map<std::string, Replacements> FileToReplaces;
432   for (const auto &Replace : Replaces) {
433     FileToReplaces[Replace.getFilePath()].insert(Replace);
434   }
435   return FileToReplaces;
436 }
437 
438 Replacements mergeReplacements(const Replacements &First,
439                                const Replacements &Second) {
440   if (First.empty() || Second.empty())
441     return First.empty() ? Second : First;
442 
443   // Delta is the amount of characters that replacements from 'Second' need to
444   // be shifted so that their offsets refer to the original text.
445   int Delta = 0;
446   Replacements Result;
447 
448   // Iterate over both sets and always add the next element (smallest total
449   // Offset) from either 'First' or 'Second'. Merge that element with
450   // subsequent replacements as long as they overlap. See more details in the
451   // comment on MergedReplacement.
452   for (auto FirstI = First.begin(), SecondI = Second.begin();
453        FirstI != First.end() || SecondI != Second.end();) {
454     bool NextIsFirst = SecondI == Second.end() ||
455                        (FirstI != First.end() &&
456                         FirstI->getOffset() < SecondI->getOffset() + Delta);
457     MergedReplacement Merged(NextIsFirst ? *FirstI : *SecondI, NextIsFirst,
458                              Delta);
459     ++(NextIsFirst ? FirstI : SecondI);
460 
461     while ((Merged.mergeSecond() && SecondI != Second.end()) ||
462            (!Merged.mergeSecond() && FirstI != First.end())) {
463       auto &I = Merged.mergeSecond() ? SecondI : FirstI;
464       if (Merged.endsBefore(*I))
465         break;
466       Merged.merge(*I);
467       ++I;
468     }
469     Delta -= Merged.deltaFirst();
470     Result.insert(Merged.asReplacement());
471   }
472   return Result;
473 }
474 
475 } // end namespace tooling
476 } // end namespace clang
477