]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/Tooling/Core/Replacement.cpp
Update LLDB snapshot to upstream r241361
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / clang / lib / Tooling / Core / Replacement.cpp
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
92   // Apply longer replacements first, specifically so that deletions are
93   // executed before insertions. It is (hopefully) never the intention to
94   // delete parts of newly inserted code.
95   if (LHS.getLength() != RHS.getLength())
96     return LHS.getLength() > RHS.getLength();
97
98   if (LHS.getFilePath() != RHS.getFilePath())
99     return LHS.getFilePath() < RHS.getFilePath();
100   return LHS.getReplacementText() < RHS.getReplacementText();
101 }
102
103 bool operator==(const Replacement &LHS, const Replacement &RHS) {
104   return LHS.getOffset() == RHS.getOffset() &&
105          LHS.getLength() == RHS.getLength() &&
106          LHS.getFilePath() == RHS.getFilePath() &&
107          LHS.getReplacementText() == RHS.getReplacementText();
108 }
109
110 void Replacement::setFromSourceLocation(const SourceManager &Sources,
111                                         SourceLocation Start, unsigned Length,
112                                         StringRef ReplacementText) {
113   const std::pair<FileID, unsigned> DecomposedLocation =
114       Sources.getDecomposedLoc(Start);
115   const FileEntry *Entry = Sources.getFileEntryForID(DecomposedLocation.first);
116   if (Entry) {
117     // Make FilePath absolute so replacements can be applied correctly when
118     // relative paths for files are used.
119     llvm::SmallString<256> FilePath(Entry->getName());
120     std::error_code EC = llvm::sys::fs::make_absolute(FilePath);
121     this->FilePath = EC ? FilePath.c_str() : Entry->getName();
122   } else {
123     this->FilePath = InvalidLocation;
124   }
125   this->ReplacementRange = Range(DecomposedLocation.second, Length);
126   this->ReplacementText = ReplacementText;
127 }
128
129 // FIXME: This should go into the Lexer, but we need to figure out how
130 // to handle ranges for refactoring in general first - there is no obvious
131 // good way how to integrate this into the Lexer yet.
132 static int getRangeSize(const SourceManager &Sources,
133                         const CharSourceRange &Range,
134                         const LangOptions &LangOpts) {
135   SourceLocation SpellingBegin = Sources.getSpellingLoc(Range.getBegin());
136   SourceLocation SpellingEnd = Sources.getSpellingLoc(Range.getEnd());
137   std::pair<FileID, unsigned> Start = Sources.getDecomposedLoc(SpellingBegin);
138   std::pair<FileID, unsigned> End = Sources.getDecomposedLoc(SpellingEnd);
139   if (Start.first != End.first) return -1;
140   if (Range.isTokenRange())
141     End.second += Lexer::MeasureTokenLength(SpellingEnd, Sources, LangOpts);
142   return End.second - Start.second;
143 }
144
145 void Replacement::setFromSourceRange(const SourceManager &Sources,
146                                      const CharSourceRange &Range,
147                                      StringRef ReplacementText,
148                                      const LangOptions &LangOpts) {
149   setFromSourceLocation(Sources, Sources.getSpellingLoc(Range.getBegin()),
150                         getRangeSize(Sources, Range, LangOpts),
151                         ReplacementText);
152 }
153
154 unsigned shiftedCodePosition(const Replacements &Replaces, unsigned Position) {
155   unsigned NewPosition = Position;
156   for (Replacements::iterator I = Replaces.begin(), E = Replaces.end(); I != E;
157        ++I) {
158     if (I->getOffset() >= Position)
159       break;
160     if (I->getOffset() + I->getLength() > Position)
161       NewPosition += I->getOffset() + I->getLength() - Position;
162     NewPosition += I->getReplacementText().size() - I->getLength();
163   }
164   return NewPosition;
165 }
166
167 // FIXME: Remove this function when Replacements is implemented as std::vector
168 // instead of std::set.
169 unsigned shiftedCodePosition(const std::vector<Replacement> &Replaces,
170                              unsigned Position) {
171   unsigned NewPosition = Position;
172   for (std::vector<Replacement>::const_iterator I = Replaces.begin(),
173                                                 E = Replaces.end();
174        I != E; ++I) {
175     if (I->getOffset() >= Position)
176       break;
177     if (I->getOffset() + I->getLength() > Position)
178       NewPosition += I->getOffset() + I->getLength() - Position;
179     NewPosition += I->getReplacementText().size() - I->getLength();
180   }
181   return NewPosition;
182 }
183
184 void deduplicate(std::vector<Replacement> &Replaces,
185                  std::vector<Range> &Conflicts) {
186   if (Replaces.empty())
187     return;
188
189   auto LessNoPath = [](const Replacement &LHS, const Replacement &RHS) {
190     if (LHS.getOffset() != RHS.getOffset())
191       return LHS.getOffset() < RHS.getOffset();
192     if (LHS.getLength() != RHS.getLength())
193       return LHS.getLength() < RHS.getLength();
194     return LHS.getReplacementText() < RHS.getReplacementText();
195   };
196
197   auto EqualNoPath = [](const Replacement &LHS, const Replacement &RHS) {
198     return LHS.getOffset() == RHS.getOffset() &&
199            LHS.getLength() == RHS.getLength() &&
200            LHS.getReplacementText() == RHS.getReplacementText();
201   };
202
203   // Deduplicate. We don't want to deduplicate based on the path as we assume
204   // that all replacements refer to the same file (or are symlinks).
205   std::sort(Replaces.begin(), Replaces.end(), LessNoPath);
206   Replaces.erase(std::unique(Replaces.begin(), Replaces.end(), EqualNoPath),
207                  Replaces.end());
208
209   // Detect conflicts
210   Range ConflictRange(Replaces.front().getOffset(),
211                       Replaces.front().getLength());
212   unsigned ConflictStart = 0;
213   unsigned ConflictLength = 1;
214   for (unsigned i = 1; i < Replaces.size(); ++i) {
215     Range Current(Replaces[i].getOffset(), Replaces[i].getLength());
216     if (ConflictRange.overlapsWith(Current)) {
217       // Extend conflicted range
218       ConflictRange = Range(ConflictRange.getOffset(),
219                             std::max(ConflictRange.getLength(),
220                                      Current.getOffset() + Current.getLength() -
221                                          ConflictRange.getOffset()));
222       ++ConflictLength;
223     } else {
224       if (ConflictLength > 1)
225         Conflicts.push_back(Range(ConflictStart, ConflictLength));
226       ConflictRange = Current;
227       ConflictStart = i;
228       ConflictLength = 1;
229     }
230   }
231
232   if (ConflictLength > 1)
233     Conflicts.push_back(Range(ConflictStart, ConflictLength));
234 }
235
236 bool applyAllReplacements(const Replacements &Replaces, Rewriter &Rewrite) {
237   bool Result = true;
238   for (Replacements::const_iterator I = Replaces.begin(),
239                                     E = Replaces.end();
240        I != E; ++I) {
241     if (I->isApplicable()) {
242       Result = I->apply(Rewrite) && Result;
243     } else {
244       Result = false;
245     }
246   }
247   return Result;
248 }
249
250 // FIXME: Remove this function when Replacements is implemented as std::vector
251 // instead of std::set.
252 bool applyAllReplacements(const std::vector<Replacement> &Replaces,
253                           Rewriter &Rewrite) {
254   bool Result = true;
255   for (std::vector<Replacement>::const_iterator I = Replaces.begin(),
256                                                 E = Replaces.end();
257        I != E; ++I) {
258     if (I->isApplicable()) {
259       Result = I->apply(Rewrite) && Result;
260     } else {
261       Result = false;
262     }
263   }
264   return Result;
265 }
266
267 std::string applyAllReplacements(StringRef Code, const Replacements &Replaces) {
268   FileManager Files((FileSystemOptions()));
269   DiagnosticsEngine Diagnostics(
270       IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
271       new DiagnosticOptions);
272   SourceManager SourceMgr(Diagnostics, Files);
273   Rewriter Rewrite(SourceMgr, LangOptions());
274   std::unique_ptr<llvm::MemoryBuffer> Buf =
275       llvm::MemoryBuffer::getMemBuffer(Code, "<stdin>");
276   const clang::FileEntry *Entry =
277       Files.getVirtualFile("<stdin>", Buf->getBufferSize(), 0);
278   SourceMgr.overrideFileContents(Entry, std::move(Buf));
279   FileID ID =
280       SourceMgr.createFileID(Entry, SourceLocation(), clang::SrcMgr::C_User);
281   for (Replacements::const_iterator I = Replaces.begin(), E = Replaces.end();
282        I != E; ++I) {
283     Replacement Replace("<stdin>", I->getOffset(), I->getLength(),
284                         I->getReplacementText());
285     if (!Replace.apply(Rewrite))
286       return "";
287   }
288   std::string Result;
289   llvm::raw_string_ostream OS(Result);
290   Rewrite.getEditBuffer(ID).write(OS);
291   OS.flush();
292   return Result;
293 }
294
295 } // end namespace tooling
296 } // end namespace clang
297