Debian Codegraph @

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

raw
1 //===-- XRefsTests.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 #include "Annotations.h"
9 #include "AST.h"
10 #include "ParsedAST.h"
11 #include "Protocol.h"
12 #include "SourceCode.h"
13 #include "SyncAPI.h"
14 #include "TestFS.h"
15 #include "TestTU.h"
16 #include "XRefs.h"
17 #include "index/MemIndex.h"
18 #include "clang/AST/Decl.h"
19 #include "clang/Basic/SourceLocation.h"
20 #include "llvm/ADT/StringRef.h"
21 #include "llvm/Support/Casting.h"
22 #include "llvm/Support/Error.h"
23 #include "llvm/Support/Path.h"
24 #include "llvm/Support/ScopedPrinter.h"
25 #include "gmock/gmock.h"
26 #include "gtest/gtest.h"
27 #include <optional>
28 #include <string>
29 #include <vector>
30
31 namespace clang {
32 namespace clangd {
33 namespace {
34
35 using ::testing::AllOf;
36 using ::testing::Contains;
37 using ::testing::ElementsAre;
38 using ::testing::Eq;
39 using ::testing::IsEmpty;
40 using ::testing::Matcher;
41 using ::testing::Not;
42 using ::testing::UnorderedElementsAre;
43 using ::testing::UnorderedElementsAreArray;
44 using ::testing::UnorderedPointwise;
45
46 MATCHER_P2(FileRange, File, Range, "") {
47 return Location{URIForFile::canonicalize(File, testRoot()), Range} == arg;
48 }
49 MATCHER(declRange, "") {
50 const LocatedSymbol &Sym = ::testing::get<0>(arg);
51 const Range &Range = ::testing::get<1>(arg);
52 return Sym.PreferredDeclaration.range == Range;
53 }
54
55 // Extracts ranges from an annotated example, and constructs a matcher for a
56 // highlight set. Ranges should be named $read/$write as appropriate.
57 Matcher<const std::vector<DocumentHighlight> &>
58 highlightsFrom(const Annotations &Test) {
59 std::vector<DocumentHighlight> Expected;
60 auto Add = [&](const Range &R, DocumentHighlightKind K) {
61 Expected.emplace_back();
62 Expected.back().range = R;
63 Expected.back().kind = K;
64 };
65 for (const auto &Range : Test.ranges())
66 Add(Range, DocumentHighlightKind::Text);
67 for (const auto &Range : Test.ranges("read"))
68 Add(Range, DocumentHighlightKind::Read);
69 for (const auto &Range : Test.ranges("write"))
70 Add(Range, DocumentHighlightKind::Write);
71 return UnorderedElementsAreArray(Expected);
72 }
73
74 TEST(HighlightsTest, All) {
75 const char *Tests[] = {
76 R"cpp(// Local variable
77 int main() {
78 int [[bonjour]];
79 $write[[^bonjour]] = 2;
80 int test1 = $read[[bonjour]];
81 }
82 )cpp",
83
84 R"cpp(// Struct
85 namespace ns1 {
86 struct [[MyClass]] {
87 static void foo([[MyClass]]*) {}
88 };
89 } // namespace ns1
90 int main() {
91 ns1::[[My^Class]]* Params;
92 }
93 )cpp",
94
95 R"cpp(// Function
96 int [[^foo]](int) {}
97 int main() {
98 [[foo]]([[foo]](42));
99 auto *X = &[[foo]];
100 }
101 )cpp",
102
103 R"cpp(// Function parameter in decl
104 void foo(int [[^bar]]);
105 )cpp",
106 R"cpp(// Not touching any identifiers.
107 struct Foo {
108 [[~]]Foo() {};
109 };
110 void foo() {
111 Foo f;
112 f.[[^~]]Foo();
113 }
114 )cpp",
115 R"cpp(// ObjC methods with split selectors.
116 @interface Foo
117 +(void) [[x]]:(int)a [[y]]:(int)b;
118 @end
119 @implementation Foo
120 +(void) [[x]]:(int)a [[y]]:(int)b {}
121 @end
122 void go() {
123 [Foo [[x]]:2 [[^y]]:4];
124 }
125 )cpp",
126 };
127 for (const char *Test : Tests) {
128 Annotations T(Test);
129 auto TU = TestTU::withCode(T.code());
130 TU.ExtraArgs.push_back("-xobjective-c++");
131 auto AST = TU.build();
132 EXPECT_THAT(findDocumentHighlights(AST, T.point()), highlightsFrom(T))
133 << Test;
134 }
135 }
136
137 TEST(HighlightsTest, ControlFlow) {
138 const char *Tests[] = {
139 R"cpp(
140 // Highlight same-function returns.
141 int fib(unsigned n) {
142 if (n <= 1) [[ret^urn]] 1;
143 [[return]] fib(n - 1) + fib(n - 2);
144
145 // Returns from other functions not highlighted.
146 auto Lambda = [] { return; };
147 class LocalClass { void x() { return; } };
148 }
149 )cpp",
150
151 R"cpp(
152 #define FAIL() return false
153 #define DO(x) { x; }
154 bool foo(int n) {
155 if (n < 0) [[FAIL]]();
156 DO([[re^turn]] true)
157 }
158 )cpp",
159
160 R"cpp(
161 // Highlight loop control flow
162 int magic() {
163 int counter = 0;
164 [[^for]] (char c : "fruit loops!") {
165 if (c == ' ') [[continue]];
166 counter += c;
167 if (c == '!') [[break]];
168 if (c == '?') [[return]] -1;
169 }
170 return counter;
171 }
172 )cpp",
173
174 R"cpp(
175 // Highlight loop and same-loop control flow
176 void nonsense() {
177 [[while]] (true) {
178 if (false) [[bre^ak]];
179 switch (1) break;
180 [[continue]];
181 }
182 }
183 )cpp",
184
185 R"cpp(
186 // Highlight switch for break (but not other breaks).
187 void describe(unsigned n) {
188 [[switch]](n) {
189 case 0:
190 break;
191 [[default]]:
192 [[^break]];
193 }
194 }
195 )cpp",
196
197 R"cpp(
198 // Highlight case and exits for switch-break (but not other cases).
199 void describe(unsigned n) {
200 [[switch]](n) {
201 case 0:
202 break;
203 [[case]] 1:
204 [[default]]:
205 [[return]];
206 [[^break]];
207 }
208 }
209 )cpp",
210
211 R"cpp(
212 // Highlight exits and switch for case
213 void describe(unsigned n) {
214 [[switch]](n) {
215 case 0:
216 break;
217 [[case]] 1:
218 [[d^efault]]:
219 [[return]];
220 [[break]];
221 }
222 }
223 )cpp",
224
225 R"cpp(
226 // Highlight nothing for switch.
227 void describe(unsigned n) {
228 s^witch(n) {
229 case 0:
230 break;
231 case 1:
232 default:
233 return;
234 break;
235 }
236 }
237 )cpp",
238
239 R"cpp(
240 // FIXME: match exception type against catch blocks
241 int catchy() {
242 try { // wrong: highlight try with matching catch
243 try { // correct: has no matching catch
244 [[thr^ow]] "oh no!";
245 } catch (int) { } // correct: catch doesn't match type
246 [[return]] -1; // correct: exits the matching catch
247 } catch (const char*) { } // wrong: highlight matching catch
248 [[return]] 42; // wrong: throw doesn't exit function
249 }
250 )cpp",
251
252 R"cpp(
253 // Loop highlights goto exiting the loop, but not jumping within it.
254 void jumpy() {
255 [[wh^ile]](1) {
256 up:
257 if (0) [[goto]] out;
258 goto up;
259 }
260 out: return;
261 }
262 )cpp",
263 };
264 for (const char *Test : Tests) {
265 Annotations T(Test);
266 auto TU = TestTU::withCode(T.code());
267 TU.ExtraArgs.push_back("-fexceptions"); // FIXME: stop testing on PS4.
268 auto AST = TU.build();
269 EXPECT_THAT(findDocumentHighlights(AST, T.point()), highlightsFrom(T))
270 << Test;
271 }
272 }
273
274 MATCHER_P3(sym, Name, Decl, DefOrNone, "") {
275 std::optional<Range> Def = DefOrNone;
276 if (Name != arg.Name) {
277 *result_listener << "Name is " << arg.Name;
278 return false;
279 }
280 if (Decl != arg.PreferredDeclaration.range) {
281 *result_listener << "Declaration is "
282 << llvm::to_string(arg.PreferredDeclaration);
283 return false;
284 }
285 if (!Def && !arg.Definition)
286 return true;
287 if (Def && !arg.Definition) {
288 *result_listener << "Has no definition";
289 return false;
290 }
291 if (!Def && arg.Definition) {
292 *result_listener << "Definition is " << llvm::to_string(*arg.Definition);
293 return false;
294 }
295 if (arg.Definition->range != *Def) {
296 *result_listener << "Definition is " << llvm::to_string(*arg.Definition);
297 return false;
298 }
299 return true;
300 }
301
302 MATCHER_P(sym, Name, "") { return arg.Name == Name; }
303
304 MATCHER_P(rangeIs, R, "") { return arg.Loc.range == R; }
305 MATCHER_P(containerIs, C, "") {
306 return arg.Loc.containerName.value_or("") == C;
307 }
308 MATCHER_P(attrsAre, A, "") { return arg.Attributes == A; }
309 MATCHER_P(hasID, ID, "") { return arg.ID == ID; }
310
311 TEST(LocateSymbol, WithIndex) {
312 Annotations SymbolHeader(R"cpp(
313 class $forward[[Forward]];
314 class $foo[[Foo]] {};
315
316 void $f1[[f1]]();
317
318 inline void $f2[[f2]]() {}
319 )cpp");
320 Annotations SymbolCpp(R"cpp(
321 class $forward[[forward]] {};
322 void $f1[[f1]]() {}
323 )cpp");
324
325 TestTU TU;
326 TU.Code = std::string(SymbolCpp.code());
327 TU.HeaderCode = std::string(SymbolHeader.code());
328 auto Index = TU.index();
329 auto LocateWithIndex = [&Index](const Annotations &Main) {
330 auto AST = TestTU::withCode(Main.code()).build();
331 return clangd::locateSymbolAt(AST, Main.point(), Index.get());
332 };
333
334 Annotations Test(R"cpp(// only declaration in AST.
335 void [[f1]]();
336 int main() {
337 ^f1();
338 }
339 )cpp");
340 EXPECT_THAT(LocateWithIndex(Test),
341 ElementsAre(sym("f1", Test.range(), SymbolCpp.range("f1"))));
342
343 Test = Annotations(R"cpp(// definition in AST.
344 void [[f1]]() {}
345 int main() {
346 ^f1();
347 }
348 )cpp");
349 EXPECT_THAT(LocateWithIndex(Test),
350 ElementsAre(sym("f1", SymbolHeader.range("f1"), Test.range())));
351
352 Test = Annotations(R"cpp(// forward declaration in AST.
353 class [[Foo]];
354 F^oo* create();
355 )cpp");
356 EXPECT_THAT(LocateWithIndex(Test),
357 ElementsAre(sym("Foo", Test.range(), SymbolHeader.range("foo"))));
358
359 Test = Annotations(R"cpp(// definition in AST.
360 class [[Forward]] {};
361 F^orward create();
362 )cpp");
363 EXPECT_THAT(
364 LocateWithIndex(Test),
365 ElementsAre(sym("Forward", SymbolHeader.range("forward"), Test.range())));
366 }
367
368 TEST(LocateSymbol, AnonymousStructFields) {
369 auto Code = Annotations(R"cpp(
370 struct $2[[Foo]] {
371 struct { int $1[[x]]; };
372 void foo() {
373 // Make sure the implicit base is skipped.
374 $1^x = 42;
375 }
376 };
377 // Check that we don't skip explicit bases.
378 int a = $2^Foo{}.x;
379 )cpp");
380 TestTU TU = TestTU::withCode(Code.code());
381 auto AST = TU.build();
382 EXPECT_THAT(locateSymbolAt(AST, Code.point("1"), TU.index().get()),
383 UnorderedElementsAre(sym("x", Code.range("1"), Code.range("1"))));
384 EXPECT_THAT(
385 locateSymbolAt(AST, Code.point("2"), TU.index().get()),
386 UnorderedElementsAre(sym("Foo", Code.range("2"), Code.range("2"))));
387 }
388
389 TEST(LocateSymbol, FindOverrides) {
390 auto Code = Annotations(R"cpp(
391 class Foo {
392 virtual void $1[[fo^o]]() = 0;
393 };
394 class Bar : public Foo {
395 void $2[[foo]]() override;
396 };
397 )cpp");
398 TestTU TU = TestTU::withCode(Code.code());
399 auto AST = TU.build();
400 EXPECT_THAT(locateSymbolAt(AST, Code.point(), TU.index().get()),
401 UnorderedElementsAre(sym("foo", Code.range("1"), std::nullopt),
402 sym("foo", Code.range("2"), std::nullopt)));
403 }
404
405 TEST(LocateSymbol, WithIndexPreferredLocation) {
406 Annotations SymbolHeader(R"cpp(
407 class $p[[Proto]] {};
408 void $f[[func]]() {};
409 )cpp");
410 TestTU TU;
411 TU.HeaderCode = std::string(SymbolHeader.code());
412 TU.HeaderFilename = "x.proto"; // Prefer locations in codegen files.
413 auto Index = TU.index();
414
415 Annotations Test(R"cpp(// only declaration in AST.
416 // Shift to make range different.
417 class Proto;
418 void func() {}
419 P$p^roto* create() {
420 fu$f^nc();
421 return nullptr;
422 }
423 )cpp");
424
425 auto AST = TestTU::withCode(Test.code()).build();
426 {
427 auto Locs = clangd::locateSymbolAt(AST, Test.point("p"), Index.get());
428 auto CodeGenLoc = SymbolHeader.range("p");
429 EXPECT_THAT(Locs, ElementsAre(sym("Proto", CodeGenLoc, CodeGenLoc)));
430 }
431 {
432 auto Locs = clangd::locateSymbolAt(AST, Test.point("f"), Index.get());
433 auto CodeGenLoc = SymbolHeader.range("f");
434 EXPECT_THAT(Locs, ElementsAre(sym("func", CodeGenLoc, CodeGenLoc)));
435 }
436 }
437
438 TEST(LocateSymbol, All) {
439 // Ranges in tests:
440 // $decl is the declaration location (if absent, no symbol is located)
441 // $def is the definition location (if absent, symbol has no definition)
442 // unnamed range becomes both $decl and $def.
443 const char *Tests[] = {
444 R"cpp(
445 struct X {
446 union {
447 int [[a]];
448 float b;
449 };
450 };
451 int test(X &x) {
452 return x.^a;
453 }
454 )cpp",
455
456 R"cpp(// Local variable
457 int main() {
458 int [[bonjour]];
459 ^bonjour = 2;
460 int test1 = bonjour;
461 }
462 )cpp",
463
464 R"cpp(// Struct
465 namespace ns1 {
466 struct [[MyClass]] {};
467 } // namespace ns1
468 int main() {
469 ns1::My^Class* Params;
470 }
471 )cpp",
472
473 R"cpp(// Function definition via pointer
474 void [[foo]](int) {}
475 int main() {
476 auto *X = &^foo;
477 }
478 )cpp",
479
480 R"cpp(// Function declaration via call
481 int $decl[[foo]](int);
482 int main() {
483 return ^foo(42);
484 }
485 )cpp",
486
487 R"cpp(// Field
488 struct Foo { int [[x]]; };
489 int main() {
490 Foo bar;
491 (void)bar.^x;
492 }
493 )cpp",
494
495 R"cpp(// Field, member initializer
496 struct Foo {
497 int [[x]];
498 Foo() : ^x(0) {}
499 };
500 )cpp",
501
502 R"cpp(// Field, field designator
503 struct Foo { int [[x]]; };
504 int main() {
505 Foo bar = { .^x = 2 };
506 }
507 )cpp",
508
509 R"cpp(// Method call
510 struct Foo { int $decl[[x]](); };
511 int main() {
512 Foo bar;
513 bar.^x();
514 }
515 )cpp",
516
517 R"cpp(// Typedef
518 typedef int $decl[[Foo]];
519 int main() {
520 ^Foo bar;
521 }
522 )cpp",
523
524 R"cpp(// Template type parameter
525 template <typename [[T]]>
526 void foo() { ^T t; }
527 )cpp",
528
529 R"cpp(// Template template type parameter
530 template <template<typename> class [[T]]>
531 void foo() { ^T<int> t; }
532 )cpp",
533
534 R"cpp(// Namespace
535 namespace $decl[[ns]] {
536 struct Foo { static void bar(); };
537 } // namespace ns
538 int main() { ^ns::Foo::bar(); }
539 )cpp",
540
541 R"cpp(// Macro
542 class TTT { public: int a; };
543 #define [[FF]](S) if (int b = S.a) {}
544 void f() {
545 TTT t;
546 F^F(t);
547 }
548 )cpp",
549
550 R"cpp(// Macro argument
551 int [[i]];
552 #define ADDRESSOF(X) &X;
553 int *j = ADDRESSOF(^i);
554 )cpp",
555 R"cpp(// Macro argument appearing multiple times in expansion
556 #define VALIDATE_TYPE(x) (void)x;
557 #define ASSERT(expr) \
558 do { \
559 VALIDATE_TYPE(expr); \
560 if (!expr); \
561 } while (false)
562 bool [[waldo]]() { return true; }
563 void foo() {
564 ASSERT(wa^ldo());
565 }
566 )cpp",
567 R"cpp(// Symbol concatenated inside macro (not supported)
568 int *pi;
569 #define POINTER(X) p ## X;
570 int x = *POINTER(^i);
571 )cpp",
572
573 R"cpp(// Forward class declaration
574 class $decl[[Foo]];
575 class $def[[Foo]] {};
576 F^oo* foo();
577 )cpp",
578
579 R"cpp(// Function declaration
580 void $decl[[foo]]();
581 void g() { f^oo(); }
582 void $def[[foo]]() {}
583 )cpp",
584
585 R"cpp(
586 #define FF(name) class name##_Test {};
587 [[FF]](my);
588 void f() { my^_Test a; }
589 )cpp",
590
591 R"cpp(
592 #define FF() class [[Test]] {};
593 FF();
594 void f() { T^est a; }
595 )cpp",
596
597 R"cpp(// explicit template specialization
598 template <typename T>
599 struct Foo { void bar() {} };
600
601 template <>
602 struct [[Foo]]<int> { void bar() {} };
603
604 void foo() {
605 Foo<char> abc;
606 Fo^o<int> b;
607 }
608 )cpp",
609
610 R"cpp(// implicit template specialization
611 template <typename T>
612 struct [[Foo]] { void bar() {} };
613 template <>
614 struct Foo<int> { void bar() {} };
615 void foo() {
616 Fo^o<char> abc;
617 Foo<int> b;
618 }
619 )cpp",
620
621 R"cpp(// partial template specialization
622 template <typename T>
623 struct Foo { void bar() {} };
624 template <typename T>
625 struct [[Foo]]<T*> { void bar() {} };
626 ^Foo<int*> x;
627 )cpp",
628
629 R"cpp(// function template specializations
630 template <class T>
631 void foo(T) {}
632 template <>
633 void [[foo]](int) {}
634 void bar() {
635 fo^o(10);
636 }
637 )cpp",
638
639 R"cpp(// variable template decls
640 template <class T>
641 T var = T();
642
643 template <>
644 double [[var]]<int> = 10;
645
646 double y = va^r<int>;
647 )cpp",
648
649 R"cpp(// No implicit constructors
650 struct X {
651 X(X&& x) = default;
652 };
653 X $decl[[makeX]]();
654 void foo() {
655 auto x = m^akeX();
656 }
657 )cpp",
658
659 R"cpp(
660 struct X {
661 X& $decl[[operator]]++();
662 };
663 void foo(X& x) {
664 +^+x;
665 }
666 )cpp",
667
668 R"cpp(
669 struct S1 { void f(); };
670 struct S2 { S1 * $decl[[operator]]->(); };
671 void test(S2 s2) {
672 s2-^>f();
673 }
674 )cpp",
675
676 R"cpp(// Declaration of explicit template specialization
677 template <typename T>
678 struct $decl[[$def[[Foo]]]] {};
679
680 template <>
681 struct Fo^o<int> {};
682 )cpp",
683
684 R"cpp(// Declaration of partial template specialization
685 template <typename T>
686 struct $decl[[$def[[Foo]]]] {};
687
688 template <typename T>
689 struct Fo^o<T*> {};
690 )cpp",
691
692 R"cpp(// Definition on ClassTemplateDecl
693 namespace ns {
694 // Forward declaration.
695 template<typename T>
696 struct $decl[[Foo]];
697
698 template <typename T>
699 struct $def[[Foo]] {};
700 }
701
702 using ::ns::Fo^o;
703 )cpp",
704
705 R"cpp(// auto builtin type (not supported)
706 ^auto x = 42;
707 )cpp",
708
709 R"cpp(// auto on lambda
710 auto x = [[[]]]{};
711 ^auto y = x;
712 )cpp",
713
714 R"cpp(// auto on struct
715 namespace ns1 {
716 struct [[S1]] {};
717 } // namespace ns1
718
719 ^auto x = ns1::S1{};
720 )cpp",
721
722 R"cpp(// decltype on struct
723 namespace ns1 {
724 struct [[S1]] {};
725 } // namespace ns1
726
727 ns1::S1 i;
728 ^decltype(i) j;
729 )cpp",
730
731 R"cpp(// decltype(auto) on struct
732 namespace ns1 {
733 struct [[S1]] {};
734 } // namespace ns1
735
736 ns1::S1 i;
737 ns1::S1& j = i;
738 ^decltype(auto) k = j;
739 )cpp",
740
741 R"cpp(// auto on template class
742 template<typename T> class [[Foo]] {};
743
744 ^auto x = Foo<int>();
745 )cpp",
746
747 R"cpp(// auto on template class with forward declared class
748 template<typename T> class [[Foo]] {};
749 class X;
750
751 ^auto x = Foo<X>();
752 )cpp",
753
754 R"cpp(// auto on specialized template class
755 template<typename T> class Foo {};
756 template<> class [[Foo]]<int> {};
757
758 ^auto x = Foo<int>();
759 )cpp",
760
761 R"cpp(// auto on initializer list.
762 namespace std
763 {
764 template<class _E>
765 class [[initializer_list]] {};
766 }
767
768 ^auto i = {1,2};
769 )cpp",
770
771 R"cpp(// auto function return with trailing type
772 struct [[Bar]] {};
773 ^auto test() -> decltype(Bar()) {
774 return Bar();
775 }
776 )cpp",
777
778 R"cpp(// decltype in trailing return type
779 struct [[Bar]] {};
780 auto test() -> ^decltype(Bar()) {
781 return Bar();
782 }
783 )cpp",
784
785 R"cpp(// auto in function return
786 struct [[Bar]] {};
787 ^auto test() {
788 return Bar();
789 }
790 )cpp",
791
792 R"cpp(// auto& in function return
793 struct [[Bar]] {};
794 ^auto& test() {
795 static Bar x;
796 return x;
797 }
798 )cpp",
799
800 R"cpp(// auto* in function return
801 struct [[Bar]] {};
802 ^auto* test() {
803 Bar* x;
804 return x;
805 }
806 )cpp",
807
808 R"cpp(// const auto& in function return
809 struct [[Bar]] {};
810 const ^auto& test() {
811 static Bar x;
812 return x;
813 }
814 )cpp",
815
816 R"cpp(// auto lambda param where there's a single instantiation
817 struct [[Bar]] {};
818 auto Lambda = [](^auto){ return 0; };
819 int x = Lambda(Bar{});
820 )cpp",
821
822 R"cpp(// decltype(auto) in function return
823 struct [[Bar]] {};
824 ^decltype(auto) test() {
825 return Bar();
826 }
827 )cpp",
828
829 R"cpp(// decltype of function with trailing return type.
830 struct [[Bar]] {};
831 auto test() -> decltype(Bar()) {
832 return Bar();
833 }
834 void foo() {
835 ^decltype(test()) i = test();
836 }
837 )cpp",
838
839 R"cpp(// Override specifier jumps to overridden method
840 class Y { virtual void $decl[[a]]() = 0; };
841 class X : Y { void a() ^override {} };
842 )cpp",
843
844 R"cpp(// Final specifier jumps to overridden method
845 class Y { virtual void $decl[[a]]() = 0; };
846 class X : Y { void a() ^final {} };
847 )cpp",
848
849 R"cpp(// Heuristic resolution of dependent method
850 template <typename T>
851 struct S {
852 void [[bar]]() {}
853 };
854
855 template <typename T>
856 void foo(S<T> arg) {
857 arg.ba^r();
858 }
859 )cpp",
860
861 R"cpp(// Heuristic resolution of dependent method via this->
862 template <typename T>
863 struct S {
864 void [[foo]]() {
865 this->fo^o();
866 }
867 };
868 )cpp",
869
870 R"cpp(// Heuristic resolution of dependent static method
871 template <typename T>
872 struct S {
873 static void [[bar]]() {}
874 };
875
876 template <typename T>
877 void foo() {
878 S<T>::ba^r();
879 }
880 )cpp",
881
882 R"cpp(// Heuristic resolution of dependent method
883 // invoked via smart pointer
884 template <typename> struct S { void [[foo]]() {} };
885 template <typename T> struct unique_ptr {
886 T* operator->();
887 };
888 template <typename T>
889 void test(unique_ptr<S<T>>& V) {
890 V->fo^o();
891 }
892 )cpp",
893
894 R"cpp(// Heuristic resolution of dependent enumerator
895 template <typename T>
896 struct Foo {
897 enum class E { [[A]], B };
898 E e = E::A^;
899 };
900 )cpp",
901
902 R"cpp(// Enum base
903 typedef int $decl[[MyTypeDef]];
904 enum Foo : My^TypeDef {};
905 )cpp",
906 R"cpp(// Enum base
907 typedef int $decl[[MyTypeDef]];
908 enum Foo : My^TypeDef;
909 )cpp",
910 R"cpp(// Enum base
911 using $decl[[MyTypeDef]] = int;
912 enum Foo : My^TypeDef {};
913 )cpp",
914
915 R"objc(
916 @protocol Dog;
917 @protocol $decl[[Dog]]
918 - (void)bark;
919 @end
920 id<Do^g> getDoggo() {
921 return 0;
922 }
923 )objc",
924
925 R"objc(
926 @interface Cat
927 @end
928 @implementation Cat
929 @end
930 @interface $decl[[Cat]] (Exte^nsion)
931 - (void)meow;
932 @end
933 @implementation $def[[Cat]] (Extension)
934 - (void)meow {}
935 @end
936 )objc",
937
938 R"objc(
939 @class $decl[[Foo]];
940 Fo^o * getFoo() {
941 return 0;
942 }
943 )objc",
944
945 R"objc(// Prefer interface definition over forward declaration
946 @class Foo;
947 @interface $decl[[Foo]]
948 @end
949 Fo^o * getFoo() {
950 return 0;
951 }
952 )objc",
953
954 R"objc(
955 @class Foo;
956 @interface $decl[[Foo]]
957 @end
958 @implementation $def[[Foo]]
959 @end
960 Fo^o * getFoo() {
961 return 0;
962 }
963 )objc",
964
965 R"objc(// Method decl and definition for ObjC class.
966 @interface Cat
967 - (void)$decl[[meow]];
968 @end
969 @implementation Cat
970 - (void)$def[[meow]] {}
971 @end
972 void makeNoise(Cat *kitty) {
973 [kitty me^ow];
974 }
975 )objc",
976
977 R"objc(// Method decl and definition for ObjC category.
978 @interface Dog
979 @end
980 @interface Dog (Play)
981 - (void)$decl[[runAround]];
982 @end
983 @implementation Dog (Play)
984 - (void)$def[[runAround]] {}
985 @end
986 void play(Dog *dog) {
987 [dog run^Around];
988 }
989 )objc",
990
991 R"objc(// Method decl and definition for ObjC class extension.
992 @interface Dog
993 @end
994 @interface Dog ()
995 - (void)$decl[[howl]];
996 @end
997 @implementation Dog
998 - (void)$def[[howl]] {}
999 @end
1000 void play(Dog *dog) {
1001 [dog ho^wl];
1002 }
1003 )objc"};
1004 for (const char *Test : Tests) {
1005 Annotations T(Test);
1006 std::optional<Range> WantDecl;
1007 std::optional<Range> WantDef;
1008 if (!T.ranges().empty())
1009 WantDecl = WantDef = T.range();
1010 if (!T.ranges("decl").empty())
1011 WantDecl = T.range("decl");
1012 if (!T.ranges("def").empty())
1013 WantDef = T.range("def");
1014
1015 TestTU TU;
1016 TU.Code = std::string(T.code());
1017
1018 TU.ExtraArgs.push_back("-xobjective-c++");
1019
1020 auto AST = TU.build();
1021 auto Results = locateSymbolAt(AST, T.point());
1022
1023 if (!WantDecl) {
1024 EXPECT_THAT(Results, IsEmpty()) << Test;
1025 } else {
1026 ASSERT_THAT(Results, ::testing::SizeIs(1)) << Test;
1027 EXPECT_EQ(Results[0].PreferredDeclaration.range, *WantDecl) << Test;
1028 EXPECT_TRUE(Results[0].ID) << Test;
1029 std::optional<Range> GotDef;
1030 if (Results[0].Definition)
1031 GotDef = Results[0].Definition->range;
1032 EXPECT_EQ(WantDef, GotDef) << Test;
1033 }
1034 }
1035 }
1036 TEST(LocateSymbol, ValidSymbolID) {
1037 auto T = Annotations(R"cpp(
1038 #define MACRO(x, y) ((x) + (y))
1039 int add(int x, int y) { return $MACRO^MACRO(x, y); }
1040 int sum = $add^add(1, 2);
1041 )cpp");
1042
1043 TestTU TU = TestTU::withCode(T.code());
1044 auto AST = TU.build();
1045 auto Index = TU.index();
1046 EXPECT_THAT(locateSymbolAt(AST, T.point("add"), Index.get()),
1047 ElementsAre(AllOf(sym("add"),
1048 hasID(getSymbolID(&findDecl(AST, "add"))))));
1049 EXPECT_THAT(
1050 locateSymbolAt(AST, T.point("MACRO"), Index.get()),
1051 ElementsAre(AllOf(sym("MACRO"),
1052 hasID(findSymbol(TU.headerSymbols(), "MACRO").ID))));
1053 }
1054
1055 TEST(LocateSymbol, AllMulti) {
1056 // Ranges in tests:
1057 // $declN is the declaration location
1058 // $defN is the definition location (if absent, symbol has no definition)
1059 //
1060 // NOTE:
1061 // N starts at 0.
1062 struct ExpectedRanges {
1063 Range WantDecl;
1064 std::optional<Range> WantDef;
1065 };
1066 const char *Tests[] = {
1067 R"objc(
1068 @interface $decl0[[Cat]]
1069 @end
1070 @implementation $def0[[Cat]]
1071 @end
1072 @interface $decl1[[Ca^t]] (Extension)
1073 - (void)meow;
1074 @end
1075 @implementation $def1[[Cat]] (Extension)
1076 - (void)meow {}
1077 @end
1078 )objc",
1079
1080 R"objc(
1081 @interface $decl0[[Cat]]
1082 @end
1083 @implementation $def0[[Cat]]
1084 @end
1085 @interface $decl1[[Cat]] (Extension)
1086 - (void)meow;
1087 @end
1088 @implementation $def1[[Ca^t]] (Extension)
1089 - (void)meow {}
1090 @end
1091 )objc",
1092
1093 R"objc(
1094 @interface $decl0[[Cat]]
1095 @end
1096 @interface $decl1[[Ca^t]] ()
1097 - (void)meow;
1098 @end
1099 @implementation $def0[[$def1[[Cat]]]]
1100 - (void)meow {}
1101 @end
1102 )objc",
1103 };
1104 for (const char *Test : Tests) {
1105 Annotations T(Test);
1106 std::vector<ExpectedRanges> Ranges;
1107 for (int Idx = 0; true; Idx++) {
1108 bool HasDecl = !T.ranges("decl" + std::to_string(Idx)).empty();
1109 bool HasDef = !T.ranges("def" + std::to_string(Idx)).empty();
1110 if (!HasDecl && !HasDef)
1111 break;
1112 ExpectedRanges Range;
1113 if (HasDecl)
1114 Range.WantDecl = T.range("decl" + std::to_string(Idx));
1115 if (HasDef)
1116 Range.WantDef = T.range("def" + std::to_string(Idx));
1117 Ranges.push_back(Range);
1118 }
1119
1120 TestTU TU;
1121 TU.Code = std::string(T.code());
1122 TU.ExtraArgs.push_back("-xobjective-c++");
1123
1124 auto AST = TU.build();
1125 auto Results = locateSymbolAt(AST, T.point());
1126
1127 ASSERT_THAT(Results, ::testing::SizeIs(Ranges.size())) << Test;
1128 for (size_t Idx = 0; Idx < Ranges.size(); Idx++) {
1129 EXPECT_EQ(Results[Idx].PreferredDeclaration.range, Ranges[Idx].WantDecl)
1130 << "($decl" << Idx << ")" << Test;
1131 std::optional<Range> GotDef;
1132 if (Results[Idx].Definition)
1133 GotDef = Results[Idx].Definition->range;
1134 EXPECT_EQ(GotDef, Ranges[Idx].WantDef) << "($def" << Idx << ")" << Test;
1135 }
1136 }
1137 }
1138
1139 // LocateSymbol test cases that produce warnings.
1140 // These are separated out from All so that in All we can assert
1141 // that there are no diagnostics.
1142 TEST(LocateSymbol, Warnings) {
1143 const char *Tests[] = {
1144 R"cpp(// Field, GNU old-style field designator
1145 struct Foo { int [[x]]; };
1146 int main() {
1147 Foo bar = { ^x : 1 };
1148 }
1149 )cpp",
1150
1151 R"cpp(// Macro
1152 #define MACRO 0
1153 #define [[MACRO]] 1
1154 int main() { return ^MACRO; }
1155 #define MACRO 2
1156 #undef macro
1157 )cpp",
1158 };
1159
1160 for (const char *Test : Tests) {
1161 Annotations T(Test);
1162 std::optional<Range> WantDecl;
1163 std::optional<Range> WantDef;
1164 if (!T.ranges().empty())
1165 WantDecl = WantDef = T.range();
1166 if (!T.ranges("decl").empty())
1167 WantDecl = T.range("decl");
1168 if (!T.ranges("def").empty())
1169 WantDef = T.range("def");
1170
1171 TestTU TU;
1172 TU.Code = std::string(T.code());
1173
1174 auto AST = TU.build();
1175 auto Results = locateSymbolAt(AST, T.point());
1176
1177 if (!WantDecl) {
1178 EXPECT_THAT(Results, IsEmpty()) << Test;
1179 } else {
1180 ASSERT_THAT(Results, ::testing::SizeIs(1)) << Test;
1181 EXPECT_EQ(Results[0].PreferredDeclaration.range, *WantDecl) << Test;
1182 std::optional<Range> GotDef;
1183 if (Results[0].Definition)
1184 GotDef = Results[0].Definition->range;
1185 EXPECT_EQ(WantDef, GotDef) << Test;
1186 }
1187 }
1188 }
1189
1190 TEST(LocateSymbol, TextualSmoke) {
1191 auto T = Annotations(
1192 R"cpp(
1193 struct [[MyClass]] {};
1194 // Comment mentioning M^yClass
1195 )cpp");
1196
1197 auto TU = TestTU::withCode(T.code());
1198 auto AST = TU.build();
1199 auto Index = TU.index();
1200 EXPECT_THAT(
1201 locateSymbolAt(AST, T.point(), Index.get()),
1202 ElementsAre(AllOf(sym("MyClass", T.range(), T.range()),
1203 hasID(getSymbolID(&findDecl(AST, "MyClass"))))));
1204 }
1205
1206 TEST(LocateSymbol, Textual) {
1207 const char *Tests[] = {
1208 R"cpp(// Comment
1209 struct [[MyClass]] {};
1210 // Comment mentioning M^yClass
1211 )cpp",
1212 R"cpp(// String
1213 struct MyClass {};
1214 // Not triggered for string literal tokens.
1215 const char* s = "String literal mentioning M^yClass";
1216 )cpp",
1217 R"cpp(// Ifdef'ed out code
1218 struct [[MyClass]] {};
1219 #ifdef WALDO
1220 M^yClass var;
1221 #endif
1222 )cpp",
1223 R"cpp(// Macro definition
1224 struct [[MyClass]] {};
1225 #define DECLARE_MYCLASS_OBJ(name) M^yClass name;
1226 )cpp",
1227 R"cpp(// Invalid code
1228 /*error-ok*/
1229 int myFunction(int);
1230 // Not triggered for token which survived preprocessing.
1231 int var = m^yFunction();
1232 )cpp"};
1233
1234 for (const char *Test : Tests) {
1235 Annotations T(Test);
1236 std::optional<Range> WantDecl;
1237 if (!T.ranges().empty())
1238 WantDecl = T.range();
1239
1240 auto TU = TestTU::withCode(T.code());
1241
1242 auto AST = TU.build();
1243 auto Index = TU.index();
1244 auto Word = SpelledWord::touching(
1245 cantFail(sourceLocationInMainFile(AST.getSourceManager(), T.point())),
1246 AST.getTokens(), AST.getLangOpts());
1247 if (!Word) {
1248 ADD_FAILURE() << "No word touching point!" << Test;
1249 continue;
1250 }
1251 auto Results = locateSymbolTextually(*Word, AST, Index.get(),
1252 testPath(TU.Filename), ASTNodeKind());
1253
1254 if (!WantDecl) {
1255 EXPECT_THAT(Results, IsEmpty()) << Test;
1256 } else {
1257 ASSERT_THAT(Results, ::testing::SizeIs(1)) << Test;
1258 EXPECT_EQ(Results[0].PreferredDeclaration.range, *WantDecl) << Test;
1259 }
1260 }
1261 } // namespace
1262
1263 TEST(LocateSymbol, Ambiguous) {
1264 auto T = Annotations(R"cpp(
1265 struct Foo {
1266 Foo();
1267 Foo(Foo&&);
1268 $ConstructorLoc[[Foo]](const char*);
1269 };
1270
1271 Foo f();
1272
1273 void g(Foo foo);
1274
1275 void call() {
1276 const char* str = "123";
1277 Foo a = $1^str;
1278 Foo b = Foo($2^str);
1279 Foo c = $3^f();
1280 $4^g($5^f());
1281 g($6^str);
1282 Foo ab$7^c;
1283 Foo ab$8^cd("asdf");
1284 Foo foox = Fo$9^o("asdf");
1285 Foo abcde$10^("asdf");
1286 Foo foox2 = Foo$11^("asdf");
1287 }
1288
1289 template <typename T>
1290 struct S {
1291 void $NonstaticOverload1[[bar]](int);
1292 void $NonstaticOverload2[[bar]](float);
1293
1294 static void $StaticOverload1[[baz]](int);
1295 static void $StaticOverload2[[baz]](float);
1296 };
1297
1298 template <typename T, typename U>
1299 void dependent_call(S<T> s, U u) {
1300 s.ba$12^r(u);
1301 S<T>::ba$13^z(u);
1302 }
1303 )cpp");
1304 auto TU = TestTU::withCode(T.code());
1305 // FIXME: Go-to-definition in a template requires disabling delayed template
1306 // parsing.
1307 TU.ExtraArgs.push_back("-fno-delayed-template-parsing");
1308 auto AST = TU.build();
1309 // Ordered assertions are deliberate: we expect a predictable order.
1310 EXPECT_THAT(locateSymbolAt(AST, T.point("1")), ElementsAre(sym("str")));
1311 EXPECT_THAT(locateSymbolAt(AST, T.point("2")), ElementsAre(sym("str")));
1312 EXPECT_THAT(locateSymbolAt(AST, T.point("3")), ElementsAre(sym("f")));
1313 EXPECT_THAT(locateSymbolAt(AST, T.point("4")), ElementsAre(sym("g")));
1314 EXPECT_THAT(locateSymbolAt(AST, T.point("5")), ElementsAre(sym("f")));
1315 EXPECT_THAT(locateSymbolAt(AST, T.point("6")), ElementsAre(sym("str")));
1316 // FIXME: Target the constructor as well.
1317 EXPECT_THAT(locateSymbolAt(AST, T.point("7")), ElementsAre(sym("abc")));
1318 // FIXME: Target the constructor as well.
1319 EXPECT_THAT(locateSymbolAt(AST, T.point("8")), ElementsAre(sym("abcd")));
1320 // FIXME: Target the constructor as well.
1321 EXPECT_THAT(locateSymbolAt(AST, T.point("9")), ElementsAre(sym("Foo")));
1322 EXPECT_THAT(locateSymbolAt(AST, T.point("10")),
1323 ElementsAre(sym("Foo", T.range("ConstructorLoc"), std::nullopt)));
1324 EXPECT_THAT(locateSymbolAt(AST, T.point("11")),
1325 ElementsAre(sym("Foo", T.range("ConstructorLoc"), std::nullopt)));
1326 // These assertions are unordered because the order comes from
1327 // CXXRecordDecl::lookupDependentName() which doesn't appear to provide
1328 // an order guarantee.
1329 EXPECT_THAT(locateSymbolAt(AST, T.point("12")),
1330 UnorderedElementsAre(
1331 sym("bar", T.range("NonstaticOverload1"), std::nullopt),
1332 sym("bar", T.range("NonstaticOverload2"), std::nullopt)));
1333 EXPECT_THAT(locateSymbolAt(AST, T.point("13")),
1334 UnorderedElementsAre(
1335 sym("baz", T.range("StaticOverload1"), std::nullopt),
1336 sym("baz", T.range("StaticOverload2"), std::nullopt)));
1337 }
1338
1339 TEST(LocateSymbol, TextualDependent) {
1340 // Put the declarations in the header to make sure we are
1341 // finding them via the index heuristic and not the
1342 // nearby-ident heuristic.
1343 Annotations Header(R"cpp(
1344 struct Foo {
1345 void $FooLoc[[uniqueMethodName]]();
1346 };
1347 struct Bar {
1348 void $BarLoc[[uniqueMethodName]]();
1349 };
1350 )cpp");
1351 Annotations Source(R"cpp(
1352 template <typename T>
1353 void f(T t) {
1354 t.u^niqueMethodName();
1355 }
1356 )cpp");
1357 TestTU TU;
1358 TU.Code = std::string(Source.code());
1359 TU.HeaderCode = std::string(Header.code());
1360 auto AST = TU.build();
1361 auto Index = TU.index();
1362 // Need to use locateSymbolAt() since we are testing an
1363 // interaction between locateASTReferent() and
1364 // locateSymbolNamedTextuallyAt().
1365 auto Results = locateSymbolAt(AST, Source.point(), Index.get());
1366 EXPECT_THAT(
1367 Results,
1368 UnorderedElementsAre(
1369 sym("uniqueMethodName", Header.range("FooLoc"), std::nullopt),
1370 sym("uniqueMethodName", Header.range("BarLoc"), std::nullopt)));
1371 }
1372
1373 TEST(LocateSymbol, Alias) {
1374 const char *Tests[] = {
1375 R"cpp(
1376 template <class T> struct function {};
1377 template <class T> using [[callback]] = function<T()>;
1378
1379 c^allback<int> foo;
1380 )cpp",
1381
1382 // triggered on non-definition of a renaming alias: should not give any
1383 // underlying decls.
1384 R"cpp(
1385 class Foo {};
1386 typedef Foo [[Bar]];
1387
1388 B^ar b;
1389 )cpp",
1390 R"cpp(
1391 class Foo {};
1392 using [[Bar]] = Foo; // definition
1393 Ba^r b;
1394 )cpp",
1395
1396 // triggered on the underlying decl of a renaming alias.
1397 R"cpp(
1398 class [[Foo]];
1399 using Bar = Fo^o;
1400 )cpp",
1401
1402 // triggered on definition of a non-renaming alias: should give underlying
1403 // decls.
1404 R"cpp(
1405 namespace ns { class [[Foo]] {}; }
1406 using ns::F^oo;
1407 )cpp",
1408
1409 R"cpp(
1410 namespace ns { int [[x]](char); int [[x]](double); }
1411 using ns::^x;
1412 )cpp",
1413
1414 R"cpp(
1415 namespace ns { int [[x]](char); int x(double); }
1416 using ns::[[x]];
1417 int y = ^x('a');
1418 )cpp",
1419
1420 R"cpp(
1421 namespace ns { class [[Foo]] {}; }
1422 using ns::[[Foo]];
1423 F^oo f;
1424 )cpp",
1425
1426 // other cases that don't matter much.
1427 R"cpp(
1428 class Foo {};
1429 typedef Foo [[Ba^r]];
1430 )cpp",
1431 R"cpp(
1432 class Foo {};
1433 using [[B^ar]] = Foo;
1434 )cpp",
1435
1436 // Member of dependent base
1437 R"cpp(
1438 template <typename T>
1439 struct Base {
1440 void [[waldo]]() {}
1441 };
1442 template <typename T>
1443 struct Derived : Base<T> {
1444 using Base<T>::w^aldo;
1445 };
1446 )cpp",
1447 };
1448
1449 for (const auto *Case : Tests) {
1450 SCOPED_TRACE(Case);
1451 auto T = Annotations(Case);
1452 auto AST = TestTU::withCode(T.code()).build();
1453 EXPECT_THAT(locateSymbolAt(AST, T.point()),
1454 UnorderedPointwise(declRange(), T.ranges()));
1455 }
1456 }
1457
1458 TEST(LocateSymbol, RelPathsInCompileCommand) {
1459 // The source is in "/clangd-test/src".
1460 // We build in "/clangd-test/build".
1461
1462 Annotations SourceAnnotations(R"cpp(
1463 #include "header_in_preamble.h"
1464 int [[foo]];
1465 #include "header_not_in_preamble.h"
1466 int baz = f$p1^oo + bar_pre$p2^amble + bar_not_pre$p3^amble;
1467 )cpp");
1468
1469 Annotations HeaderInPreambleAnnotations(R"cpp(
1470 int [[bar_preamble]];
1471 )cpp");
1472
1473 Annotations HeaderNotInPreambleAnnotations(R"cpp(
1474 int [[bar_not_preamble]];
1475 )cpp");
1476
1477 // Make the compilation paths appear as ../src/foo.cpp in the compile
1478 // commands.
1479 SmallString<32> RelPathPrefix("..");
1480 llvm::sys::path::append(RelPathPrefix, "src");
1481 std::string BuildDir = testPath("build");
1482 MockCompilationDatabase CDB(BuildDir, RelPathPrefix);
1483
1484 MockFS FS;
1485 ClangdServer Server(CDB, FS, ClangdServer::optsForTest());
1486
1487 // Fill the filesystem.
1488 auto FooCpp = testPath("src/foo.cpp");
1489 FS.Files[FooCpp] = "";
1490 auto HeaderInPreambleH = testPath("src/header_in_preamble.h");
1491 FS.Files[HeaderInPreambleH] = std::string(HeaderInPreambleAnnotations.code());
1492 auto HeaderNotInPreambleH = testPath("src/header_not_in_preamble.h");
1493 FS.Files[HeaderNotInPreambleH] =
1494 std::string(HeaderNotInPreambleAnnotations.code());
1495
1496 runAddDocument(Server, FooCpp, SourceAnnotations.code());
1497
1498 // Go to a definition in main source file.
1499 auto Locations =
1500 runLocateSymbolAt(Server, FooCpp, SourceAnnotations.point("p1"));
1501 EXPECT_TRUE(bool(Locations)) << "findDefinitions returned an error";
1502 EXPECT_THAT(*Locations, ElementsAre(sym("foo", SourceAnnotations.range(),
1503 SourceAnnotations.range())));
1504
1505 // Go to a definition in header_in_preamble.h.
1506 Locations = runLocateSymbolAt(Server, FooCpp, SourceAnnotations.point("p2"));
1507 EXPECT_TRUE(bool(Locations)) << "findDefinitions returned an error";
1508 EXPECT_THAT(
1509 *Locations,
1510 ElementsAre(sym("bar_preamble", HeaderInPreambleAnnotations.range(),
1511 HeaderInPreambleAnnotations.range())));
1512
1513 // Go to a definition in header_not_in_preamble.h.
1514 Locations = runLocateSymbolAt(Server, FooCpp, SourceAnnotations.point("p3"));
1515 EXPECT_TRUE(bool(Locations)) << "findDefinitions returned an error";
1516 EXPECT_THAT(*Locations,
1517 ElementsAre(sym("bar_not_preamble",
1518 HeaderNotInPreambleAnnotations.range(),
1519 HeaderNotInPreambleAnnotations.range())));
1520 }
1521
1522 TEST(GoToInclude, All) {
1523 MockFS FS;
1524 MockCompilationDatabase CDB;
1525 ClangdServer Server(CDB, FS, ClangdServer::optsForTest());
1526
1527 auto FooCpp = testPath("foo.cpp");
1528 const char *SourceContents = R"cpp(
1529 #include ^"$2^foo.h$3^"
1530 #include "$4^invalid.h"
1531 int b = a;
1532 // test
1533 int foo;
1534 #in$5^clude "$6^foo.h"$7^
1535 )cpp";
1536 Annotations SourceAnnotations(SourceContents);
1537 FS.Files[FooCpp] = std::string(SourceAnnotations.code());
1538 auto FooH = testPath("foo.h");
1539
1540 const char *HeaderContents = R"cpp([[]]#pragma once
1541 int a;
1542 )cpp";
1543 Annotations HeaderAnnotations(HeaderContents);
1544 FS.Files[FooH] = std::string(HeaderAnnotations.code());
1545
1546 runAddDocument(Server, FooH, HeaderAnnotations.code());
1547 runAddDocument(Server, FooCpp, SourceAnnotations.code());
1548
1549 // Test include in preamble.
1550 auto Locations = runLocateSymbolAt(Server, FooCpp, SourceAnnotations.point());
1551 ASSERT_TRUE(bool(Locations)) << "locateSymbolAt returned an error";
1552 EXPECT_THAT(*Locations, ElementsAre(sym("foo.h", HeaderAnnotations.range(),
1553 HeaderAnnotations.range())));
1554
1555 // Test include in preamble, last char.
1556 Locations = runLocateSymbolAt(Server, FooCpp, SourceAnnotations.point("2"));
1557 ASSERT_TRUE(bool(Locations)) << "locateSymbolAt returned an error";
1558 EXPECT_THAT(*Locations, ElementsAre(sym("foo.h", HeaderAnnotations.range(),
1559 HeaderAnnotations.range())));
1560
1561 Locations = runLocateSymbolAt(Server, FooCpp, SourceAnnotations.point("3"));
1562 ASSERT_TRUE(bool(Locations)) << "locateSymbolAt returned an error";
1563 EXPECT_THAT(*Locations, ElementsAre(sym("foo.h", HeaderAnnotations.range(),
1564 HeaderAnnotations.range())));
1565
1566 // Test include outside of preamble.
1567 Locations = runLocateSymbolAt(Server, FooCpp, SourceAnnotations.point("6"));
1568 ASSERT_TRUE(bool(Locations)) << "locateSymbolAt returned an error";
1569 EXPECT_THAT(*Locations, ElementsAre(sym("foo.h", HeaderAnnotations.range(),
1570 HeaderAnnotations.range())));
1571
1572 // Test a few positions that do not result in Locations.
1573 Locations = runLocateSymbolAt(Server, FooCpp, SourceAnnotations.point("4"));
1574 ASSERT_TRUE(bool(Locations)) << "locateSymbolAt returned an error";
1575 EXPECT_THAT(*Locations, IsEmpty());
1576
1577 Locations = runLocateSymbolAt(Server, FooCpp, SourceAnnotations.point("5"));
1578 ASSERT_TRUE(bool(Locations)) << "locateSymbolAt returned an error";
1579 EXPECT_THAT(*Locations, ElementsAre(sym("foo.h", HeaderAnnotations.range(),
1580 HeaderAnnotations.range())));
1581
1582 Locations = runLocateSymbolAt(Server, FooCpp, SourceAnnotations.point("7"));
1583 ASSERT_TRUE(bool(Locations)) << "locateSymbolAt returned an error";
1584 EXPECT_THAT(*Locations, ElementsAre(sym("foo.h", HeaderAnnotations.range(),
1585 HeaderAnnotations.range())));
1586
1587 // Objective C #import directive.
1588 Annotations ObjC(R"objc(
1589 #import "^foo.h"
1590 )objc");
1591 auto FooM = testPath("foo.m");
1592 FS.Files[FooM] = std::string(ObjC.code());
1593
1594 runAddDocument(Server, FooM, ObjC.code());
1595 Locations = runLocateSymbolAt(Server, FooM, ObjC.point());
1596 ASSERT_TRUE(bool(Locations)) << "locateSymbolAt returned an error";
1597 EXPECT_THAT(*Locations, ElementsAre(sym("foo.h", HeaderAnnotations.range(),
1598 HeaderAnnotations.range())));
1599 }
1600
1601 TEST(LocateSymbol, WithPreamble) {
1602 // Test stragety: AST should always use the latest preamble instead of last
1603 // good preamble.
1604 MockFS FS;
1605 MockCompilationDatabase CDB;
1606 ClangdServer Server(CDB, FS, ClangdServer::optsForTest());
1607
1608 auto FooCpp = testPath("foo.cpp");
1609 // The trigger locations must be the same.
1610 Annotations FooWithHeader(R"cpp(#include "fo^o.h")cpp");
1611 Annotations FooWithoutHeader(R"cpp(double [[fo^o]]();)cpp");
1612
1613 FS.Files[FooCpp] = std::string(FooWithHeader.code());
1614
1615 auto FooH = testPath("foo.h");
1616 Annotations FooHeader(R"cpp([[]])cpp");
1617 FS.Files[FooH] = std::string(FooHeader.code());
1618
1619 runAddDocument(Server, FooCpp, FooWithHeader.code());
1620 // LocateSymbol goes to a #include file: the result comes from the preamble.
1621 EXPECT_THAT(
1622 cantFail(runLocateSymbolAt(Server, FooCpp, FooWithHeader.point())),
1623 ElementsAre(sym("foo.h", FooHeader.range(), FooHeader.range())));
1624
1625 // Only preamble is built, and no AST is built in this request.
1626 Server.addDocument(FooCpp, FooWithoutHeader.code(), "null",
1627 WantDiagnostics::No);
1628 // We build AST here, and it should use the latest preamble rather than the
1629 // stale one.
1630 EXPECT_THAT(
1631 cantFail(runLocateSymbolAt(Server, FooCpp, FooWithoutHeader.point())),
1632 ElementsAre(sym("foo", FooWithoutHeader.range(), std::nullopt)));
1633
1634 // Reset test environment.
1635 runAddDocument(Server, FooCpp, FooWithHeader.code());
1636 // Both preamble and AST are built in this request.
1637 Server.addDocument(FooCpp, FooWithoutHeader.code(), "null",
1638 WantDiagnostics::Yes);
1639 // Use the AST being built in above request.
1640 EXPECT_THAT(
1641 cantFail(runLocateSymbolAt(Server, FooCpp, FooWithoutHeader.point())),
1642 ElementsAre(sym("foo", FooWithoutHeader.range(), std::nullopt)));
1643 }
1644
1645 TEST(LocateSymbol, NearbyTokenSmoke) {
1646 auto T = Annotations(R"cpp(
1647 // prints e^rr and crashes
1648 void die(const char* [[err]]);
1649 )cpp");
1650 auto AST = TestTU::withCode(T.code()).build();
1651 // We don't pass an index, so can't hit index-based fallback.
1652 EXPECT_THAT(locateSymbolAt(AST, T.point()),
1653 ElementsAre(sym("err", T.range(), T.range())));
1654 }
1655
1656 TEST(LocateSymbol, NearbyIdentifier) {
1657 const char *Tests[] = {
1658 R"cpp(
1659 // regular identifiers (won't trigger)
1660 int hello;
1661 int y = he^llo;
1662 )cpp",
1663 R"cpp(
1664 // disabled preprocessor sections
1665 int [[hello]];
1666 #if 0
1667 int y = ^hello;
1668 #endif
1669 )cpp",
1670 R"cpp(
1671 // comments
1672 // he^llo, world
1673 int [[hello]];
1674 )cpp",
1675 R"cpp(
1676 // not triggered by string literals
1677 int hello;
1678 const char* greeting = "h^ello, world";
1679 )cpp",
1680
1681 R"cpp(
1682 // can refer to macro invocations
1683 #define INT int
1684 [[INT]] x;
1685 // I^NT
1686 )cpp",
1687
1688 R"cpp(
1689 // can refer to macro invocations (even if they expand to nothing)
1690 #define EMPTY
1691 [[EMPTY]] int x;
1692 // E^MPTY
1693 )cpp",
1694
1695 R"cpp(
1696 // prefer nearest occurrence, backwards is worse than forwards
1697 int hello;
1698 int x = hello;
1699 // h^ello
1700 int y = [[hello]];
1701 int z = hello;
1702 )cpp",
1703
1704 R"cpp(
1705 // short identifiers find near results
1706 int [[hi]];
1707 // h^i
1708 )cpp",
1709 R"cpp(
1710 // short identifiers don't find far results
1711 int hi;
1712
1713
1714
1715 // h^i
1716
1717
1718
1719
1720 int x = hi;
1721 )cpp",
1722 R"cpp(
1723 // prefer nearest occurrence even if several matched tokens
1724 // have the same value of `floor(log2(<token line> - <word line>))`.
1725 int hello;
1726 int x = hello, y = hello;
1727 int z = [[hello]];
1728 // h^ello
1729 )cpp"};
1730 for (const char *Test : Tests) {
1731 Annotations T(Test);
1732 auto AST = TestTU::withCode(T.code()).build();
1733 const auto &SM = AST.getSourceManager();
1734 std::optional<Range> Nearby;
1735 auto Word =
1736 SpelledWord::touching(cantFail(sourceLocationInMainFile(SM, T.point())),
1737 AST.getTokens(), AST.getLangOpts());
1738 if (!Word) {
1739 ADD_FAILURE() << "No word at point! " << Test;
1740 continue;
1741 }
1742 if (const auto *Tok = findNearbyIdentifier(*Word, AST.getTokens()))
1743 Nearby = halfOpenToRange(SM, CharSourceRange::getCharRange(
1744 Tok->location(), Tok->endLocation()));
1745 if (T.ranges().empty())
1746 EXPECT_THAT(Nearby, Eq(std::nullopt)) << Test;
1747 else
1748 EXPECT_EQ(Nearby, T.range()) << Test;
1749 }
1750 }
1751
1752 TEST(FindImplementations, Inheritance) {
1753 llvm::StringRef Test = R"cpp(
1754 struct $0^Base {
1755 virtual void F$1^oo();
1756 void C$4^oncrete();
1757 };
1758 struct $0[[Child1]] : Base {
1759 void $1[[Fo$3^o]]() override;
1760 virtual void B$2^ar();
1761 void Concrete(); // No implementations for concrete methods.
1762 };
1763 struct Child2 : Child1 {
1764 void $3[[Foo]]() override;
1765 void $2[[Bar]]() override;
1766 };
1767 void FromReference() {
1768 $0^Base* B;
1769 B->Fo$1^o();
1770 B->C$4^oncrete();
1771 &Base::Fo$1^o;
1772 Child1 * C1;
1773 C1->B$2^ar();
1774 C1->Fo$3^o();
1775 }
1776 // CRTP should work.
1777 template<typename T>
1778 struct $5^TemplateBase {};
1779 struct $5[[Child3]] : public TemplateBase<Child3> {};
1780
1781 // Local classes.
1782 void LocationFunction() {
1783 struct $0[[LocalClass1]] : Base {
1784 void $1[[Foo]]() override;
1785 };
1786 struct $6^LocalBase {
1787 virtual void $7^Bar();
1788 };
1789 struct $6[[LocalClass2]]: LocalBase {
1790 void $7[[Bar]]() override;
1791 };
1792 }
1793 )cpp";
1794
1795 Annotations Code(Test);
1796 auto TU = TestTU::withCode(Code.code());
1797 auto AST = TU.build();
1798 auto Index = TU.index();
1799 for (StringRef Label : {"0", "1", "2", "3", "4", "5", "6", "7"}) {
1800 for (const auto &Point : Code.points(Label)) {
1801 EXPECT_THAT(findImplementations(AST, Point, Index.get()),
1802 UnorderedPointwise(declRange(), Code.ranges(Label)))
1803 << Code.code() << " at " << Point << " for Label " << Label;
1804 }
1805 }
1806 }
1807
1808 TEST(FindImplementations, CaptureDefinition) {
1809 llvm::StringRef Test = R"cpp(
1810 struct Base {
1811 virtual void F^oo();
1812 };
1813 struct Child1 : Base {
1814 void $Decl[[Foo]]() override;
1815 };
1816 struct Child2 : Base {
1817 void $Child2[[Foo]]() override;
1818 };
1819 void Child1::$Def[[Foo]]() { /* Definition */ }
1820 )cpp";
1821 Annotations Code(Test);
1822 auto TU = TestTU::withCode(Code.code());
1823 auto AST = TU.build();
1824 EXPECT_THAT(
1825 findImplementations(AST, Code.point(), TU.index().get()),
1826 UnorderedElementsAre(sym("Foo", Code.range("Decl"), Code.range("Def")),
1827 sym("Foo", Code.range("Child2"), std::nullopt)))
1828 << Test;
1829 }
1830
1831 TEST(FindType, All) {
1832 Annotations HeaderA(R"cpp(
1833 struct $Target[[Target]] { operator int() const; };
1834 struct Aggregate { Target a, b; };
1835 Target t;
1836 Target make();
1837
1838 template <typename T> struct $smart_ptr[[smart_ptr]] {
1839 T& operator*();
1840 T* operator->();
1841 T* get();
1842 };
1843 )cpp");
1844 auto TU = TestTU::withHeaderCode(HeaderA.code());
1845 for (const llvm::StringRef Case : {
1846 "str^uct Target;",
1847 "T^arget x;",
1848 "Target ^x;",
1849 "a^uto x = Target{};",
1850 "namespace m { Target tgt; } auto x = m^::tgt;",
1851 "Target funcCall(); auto x = ^funcCall();",
1852 "Aggregate a = { {}, ^{} };",
1853 "Aggregate a = { ^.a=t, };",
1854 "struct X { Target a; X() : ^a() {} };",
1855 "^using T = Target; ^T foo();",
1856 "^template <int> Target foo();",
1857 "void x() { try {} ^catch(Target e) {} }",
1858 "void x() { ^throw t; }",
1859 "int x() { ^return t; }",
1860 "void x() { ^switch(t) {} }",
1861 "void x() { ^delete (Target*)nullptr; }",
1862 "Target& ^tref = t;",
1863 "void x() { ^if (t) {} }",
1864 "void x() { ^while (t) {} }",
1865 "void x() { ^do { } while (t); }",
1866 "void x() { ^make(); }",
1867 "void x(smart_ptr<Target> &t) { t.^get(); }",
1868 "^auto x = []() { return t; };",
1869 "Target* ^tptr = &t;",
1870 "Target ^tarray[3];",
1871 }) {
1872 Annotations A(Case);
1873 TU.Code = A.code().str();
1874 ParsedAST AST = TU.build();
1875
1876 ASSERT_GT(A.points().size(), 0u) << Case;
1877 for (auto Pos : A.points())
1878 EXPECT_THAT(findType(AST, Pos),
1879 ElementsAre(
1880 sym("Target", HeaderA.range("Target"), HeaderA.range("Target"))))
1881 << Case;
1882 }
1883
1884 for (const llvm::StringRef Case : {
1885 "smart_ptr<Target> ^tsmart;",
1886 }) {
1887 Annotations A(Case);
1888 TU.Code = A.code().str();
1889 ParsedAST AST = TU.build();
1890
1891 EXPECT_THAT(findType(AST, A.point()),
1892 UnorderedElementsAre(
1893 sym("Target", HeaderA.range("Target"), HeaderA.range("Target")),
1894 sym("smart_ptr", HeaderA.range("smart_ptr"), HeaderA.range("smart_ptr"))
1895 ))
1896 << Case;
1897 }
1898 }
1899
1900 void checkFindRefs(llvm::StringRef Test, bool UseIndex = false) {
1901 Annotations T(Test);
1902 auto TU = TestTU::withCode(T.code());
1903 TU.ExtraArgs.push_back("-std=c++20");
1904
1905 auto AST = TU.build();
1906 std::vector<Matcher<ReferencesResult::Reference>> ExpectedLocations;
1907 for (const auto &[R, Context] : T.rangesWithPayload())
1908 ExpectedLocations.push_back(
1909 AllOf(rangeIs(R), containerIs(Context), attrsAre(0u)));
1910 // $def is actually shorthand for both definition and declaration.
1911 // If we have cases that are definition-only, we should change this.
1912 for (const auto &[R, Context] : T.rangesWithPayload("def"))
1913 ExpectedLocations.push_back(AllOf(rangeIs(R), containerIs(Context),
1914 attrsAre(ReferencesResult::Definition |
1915 ReferencesResult::Declaration)));
1916 for (const auto &[R, Context] : T.rangesWithPayload("decl"))
1917 ExpectedLocations.push_back(AllOf(rangeIs(R), containerIs(Context),
1918 attrsAre(ReferencesResult::Declaration)));
1919 for (const auto &[R, Context] : T.rangesWithPayload("overridedecl"))
1920 ExpectedLocations.push_back(AllOf(
1921 rangeIs(R), containerIs(Context),
1922 attrsAre(ReferencesResult::Declaration | ReferencesResult::Override)));
1923 for (const auto &[R, Context] : T.rangesWithPayload("overridedef"))
1924 ExpectedLocations.push_back(AllOf(rangeIs(R), containerIs(Context),
1925 attrsAre(ReferencesResult::Declaration |
1926 ReferencesResult::Definition |
1927 ReferencesResult::Override)));
1928 for (const auto &P : T.points()) {
1929 EXPECT_THAT(findReferences(AST, P, 0, UseIndex ? TU.index().get() : nullptr,
1930 /*AddContext*/ true)
1931 .References,
1932 UnorderedElementsAreArray(ExpectedLocations))
1933 << "Failed for Refs at " << P << "\n"
1934 << Test;
1935 }
1936 }
1937
1938 TEST(FindReferences, WithinAST) {
1939 const char *Tests[] = {
1940 R"cpp(// Local variable
1941 int main() {
1942 int $def(main)[[foo]];
1943 $(main)[[^foo]] = 2;
1944 int test1 = $(main)[[foo]];
1945 }
1946 )cpp",
1947
1948 R"cpp(// Struct
1949 namespace ns1 {
1950 struct $def(ns1)[[Foo]] {};
1951 } // namespace ns1
1952 int main() {
1953 ns1::$(main)[[Fo^o]]* Params;
1954 }
1955 )cpp",
1956
1957 R"cpp(// Forward declaration
1958 class $decl[[Foo]];
1959 class $def[[Foo]] {};
1960 int main() {
1961 $(main)[[Fo^o]] foo;
1962 }
1963 )cpp",
1964
1965 R"cpp(// Function
1966 int $def[[foo]](int) {}
1967 int main() {
1968 auto *X = &$(main)[[^foo]];
1969 $(main)[[foo]](42);
1970 }
1971 )cpp",
1972
1973 R"cpp(// Field
1974 struct Foo {
1975 int $def(Foo)[[foo]];
1976 Foo() : $(Foo::Foo)[[foo]](0) {}
1977 };
1978 int main() {
1979 Foo f;
1980 f.$(main)[[f^oo]] = 1;
1981 }
1982 )cpp",
1983
1984 R"cpp(// Method call
1985 struct Foo { int $decl(Foo)[[foo]](); };
1986 int Foo::$def(Foo)[[foo]]() {}
1987 int main() {
1988 Foo f;
1989 f.$(main)[[^foo]]();
1990 }
1991 )cpp",
1992
1993 R"cpp(// Constructor
1994 struct Foo {
1995 $decl(Foo)[[F^oo]](int);
1996 };
1997 void foo() {
1998 Foo f = $(foo)[[Foo]](42);
1999 }
2000 )cpp",
2001
2002 R"cpp(// Typedef
2003 typedef int $def[[Foo]];
2004 int main() {
2005 $(main)[[^Foo]] bar;
2006 }
2007 )cpp",
2008
2009 R"cpp(// Namespace
2010 namespace $decl[[ns]] { // FIXME: def?
2011 struct Foo {};
2012 } // namespace ns
2013 int main() { $(main)[[^ns]]::Foo foo; }
2014 )cpp",
2015
2016 R"cpp(// Macros
2017 #define TYPE(X) X
2018 #define FOO Foo
2019 #define CAT(X, Y) X##Y
2020 class $def[[Fo^o]] {};
2021 void test() {
2022 TYPE($(test)[[Foo]]) foo;
2023 $(test)[[FOO]] foo2;
2024 TYPE(TYPE($(test)[[Foo]])) foo3;
2025 $(test)[[CAT]](Fo, o) foo4;
2026 }
2027 )cpp",
2028
2029 R"cpp(// Macros
2030 #define $def[[MA^CRO]](X) (X+1)
2031 void test() {
2032 int x = $[[MACRO]]($[[MACRO]](1));
2033 }
2034 )cpp",
2035
2036 R"cpp(// Macro outside preamble
2037 int breakPreamble;
2038 #define $def[[MA^CRO]](X) (X+1)
2039 void test() {
2040 int x = $[[MACRO]]($[[MACRO]](1));
2041 }
2042 )cpp",
2043
2044 R"cpp(
2045 int $def[[v^ar]] = 0;
2046 void foo(int s = $(foo)[[var]]);
2047 )cpp",
2048
2049 R"cpp(
2050 template <typename T>
2051 class $def[[Fo^o]] {};
2052 void func($(func)[[Foo]]<int>);
2053 )cpp",
2054
2055 R"cpp(
2056 template <typename T>
2057 class $def[[Foo]] {};
2058 void func($(func)[[Fo^o]]<int>);
2059 )cpp",
2060 R"cpp(// Not touching any identifiers.
2061 struct Foo {
2062 $def(Foo)[[~]]Foo() {};
2063 };
2064 void foo() {
2065 Foo f;
2066 f.$(foo)[[^~]]Foo();
2067 }
2068 )cpp",
2069 R"cpp(// Lambda capture initializer
2070 void foo() {
2071 int $def(foo)[[w^aldo]] = 42;
2072 auto lambda = [x = $(foo)[[waldo]]](){};
2073 }
2074 )cpp",
2075 R"cpp(// Renaming alias
2076 template <typename> class Vector {};
2077 using $def[[^X]] = Vector<int>;
2078 $(x1)[[X]] x1;
2079 Vector<int> x2;
2080 Vector<double> y;
2081 )cpp",
2082 R"cpp(// Dependent code
2083 template <typename T> void $decl[[foo]](T t);
2084 template <typename T> void bar(T t) { $(bar)[[foo]](t); } // foo in bar is uninstantiated.
2085 void baz(int x) { $(baz)[[f^oo]](x); }
2086 )cpp",
2087 R"cpp(
2088 namespace ns {
2089 struct S{};
2090 void $decl(ns)[[foo]](S s);
2091 } // namespace ns
2092 template <typename T> void foo(T t);
2093 // FIXME: Maybe report this foo as a ref to ns::foo (because of ADL)
2094 // when bar<ns::S> is instantiated?
2095 template <typename T> void bar(T t) { foo(t); }
2096 void baz(int x) {
2097 ns::S s;
2098 bar<ns::S>(s);
2099 $(baz)[[f^oo]](s);
2100 }
2101 )cpp",
2102 R"cpp(// unresolved member expression
2103 struct Foo {
2104 template <typename T> void $decl(Foo)[[b^ar]](T t);
2105 };
2106 template <typename T> void test(Foo F, T t) {
2107 F.$(test)[[bar]](t);
2108 }
2109 )cpp",
2110
2111 // Enum base
2112 R"cpp(
2113 typedef int $def[[MyTypeD^ef]];
2114 enum MyEnum : $(MyEnum)[[MyTy^peDef]] { };
2115 )cpp",
2116 R"cpp(
2117 typedef int $def[[MyType^Def]];
2118 enum MyEnum : $(MyEnum)[[MyTypeD^ef]];
2119 )cpp",
2120 R"cpp(
2121 using $def[[MyTypeD^ef]] = int;
2122 enum MyEnum : $(MyEnum)[[MyTy^peDef]] { };
2123 )cpp",
2124 };
2125 for (const char *Test : Tests)
2126 checkFindRefs(Test);
2127 }
2128
2129 TEST(FindReferences, ConceptsWithinAST) {
2130 constexpr llvm::StringLiteral Code = R"cpp(
2131 template <class T>
2132 concept $def[[IsSmal^l]] = sizeof(T) <= 8;
2133
2134 template <class T>
2135 concept IsSmallPtr = requires(T x) {
2136 { *x } -> $(IsSmallPtr)[[IsSmal^l]];
2137 };
2138
2139 $(i)[[IsSmall]] auto i = 'c';
2140 template<$(foo)[[IsSmal^l]] U> void foo();
2141 template<class U> void bar() requires $(bar)[[IsSmal^l]]<U>;
2142 template<class U> requires $(baz)[[IsSmal^l]]<U> void baz();
2143 static_assert([[IsSma^ll]]<char>);
2144 )cpp";
2145 checkFindRefs(Code);
2146 }
2147
2148 TEST(FindReferences, ConceptReq) {
2149 constexpr llvm::StringLiteral Code = R"cpp(
2150 template <class T>
2151 concept $def[[IsSmal^l]] = sizeof(T) <= 8;
2152
2153 template <class T>
2154 concept IsSmallPtr = requires(T x) {
2155 { *x } -> $(IsSmallPtr)[[IsSmal^l]];
2156 };
2157 )cpp";
2158 checkFindRefs(Code);
2159 }
2160
2161 TEST(FindReferences, RequiresExprParameters) {
2162 constexpr llvm::StringLiteral Code = R"cpp(
2163 template <class T>
2164 concept IsSmall = sizeof(T) <= 8;
2165
2166 template <class T>
2167 concept IsSmallPtr = requires(T $def[[^x]]) {
2168 { *$(IsSmallPtr)[[^x]] } -> IsSmall;
2169 };
2170 )cpp";
2171 checkFindRefs(Code);
2172 }
2173
2174 TEST(FindReferences, IncludeOverrides) {
2175 llvm::StringRef Test =
2176 R"cpp(
2177 class Base {
2178 public:
2179 virtu^al void $decl(Base)[[f^unc]]() ^= ^0;
2180 };
2181 class Derived : public Base {
2182 public:
2183 void $overridedecl(Derived::func)[[func]]() override;
2184 };
2185 void Derived::$overridedef[[func]]() {}
2186 class Derived2 : public Base {
2187 void $overridedef(Derived2::func)[[func]]() override {}
2188 };
2189 void test(Derived* D, Base* B) {
2190 D->func(); // No references to the overrides.
2191 B->$(test)[[func]]();
2192 })cpp";
2193 checkFindRefs(Test, /*UseIndex=*/true);
2194 }
2195
2196 TEST(FindReferences, RefsToBaseMethod) {
2197 llvm::StringRef Test =
2198 R"cpp(
2199 class BaseBase {
2200 public:
2201 virtual void $(BaseBase)[[func]]();
2202 };
2203 class Base : public BaseBase {
2204 public:
2205 void $(Base)[[func]]() override;
2206 };
2207 class Derived : public Base {
2208 public:
2209 void $decl(Derived)[[fu^nc]]() over^ride;
2210 };
2211 void test(BaseBase* BB, Base* B, Derived* D) {
2212 // refs to overridden methods in complete type hierarchy are reported.
2213 BB->$(test)[[func]]();
2214 B->$(test)[[func]]();
2215 D->$(test)[[fu^nc]]();
2216 })cpp";
2217 checkFindRefs(Test, /*UseIndex=*/true);
2218 }
2219
2220 TEST(FindReferences, MainFileReferencesOnly) {
2221 llvm::StringRef Test =
2222 R"cpp(
2223 void test() {
2224 int [[fo^o]] = 1;
2225 // refs not from main file should not be included.
2226 #include "foo.inc"
2227 })cpp";
2228
2229 Annotations Code(Test);
2230 auto TU = TestTU::withCode(Code.code());
2231 TU.AdditionalFiles["foo.inc"] = R"cpp(
2232 foo = 3;
2233 )cpp";
2234 auto AST = TU.build();
2235
2236 std::vector<Matcher<ReferencesResult::Reference>> ExpectedLocations;
2237 for (const auto &R : Code.ranges())
2238 ExpectedLocations.push_back(rangeIs(R));
2239 EXPECT_THAT(findReferences(AST, Code.point(), 0).References,
2240 ElementsAreArray(ExpectedLocations))
2241 << Test;
2242 }
2243
2244 TEST(FindReferences, ExplicitSymbols) {
2245 const char *Tests[] = {
2246 R"cpp(
2247 struct Foo { Foo* $decl(Foo)[[self]]() const; };
2248 void f() {
2249 Foo foo;
2250 if (Foo* T = foo.$(f)[[^self]]()) {} // Foo member call expr.
2251 }
2252 )cpp",
2253
2254 R"cpp(
2255 struct Foo { Foo(int); };
2256 Foo f() {
2257 int $def(f)[[b]];
2258 return $(f)[[^b]]; // Foo constructor expr.
2259 }
2260 )cpp",
2261
2262 R"cpp(
2263 struct Foo {};
2264 void g(Foo);
2265 Foo $decl[[f]]();
2266 void call() {
2267 g($(call)[[^f]]()); // Foo constructor expr.
2268 }
2269 )cpp",
2270
2271 R"cpp(
2272 void $decl[[foo]](int);
2273 void $decl[[foo]](double);
2274
2275 namespace ns {
2276 using ::$decl(ns)[[fo^o]];
2277 }
2278 )cpp",
2279
2280 R"cpp(
2281 struct X {
2282 operator bool();
2283 };
2284
2285 int test() {
2286 X $def(test)[[a]];
2287 $(test)[[a]].operator bool();
2288 if ($(test)[[a^]]) {} // ignore implicit conversion-operator AST node
2289 }
2290 )cpp",
2291 };
2292 for (const char *Test : Tests)
2293 checkFindRefs(Test);
2294 }
2295
2296 TEST(FindReferences, NeedsIndexForSymbols) {
2297 const char *Header = "int foo();";
2298 Annotations Main("int main() { [[f^oo]](); }");
2299 TestTU TU;
2300 TU.Code = std::string(Main.code());
2301 TU.HeaderCode = Header;
2302 auto AST = TU.build();
2303
2304 // References in main file are returned without index.
2305 EXPECT_THAT(
2306 findReferences(AST, Main.point(), 0, /*Index=*/nullptr).References,
2307 ElementsAre(rangeIs(Main.range())));
2308 Annotations IndexedMain(R"cpp(
2309 int $decl[[foo]]() { return 42; }
2310 void bar() { $bar(bar)[[foo]](); }
2311 struct S { void bar() { $S(S::bar)[[foo]](); } };
2312 namespace N { void bar() { $N(N::bar)[[foo]](); } }
2313 )cpp");
2314
2315 // References from indexed files are included.
2316 TestTU IndexedTU;
2317 IndexedTU.Code = std::string(IndexedMain.code());
2318 IndexedTU.Filename = "Indexed.cpp";
2319 IndexedTU.HeaderCode = Header;
2320 EXPECT_THAT(
2321 findReferences(AST, Main.point(), 0, IndexedTU.index().get(),
2322 /*AddContext*/ true)
2323 .References,
2324 ElementsAre(
2325 rangeIs(Main.range()),
2326 AllOf(rangeIs(IndexedMain.range("decl")),
2327 attrsAre(ReferencesResult::Declaration |
2328 ReferencesResult::Definition)),
2329 AllOf(rangeIs(IndexedMain.range("bar")), containerIs("bar")),
2330 AllOf(rangeIs(IndexedMain.range("S")), containerIs("S::bar")),
2331 AllOf(rangeIs(IndexedMain.range("N")), containerIs("N::bar"))));
2332 auto LimitRefs =
2333 findReferences(AST, Main.point(), /*Limit*/ 1, IndexedTU.index().get());
2334 EXPECT_EQ(1u, LimitRefs.References.size());
2335 EXPECT_TRUE(LimitRefs.HasMore);
2336
2337 // Avoid indexed results for the main file. Use AST for the mainfile.
2338 TU.Code = ("\n\n" + Main.code()).str();
2339 EXPECT_THAT(findReferences(AST, Main.point(), 0, TU.index().get()).References,
2340 ElementsAre(rangeIs(Main.range())));
2341 }
2342
2343 TEST(FindReferences, NeedsIndexForMacro) {
2344 const char *Header = "#define MACRO(X) (X+1)";
2345 Annotations Main(R"cpp(
2346 int main() {
2347 int a = [[MA^CRO]](1);
2348 }
2349 )cpp");
2350 TestTU TU;
2351 TU.Code = std::string(Main.code());
2352 TU.HeaderCode = Header;
2353 auto AST = TU.build();
2354
2355 // References in main file are returned without index.
2356 EXPECT_THAT(
2357 findReferences(AST, Main.point(), 0, /*Index=*/nullptr).References,
2358 ElementsAre(rangeIs(Main.range())));
2359
2360 Annotations IndexedMain(R"cpp(
2361 int indexed_main() {
2362 int a = [[MACRO]](1);
2363 }
2364 )cpp");
2365
2366 // References from indexed files are included.
2367 TestTU IndexedTU;
2368 IndexedTU.Code = std::string(IndexedMain.code());
2369 IndexedTU.Filename = "Indexed.cpp";
2370 IndexedTU.HeaderCode = Header;
2371 EXPECT_THAT(
2372 findReferences(AST, Main.point(), 0, IndexedTU.index().get()).References,
2373 ElementsAre(rangeIs(Main.range()), rangeIs(IndexedMain.range())));
2374 auto LimitRefs =
2375 findReferences(AST, Main.point(), /*Limit*/ 1, IndexedTU.index().get());
2376 EXPECT_EQ(1u, LimitRefs.References.size());
2377 EXPECT_TRUE(LimitRefs.HasMore);
2378 }
2379
2380 TEST(FindReferences, NoQueryForLocalSymbols) {
2381 struct RecordingIndex : public MemIndex {
2382 mutable std::optional<llvm::DenseSet<SymbolID>> RefIDs;
2383 bool refs(const RefsRequest &Req,
2384 llvm::function_ref<void(const Ref &)>) const override {
2385 RefIDs = Req.IDs;
2386 return false;
2387 }
2388 };
2389
2390 struct Test {
2391 StringRef AnnotatedCode;
2392 bool WantQuery;
2393 } Tests[] = {
2394 {"int ^x;", true},
2395 // For now we don't assume header structure which would allow skipping.
2396 {"namespace { int ^x; }", true},
2397 {"static int ^x;", true},
2398 // Anything in a function certainly can't be referenced though.
2399 {"void foo() { int ^x; }", false},
2400 {"void foo() { struct ^x{}; }", false},
2401 {"auto lambda = []{ int ^x; };", false},
2402 };
2403 for (Test T : Tests) {
2404 Annotations File(T.AnnotatedCode);
2405 RecordingIndex Rec;
2406 auto AST = TestTU::withCode(File.code()).build();
2407 findReferences(AST, File.point(), 0, &Rec);
2408 if (T.WantQuery)
2409 EXPECT_NE(Rec.RefIDs, std::nullopt) << T.AnnotatedCode;
2410 else
2411 EXPECT_EQ(Rec.RefIDs, std::nullopt) << T.AnnotatedCode;
2412 }
2413 }
2414
2415 TEST(GetNonLocalDeclRefs, All) {
2416 struct Case {
2417 llvm::StringRef AnnotatedCode;
2418 std::vector<std::string> ExpectedDecls;
2419 } Cases[] = {
2420 {
2421 // VarDecl and ParamVarDecl
2422 R"cpp(
2423 void bar();
2424 void ^foo(int baz) {
2425 int x = 10;
2426 bar();
2427 })cpp",
2428 {"bar"},
2429 },
2430 {
2431 // Method from class
2432 R"cpp(
2433 class Foo { public: void foo(); };
2434 class Bar {
2435 void foo();
2436 void bar();
2437 };
2438 void Bar::^foo() {
2439 Foo f;
2440 bar();
2441 f.foo();
2442 })cpp",
2443 {"Bar", "Bar::bar", "Foo", "Foo::foo"},
2444 },
2445 {
2446 // Local types
2447 R"cpp(
2448 void ^foo() {
2449 class Foo { public: void foo() {} };
2450 class Bar { public: void bar() {} };
2451 Foo f;
2452 Bar b;
2453 b.bar();
2454 f.foo();
2455 })cpp",
2456 {},
2457 },
2458 {
2459 // Template params
2460 R"cpp(
2461 template <typename T, template<typename> class Q>
2462 void ^foo() {
2463 T x;
2464 Q<T> y;
2465 })cpp",
2466 {},
2467 },
2468 };
2469 for (const Case &C : Cases) {
2470 Annotations File(C.AnnotatedCode);
2471 auto AST = TestTU::withCode(File.code()).build();
2472 SourceLocation SL = llvm::cantFail(
2473 sourceLocationInMainFile(AST.getSourceManager(), File.point()));
2474
2475 const FunctionDecl *FD =
2476 llvm::dyn_cast<FunctionDecl>(&findDecl(AST, [SL](const NamedDecl &ND) {
2477 return ND.getLocation() == SL && llvm::isa<FunctionDecl>(ND);
2478 }));
2479 ASSERT_NE(FD, nullptr);
2480
2481 auto NonLocalDeclRefs = getNonLocalDeclRefs(AST, FD);
2482 std::vector<std::string> Names;
2483 for (const Decl *D : NonLocalDeclRefs) {
2484 if (const auto *ND = llvm::dyn_cast<NamedDecl>(D))
2485 Names.push_back(ND->getQualifiedNameAsString());
2486 }
2487 EXPECT_THAT(Names, UnorderedElementsAreArray(C.ExpectedDecls))
2488 << File.code();
2489 }
2490 }
2491
2492 TEST(DocumentLinks, All) {
2493 Annotations MainCpp(R"cpp(
2494 #/*comments*/include /*comments*/ $foo[["foo.h"]] //more comments
2495 int end_of_preamble = 0;
2496 #include $bar[[<bar.h>]]
2497 )cpp");
2498
2499 TestTU TU;
2500 TU.Code = std::string(MainCpp.code());
2501 TU.AdditionalFiles = {{"foo.h", ""}, {"bar.h", ""}};
2502 TU.ExtraArgs = {"-isystem."};
2503 auto AST = TU.build();
2504
2505 EXPECT_THAT(
2506 clangd::getDocumentLinks(AST),
2507 ElementsAre(
2508 DocumentLink({MainCpp.range("foo"),
2509 URIForFile::canonicalize(testPath("foo.h"), "")}),
2510 DocumentLink({MainCpp.range("bar"),
2511 URIForFile::canonicalize(testPath("bar.h"), "")})));
2512 }
2513
2514 } // namespace
2515 } // namespace clangd
2516 } // namespace clang