1 //===- unittest/Tooling/RefactoringTest.cpp - Refactoring unit tests ------===//
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 #include "clang/Tooling/Refactoring.h"
10 #include "ReplacementTest.h"
11 #include "RewriterTestContext.h"
12 #include "clang/AST/ASTConsumer.h"
13 #include "clang/AST/ASTContext.h"
14 #include "clang/AST/DeclCXX.h"
15 #include "clang/AST/DeclGroup.h"
16 #include "clang/AST/RecursiveASTVisitor.h"
17 #include "clang/Basic/Diagnostic.h"
18 #include "clang/Basic/DiagnosticOptions.h"
19 #include "clang/Basic/FileManager.h"
20 #include "clang/Basic/LangOptions.h"
21 #include "clang/Basic/SourceManager.h"
22 #include "clang/Format/Format.h"
23 #include "clang/Frontend/CompilerInstance.h"
24 #include "clang/Frontend/FrontendAction.h"
25 #include "clang/Frontend/TextDiagnosticPrinter.h"
26 #include "clang/Rewrite/Core/Rewriter.h"
27 #include "clang/Tooling/Refactoring/AtomicChange.h"
28 #include "clang/Tooling/Tooling.h"
29 #include "llvm/ADT/SmallString.h"
30 #include "llvm/Support/VirtualFileSystem.h"
31 #include "gtest/gtest.h"
32
33 namespace clang {
34 namespace tooling {
35
TEST_F(ReplacementTest,CanDeleteAllText)36 TEST_F(ReplacementTest, CanDeleteAllText) {
37 FileID ID = Context.createInMemoryFile("input.cpp", "text");
38 SourceLocation Location = Context.getLocation(ID, 1, 1);
39 Replacement Replace(createReplacement(Location, 4, ""));
40 EXPECT_TRUE(Replace.apply(Context.Rewrite));
41 EXPECT_EQ("", Context.getRewrittenText(ID));
42 }
43
TEST_F(ReplacementTest,CanDeleteAllTextInTextWithNewlines)44 TEST_F(ReplacementTest, CanDeleteAllTextInTextWithNewlines) {
45 FileID ID = Context.createInMemoryFile("input.cpp", "line1\nline2\nline3");
46 SourceLocation Location = Context.getLocation(ID, 1, 1);
47 Replacement Replace(createReplacement(Location, 17, ""));
48 EXPECT_TRUE(Replace.apply(Context.Rewrite));
49 EXPECT_EQ("", Context.getRewrittenText(ID));
50 }
51
TEST_F(ReplacementTest,CanAddText)52 TEST_F(ReplacementTest, CanAddText) {
53 FileID ID = Context.createInMemoryFile("input.cpp", "");
54 SourceLocation Location = Context.getLocation(ID, 1, 1);
55 Replacement Replace(createReplacement(Location, 0, "result"));
56 EXPECT_TRUE(Replace.apply(Context.Rewrite));
57 EXPECT_EQ("result", Context.getRewrittenText(ID));
58 }
59
TEST_F(ReplacementTest,CanReplaceTextAtPosition)60 TEST_F(ReplacementTest, CanReplaceTextAtPosition) {
61 FileID ID = Context.createInMemoryFile("input.cpp",
62 "line1\nline2\nline3\nline4");
63 SourceLocation Location = Context.getLocation(ID, 2, 3);
64 Replacement Replace(createReplacement(Location, 12, "x"));
65 EXPECT_TRUE(Replace.apply(Context.Rewrite));
66 EXPECT_EQ("line1\nlixne4", Context.getRewrittenText(ID));
67 }
68
TEST_F(ReplacementTest,CanReplaceTextAtPositionMultipleTimes)69 TEST_F(ReplacementTest, CanReplaceTextAtPositionMultipleTimes) {
70 FileID ID = Context.createInMemoryFile("input.cpp",
71 "line1\nline2\nline3\nline4");
72 SourceLocation Location1 = Context.getLocation(ID, 2, 3);
73 Replacement Replace1(createReplacement(Location1, 12, "x\ny\n"));
74 EXPECT_TRUE(Replace1.apply(Context.Rewrite));
75 EXPECT_EQ("line1\nlix\ny\nne4", Context.getRewrittenText(ID));
76
77 // Since the original source has not been modified, the (4, 4) points to the
78 // 'e' in the original content.
79 SourceLocation Location2 = Context.getLocation(ID, 4, 4);
80 Replacement Replace2(createReplacement(Location2, 1, "f"));
81 EXPECT_TRUE(Replace2.apply(Context.Rewrite));
82 EXPECT_EQ("line1\nlix\ny\nnf4", Context.getRewrittenText(ID));
83 }
84
TEST_F(ReplacementTest,ApplyFailsForNonExistentLocation)85 TEST_F(ReplacementTest, ApplyFailsForNonExistentLocation) {
86 Replacement Replace("nonexistent-file.cpp", 0, 1, "");
87 EXPECT_FALSE(Replace.apply(Context.Rewrite));
88 }
89
TEST_F(ReplacementTest,CanRetrivePath)90 TEST_F(ReplacementTest, CanRetrivePath) {
91 Replacement Replace("/path/to/file.cpp", 0, 1, "");
92 EXPECT_EQ("/path/to/file.cpp", Replace.getFilePath());
93 }
94
TEST_F(ReplacementTest,ReturnsInvalidPath)95 TEST_F(ReplacementTest, ReturnsInvalidPath) {
96 Replacement Replace1(Context.Sources, SourceLocation(), 0, "");
97 EXPECT_TRUE(Replace1.getFilePath().empty());
98
99 Replacement Replace2;
100 EXPECT_TRUE(Replace2.getFilePath().empty());
101 }
102
103 // Checks that an llvm::Error instance contains a ReplacementError with expected
104 // error code, expected new replacement, and expected existing replacement.
checkReplacementError(llvm::Error && Error,replacement_error ExpectedErr,llvm::Optional<Replacement> ExpectedExisting,llvm::Optional<Replacement> ExpectedNew)105 static bool checkReplacementError(llvm::Error &&Error,
106 replacement_error ExpectedErr,
107 llvm::Optional<Replacement> ExpectedExisting,
108 llvm::Optional<Replacement> ExpectedNew) {
109 if (!Error) {
110 llvm::errs() << "Error is a success.";
111 return false;
112 }
113 std::string ErrorMessage;
114 llvm::raw_string_ostream OS(ErrorMessage);
115 llvm::handleAllErrors(std::move(Error), [&](const ReplacementError &RE) {
116 llvm::errs() << "Handling error...\n";
117 if (ExpectedErr != RE.get())
118 OS << "Unexpected error code: " << int(RE.get()) << "\n";
119 if (ExpectedExisting != RE.getExistingReplacement()) {
120 OS << "Expected Existing != Actual Existing.\n";
121 if (ExpectedExisting.hasValue())
122 OS << "Expected existing replacement: " << ExpectedExisting->toString()
123 << "\n";
124 if (RE.getExistingReplacement().hasValue())
125 OS << "Actual existing replacement: "
126 << RE.getExistingReplacement()->toString() << "\n";
127 }
128 if (ExpectedNew != RE.getNewReplacement()) {
129 OS << "Expected New != Actual New.\n";
130 if (ExpectedNew.hasValue())
131 OS << "Expected new replacement: " << ExpectedNew->toString() << "\n";
132 if (RE.getNewReplacement().hasValue())
133 OS << "Actual new replacement: " << RE.getNewReplacement()->toString()
134 << "\n";
135 }
136 });
137 OS.flush();
138 if (ErrorMessage.empty()) return true;
139 llvm::errs() << ErrorMessage;
140 return false;
141 }
142
TEST_F(ReplacementTest,FailAddReplacements)143 TEST_F(ReplacementTest, FailAddReplacements) {
144 Replacements Replaces;
145 Replacement Deletion("x.cc", 0, 10, "3");
146 auto Err = Replaces.add(Deletion);
147 EXPECT_TRUE(!Err);
148 llvm::consumeError(std::move(Err));
149
150 Replacement OverlappingReplacement("x.cc", 0, 2, "a");
151 Err = Replaces.add(OverlappingReplacement);
152 EXPECT_TRUE(checkReplacementError(std::move(Err),
153 replacement_error::overlap_conflict,
154 Deletion, OverlappingReplacement));
155
156 Replacement ContainedReplacement("x.cc", 2, 2, "a");
157 Err = Replaces.add(Replacement(ContainedReplacement));
158 EXPECT_TRUE(checkReplacementError(std::move(Err),
159 replacement_error::overlap_conflict,
160 Deletion, ContainedReplacement));
161
162 Replacement WrongPathReplacement("y.cc", 20, 2, "");
163 Err = Replaces.add(WrongPathReplacement);
164 EXPECT_TRUE(checkReplacementError(std::move(Err),
165 replacement_error::wrong_file_path,
166 Deletion, WrongPathReplacement));
167
168 EXPECT_EQ(1u, Replaces.size());
169 EXPECT_EQ(Deletion, *Replaces.begin());
170 }
171
TEST_F(ReplacementTest,DeletionInReplacements)172 TEST_F(ReplacementTest, DeletionInReplacements) {
173 Replacements Replaces;
174 Replacement R("x.cc", 0, 10, "3");
175 auto Err = Replaces.add(R);
176 EXPECT_TRUE(!Err);
177 llvm::consumeError(std::move(Err));
178 Err = Replaces.add(Replacement("x.cc", 0, 2, ""));
179 EXPECT_TRUE(!Err);
180 llvm::consumeError(std::move(Err));
181 Err = Replaces.add(Replacement("x.cc", 2, 2, ""));
182 EXPECT_TRUE(!Err);
183 llvm::consumeError(std::move(Err));
184 EXPECT_EQ(1u, Replaces.size());
185 EXPECT_EQ(R, *Replaces.begin());
186 }
187
TEST_F(ReplacementTest,OverlappingReplacements)188 TEST_F(ReplacementTest, OverlappingReplacements) {
189 Replacements Replaces;
190 auto Err = Replaces.add(Replacement("x.cc", 0, 3, "345"));
191 EXPECT_TRUE(!Err);
192 llvm::consumeError(std::move(Err));
193 Err = Replaces.add(Replacement("x.cc", 2, 3, "543"));
194 EXPECT_TRUE(!Err);
195 llvm::consumeError(std::move(Err));
196
197 EXPECT_EQ(1u, Replaces.size());
198 EXPECT_EQ(Replacement("x.cc", 0, 5, "34543"), *Replaces.begin());
199
200 Err = Replaces.add(Replacement("x.cc", 2, 1, "5"));
201 EXPECT_TRUE(!Err);
202 llvm::consumeError(std::move(Err));
203 EXPECT_EQ(1u, Replaces.size());
204 EXPECT_EQ(Replacement("x.cc", 0, 5, "34543"), *Replaces.begin());
205 }
206
TEST_F(ReplacementTest,AddAdjacentInsertionAndReplacement)207 TEST_F(ReplacementTest, AddAdjacentInsertionAndReplacement) {
208 Replacements Replaces;
209 // Test adding an insertion at the offset of an existing replacement.
210 auto Err = Replaces.add(Replacement("x.cc", 10, 3, "replace"));
211 EXPECT_TRUE(!Err);
212 llvm::consumeError(std::move(Err));
213 Err = Replaces.add(Replacement("x.cc", 10, 0, "insert"));
214 EXPECT_TRUE(!Err);
215 llvm::consumeError(std::move(Err));
216 EXPECT_EQ(Replaces.size(), 2u);
217
218 Replaces.clear();
219 // Test overlap with an existing insertion.
220 Err = Replaces.add(Replacement("x.cc", 10, 0, "insert"));
221 EXPECT_TRUE(!Err);
222 llvm::consumeError(std::move(Err));
223 Err = Replaces.add(Replacement("x.cc", 10, 3, "replace"));
224 EXPECT_TRUE(!Err);
225 llvm::consumeError(std::move(Err));
226 EXPECT_EQ(Replaces.size(), 2u);
227 }
228
TEST_F(ReplacementTest,MergeNewDeletions)229 TEST_F(ReplacementTest, MergeNewDeletions) {
230 Replacements Replaces;
231 Replacement ContainingReplacement("x.cc", 0, 10, "");
232 auto Err = Replaces.add(ContainingReplacement);
233 EXPECT_TRUE(!Err);
234 llvm::consumeError(std::move(Err));
235
236 Err = Replaces.add(Replacement("x.cc", 5, 3, ""));
237 EXPECT_TRUE(!Err);
238 llvm::consumeError(std::move(Err));
239
240 Err = Replaces.add(Replacement("x.cc", 0, 10, ""));
241 EXPECT_TRUE(!Err);
242 llvm::consumeError(std::move(Err));
243
244 Err = Replaces.add(Replacement("x.cc", 5, 5, ""));
245 EXPECT_TRUE(!Err);
246 llvm::consumeError(std::move(Err));
247
248 EXPECT_EQ(1u, Replaces.size());
249 EXPECT_EQ(*Replaces.begin(), ContainingReplacement);
250 }
251
TEST_F(ReplacementTest,MergeOverlappingButNotAdjacentReplacement)252 TEST_F(ReplacementTest, MergeOverlappingButNotAdjacentReplacement) {
253 Replacements Replaces;
254 auto Err = Replaces.add(Replacement("x.cc", 0, 2, ""));
255 EXPECT_TRUE(!Err);
256 llvm::consumeError(std::move(Err));
257
258 Err = Replaces.add(Replacement("x.cc", 5, 5, ""));
259 EXPECT_TRUE(!Err);
260 llvm::consumeError(std::move(Err));
261
262 Replacement After = Replacement("x.cc", 10, 5, "");
263 Err = Replaces.add(After);
264 EXPECT_TRUE(!Err);
265 llvm::consumeError(std::move(Err));
266
267 Replacement ContainingReplacement("x.cc", 0, 10, "");
268 Err = Replaces.add(ContainingReplacement);
269 EXPECT_TRUE(!Err);
270 llvm::consumeError(std::move(Err));
271
272 EXPECT_EQ(2u, Replaces.size());
273 EXPECT_EQ(*Replaces.begin(), ContainingReplacement);
274 EXPECT_EQ(*(++Replaces.begin()), After);
275 }
276
TEST_F(ReplacementTest,InsertionBeforeMergedDeletions)277 TEST_F(ReplacementTest, InsertionBeforeMergedDeletions) {
278 Replacements Replaces;
279
280 Replacement Insertion("x.cc", 0, 0, "123");
281 auto Err = Replaces.add(Insertion);
282 EXPECT_TRUE(!Err);
283 llvm::consumeError(std::move(Err));
284
285 Err = Replaces.add(Replacement("x.cc", 5, 5, ""));
286 EXPECT_TRUE(!Err);
287 llvm::consumeError(std::move(Err));
288
289 Replacement Deletion("x.cc", 0, 10, "");
290 Err = Replaces.add(Deletion);
291 EXPECT_TRUE(!Err);
292 llvm::consumeError(std::move(Err));
293
294 EXPECT_EQ(2u, Replaces.size());
295 EXPECT_EQ(*Replaces.begin(), Insertion);
296 EXPECT_EQ(*(++Replaces.begin()), Deletion);
297 }
298
TEST_F(ReplacementTest,MergeOverlappingDeletions)299 TEST_F(ReplacementTest, MergeOverlappingDeletions) {
300 Replacements Replaces;
301 auto Err = Replaces.add(Replacement("x.cc", 0, 2, ""));
302 EXPECT_TRUE(!Err);
303 llvm::consumeError(std::move(Err));
304
305 Err = Replaces.add(Replacement("x.cc", 0, 5, ""));
306 EXPECT_TRUE(!Err);
307 llvm::consumeError(std::move(Err));
308
309 EXPECT_EQ(1u, Replaces.size());
310 EXPECT_EQ(Replacement("x.cc", 0, 5, ""), *Replaces.begin());
311
312 Err = Replaces.add(Replacement("x.cc", 1, 5, ""));
313 EXPECT_TRUE(!Err);
314 llvm::consumeError(std::move(Err));
315 EXPECT_EQ(1u, Replaces.size());
316 EXPECT_EQ(Replacement("x.cc", 0, 6, ""), *Replaces.begin());
317 }
318
TEST_F(ReplacementTest,FailedMergeExistingDeletions)319 TEST_F(ReplacementTest, FailedMergeExistingDeletions) {
320 Replacements Replaces;
321 Replacement First("x.cc", 0, 2, "");
322 auto Err = Replaces.add(First);
323 EXPECT_TRUE(!Err);
324 llvm::consumeError(std::move(Err));
325
326 Replacement Second("x.cc", 5, 5, "");
327 Err = Replaces.add(Second);
328 EXPECT_TRUE(!Err);
329 llvm::consumeError(std::move(Err));
330
331 Err = Replaces.add(Replacement("x.cc", 1, 10, ""));
332 EXPECT_TRUE(!Err);
333 llvm::consumeError(std::move(Err));
334
335 EXPECT_EQ(1u, Replaces.size());
336 EXPECT_EQ(Replacement("x.cc", 0, 11, ""), *Replaces.begin());
337 }
338
TEST_F(ReplacementTest,FailAddRegression)339 TEST_F(ReplacementTest, FailAddRegression) {
340 Replacements Replaces;
341 // Create two replacements, where the second one is an insertion of the empty
342 // string exactly at the end of the first one.
343 auto Err = Replaces.add(Replacement("x.cc", 0, 10, "1"));
344 EXPECT_TRUE(!Err);
345 llvm::consumeError(std::move(Err));
346 Err = Replaces.add(Replacement("x.cc", 10, 0, ""));
347 EXPECT_TRUE(!Err);
348 llvm::consumeError(std::move(Err));
349
350 // Make sure we find the overlap with the first entry when inserting a
351 // replacement that ends exactly at the seam of the existing replacements.
352 Replacement OverlappingReplacement("x.cc", 5, 5, "fail");
353 Err = Replaces.add(OverlappingReplacement);
354 EXPECT_TRUE(checkReplacementError(std::move(Err),
355 replacement_error::overlap_conflict,
356 *Replaces.begin(), OverlappingReplacement));
357
358 Err = Replaces.add(Replacement("x.cc", 10, 0, ""));
359 EXPECT_TRUE(!Err);
360 llvm::consumeError(std::move(Err));
361 }
362
TEST_F(ReplacementTest,InsertAtOffsetOfReplacement)363 TEST_F(ReplacementTest, InsertAtOffsetOfReplacement) {
364 Replacements Replaces;
365 auto Err = Replaces.add(Replacement("x.cc", 10, 2, ""));
366 EXPECT_TRUE(!Err);
367 llvm::consumeError(std::move(Err));
368 Err = Replaces.add(Replacement("x.cc", 10, 0, ""));
369 EXPECT_TRUE(!Err);
370 llvm::consumeError(std::move(Err));
371 EXPECT_EQ(Replaces.size(), 2u);
372
373 Replaces.clear();
374 Err = Replaces.add(Replacement("x.cc", 10, 0, ""));
375 EXPECT_TRUE(!Err);
376 llvm::consumeError(std::move(Err));
377 Err = Replaces.add(Replacement("x.cc", 10, 2, ""));
378 EXPECT_TRUE(!Err);
379 llvm::consumeError(std::move(Err));
380 EXPECT_EQ(Replaces.size(), 2u);
381 }
382
TEST_F(ReplacementTest,AddInsertAtOtherInsertWhenOderIndependent)383 TEST_F(ReplacementTest, AddInsertAtOtherInsertWhenOderIndependent) {
384 Replacements Replaces;
385 auto Err = Replaces.add(Replacement("x.cc", 10, 0, "a"));
386 EXPECT_TRUE(!Err);
387 llvm::consumeError(std::move(Err));
388 Replacement ConflictInsertion("x.cc", 10, 0, "b");
389 Err = Replaces.add(ConflictInsertion);
390 EXPECT_TRUE(checkReplacementError(std::move(Err),
391 replacement_error::insert_conflict,
392 *Replaces.begin(), ConflictInsertion));
393
394 Replaces.clear();
395 Err = Replaces.add(Replacement("x.cc", 10, 0, "a"));
396 EXPECT_TRUE(!Err);
397 llvm::consumeError(std::move(Err));
398 Err = Replaces.add(Replacement("x.cc", 10, 0, "aa"));
399 EXPECT_TRUE(!Err);
400 llvm::consumeError(std::move(Err));
401 EXPECT_EQ(1u, Replaces.size());
402 EXPECT_EQ(Replacement("x.cc", 10, 0, "aaa"), *Replaces.begin());
403
404 Replaces.clear();
405 Err = Replaces.add(Replacement("x.cc", 10, 0, ""));
406 EXPECT_TRUE(!Err);
407 llvm::consumeError(std::move(Err));
408 Err = Replaces.add(Replacement("x.cc", 10, 3, ""));
409 EXPECT_TRUE(!Err);
410 llvm::consumeError(std::move(Err));
411 Err = Replaces.add(Replacement("x.cc", 10, 0, ""));
412 EXPECT_TRUE(!Err);
413 llvm::consumeError(std::move(Err));
414 EXPECT_EQ(2u, Replaces.size());
415 EXPECT_EQ(Replacement("x.cc", 10, 0, ""), *Replaces.begin());
416 EXPECT_EQ(Replacement("x.cc", 10, 3, ""), *std::next(Replaces.begin()));
417 }
418
TEST_F(ReplacementTest,InsertBetweenAdjacentReplacements)419 TEST_F(ReplacementTest, InsertBetweenAdjacentReplacements) {
420 Replacements Replaces;
421 auto Err = Replaces.add(Replacement("x.cc", 10, 5, "a"));
422 EXPECT_TRUE(!Err);
423 llvm::consumeError(std::move(Err));
424 Err = Replaces.add(Replacement("x.cc", 8, 2, "a"));
425 EXPECT_TRUE(!Err);
426 llvm::consumeError(std::move(Err));
427 Err = Replaces.add(Replacement("x.cc", 10, 0, "b"));
428 EXPECT_TRUE(!Err);
429 llvm::consumeError(std::move(Err));
430 }
431
TEST_F(ReplacementTest,CanApplyReplacements)432 TEST_F(ReplacementTest, CanApplyReplacements) {
433 FileID ID = Context.createInMemoryFile("input.cpp",
434 "line1\nline2\nline3\nline4");
435 Replacements Replaces =
436 toReplacements({Replacement(Context.Sources,
437 Context.getLocation(ID, 2, 1), 5, "replaced"),
438 Replacement(Context.Sources,
439 Context.getLocation(ID, 3, 1), 5, "other")});
440 EXPECT_TRUE(applyAllReplacements(Replaces, Context.Rewrite));
441 EXPECT_EQ("line1\nreplaced\nother\nline4", Context.getRewrittenText(ID));
442 }
443
444 // Verifies that replacement/deletion is applied before insertion at the same
445 // offset.
TEST_F(ReplacementTest,InsertAndDelete)446 TEST_F(ReplacementTest, InsertAndDelete) {
447 FileID ID = Context.createInMemoryFile("input.cpp",
448 "line1\nline2\nline3\nline4");
449 Replacements Replaces = toReplacements(
450 {Replacement(Context.Sources, Context.getLocation(ID, 2, 1), 6, ""),
451 Replacement(Context.Sources, Context.getLocation(ID, 2, 1), 0,
452 "other\n")});
453 EXPECT_TRUE(applyAllReplacements(Replaces, Context.Rewrite));
454 EXPECT_EQ("line1\nother\nline3\nline4", Context.getRewrittenText(ID));
455 }
456
TEST_F(ReplacementTest,AdjacentReplacements)457 TEST_F(ReplacementTest, AdjacentReplacements) {
458 FileID ID = Context.createInMemoryFile("input.cpp",
459 "ab");
460 Replacements Replaces = toReplacements(
461 {Replacement(Context.Sources, Context.getLocation(ID, 1, 1), 1, "x"),
462 Replacement(Context.Sources, Context.getLocation(ID, 1, 2), 1, "y")});
463 EXPECT_TRUE(applyAllReplacements(Replaces, Context.Rewrite));
464 EXPECT_EQ("xy", Context.getRewrittenText(ID));
465 }
466
TEST_F(ReplacementTest,AddDuplicateReplacements)467 TEST_F(ReplacementTest, AddDuplicateReplacements) {
468 FileID ID = Context.createInMemoryFile("input.cpp",
469 "line1\nline2\nline3\nline4");
470 auto Replaces = toReplacements({Replacement(
471 Context.Sources, Context.getLocation(ID, 2, 1), 5, "replaced")});
472
473 auto Err = Replaces.add(Replacement(
474 Context.Sources, Context.getLocation(ID, 2, 1), 5, "replaced"));
475 EXPECT_TRUE(!Err);
476 llvm::consumeError(std::move(Err));
477
478 Err = Replaces.add(Replacement(Context.Sources, Context.getLocation(ID, 2, 1),
479 5, "replaced"));
480 EXPECT_TRUE(!Err);
481 llvm::consumeError(std::move(Err));
482
483 EXPECT_TRUE(applyAllReplacements(Replaces, Context.Rewrite));
484 EXPECT_EQ("line1\nreplaced\nline3\nline4", Context.getRewrittenText(ID));
485 }
486
TEST_F(ReplacementTest,FailOrderDependentReplacements)487 TEST_F(ReplacementTest, FailOrderDependentReplacements) {
488 FileID ID = Context.createInMemoryFile("input.cpp",
489 "line1\nline2\nline3\nline4");
490 auto Replaces = toReplacements({Replacement(
491 Context.Sources, Context.getLocation(ID, 2, 1), 5, "other")});
492
493 Replacement ConflictReplacement(Context.Sources,
494 Context.getLocation(ID, 2, 1), 5, "rehto");
495 auto Err = Replaces.add(ConflictReplacement);
496 EXPECT_TRUE(checkReplacementError(std::move(Err),
497 replacement_error::overlap_conflict,
498 *Replaces.begin(), ConflictReplacement));
499
500 EXPECT_TRUE(applyAllReplacements(Replaces, Context.Rewrite));
501 EXPECT_EQ("line1\nother\nline3\nline4", Context.getRewrittenText(ID));
502 }
503
TEST_F(ReplacementTest,InvalidSourceLocationFailsApplyAll)504 TEST_F(ReplacementTest, InvalidSourceLocationFailsApplyAll) {
505 Replacements Replaces =
506 toReplacements({Replacement(Context.Sources, SourceLocation(), 5, "2")});
507
508 EXPECT_FALSE(applyAllReplacements(Replaces, Context.Rewrite));
509 }
510
TEST_F(ReplacementTest,MultipleFilesReplaceAndFormat)511 TEST_F(ReplacementTest, MultipleFilesReplaceAndFormat) {
512 // Column limit is 20.
513 std::string Code1 = "Long *a =\n"
514 " new Long();\n"
515 "long x = 1;";
516 std::string Expected1 = "auto a = new Long();\n"
517 "long x =\n"
518 " 12345678901;";
519 std::string Code2 = "int x = 123;\n"
520 "int y = 0;";
521 std::string Expected2 = "int x =\n"
522 " 1234567890123;\n"
523 "int y = 10;";
524 StringRef File1 = "format_1.cpp";
525 StringRef File2 = "format_2.cpp";
526 FileID ID1 = Context.createInMemoryFile(File1, Code1);
527 FileID ID2 = Context.createInMemoryFile(File2, Code2);
528
529 // Scrambled the order of replacements.
530 std::map<std::string, Replacements> FileToReplaces;
531 FileToReplaces[std::string(File1)] = toReplacements(
532 {tooling::Replacement(Context.Sources, Context.getLocation(ID1, 1, 1), 6,
533 "auto "),
534 tooling::Replacement(Context.Sources, Context.getLocation(ID1, 3, 10), 1,
535 "12345678901")});
536 FileToReplaces[std::string(File2)] = toReplacements(
537 {tooling::Replacement(Context.Sources, Context.getLocation(ID2, 1, 12), 0,
538 "4567890123"),
539 tooling::Replacement(Context.Sources, Context.getLocation(ID2, 2, 9), 1,
540 "10")});
541 EXPECT_TRUE(
542 formatAndApplyAllReplacements(FileToReplaces, Context.Rewrite,
543 "{BasedOnStyle: LLVM, ColumnLimit: 20}"));
544 EXPECT_EQ(Expected1, Context.getRewrittenText(ID1));
545 EXPECT_EQ(Expected2, Context.getRewrittenText(ID2));
546 }
547
TEST(ShiftedCodePositionTest,FindsNewCodePosition)548 TEST(ShiftedCodePositionTest, FindsNewCodePosition) {
549 Replacements Replaces =
550 toReplacements({Replacement("", 0, 1, ""), Replacement("", 4, 3, " ")});
551 // Assume ' int i;' is turned into 'int i;' and cursor is located at '|'.
552 EXPECT_EQ(0u, Replaces.getShiftedCodePosition(0)); // |int i;
553 EXPECT_EQ(0u, Replaces.getShiftedCodePosition(1)); // |nt i;
554 EXPECT_EQ(1u, Replaces.getShiftedCodePosition(2)); // i|t i;
555 EXPECT_EQ(2u, Replaces.getShiftedCodePosition(3)); // in| i;
556 EXPECT_EQ(3u, Replaces.getShiftedCodePosition(4)); // int| i;
557 EXPECT_EQ(3u, Replaces.getShiftedCodePosition(5)); // int | i;
558 EXPECT_EQ(3u, Replaces.getShiftedCodePosition(6)); // int |i;
559 EXPECT_EQ(4u, Replaces.getShiftedCodePosition(7)); // int |;
560 EXPECT_EQ(5u, Replaces.getShiftedCodePosition(8)); // int i|
561 }
562
TEST(ShiftedCodePositionTest,FindsNewCodePositionWithInserts)563 TEST(ShiftedCodePositionTest, FindsNewCodePositionWithInserts) {
564 Replacements Replaces = toReplacements({Replacement("", 4, 0, "\"\n\"")});
565 // Assume '"12345678"' is turned into '"1234"\n"5678"'.
566 EXPECT_EQ(3u, Replaces.getShiftedCodePosition(3)); // "123|5678"
567 EXPECT_EQ(7u, Replaces.getShiftedCodePosition(4)); // "1234|678"
568 EXPECT_EQ(8u, Replaces.getShiftedCodePosition(5)); // "12345|78"
569 }
570
TEST(ShiftedCodePositionTest,FindsNewCodePositionInReplacedText)571 TEST(ShiftedCodePositionTest, FindsNewCodePositionInReplacedText) {
572 // Replace the first four characters with "abcd".
573 auto Replaces = toReplacements({Replacement("", 0, 4, "abcd")});
574 for (unsigned i = 0; i < 3; ++i)
575 EXPECT_EQ(i, Replaces.getShiftedCodePosition(i));
576 }
577
TEST(ShiftedCodePositionTest,NoReplacementText)578 TEST(ShiftedCodePositionTest, NoReplacementText) {
579 Replacements Replaces = toReplacements({Replacement("", 0, 42, "")});
580 EXPECT_EQ(0u, Replaces.getShiftedCodePosition(0));
581 EXPECT_EQ(0u, Replaces.getShiftedCodePosition(39));
582 EXPECT_EQ(3u, Replaces.getShiftedCodePosition(45));
583 EXPECT_EQ(0u, Replaces.getShiftedCodePosition(42));
584 }
585
586 class FlushRewrittenFilesTest : public ::testing::Test {
587 public:
FlushRewrittenFilesTest()588 FlushRewrittenFilesTest() {}
589
~FlushRewrittenFilesTest()590 ~FlushRewrittenFilesTest() override {
591 for (llvm::StringMap<std::string>::iterator I = TemporaryFiles.begin(),
592 E = TemporaryFiles.end();
593 I != E; ++I) {
594 llvm::StringRef Name = I->second;
595 std::error_code EC = llvm::sys::fs::remove(Name);
596 (void)EC;
597 assert(!EC);
598 }
599 }
600
createFile(llvm::StringRef Name,llvm::StringRef Content)601 FileID createFile(llvm::StringRef Name, llvm::StringRef Content) {
602 SmallString<1024> Path;
603 int FD;
604 std::error_code EC = llvm::sys::fs::createTemporaryFile(Name, "", FD, Path);
605 assert(!EC);
606 (void)EC;
607
608 llvm::raw_fd_ostream OutStream(FD, true);
609 OutStream << Content;
610 OutStream.close();
611 auto File = Context.Files.getFile(Path);
612 assert(File);
613
614 StringRef Found =
615 TemporaryFiles.insert(std::make_pair(Name, std::string(Path.str())))
616 .first->second;
617 assert(Found == Path);
618 (void)Found;
619 return Context.Sources.createFileID(*File, SourceLocation(),
620 SrcMgr::C_User);
621 }
622
getFileContentFromDisk(llvm::StringRef Name)623 std::string getFileContentFromDisk(llvm::StringRef Name) {
624 std::string Path = TemporaryFiles.lookup(Name);
625 assert(!Path.empty());
626 // We need to read directly from the FileManager without relaying through
627 // a FileEntry, as otherwise we'd read through an already opened file
628 // descriptor, which might not see the changes made.
629 // FIXME: Figure out whether there is a way to get the SourceManger to
630 // reopen the file.
631 auto FileBuffer = Context.Files.getBufferForFile(Path);
632 return std::string((*FileBuffer)->getBuffer());
633 }
634
635 llvm::StringMap<std::string> TemporaryFiles;
636 RewriterTestContext Context;
637 };
638
TEST_F(FlushRewrittenFilesTest,StoresChangesOnDisk)639 TEST_F(FlushRewrittenFilesTest, StoresChangesOnDisk) {
640 FileID ID = createFile("input.cpp", "line1\nline2\nline3\nline4");
641 Replacements Replaces = toReplacements({Replacement(
642 Context.Sources, Context.getLocation(ID, 2, 1), 5, "replaced")});
643 EXPECT_TRUE(applyAllReplacements(Replaces, Context.Rewrite));
644 EXPECT_FALSE(Context.Rewrite.overwriteChangedFiles());
645 EXPECT_EQ("line1\nreplaced\nline3\nline4",
646 getFileContentFromDisk("input.cpp"));
647 }
648
649 namespace {
650 template <typename T>
651 class TestVisitor : public clang::RecursiveASTVisitor<T> {
652 public:
runOver(StringRef Code)653 bool runOver(StringRef Code) {
654 return runToolOnCode(std::make_unique<TestAction>(this), Code);
655 }
656
657 protected:
658 clang::SourceManager *SM;
659 clang::ASTContext *Context;
660
661 private:
662 class FindConsumer : public clang::ASTConsumer {
663 public:
FindConsumer(TestVisitor * Visitor)664 FindConsumer(TestVisitor *Visitor) : Visitor(Visitor) {}
665
HandleTranslationUnit(clang::ASTContext & Context)666 void HandleTranslationUnit(clang::ASTContext &Context) override {
667 Visitor->TraverseDecl(Context.getTranslationUnitDecl());
668 }
669
670 private:
671 TestVisitor *Visitor;
672 };
673
674 class TestAction : public clang::ASTFrontendAction {
675 public:
TestAction(TestVisitor * Visitor)676 TestAction(TestVisitor *Visitor) : Visitor(Visitor) {}
677
678 std::unique_ptr<clang::ASTConsumer>
CreateASTConsumer(clang::CompilerInstance & compiler,llvm::StringRef dummy)679 CreateASTConsumer(clang::CompilerInstance &compiler,
680 llvm::StringRef dummy) override {
681 Visitor->SM = &compiler.getSourceManager();
682 Visitor->Context = &compiler.getASTContext();
683 /// TestConsumer will be deleted by the framework calling us.
684 return std::make_unique<FindConsumer>(Visitor);
685 }
686
687 private:
688 TestVisitor *Visitor;
689 };
690 };
691 } // end namespace
692
expectReplacementAt(const Replacement & Replace,StringRef File,unsigned Offset,unsigned Length)693 void expectReplacementAt(const Replacement &Replace,
694 StringRef File, unsigned Offset, unsigned Length) {
695 ASSERT_TRUE(Replace.isApplicable());
696 EXPECT_EQ(File, Replace.getFilePath());
697 EXPECT_EQ(Offset, Replace.getOffset());
698 EXPECT_EQ(Length, Replace.getLength());
699 }
700
701 class ClassDeclXVisitor : public TestVisitor<ClassDeclXVisitor> {
702 public:
VisitCXXRecordDecl(CXXRecordDecl * Record)703 bool VisitCXXRecordDecl(CXXRecordDecl *Record) {
704 if (Record->getName() == "X") {
705 Replace = Replacement(*SM, Record, "");
706 }
707 return true;
708 }
709 Replacement Replace;
710 };
711
TEST(Replacement,CanBeConstructedFromNode)712 TEST(Replacement, CanBeConstructedFromNode) {
713 ClassDeclXVisitor ClassDeclX;
714 EXPECT_TRUE(ClassDeclX.runOver(" class X;"));
715 expectReplacementAt(ClassDeclX.Replace, "input.cc", 5, 7);
716 }
717
TEST(Replacement,ReplacesAtSpellingLocation)718 TEST(Replacement, ReplacesAtSpellingLocation) {
719 ClassDeclXVisitor ClassDeclX;
720 EXPECT_TRUE(ClassDeclX.runOver("#define A(Y) Y\nA(class X);"));
721 expectReplacementAt(ClassDeclX.Replace, "input.cc", 17, 7);
722 }
723
724 class CallToFVisitor : public TestVisitor<CallToFVisitor> {
725 public:
VisitCallExpr(CallExpr * Call)726 bool VisitCallExpr(CallExpr *Call) {
727 if (Call->getDirectCallee()->getName() == "F") {
728 Replace = Replacement(*SM, Call, "");
729 }
730 return true;
731 }
732 Replacement Replace;
733 };
734
TEST(Replacement,FunctionCall)735 TEST(Replacement, FunctionCall) {
736 CallToFVisitor CallToF;
737 EXPECT_TRUE(CallToF.runOver("void F(); void G() { F(); }"));
738 expectReplacementAt(CallToF.Replace, "input.cc", 21, 3);
739 }
740
TEST(Replacement,TemplatedFunctionCall)741 TEST(Replacement, TemplatedFunctionCall) {
742 CallToFVisitor CallToF;
743 EXPECT_TRUE(CallToF.runOver(
744 "template <typename T> void F(); void G() { F<int>(); }"));
745 expectReplacementAt(CallToF.Replace, "input.cc", 43, 8);
746 }
747
748 class NestedNameSpecifierAVisitor
749 : public TestVisitor<NestedNameSpecifierAVisitor> {
750 public:
TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNSLoc)751 bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNSLoc) {
752 if (NNSLoc.getNestedNameSpecifier()) {
753 if (const NamespaceDecl* NS = NNSLoc.getNestedNameSpecifier()->getAsNamespace()) {
754 if (NS->getName() == "a") {
755 Replace = Replacement(*SM, &NNSLoc, "", Context->getLangOpts());
756 }
757 }
758 }
759 return TestVisitor<NestedNameSpecifierAVisitor>::TraverseNestedNameSpecifierLoc(
760 NNSLoc);
761 }
762 Replacement Replace;
763 };
764
TEST(Replacement,ColonColon)765 TEST(Replacement, ColonColon) {
766 NestedNameSpecifierAVisitor VisitNNSA;
767 EXPECT_TRUE(VisitNNSA.runOver("namespace a { void f() { ::a::f(); } }"));
768 expectReplacementAt(VisitNNSA.Replace, "input.cc", 25, 5);
769 }
770
TEST(Range,overlaps)771 TEST(Range, overlaps) {
772 EXPECT_TRUE(Range(10, 10).overlapsWith(Range(0, 11)));
773 EXPECT_TRUE(Range(0, 11).overlapsWith(Range(10, 10)));
774 EXPECT_FALSE(Range(10, 10).overlapsWith(Range(0, 10)));
775 EXPECT_FALSE(Range(0, 10).overlapsWith(Range(10, 10)));
776 EXPECT_TRUE(Range(0, 10).overlapsWith(Range(2, 6)));
777 EXPECT_TRUE(Range(2, 6).overlapsWith(Range(0, 10)));
778 }
779
TEST(Range,contains)780 TEST(Range, contains) {
781 EXPECT_TRUE(Range(0, 10).contains(Range(0, 10)));
782 EXPECT_TRUE(Range(0, 10).contains(Range(2, 6)));
783 EXPECT_FALSE(Range(2, 6).contains(Range(0, 10)));
784 EXPECT_FALSE(Range(0, 10).contains(Range(0, 11)));
785 }
786
TEST(Range,CalculateRangesOfReplacements)787 TEST(Range, CalculateRangesOfReplacements) {
788 // Before: aaaabbbbbbz
789 // After : bbbbbbzzzzzzoooooooooooooooo
790 Replacements Replaces = toReplacements(
791 {Replacement("foo", 0, 4, ""), Replacement("foo", 10, 1, "zzzzzz"),
792 Replacement("foo", 11, 0, "oooooooooooooooo")});
793
794 std::vector<Range> Ranges = Replaces.getAffectedRanges();
795
796 EXPECT_EQ(2ul, Ranges.size());
797 EXPECT_TRUE(Ranges[0].getOffset() == 0);
798 EXPECT_TRUE(Ranges[0].getLength() == 0);
799 EXPECT_TRUE(Ranges[1].getOffset() == 6);
800 EXPECT_TRUE(Ranges[1].getLength() == 22);
801 }
802
TEST(Range,CalculateRangesOfInsertionAroundReplacement)803 TEST(Range, CalculateRangesOfInsertionAroundReplacement) {
804 Replacements Replaces = toReplacements(
805 {Replacement("foo", 0, 2, ""), Replacement("foo", 0, 0, "ba")});
806
807 std::vector<Range> Ranges = Replaces.getAffectedRanges();
808
809 EXPECT_EQ(1ul, Ranges.size());
810 EXPECT_EQ(0u, Ranges[0].getOffset());
811 EXPECT_EQ(2u, Ranges[0].getLength());
812 }
813
TEST(Range,RangesAfterEmptyReplacements)814 TEST(Range, RangesAfterEmptyReplacements) {
815 std::vector<Range> Ranges = {Range(5, 6), Range(10, 5)};
816 Replacements Replaces;
817 std::vector<Range> Expected = {Range(5, 10)};
818 EXPECT_EQ(Expected, calculateRangesAfterReplacements(Replaces, Ranges));
819 }
820
TEST(Range,RangesAfterReplacements)821 TEST(Range, RangesAfterReplacements) {
822 std::vector<Range> Ranges = {Range(5, 2), Range(10, 5)};
823 Replacements Replaces = toReplacements({Replacement("foo", 0, 2, "1234")});
824 std::vector<Range> Expected = {Range(0, 4), Range(7, 2), Range(12, 5)};
825 EXPECT_EQ(Expected, calculateRangesAfterReplacements(Replaces, Ranges));
826 }
827
TEST(Range,RangesBeforeReplacements)828 TEST(Range, RangesBeforeReplacements) {
829 std::vector<Range> Ranges = {Range(5, 2), Range(10, 5)};
830 Replacements Replaces = toReplacements({Replacement("foo", 20, 2, "1234")});
831 std::vector<Range> Expected = {Range(5, 2), Range(10, 5), Range(20, 4)};
832 EXPECT_EQ(Expected, calculateRangesAfterReplacements(Replaces, Ranges));
833 }
834
TEST(Range,NotAffectedByReplacements)835 TEST(Range, NotAffectedByReplacements) {
836 std::vector<Range> Ranges = {Range(0, 2), Range(5, 2), Range(10, 5)};
837 Replacements Replaces = toReplacements({Replacement("foo", 3, 2, "12"),
838 Replacement("foo", 12, 2, "12"),
839 Replacement("foo", 20, 5, "")});
840 std::vector<Range> Expected = {Range(0, 2), Range(3, 4), Range(10, 5),
841 Range(20, 0)};
842 EXPECT_EQ(Expected, calculateRangesAfterReplacements(Replaces, Ranges));
843 }
844
TEST(Range,RangesWithNonOverlappingReplacements)845 TEST(Range, RangesWithNonOverlappingReplacements) {
846 std::vector<Range> Ranges = {Range(0, 2), Range(5, 2), Range(10, 5)};
847 Replacements Replaces = toReplacements({Replacement("foo", 3, 1, ""),
848 Replacement("foo", 6, 1, "123"),
849 Replacement("foo", 20, 2, "12345")});
850 std::vector<Range> Expected = {Range(0, 2), Range(3, 0), Range(4, 4),
851 Range(11, 5), Range(21, 5)};
852 EXPECT_EQ(Expected, calculateRangesAfterReplacements(Replaces, Ranges));
853 }
854
TEST(Range,RangesWithOverlappingReplacements)855 TEST(Range, RangesWithOverlappingReplacements) {
856 std::vector<Range> Ranges = {Range(0, 2), Range(5, 2), Range(15, 5),
857 Range(30, 5)};
858 Replacements Replaces = toReplacements(
859 {Replacement("foo", 1, 3, ""), Replacement("foo", 6, 1, "123"),
860 Replacement("foo", 13, 3, "1"), Replacement("foo", 25, 15, "")});
861 std::vector<Range> Expected = {Range(0, 1), Range(2, 4), Range(12, 5),
862 Range(22, 0)};
863 EXPECT_EQ(Expected, calculateRangesAfterReplacements(Replaces, Ranges));
864 }
865
TEST(Range,MergeIntoOneRange)866 TEST(Range, MergeIntoOneRange) {
867 std::vector<Range> Ranges = {Range(0, 2), Range(5, 2), Range(15, 5)};
868 Replacements Replaces =
869 toReplacements({Replacement("foo", 1, 15, "1234567890")});
870 std::vector<Range> Expected = {Range(0, 15)};
871 EXPECT_EQ(Expected, calculateRangesAfterReplacements(Replaces, Ranges));
872 }
873
TEST(Range,ReplacementsStartingAtRangeOffsets)874 TEST(Range, ReplacementsStartingAtRangeOffsets) {
875 std::vector<Range> Ranges = {Range(0, 2), Range(5, 5), Range(15, 5)};
876 Replacements Replaces = toReplacements(
877 {Replacement("foo", 0, 2, "12"), Replacement("foo", 5, 1, "123"),
878 Replacement("foo", 7, 4, "12345"), Replacement("foo", 15, 10, "12")});
879 std::vector<Range> Expected = {Range(0, 2), Range(5, 9), Range(18, 2)};
880 EXPECT_EQ(Expected, calculateRangesAfterReplacements(Replaces, Ranges));
881 }
882
TEST(Range,ReplacementsEndingAtRangeEnds)883 TEST(Range, ReplacementsEndingAtRangeEnds) {
884 std::vector<Range> Ranges = {Range(0, 2), Range(5, 2), Range(15, 5)};
885 Replacements Replaces = toReplacements(
886 {Replacement("foo", 6, 1, "123"), Replacement("foo", 17, 3, "12")});
887 std::vector<Range> Expected = {Range(0, 2), Range(5, 4), Range(17, 4)};
888 EXPECT_EQ(Expected, calculateRangesAfterReplacements(Replaces, Ranges));
889 }
890
TEST(Range,AjacentReplacements)891 TEST(Range, AjacentReplacements) {
892 std::vector<Range> Ranges = {Range(0, 0), Range(15, 5)};
893 Replacements Replaces = toReplacements(
894 {Replacement("foo", 1, 2, "123"), Replacement("foo", 12, 3, "1234")});
895 std::vector<Range> Expected = {Range(0, 0), Range(1, 3), Range(13, 9)};
896 EXPECT_EQ(Expected, calculateRangesAfterReplacements(Replaces, Ranges));
897 }
898
TEST(Range,MergeRangesAfterReplacements)899 TEST(Range, MergeRangesAfterReplacements) {
900 std::vector<Range> Ranges = {Range(8, 0), Range(5, 2), Range(9, 0), Range(0, 1)};
901 Replacements Replaces = toReplacements({Replacement("foo", 1, 3, ""),
902 Replacement("foo", 7, 0, "12"),
903 Replacement("foo", 9, 2, "")});
904 std::vector<Range> Expected = {Range(0, 1), Range(2, 4), Range(7, 0),
905 Range(8, 0)};
906 EXPECT_EQ(Expected, calculateRangesAfterReplacements(Replaces, Ranges));
907 }
908
TEST(Range,ConflictingRangesBeforeReplacements)909 TEST(Range, ConflictingRangesBeforeReplacements) {
910 std::vector<Range> Ranges = {Range(8, 3), Range(5, 4), Range(9, 1)};
911 Replacements Replaces = toReplacements({Replacement("foo", 1, 3, "")});
912 std::vector<Range> Expected = {Range(1, 0), Range(2, 6)};
913 EXPECT_EQ(Expected, calculateRangesAfterReplacements(Replaces, Ranges));
914 }
915
916 class MergeReplacementsTest : public ::testing::Test {
917 protected:
mergeAndTestRewrite(StringRef Code,StringRef Intermediate,StringRef Result,const Replacements & First,const Replacements & Second)918 void mergeAndTestRewrite(StringRef Code, StringRef Intermediate,
919 StringRef Result, const Replacements &First,
920 const Replacements &Second) {
921 // These are mainly to verify the test itself and make it easier to read.
922 auto AfterFirst = applyAllReplacements(Code, First);
923 EXPECT_TRUE(static_cast<bool>(AfterFirst));
924 auto InSequenceRewrite = applyAllReplacements(*AfterFirst, Second);
925 EXPECT_TRUE(static_cast<bool>(InSequenceRewrite));
926 EXPECT_EQ(Intermediate, *AfterFirst);
927 EXPECT_EQ(Result, *InSequenceRewrite);
928
929 tooling::Replacements Merged = First.merge(Second);
930 auto MergedRewrite = applyAllReplacements(Code, Merged);
931 EXPECT_TRUE(static_cast<bool>(MergedRewrite));
932 EXPECT_EQ(*InSequenceRewrite, *MergedRewrite);
933 if (*InSequenceRewrite != *MergedRewrite)
934 for (tooling::Replacement M : Merged)
935 llvm::errs() << M.getOffset() << " " << M.getLength() << " "
936 << M.getReplacementText() << "\n";
937 }
mergeAndTestRewrite(StringRef Code,const Replacements & First,const Replacements & Second)938 void mergeAndTestRewrite(StringRef Code, const Replacements &First,
939 const Replacements &Second) {
940 auto AfterFirst = applyAllReplacements(Code, First);
941 EXPECT_TRUE(static_cast<bool>(AfterFirst));
942 auto InSequenceRewrite = applyAllReplacements(*AfterFirst, Second);
943 tooling::Replacements Merged = First.merge(Second);
944 auto MergedRewrite = applyAllReplacements(Code, Merged);
945 EXPECT_TRUE(static_cast<bool>(MergedRewrite));
946 EXPECT_EQ(*InSequenceRewrite, *MergedRewrite);
947 if (*InSequenceRewrite != *MergedRewrite)
948 for (tooling::Replacement M : Merged)
949 llvm::errs() << M.getOffset() << " " << M.getLength() << " "
950 << M.getReplacementText() << "\n";
951 }
952 };
953
TEST_F(MergeReplacementsTest,Offsets)954 TEST_F(MergeReplacementsTest, Offsets) {
955 mergeAndTestRewrite("aaa", "aabab", "cacabab",
956 toReplacements({{"", 2, 0, "b"}, {"", 3, 0, "b"}}),
957 toReplacements({{"", 0, 0, "c"}, {"", 1, 0, "c"}}));
958 mergeAndTestRewrite("aaa", "babaa", "babacac",
959 toReplacements({{"", 0, 0, "b"}, {"", 1, 0, "b"}}),
960 toReplacements({{"", 4, 0, "c"}, {"", 5, 0, "c"}}));
961 mergeAndTestRewrite("aaaa", "aaa", "aac", toReplacements({{"", 1, 1, ""}}),
962 toReplacements({{"", 2, 1, "c"}}));
963
964 mergeAndTestRewrite("aa", "bbabba", "bbabcba",
965 toReplacements({{"", 0, 0, "bb"}, {"", 1, 0, "bb"}}),
966 toReplacements({{"", 4, 0, "c"}}));
967 }
968
TEST_F(MergeReplacementsTest,Concatenations)969 TEST_F(MergeReplacementsTest, Concatenations) {
970 // Basic concatenations. It is important to merge these into a single
971 // replacement to ensure the correct order.
972 {
973 auto First = toReplacements({{"", 0, 0, "a"}});
974 auto Second = toReplacements({{"", 1, 0, "b"}});
975 EXPECT_EQ(toReplacements({{"", 0, 0, "ab"}}), First.merge(Second));
976 }
977 {
978 auto First = toReplacements({{"", 0, 0, "a"}});
979 auto Second = toReplacements({{"", 0, 0, "b"}});
980 EXPECT_EQ(toReplacements({{"", 0, 0, "ba"}}), First.merge(Second));
981 }
982 mergeAndTestRewrite("", "a", "ab", toReplacements({{"", 0, 0, "a"}}),
983 toReplacements({{"", 1, 0, "b"}}));
984 mergeAndTestRewrite("", "a", "ba", toReplacements({{"", 0, 0, "a"}}),
985 toReplacements({{"", 0, 0, "b"}}));
986 }
987
TEST_F(MergeReplacementsTest,NotChangingLengths)988 TEST_F(MergeReplacementsTest, NotChangingLengths) {
989 mergeAndTestRewrite("aaaa", "abba", "acca",
990 toReplacements({{"", 1, 2, "bb"}}),
991 toReplacements({{"", 1, 2, "cc"}}));
992 mergeAndTestRewrite("aaaa", "abba", "abcc",
993 toReplacements({{"", 1, 2, "bb"}}),
994 toReplacements({{"", 2, 2, "cc"}}));
995 mergeAndTestRewrite("aaaa", "abba", "ccba",
996 toReplacements({{"", 1, 2, "bb"}}),
997 toReplacements({{"", 0, 2, "cc"}}));
998 mergeAndTestRewrite("aaaaaa", "abbdda", "abccda",
999 toReplacements({{"", 1, 2, "bb"}, {"", 3, 2, "dd"}}),
1000 toReplacements({{"", 2, 2, "cc"}}));
1001 }
1002
TEST_F(MergeReplacementsTest,OverlappingRanges)1003 TEST_F(MergeReplacementsTest, OverlappingRanges) {
1004 mergeAndTestRewrite("aaa", "bbd", "bcbcd",
1005 toReplacements({{"", 0, 1, "bb"}, {"", 1, 2, "d"}}),
1006 toReplacements({{"", 1, 0, "c"}, {"", 2, 0, "c"}}));
1007
1008 mergeAndTestRewrite("aaaa", "aabbaa", "acccca",
1009 toReplacements({{"", 2, 0, "bb"}}),
1010 toReplacements({{"", 1, 4, "cccc"}}));
1011 mergeAndTestRewrite("aaaa", "aababa", "acccca",
1012 toReplacements({{"", 2, 0, "b"}, {"", 3, 0, "b"}}),
1013 toReplacements({{"", 1, 4, "cccc"}}));
1014 mergeAndTestRewrite("aaaaaa", "abbbba", "abba",
1015 toReplacements({{"", 1, 4, "bbbb"}}),
1016 toReplacements({{"", 2, 2, ""}}));
1017 mergeAndTestRewrite("aaaa", "aa", "cc",
1018 toReplacements({{"", 1, 1, ""}, {"", 2, 1, ""}}),
1019 toReplacements({{"", 0, 2, "cc"}}));
1020 mergeAndTestRewrite("aa", "abbba", "abcbcba",
1021 toReplacements({{"", 1, 0, "bbb"}}),
1022 toReplacements({{"", 2, 0, "c"}, {"", 3, 0, "c"}}));
1023
1024 mergeAndTestRewrite(
1025 "aaa", "abbab", "ccdd",
1026 toReplacements({{"", 0, 1, ""}, {"", 2, 0, "bb"}, {"", 3, 0, "b"}}),
1027 toReplacements({{"", 0, 2, "cc"}, {"", 2, 3, "dd"}}));
1028 mergeAndTestRewrite(
1029 "aa", "babbab", "ccdd",
1030 toReplacements({{"", 0, 0, "b"}, {"", 1, 0, "bb"}, {"", 2, 0, "b"}}),
1031 toReplacements({{"", 0, 3, "cc"}, {"", 3, 3, "dd"}}));
1032 }
1033
TEST(DeduplicateByFileTest,PathsWithDots)1034 TEST(DeduplicateByFileTest, PathsWithDots) {
1035 std::map<std::string, Replacements> FileToReplaces;
1036 llvm::IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem> VFS(
1037 new llvm::vfs::InMemoryFileSystem());
1038 FileManager FileMgr(FileSystemOptions(), VFS);
1039 #if !defined(_WIN32)
1040 StringRef Path1 = "a/b/.././c.h";
1041 StringRef Path2 = "a/c.h";
1042 #else
1043 StringRef Path1 = "a\\b\\..\\.\\c.h";
1044 StringRef Path2 = "a\\c.h";
1045 #endif
1046 EXPECT_TRUE(VFS->addFile(Path1, 0, llvm::MemoryBuffer::getMemBuffer("")));
1047 EXPECT_TRUE(VFS->addFile(Path2, 0, llvm::MemoryBuffer::getMemBuffer("")));
1048 FileToReplaces[std::string(Path1)] = Replacements();
1049 FileToReplaces[std::string(Path2)] = Replacements();
1050 FileToReplaces = groupReplacementsByFile(FileMgr, FileToReplaces);
1051 EXPECT_EQ(1u, FileToReplaces.size());
1052 EXPECT_EQ(Path1, FileToReplaces.begin()->first);
1053 }
1054
TEST(DeduplicateByFileTest,PathWithDotSlash)1055 TEST(DeduplicateByFileTest, PathWithDotSlash) {
1056 std::map<std::string, Replacements> FileToReplaces;
1057 llvm::IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem> VFS(
1058 new llvm::vfs::InMemoryFileSystem());
1059 FileManager FileMgr(FileSystemOptions(), VFS);
1060 #if !defined(_WIN32)
1061 StringRef Path1 = "./a/b/c.h";
1062 StringRef Path2 = "a/b/c.h";
1063 #else
1064 StringRef Path1 = ".\\a\\b\\c.h";
1065 StringRef Path2 = "a\\b\\c.h";
1066 #endif
1067 EXPECT_TRUE(VFS->addFile(Path1, 0, llvm::MemoryBuffer::getMemBuffer("")));
1068 EXPECT_TRUE(VFS->addFile(Path2, 0, llvm::MemoryBuffer::getMemBuffer("")));
1069 FileToReplaces[std::string(Path1)] = Replacements();
1070 FileToReplaces[std::string(Path2)] = Replacements();
1071 FileToReplaces = groupReplacementsByFile(FileMgr, FileToReplaces);
1072 EXPECT_EQ(1u, FileToReplaces.size());
1073 EXPECT_EQ(Path1, FileToReplaces.begin()->first);
1074 }
1075
TEST(DeduplicateByFileTest,NonExistingFilePath)1076 TEST(DeduplicateByFileTest, NonExistingFilePath) {
1077 std::map<std::string, Replacements> FileToReplaces;
1078 llvm::IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem> VFS(
1079 new llvm::vfs::InMemoryFileSystem());
1080 FileManager FileMgr(FileSystemOptions(), VFS);
1081 #if !defined(_WIN32)
1082 StringRef Path1 = "./a/b/c.h";
1083 StringRef Path2 = "a/b/c.h";
1084 #else
1085 StringRef Path1 = ".\\a\\b\\c.h";
1086 StringRef Path2 = "a\\b\\c.h";
1087 #endif
1088 FileToReplaces[std::string(Path1)] = Replacements();
1089 FileToReplaces[std::string(Path2)] = Replacements();
1090 FileToReplaces = groupReplacementsByFile(FileMgr, FileToReplaces);
1091 EXPECT_TRUE(FileToReplaces.empty());
1092 }
1093
1094 class AtomicChangeTest : public ::testing::Test {
1095 protected:
SetUp()1096 void SetUp() override {
1097 DefaultFileID = Context.createInMemoryFile("input.cpp", DefaultCode);
1098 DefaultLoc = Context.Sources.getLocForStartOfFile(DefaultFileID)
1099 .getLocWithOffset(20);
1100 assert(DefaultLoc.isValid() && "Default location must be valid.");
1101 }
1102
1103 RewriterTestContext Context;
1104 std::string DefaultCode = std::string(100, 'a');
1105 unsigned DefaultOffset = 20;
1106 SourceLocation DefaultLoc;
1107 FileID DefaultFileID;
1108 };
1109
TEST_F(AtomicChangeTest,AtomicChangeToYAML)1110 TEST_F(AtomicChangeTest, AtomicChangeToYAML) {
1111 AtomicChange Change(Context.Sources, DefaultLoc);
1112 llvm::Error Err =
1113 Change.insert(Context.Sources, DefaultLoc, "aa", /*InsertAfter=*/false);
1114 ASSERT_TRUE(!Err);
1115 Err = Change.insert(Context.Sources, DefaultLoc.getLocWithOffset(10), "bb",
1116 /*InsertAfter=*/false);
1117 ASSERT_TRUE(!Err);
1118 Change.addHeader("a.h");
1119 Change.removeHeader("b.h");
1120 std::string YAMLString = Change.toYAMLString();
1121
1122 // NOTE: If this test starts to fail for no obvious reason, check whitespace.
1123 ASSERT_STREQ("---\n"
1124 "Key: 'input.cpp:20'\n"
1125 "FilePath: input.cpp\n"
1126 "Error: ''\n"
1127 "InsertedHeaders:\n"
1128 " - a.h\n"
1129 "RemovedHeaders:\n"
1130 " - b.h\n"
1131 "Replacements:\n"
1132 " - FilePath: input.cpp\n"
1133 " Offset: 20\n"
1134 " Length: 0\n"
1135 " ReplacementText: aa\n"
1136 " - FilePath: input.cpp\n"
1137 " Offset: 30\n"
1138 " Length: 0\n"
1139 " ReplacementText: bb\n"
1140 "...\n",
1141 YAMLString.c_str());
1142 }
1143
TEST_F(AtomicChangeTest,YAMLToAtomicChange)1144 TEST_F(AtomicChangeTest, YAMLToAtomicChange) {
1145 std::string YamlContent = "---\n"
1146 "Key: 'input.cpp:20'\n"
1147 "FilePath: input.cpp\n"
1148 "Error: 'ok'\n"
1149 "InsertedHeaders:\n"
1150 " - a.h\n"
1151 "RemovedHeaders:\n"
1152 " - b.h\n"
1153 "Replacements:\n"
1154 " - FilePath: input.cpp\n"
1155 " Offset: 20\n"
1156 " Length: 0\n"
1157 " ReplacementText: aa\n"
1158 " - FilePath: input.cpp\n"
1159 " Offset: 30\n"
1160 " Length: 0\n"
1161 " ReplacementText: bb\n"
1162 "...\n";
1163 AtomicChange ExpectedChange(Context.Sources, DefaultLoc);
1164 llvm::Error Err = ExpectedChange.insert(Context.Sources, DefaultLoc, "aa",
1165 /*InsertAfter=*/false);
1166 ASSERT_TRUE(!Err);
1167 Err = ExpectedChange.insert(Context.Sources, DefaultLoc.getLocWithOffset(10),
1168 "bb", /*InsertAfter=*/false);
1169 ASSERT_TRUE(!Err);
1170
1171 ExpectedChange.addHeader("a.h");
1172 ExpectedChange.removeHeader("b.h");
1173 ExpectedChange.setError("ok");
1174
1175 AtomicChange ActualChange = AtomicChange::convertFromYAML(YamlContent);
1176 EXPECT_EQ(ExpectedChange.getKey(), ActualChange.getKey());
1177 EXPECT_EQ(ExpectedChange.getFilePath(), ActualChange.getFilePath());
1178 EXPECT_EQ(ExpectedChange.getError(), ActualChange.getError());
1179 EXPECT_EQ(ExpectedChange.getInsertedHeaders(),
1180 ActualChange.getInsertedHeaders());
1181 EXPECT_EQ(ExpectedChange.getRemovedHeaders(),
1182 ActualChange.getRemovedHeaders());
1183 EXPECT_EQ(ExpectedChange.getReplacements().size(),
1184 ActualChange.getReplacements().size());
1185 EXPECT_EQ(2u, ActualChange.getReplacements().size());
1186 EXPECT_EQ(*ExpectedChange.getReplacements().begin(),
1187 *ActualChange.getReplacements().begin());
1188 EXPECT_EQ(*(++ExpectedChange.getReplacements().begin()),
1189 *(++ActualChange.getReplacements().begin()));
1190 }
1191
TEST_F(AtomicChangeTest,CheckKeyAndKeyFile)1192 TEST_F(AtomicChangeTest, CheckKeyAndKeyFile) {
1193 AtomicChange Change(Context.Sources, DefaultLoc);
1194 EXPECT_EQ("input.cpp:20", Change.getKey());
1195 EXPECT_EQ("input.cpp", Change.getFilePath());
1196 }
1197
TEST_F(AtomicChangeTest,Replace)1198 TEST_F(AtomicChangeTest, Replace) {
1199 AtomicChange Change(Context.Sources, DefaultLoc);
1200 llvm::Error Err = Change.replace(Context.Sources, DefaultLoc, 2, "aa");
1201 ASSERT_TRUE(!Err);
1202 EXPECT_EQ(Change.getReplacements().size(), 1u);
1203 EXPECT_EQ(*Change.getReplacements().begin(),
1204 Replacement(Context.Sources, DefaultLoc, 2, "aa"));
1205
1206 // Add a new replacement that conflicts with the existing one.
1207 Err = Change.replace(Context.Sources, DefaultLoc, 3, "ab");
1208 EXPECT_TRUE((bool)Err);
1209 llvm::consumeError(std::move(Err));
1210 EXPECT_EQ(Change.getReplacements().size(), 1u);
1211 }
1212
TEST_F(AtomicChangeTest,ReplaceWithRange)1213 TEST_F(AtomicChangeTest, ReplaceWithRange) {
1214 AtomicChange Change(Context.Sources, DefaultLoc);
1215 SourceLocation End = DefaultLoc.getLocWithOffset(20);
1216 llvm::Error Err = Change.replace(
1217 Context.Sources, CharSourceRange::getCharRange(DefaultLoc, End), "aa");
1218 ASSERT_TRUE(!Err);
1219 EXPECT_EQ(Change.getReplacements().size(), 1u);
1220 EXPECT_EQ(*Change.getReplacements().begin(),
1221 Replacement(Context.Sources, DefaultLoc, 20, "aa"));
1222 }
1223
TEST_F(AtomicChangeTest,InsertBefore)1224 TEST_F(AtomicChangeTest, InsertBefore) {
1225 AtomicChange Change(Context.Sources, DefaultLoc);
1226 llvm::Error Err = Change.insert(Context.Sources, DefaultLoc, "aa");
1227 ASSERT_TRUE(!Err);
1228 EXPECT_EQ(Change.getReplacements().size(), 1u);
1229 EXPECT_EQ(*Change.getReplacements().begin(),
1230 Replacement(Context.Sources, DefaultLoc, 0, "aa"));
1231 Err = Change.insert(Context.Sources, DefaultLoc, "b", /*InsertAfter=*/false);
1232 ASSERT_TRUE(!Err);
1233 EXPECT_EQ(Change.getReplacements().size(), 1u);
1234 EXPECT_EQ(*Change.getReplacements().begin(),
1235 Replacement(Context.Sources, DefaultLoc, 0, "baa"));
1236 }
1237
TEST_F(AtomicChangeTest,InsertAfter)1238 TEST_F(AtomicChangeTest, InsertAfter) {
1239 AtomicChange Change(Context.Sources, DefaultLoc);
1240 llvm::Error Err = Change.insert(Context.Sources, DefaultLoc, "aa");
1241 ASSERT_TRUE(!Err);
1242 EXPECT_EQ(Change.getReplacements().size(), 1u);
1243 EXPECT_EQ(*Change.getReplacements().begin(),
1244 Replacement(Context.Sources, DefaultLoc, 0, "aa"));
1245 Err = Change.insert(Context.Sources, DefaultLoc, "b");
1246 ASSERT_TRUE(!Err);
1247 EXPECT_EQ(Change.getReplacements().size(), 1u);
1248 EXPECT_EQ(*Change.getReplacements().begin(),
1249 Replacement(Context.Sources, DefaultLoc, 0, "aab"));
1250 }
1251
TEST_F(AtomicChangeTest,InsertBeforeWithInvalidLocation)1252 TEST_F(AtomicChangeTest, InsertBeforeWithInvalidLocation) {
1253 AtomicChange Change(Context.Sources, DefaultLoc);
1254 llvm::Error Err =
1255 Change.insert(Context.Sources, DefaultLoc, "a", /*InsertAfter=*/false);
1256 ASSERT_TRUE(!Err);
1257
1258 // Invalid location.
1259 Err = Change.insert(Context.Sources, SourceLocation(), "a",
1260 /*InsertAfter=*/false);
1261 ASSERT_TRUE((bool)Err);
1262 EXPECT_TRUE(checkReplacementError(
1263 std::move(Err), replacement_error::wrong_file_path,
1264 Replacement(Context.Sources, DefaultLoc, 0, "a"),
1265 Replacement(Context.Sources, SourceLocation(), 0, "a")));
1266 }
1267
TEST_F(AtomicChangeTest,InsertBeforeToWrongFile)1268 TEST_F(AtomicChangeTest, InsertBeforeToWrongFile) {
1269 AtomicChange Change(Context.Sources, DefaultLoc);
1270 llvm::Error Err =
1271 Change.insert(Context.Sources, DefaultLoc, "a", /*InsertAfter=*/false);
1272 ASSERT_TRUE(!Err);
1273
1274 // Inserting at a different file.
1275 FileID NewID = Context.createInMemoryFile("extra.cpp", DefaultCode);
1276 SourceLocation NewLoc = Context.Sources.getLocForStartOfFile(NewID);
1277 Err = Change.insert(Context.Sources, NewLoc, "b", /*InsertAfter=*/false);
1278 ASSERT_TRUE((bool)Err);
1279 EXPECT_TRUE(
1280 checkReplacementError(std::move(Err), replacement_error::wrong_file_path,
1281 Replacement(Context.Sources, DefaultLoc, 0, "a"),
1282 Replacement(Context.Sources, NewLoc, 0, "b")));
1283 }
1284
TEST_F(AtomicChangeTest,InsertAfterWithInvalidLocation)1285 TEST_F(AtomicChangeTest, InsertAfterWithInvalidLocation) {
1286 AtomicChange Change(Context.Sources, DefaultLoc);
1287 llvm::Error Err = Change.insert(Context.Sources, DefaultLoc, "a");
1288 ASSERT_TRUE(!Err);
1289
1290 // Invalid location.
1291 Err = Change.insert(Context.Sources, SourceLocation(), "b");
1292 ASSERT_TRUE((bool)Err);
1293 EXPECT_TRUE(checkReplacementError(
1294 std::move(Err), replacement_error::wrong_file_path,
1295 Replacement(Context.Sources, DefaultLoc, 0, "a"),
1296 Replacement(Context.Sources, SourceLocation(), 0, "b")));
1297 }
1298
TEST_F(AtomicChangeTest,Metadata)1299 TEST_F(AtomicChangeTest, Metadata) {
1300 AtomicChange Change(Context.Sources, DefaultLoc, 17);
1301 const llvm::Any &Metadata = Change.getMetadata();
1302 ASSERT_TRUE(llvm::any_isa<int>(Metadata));
1303 EXPECT_EQ(llvm::any_cast<int>(Metadata), 17);
1304 }
1305
TEST_F(AtomicChangeTest,NoMetadata)1306 TEST_F(AtomicChangeTest, NoMetadata) {
1307 AtomicChange Change(Context.Sources, DefaultLoc);
1308 EXPECT_FALSE(Change.getMetadata().hasValue());
1309 }
1310
1311 class ApplyAtomicChangesTest : public ::testing::Test {
1312 protected:
ApplyAtomicChangesTest()1313 ApplyAtomicChangesTest() : FilePath("file.cc") {
1314 Spec.Cleanup = true;
1315 Spec.Format = ApplyChangesSpec::kAll;
1316 Spec.Style = format::getLLVMStyle();
1317 }
1318
~ApplyAtomicChangesTest()1319 ~ApplyAtomicChangesTest() override {}
1320
setInput(llvm::StringRef Input)1321 void setInput(llvm::StringRef Input) {
1322 Code = std::string(Input);
1323 FID = Context.createInMemoryFile(FilePath, Code);
1324 }
1325
getLoc(unsigned Offset) const1326 SourceLocation getLoc(unsigned Offset) const {
1327 return Context.Sources.getLocForStartOfFile(FID).getLocWithOffset(Offset);
1328 }
1329
replacementToAtomicChange(llvm::StringRef Key,unsigned Offset,unsigned Length,llvm::StringRef Text)1330 AtomicChange replacementToAtomicChange(llvm::StringRef Key, unsigned Offset,
1331 unsigned Length,
1332 llvm::StringRef Text) {
1333 AtomicChange Change(FilePath, Key);
1334 llvm::Error Err =
1335 Change.replace(Context.Sources, getLoc(Offset), Length, Text);
1336 EXPECT_FALSE(Err);
1337 return Change;
1338 }
1339
rewrite(bool FailureExpected=false)1340 std::string rewrite(bool FailureExpected = false) {
1341 llvm::Expected<std::string> ChangedCode =
1342 applyAtomicChanges(FilePath, Code, Changes, Spec);
1343 EXPECT_EQ(FailureExpected, !ChangedCode);
1344 if (!ChangedCode) {
1345 llvm::errs() << "Failed to apply changes: "
1346 << llvm::toString(ChangedCode.takeError()) << "\n";
1347 return "";
1348 }
1349 return *ChangedCode;
1350 }
1351
1352 RewriterTestContext Context;
1353 FileID FID;
1354 ApplyChangesSpec Spec;
1355 std::string Code;
1356 std::string FilePath;
1357 llvm::SmallVector<AtomicChange, 8> Changes;
1358 };
1359
TEST_F(ApplyAtomicChangesTest,BasicRefactoring)1360 TEST_F(ApplyAtomicChangesTest, BasicRefactoring) {
1361 setInput("int a;");
1362 AtomicChange Change(FilePath, "key1");
1363 Changes.push_back(replacementToAtomicChange("key1", 4, 1, "b"));
1364 EXPECT_EQ("int b;", rewrite());
1365 }
1366
TEST_F(ApplyAtomicChangesTest,SeveralRefactorings)1367 TEST_F(ApplyAtomicChangesTest, SeveralRefactorings) {
1368 setInput("int a;\n"
1369 "int b;");
1370 Changes.push_back(replacementToAtomicChange("key1", 0, 3, "float"));
1371 Changes.push_back(replacementToAtomicChange("key2", 4, 1, "f"));
1372 Changes.push_back(replacementToAtomicChange("key3", 11, 1, "g"));
1373 Changes.push_back(replacementToAtomicChange("key4", 7, 3, "float"));
1374 EXPECT_EQ("float f;\n"
1375 "float g;",
1376 rewrite());
1377 }
1378
TEST_F(ApplyAtomicChangesTest,IgnorePathsInRefactorings)1379 TEST_F(ApplyAtomicChangesTest, IgnorePathsInRefactorings) {
1380 setInput("int a;\n"
1381 "int b;");
1382 Changes.push_back(replacementToAtomicChange("key1", 4, 1, "aa"));
1383
1384 FileID ID = Context.createInMemoryFile("AnotherFile", "12345678912345");
1385 Changes.emplace_back("AnotherFile", "key2");
1386 auto Err = Changes.back().replace(
1387 Context.Sources,
1388 Context.Sources.getLocForStartOfFile(ID).getLocWithOffset(11), 1, "bb");
1389 ASSERT_TRUE(!Err);
1390 EXPECT_EQ("int aa;\n"
1391 "int bb;",
1392 rewrite());
1393 }
1394
TEST_F(ApplyAtomicChangesTest,AppliesDuplicateInsertions)1395 TEST_F(ApplyAtomicChangesTest, AppliesDuplicateInsertions) {
1396 setInput("int a;");
1397 Changes.push_back(replacementToAtomicChange("key1", 5, 0, "b"));
1398 Changes.push_back(replacementToAtomicChange("key2", 5, 0, "b"));
1399 EXPECT_EQ("int abb;", rewrite());
1400 }
1401
TEST_F(ApplyAtomicChangesTest,BailsOnOverlappingRefactorings)1402 TEST_F(ApplyAtomicChangesTest, BailsOnOverlappingRefactorings) {
1403 setInput("int a;");
1404 Changes.push_back(replacementToAtomicChange("key1", 0, 5, "float f"));
1405 Changes.push_back(replacementToAtomicChange("key2", 4, 1, "b"));
1406 EXPECT_EQ("", rewrite(/*FailureExpected=*/true));
1407 }
1408
TEST_F(ApplyAtomicChangesTest,BasicReformatting)1409 TEST_F(ApplyAtomicChangesTest, BasicReformatting) {
1410 setInput("int a;");
1411 Changes.push_back(replacementToAtomicChange("key1", 5, 1, "b"));
1412 EXPECT_EQ("int b;", rewrite());
1413 }
1414
TEST_F(ApplyAtomicChangesTest,OnlyFormatWhenViolateColumnLimits)1415 TEST_F(ApplyAtomicChangesTest, OnlyFormatWhenViolateColumnLimits) {
1416 Spec.Format = ApplyChangesSpec::kViolations;
1417 Spec.Style.ColumnLimit = 8;
1418 setInput("int a;\n"
1419 "int a;\n"
1420 "int aaaaaaaa;\n");
1421 Changes.push_back(replacementToAtomicChange("key1", 5, 1, "x"));
1422 Changes.push_back(replacementToAtomicChange("key2", 15, 1, "x"));
1423 Changes.push_back(replacementToAtomicChange("key3", 23, 8, "xx"));
1424 EXPECT_EQ("int x;\n"
1425 "int x;\n"
1426 "int xx;\n",
1427 rewrite());
1428 }
1429
TEST_F(ApplyAtomicChangesTest,LastLineViolateColumnLimits)1430 TEST_F(ApplyAtomicChangesTest, LastLineViolateColumnLimits) {
1431 Spec.Format = ApplyChangesSpec::kViolations;
1432 Spec.Style.ColumnLimit = 8;
1433 setInput("int a;\n"
1434 "int a;");
1435 Changes.push_back(replacementToAtomicChange("key1", 0, 1, "i"));
1436 Changes.push_back(replacementToAtomicChange("key2", 15, 2, "y;"));
1437 EXPECT_EQ("int a;\n"
1438 "int y;",
1439 rewrite());
1440 }
1441
TEST_F(ApplyAtomicChangesTest,LastLineWithNewlineViolateColumnLimits)1442 TEST_F(ApplyAtomicChangesTest, LastLineWithNewlineViolateColumnLimits) {
1443 Spec.Format = ApplyChangesSpec::kViolations;
1444 Spec.Style.ColumnLimit = 8;
1445 setInput("int a;\n"
1446 "int a;\n");
1447 Changes.push_back(replacementToAtomicChange("key1", 0, 1, "i"));
1448 Changes.push_back(replacementToAtomicChange("key2", 14, 3, "y;\n"));
1449 EXPECT_EQ("int a;\n"
1450 "int y;\n",
1451 rewrite());
1452 }
1453
TEST_F(ApplyAtomicChangesTest,Longer)1454 TEST_F(ApplyAtomicChangesTest, Longer) {
1455 setInput("int a;");
1456 Changes.push_back(replacementToAtomicChange("key1", 5, 1, "bbb"));
1457 EXPECT_EQ("int bbb;", rewrite());
1458 }
1459
TEST_F(ApplyAtomicChangesTest,Shorter)1460 TEST_F(ApplyAtomicChangesTest, Shorter) {
1461 setInput("int aaa;");
1462 Changes.push_back(replacementToAtomicChange("key1", 5, 3, "b"));
1463 EXPECT_EQ("int b;", rewrite());
1464 }
1465
TEST_F(ApplyAtomicChangesTest,OnlyFormatChangedLines)1466 TEST_F(ApplyAtomicChangesTest, OnlyFormatChangedLines) {
1467 setInput("int aaa;\n"
1468 "int a = b;\n"
1469 "int bbb;");
1470 Changes.push_back(replacementToAtomicChange("key1", 14, 1, "b"));
1471 EXPECT_EQ("int aaa;\n"
1472 "int b = b;\n"
1473 "int bbb;",
1474 rewrite());
1475 }
1476
TEST_F(ApplyAtomicChangesTest,DisableFormatting)1477 TEST_F(ApplyAtomicChangesTest, DisableFormatting) {
1478 Spec.Format = ApplyChangesSpec::kNone;
1479 setInput("int aaa;\n"
1480 "int a = b;\n"
1481 "int bbb;");
1482 Changes.push_back(replacementToAtomicChange("key1", 14, 1, "b"));
1483 EXPECT_EQ("int aaa;\n"
1484 "int b = b;\n"
1485 "int bbb;",
1486 rewrite());
1487 }
1488
TEST_F(ApplyAtomicChangesTest,AdaptsToLocalPointerStyle)1489 TEST_F(ApplyAtomicChangesTest, AdaptsToLocalPointerStyle) {
1490 setInput("int *aaa;\n"
1491 "int *bbb;");
1492 Changes.push_back(replacementToAtomicChange("key1", 0, 0, "int* ccc;\n"));
1493 EXPECT_EQ("int *ccc;\n"
1494 "int *aaa;\n"
1495 "int *bbb;",
1496 rewrite());
1497 }
1498
TEST_F(ApplyAtomicChangesTest,AcceptsSurroundingFormatting)1499 TEST_F(ApplyAtomicChangesTest, AcceptsSurroundingFormatting) {
1500 setInput(" int aaa;\n"
1501 " int a = b;\n"
1502 " int bbb;");
1503 Changes.push_back(replacementToAtomicChange("key1", 20, 1, "b"));
1504 EXPECT_EQ(" int aaa;\n"
1505 " int b = b;\n"
1506 " int bbb;",
1507 rewrite());
1508 }
1509
TEST_F(ApplyAtomicChangesTest,BailsOutOnConflictingChanges)1510 TEST_F(ApplyAtomicChangesTest, BailsOutOnConflictingChanges) {
1511 setInput("int c;\n"
1512 "int f;");
1513 // Insertions at the same offset are only allowed in the same AtomicChange.
1514 Changes.push_back(replacementToAtomicChange("key1", 0, 0, "int a;\n"));
1515 Changes.push_back(replacementToAtomicChange("key2", 0, 0, "int b;\n"));
1516 EXPECT_EQ("", rewrite(/*FailureExpected=*/true));
1517 }
1518
TEST_F(ApplyAtomicChangesTest,InsertsNewIncludesInRightOrder)1519 TEST_F(ApplyAtomicChangesTest, InsertsNewIncludesInRightOrder) {
1520 setInput("int a;");
1521 Changes.emplace_back(FilePath, "key1");
1522 Changes.back().addHeader("b");
1523 Changes.back().addHeader("c");
1524 Changes.emplace_back(FilePath, "key2");
1525 Changes.back().addHeader("a");
1526 EXPECT_EQ("#include \"a\"\n"
1527 "#include \"b\"\n"
1528 "#include \"c\"\n"
1529 "int a;",
1530 rewrite());
1531 }
1532
TEST_F(ApplyAtomicChangesTest,RemoveAndSortIncludes)1533 TEST_F(ApplyAtomicChangesTest, RemoveAndSortIncludes) {
1534 setInput("#include \"a\"\n"
1535 "#include \"b\"\n"
1536 "#include \"c\"\n"
1537 "\n"
1538 "int a;");
1539 Changes.emplace_back(FilePath, "key1");
1540 Changes.back().removeHeader("b");
1541 EXPECT_EQ("#include \"a\"\n"
1542 "#include \"c\"\n"
1543 "\n"
1544 "int a;",
1545 rewrite());
1546 }
TEST_F(ApplyAtomicChangesTest,InsertsSystemIncludes)1547 TEST_F(ApplyAtomicChangesTest, InsertsSystemIncludes) {
1548 setInput("#include <asys>\n"
1549 "#include <csys>\n"
1550 "\n"
1551 "#include \"a\"\n"
1552 "#include \"c\"\n");
1553 Changes.emplace_back(FilePath, "key1");
1554 Changes.back().addHeader("<asys>"); // Already exists.
1555 Changes.back().addHeader("<b>");
1556 Changes.back().addHeader("<d>");
1557 Changes.back().addHeader("\"b-already-escaped\"");
1558 EXPECT_EQ("#include <asys>\n"
1559 "#include <b>\n"
1560 "#include <csys>\n"
1561 "#include <d>\n"
1562 "\n"
1563 "#include \"a\"\n"
1564 "#include \"b-already-escaped\"\n"
1565 "#include \"c\"\n",
1566 rewrite());
1567 }
1568
TEST_F(ApplyAtomicChangesTest,RemoveSystemIncludes)1569 TEST_F(ApplyAtomicChangesTest, RemoveSystemIncludes) {
1570 setInput("#include <a>\n"
1571 "#include <b>\n"
1572 "\n"
1573 "#include \"c\""
1574 "\n"
1575 "int a;");
1576 Changes.emplace_back(FilePath, "key1");
1577 Changes.back().removeHeader("<a>");
1578 EXPECT_EQ("#include <b>\n"
1579 "\n"
1580 "#include \"c\""
1581 "\n"
1582 "int a;",
1583 rewrite());
1584 }
1585
TEST_F(ApplyAtomicChangesTest,DoNotFormatFollowingLinesIfSeparatedWithNewline)1586 TEST_F(ApplyAtomicChangesTest,
1587 DoNotFormatFollowingLinesIfSeparatedWithNewline) {
1588 setInput("#ifndef __H__\n"
1589 "#define __H__\n"
1590 "#include \"b\"\n"
1591 "\n"
1592 "int a;\n"
1593 "int a;\n"
1594 "int a;\n"
1595 "#endif // __H__\n");
1596 Changes.push_back(replacementToAtomicChange("key1",
1597 llvm::StringRef("#ifndef __H__\n"
1598 "#define __H__\n"
1599 "\n"
1600 "#include \"b\"\n"
1601 "int a;\n"
1602 "int ")
1603 .size(),
1604 1, "b"));
1605 Changes.back().addHeader("a");
1606 EXPECT_EQ("#ifndef __H__\n"
1607 "#define __H__\n"
1608 "#include \"a\"\n"
1609 "#include \"b\"\n"
1610 "\n"
1611 "int a;\n"
1612 "int b;\n"
1613 "int a;\n"
1614 "#endif // __H__\n",
1615 rewrite());
1616 }
1617
TEST_F(ApplyAtomicChangesTest,FormatsCorrectLineWhenHeaderIsRemoved)1618 TEST_F(ApplyAtomicChangesTest, FormatsCorrectLineWhenHeaderIsRemoved) {
1619 setInput("#include \"a\"\n"
1620 "\n"
1621 "int a;\n"
1622 "int a;\n"
1623 "int a;");
1624 Changes.push_back(replacementToAtomicChange("key1", 27, 1, "b"));
1625 Changes.back().removeHeader("a");
1626 EXPECT_EQ("\n"
1627 "int a;\n"
1628 "int b;\n"
1629 "int a;",
1630 rewrite());
1631 }
1632
TEST_F(ApplyAtomicChangesTest,CleansUpCtorInitializers)1633 TEST_F(ApplyAtomicChangesTest, CleansUpCtorInitializers) {
1634 setInput("A::A() : a(), b() {}\n"
1635 "A::A() : a(), b() {}\n"
1636 "A::A() : a(), b() {}\n"
1637 "A::A() : a()/**/, b() {}\n"
1638 "A::A() : a() ,// \n"
1639 " /**/ b() {}");
1640 Changes.emplace_back(FilePath, "key1");
1641 auto Err = Changes.back().replace(Context.Sources, getLoc(9), 3, "");
1642 ASSERT_TRUE(!Err);
1643 Err = Changes.back().replace(Context.Sources, getLoc(35), 3, "");
1644 ASSERT_TRUE(!Err);
1645 Err = Changes.back().replace(Context.Sources, getLoc(51), 3, "");
1646 ASSERT_TRUE(!Err);
1647 Err = Changes.back().replace(Context.Sources, getLoc(56), 3, "");
1648 ASSERT_TRUE(!Err);
1649 Err = Changes.back().replace(Context.Sources, getLoc(72), 3, "");
1650 ASSERT_TRUE(!Err);
1651 Err = Changes.back().replace(Context.Sources, getLoc(97), 3, "");
1652 ASSERT_TRUE(!Err);
1653 Err = Changes.back().replace(Context.Sources, getLoc(118), 3, "");
1654 ASSERT_TRUE(!Err);
1655 EXPECT_EQ("A::A() : b() {}\n"
1656 "A::A() : a() {}\n"
1657 "A::A() {}\n"
1658 "A::A() : b() {}\n"
1659 "A::A() {}",
1660 rewrite());
1661 }
1662
TEST_F(ApplyAtomicChangesTest,CleansUpParameterLists)1663 TEST_F(ApplyAtomicChangesTest, CleansUpParameterLists) {
1664 setInput("void f(int i, float f, string s);\n"
1665 "f(1, 2.0f, \"a\");\n"
1666 "g(1, 1);");
1667 Changes.emplace_back(FilePath, "key1");
1668 auto Err = Changes.back().replace(Context.Sources, getLoc(7), 5, "");
1669 ASSERT_TRUE(!Err);
1670 Err = Changes.back().replace(Context.Sources, getLoc(23), 8, "");
1671 ASSERT_TRUE(!Err);
1672 Err = Changes.back().replace(Context.Sources, getLoc(36), 1, "");
1673 ASSERT_TRUE(!Err);
1674 Err = Changes.back().replace(Context.Sources, getLoc(45), 3, "");
1675 ASSERT_TRUE(!Err);
1676 Err = Changes.back().replace(Context.Sources, getLoc(53), 1, "");
1677 ASSERT_TRUE(!Err);
1678 Err = Changes.back().replace(Context.Sources, getLoc(56), 1, "");
1679 ASSERT_TRUE(!Err);
1680 EXPECT_EQ("void f(float f);\n"
1681 "f(2.0f);\n"
1682 "g();",
1683 rewrite());
1684 }
1685
TEST_F(ApplyAtomicChangesTest,DisableCleanup)1686 TEST_F(ApplyAtomicChangesTest, DisableCleanup) {
1687 Spec.Cleanup = false;
1688 setInput("void f(int i, float f, string s);\n"
1689 "f(1, 2.0f, \"a\");\n"
1690 "g(1, 1);");
1691 Changes.emplace_back(FilePath, "key1");
1692 auto Err = Changes.back().replace(Context.Sources, getLoc(7), 5, "");
1693 ASSERT_TRUE(!Err);
1694 Err = Changes.back().replace(Context.Sources, getLoc(23), 8, "");
1695 ASSERT_TRUE(!Err);
1696 Err = Changes.back().replace(Context.Sources, getLoc(36), 1, "");
1697 ASSERT_TRUE(!Err);
1698 Err = Changes.back().replace(Context.Sources, getLoc(45), 3, "");
1699 ASSERT_TRUE(!Err);
1700 Err = Changes.back().replace(Context.Sources, getLoc(53), 1, "");
1701 ASSERT_TRUE(!Err);
1702 Err = Changes.back().replace(Context.Sources, getLoc(56), 1, "");
1703 ASSERT_TRUE(!Err);
1704 EXPECT_EQ("void f(, float f, );\n"
1705 "f(, 2.0f, );\n"
1706 "g(, );",
1707 rewrite());
1708 }
1709
TEST_F(ApplyAtomicChangesTest,EverythingDeleted)1710 TEST_F(ApplyAtomicChangesTest, EverythingDeleted) {
1711 setInput("int a;");
1712 Changes.push_back(replacementToAtomicChange("key1", 0, 6, ""));
1713 EXPECT_EQ("", rewrite());
1714 }
1715
TEST_F(ApplyAtomicChangesTest,DoesNotDeleteInserts)1716 TEST_F(ApplyAtomicChangesTest, DoesNotDeleteInserts) {
1717 setInput("int a;\n"
1718 "int b;");
1719 Changes.emplace_back(FilePath, "key1");
1720 auto Err = Changes.back().replace(Context.Sources, getLoc(4), 1, "");
1721 ASSERT_TRUE(!Err);
1722 Err = Changes.back().replace(Context.Sources, getLoc(4), 0, "b");
1723 ASSERT_TRUE(!Err);
1724 Err = Changes.back().replace(Context.Sources, getLoc(11), 0, "a");
1725 ASSERT_TRUE(!Err);
1726 Err = Changes.back().replace(Context.Sources, getLoc(11), 1, "");
1727 ASSERT_TRUE(!Err);
1728 EXPECT_EQ("int b;\n"
1729 "int a;",
1730 rewrite());
1731 }
1732
1733 } // end namespace tooling
1734 } // end namespace clang
1735