/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/Tooling/Core/Replacement.cpp
Line | Count | Source (jump to first uncovered line) |
1 | | //===- Replacement.cpp - Framework for clang refactoring tools ------------===// |
2 | | // |
3 | | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
4 | | // See https://llvm.org/LICENSE.txt for license information. |
5 | | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
6 | | // |
7 | | //===----------------------------------------------------------------------===// |
8 | | // |
9 | | // Implements classes to support/store refactorings. |
10 | | // |
11 | | //===----------------------------------------------------------------------===// |
12 | | |
13 | | #include "clang/Tooling/Core/Replacement.h" |
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/FileSystemOptions.h" |
19 | | #include "clang/Basic/SourceLocation.h" |
20 | | #include "clang/Basic/SourceManager.h" |
21 | | #include "clang/Lex/Lexer.h" |
22 | | #include "clang/Rewrite/Core/RewriteBuffer.h" |
23 | | #include "clang/Rewrite/Core/Rewriter.h" |
24 | | #include "llvm/ADT/IntrusiveRefCntPtr.h" |
25 | | #include "llvm/ADT/SmallPtrSet.h" |
26 | | #include "llvm/ADT/StringRef.h" |
27 | | #include "llvm/Support/Error.h" |
28 | | #include "llvm/Support/ErrorHandling.h" |
29 | | #include "llvm/Support/MemoryBuffer.h" |
30 | | #include "llvm/Support/VirtualFileSystem.h" |
31 | | #include "llvm/Support/raw_ostream.h" |
32 | | #include <algorithm> |
33 | | #include <cassert> |
34 | | #include <limits> |
35 | | #include <map> |
36 | | #include <string> |
37 | | #include <utility> |
38 | | #include <vector> |
39 | | |
40 | | using namespace clang; |
41 | | using namespace tooling; |
42 | | |
43 | | static const char * const InvalidLocation = ""; |
44 | | |
45 | 13 | Replacement::Replacement() : FilePath(InvalidLocation) {} |
46 | | |
47 | | Replacement::Replacement(StringRef FilePath, unsigned Offset, unsigned Length, |
48 | | StringRef ReplacementText) |
49 | | : FilePath(std::string(FilePath)), ReplacementRange(Offset, Length), |
50 | 170k | ReplacementText(std::string(ReplacementText)) {} |
51 | | |
52 | | Replacement::Replacement(const SourceManager &Sources, SourceLocation Start, |
53 | 448 | unsigned Length, StringRef ReplacementText) { |
54 | 448 | setFromSourceLocation(Sources, Start, Length, ReplacementText); |
55 | 448 | } |
56 | | |
57 | | Replacement::Replacement(const SourceManager &Sources, |
58 | | const CharSourceRange &Range, |
59 | | StringRef ReplacementText, |
60 | 32.4k | const LangOptions &LangOpts) { |
61 | 32.4k | setFromSourceRange(Sources, Range, ReplacementText, LangOpts); |
62 | 32.4k | } |
63 | | |
64 | 2.89k | bool Replacement::isApplicable() const { |
65 | 2.89k | return FilePath != InvalidLocation; |
66 | 2.89k | } |
67 | | |
68 | 64.8k | bool Replacement::apply(Rewriter &Rewrite) const { |
69 | 64.8k | SourceManager &SM = Rewrite.getSourceMgr(); |
70 | 64.8k | auto Entry = SM.getFileManager().getFile(FilePath); |
71 | 64.8k | if (!Entry) |
72 | 1 | return false; |
73 | | |
74 | 64.8k | FileID ID = SM.getOrCreateFileID(*Entry, SrcMgr::C_User); |
75 | 64.8k | const SourceLocation Start = |
76 | 64.8k | SM.getLocForStartOfFile(ID). |
77 | 64.8k | getLocWithOffset(ReplacementRange.getOffset()); |
78 | | // ReplaceText returns false on success. |
79 | | // ReplaceText only fails if the source location is not a file location, in |
80 | | // which case we already returned false earlier. |
81 | 64.8k | bool RewriteSucceeded = !Rewrite.ReplaceText( |
82 | 64.8k | Start, ReplacementRange.getLength(), ReplacementText); |
83 | 64.8k | assert(RewriteSucceeded); |
84 | 0 | return RewriteSucceeded; |
85 | 64.8k | } |
86 | | |
87 | 8 | std::string Replacement::toString() const { |
88 | 8 | std::string Result; |
89 | 8 | llvm::raw_string_ostream Stream(Result); |
90 | 8 | Stream << FilePath << ": " << ReplacementRange.getOffset() << ":+" |
91 | 8 | << ReplacementRange.getLength() << ":\"" << ReplacementText << "\""; |
92 | 8 | return Stream.str(); |
93 | 8 | } |
94 | | |
95 | | namespace clang { |
96 | | namespace tooling { |
97 | | |
98 | 612k | bool operator<(const Replacement &LHS, const Replacement &RHS) { |
99 | 612k | if (LHS.getOffset() != RHS.getOffset()) |
100 | 612k | return LHS.getOffset() < RHS.getOffset(); |
101 | | |
102 | 298 | if (LHS.getLength() != RHS.getLength()) |
103 | 50 | return LHS.getLength() < RHS.getLength(); |
104 | | |
105 | 248 | if (LHS.getFilePath() != RHS.getFilePath()) |
106 | 0 | return LHS.getFilePath() < RHS.getFilePath(); |
107 | 248 | return LHS.getReplacementText() < RHS.getReplacementText(); |
108 | 248 | } |
109 | | |
110 | 248 | bool operator==(const Replacement &LHS, const Replacement &RHS) { |
111 | 248 | return LHS.getOffset() == RHS.getOffset() && |
112 | 248 | LHS.getLength() == RHS.getLength() && |
113 | 248 | LHS.getFilePath() == RHS.getFilePath() && |
114 | 248 | LHS.getReplacementText() == RHS.getReplacementText(); |
115 | 248 | } |
116 | | |
117 | | } // namespace tooling |
118 | | } // namespace clang |
119 | | |
120 | | void Replacement::setFromSourceLocation(const SourceManager &Sources, |
121 | | SourceLocation Start, unsigned Length, |
122 | 32.8k | StringRef ReplacementText) { |
123 | 32.8k | const std::pair<FileID, unsigned> DecomposedLocation = |
124 | 32.8k | Sources.getDecomposedLoc(Start); |
125 | 32.8k | const FileEntry *Entry = Sources.getFileEntryForID(DecomposedLocation.first); |
126 | 32.8k | this->FilePath = std::string(Entry ? Entry->getName()32.8k : InvalidLocation6 ); |
127 | 32.8k | this->ReplacementRange = Range(DecomposedLocation.second, Length); |
128 | 32.8k | this->ReplacementText = std::string(ReplacementText); |
129 | 32.8k | } |
130 | | |
131 | | // FIXME: This should go into the Lexer, but we need to figure out how |
132 | | // to handle ranges for refactoring in general first - there is no obvious |
133 | | // good way how to integrate this into the Lexer yet. |
134 | | static int getRangeSize(const SourceManager &Sources, |
135 | | const CharSourceRange &Range, |
136 | 32.4k | const LangOptions &LangOpts) { |
137 | 32.4k | SourceLocation SpellingBegin = Sources.getSpellingLoc(Range.getBegin()); |
138 | 32.4k | SourceLocation SpellingEnd = Sources.getSpellingLoc(Range.getEnd()); |
139 | 32.4k | std::pair<FileID, unsigned> Start = Sources.getDecomposedLoc(SpellingBegin); |
140 | 32.4k | std::pair<FileID, unsigned> End = Sources.getDecomposedLoc(SpellingEnd); |
141 | 32.4k | if (Start.first != End.first) return -10 ; |
142 | 32.4k | if (Range.isTokenRange()) |
143 | 742 | End.second += Lexer::MeasureTokenLength(SpellingEnd, Sources, LangOpts); |
144 | 32.4k | return End.second - Start.second; |
145 | 32.4k | } |
146 | | |
147 | | void Replacement::setFromSourceRange(const SourceManager &Sources, |
148 | | const CharSourceRange &Range, |
149 | | StringRef ReplacementText, |
150 | 32.4k | const LangOptions &LangOpts) { |
151 | 32.4k | setFromSourceLocation(Sources, Sources.getSpellingLoc(Range.getBegin()), |
152 | 32.4k | getRangeSize(Sources, Range, LangOpts), |
153 | 32.4k | ReplacementText); |
154 | 32.4k | } |
155 | | |
156 | | Replacement |
157 | 388 | Replacements::getReplacementInChangedCode(const Replacement &R) const { |
158 | 388 | unsigned NewStart = getShiftedCodePosition(R.getOffset()); |
159 | 388 | unsigned NewEnd = getShiftedCodePosition(R.getOffset() + R.getLength()); |
160 | 388 | return Replacement(R.getFilePath(), NewStart, NewEnd - NewStart, |
161 | 388 | R.getReplacementText()); |
162 | 388 | } |
163 | | |
164 | 4 | static std::string getReplacementErrString(replacement_error Err) { |
165 | 4 | switch (Err) { |
166 | 0 | case replacement_error::fail_to_apply: |
167 | 0 | return "Failed to apply a replacement."; |
168 | 0 | case replacement_error::wrong_file_path: |
169 | 0 | return "The new replacement's file path is different from the file path of " |
170 | 0 | "existing replacements"; |
171 | 3 | case replacement_error::overlap_conflict: |
172 | 3 | return "The new replacement overlaps with an existing replacement."; |
173 | 1 | case replacement_error::insert_conflict: |
174 | 1 | return "The new insertion has the same insert location as an existing " |
175 | 1 | "replacement."; |
176 | 4 | } |
177 | 0 | llvm_unreachable("A value of replacement_error has no message."); |
178 | 0 | } |
179 | | |
180 | 4 | std::string ReplacementError::message() const { |
181 | 4 | std::string Message = getReplacementErrString(Err); |
182 | 4 | if (NewReplacement) |
183 | 4 | Message += "\nNew replacement: " + NewReplacement->toString(); |
184 | 4 | if (ExistingReplacement) |
185 | 4 | Message += "\nExisting replacement: " + ExistingReplacement->toString(); |
186 | 4 | return Message; |
187 | 4 | } |
188 | | |
189 | | char ReplacementError::ID = 0; |
190 | | |
191 | 386 | Replacements Replacements::getCanonicalReplacements() const { |
192 | 386 | std::vector<Replacement> NewReplaces; |
193 | | // Merge adjacent replacements. |
194 | 387 | for (const auto &R : Replaces) { |
195 | 387 | if (NewReplaces.empty()) { |
196 | 386 | NewReplaces.push_back(R); |
197 | 386 | continue; |
198 | 386 | } |
199 | 1 | auto &Prev = NewReplaces.back(); |
200 | 1 | unsigned PrevEnd = Prev.getOffset() + Prev.getLength(); |
201 | 1 | if (PrevEnd < R.getOffset()) { |
202 | 0 | NewReplaces.push_back(R); |
203 | 1 | } else { |
204 | 1 | assert(PrevEnd == R.getOffset() && |
205 | 1 | "Existing replacements must not overlap."); |
206 | 0 | Replacement NewR( |
207 | 1 | R.getFilePath(), Prev.getOffset(), Prev.getLength() + R.getLength(), |
208 | 1 | (Prev.getReplacementText() + R.getReplacementText()).str()); |
209 | 1 | Prev = NewR; |
210 | 1 | } |
211 | 1 | } |
212 | 386 | ReplacementsImpl NewReplacesImpl(NewReplaces.begin(), NewReplaces.end()); |
213 | 386 | return Replacements(NewReplacesImpl.begin(), NewReplacesImpl.end()); |
214 | 386 | } |
215 | | |
216 | | // `R` and `Replaces` are order-independent if applying them in either order |
217 | | // has the same effect, so we need to compare replacements associated to |
218 | | // applying them in either order. |
219 | | llvm::Expected<Replacements> |
220 | 193 | Replacements::mergeIfOrderIndependent(const Replacement &R) const { |
221 | 193 | Replacements Rs(R); |
222 | | // A Replacements set containing a single replacement that is `R` referring to |
223 | | // the code after the existing replacements `Replaces` are applied. |
224 | 193 | Replacements RsShiftedByReplaces(getReplacementInChangedCode(R)); |
225 | | // A Replacements set that is `Replaces` referring to the code after `R` is |
226 | | // applied. |
227 | 193 | Replacements ReplacesShiftedByRs; |
228 | 193 | for (const auto &Replace : Replaces) |
229 | 195 | ReplacesShiftedByRs.Replaces.insert( |
230 | 195 | Rs.getReplacementInChangedCode(Replace)); |
231 | | // This is equivalent to applying `Replaces` first and then `R`. |
232 | 193 | auto MergeShiftedRs = merge(RsShiftedByReplaces); |
233 | | // This is equivalent to applying `R` first and then `Replaces`. |
234 | 193 | auto MergeShiftedReplaces = Rs.merge(ReplacesShiftedByRs); |
235 | | |
236 | | // Since empty or segmented replacements around existing replacements might be |
237 | | // produced above, we need to compare replacements in canonical forms. |
238 | 193 | if (MergeShiftedRs.getCanonicalReplacements() == |
239 | 193 | MergeShiftedReplaces.getCanonicalReplacements()) |
240 | 185 | return MergeShiftedRs; |
241 | 8 | return llvm::make_error<ReplacementError>(replacement_error::overlap_conflict, |
242 | 8 | R, *Replaces.begin()); |
243 | 193 | } |
244 | | |
245 | 99.0k | llvm::Error Replacements::add(const Replacement &R) { |
246 | | // Check the file path. |
247 | 99.0k | if (!Replaces.empty() && R.getFilePath() != Replaces.begin()->getFilePath()66.0k ) |
248 | 4 | return llvm::make_error<ReplacementError>( |
249 | 4 | replacement_error::wrong_file_path, R, *Replaces.begin()); |
250 | | |
251 | | // Special-case header insertions. |
252 | 99.0k | if (R.getOffset() == std::numeric_limits<unsigned>::max()) { |
253 | 78 | Replaces.insert(R); |
254 | 78 | return llvm::Error::success(); |
255 | 78 | } |
256 | | |
257 | | // This replacement cannot conflict with replacements that end before |
258 | | // this replacement starts or start after this replacement ends. |
259 | | // We also know that there currently are no overlapping replacements. |
260 | | // Thus, we know that all replacements that start after the end of the current |
261 | | // replacement cannot overlap. |
262 | 98.9k | Replacement AtEnd(R.getFilePath(), R.getOffset() + R.getLength(), 0, ""); |
263 | | |
264 | | // Find the first entry that starts after or at the end of R. Note that |
265 | | // entries that start at the end can still be conflicting if R is an |
266 | | // insertion. |
267 | 98.9k | auto I = Replaces.lower_bound(AtEnd); |
268 | | // If `I` starts at the same offset as `R`, `R` must be an insertion. |
269 | 98.9k | if (I != Replaces.end() && R.getOffset() == I->getOffset()342 ) { |
270 | 32 | assert(R.getLength() == 0); |
271 | | // `I` is also an insertion, `R` and `I` conflict. |
272 | 32 | if (I->getLength() == 0) { |
273 | | // Check if two insertions are order-indepedent: if inserting them in |
274 | | // either order produces the same text, they are order-independent. |
275 | 27 | if ((R.getReplacementText() + I->getReplacementText()).str() != |
276 | 27 | (I->getReplacementText() + R.getReplacementText()).str()) |
277 | 21 | return llvm::make_error<ReplacementError>( |
278 | 21 | replacement_error::insert_conflict, R, *I); |
279 | | // If insertions are order-independent, we can merge them. |
280 | 6 | Replacement NewR( |
281 | 6 | R.getFilePath(), R.getOffset(), 0, |
282 | 6 | (R.getReplacementText() + I->getReplacementText()).str()); |
283 | 6 | Replaces.erase(I); |
284 | 6 | Replaces.insert(std::move(NewR)); |
285 | 6 | return llvm::Error::success(); |
286 | 27 | } |
287 | | // Insertion `R` is adjacent to a non-insertion replacement `I`, so they |
288 | | // are order-independent. It is safe to assume that `R` will not conflict |
289 | | // with any replacement before `I` since all replacements before `I` must |
290 | | // either end before `R` or end at `R` but has length > 0 (if the |
291 | | // replacement before `I` is an insertion at `R`, it would have been `I` |
292 | | // since it is a lower bound of `AtEnd` and ordered before the current `I` |
293 | | // in the set). |
294 | 5 | Replaces.insert(R); |
295 | 5 | return llvm::Error::success(); |
296 | 32 | } |
297 | | |
298 | | // `I` is the smallest iterator (after `R`) whose entry cannot overlap. |
299 | | // If that is begin(), there are no overlaps. |
300 | 98.9k | if (I == Replaces.begin()) { |
301 | 33.0k | Replaces.insert(R); |
302 | 33.0k | return llvm::Error::success(); |
303 | 33.0k | } |
304 | 65.8k | --I; |
305 | 65.9k | auto Overlap = [](const Replacement &R1, const Replacement &R2) -> bool { |
306 | 65.9k | return Range(R1.getOffset(), R1.getLength()) |
307 | 65.9k | .overlapsWith(Range(R2.getOffset(), R2.getLength())); |
308 | 65.9k | }; |
309 | | // If the previous entry does not overlap, we know that entries before it |
310 | | // can also not overlap. |
311 | 65.8k | if (!Overlap(R, *I)) { |
312 | | // If `R` and `I` do not have the same offset, it is safe to add `R` since |
313 | | // it must come after `I`. Otherwise: |
314 | | // - If `R` is an insertion, `I` must not be an insertion since it would |
315 | | // have come after `AtEnd`. |
316 | | // - If `R` is not an insertion, `I` must be an insertion; otherwise, `R` |
317 | | // and `I` would have overlapped. |
318 | | // In either case, we can safely insert `R`. |
319 | 65.6k | Replaces.insert(R); |
320 | 65.6k | } else { |
321 | | // `I` overlaps with `R`. We need to check `R` against all overlapping |
322 | | // replacements to see if they are order-indepedent. If they are, merge `R` |
323 | | // with them and replace them with the merged replacements. |
324 | 193 | auto MergeBegin = I; |
325 | 193 | auto MergeEnd = std::next(I); |
326 | 195 | while (I != Replaces.begin()) { |
327 | 54 | --I; |
328 | | // If `I` doesn't overlap with `R`, don't merge it. |
329 | 54 | if (!Overlap(R, *I)) |
330 | 52 | break; |
331 | 2 | MergeBegin = I; |
332 | 2 | } |
333 | 193 | Replacements OverlapReplaces(MergeBegin, MergeEnd); |
334 | 193 | llvm::Expected<Replacements> Merged = |
335 | 193 | OverlapReplaces.mergeIfOrderIndependent(R); |
336 | 193 | if (!Merged) |
337 | 8 | return Merged.takeError(); |
338 | 185 | Replaces.erase(MergeBegin, MergeEnd); |
339 | 185 | Replaces.insert(Merged->begin(), Merged->end()); |
340 | 185 | } |
341 | 65.8k | return llvm::Error::success(); |
342 | 65.8k | } |
343 | | |
344 | | namespace { |
345 | | |
346 | | // Represents a merged replacement, i.e. a replacement consisting of multiple |
347 | | // overlapping replacements from 'First' and 'Second' in mergeReplacements. |
348 | | // |
349 | | // Position projection: |
350 | | // Offsets and lengths of the replacements can generally refer to two different |
351 | | // coordinate spaces. Replacements from 'First' refer to the original text |
352 | | // whereas replacements from 'Second' refer to the text after applying 'First'. |
353 | | // |
354 | | // MergedReplacement always operates in the coordinate space of the original |
355 | | // text, i.e. transforms elements from 'Second' to take into account what was |
356 | | // changed based on the elements from 'First'. |
357 | | // |
358 | | // We can correctly calculate this projection as we look at the replacements in |
359 | | // order of strictly increasing offsets. |
360 | | // |
361 | | // Invariants: |
362 | | // * We always merge elements from 'First' into elements from 'Second' and vice |
363 | | // versa. Within each set, the replacements are non-overlapping. |
364 | | // * We only extend to the right, i.e. merge elements with strictly increasing |
365 | | // offsets. |
366 | | class MergedReplacement { |
367 | | public: |
368 | | MergedReplacement(const Replacement &R, bool MergeSecond, int D) |
369 | | : MergeSecond(MergeSecond), Delta(D), FilePath(R.getFilePath()), |
370 | | Offset(R.getOffset() + (MergeSecond ? 0 : Delta)), |
371 | 5.92k | Length(R.getLength()), Text(std::string(R.getReplacementText())) { |
372 | 5.92k | Delta += MergeSecond ? 01.72k : Text.size() - Length4.19k ; |
373 | 5.92k | DeltaFirst = MergeSecond ? Text.size() - Length1.72k : 04.19k ; |
374 | 5.92k | } |
375 | | |
376 | | // Merges the next element 'R' into this merged element. As we always merge |
377 | | // from 'First' into 'Second' or vice versa, the MergedReplacement knows what |
378 | | // set the next element is coming from. |
379 | 4.82k | void merge(const Replacement &R) { |
380 | 4.82k | if (MergeSecond) { |
381 | 2.46k | unsigned REnd = R.getOffset() + Delta + R.getLength(); |
382 | 2.46k | unsigned End = Offset + Text.size(); |
383 | 2.46k | if (REnd > End) { |
384 | 109 | Length += REnd - End; |
385 | 109 | MergeSecond = false; |
386 | 109 | } |
387 | 2.46k | StringRef TextRef = Text; |
388 | 2.46k | StringRef Head = TextRef.substr(0, R.getOffset() + Delta - Offset); |
389 | 2.46k | StringRef Tail = TextRef.substr(REnd - Offset); |
390 | 2.46k | Text = (Head + R.getReplacementText() + Tail).str(); |
391 | 2.46k | Delta += R.getReplacementText().size() - R.getLength(); |
392 | 2.46k | } else { |
393 | 2.36k | unsigned End = Offset + Length; |
394 | 2.36k | StringRef RText = R.getReplacementText(); |
395 | 2.36k | StringRef Tail = RText.substr(End - R.getOffset()); |
396 | 2.36k | Text = (Text + Tail).str(); |
397 | 2.36k | if (R.getOffset() + RText.size() > End) { |
398 | 1.55k | Length = R.getOffset() + R.getLength() - Offset; |
399 | 1.55k | MergeSecond = true; |
400 | 1.55k | } else { |
401 | 802 | Length += R.getLength() - RText.size(); |
402 | 802 | } |
403 | 2.36k | DeltaFirst += RText.size() - R.getLength(); |
404 | 2.36k | } |
405 | 4.82k | } |
406 | | |
407 | | // Returns 'true' if 'R' starts strictly after the MergedReplacement and thus |
408 | | // doesn't need to be merged. |
409 | 6.95k | bool endsBefore(const Replacement &R) const { |
410 | 6.95k | if (MergeSecond) |
411 | 2.98k | return Offset + Text.size() < R.getOffset() + Delta; |
412 | 3.97k | return Offset + Length < R.getOffset(); |
413 | 6.95k | } |
414 | | |
415 | | // Returns 'true' if an element from the second set should be merged next. |
416 | 25.4k | bool mergeSecond() const { return MergeSecond; } |
417 | | |
418 | 5.92k | int deltaFirst() const { return DeltaFirst; } |
419 | 5.92k | Replacement asReplacement() const { return {FilePath, Offset, Length, Text}; } |
420 | | |
421 | | private: |
422 | | bool MergeSecond; |
423 | | |
424 | | // Amount of characters that elements from 'Second' need to be shifted by in |
425 | | // order to refer to the original text. |
426 | | int Delta; |
427 | | |
428 | | // Sum of all deltas (text-length - length) of elements from 'First' merged |
429 | | // into this element. This is used to update 'Delta' once the |
430 | | // MergedReplacement is completed. |
431 | | int DeltaFirst; |
432 | | |
433 | | // Data of the actually merged replacement. FilePath and Offset aren't changed |
434 | | // as the element is only extended to the right. |
435 | | const StringRef FilePath; |
436 | | const unsigned Offset; |
437 | | unsigned Length; |
438 | | std::string Text; |
439 | | }; |
440 | | |
441 | | } // namespace |
442 | | |
443 | 68.3k | Replacements Replacements::merge(const Replacements &ReplacesToMerge) const { |
444 | 68.3k | if (empty() || ReplacesToMerge.empty()6.07k ) |
445 | 64.8k | return empty() ? ReplacesToMerge62.3k : *this2.56k ; |
446 | | |
447 | 3.51k | auto &First = Replaces; |
448 | 3.51k | auto &Second = ReplacesToMerge.Replaces; |
449 | | // Delta is the amount of characters that replacements from 'Second' need to |
450 | | // be shifted so that their offsets refer to the original text. |
451 | 3.51k | int Delta = 0; |
452 | 3.51k | ReplacementsImpl Result; |
453 | | |
454 | | // Iterate over both sets and always add the next element (smallest total |
455 | | // Offset) from either 'First' or 'Second'. Merge that element with |
456 | | // subsequent replacements as long as they overlap. See more details in the |
457 | | // comment on MergedReplacement. |
458 | 3.51k | for (auto FirstI = First.begin(), SecondI = Second.begin(); |
459 | 9.43k | FirstI != First.end() || SecondI != Second.end()3.98k ;) { |
460 | 5.92k | bool NextIsFirst = SecondI == Second.end() || |
461 | 5.92k | (5.72k FirstI != First.end()5.72k && |
462 | 5.72k | FirstI->getOffset() < SecondI->getOffset() + Delta5.26k ); |
463 | 5.92k | MergedReplacement Merged(NextIsFirst ? *FirstI1.72k : *SecondI4.19k , NextIsFirst, |
464 | 5.92k | Delta); |
465 | 5.92k | ++(NextIsFirst ? FirstI1.72k : SecondI4.19k ); |
466 | | |
467 | 10.7k | while ((Merged.mergeSecond() && SecondI != Second.end()5.63k ) || |
468 | 10.7k | (7.76k !Merged.mergeSecond()7.76k && FirstI != First.end()5.10k )) { |
469 | 6.95k | auto &I = Merged.mergeSecond() ? SecondI2.98k : FirstI3.97k ; |
470 | 6.95k | if (Merged.endsBefore(*I)) |
471 | 2.13k | break; |
472 | 4.82k | Merged.merge(*I); |
473 | 4.82k | ++I; |
474 | 4.82k | } |
475 | 5.92k | Delta -= Merged.deltaFirst(); |
476 | 5.92k | Result.insert(Merged.asReplacement()); |
477 | 5.92k | } |
478 | 3.51k | return Replacements(Result.begin(), Result.end()); |
479 | 68.3k | } |
480 | | |
481 | | // Combines overlapping ranges in \p Ranges and sorts the combined ranges. |
482 | | // Returns a set of non-overlapping and sorted ranges that is equivalent to |
483 | | // \p Ranges. |
484 | 44.9k | static std::vector<Range> combineAndSortRanges(std::vector<Range> Ranges) { |
485 | 44.9k | llvm::sort(Ranges, [](const Range &LHS, const Range &RHS) { |
486 | 1.20k | if (LHS.getOffset() != RHS.getOffset()) |
487 | 1.20k | return LHS.getOffset() < RHS.getOffset(); |
488 | 1 | return LHS.getLength() < RHS.getLength(); |
489 | 1.20k | }); |
490 | 44.9k | std::vector<Range> Result; |
491 | 46.1k | for (const auto &R : Ranges) { |
492 | 46.1k | if (Result.empty() || |
493 | 46.1k | Result.back().getOffset() + Result.back().getLength() < R.getOffset()1.20k ) { |
494 | 46.1k | Result.push_back(R); |
495 | 46.1k | } else { |
496 | 15 | unsigned NewEnd = |
497 | 15 | std::max(Result.back().getOffset() + Result.back().getLength(), |
498 | 15 | R.getOffset() + R.getLength()); |
499 | 15 | Result[Result.size() - 1] = |
500 | 15 | Range(Result.back().getOffset(), NewEnd - Result.back().getOffset()); |
501 | 15 | } |
502 | 46.1k | } |
503 | 44.9k | return Result; |
504 | 44.9k | } |
505 | | |
506 | | namespace clang { |
507 | | namespace tooling { |
508 | | |
509 | | std::vector<Range> |
510 | | calculateRangesAfterReplacements(const Replacements &Replaces, |
511 | 41.4k | const std::vector<Range> &Ranges) { |
512 | | // To calculate the new ranges, |
513 | | // - Turn \p Ranges into Replacements at (offset, length) with an empty |
514 | | // (unimportant) replacement text of length "length". |
515 | | // - Merge with \p Replaces. |
516 | | // - The new ranges will be the affected ranges of the merged replacements. |
517 | 41.4k | auto MergedRanges = combineAndSortRanges(Ranges); |
518 | 41.4k | if (Replaces.empty()) |
519 | 39.1k | return MergedRanges; |
520 | 2.28k | tooling::Replacements FakeReplaces; |
521 | 2.32k | for (const auto &R : MergedRanges) { |
522 | 2.32k | llvm::cantFail( |
523 | 2.32k | FakeReplaces.add(Replacement(Replaces.begin()->getFilePath(), |
524 | 2.32k | R.getOffset(), R.getLength(), |
525 | 2.32k | std::string(R.getLength(), ' '))), |
526 | 2.32k | "Replacements must not conflict since ranges have been merged."); |
527 | 2.32k | } |
528 | 2.28k | return FakeReplaces.merge(Replaces).getAffectedRanges(); |
529 | 41.4k | } |
530 | | |
531 | | } // namespace tooling |
532 | | } // namespace clang |
533 | | |
534 | 3.47k | std::vector<Range> Replacements::getAffectedRanges() const { |
535 | 3.47k | std::vector<Range> ChangedRanges; |
536 | 3.47k | int Shift = 0; |
537 | 4.20k | for (const auto &R : Replaces) { |
538 | 4.20k | unsigned Offset = R.getOffset() + Shift; |
539 | 4.20k | unsigned Length = R.getReplacementText().size(); |
540 | 4.20k | Shift += Length - R.getLength(); |
541 | 4.20k | ChangedRanges.push_back(Range(Offset, Length)); |
542 | 4.20k | } |
543 | 3.47k | return combineAndSortRanges(ChangedRanges); |
544 | 3.47k | } |
545 | | |
546 | 816 | unsigned Replacements::getShiftedCodePosition(unsigned Position) const { |
547 | 816 | unsigned Offset = 0; |
548 | 831 | for (const auto &R : Replaces) { |
549 | 831 | if (R.getOffset() + R.getLength() <= Position) { |
550 | 410 | Offset += R.getReplacementText().size() - R.getLength(); |
551 | 410 | continue; |
552 | 410 | } |
553 | 421 | if (R.getOffset() < Position && |
554 | 421 | R.getOffset() + R.getReplacementText().size() <= Position34 ) { |
555 | 25 | Position = R.getOffset() + R.getReplacementText().size(); |
556 | 25 | if (!R.getReplacementText().empty()) |
557 | 11 | Position--; |
558 | 25 | } |
559 | 421 | break; |
560 | 831 | } |
561 | 816 | return Position + Offset; |
562 | 816 | } |
563 | | |
564 | | namespace clang { |
565 | | namespace tooling { |
566 | | |
567 | 607 | bool applyAllReplacements(const Replacements &Replaces, Rewriter &Rewrite) { |
568 | 607 | bool Result = true; |
569 | 3.49k | for (auto I = Replaces.rbegin(), E = Replaces.rend(); I != E; ++I2.89k ) { |
570 | 2.89k | if (I->isApplicable()) { |
571 | 2.89k | Result = I->apply(Rewrite) && Result; |
572 | 2.89k | } else { |
573 | 1 | Result = false; |
574 | 1 | } |
575 | 2.89k | } |
576 | 607 | return Result; |
577 | 607 | } |
578 | | |
579 | | llvm::Expected<std::string> applyAllReplacements(StringRef Code, |
580 | 88.2k | const Replacements &Replaces) { |
581 | 88.2k | if (Replaces.empty()) |
582 | 68.5k | return Code.str(); |
583 | | |
584 | 19.7k | IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem> InMemoryFileSystem( |
585 | 19.7k | new llvm::vfs::InMemoryFileSystem); |
586 | 19.7k | FileManager Files(FileSystemOptions(), InMemoryFileSystem); |
587 | 19.7k | DiagnosticsEngine Diagnostics( |
588 | 19.7k | IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs), |
589 | 19.7k | new DiagnosticOptions); |
590 | 19.7k | SourceManager SourceMgr(Diagnostics, Files); |
591 | 19.7k | Rewriter Rewrite(SourceMgr, LangOptions()); |
592 | 19.7k | InMemoryFileSystem->addFile( |
593 | 19.7k | "<stdin>", 0, llvm::MemoryBuffer::getMemBuffer(Code, "<stdin>")); |
594 | 19.7k | FileID ID = SourceMgr.createFileID(*Files.getOptionalFileRef("<stdin>"), |
595 | 19.7k | SourceLocation(), |
596 | 19.7k | clang::SrcMgr::C_User); |
597 | 81.6k | for (auto I = Replaces.rbegin(), E = Replaces.rend(); I != E; ++I61.9k ) { |
598 | 61.9k | Replacement Replace("<stdin>", I->getOffset(), I->getLength(), |
599 | 61.9k | I->getReplacementText()); |
600 | 61.9k | if (!Replace.apply(Rewrite)) |
601 | 0 | return llvm::make_error<ReplacementError>( |
602 | 0 | replacement_error::fail_to_apply, Replace); |
603 | 61.9k | } |
604 | 19.7k | std::string Result; |
605 | 19.7k | llvm::raw_string_ostream OS(Result); |
606 | 19.7k | Rewrite.getEditBuffer(ID).write(OS); |
607 | 19.7k | OS.flush(); |
608 | 19.7k | return Result; |
609 | 19.7k | } |
610 | | |
611 | | std::map<std::string, Replacements> groupReplacementsByFile( |
612 | | FileManager &FileMgr, |
613 | 333 | const std::map<std::string, Replacements> &FileToReplaces) { |
614 | 333 | std::map<std::string, Replacements> Result; |
615 | 333 | llvm::SmallPtrSet<const FileEntry *, 16> ProcessedFileEntries; |
616 | 556 | for (const auto &Entry : FileToReplaces) { |
617 | 556 | auto FE = FileMgr.getFile(Entry.first); |
618 | 556 | if (!FE) |
619 | 2 | llvm::errs() << "File path " << Entry.first << " is invalid.\n"; |
620 | 554 | else if (ProcessedFileEntries.insert(*FE).second) |
621 | 552 | Result[Entry.first] = std::move(Entry.second); |
622 | 556 | } |
623 | 333 | return Result; |
624 | 333 | } |
625 | | |
626 | | } // namespace tooling |
627 | | } // namespace clang |