Debian Codegraph @

llvm-project/clang-tools-extra/clangd/unittests/RenameTests.cpp

raw
1 //===-- RenameTests.cpp -----------------------------------------*- C++ -*-===//
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 "Annotations.h"
10 #include "ClangdServer.h"
11 #include "SyncAPI.h"
12 #include "TestFS.h"
13 #include "TestTU.h"
14 #include "index/Ref.h"
15 #include "refactor/Rename.h"
16 #include "support/TestTracer.h"
17 #include "clang/Tooling/Core/Replacement.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/Support/MemoryBuffer.h"
20 #include <algorithm>
21 #include "gmock/gmock.h"
22 #include "gtest/gtest.h"
23
24 namespace clang {
25 namespace clangd {
26 namespace {
27
28 using testing::ElementsAre;
29 using testing::Eq;
30 using testing::IsEmpty;
31 using testing::Pair;
32 using testing::SizeIs;
33 using testing::UnorderedElementsAre;
34 using testing::UnorderedElementsAreArray;
35
36 llvm::IntrusiveRefCntPtr<llvm::vfs::OverlayFileSystem>
37 createOverlay(llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> Base,
38 llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> Overlay) {
39 auto OFS =
40 llvm::makeIntrusiveRefCnt<llvm::vfs::OverlayFileSystem>(std::move(Base));
41 OFS->pushOverlay(std::move(Overlay));
42 return OFS;
43 }
44
45 llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> getVFSFromAST(ParsedAST &AST) {
46 return &AST.getSourceManager().getFileManager().getVirtualFileSystem();
47 }
48
49 // Convert a Range to a Ref.
50 Ref refWithRange(const clangd::Range &Range, const std::string &URI) {
51 Ref Result;
52 Result.Kind = RefKind::Reference | RefKind::Spelled;
53 Result.Location.Start.setLine(Range.start.line);
54 Result.Location.Start.setColumn(Range.start.character);
55 Result.Location.End.setLine(Range.end.line);
56 Result.Location.End.setColumn(Range.end.character);
57 Result.Location.FileURI = URI.c_str();
58 return Result;
59 }
60
61 // Build a RefSlab from all marked ranges in the annotation. The ranges are
62 // assumed to associate with the given SymbolName.
63 std::unique_ptr<RefSlab> buildRefSlab(const Annotations &Code,
64 llvm::StringRef SymbolName,
65 llvm::StringRef Path) {
66 RefSlab::Builder Builder;
67 TestTU TU;
68 TU.HeaderCode = std::string(Code.code());
69 auto Symbols = TU.headerSymbols();
70 const auto &SymbolID = findSymbol(Symbols, SymbolName).ID;
71 std::string PathURI = URI::create(Path).toString();
72 for (const auto &Range : Code.ranges())
73 Builder.insert(SymbolID, refWithRange(Range, PathURI));
74
75 return std::make_unique<RefSlab>(std::move(Builder).build());
76 }
77
78 std::vector<
79 std::pair</*FilePath*/ std::string, /*CodeAfterRename*/ std::string>>
80 applyEdits(FileEdits FE) {
81 std::vector<std::pair<std::string, std::string>> Results;
82 for (auto &It : FE)
83 Results.emplace_back(
84 It.first().str(),
85 llvm::cantFail(tooling::applyAllReplacements(
86 It.getValue().InitialCode, It.getValue().Replacements)));
87 return Results;
88 }
89
90 // Generates an expected rename result by replacing all ranges in the given
91 // annotation with the NewName.
92 std::string expectedResult(Annotations Test, llvm::StringRef NewName) {
93 std::string Result;
94 unsigned NextChar = 0;
95 llvm::StringRef Code = Test.code();
96 for (const auto &R : Test.llvm::Annotations::ranges()) {
97 assert(R.Begin <= R.End && NextChar <= R.Begin);
98 Result += Code.substr(NextChar, R.Begin - NextChar);
99 Result += NewName;
100 NextChar = R.End;
101 }
102 Result += Code.substr(NextChar);
103 return Result;
104 }
105
106 TEST(RenameTest, WithinFileRename) {
107 // For each "^" this test moves cursor to its location and applies renaming
108 // while checking that all identifiers in [[]] ranges are also renamed.
109 llvm::StringRef Tests[] = {
110 // Function.
111 R"cpp(
112 void [[foo^]]() {
113 [[fo^o]]();
114 }
115 )cpp",
116
117 // Type.
118 R"cpp(
119 struct [[foo^]] {};
120 [[foo]] test() {
121 [[f^oo]] x;
122 return x;
123 }
124 )cpp",
125
126 // Local variable.
127 R"cpp(
128 void bar() {
129 if (auto [[^foo]] = 5) {
130 [[foo]] = 3;
131 }
132 }
133 )cpp",
134
135 // Class, its constructor and destructor.
136 R"cpp(
137 class [[F^oo]] {
138 [[F^oo]]();
139 ~[[F^oo]]();
140 [[F^oo]] *foo(int x);
141
142 [[F^oo]] *Ptr;
143 };
144 [[F^oo]]::[[Fo^o]]() {}
145 [[F^oo]]::~[[Fo^o]]() {}
146 [[F^oo]] *[[F^oo]]::foo(int x) { return Ptr; }
147 )cpp",
148
149 // Template class, its constructor and destructor.
150 R"cpp(
151 template <typename T>
152 class [[F^oo]] {
153 [[F^oo]]();
154 ~[[F^oo]]();
155 void f([[F^oo]] x);
156 };
157
158 template<typename T>
159 [[F^oo]]<T>::[[Fo^o]]() {}
160
161 template<typename T>
162 [[F^oo]]<T>::~[[Fo^o]]() {}
163 )cpp",
164
165 // Template class constructor.
166 R"cpp(
167 class [[F^oo]] {
168 template<typename T>
169 [[Fo^o]]();
170
171 template<typename T>
172 [[F^oo]](T t);
173 };
174
175 template<typename T>
176 [[F^oo]]::[[Fo^o]]() {}
177 )cpp",
178
179 // Class in template argument.
180 R"cpp(
181 class [[F^oo]] {};
182 template <typename T> void func();
183 template <typename T> class Baz {};
184 int main() {
185 func<[[F^oo]]>();
186 Baz<[[F^oo]]> obj;
187 return 0;
188 }
189 )cpp",
190
191 // Forward class declaration without definition.
192 R"cpp(
193 class [[F^oo]];
194 [[F^oo]] *f();
195 )cpp",
196
197 // Member function.
198 R"cpp(
199 struct X {
200 void [[F^oo]]() {}
201 void Baz() { [[F^oo]](); }
202 };
203 )cpp",
204
205 // Templated method instantiation.
206 R"cpp(
207 template<typename T>
208 class Foo {
209 public:
210 static T [[f^oo]]() {}
211 };
212
213 void bar() {
214 Foo<int>::[[f^oo]]();
215 }
216 )cpp",
217 R"cpp(
218 template<typename T>
219 class Foo {
220 public:
221 T [[f^oo]]() {}
222 };
223
224 void bar() {
225 Foo<int>().[[f^oo]]();
226 }
227 )cpp",
228
229 // Template class (partial) specializations.
230 R"cpp(
231 template <typename T>
232 class [[F^oo]] {};
233
234 template<>
235 class [[F^oo]]<bool> {};
236 template <typename T>
237 class [[F^oo]]<T*> {};
238
239 void test() {
240 [[F^oo]]<int> x;
241 [[F^oo]]<bool> y;
242 [[F^oo]]<int*> z;
243 }
244 )cpp",
245
246 // Incomplete class specializations
247 R"cpp(
248 template <typename T>
249 class [[Fo^o]] {};
250 void func([[F^oo]]<int>);
251 )cpp",
252
253 // Template class instantiations.
254 R"cpp(
255 template <typename T>
256 class [[F^oo]] {
257 public:
258 T foo(T arg, T& ref, T* ptr) {
259 T value;
260 int number = 42;
261 value = (T)number;
262 value = static_cast<T>(number);
263 return value;
264 }
265 static void foo(T value) {}
266 T member;
267 };
268
269 template <typename T>
270 void func() {
271 [[F^oo]]<T> obj;
272 obj.member = T();
273 [[Foo]]<T>::foo();
274 }
275
276 void test() {
277 [[F^oo]]<int> i;
278 i.member = 0;
279 [[F^oo]]<int>::foo(0);
280
281 [[F^oo]]<bool> b;
282 b.member = false;
283 [[F^oo]]<bool>::foo(false);
284 }
285 )cpp",
286
287 // Template class methods.
288 R"cpp(
289 template <typename T>
290 class A {
291 public:
292 void [[f^oo]]() {}
293 };
294
295 void func() {
296 A<int>().[[f^oo]]();
297 A<double>().[[f^oo]]();
298 A<float>().[[f^oo]]();
299 }
300 )cpp",
301
302 // Templated class specialization.
303 R"cpp(
304 template<typename T, typename U=bool>
305 class [[Foo^]];
306
307 template<typename T, typename U>
308 class [[Foo^]] {};
309
310 template<typename T=int, typename U>
311 class [[Foo^]];
312 )cpp",
313 R"cpp(
314 template<typename T=float, typename U=int>
315 class [[Foo^]];
316
317 template<typename T, typename U>
318 class [[Foo^]] {};
319 )cpp",
320
321 // Function template specialization.
322 R"cpp(
323 template<typename T=int, typename U=bool>
324 U [[foo^]]();
325
326 template<typename T, typename U>
327 U [[foo^]]() {};
328 )cpp",
329 R"cpp(
330 template<typename T, typename U>
331 U [[foo^]]() {};
332
333 template<typename T=int, typename U=bool>
334 U [[foo^]]();
335 )cpp",
336 R"cpp(
337 template<typename T=int, typename U=bool>
338 U [[foo^]]();
339
340 template<typename T, typename U>
341 U [[foo^]]();
342 )cpp",
343 R"cpp(
344 template <typename T>
345 void [[f^oo]](T t);
346
347 template <>
348 void [[f^oo]](int a);
349
350 void test() {
351 [[f^oo]]<double>(1);
352 }
353 )cpp",
354
355 // Variable template.
356 R"cpp(
357 template <typename T, int U>
358 bool [[F^oo]] = true;
359
360 // Explicit template specialization
361 template <>
362 bool [[F^oo]]<int, 0> = false;
363
364 // Partial template specialization
365 template <typename T>
366 bool [[F^oo]]<T, 1> = false;
367
368 void foo() {
369 // Ref to the explicit template specialization
370 [[F^oo]]<int, 0>;
371 // Ref to the primary template.
372 [[F^oo]]<double, 2>;
373 }
374 )cpp",
375
376 // Complicated class type.
377 R"cpp(
378 // Forward declaration.
379 class [[Fo^o]];
380 class Baz {
381 virtual int getValue() const = 0;
382 };
383
384 class [[F^oo]] : public Baz {
385 public:
386 [[F^oo]](int value = 0) : x(value) {}
387
388 [[F^oo]] &operator++(int);
389
390 bool operator<([[Foo]] const &rhs);
391 int getValue() const;
392 private:
393 int x;
394 };
395
396 void func() {
397 [[F^oo]] *Pointer = 0;
398 [[F^oo]] Variable = [[Foo]](10);
399 for ([[F^oo]] it; it < Variable; it++);
400 const [[F^oo]] *C = new [[Foo]]();
401 const_cast<[[F^oo]] *>(C)->getValue();
402 [[F^oo]] foo;
403 const Baz &BazReference = foo;
404 const Baz *BazPointer = &foo;
405 reinterpret_cast<const [[^Foo]] *>(BazPointer)->getValue();
406 static_cast<const [[^Foo]] &>(BazReference).getValue();
407 static_cast<const [[^Foo]] *>(BazPointer)->getValue();
408 }
409 )cpp",
410
411 // Static class member.
412 R"cpp(
413 struct Foo {
414 static Foo *[[Static^Member]];
415 };
416
417 Foo* Foo::[[Static^Member]] = nullptr;
418
419 void foo() {
420 Foo* Pointer = Foo::[[Static^Member]];
421 }
422 )cpp",
423
424 // Reference in lambda parameters.
425 R"cpp(
426 template <class T>
427 class function;
428 template <class R, class... ArgTypes>
429 class function<R(ArgTypes...)> {
430 public:
431 template <typename Functor>
432 function(Functor f) {}
433
434 function() {}
435
436 R operator()(ArgTypes...) const {}
437 };
438
439 namespace ns {
440 class [[Old]] {};
441 void f() {
442 function<void([[Old]])> func;
443 }
444 } // namespace ns
445 )cpp",
446
447 // Destructor explicit call.
448 R"cpp(
449 class [[F^oo]] {
450 public:
451 ~[[^Foo]]();
452 };
453
454 [[Foo^]]::~[[^Foo]]() {}
455
456 int main() {
457 [[Fo^o]] f;
458 f.~/*something*/[[^Foo]]();
459 f.~[[^Foo]]();
460 }
461 )cpp",
462
463 // Derived destructor explicit call.
464 R"cpp(
465 class [[Bas^e]] {};
466 class Derived : public [[Bas^e]] {};
467
468 int main() {
469 [[Bas^e]] *foo = new Derived();
470 foo->[[^Base]]::~[[^Base]]();
471 }
472 )cpp",
473
474 // CXXConstructor initializer list.
475 R"cpp(
476 class Baz {};
477 class Qux {
478 Baz [[F^oo]];
479 public:
480 Qux();
481 };
482 Qux::Qux() : [[F^oo]]() {}
483 )cpp",
484
485 // DeclRefExpr.
486 R"cpp(
487 class C {
488 public:
489 static int [[F^oo]];
490 };
491
492 int foo(int x);
493 #define MACRO(a) foo(a)
494
495 void func() {
496 C::[[F^oo]] = 1;
497 MACRO(C::[[Foo]]);
498 int y = C::[[F^oo]];
499 }
500 )cpp",
501
502 // Macros.
503 R"cpp(
504 // no rename inside macro body.
505 #define M1 foo
506 #define M2(x) x
507 int [[fo^o]]();
508 void boo(int);
509
510 void qoo() {
511 [[f^oo]]();
512 boo([[f^oo]]());
513 M1();
514 boo(M1());
515 M2([[f^oo]]());
516 M2(M1()); // foo is inside the nested macro body.
517 }
518 )cpp",
519
520 // MemberExpr in macros
521 R"cpp(
522 class Baz {
523 public:
524 int [[F^oo]];
525 };
526 int qux(int x);
527 #define MACRO(a) qux(a)
528
529 int main() {
530 Baz baz;
531 baz.[[F^oo]] = 1;
532 MACRO(baz.[[F^oo]]);
533 int y = baz.[[F^oo]];
534 }
535 )cpp",
536
537 // Fields in classes & partial and full specialiations.
538 R"cpp(
539 template<typename T>
540 struct Foo {
541 T [[Vari^able]] = 42;
542 };
543
544 void foo() {
545 Foo<int> f;
546 f.[[Varia^ble]] = 9000;
547 }
548 )cpp",
549 R"cpp(
550 template<typename T, typename U>
551 struct Foo {
552 T Variable[42];
553 U Another;
554
555 void bar() {}
556 };
557
558 template<typename T>
559 struct Foo<T, bool> {
560 T [[Var^iable]];
561 void bar() { ++[[Var^iable]]; }
562 };
563
564 void foo() {
565 Foo<unsigned, bool> f;
566 f.[[Var^iable]] = 9000;
567 }
568 )cpp",
569 R"cpp(
570 template<typename T, typename U>
571 struct Foo {
572 T Variable[42];
573 U Another;
574
575 void bar() {}
576 };
577
578 template<typename T>
579 struct Foo<T, bool> {
580 T Variable;
581 void bar() { ++Variable; }
582 };
583
584 template<>
585 struct Foo<unsigned, bool> {
586 unsigned [[Var^iable]];
587 void bar() { ++[[Var^iable]]; }
588 };
589
590 void foo() {
591 Foo<unsigned, bool> f;
592 f.[[Var^iable]] = 9000;
593 }
594 )cpp",
595 // Static fields.
596 R"cpp(
597 struct Foo {
598 static int [[Var^iable]];
599 };
600
601 int Foo::[[Var^iable]] = 42;
602
603 void foo() {
604 int LocalInt = Foo::[[Var^iable]];
605 }
606 )cpp",
607 R"cpp(
608 template<typename T>
609 struct Foo {
610 static T [[Var^iable]];
611 };
612
613 template <>
614 int Foo<int>::[[Var^iable]] = 42;
615
616 template <>
617 bool Foo<bool>::[[Var^iable]] = true;
618
619 void foo() {
620 int LocalInt = Foo<int>::[[Var^iable]];
621 bool LocalBool = Foo<bool>::[[Var^iable]];
622 }
623 )cpp",
624
625 // Template parameters.
626 R"cpp(
627 template <typename [[^T]]>
628 class Foo {
629 [[T^]] foo([[T^]] arg, [[T^]]& ref, [[^T]]* ptr) {
630 [[T]] value;
631 int number = 42;
632 value = ([[T^]])number;
633 value = static_cast<[[^T]]>(number);
634 return value;
635 }
636 static void foo([[T^]] value) {}
637 [[T^]] member;
638 };
639 )cpp",
640
641 // Typedef.
642 R"cpp(
643 namespace ns {
644 class basic_string {};
645 typedef basic_string [[s^tring]];
646 } // namespace ns
647
648 ns::[[s^tring]] foo();
649 )cpp",
650
651 // Variable.
652 R"cpp(
653 namespace A {
654 int [[F^oo]];
655 }
656 int Foo;
657 int Qux = Foo;
658 int Baz = A::[[^Foo]];
659 void fun() {
660 struct {
661 int Foo;
662 } b = {100};
663 int Foo = 100;
664 Baz = Foo;
665 {
666 extern int Foo;
667 Baz = Foo;
668 Foo = A::[[F^oo]] + Baz;
669 A::[[Fo^o]] = b.Foo;
670 }
671 Foo = b.Foo;
672 }
673 )cpp",
674
675 // Namespace alias.
676 R"cpp(
677 namespace a { namespace b { void foo(); } }
678 namespace [[^x]] = a::b;
679 void bar() {
680 [[x^]]::foo();
681 }
682 )cpp",
683
684 // Enum.
685 R"cpp(
686 enum [[C^olor]] { Red, Green, Blue };
687 void foo() {
688 [[C^olor]] c;
689 c = [[C^olor]]::Blue;
690 }
691 )cpp",
692
693 // Scoped enum.
694 R"cpp(
695 enum class [[K^ind]] { ABC };
696 void ff() {
697 [[K^ind]] s;
698 s = [[K^ind]]::ABC;
699 }
700 )cpp",
701
702 // Template class in template argument list.
703 R"cpp(
704 template<typename T>
705 class [[Fo^o]] {};
706 template <template<typename> class Z> struct Bar { };
707 template <> struct Bar<[[F^oo]]> {};
708 )cpp",
709
710 // Designated initializer.
711 R"cpp(
712 struct Bar {
713 int [[Fo^o]];
714 };
715 Bar bar { .[[^Foo]] = 42 };
716 )cpp",
717
718 // Nested designated initializer.
719 R"cpp(
720 struct Baz {
721 int Field;
722 };
723 struct Bar {
724 Baz [[Fo^o]];
725 };
726 // FIXME: v selecting here results in renaming Field.
727 Bar bar { .[[Foo]].Field = 42 };
728 )cpp",
729 R"cpp(
730 struct Baz {
731 int [[Fiel^d]];
732 };
733 struct Bar {
734 Baz Foo;
735 };
736 Bar bar { .Foo.[[^Field]] = 42 };
737 )cpp",
738
739 // Templated alias.
740 R"cpp(
741 template <typename T>
742 class X { T t; };
743
744 template <typename T>
745 using [[Fo^o]] = X<T>;
746
747 void bar() {
748 [[Fo^o]]<int> Bar;
749 }
750 )cpp",
751
752 // Alias.
753 R"cpp(
754 class X {};
755 using [[F^oo]] = X;
756
757 void bar() {
758 [[Fo^o]] Bar;
759 }
760 )cpp",
761
762 // Alias within a namespace.
763 R"cpp(
764 namespace x { class X {}; }
765 namespace ns {
766 using [[Fo^o]] = x::X;
767 }
768
769 void bar() {
770 ns::[[Fo^o]] Bar;
771 }
772 )cpp",
773
774 // Alias within macros.
775 R"cpp(
776 namespace x { class Old {}; }
777 namespace ns {
778 #define REF(alias) alias alias_var;
779
780 #define ALIAS(old) \
781 using old##Alias = x::old; \
782 REF(old##Alias);
783
784 ALIAS(Old);
785
786 [[Old^Alias]] old_alias;
787 }
788
789 void bar() {
790 ns::[[Old^Alias]] Bar;
791 }
792 )cpp",
793
794 // User defined conversion.
795 R"cpp(
796 class [[F^oo]] {
797 public:
798 [[F^oo]]() {}
799 };
800
801 class Baz {
802 public:
803 operator [[F^oo]]() {
804 return [[F^oo]]();
805 }
806 };
807
808 int main() {
809 Baz boo;
810 [[F^oo]] foo = static_cast<[[F^oo]]>(boo);
811 }
812 )cpp",
813
814 // ObjC, should not crash.
815 R"cpp(
816 @interface ObjC {
817 char [[da^ta]];
818 } @end
819 )cpp",
820
821 // Issue 170: Rename symbol introduced by UsingDecl
822 R"cpp(
823 namespace ns { void [[f^oo]](); }
824
825 using ns::[[f^oo]];
826
827 void f() {
828 [[f^oo]]();
829 auto p = &[[f^oo]];
830 }
831 )cpp",
832
833 // Issue 170: using decl that imports multiple overloads
834 // -> Only the overload under the cursor is renamed
835 R"cpp(
836 namespace ns { int [[^foo]](int); char foo(char); }
837 using ns::[[foo]];
838 void f() {
839 [[^foo]](42);
840 foo('x');
841 }
842 )cpp",
843 };
844 llvm::StringRef NewName = "NewName";
845 for (llvm::StringRef T : Tests) {
846 SCOPED_TRACE(T);
847 Annotations Code(T);
848 auto TU = TestTU::withCode(Code.code());
849 TU.ExtraArgs.push_back("-xobjective-c++");
850 auto AST = TU.build();
851 auto Index = TU.index();
852 for (const auto &RenamePos : Code.points()) {
853 auto RenameResult =
854 rename({RenamePos, NewName, AST, testPath(TU.Filename),
855 getVFSFromAST(AST), Index.get()});
856 ASSERT_TRUE(bool(RenameResult)) << RenameResult.takeError();
857 ASSERT_EQ(1u, RenameResult->GlobalChanges.size());
858 EXPECT_EQ(
859 applyEdits(std::move(RenameResult->GlobalChanges)).front().second,
860 expectedResult(Code, NewName));
861 }
862 }
863 }
864
865 TEST(RenameTest, Renameable) {
866 struct Case {
867 const char *Code;
868 const char* ErrorMessage; // null if no error
869 bool IsHeaderFile;
870 llvm::StringRef NewName = "MockName";
871 };
872 const bool HeaderFile = true;
873 Case Cases[] = {
874 {R"cpp(// allow -- function-local
875 void f(int [[Lo^cal]]) {
876 [[Local]] = 2;
877 }
878 )cpp",
879 nullptr, HeaderFile},
880
881 {R"cpp(// disallow -- symbol in anonymous namespace in header is not indexable.
882 namespace {
883 class Unin^dexable {};
884 }
885 )cpp",
886 "not eligible for indexing", HeaderFile},
887
888 {R"cpp(// disallow -- namespace symbol isn't supported
889 namespace n^s {}
890 )cpp",
891 "not a supported kind", HeaderFile},
892
893 {
894 R"cpp(
895 #define MACRO 1
896 int s = MAC^RO;
897 )cpp",
898 "not a supported kind", HeaderFile},
899
900 {
901 R"cpp(
902 struct X { X operator++(int); };
903 void f(X x) {x+^+;})cpp",
904 "no symbol", HeaderFile},
905
906 {R"cpp(// disallow rename on non-normal identifiers.
907 @interface Foo {}
908 -(int) fo^o:(int)x; // Token is an identifier, but declaration name isn't a simple identifier.
909 @end
910 )cpp",
911 "not a supported kind", HeaderFile},
912 {R"cpp(
913 void foo(int);
914 void foo(char);
915 template <typename T> void f(T t) {
916 fo^o(t);
917 })cpp",
918 "multiple symbols", !HeaderFile},
919
920 {R"cpp(// disallow rename on unrelated token.
921 cl^ass Foo {};
922 )cpp",
923 "no symbol", !HeaderFile},
924
925 {R"cpp(// disallow rename on unrelated token.
926 temp^late<typename T>
927 class Foo {};
928 )cpp",
929 "no symbol", !HeaderFile},
930
931 {R"cpp(
932 namespace {
933 int Conflict;
934 int Va^r;
935 }
936 )cpp",
937 "conflict", !HeaderFile, "Conflict"},
938
939 {R"cpp(
940 int Conflict;
941 int Va^r;
942 )cpp",
943 "conflict", !HeaderFile, "Conflict"},
944
945 {R"cpp(
946 class Foo {
947 int Conflict;
948 int Va^r;
949 };
950 )cpp",
951 "conflict", !HeaderFile, "Conflict"},
952
953 {R"cpp(
954 enum E {
955 Conflict,
956 Fo^o,
957 };
958 )cpp",
959 "conflict", !HeaderFile, "Conflict"},
960
961 {R"cpp(
962 int Conflict;
963 enum E { // transparent context.
964 F^oo,
965 };
966 )cpp",
967 "conflict", !HeaderFile, "Conflict"},
968
969 {R"cpp(
970 void func() {
971 bool Whatever;
972 int V^ar;
973 char Conflict;
974 }
975 )cpp",
976 "conflict", !HeaderFile, "Conflict"},
977
978 {R"cpp(
979 void func() {
980 if (int Conflict = 42) {
981 int V^ar;
982 }
983 }
984 )cpp",
985 "conflict", !HeaderFile, "Conflict"},
986
987 {R"cpp(
988 void func() {
989 if (int Conflict = 42) {
990 } else {
991 bool V^ar;
992 }
993 }
994 )cpp",
995 "conflict", !HeaderFile, "Conflict"},
996
997 {R"cpp(
998 void func() {
999 if (int V^ar = 42) {
1000 } else {
1001 bool Conflict;
1002 }
1003 }
1004 )cpp",
1005 "conflict", !HeaderFile, "Conflict"},
1006
1007 {R"cpp(
1008 void func() {
1009 while (int V^ar = 10) {
1010 bool Conflict = true;
1011 }
1012 }
1013 )cpp",
1014 "conflict", !HeaderFile, "Conflict"},
1015
1016 {R"cpp(
1017 void func() {
1018 for (int Something = 9000, Anything = 14, Conflict = 42; Anything > 9;
1019 ++Something) {
1020 int V^ar;
1021 }
1022 }
1023 )cpp",
1024 "conflict", !HeaderFile, "Conflict"},
1025
1026 {R"cpp(
1027 void func() {
1028 for (int V^ar = 14, Conflict = 42;;) {
1029 }
1030 }
1031 )cpp",
1032 "conflict", !HeaderFile, "Conflict"},
1033
1034 {R"cpp(
1035 void func(int Conflict) {
1036 bool V^ar;
1037 }
1038 )cpp",
1039 "conflict", !HeaderFile, "Conflict"},
1040
1041 {R"cpp(
1042 void func(int Var);
1043
1044 void func(int V^ar) {
1045 bool Conflict;
1046 }
1047 )cpp",
1048 "conflict", !HeaderFile, "Conflict"},
1049
1050 {R"cpp(// No conflict: only forward declaration's argument is renamed.
1051 void func(int [[V^ar]]);
1052
1053 void func(int Var) {
1054 bool Conflict;
1055 }
1056 )cpp",
1057 nullptr, !HeaderFile, "Conflict"},
1058
1059 {R"cpp(
1060 void func(int V^ar, int Conflict) {
1061 }
1062 )cpp",
1063 "conflict", !HeaderFile, "Conflict"},
1064
1065 {R"cpp(
1066 int V^ar;
1067 )cpp",
1068 "\"const\" is a keyword", !HeaderFile, "const"},
1069
1070 {R"cpp(// Trying to rename into the same name, SameName == SameName.
1071 void func() {
1072 int S^ameName;
1073 }
1074 )cpp",
1075 "new name is the same", !HeaderFile, "SameName"},
1076 {R"cpp(// Ensure it doesn't associate base specifier with base name.
1077 struct A {};
1078 struct B : priv^ate A {};
1079 )cpp",
1080 "Cannot rename symbol: there is no symbol at the given location", false},
1081 {R"cpp(// Ensure it doesn't associate base specifier with base name.
1082 /*error-ok*/
1083 struct A {
1084 A() : inva^lid(0) {}
1085 };
1086 )cpp",
1087 "no symbol", false},
1088
1089 {R"cpp(// FIXME we probably want to rename both overloads here,
1090 // but renaming currently assumes there's only a
1091 // single canonical declaration.
1092 namespace ns { int foo(int); char foo(char); }
1093 using ns::^foo;
1094 )cpp",
1095 "there are multiple symbols at the given location", !HeaderFile},
1096 };
1097
1098 for (const auto& Case : Cases) {
1099 SCOPED_TRACE(Case.Code);
1100 Annotations T(Case.Code);
1101 TestTU TU = TestTU::withCode(T.code());
1102 TU.ExtraArgs.push_back("-fno-delayed-template-parsing");
1103 if (Case.IsHeaderFile) {
1104 // We open the .h file as the main file.
1105 TU.Filename = "test.h";
1106 // Parsing the .h file as C++ include.
1107 TU.ExtraArgs.push_back("-xobjective-c++-header");
1108 }
1109 auto AST = TU.build();
1110 llvm::StringRef NewName = Case.NewName;
1111 auto Results = rename({T.point(), NewName, AST, testPath(TU.Filename)});
1112 bool WantRename = true;
1113 if (T.ranges().empty())
1114 WantRename = false;
1115 if (!WantRename) {
1116 assert(Case.ErrorMessage && "Error message must be set!");
1117 EXPECT_FALSE(Results)
1118 << "expected rename returned an error: " << T.code();
1119 auto ActualMessage = llvm::toString(Results.takeError());
1120 EXPECT_THAT(ActualMessage, testing::HasSubstr(Case.ErrorMessage));
1121 } else {
1122 EXPECT_TRUE(bool(Results)) << "rename returned an error: "
1123 << llvm::toString(Results.takeError());
1124 ASSERT_EQ(1u, Results->GlobalChanges.size());
1125 EXPECT_EQ(applyEdits(std::move(Results->GlobalChanges)).front().second,
1126 expectedResult(T, NewName));
1127 }
1128 }
1129 }
1130
1131 MATCHER_P(newText, T, "") { return arg.newText == T; }
1132
1133 TEST(RenameTest, IndexMergeMainFile) {
1134 Annotations Code("int ^x();");
1135 TestTU TU = TestTU::withCode(Code.code());
1136 TU.Filename = "main.cc";
1137 auto AST = TU.build();
1138
1139 auto Main = testPath("main.cc");
1140 auto InMemFS = llvm::makeIntrusiveRefCnt<llvm::vfs::InMemoryFileSystem>();
1141 InMemFS->addFile(testPath("main.cc"), 0,
1142 llvm::MemoryBuffer::getMemBuffer(Code.code()));
1143 InMemFS->addFile(testPath("other.cc"), 0,
1144 llvm::MemoryBuffer::getMemBuffer(Code.code()));
1145
1146 auto Rename = [&](const SymbolIndex *Idx) {
1147 RenameInputs Inputs{Code.point(),
1148 "xPrime",
1149 AST,
1150 Main,
1151 Idx ? createOverlay(getVFSFromAST(AST), InMemFS)
1152 : nullptr,
1153 Idx,
1154 RenameOptions()};
1155 auto Results = rename(Inputs);
1156 EXPECT_TRUE(bool(Results)) << llvm::toString(Results.takeError());
1157 return std::move(*Results);
1158 };
1159
1160 // We do not expect to see duplicated edits from AST vs index.
1161 auto Results = Rename(TU.index().get());
1162 EXPECT_THAT(Results.GlobalChanges.keys(), ElementsAre(Main));
1163 EXPECT_THAT(Results.GlobalChanges[Main].asTextEdits(),
1164 ElementsAre(newText("xPrime")));
1165
1166 // Sanity check: we do expect to see index results!
1167 TU.Filename = "other.cc";
1168 Results = Rename(TU.index().get());
1169 EXPECT_THAT(Results.GlobalChanges.keys(),
1170 UnorderedElementsAre(Main, testPath("other.cc")));
1171
1172 #ifdef CLANGD_PATH_CASE_INSENSITIVE
1173 // On case-insensitive systems, no duplicates if AST vs index case differs.
1174 // https://github.com/clangd/clangd/issues/665
1175 TU.Filename = "MAIN.CC";
1176 Results = Rename(TU.index().get());
1177 EXPECT_THAT(Results.GlobalChanges.keys(), ElementsAre(Main));
1178 EXPECT_THAT(Results.GlobalChanges[Main].asTextEdits(),
1179 ElementsAre(newText("xPrime")));
1180 #endif
1181 }
1182
1183 TEST(RenameTest, MainFileReferencesOnly) {
1184 // filter out references not from main file.
1185 llvm::StringRef Test =
1186 R"cpp(
1187 void test() {
1188 int [[fo^o]] = 1;
1189 // rename references not from main file are not included.
1190 #include "foo.inc"
1191 })cpp";
1192
1193 Annotations Code(Test);
1194 auto TU = TestTU::withCode(Code.code());
1195 TU.AdditionalFiles["foo.inc"] = R"cpp(
1196 #define Macro(X) X
1197 &Macro(foo);
1198 &foo;
1199 )cpp";
1200 auto AST = TU.build();
1201 llvm::StringRef NewName = "abcde";
1202
1203 auto RenameResult =
1204 rename({Code.point(), NewName, AST, testPath(TU.Filename)});
1205 ASSERT_TRUE(bool(RenameResult)) << RenameResult.takeError() << Code.point();
1206 ASSERT_EQ(1u, RenameResult->GlobalChanges.size());
1207 EXPECT_EQ(applyEdits(std::move(RenameResult->GlobalChanges)).front().second,
1208 expectedResult(Code, NewName));
1209 }
1210
1211 TEST(RenameTest, NoRenameOnSymbolsFromSystemHeaders) {
1212 llvm::StringRef Test =
1213 R"cpp(
1214 #include <cstdlib>
1215 #include <system>
1216
1217 SystemSym^bol abc;
1218
1219 void foo() { at^oi("9000"); }
1220 )cpp";
1221
1222 Annotations Code(Test);
1223 auto TU = TestTU::withCode(Code.code());
1224 TU.AdditionalFiles["system"] = R"cpp(
1225 class SystemSymbol {};
1226 )cpp";
1227 TU.AdditionalFiles["cstdlib"] = R"cpp(
1228 int atoi(const char *str);
1229 )cpp";
1230 TU.ExtraArgs = {"-isystem", testRoot()};
1231 auto AST = TU.build();
1232 llvm::StringRef NewName = "abcde";
1233
1234 // Clangd will not allow renaming symbols from the system headers for
1235 // correctness.
1236 for (auto &Point : Code.points()) {
1237 auto Results = rename({Point, NewName, AST, testPath(TU.Filename)});
1238 EXPECT_FALSE(Results) << "expected rename returned an error: "
1239 << Code.code();
1240 auto ActualMessage = llvm::toString(Results.takeError());
1241 EXPECT_THAT(ActualMessage, testing::HasSubstr("not a supported kind"));
1242 }
1243 }
1244
1245 TEST(RenameTest, ProtobufSymbolIsExcluded) {
1246 Annotations Code("Prot^obuf buf;");
1247 auto TU = TestTU::withCode(Code.code());
1248 TU.HeaderCode =
1249 R"cpp(// Generated by the protocol buffer compiler. DO NOT EDIT!
1250 class Protobuf {};
1251 )cpp";
1252 TU.HeaderFilename = "protobuf.pb.h";
1253 auto AST = TU.build();
1254 auto Results = rename({Code.point(), "newName", AST, testPath(TU.Filename)});
1255 EXPECT_FALSE(Results);
1256 EXPECT_THAT(llvm::toString(Results.takeError()),
1257 testing::HasSubstr("not a supported kind"));
1258 }
1259
1260 TEST(RenameTest, PrepareRename) {
1261 Annotations FooH("void func();");
1262 Annotations FooCC(R"cpp(
1263 #include "foo.h"
1264 void [[fu^nc]]() {}
1265 )cpp");
1266 std::string FooHPath = testPath("foo.h");
1267 std::string FooCCPath = testPath("foo.cc");
1268 MockFS FS;
1269 FS.Files[FooHPath] = std::string(FooH.code());
1270 FS.Files[FooCCPath] = std::string(FooCC.code());
1271
1272 auto ServerOpts = ClangdServer::optsForTest();
1273 ServerOpts.BuildDynamicSymbolIndex = true;
1274
1275 trace::TestTracer Tracer;
1276 MockCompilationDatabase CDB;
1277 ClangdServer Server(CDB, FS, ServerOpts);
1278 runAddDocument(Server, FooHPath, FooH.code());
1279 runAddDocument(Server, FooCCPath, FooCC.code());
1280
1281 auto Results = runPrepareRename(Server, FooCCPath, FooCC.point(),
1282 /*NewName=*/std::nullopt, {});
1283 // Verify that for multi-file rename, we only return main-file occurrences.
1284 ASSERT_TRUE(bool(Results)) << Results.takeError();
1285 // We don't know the result is complete in prepareRename (passing a nullptr
1286 // index internally), so GlobalChanges should be empty.
1287 EXPECT_TRUE(Results->GlobalChanges.empty());
1288 EXPECT_THAT(FooCC.ranges(),
1289 testing::UnorderedElementsAreArray(Results->LocalChanges));
1290
1291 // Name validation.
1292 Results = runPrepareRename(Server, FooCCPath, FooCC.point(),
1293 /*NewName=*/std::string("int"), {});
1294 EXPECT_FALSE(Results);
1295 EXPECT_THAT(llvm::toString(Results.takeError()),
1296 testing::HasSubstr("keyword"));
1297 EXPECT_THAT(Tracer.takeMetric("rename_name_invalid", "Keywords"),
1298 ElementsAre(1));
1299
1300 for (std::string BadIdent : {"foo!bar", "123foo", "😀@"}) {
1301 Results = runPrepareRename(Server, FooCCPath, FooCC.point(),
1302 /*NewName=*/BadIdent, {});
1303 EXPECT_FALSE(Results);
1304 EXPECT_THAT(llvm::toString(Results.takeError()),
1305 testing::HasSubstr("identifier"));
1306 EXPECT_THAT(Tracer.takeMetric("rename_name_invalid", "BadIdentifier"),
1307 ElementsAre(1));
1308 }
1309 for (std::string GoodIdent : {"fooBar", "__foo$", "😀"}) {
1310 Results = runPrepareRename(Server, FooCCPath, FooCC.point(),
1311 /*NewName=*/GoodIdent, {});
1312 EXPECT_TRUE(bool(Results));
1313 }
1314 }
1315
1316 TEST(CrossFileRenameTests, DirtyBuffer) {
1317 Annotations FooCode("class [[Foo]] {};");
1318 std::string FooPath = testPath("foo.cc");
1319 Annotations FooDirtyBuffer("class [[Foo]] {};\n// this is dirty buffer");
1320 Annotations BarCode("void [[Bar]]() {}");
1321 std::string BarPath = testPath("bar.cc");
1322 // Build the index, the index has "Foo" references from foo.cc and "Bar"
1323 // references from bar.cc.
1324 FileSymbols FSymbols(IndexContents::All);
1325 FSymbols.update(FooPath, nullptr, buildRefSlab(FooCode, "Foo", FooPath),
1326 nullptr, false);
1327 FSymbols.update(BarPath, nullptr, buildRefSlab(BarCode, "Bar", BarPath),
1328 nullptr, false);
1329 auto Index = FSymbols.buildIndex(IndexType::Light);
1330
1331 Annotations MainCode("class [[Fo^o]] {};");
1332 auto MainFilePath = testPath("main.cc");
1333 llvm::IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem> InMemFS =
1334 new llvm::vfs::InMemoryFileSystem;
1335 InMemFS->addFile(FooPath, 0,
1336 llvm::MemoryBuffer::getMemBuffer(FooDirtyBuffer.code()));
1337
1338 // Run rename on Foo, there is a dirty buffer for foo.cc, rename should
1339 // respect the dirty buffer.
1340 TestTU TU = TestTU::withCode(MainCode.code());
1341 auto AST = TU.build();
1342 llvm::StringRef NewName = "newName";
1343 auto Results =
1344 rename({MainCode.point(), NewName, AST, MainFilePath,
1345 createOverlay(getVFSFromAST(AST), InMemFS), Index.get()});
1346 ASSERT_TRUE(bool(Results)) << Results.takeError();
1347 EXPECT_THAT(
1348 applyEdits(std::move(Results->GlobalChanges)),
1349 UnorderedElementsAre(
1350 Pair(Eq(FooPath), Eq(expectedResult(FooDirtyBuffer, NewName))),
1351 Pair(Eq(MainFilePath), Eq(expectedResult(MainCode, NewName)))));
1352
1353 // Run rename on Bar, there is no dirty buffer for the affected file bar.cc,
1354 // so we should read file content from VFS.
1355 MainCode = Annotations("void [[Bar]]() { [[B^ar]](); }");
1356 TU = TestTU::withCode(MainCode.code());
1357 // Set a file "bar.cc" on disk.
1358 TU.AdditionalFiles["bar.cc"] = std::string(BarCode.code());
1359 AST = TU.build();
1360 Results = rename({MainCode.point(), NewName, AST, MainFilePath,
1361 createOverlay(getVFSFromAST(AST), InMemFS), Index.get()});
1362 ASSERT_TRUE(bool(Results)) << Results.takeError();
1363 EXPECT_THAT(
1364 applyEdits(std::move(Results->GlobalChanges)),
1365 UnorderedElementsAre(
1366 Pair(Eq(BarPath), Eq(expectedResult(BarCode, NewName))),
1367 Pair(Eq(MainFilePath), Eq(expectedResult(MainCode, NewName)))));
1368
1369 // Run rename on a pagination index which couldn't return all refs in one
1370 // request, we reject rename on this case.
1371 class PaginationIndex : public SymbolIndex {
1372 bool refs(const RefsRequest &Req,
1373 llvm::function_ref<void(const Ref &)> Callback) const override {
1374 return true; // has more references
1375 }
1376
1377 bool fuzzyFind(
1378 const FuzzyFindRequest &Req,
1379 llvm::function_ref<void(const Symbol &)> Callback) const override {
1380 return false;
1381 }
1382 void
1383 lookup(const LookupRequest &Req,
1384 llvm::function_ref<void(const Symbol &)> Callback) const override {}
1385
1386 void relations(const RelationsRequest &Req,
1387 llvm::function_ref<void(const SymbolID &, const Symbol &)>
1388 Callback) const override {}
1389
1390 llvm::unique_function<IndexContents(llvm::StringRef) const>
1391 indexedFiles() const override {
1392 return [](llvm::StringRef) { return IndexContents::None; };
1393 }
1394
1395 size_t estimateMemoryUsage() const override { return 0; }
1396 } PIndex;
1397 Results = rename({MainCode.point(), NewName, AST, MainFilePath,
1398 createOverlay(getVFSFromAST(AST), InMemFS), &PIndex});
1399 EXPECT_FALSE(Results);
1400 EXPECT_THAT(llvm::toString(Results.takeError()),
1401 testing::HasSubstr("too many occurrences"));
1402 }
1403
1404 TEST(CrossFileRenameTests, DeduplicateRefsFromIndex) {
1405 auto MainCode = Annotations("int [[^x]] = 2;");
1406 auto MainFilePath = testPath("main.cc");
1407 auto BarCode = Annotations("int [[x]];");
1408 auto BarPath = testPath("bar.cc");
1409 auto TU = TestTU::withCode(MainCode.code());
1410 // Set a file "bar.cc" on disk.
1411 TU.AdditionalFiles["bar.cc"] = std::string(BarCode.code());
1412 auto AST = TU.build();
1413 std::string BarPathURI = URI::create(BarPath).toString();
1414 Ref XRefInBarCC = refWithRange(BarCode.range(), BarPathURI);
1415 // The index will return duplicated refs, our code should be robost to handle
1416 // it.
1417 class DuplicatedXRefIndex : public SymbolIndex {
1418 public:
1419 DuplicatedXRefIndex(const Ref &ReturnedRef) : ReturnedRef(ReturnedRef) {}
1420 bool refs(const RefsRequest &Req,
1421 llvm::function_ref<void(const Ref &)> Callback) const override {
1422 // Return two duplicated refs.
1423 Callback(ReturnedRef);
1424 Callback(ReturnedRef);
1425 return false;
1426 }
1427
1428 bool fuzzyFind(const FuzzyFindRequest &,
1429 llvm::function_ref<void(const Symbol &)>) const override {
1430 return false;
1431 }
1432 void lookup(const LookupRequest &,
1433 llvm::function_ref<void(const Symbol &)>) const override {}
1434
1435 void relations(const RelationsRequest &,
1436 llvm::function_ref<void(const SymbolID &, const Symbol &)>)
1437 const override {}
1438
1439 llvm::unique_function<IndexContents(llvm::StringRef) const>
1440 indexedFiles() const override {
1441 return [](llvm::StringRef) { return IndexContents::None; };
1442 }
1443
1444 size_t estimateMemoryUsage() const override { return 0; }
1445 Ref ReturnedRef;
1446 } DIndex(XRefInBarCC);
1447 llvm::StringRef NewName = "newName";
1448 auto Results = rename({MainCode.point(), NewName, AST, MainFilePath,
1449 getVFSFromAST(AST), &DIndex});
1450 ASSERT_TRUE(bool(Results)) << Results.takeError();
1451 EXPECT_THAT(
1452 applyEdits(std::move(Results->GlobalChanges)),
1453 UnorderedElementsAre(
1454 Pair(Eq(BarPath), Eq(expectedResult(BarCode, NewName))),
1455 Pair(Eq(MainFilePath), Eq(expectedResult(MainCode, NewName)))));
1456 }
1457
1458 TEST(CrossFileRenameTests, WithUpToDateIndex) {
1459 MockCompilationDatabase CDB;
1460 CDB.ExtraClangFlags = {"-xc++"};
1461 // rename is runnning on all "^" points in FooH, and "[[]]" ranges are the
1462 // expected rename occurrences.
1463 struct Case {
1464 llvm::StringRef FooH;
1465 llvm::StringRef FooCC;
1466 } Cases[] = {
1467 {
1468 // classes.
1469 R"cpp(
1470 class [[Fo^o]] {
1471 [[Foo]]();
1472 ~[[Foo]]();
1473 };
1474 )cpp",
1475 R"cpp(
1476 #include "foo.h"
1477 [[Foo]]::[[Foo]]() {}
1478 [[Foo]]::~[[Foo]]() {}
1479
1480 void func() {
1481 [[Foo]] foo;
1482 }
1483 )cpp",
1484 },
1485 {
1486 // class templates.
1487 R"cpp(
1488 template <typename T>
1489 class [[Foo]] {};
1490 // FIXME: explicit template specializations are not supported due the
1491 // clangd index limitations.
1492 template <>
1493 class Foo<double> {};
1494 )cpp",
1495 R"cpp(
1496 #include "foo.h"
1497 void func() {
1498 [[F^oo]]<int> foo;
1499 }
1500 )cpp",
1501 },
1502 {
1503 // class methods.
1504 R"cpp(
1505 class Foo {
1506 void [[f^oo]]();
1507 };
1508 )cpp",
1509 R"cpp(
1510 #include "foo.h"
1511 void Foo::[[foo]]() {}
1512
1513 void func(Foo* p) {
1514 p->[[foo]]();
1515 }
1516 )cpp",
1517 },
1518 {
1519 // virtual methods.
1520 R"cpp(
1521 class Base {
1522 virtual void [[foo]]();
1523 };
1524 class Derived1 : public Base {
1525 void [[f^oo]]() override;
1526 };
1527 class NotDerived {
1528 void foo() {};
1529 }
1530 )cpp",
1531 R"cpp(
1532 #include "foo.h"
1533 void Base::[[foo]]() {}
1534 void Derived1::[[foo]]() {}
1535
1536 class Derived2 : public Derived1 {
1537 void [[foo]]() override {};
1538 };
1539
1540 void func(Base* b, Derived1* d1,
1541 Derived2* d2, NotDerived* nd) {
1542 b->[[foo]]();
1543 d1->[[foo]]();
1544 d2->[[foo]]();
1545 nd->foo();
1546 }
1547 )cpp",
1548 },
1549 {
1550 // virtual templated method
1551 R"cpp(
1552 template <typename> class Foo { virtual void [[m]](); };
1553 class Bar : Foo<int> { void [[^m]]() override; };
1554 )cpp",
1555 R"cpp(
1556 #include "foo.h"
1557
1558 template<typename T> void Foo<T>::[[m]]() {}
1559 // FIXME: not renamed as the index doesn't see this as an override of
1560 // the canonical Foo<T>::m().
1561 // https://github.com/clangd/clangd/issues/1325
1562 class Baz : Foo<float> { void m() override; };
1563 )cpp"
1564 },
1565 {
1566 // rename on constructor and destructor.
1567 R"cpp(
1568 class [[Foo]] {
1569 [[^Foo]]();
1570 ~[[Foo^]]();
1571 };
1572 )cpp",
1573 R"cpp(
1574 #include "foo.h"
1575 [[Foo]]::[[Foo]]() {}
1576 [[Foo]]::~[[Foo]]() {}
1577
1578 void func() {
1579 [[Foo]] foo;
1580 }
1581 )cpp",
1582 },
1583 {
1584 // functions.
1585 R"cpp(
1586 void [[f^oo]]();
1587 )cpp",
1588 R"cpp(
1589 #include "foo.h"
1590 void [[foo]]() {}
1591
1592 void func() {
1593 [[foo]]();
1594 }
1595 )cpp",
1596 },
1597 {
1598 // typedefs.
1599 R"cpp(
1600 typedef int [[IN^T]];
1601 [[INT]] foo();
1602 )cpp",
1603 R"cpp(
1604 #include "foo.h"
1605 [[INT]] foo() {}
1606 )cpp",
1607 },
1608 {
1609 // usings.
1610 R"cpp(
1611 using [[I^NT]] = int;
1612 [[INT]] foo();
1613 )cpp",
1614 R"cpp(
1615 #include "foo.h"
1616 [[INT]] foo() {}
1617 )cpp",
1618 },
1619 {
1620 // variables.
1621 R"cpp(
1622 static const int [[VA^R]] = 123;
1623 )cpp",
1624 R"cpp(
1625 #include "foo.h"
1626 int s = [[VAR]];
1627 )cpp",
1628 },
1629 {
1630 // scope enums.
1631 R"cpp(
1632 enum class [[K^ind]] { ABC };
1633 )cpp",
1634 R"cpp(
1635 #include "foo.h"
1636 [[Kind]] ff() {
1637 return [[Kind]]::ABC;
1638 }
1639 )cpp",
1640 },
1641 {
1642 // enum constants.
1643 R"cpp(
1644 enum class Kind { [[A^BC]] };
1645 )cpp",
1646 R"cpp(
1647 #include "foo.h"
1648 Kind ff() {
1649 return Kind::[[ABC]];
1650 }
1651 )cpp",
1652 },
1653 {
1654 // Implicit references in macro expansions.
1655 R"cpp(
1656 class [[Fo^o]] {};
1657 #define FooFoo Foo
1658 #define FOO Foo
1659 )cpp",
1660 R"cpp(
1661 #include "foo.h"
1662 void bar() {
1663 [[Foo]] x;
1664 FOO y;
1665 FooFoo z;
1666 }
1667 )cpp",
1668 },
1669 };
1670
1671 trace::TestTracer Tracer;
1672 for (const auto &T : Cases) {
1673 SCOPED_TRACE(T.FooH);
1674 Annotations FooH(T.FooH);
1675 Annotations FooCC(T.FooCC);
1676 std::string FooHPath = testPath("foo.h");
1677 std::string FooCCPath = testPath("foo.cc");
1678
1679 MockFS FS;
1680 FS.Files[FooHPath] = std::string(FooH.code());
1681 FS.Files[FooCCPath] = std::string(FooCC.code());
1682
1683 auto ServerOpts = ClangdServer::optsForTest();
1684 ServerOpts.BuildDynamicSymbolIndex = true;
1685 ClangdServer Server(CDB, FS, ServerOpts);
1686
1687 // Add all files to clangd server to make sure the dynamic index has been
1688 // built.
1689 runAddDocument(Server, FooHPath, FooH.code());
1690 runAddDocument(Server, FooCCPath, FooCC.code());
1691
1692 llvm::StringRef NewName = "NewName";
1693 for (const auto &RenamePos : FooH.points()) {
1694 EXPECT_THAT(Tracer.takeMetric("rename_files"), SizeIs(0));
1695 auto FileEditsList =
1696 llvm::cantFail(runRename(Server, FooHPath, RenamePos, NewName, {}));
1697 EXPECT_THAT(Tracer.takeMetric("rename_files"), ElementsAre(2));
1698 EXPECT_THAT(
1699 applyEdits(std::move(FileEditsList.GlobalChanges)),
1700 UnorderedElementsAre(
1701 Pair(Eq(FooHPath), Eq(expectedResult(T.FooH, NewName))),
1702 Pair(Eq(FooCCPath), Eq(expectedResult(T.FooCC, NewName)))));
1703 }
1704 }
1705 }
1706
1707 TEST(CrossFileRenameTests, CrossFileOnLocalSymbol) {
1708 // cross-file rename should work for function-local symbols, even there is no
1709 // index provided.
1710 Annotations Code("void f(int [[abc]]) { [[a^bc]] = 3; }");
1711 auto TU = TestTU::withCode(Code.code());
1712 auto Path = testPath(TU.Filename);
1713 auto AST = TU.build();
1714 llvm::StringRef NewName = "newName";
1715 auto Results = rename({Code.point(), NewName, AST, Path});
1716 ASSERT_TRUE(bool(Results)) << Results.takeError();
1717 EXPECT_THAT(
1718 applyEdits(std::move(Results->GlobalChanges)),
1719 UnorderedElementsAre(Pair(Eq(Path), Eq(expectedResult(Code, NewName)))));
1720 }
1721
1722 TEST(CrossFileRenameTests, BuildRenameEdits) {
1723 Annotations Code("[[😂]]");
1724 auto LSPRange = Code.range();
1725 llvm::StringRef FilePath = "/test/TestTU.cpp";
1726 llvm::StringRef NewName = "abc";
1727 auto Edit = buildRenameEdit(FilePath, Code.code(), {LSPRange}, NewName);
1728 ASSERT_TRUE(bool(Edit)) << Edit.takeError();
1729 ASSERT_EQ(1UL, Edit->Replacements.size());
1730 EXPECT_EQ(FilePath, Edit->Replacements.begin()->getFilePath());
1731 EXPECT_EQ(4UL, Edit->Replacements.begin()->getLength());
1732
1733 // Test invalid range.
1734 LSPRange.end = {10, 0}; // out of range
1735 Edit = buildRenameEdit(FilePath, Code.code(), {LSPRange}, NewName);
1736 EXPECT_FALSE(Edit);
1737 EXPECT_THAT(llvm::toString(Edit.takeError()),
1738 testing::HasSubstr("fail to convert"));
1739
1740 // Normal ascii characters.
1741 Annotations T(R"cpp(
1742 [[range]]
1743 [[range]]
1744 [[range]]
1745 )cpp");
1746 Edit = buildRenameEdit(FilePath, T.code(), T.ranges(), NewName);
1747 ASSERT_TRUE(bool(Edit)) << Edit.takeError();
1748 EXPECT_EQ(applyEdits(FileEdits{{T.code(), std::move(*Edit)}}).front().second,
1749 expectedResult(T, NewName));
1750 }
1751
1752 TEST(CrossFileRenameTests, adjustRenameRanges) {
1753 // Ranges in IndexedCode indicate the indexed occurrences;
1754 // ranges in DraftCode indicate the expected mapped result, empty indicates
1755 // we expect no matched result found.
1756 struct {
1757 llvm::StringRef IndexedCode;
1758 llvm::StringRef DraftCode;
1759 } Tests[] = {
1760 {
1761 // both line and column are changed, not a near miss.
1762 R"cpp(
1763 int [[x]] = 0;
1764 )cpp",
1765 R"cpp(
1766 // insert a line.
1767 double x = 0;
1768 )cpp",
1769 },
1770 {
1771 // subset.
1772 R"cpp(
1773 int [[x]] = 0;
1774 )cpp",
1775 R"cpp(
1776 int [[x]] = 0;
1777 {int x = 0; }
1778 )cpp",
1779 },
1780 {
1781 // shift columns.
1782 R"cpp(int [[x]] = 0; void foo(int x);)cpp",
1783 R"cpp(double [[x]] = 0; void foo(double x);)cpp",
1784 },
1785 {
1786 // shift lines.
1787 R"cpp(
1788 int [[x]] = 0;
1789 void foo(int x);
1790 )cpp",
1791 R"cpp(
1792 // insert a line.
1793 int [[x]] = 0;
1794 void foo(int x);
1795 )cpp",
1796 },
1797 };
1798 LangOptions LangOpts;
1799 LangOpts.CPlusPlus = true;
1800 for (const auto &T : Tests) {
1801 SCOPED_TRACE(T.DraftCode);
1802 Annotations Draft(T.DraftCode);
1803 auto ActualRanges = adjustRenameRanges(
1804 Draft.code(), "x", Annotations(T.IndexedCode).ranges(), LangOpts);
1805 if (!ActualRanges)
1806 EXPECT_THAT(Draft.ranges(), testing::IsEmpty());
1807 else
1808 EXPECT_THAT(Draft.ranges(),
1809 testing::UnorderedElementsAreArray(*ActualRanges));
1810 }
1811 }
1812
1813 TEST(RangePatchingHeuristic, GetMappedRanges) {
1814 // ^ in LexedCode marks the ranges we expect to be mapped; no ^ indicates
1815 // there are no mapped ranges.
1816 struct {
1817 llvm::StringRef IndexedCode;
1818 llvm::StringRef LexedCode;
1819 } Tests[] = {
1820 {
1821 // no lexed ranges.
1822 "[[]]",
1823 "",
1824 },
1825 {
1826 // both line and column are changed, not a near miss.
1827 R"([[]])",
1828 R"(
1829 [[]]
1830 )",
1831 },
1832 {
1833 // subset.
1834 "[[]]",
1835 "^[[]] [[]]"
1836 },
1837 {
1838 // shift columns.
1839 "[[]] [[]]",
1840 " ^[[]] ^[[]] [[]]"
1841 },
1842 {
1843 R"(
1844 [[]]
1845
1846 [[]] [[]]
1847 )",
1848 R"(
1849 // insert a line
1850 ^[[]]
1851
1852 ^[[]] ^[[]]
1853 )",
1854 },
1855 {
1856 R"(
1857 [[]]
1858
1859 [[]] [[]]
1860 )",
1861 R"(
1862 // insert a line
1863 ^[[]]
1864 ^[[]] ^[[]] // column is shifted.
1865 )",
1866 },
1867 {
1868 R"(
1869 [[]]
1870
1871 [[]] [[]]
1872 )",
1873 R"(
1874 // insert a line
1875 [[]]
1876
1877 [[]] [[]] // not mapped (both line and column are changed).
1878 )",
1879 },
1880 {
1881 R"(
1882 [[]]
1883 [[]]
1884
1885 [[]]
1886 [[]]
1887
1888 }
1889 )",
1890 R"(
1891 // insert a new line
1892 ^[[]]
1893 ^[[]]
1894 [[]] // additional range
1895 ^[[]]
1896 ^[[]]
1897 [[]] // additional range
1898 )",
1899 },
1900 {
1901 // non-distinct result (two best results), not a near miss
1902 R"(
1903 [[]]
1904 [[]]
1905 [[]]
1906 )",
1907 R"(
1908 [[]]
1909 [[]]
1910 [[]]
1911 [[]]
1912 )",
1913 }
1914 };
1915 for (const auto &T : Tests) {
1916 SCOPED_TRACE(T.IndexedCode);
1917 auto Lexed = Annotations(T.LexedCode);
1918 auto LexedRanges = Lexed.ranges();
1919 std::vector<Range> ExpectedMatches;
1920 for (auto P : Lexed.points()) {
1921 auto Match = llvm::find_if(LexedRanges, [&P](const Range& R) {
1922 return R.start == P;
1923 });
1924 ASSERT_NE(Match, LexedRanges.end());
1925 ExpectedMatches.push_back(*Match);
1926 }
1927
1928 auto Mapped =
1929 getMappedRanges(Annotations(T.IndexedCode).ranges(), LexedRanges);
1930 if (!Mapped)
1931 EXPECT_THAT(ExpectedMatches, IsEmpty());
1932 else
1933 EXPECT_THAT(ExpectedMatches, UnorderedElementsAreArray(*Mapped));
1934 }
1935 }
1936
1937 TEST(CrossFileRenameTests, adjustmentCost) {
1938 struct {
1939 llvm::StringRef RangeCode;
1940 size_t ExpectedCost;
1941 } Tests[] = {
1942 {
1943 R"(
1944 $idx[[]]$lex[[]] // diff: 0
1945 )",
1946 0,
1947 },
1948 {
1949 R"(
1950 $idx[[]]
1951 $lex[[]] // line diff: +1
1952 $idx[[]]
1953 $lex[[]] // line diff: +1
1954 $idx[[]]
1955 $lex[[]] // line diff: +1
1956
1957 $idx[[]]
1958
1959 $lex[[]] // line diff: +2
1960 )",
1961 1 + 1
1962 },
1963 {
1964 R"(
1965 $idx[[]]
1966 $lex[[]] // line diff: +1
1967 $idx[[]]
1968
1969 $lex[[]] // line diff: +2
1970 $idx[[]]
1971
1972
1973 $lex[[]] // line diff: +3
1974 )",
1975 1 + 1 + 1
1976 },
1977 {
1978 R"(
1979 $idx[[]]
1980
1981
1982 $lex[[]] // line diff: +3
1983 $idx[[]]
1984
1985 $lex[[]] // line diff: +2
1986 $idx[[]]
1987 $lex[[]] // line diff: +1
1988 )",
1989 3 + 1 + 1
1990 },
1991 {
1992 R"(
1993 $idx[[]]
1994 $lex[[]] // line diff: +1
1995 $lex[[]] // line diff: -2
1996
1997 $idx[[]]
1998 $idx[[]]
1999
2000
2001 $lex[[]] // line diff: +3
2002 )",
2003 1 + 3 + 5
2004 },
2005 {
2006 R"(
2007 $idx[[]] $lex[[]] // column diff: +1
2008 $idx[[]]$lex[[]] // diff: 0
2009 )",
2010 1
2011 },
2012 {
2013 R"(
2014 $idx[[]]
2015 $lex[[]] // diff: +1
2016 $idx[[]] $lex[[]] // column diff: +1
2017 $idx[[]]$lex[[]] // diff: 0
2018 )",
2019 1 + 1 + 1
2020 },
2021 {
2022 R"(
2023 $idx[[]] $lex[[]] // column diff: +1
2024 )",
2025 1
2026 },
2027 {
2028 R"(
2029 // column diffs: +1, +2, +3
2030 $idx[[]] $lex[[]] $idx[[]] $lex[[]] $idx[[]] $lex[[]]
2031 )",
2032 1 + 1 + 1,
2033 },
2034 };
2035 for (const auto &T : Tests) {
2036 SCOPED_TRACE(T.RangeCode);
2037 Annotations C(T.RangeCode);
2038 std::vector<size_t> MappedIndex;
2039 for (size_t I = 0; I < C.ranges("lex").size(); ++I)
2040 MappedIndex.push_back(I);
2041 EXPECT_EQ(renameRangeAdjustmentCost(C.ranges("idx"), C.ranges("lex"),
2042 MappedIndex),
2043 T.ExpectedCost);
2044 }
2045 }
2046
2047 } // namespace
2048 } // namespace clangd
2049 } // namespace clang