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/Basic/Diagnostic.h"
15 #include "clang/Basic/DiagnosticIDs.h"
16 #include "clang/Basic/DiagnosticOptions.h"
17 #include "clang/Basic/FileManager.h"
18 #include "clang/Basic/SourceManager.h"
19 #include "clang/Lex/Lexer.h"
20 #include "clang/Rewrite/Core/Rewriter.h"
21 #include "clang/Tooling/Core/Replacement.h"
22 #include "llvm/Support/FileSystem.h"
23 #include "llvm/Support/Path.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   FileID ID;
61   // FIXME: Use SM.translateFile directly.
62   SourceLocation Location = SM.translateFileLineCol(Entry, 1, 1);
63   ID = Location.isValid() ?
64     SM.getFileID(Location) :
65     SM.createFileID(Entry, SourceLocation(), SrcMgr::C_User);
66   // FIXME: We cannot check whether Offset + Length is in the file, as
67   // the remapping API is not public in the RewriteBuffer.
68   const SourceLocation Start =
69     SM.getLocForStartOfFile(ID).
70     getLocWithOffset(ReplacementRange.getOffset());
71   // ReplaceText returns false on success.
72   // ReplaceText only fails if the source location is not a file location, in
73   // which case we already returned false earlier.
74   bool RewriteSucceeded = !Rewrite.ReplaceText(
75       Start, ReplacementRange.getLength(), ReplacementText);
76   assert(RewriteSucceeded);
77   return RewriteSucceeded;
78 }
79 
80 std::string Replacement::toString() const {
81   std::string Result;
82   llvm::raw_string_ostream Stream(Result);
83   Stream << FilePath << ": " << ReplacementRange.getOffset() << ":+"
84          << ReplacementRange.getLength() << ":\"" << ReplacementText << "\"";
85   return Stream.str();
86 }
87 
88 bool operator<(const Replacement &LHS, const Replacement &RHS) {
89   if (LHS.getOffset() != RHS.getOffset())
90     return LHS.getOffset() < RHS.getOffset();
91   if (LHS.getLength() != RHS.getLength())
92     return LHS.getLength() < RHS.getLength();
93   if (LHS.getFilePath() != RHS.getFilePath())
94     return LHS.getFilePath() < RHS.getFilePath();
95   return LHS.getReplacementText() < RHS.getReplacementText();
96 }
97 
98 bool operator==(const Replacement &LHS, const Replacement &RHS) {
99   return LHS.getOffset() == RHS.getOffset() &&
100          LHS.getLength() == RHS.getLength() &&
101          LHS.getFilePath() == RHS.getFilePath() &&
102          LHS.getReplacementText() == RHS.getReplacementText();
103 }
104 
105 void Replacement::setFromSourceLocation(const SourceManager &Sources,
106                                         SourceLocation Start, unsigned Length,
107                                         StringRef ReplacementText) {
108   const std::pair<FileID, unsigned> DecomposedLocation =
109       Sources.getDecomposedLoc(Start);
110   const FileEntry *Entry = Sources.getFileEntryForID(DecomposedLocation.first);
111   if (Entry) {
112     // Make FilePath absolute so replacements can be applied correctly when
113     // relative paths for files are used.
114     llvm::SmallString<256> FilePath(Entry->getName());
115     std::error_code EC = llvm::sys::fs::make_absolute(FilePath);
116     this->FilePath = EC ? FilePath.c_str() : Entry->getName();
117   } else {
118     this->FilePath = InvalidLocation;
119   }
120   this->ReplacementRange = Range(DecomposedLocation.second, Length);
121   this->ReplacementText = ReplacementText;
122 }
123 
124 // FIXME: This should go into the Lexer, but we need to figure out how
125 // to handle ranges for refactoring in general first - there is no obvious
126 // good way how to integrate this into the Lexer yet.
127 static int getRangeSize(const SourceManager &Sources,
128                         const CharSourceRange &Range,
129                         const LangOptions &LangOpts) {
130   SourceLocation SpellingBegin = Sources.getSpellingLoc(Range.getBegin());
131   SourceLocation SpellingEnd = Sources.getSpellingLoc(Range.getEnd());
132   std::pair<FileID, unsigned> Start = Sources.getDecomposedLoc(SpellingBegin);
133   std::pair<FileID, unsigned> End = Sources.getDecomposedLoc(SpellingEnd);
134   if (Start.first != End.first) return -1;
135   if (Range.isTokenRange())
136     End.second += Lexer::MeasureTokenLength(SpellingEnd, Sources, LangOpts);
137   return End.second - Start.second;
138 }
139 
140 void Replacement::setFromSourceRange(const SourceManager &Sources,
141                                      const CharSourceRange &Range,
142                                      StringRef ReplacementText,
143                                      const LangOptions &LangOpts) {
144   setFromSourceLocation(Sources, Sources.getSpellingLoc(Range.getBegin()),
145                         getRangeSize(Sources, Range, LangOpts),
146                         ReplacementText);
147 }
148 
149 unsigned shiftedCodePosition(const Replacements &Replaces, unsigned Position) {
150   unsigned NewPosition = Position;
151   for (Replacements::iterator I = Replaces.begin(), E = Replaces.end(); I != E;
152        ++I) {
153     if (I->getOffset() >= Position)
154       break;
155     if (I->getOffset() + I->getLength() > Position)
156       NewPosition += I->getOffset() + I->getLength() - Position;
157     NewPosition += I->getReplacementText().size() - I->getLength();
158   }
159   return NewPosition;
160 }
161 
162 // FIXME: Remove this function when Replacements is implemented as std::vector
163 // instead of std::set.
164 unsigned shiftedCodePosition(const std::vector<Replacement> &Replaces,
165                              unsigned Position) {
166   unsigned NewPosition = Position;
167   for (std::vector<Replacement>::const_iterator I = Replaces.begin(),
168                                                 E = Replaces.end();
169        I != E; ++I) {
170     if (I->getOffset() >= Position)
171       break;
172     if (I->getOffset() + I->getLength() > Position)
173       NewPosition += I->getOffset() + I->getLength() - Position;
174     NewPosition += I->getReplacementText().size() - I->getLength();
175   }
176   return NewPosition;
177 }
178 
179 void deduplicate(std::vector<Replacement> &Replaces,
180                  std::vector<Range> &Conflicts) {
181   if (Replaces.empty())
182     return;
183 
184   auto LessNoPath = [](const Replacement &LHS, const Replacement &RHS) {
185     if (LHS.getOffset() != RHS.getOffset())
186       return LHS.getOffset() < RHS.getOffset();
187     if (LHS.getLength() != RHS.getLength())
188       return LHS.getLength() < RHS.getLength();
189     return LHS.getReplacementText() < RHS.getReplacementText();
190   };
191 
192   auto EqualNoPath = [](const Replacement &LHS, const Replacement &RHS) {
193     return LHS.getOffset() == RHS.getOffset() &&
194            LHS.getLength() == RHS.getLength() &&
195            LHS.getReplacementText() == RHS.getReplacementText();
196   };
197 
198   // Deduplicate. We don't want to deduplicate based on the path as we assume
199   // that all replacements refer to the same file (or are symlinks).
200   std::sort(Replaces.begin(), Replaces.end(), LessNoPath);
201   Replaces.erase(std::unique(Replaces.begin(), Replaces.end(), EqualNoPath),
202                  Replaces.end());
203 
204   // Detect conflicts
205   Range ConflictRange(Replaces.front().getOffset(),
206                       Replaces.front().getLength());
207   unsigned ConflictStart = 0;
208   unsigned ConflictLength = 1;
209   for (unsigned i = 1; i < Replaces.size(); ++i) {
210     Range Current(Replaces[i].getOffset(), Replaces[i].getLength());
211     if (ConflictRange.overlapsWith(Current)) {
212       // Extend conflicted range
213       ConflictRange = Range(ConflictRange.getOffset(),
214                             std::max(ConflictRange.getLength(),
215                                      Current.getOffset() + Current.getLength() -
216                                          ConflictRange.getOffset()));
217       ++ConflictLength;
218     } else {
219       if (ConflictLength > 1)
220         Conflicts.push_back(Range(ConflictStart, ConflictLength));
221       ConflictRange = Current;
222       ConflictStart = i;
223       ConflictLength = 1;
224     }
225   }
226 
227   if (ConflictLength > 1)
228     Conflicts.push_back(Range(ConflictStart, ConflictLength));
229 }
230 
231 bool applyAllReplacements(const Replacements &Replaces, Rewriter &Rewrite) {
232   bool Result = true;
233   for (Replacements::const_iterator I = Replaces.begin(),
234                                     E = Replaces.end();
235        I != E; ++I) {
236     if (I->isApplicable()) {
237       Result = I->apply(Rewrite) && Result;
238     } else {
239       Result = false;
240     }
241   }
242   return Result;
243 }
244 
245 // FIXME: Remove this function when Replacements is implemented as std::vector
246 // instead of std::set.
247 bool applyAllReplacements(const std::vector<Replacement> &Replaces,
248                           Rewriter &Rewrite) {
249   bool Result = true;
250   for (std::vector<Replacement>::const_iterator I = Replaces.begin(),
251                                                 E = Replaces.end();
252        I != E; ++I) {
253     if (I->isApplicable()) {
254       Result = I->apply(Rewrite) && Result;
255     } else {
256       Result = false;
257     }
258   }
259   return Result;
260 }
261 
262 std::string applyAllReplacements(StringRef Code, const Replacements &Replaces) {
263   FileManager Files((FileSystemOptions()));
264   DiagnosticsEngine Diagnostics(
265       IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
266       new DiagnosticOptions);
267   SourceManager SourceMgr(Diagnostics, Files);
268   Rewriter Rewrite(SourceMgr, LangOptions());
269   std::unique_ptr<llvm::MemoryBuffer> Buf =
270       llvm::MemoryBuffer::getMemBuffer(Code, "<stdin>");
271   const clang::FileEntry *Entry =
272       Files.getVirtualFile("<stdin>", Buf->getBufferSize(), 0);
273   SourceMgr.overrideFileContents(Entry, std::move(Buf));
274   FileID ID =
275       SourceMgr.createFileID(Entry, SourceLocation(), clang::SrcMgr::C_User);
276   for (Replacements::const_iterator I = Replaces.begin(), E = Replaces.end();
277        I != E; ++I) {
278     Replacement Replace("<stdin>", I->getOffset(), I->getLength(),
279                         I->getReplacementText());
280     if (!Replace.apply(Rewrite))
281       return "";
282   }
283   std::string Result;
284   llvm::raw_string_ostream OS(Result);
285   Rewrite.getEditBuffer(ID).write(OS);
286   OS.flush();
287   return Result;
288 }
289 
290 } // end namespace tooling
291 } // end namespace clang
292 
293