1 //===-- FindTargetTests.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 "FindTarget.h"
9 
10 #include "Selection.h"
11 #include "TestTU.h"
12 #include "clang/AST/Decl.h"
13 #include "clang/AST/DeclTemplate.h"
14 #include "clang/Basic/SourceLocation.h"
15 #include "llvm/ADT/StringRef.h"
16 #include "llvm/Support/Casting.h"
17 #include "llvm/Support/raw_ostream.h"
18 #include "llvm/Testing/Support/Annotations.h"
19 #include "gmock/gmock.h"
20 #include "gtest/gtest.h"
21 #include <initializer_list>
22 
23 namespace clang {
24 namespace clangd {
25 namespace {
26 
27 // A referenced Decl together with its DeclRelationSet, for assertions.
28 //
29 // There's no great way to assert on the "content" of a Decl in the general case
30 // that's both expressive and unambiguous (e.g. clearly distinguishes between
31 // templated decls and their specializations).
32 //
33 // We use the result of pretty-printing the decl, with the {body} truncated.
34 struct PrintedDecl {
PrintedDeclclang::clangd::__anond1dea4c80111::PrintedDecl35   PrintedDecl(const char *Name, DeclRelationSet Relations = {})
36       : Name(Name), Relations(Relations) {}
PrintedDeclclang::clangd::__anond1dea4c80111::PrintedDecl37   PrintedDecl(const NamedDecl *D, DeclRelationSet Relations = {})
38       : Relations(Relations) {
39     std::string S;
40     llvm::raw_string_ostream OS(S);
41     D->print(OS);
42     llvm::StringRef FirstLine =
__anond1dea4c80202(char C) 43         llvm::StringRef(OS.str()).take_until([](char C) { return C == '\n'; });
44     FirstLine = FirstLine.rtrim(" {");
45     Name = std::string(FirstLine.rtrim(" {"));
46   }
47 
48   std::string Name;
49   DeclRelationSet Relations;
50 };
operator ==(const PrintedDecl & L,const PrintedDecl & R)51 bool operator==(const PrintedDecl &L, const PrintedDecl &R) {
52   return std::tie(L.Name, L.Relations) == std::tie(R.Name, R.Relations);
53 }
operator <<(llvm::raw_ostream & OS,const PrintedDecl & D)54 llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const PrintedDecl &D) {
55   return OS << D.Name << " Rel=" << D.Relations;
56 }
57 
58 // The test cases in for targetDecl() take the form
59 //  - a piece of code (Code = "...")
60 //  - Code should have a single AST node marked as a [[range]]
61 //  - an EXPECT_DECLS() assertion that verify the type of node selected, and
62 //    all the decls that targetDecl() considers it to reference
63 // Despite the name, these cases actually test allTargetDecls() for brevity.
64 class TargetDeclTest : public ::testing::Test {
65 protected:
66   using Rel = DeclRelation;
67   std::string Code;
68   std::vector<std::string> Flags;
69 
70   // Asserts that `Code` has a marked selection of a node `NodeType`,
71   // and returns allTargetDecls() as PrintedDecl structs.
72   // Use via EXPECT_DECLS().
assertNodeAndPrintDecls(const char * NodeType)73   std::vector<PrintedDecl> assertNodeAndPrintDecls(const char *NodeType) {
74     llvm::Annotations A(Code);
75     auto TU = TestTU::withCode(A.code());
76     TU.ExtraArgs = Flags;
77     auto AST = TU.build();
78     llvm::Annotations::Range R = A.range();
79     auto Selection = SelectionTree::createRight(
80         AST.getASTContext(), AST.getTokens(), R.Begin, R.End);
81     const SelectionTree::Node *N = Selection.commonAncestor();
82     if (!N) {
83       ADD_FAILURE() << "No node selected!\n" << Code;
84       return {};
85     }
86     EXPECT_EQ(N->kind(), NodeType) << Selection;
87 
88     std::vector<PrintedDecl> ActualDecls;
89     for (const auto &Entry :
90          allTargetDecls(N->ASTNode, AST.getHeuristicResolver()))
91       ActualDecls.emplace_back(Entry.first, Entry.second);
92     return ActualDecls;
93   }
94 };
95 
96 // This is a macro to preserve line numbers in assertion failures.
97 // It takes the expected decls as varargs to work around comma-in-macro issues.
98 #define EXPECT_DECLS(NodeType, ...)                                            \
99   EXPECT_THAT(assertNodeAndPrintDecls(NodeType),                               \
100               ::testing::UnorderedElementsAreArray(                            \
101                   std::vector<PrintedDecl>({__VA_ARGS__})))                    \
102       << Code
103 using ExpectedDecls = std::vector<PrintedDecl>;
104 
TEST_F(TargetDeclTest,Exprs)105 TEST_F(TargetDeclTest, Exprs) {
106   Code = R"cpp(
107     int f();
108     int x = [[f]]();
109   )cpp";
110   EXPECT_DECLS("DeclRefExpr", "int f()");
111 
112   Code = R"cpp(
113     struct S { S operator+(S) const; };
114     auto X = S() [[+]] S();
115   )cpp";
116   EXPECT_DECLS("DeclRefExpr", "S operator+(S) const");
117 
118   Code = R"cpp(
119     int foo();
120     int s = foo[[()]];
121   )cpp";
122   EXPECT_DECLS("CallExpr", "int foo()");
123 
124   Code = R"cpp(
125     struct X {
126     void operator()(int n);
127     };
128     void test() {
129       X x;
130       x[[(123)]];
131     }
132   )cpp";
133   EXPECT_DECLS("CXXOperatorCallExpr", "void operator()(int n)");
134 
135   Code = R"cpp(
136     void test() {
137       goto [[label]];
138     label:
139       return;
140     }
141   )cpp";
142   EXPECT_DECLS("GotoStmt", "label:");
143   Code = R"cpp(
144     void test() {
145     [[label]]:
146       return;
147     }
148   )cpp";
149   EXPECT_DECLS("LabelStmt", "label:");
150 }
151 
TEST_F(TargetDeclTest,RecoveryForC)152 TEST_F(TargetDeclTest, RecoveryForC) {
153   Flags = {"-xc", "-Xclang", "-frecovery-ast"};
154   Code = R"cpp(
155     // error-ok: testing behavior on broken code
156     // int f();
157     int f(int);
158     int x = [[f]]();
159   )cpp";
160   EXPECT_DECLS("DeclRefExpr", "int f(int)");
161 }
162 
TEST_F(TargetDeclTest,Recovery)163 TEST_F(TargetDeclTest, Recovery) {
164   Code = R"cpp(
165     // error-ok: testing behavior on broken code
166     int f();
167     int f(int, int);
168     int x = [[f]](42);
169   )cpp";
170   EXPECT_DECLS("UnresolvedLookupExpr", "int f()", "int f(int, int)");
171 }
172 
TEST_F(TargetDeclTest,RecoveryType)173 TEST_F(TargetDeclTest, RecoveryType) {
174   Code = R"cpp(
175     // error-ok: testing behavior on broken code
176     struct S { int member; };
177     S overloaded(int);
178     void foo() {
179       // No overload matches, but we have recovery-expr with the correct type.
180       overloaded().[[member]];
181     }
182   )cpp";
183   EXPECT_DECLS("MemberExpr", "int member");
184 }
185 
TEST_F(TargetDeclTest,UsingDecl)186 TEST_F(TargetDeclTest, UsingDecl) {
187   Code = R"cpp(
188     namespace foo {
189       int f(int);
190       int f(char);
191     }
192     using foo::f;
193     int x = [[f]](42);
194   )cpp";
195   // f(char) is not referenced!
196   EXPECT_DECLS("DeclRefExpr", {"using foo::f", Rel::Alias}, {"int f(int)"});
197 
198   Code = R"cpp(
199     namespace foo {
200       int f(int);
201       int f(char);
202     }
203     [[using foo::f]];
204   )cpp";
205   // All overloads are referenced.
206   EXPECT_DECLS("UsingDecl", {"using foo::f", Rel::Alias}, {"int f(int)"},
207                {"int f(char)"});
208 
209   Code = R"cpp(
210     struct X {
211       int foo();
212     };
213     struct Y : X {
214       using X::foo;
215     };
216     int x = Y().[[foo]]();
217   )cpp";
218   EXPECT_DECLS("MemberExpr", {"using X::foo", Rel::Alias}, {"int foo()"});
219 
220   Code = R"cpp(
221       template <typename T>
222       struct Base {
223         void waldo() {}
224       };
225       template <typename T>
226       struct Derived : Base<T> {
227         using Base<T>::[[waldo]];
228       };
229     )cpp";
230   EXPECT_DECLS("UnresolvedUsingValueDecl", {"using Base<T>::waldo", Rel::Alias},
231                {"void waldo()"});
232 
233   Code = R"cpp(
234     namespace ns {
235     template<typename T> class S {};
236     }
237 
238     using ns::S;
239 
240     template<typename T>
241     using A = [[S]]<T>;
242   )cpp";
243   EXPECT_DECLS("TemplateSpecializationTypeLoc", {"using ns::S", Rel::Alias},
244                {"template <typename T> class S"},
245                {"class S", Rel::TemplatePattern});
246 
247   Code = R"cpp(
248     namespace ns {
249     template<typename T> class S {};
250     }
251 
252     using ns::S;
253     template <template <typename> class T> class X {};
254     using B = X<[[S]]>;
255   )cpp";
256   EXPECT_DECLS("TemplateArgumentLoc", {"using ns::S", Rel::Alias},
257                {"template <typename T> class S"});
258 
259   Code = R"cpp(
260     namespace ns {
261     template<typename T> class S { public: S(T); };
262     }
263 
264     using ns::S;
265     [[S]] s(123);
266   )cpp";
267   Flags.push_back("-std=c++17"); // For CTAD feature.
268   EXPECT_DECLS("DeducedTemplateSpecializationTypeLoc",
269                {"using ns::S", Rel::Alias}, {"template <typename T> class S"},
270                {"class S", Rel::TemplatePattern});
271 
272   Code = R"cpp(
273     template<typename T>
274     class Foo { public: class foo {}; };
275     template <class T> class A : public Foo<T> {
276       using typename Foo<T>::foo;
277       [[foo]] abc;
278     };
279   )cpp";
280   EXPECT_DECLS("UnresolvedUsingTypeLoc",
281                {"using typename Foo<T>::foo", Rel::Alias});
282 }
283 
TEST_F(TargetDeclTest,BaseSpecifier)284 TEST_F(TargetDeclTest, BaseSpecifier) {
285   Code = R"cpp(
286     struct X {};
287     struct Y : [[private]] X {};
288   )cpp";
289   EXPECT_DECLS("CXXBaseSpecifier", "struct X");
290   Code = R"cpp(
291     struct X {};
292     struct Y : [[private X]] {};
293   )cpp";
294   EXPECT_DECLS("CXXBaseSpecifier", "struct X");
295   Code = R"cpp(
296     struct X {};
297     struct Y : private [[X]] {};
298   )cpp";
299   EXPECT_DECLS("RecordTypeLoc", "struct X");
300 }
301 
TEST_F(TargetDeclTest,ConstructorInitList)302 TEST_F(TargetDeclTest, ConstructorInitList) {
303   Code = R"cpp(
304     struct X {
305       int a;
306       X() : [[a]](42) {}
307     };
308   )cpp";
309   EXPECT_DECLS("CXXCtorInitializer", "int a");
310 
311   Code = R"cpp(
312     struct X {
313       X() : [[X]](1) {}
314       X(int);
315     };
316   )cpp";
317   EXPECT_DECLS("RecordTypeLoc", "struct X");
318 }
319 
TEST_F(TargetDeclTest,DesignatedInit)320 TEST_F(TargetDeclTest, DesignatedInit) {
321   Flags = {"-xc"}; // array designators are a C99 extension.
322   Code = R"c(
323     struct X { int a; };
324     struct Y { int b; struct X c[2]; };
325     struct Y y = { .c[0].[[a]] = 1 };
326   )c";
327   EXPECT_DECLS("DesignatedInitExpr", "int a");
328 }
329 
TEST_F(TargetDeclTest,NestedNameSpecifier)330 TEST_F(TargetDeclTest, NestedNameSpecifier) {
331   Code = R"cpp(
332     namespace a { namespace b { int c; } }
333     int x = a::[[b::]]c;
334   )cpp";
335   EXPECT_DECLS("NestedNameSpecifierLoc", "namespace b");
336 
337   Code = R"cpp(
338     namespace a { struct X { enum { y }; }; }
339     int x = a::[[X::]]y;
340   )cpp";
341   EXPECT_DECLS("NestedNameSpecifierLoc", "struct X");
342 
343   Code = R"cpp(
344     template <typename T>
345     int x = [[T::]]y;
346   )cpp";
347   EXPECT_DECLS("NestedNameSpecifierLoc", "typename T");
348 
349   Code = R"cpp(
350     namespace a { int x; }
351     namespace b = a;
352     int y = [[b]]::x;
353   )cpp";
354   EXPECT_DECLS("NestedNameSpecifierLoc", {"namespace b = a", Rel::Alias},
355                {"namespace a", Rel::Underlying});
356 }
357 
TEST_F(TargetDeclTest,Types)358 TEST_F(TargetDeclTest, Types) {
359   Code = R"cpp(
360     struct X{};
361     [[X]] x;
362   )cpp";
363   EXPECT_DECLS("RecordTypeLoc", "struct X");
364 
365   Code = R"cpp(
366     struct S{};
367     typedef S X;
368     [[X]] x;
369   )cpp";
370   EXPECT_DECLS("TypedefTypeLoc", {"typedef S X", Rel::Alias},
371                {"struct S", Rel::Underlying});
372   Code = R"cpp(
373     namespace ns { struct S{}; }
374     typedef ns::S X;
375     [[X]] x;
376   )cpp";
377   EXPECT_DECLS("TypedefTypeLoc", {"typedef ns::S X", Rel::Alias},
378                {"struct S", Rel::Underlying});
379 
380   Code = R"cpp(
381     template<class T>
382     void foo() { [[T]] x; }
383   )cpp";
384   EXPECT_DECLS("TemplateTypeParmTypeLoc", "class T");
385   Flags.clear();
386 
387   Code = R"cpp(
388     template<template<typename> class T>
389     void foo() { [[T<int>]] x; }
390   )cpp";
391   EXPECT_DECLS("TemplateSpecializationTypeLoc", "template <typename> class T");
392   Flags.clear();
393 
394   Code = R"cpp(
395   template<template<typename> class ...T>
396   class C {
397     C<[[T...]]> foo;
398     };
399   )cpp";
400   EXPECT_DECLS("TemplateArgumentLoc", {"template <typename> class ...T"});
401   Flags.clear();
402 
403   Code = R"cpp(
404     struct S{};
405     S X;
406     [[decltype]](X) Y;
407   )cpp";
408   EXPECT_DECLS("DecltypeTypeLoc", {"struct S", Rel::Underlying});
409 
410   Code = R"cpp(
411     struct S{};
412     [[auto]] X = S{};
413   )cpp";
414   // FIXME: deduced type missing in AST. https://llvm.org/PR42914
415   EXPECT_DECLS("AutoTypeLoc");
416 
417   Code = R"cpp(
418     template <typename... E>
419     struct S {
420       static const int size = sizeof...([[E]]);
421     };
422   )cpp";
423   EXPECT_DECLS("SizeOfPackExpr", "typename ...E");
424 
425   Code = R"cpp(
426     template <typename T>
427     class Foo {
428       void f([[Foo]] x);
429     };
430   )cpp";
431   EXPECT_DECLS("InjectedClassNameTypeLoc", "class Foo");
432 }
433 
TEST_F(TargetDeclTest,ClassTemplate)434 TEST_F(TargetDeclTest, ClassTemplate) {
435   Code = R"cpp(
436     // Implicit specialization.
437     template<int x> class Foo{};
438     [[Foo<42>]] B;
439   )cpp";
440   EXPECT_DECLS("TemplateSpecializationTypeLoc",
441                {"template<> class Foo<42>", Rel::TemplateInstantiation},
442                {"class Foo", Rel::TemplatePattern});
443 
444   Code = R"cpp(
445     template<typename T> class Foo {};
446     // The "Foo<int>" SpecializationDecl is incomplete, there is no
447     // instantiation happening.
448     void func([[Foo<int>]] *);
449   )cpp";
450   EXPECT_DECLS("TemplateSpecializationTypeLoc",
451                {"class Foo", Rel::TemplatePattern},
452                {"template<> class Foo<int>", Rel::TemplateInstantiation});
453 
454   Code = R"cpp(
455     // Explicit specialization.
456     template<int x> class Foo{};
457     template<> class Foo<42>{};
458     [[Foo<42>]] B;
459   )cpp";
460   EXPECT_DECLS("TemplateSpecializationTypeLoc", "template<> class Foo<42>");
461 
462   Code = R"cpp(
463     // Partial specialization.
464     template<typename T> class Foo{};
465     template<typename T> class Foo<T*>{};
466     [[Foo<int*>]] B;
467   )cpp";
468   EXPECT_DECLS("TemplateSpecializationTypeLoc",
469                {"template<> class Foo<int *>", Rel::TemplateInstantiation},
470                {"template <typename T> class Foo<T *>", Rel::TemplatePattern});
471 
472   Code = R"cpp(
473     // Template template argument.
474     template<typename T> struct Vector {};
475     template <template <typename> class Container>
476     struct A {};
477     A<[[Vector]]> a;
478   )cpp";
479   EXPECT_DECLS("TemplateArgumentLoc", {"template <typename T> struct Vector"});
480 
481   Flags.push_back("-std=c++17"); // for CTAD tests
482 
483   Code = R"cpp(
484     // Class template argument deduction
485     template <typename T>
486     struct Test {
487       Test(T);
488     };
489     void foo() {
490       [[Test]] a(5);
491     }
492   )cpp";
493   EXPECT_DECLS("DeducedTemplateSpecializationTypeLoc",
494                {"struct Test", Rel::TemplatePattern});
495 
496   Code = R"cpp(
497     // Deduction guide
498     template <typename T>
499     struct Test {
500       template <typename I>
501       Test(I, I);
502     };
503     template <typename I>
504     [[Test]](I, I) -> Test<typename I::type>;
505   )cpp";
506   EXPECT_DECLS("CXXDeductionGuideDecl", {"template <typename T> struct Test"});
507 }
508 
TEST_F(TargetDeclTest,Concept)509 TEST_F(TargetDeclTest, Concept) {
510   Flags.push_back("-std=c++20");
511 
512   // FIXME: Should we truncate the pretty-printed form of a concept decl
513   // somewhere?
514 
515   Code = R"cpp(
516     template <typename T>
517     concept Fooable = requires (T t) { t.foo(); };
518 
519     template <typename T> requires [[Fooable]]<T>
520     void bar(T t) {
521       t.foo();
522     }
523   )cpp";
524   EXPECT_DECLS(
525       "ConceptSpecializationExpr",
526       {"template <typename T> concept Fooable = requires (T t) { t.foo(); }"});
527 
528   // trailing requires clause
529   Code = R"cpp(
530       template <typename T>
531       concept Fooable = true;
532 
533       template <typename T>
534       void foo() requires [[Fooable]]<T>;
535   )cpp";
536   EXPECT_DECLS("ConceptSpecializationExpr",
537                {"template <typename T> concept Fooable = true"});
538 
539   // constrained-parameter
540   Code = R"cpp(
541     template <typename T>
542     concept Fooable = true;
543 
544     template <[[Fooable]] T>
545     void bar(T t);
546   )cpp";
547   EXPECT_DECLS("ConceptSpecializationExpr",
548                {"template <typename T> concept Fooable = true"});
549 
550   // partial-concept-id
551   Code = R"cpp(
552     template <typename T, typename U>
553     concept Fooable = true;
554 
555     template <[[Fooable]]<int> T>
556     void bar(T t);
557   )cpp";
558   EXPECT_DECLS("ConceptSpecializationExpr",
559                {"template <typename T, typename U> concept Fooable = true"});
560 }
561 
TEST_F(TargetDeclTest,Coroutine)562 TEST_F(TargetDeclTest, Coroutine) {
563   Flags.push_back("-std=c++20");
564 
565   Code = R"cpp(
566     namespace std::experimental {
567     template <typename, typename...> struct coroutine_traits;
568     template <typename> struct coroutine_handle {
569       template <typename U>
570       coroutine_handle(coroutine_handle<U>&&) noexcept;
571       static coroutine_handle from_address(void* __addr) noexcept;
572     };
573     } // namespace std::experimental
574 
575     struct executor {};
576     struct awaitable {};
577     struct awaitable_frame {
578       awaitable get_return_object();
579       void return_void();
580       void unhandled_exception();
581       struct result_t {
582         ~result_t();
583         bool await_ready() const noexcept;
584         void await_suspend(std::experimental::coroutine_handle<void>) noexcept;
585         void await_resume() const noexcept;
586       };
587       result_t initial_suspend() noexcept;
588       result_t final_suspend() noexcept;
589       result_t await_transform(executor) noexcept;
590     };
591 
592     namespace std::experimental {
593     template <>
594     struct coroutine_traits<awaitable> {
595       typedef awaitable_frame promise_type;
596     };
597     } // namespace std::experimental
598 
599     awaitable foo() {
600       co_await [[executor]]();
601     }
602   )cpp";
603   EXPECT_DECLS("RecordTypeLoc", "struct executor");
604 }
605 
TEST_F(TargetDeclTest,FunctionTemplate)606 TEST_F(TargetDeclTest, FunctionTemplate) {
607   Code = R"cpp(
608     // Implicit specialization.
609     template<typename T> bool foo(T) { return false; };
610     bool x = [[foo]](42);
611   )cpp";
612   EXPECT_DECLS("DeclRefExpr",
613                {"template<> bool foo<int>(int)", Rel::TemplateInstantiation},
614                {"bool foo(T)", Rel::TemplatePattern});
615 
616   Code = R"cpp(
617     // Explicit specialization.
618     template<typename T> bool foo(T) { return false; };
619     template<> bool foo<int>(int) { return false; };
620     bool x = [[foo]](42);
621   )cpp";
622   EXPECT_DECLS("DeclRefExpr", "template<> bool foo<int>(int)");
623 }
624 
TEST_F(TargetDeclTest,VariableTemplate)625 TEST_F(TargetDeclTest, VariableTemplate) {
626   // Pretty-printer doesn't do a very good job of variable templates :-(
627   Code = R"cpp(
628     // Implicit specialization.
629     template<typename T> int foo;
630     int x = [[foo]]<char>;
631   )cpp";
632   EXPECT_DECLS("DeclRefExpr", {"int foo", Rel::TemplateInstantiation},
633                {"int foo", Rel::TemplatePattern});
634 
635   Code = R"cpp(
636     // Explicit specialization.
637     template<typename T> int foo;
638     template <> bool foo<char>;
639     int x = [[foo]]<char>;
640   )cpp";
641   EXPECT_DECLS("DeclRefExpr", "bool foo");
642 
643   Code = R"cpp(
644     // Partial specialization.
645     template<typename T> int foo;
646     template<typename T> bool foo<T*>;
647     bool x = [[foo]]<char*>;
648   )cpp";
649   EXPECT_DECLS("DeclRefExpr", {"bool foo", Rel::TemplateInstantiation},
650                {"bool foo", Rel::TemplatePattern});
651 }
652 
TEST_F(TargetDeclTest,TypeAliasTemplate)653 TEST_F(TargetDeclTest, TypeAliasTemplate) {
654   Code = R"cpp(
655     template<typename T, int X> class SmallVector {};
656     template<typename U> using TinyVector = SmallVector<U, 1>;
657     [[TinyVector<int>]] X;
658   )cpp";
659   EXPECT_DECLS("TemplateSpecializationTypeLoc",
660                {"template<> class SmallVector<int, 1>",
661                 Rel::TemplateInstantiation | Rel::Underlying},
662                {"class SmallVector", Rel::TemplatePattern | Rel::Underlying},
663                {"using TinyVector = SmallVector<U, 1>",
664                 Rel::Alias | Rel::TemplatePattern});
665 }
666 
TEST_F(TargetDeclTest,MemberOfTemplate)667 TEST_F(TargetDeclTest, MemberOfTemplate) {
668   Code = R"cpp(
669     template <typename T> struct Foo {
670       int x(T);
671     };
672     int y = Foo<int>().[[x]](42);
673   )cpp";
674   EXPECT_DECLS("MemberExpr", {"int x(int)", Rel::TemplateInstantiation},
675                {"int x(T)", Rel::TemplatePattern});
676 
677   Code = R"cpp(
678     template <typename T> struct Foo {
679       template <typename U>
680       int x(T, U);
681     };
682     int y = Foo<char>().[[x]]('c', 42);
683   )cpp";
684   EXPECT_DECLS("MemberExpr",
685                {"template<> int x<int>(char, int)", Rel::TemplateInstantiation},
686                {"int x(T, U)", Rel::TemplatePattern});
687 }
688 
TEST_F(TargetDeclTest,Lambda)689 TEST_F(TargetDeclTest, Lambda) {
690   Code = R"cpp(
691     void foo(int x = 42) {
692       auto l = [ [[x]] ]{ return x + 1; };
693     };
694   )cpp";
695   EXPECT_DECLS("DeclRefExpr", "int x = 42");
696 
697   // It seems like this should refer to another var, with the outer param being
698   // an underlying decl. But it doesn't seem to exist.
699   Code = R"cpp(
700     void foo(int x = 42) {
701       auto l = [x]{ return [[x]] + 1; };
702     };
703   )cpp";
704   EXPECT_DECLS("DeclRefExpr", "int x = 42");
705 
706   Code = R"cpp(
707     void foo() {
708       auto l = [x = 1]{ return [[x]] + 1; };
709     };
710   )cpp";
711   // FIXME: why both auto and int?
712   EXPECT_DECLS("DeclRefExpr", "auto int x = 1");
713 }
714 
TEST_F(TargetDeclTest,OverloadExpr)715 TEST_F(TargetDeclTest, OverloadExpr) {
716   Flags.push_back("--target=x86_64-pc-linux-gnu");
717 
718   Code = R"cpp(
719     void func(int*);
720     void func(char*);
721 
722     template <class T>
723     void foo(T t) {
724       [[func]](t);
725     };
726   )cpp";
727   EXPECT_DECLS("UnresolvedLookupExpr", "void func(int *)", "void func(char *)");
728 
729   Code = R"cpp(
730     struct X {
731       void func(int*);
732       void func(char*);
733     };
734 
735     template <class T>
736     void foo(X x, T t) {
737       x.[[func]](t);
738     };
739   )cpp";
740   EXPECT_DECLS("UnresolvedMemberExpr", "void func(int *)", "void func(char *)");
741 
742   Code = R"cpp(
743     struct X {
744       static void *operator new(unsigned long);
745     };
746     auto* k = [[new]] X();
747   )cpp";
748   EXPECT_DECLS("CXXNewExpr", "static void *operator new(unsigned long)");
749   Code = R"cpp(
750     void *operator new(unsigned long);
751     auto* k = [[new]] int();
752   )cpp";
753   EXPECT_DECLS("CXXNewExpr", "void *operator new(unsigned long)");
754 
755   Code = R"cpp(
756     struct X {
757       static void operator delete(void *) noexcept;
758     };
759     void k(X* x) {
760       [[delete]] x;
761     }
762   )cpp";
763   EXPECT_DECLS("CXXDeleteExpr", "static void operator delete(void *) noexcept");
764   Code = R"cpp(
765     void operator delete(void *) noexcept;
766     void k(int* x) {
767       [[delete]] x;
768     }
769   )cpp";
770   EXPECT_DECLS("CXXDeleteExpr", "void operator delete(void *) noexcept");
771 }
772 
TEST_F(TargetDeclTest,DependentExprs)773 TEST_F(TargetDeclTest, DependentExprs) {
774   // Heuristic resolution of method of dependent field
775   Code = R"cpp(
776         struct A { void foo() {} };
777         template <typename T>
778         struct B {
779           A a;
780           void bar() {
781             this->a.[[foo]]();
782           }
783         };
784       )cpp";
785   EXPECT_DECLS("CXXDependentScopeMemberExpr", "void foo()");
786 
787   // Similar to above but base expression involves a function call.
788   Code = R"cpp(
789         struct A {
790           void foo() {}
791         };
792         struct B {
793           A getA();
794         };
795         template <typename T>
796         struct C {
797           B c;
798           void bar() {
799             this->c.getA().[[foo]]();
800           }
801         };
802       )cpp";
803   EXPECT_DECLS("CXXDependentScopeMemberExpr", "void foo()");
804 
805   // Similar to above but uses a function pointer.
806   Code = R"cpp(
807         struct A {
808           void foo() {}
809         };
810         struct B {
811           using FPtr = A(*)();
812           FPtr fptr;
813         };
814         template <typename T>
815         struct C {
816           B c;
817           void bar() {
818             this->c.fptr().[[foo]]();
819           }
820         };
821       )cpp";
822   EXPECT_DECLS("CXXDependentScopeMemberExpr", "void foo()");
823 
824   // Base expression involves a member access into this.
825   Code = R"cpp(
826         struct Bar {
827           int aaaa;
828         };
829         template <typename T> struct Foo {
830           Bar func(int);
831           void test() {
832             func(1).[[aaaa]];
833           }
834         };
835       )cpp";
836   EXPECT_DECLS("CXXDependentScopeMemberExpr", "int aaaa");
837 
838   Code = R"cpp(
839         class Foo {
840         public:
841           static Foo k(int);
842           template <typename T> T convert() const;
843         };
844         template <typename T>
845         void test() {
846           Foo::k(T()).template [[convert]]<T>();
847         }
848       )cpp";
849   EXPECT_DECLS("CXXDependentScopeMemberExpr",
850                "template <typename T> T convert() const");
851 }
852 
TEST_F(TargetDeclTest,DependentTypes)853 TEST_F(TargetDeclTest, DependentTypes) {
854   // Heuristic resolution of dependent type name
855   Code = R"cpp(
856         template <typename>
857         struct A { struct B {}; };
858 
859         template <typename T>
860         void foo(typename A<T>::[[B]]);
861       )cpp";
862   EXPECT_DECLS("DependentNameTypeLoc", "struct B");
863 
864   // Heuristic resolution of dependent type name which doesn't get a TypeLoc
865   Code = R"cpp(
866         template <typename>
867         struct A { struct B { struct C {}; }; };
868 
869         template <typename T>
870         void foo(typename A<T>::[[B]]::C);
871       )cpp";
872   EXPECT_DECLS("NestedNameSpecifierLoc", "struct B");
873 
874   // Heuristic resolution of dependent type name whose qualifier is also
875   // dependent
876   Code = R"cpp(
877         template <typename>
878         struct A { struct B { struct C {}; }; };
879 
880         template <typename T>
881         void foo(typename A<T>::B::[[C]]);
882       )cpp";
883   EXPECT_DECLS("DependentNameTypeLoc", "struct C");
884 
885   // Heuristic resolution of dependent template name
886   Code = R"cpp(
887         template <typename>
888         struct A {
889           template <typename> struct B {};
890         };
891 
892         template <typename T>
893         void foo(typename A<T>::template [[B]]<int>);
894       )cpp";
895   EXPECT_DECLS("DependentTemplateSpecializationTypeLoc",
896                "template <typename> struct B");
897 }
898 
TEST_F(TargetDeclTest,TypedefCascade)899 TEST_F(TargetDeclTest, TypedefCascade) {
900   Code = R"cpp(
901         struct C {
902           using type = int;
903         };
904         struct B {
905           using type = C::type;
906         };
907         struct A {
908           using type = B::type;
909         };
910         A::[[type]] waldo;
911   )cpp";
912   EXPECT_DECLS("TypedefTypeLoc",
913                {"using type = int", Rel::Alias | Rel::Underlying},
914                {"using type = C::type", Rel::Alias | Rel::Underlying},
915                {"using type = B::type", Rel::Alias});
916 }
917 
TEST_F(TargetDeclTest,RecursiveTemplate)918 TEST_F(TargetDeclTest, RecursiveTemplate) {
919   Flags.push_back("-std=c++20"); // the test case uses concepts
920 
921   Code = R"cpp(
922         template <typename T>
923         concept Leaf = false;
924 
925         template <typename Tree>
926         struct descend_left {
927           using type = typename descend_left<typename Tree::left>::[[type]];
928         };
929 
930         template <Leaf Tree>
931         struct descend_left<Tree> {
932           using type = typename Tree::value;
933         };
934   )cpp";
935   EXPECT_DECLS("DependentNameTypeLoc",
936                {"using type = typename descend_left<typename Tree::left>::type",
937                 Rel::Alias | Rel::Underlying});
938 }
939 
TEST_F(TargetDeclTest,ObjC)940 TEST_F(TargetDeclTest, ObjC) {
941   Flags = {"-xobjective-c"};
942   Code = R"cpp(
943     @interface Foo {}
944     -(void)bar;
945     @end
946     void test(Foo *f) {
947       [f [[bar]] ];
948     }
949   )cpp";
950   EXPECT_DECLS("ObjCMessageExpr", "- (void)bar");
951 
952   Code = R"cpp(
953     @interface Foo { @public int bar; }
954     @end
955     int test(Foo *f) {
956       return [[f->bar]];
957     }
958   )cpp";
959   EXPECT_DECLS("ObjCIvarRefExpr", "int bar");
960 
961   Code = R"cpp(
962     @interface Foo {}
963     -(int) x;
964     -(void) setX:(int)x;
965     @end
966     void test(Foo *f) {
967       [[f.x]] = 42;
968     }
969   )cpp";
970   EXPECT_DECLS("ObjCPropertyRefExpr", "- (void)setX:(int)x");
971 
972   Code = R"cpp(
973     @interface I {}
974     @property(retain) I* x;
975     @property(retain) I* y;
976     @end
977     void test(I *f) {
978       [[f.x]].y = 0;
979     }
980   )cpp";
981   EXPECT_DECLS("ObjCPropertyRefExpr",
982                "@property(atomic, retain, readwrite) I *x");
983 
984   Code = R"cpp(
985     @interface MYObject
986     @end
987     @interface Interface
988     @property(retain) [[MYObject]] *x;
989     @end
990   )cpp";
991   EXPECT_DECLS("ObjCInterfaceTypeLoc", "@interface MYObject");
992 
993   Code = R"cpp(
994     @interface MYObject2
995     @end
996     @interface Interface
997     @property(retain, nonnull) [[MYObject2]] *x;
998     @end
999   )cpp";
1000   EXPECT_DECLS("ObjCInterfaceTypeLoc", "@interface MYObject2");
1001 
1002   Code = R"cpp(
1003     @protocol Foo
1004     @end
1005     id test() {
1006       return [[@protocol(Foo)]];
1007     }
1008   )cpp";
1009   EXPECT_DECLS("ObjCProtocolExpr", "@protocol Foo");
1010 
1011   Code = R"cpp(
1012     @interface Foo
1013     @end
1014     void test([[Foo]] *p);
1015   )cpp";
1016   EXPECT_DECLS("ObjCInterfaceTypeLoc", "@interface Foo");
1017 
1018   Code = R"cpp(// Don't consider implicit interface as the target.
1019     @implementation [[Implicit]]
1020     @end
1021   )cpp";
1022   EXPECT_DECLS("ObjCImplementationDecl", "@implementation Implicit");
1023 
1024   Code = R"cpp(
1025     @interface Foo
1026     @end
1027     @implementation [[Foo]]
1028     @end
1029   )cpp";
1030   EXPECT_DECLS("ObjCImplementationDecl", "@interface Foo");
1031 
1032   Code = R"cpp(
1033     @interface Foo
1034     @end
1035     @interface Foo (Ext)
1036     @end
1037     @implementation [[Foo]] (Ext)
1038     @end
1039   )cpp";
1040   EXPECT_DECLS("ObjCCategoryImplDecl", "@interface Foo(Ext)");
1041 
1042   Code = R"cpp(
1043     void test(id</*error-ok*/[[InvalidProtocol]]> p);
1044   )cpp";
1045   EXPECT_DECLS("ParmVarDecl", "id p");
1046 
1047   Code = R"cpp(
1048     @class C;
1049     @protocol Foo
1050     @end
1051     void test([[C]]<Foo> *p);
1052   )cpp";
1053   EXPECT_DECLS("ObjCInterfaceTypeLoc", "@class C;");
1054 
1055   Code = R"cpp(
1056     @class C;
1057     @protocol Foo
1058     @end
1059     void test(C<[[Foo]]> *p);
1060   )cpp";
1061   EXPECT_DECLS("ObjCProtocolLoc", "@protocol Foo");
1062 
1063   Code = R"cpp(
1064     @class C;
1065     @protocol Foo
1066     @end
1067     @protocol Bar
1068     @end
1069     void test(C<[[Foo]], Bar> *p);
1070   )cpp";
1071   EXPECT_DECLS("ObjCProtocolLoc", "@protocol Foo");
1072 
1073   Code = R"cpp(
1074     @class C;
1075     @protocol Foo
1076     @end
1077     @protocol Bar
1078     @end
1079     void test(C<Foo, [[Bar]]> *p);
1080   )cpp";
1081   EXPECT_DECLS("ObjCProtocolLoc", "@protocol Bar");
1082 
1083   Code = R"cpp(
1084     @interface Foo
1085     + (id)sharedInstance;
1086     @end
1087     @implementation Foo
1088     + (id)sharedInstance { return 0; }
1089     @end
1090     void test() {
1091       id value = [[Foo]].sharedInstance;
1092     }
1093   )cpp";
1094   EXPECT_DECLS("ObjCInterfaceTypeLoc", "@interface Foo");
1095 
1096   Code = R"cpp(
1097     @interface Foo
1098     + (id)sharedInstance;
1099     @end
1100     @implementation Foo
1101     + (id)sharedInstance { return 0; }
1102     @end
1103     void test() {
1104       id value = Foo.[[sharedInstance]];
1105     }
1106   )cpp";
1107   EXPECT_DECLS("ObjCPropertyRefExpr", "+ (id)sharedInstance");
1108 
1109   Code = R"cpp(
1110     @interface Foo
1111     + ([[id]])sharedInstance;
1112     @end
1113   )cpp";
1114   EXPECT_DECLS("TypedefTypeLoc");
1115 
1116   Code = R"cpp(
1117     @interface Foo
1118     + ([[instancetype]])sharedInstance;
1119     @end
1120   )cpp";
1121   EXPECT_DECLS("TypedefTypeLoc");
1122 }
1123 
1124 class FindExplicitReferencesTest : public ::testing::Test {
1125 protected:
1126   struct AllRefs {
1127     std::string AnnotatedCode;
1128     std::string DumpedReferences;
1129   };
1130 
1131   /// Parses \p Code, finds function or namespace '::foo' and annotates its body
1132   /// with results of findExplicitReferences.
1133   /// See actual tests for examples of annotation format.
annotateReferencesInFoo(llvm::StringRef Code)1134   AllRefs annotateReferencesInFoo(llvm::StringRef Code) {
1135     TestTU TU;
1136     TU.Code = std::string(Code);
1137 
1138     // FIXME: Auto-completion in a template requires disabling delayed template
1139     // parsing.
1140     TU.ExtraArgs.push_back("-std=c++20");
1141     TU.ExtraArgs.push_back("-xobjective-c++");
1142 
1143     auto AST = TU.build();
1144     auto *TestDecl = &findDecl(AST, "foo");
1145     if (auto *T = llvm::dyn_cast<FunctionTemplateDecl>(TestDecl))
1146       TestDecl = T->getTemplatedDecl();
1147 
1148     std::vector<ReferenceLoc> Refs;
1149     if (const auto *Func = llvm::dyn_cast<FunctionDecl>(TestDecl))
1150       findExplicitReferences(
1151           Func->getBody(),
1152           [&Refs](ReferenceLoc R) { Refs.push_back(std::move(R)); },
1153           AST.getHeuristicResolver());
1154     else if (const auto *NS = llvm::dyn_cast<NamespaceDecl>(TestDecl))
1155       findExplicitReferences(
1156           NS,
1157           [&Refs, &NS](ReferenceLoc R) {
1158             // Avoid adding the namespace foo decl to the results.
1159             if (R.Targets.size() == 1 && R.Targets.front() == NS)
1160               return;
1161             Refs.push_back(std::move(R));
1162           },
1163           AST.getHeuristicResolver());
1164     else
1165       ADD_FAILURE() << "Failed to find ::foo decl for test";
1166 
1167     auto &SM = AST.getSourceManager();
1168     llvm::sort(Refs, [&](const ReferenceLoc &L, const ReferenceLoc &R) {
1169       return SM.isBeforeInTranslationUnit(L.NameLoc, R.NameLoc);
1170     });
1171 
1172     std::string AnnotatedCode;
1173     unsigned NextCodeChar = 0;
1174     for (unsigned I = 0; I < Refs.size(); ++I) {
1175       auto &R = Refs[I];
1176 
1177       SourceLocation Pos = R.NameLoc;
1178       assert(Pos.isValid());
1179       if (Pos.isMacroID()) // FIXME: figure out how to show macro locations.
1180         Pos = SM.getExpansionLoc(Pos);
1181       assert(Pos.isFileID());
1182 
1183       FileID File;
1184       unsigned Offset;
1185       std::tie(File, Offset) = SM.getDecomposedLoc(Pos);
1186       if (File == SM.getMainFileID()) {
1187         // Print the reference in a source code.
1188         assert(NextCodeChar <= Offset);
1189         AnnotatedCode += Code.substr(NextCodeChar, Offset - NextCodeChar);
1190         AnnotatedCode += "$" + std::to_string(I) + "^";
1191 
1192         NextCodeChar = Offset;
1193       }
1194     }
1195     AnnotatedCode += Code.substr(NextCodeChar);
1196 
1197     std::string DumpedReferences;
1198     for (unsigned I = 0; I < Refs.size(); ++I)
1199       DumpedReferences += std::string(llvm::formatv("{0}: {1}\n", I, Refs[I]));
1200 
1201     return AllRefs{std::move(AnnotatedCode), std::move(DumpedReferences)};
1202   }
1203 };
1204 
TEST_F(FindExplicitReferencesTest,All)1205 TEST_F(FindExplicitReferencesTest, All) {
1206   std::pair</*Code*/ llvm::StringRef, /*References*/ llvm::StringRef> Cases[] =
1207       {// Simple expressions.
1208        {R"cpp(
1209         int global;
1210         int func();
1211         void foo(int param) {
1212           $0^global = $1^param + $2^func();
1213         }
1214         )cpp",
1215         "0: targets = {global}\n"
1216         "1: targets = {param}\n"
1217         "2: targets = {func}\n"},
1218        {R"cpp(
1219         struct X { int a; };
1220         void foo(X x) {
1221           $0^x.$1^a = 10;
1222         }
1223         )cpp",
1224         "0: targets = {x}\n"
1225         "1: targets = {X::a}\n"},
1226        {R"cpp(
1227         // error-ok: testing with broken code
1228         int bar();
1229         int foo() {
1230           return $0^bar() + $1^bar(42);
1231         }
1232         )cpp",
1233         "0: targets = {bar}\n"
1234         "1: targets = {bar}\n"},
1235        // Namespaces and aliases.
1236        {R"cpp(
1237           namespace ns {}
1238           namespace alias = ns;
1239           void foo() {
1240             using namespace $0^ns;
1241             using namespace $1^alias;
1242           }
1243         )cpp",
1244         "0: targets = {ns}\n"
1245         "1: targets = {alias}\n"},
1246        // Using declarations.
1247        {R"cpp(
1248           namespace ns { int global; }
1249           void foo() {
1250             using $0^ns::$1^global;
1251           }
1252         )cpp",
1253         "0: targets = {ns}\n"
1254         "1: targets = {ns::global}, qualifier = 'ns::'\n"},
1255        // Simple types.
1256        {R"cpp(
1257          struct Struct { int a; };
1258          using Typedef = int;
1259          void foo() {
1260            $0^Struct $1^x;
1261            $2^Typedef $3^y;
1262            static_cast<$4^Struct*>(0);
1263          }
1264        )cpp",
1265         "0: targets = {Struct}\n"
1266         "1: targets = {x}, decl\n"
1267         "2: targets = {Typedef}\n"
1268         "3: targets = {y}, decl\n"
1269         "4: targets = {Struct}\n"},
1270        // Name qualifiers.
1271        {R"cpp(
1272          namespace a { namespace b { struct S { typedef int type; }; } }
1273          void foo() {
1274            $0^a::$1^b::$2^S $3^x;
1275            using namespace $4^a::$5^b;
1276            $6^S::$7^type $8^y;
1277          }
1278         )cpp",
1279         "0: targets = {a}\n"
1280         "1: targets = {a::b}, qualifier = 'a::'\n"
1281         "2: targets = {a::b::S}, qualifier = 'a::b::'\n"
1282         "3: targets = {x}, decl\n"
1283         "4: targets = {a}\n"
1284         "5: targets = {a::b}, qualifier = 'a::'\n"
1285         "6: targets = {a::b::S}\n"
1286         "7: targets = {a::b::S::type}, qualifier = 'struct S::'\n"
1287         "8: targets = {y}, decl\n"},
1288        {R"cpp(
1289          void foo() {
1290            $0^ten: // PRINT "HELLO WORLD!"
1291            goto $1^ten;
1292          }
1293        )cpp",
1294         "0: targets = {ten}, decl\n"
1295         "1: targets = {ten}\n"},
1296        // Simple templates.
1297        {R"cpp(
1298           template <class T> struct vector { using value_type = T; };
1299           template <> struct vector<bool> { using value_type = bool; };
1300           void foo() {
1301             $0^vector<int> $1^vi;
1302             $2^vector<bool> $3^vb;
1303           }
1304         )cpp",
1305         "0: targets = {vector<int>}\n"
1306         "1: targets = {vi}, decl\n"
1307         "2: targets = {vector<bool>}\n"
1308         "3: targets = {vb}, decl\n"},
1309        // Template type aliases.
1310        {R"cpp(
1311             template <class T> struct vector { using value_type = T; };
1312             template <> struct vector<bool> { using value_type = bool; };
1313             template <class T> using valias = vector<T>;
1314             void foo() {
1315               $0^valias<int> $1^vi;
1316               $2^valias<bool> $3^vb;
1317             }
1318           )cpp",
1319         "0: targets = {valias}\n"
1320         "1: targets = {vi}, decl\n"
1321         "2: targets = {valias}\n"
1322         "3: targets = {vb}, decl\n"},
1323        // Injected class name.
1324        {R"cpp(
1325             namespace foo {
1326               template <typename $0^T>
1327               class $1^Bar {
1328                 ~$2^Bar();
1329                 void $3^f($4^Bar);
1330               };
1331             }
1332           )cpp",
1333         "0: targets = {foo::Bar::T}, decl\n"
1334         "1: targets = {foo::Bar}, decl\n"
1335         "2: targets = {foo::Bar}\n"
1336         "3: targets = {foo::Bar::f}, decl\n"
1337         "4: targets = {foo::Bar}\n"},
1338        // MemberExpr should know their using declaration.
1339        {R"cpp(
1340             struct X { void func(int); };
1341             struct Y : X {
1342               using X::func;
1343             };
1344             void foo(Y y) {
1345               $0^y.$1^func(1);
1346             }
1347         )cpp",
1348         "0: targets = {y}\n"
1349         "1: targets = {Y::func}\n"},
1350        // DeclRefExpr should know their using declaration.
1351        {R"cpp(
1352             namespace ns { void bar(int); }
1353             using ns::bar;
1354 
1355             void foo() {
1356               $0^bar(10);
1357             }
1358         )cpp",
1359         "0: targets = {bar}\n"},
1360        // References from a macro.
1361        {R"cpp(
1362             #define FOO a
1363             #define BAR b
1364 
1365             void foo(int a, int b) {
1366               $0^FOO+$1^BAR;
1367             }
1368         )cpp",
1369         "0: targets = {a}\n"
1370         "1: targets = {b}\n"},
1371        // No references from implicit nodes.
1372        {R"cpp(
1373             struct vector {
1374               int *begin();
1375               int *end();
1376             };
1377 
1378             void foo() {
1379               for (int $0^x : $1^vector()) {
1380                 $2^x = 10;
1381               }
1382             }
1383         )cpp",
1384         "0: targets = {x}, decl\n"
1385         "1: targets = {vector}\n"
1386         "2: targets = {x}\n"},
1387        // Handle UnresolvedLookupExpr.
1388        {R"cpp(
1389             namespace ns1 { void func(char*); }
1390             namespace ns2 { void func(int*); }
1391             using namespace ns1;
1392             using namespace ns2;
1393 
1394             template <class T>
1395             void foo(T t) {
1396               $0^func($1^t);
1397             }
1398         )cpp",
1399         "0: targets = {ns1::func, ns2::func}\n"
1400         "1: targets = {t}\n"},
1401        // Handle UnresolvedMemberExpr.
1402        {R"cpp(
1403             struct X {
1404               void func(char*);
1405               void func(int*);
1406             };
1407 
1408             template <class T>
1409             void foo(X x, T t) {
1410               $0^x.$1^func($2^t);
1411             }
1412         )cpp",
1413         "0: targets = {x}\n"
1414         "1: targets = {X::func, X::func}\n"
1415         "2: targets = {t}\n"},
1416        // Handle DependentScopeDeclRefExpr.
1417        {R"cpp(
1418             template <class T>
1419             struct S {
1420               static int value;
1421             };
1422 
1423             template <class T>
1424             void foo() {
1425               $0^S<$1^T>::$2^value;
1426             }
1427        )cpp",
1428         "0: targets = {S}\n"
1429         "1: targets = {T}\n"
1430         "2: targets = {S::value}, qualifier = 'S<T>::'\n"},
1431        // Handle CXXDependentScopeMemberExpr.
1432        {R"cpp(
1433             template <class T>
1434             struct S {
1435               int value;
1436             };
1437 
1438             template <class T>
1439             void foo(S<T> t) {
1440               $0^t.$1^value;
1441             }
1442        )cpp",
1443         "0: targets = {t}\n"
1444         "1: targets = {S::value}\n"},
1445        // Type template parameters.
1446        {R"cpp(
1447             template <class T>
1448             void foo() {
1449               static_cast<$0^T>(0);
1450               $1^T();
1451               $2^T $3^t;
1452             }
1453         )cpp",
1454         "0: targets = {T}\n"
1455         "1: targets = {T}\n"
1456         "2: targets = {T}\n"
1457         "3: targets = {t}, decl\n"},
1458        // Non-type template parameters.
1459        {R"cpp(
1460             template <int I>
1461             void foo() {
1462               int $0^x = $1^I;
1463             }
1464         )cpp",
1465         "0: targets = {x}, decl\n"
1466         "1: targets = {I}\n"},
1467        // Template template parameters.
1468        {R"cpp(
1469             template <class T> struct vector {};
1470 
1471             template <template<class> class TT, template<class> class ...TP>
1472             void foo() {
1473               $0^TT<int> $1^x;
1474               $2^foo<$3^TT>();
1475               $4^foo<$5^vector>();
1476               $6^foo<$7^TP...>();
1477             }
1478         )cpp",
1479         "0: targets = {TT}\n"
1480         "1: targets = {x}, decl\n"
1481         "2: targets = {foo}\n"
1482         "3: targets = {TT}\n"
1483         "4: targets = {foo}\n"
1484         "5: targets = {vector}\n"
1485         "6: targets = {foo}\n"
1486         "7: targets = {TP}\n"},
1487        // Non-type template parameters with declarations.
1488        {R"cpp(
1489             int func();
1490             template <int(*)()> struct wrapper {};
1491 
1492             template <int(*FuncParam)()>
1493             void foo() {
1494               $0^wrapper<$1^func> $2^w;
1495               $3^FuncParam();
1496             }
1497         )cpp",
1498         "0: targets = {wrapper<&func>}\n"
1499         "1: targets = {func}\n"
1500         "2: targets = {w}, decl\n"
1501         "3: targets = {FuncParam}\n"},
1502        // declaration references.
1503        {R"cpp(
1504              namespace ns {}
1505              class S {};
1506              void foo() {
1507                class $0^Foo { $1^Foo(); ~$2^Foo(); int $3^field; };
1508                int $4^Var;
1509                enum $5^E { $6^ABC };
1510                typedef int $7^INT;
1511                using $8^INT2 = int;
1512                namespace $9^NS = $10^ns;
1513              }
1514            )cpp",
1515         "0: targets = {Foo}, decl\n"
1516         "1: targets = {foo()::Foo::Foo}, decl\n"
1517         "2: targets = {Foo}\n"
1518         "3: targets = {foo()::Foo::field}, decl\n"
1519         "4: targets = {Var}, decl\n"
1520         "5: targets = {E}, decl\n"
1521         "6: targets = {foo()::ABC}, decl\n"
1522         "7: targets = {INT}, decl\n"
1523         "8: targets = {INT2}, decl\n"
1524         "9: targets = {NS}, decl\n"
1525         "10: targets = {ns}\n"},
1526        // User-defined conversion operator.
1527        {R"cpp(
1528             void foo() {
1529                class $0^Bar {};
1530                class $1^Foo {
1531                public:
1532                  // FIXME: This should have only one reference to Bar.
1533                  $2^operator $3^$4^Bar();
1534                };
1535 
1536                $5^Foo $6^f;
1537                $7^f.$8^operator $9^Bar();
1538             }
1539         )cpp",
1540         "0: targets = {Bar}, decl\n"
1541         "1: targets = {Foo}, decl\n"
1542         "2: targets = {foo()::Foo::operator Bar}, decl\n"
1543         "3: targets = {Bar}\n"
1544         "4: targets = {Bar}\n"
1545         "5: targets = {Foo}\n"
1546         "6: targets = {f}, decl\n"
1547         "7: targets = {f}\n"
1548         "8: targets = {foo()::Foo::operator Bar}\n"
1549         "9: targets = {Bar}\n"},
1550        // Destructor.
1551        {R"cpp(
1552              void foo() {
1553                class $0^Foo {
1554                public:
1555                  ~$1^Foo() {}
1556 
1557                  void $2^destructMe() {
1558                    this->~$3^Foo();
1559                  }
1560                };
1561 
1562                $4^Foo $5^f;
1563                $6^f.~ /*...*/ $7^Foo();
1564              }
1565            )cpp",
1566         "0: targets = {Foo}, decl\n"
1567         // FIXME: It's better to target destructor's FunctionDecl instead of
1568         // the type itself (similar to constructor).
1569         "1: targets = {Foo}\n"
1570         "2: targets = {foo()::Foo::destructMe}, decl\n"
1571         "3: targets = {Foo}\n"
1572         "4: targets = {Foo}\n"
1573         "5: targets = {f}, decl\n"
1574         "6: targets = {f}\n"
1575         "7: targets = {Foo}\n"},
1576        // cxx constructor initializer.
1577        {R"cpp(
1578              class Base {};
1579              void foo() {
1580                // member initializer
1581                class $0^X {
1582                  int $1^abc;
1583                  $2^X(): $3^abc() {}
1584                };
1585                // base initializer
1586                class $4^Derived : public $5^Base {
1587                  $6^Base $7^B;
1588                  $8^Derived() : $9^Base() {}
1589                };
1590                // delegating initializer
1591                class $10^Foo {
1592                  $11^Foo(int);
1593                  $12^Foo(): $13^Foo(111) {}
1594                };
1595              }
1596            )cpp",
1597         "0: targets = {X}, decl\n"
1598         "1: targets = {foo()::X::abc}, decl\n"
1599         "2: targets = {foo()::X::X}, decl\n"
1600         "3: targets = {foo()::X::abc}\n"
1601         "4: targets = {Derived}, decl\n"
1602         "5: targets = {Base}\n"
1603         "6: targets = {Base}\n"
1604         "7: targets = {foo()::Derived::B}, decl\n"
1605         "8: targets = {foo()::Derived::Derived}, decl\n"
1606         "9: targets = {Base}\n"
1607         "10: targets = {Foo}, decl\n"
1608         "11: targets = {foo()::Foo::Foo}, decl\n"
1609         "12: targets = {foo()::Foo::Foo}, decl\n"
1610         "13: targets = {Foo}\n"},
1611        // Anonymous entities should not be reported.
1612        {
1613            R"cpp(
1614              void foo() {
1615               class {} $0^x;
1616               int (*$1^fptr)(int $2^a, int) = nullptr;
1617              }
1618            )cpp",
1619            "0: targets = {x}, decl\n"
1620            "1: targets = {fptr}, decl\n"
1621            "2: targets = {a}, decl\n"},
1622        // Namespace aliases should be handled properly.
1623        {
1624            R"cpp(
1625                 namespace ns { struct Type {}; }
1626                 namespace alias = ns;
1627                 namespace rec_alias = alias;
1628 
1629                 void foo() {
1630                   $0^ns::$1^Type $2^a;
1631                   $3^alias::$4^Type $5^b;
1632                   $6^rec_alias::$7^Type $8^c;
1633                 }
1634            )cpp",
1635            "0: targets = {ns}\n"
1636            "1: targets = {ns::Type}, qualifier = 'ns::'\n"
1637            "2: targets = {a}, decl\n"
1638            "3: targets = {alias}\n"
1639            "4: targets = {ns::Type}, qualifier = 'alias::'\n"
1640            "5: targets = {b}, decl\n"
1641            "6: targets = {rec_alias}\n"
1642            "7: targets = {ns::Type}, qualifier = 'rec_alias::'\n"
1643            "8: targets = {c}, decl\n"},
1644        // Handle SizeOfPackExpr.
1645        {
1646            R"cpp(
1647                 template <typename... E>
1648                 void foo() {
1649                   constexpr int $0^size = sizeof...($1^E);
1650                 };
1651             )cpp",
1652            "0: targets = {size}, decl\n"
1653            "1: targets = {E}\n"},
1654        // Class template argument deduction
1655        {
1656            R"cpp(
1657                 template <typename T>
1658                 struct Test {
1659                 Test(T);
1660               };
1661               void foo() {
1662                 $0^Test $1^a(5);
1663               }
1664             )cpp",
1665            "0: targets = {Test}\n"
1666            "1: targets = {a}, decl\n"},
1667        // Templates
1668        {R"cpp(
1669             namespace foo {
1670               template <typename $0^T>
1671               class $1^Bar {};
1672             }
1673           )cpp",
1674         "0: targets = {foo::Bar::T}, decl\n"
1675         "1: targets = {foo::Bar}, decl\n"},
1676        // Templates
1677        {R"cpp(
1678             namespace foo {
1679               template <typename $0^T>
1680               void $1^func();
1681             }
1682           )cpp",
1683         "0: targets = {T}, decl\n"
1684         "1: targets = {foo::func}, decl\n"},
1685        // Templates
1686        {R"cpp(
1687             namespace foo {
1688               template <typename $0^T>
1689               $1^T $2^x;
1690             }
1691           )cpp",
1692         "0: targets = {foo::T}, decl\n"
1693         "1: targets = {foo::T}\n"
1694         "2: targets = {foo::x}, decl\n"},
1695        // Templates
1696        {R"cpp(
1697             template<typename T> class vector {};
1698             namespace foo {
1699               template <typename $0^T>
1700               using $1^V = $2^vector<$3^T>;
1701             }
1702           )cpp",
1703         "0: targets = {foo::T}, decl\n"
1704         "1: targets = {foo::V}, decl\n"
1705         "2: targets = {vector}\n"
1706         "3: targets = {foo::T}\n"},
1707        // Concept
1708        {
1709            R"cpp(
1710               template <typename T>
1711               concept Drawable = requires (T t) { t.draw(); };
1712 
1713               namespace foo {
1714                 template <typename $0^T> requires $1^Drawable<$2^T>
1715                 void $3^bar($4^T $5^t) {
1716                   $6^t.$7^draw();
1717                 }
1718               }
1719           )cpp",
1720            "0: targets = {T}, decl\n"
1721            "1: targets = {Drawable}\n"
1722            "2: targets = {T}\n"
1723            "3: targets = {foo::bar}, decl\n"
1724            "4: targets = {T}\n"
1725            "5: targets = {t}, decl\n"
1726            "6: targets = {t}\n"
1727            "7: targets = {}\n"},
1728        // Objective-C: instance variables
1729        {
1730            R"cpp(
1731             @interface I {
1732             @public
1733               I *_z;
1734             }
1735             @end
1736             I *f;
1737             void foo() {
1738               $0^f->$1^_z = 0;
1739             }
1740           )cpp",
1741            "0: targets = {f}\n"
1742            "1: targets = {I::_z}\n"},
1743        // Objective-C: properties
1744        {
1745            R"cpp(
1746             @interface I {}
1747             @property(retain) I* x;
1748             @property(retain) I* y;
1749             @end
1750             I *f;
1751             void foo() {
1752               $0^f.$1^x.$2^y = 0;
1753             }
1754           )cpp",
1755            "0: targets = {f}\n"
1756            "1: targets = {I::x}\n"
1757            "2: targets = {I::y}\n"},
1758        // Objective-C: implicit properties
1759        {
1760            R"cpp(
1761             @interface I {}
1762             -(I*)x;
1763             -(void)setY:(I*)y;
1764             @end
1765             I *f;
1766             void foo() {
1767               $0^f.$1^x.$2^y = 0;
1768             }
1769           )cpp",
1770            "0: targets = {f}\n"
1771            "1: targets = {I::x}\n"
1772            "2: targets = {I::setY:}\n"},
1773        // Objective-C: class properties
1774        {
1775            R"cpp(
1776             @interface I {}
1777             @property(class) I *x;
1778             @end
1779             id local;
1780             void foo() {
1781               $0^I.$1^x = 0;
1782               $2^local = $3^I.$4^x;
1783             }
1784           )cpp",
1785            "0: targets = {I}\n"
1786            "1: targets = {I::setX:}\n"
1787            "2: targets = {local}\n"
1788            "3: targets = {I}\n"
1789            "4: targets = {I::x}\n"},
1790        // Objective-C: implicit class properties
1791        {
1792            R"cpp(
1793             @interface I {}
1794             +(I*)x;
1795             +(void)setX:(I*)x;
1796             @end
1797             id local;
1798             void foo() {
1799               $0^I.$1^x = 0;
1800               $2^local = $3^I.$4^x;
1801             }
1802           )cpp",
1803            "0: targets = {I}\n"
1804            "1: targets = {I::setX:}\n"
1805            "2: targets = {local}\n"
1806            "3: targets = {I}\n"
1807            "4: targets = {I::x}\n"},
1808        {// Objective-C: methods
1809         R"cpp(
1810             @interface I
1811               -(void) a:(int)x b:(int)y;
1812             @end
1813             void foo(I *i) {
1814               [$0^i $1^a:1 b:2];
1815             }
1816           )cpp",
1817         "0: targets = {i}\n"
1818         "1: targets = {I::a:b:}\n"},
1819        {// Objective-C: protocols
1820         R"cpp(
1821             @interface I
1822             @end
1823             @protocol P
1824             @end
1825             void foo() {
1826               $0^I<$1^P> *$2^x;
1827             }
1828           )cpp",
1829         "0: targets = {I}\n"
1830         "1: targets = {P}\n"
1831         "2: targets = {x}, decl\n"},
1832 
1833        // Designated initializers.
1834        {R"cpp(
1835             void foo() {
1836               struct $0^Foo {
1837                 int $1^Bar;
1838               };
1839               $2^Foo $3^f { .$4^Bar = 42 };
1840             }
1841         )cpp",
1842         "0: targets = {Foo}, decl\n"
1843         "1: targets = {foo()::Foo::Bar}, decl\n"
1844         "2: targets = {Foo}\n"
1845         "3: targets = {f}, decl\n"
1846         "4: targets = {foo()::Foo::Bar}\n"},
1847        {R"cpp(
1848             void foo() {
1849               struct $0^Baz {
1850                 int $1^Field;
1851               };
1852               struct $2^Bar {
1853                 $3^Baz $4^Foo;
1854               };
1855               $5^Bar $6^bar { .$7^Foo.$8^Field = 42 };
1856             }
1857         )cpp",
1858         "0: targets = {Baz}, decl\n"
1859         "1: targets = {foo()::Baz::Field}, decl\n"
1860         "2: targets = {Bar}, decl\n"
1861         "3: targets = {Baz}\n"
1862         "4: targets = {foo()::Bar::Foo}, decl\n"
1863         "5: targets = {Bar}\n"
1864         "6: targets = {bar}, decl\n"
1865         "7: targets = {foo()::Bar::Foo}\n"
1866         "8: targets = {foo()::Baz::Field}\n"},
1867        {R"cpp(
1868            template<typename T>
1869            void crash(T);
1870            template<typename T>
1871            void foo() {
1872              $0^crash({.$1^x = $2^T()});
1873            }
1874         )cpp",
1875         "0: targets = {crash}\n"
1876         "1: targets = {}\n"
1877         "2: targets = {T}\n"},
1878        // unknown template name should not crash.
1879        {R"cpp(
1880         template <template <typename> typename T>
1881         struct Base {};
1882         namespace foo {
1883         template <typename $0^T>
1884         struct $1^Derive : $2^Base<$3^T::template $4^Unknown> {};
1885         }
1886       )cpp",
1887         "0: targets = {foo::Derive::T}, decl\n"
1888         "1: targets = {foo::Derive}, decl\n"
1889         "2: targets = {Base}\n"
1890         "3: targets = {foo::Derive::T}\n"
1891         "4: targets = {}, qualifier = 'T::'\n"},
1892        // deduction guide
1893        {R"cpp(
1894           namespace foo {
1895             template <typename $0^T>
1896             struct $1^Test {
1897               template <typename $2^I>
1898               $3^Test($4^I);
1899             };
1900             template <typename $5^I>
1901             $6^Test($7^I) -> $8^Test<typename $9^I::$10^type>;
1902           }
1903         )cpp",
1904         "0: targets = {T}, decl\n"
1905         "1: targets = {foo::Test}, decl\n"
1906         "2: targets = {I}, decl\n"
1907         "3: targets = {foo::Test::Test<T>}, decl\n"
1908         "4: targets = {I}\n"
1909         "5: targets = {I}, decl\n"
1910         "6: targets = {foo::Test}\n"
1911         "7: targets = {I}\n"
1912         "8: targets = {foo::Test}\n"
1913         "9: targets = {I}\n"
1914         "10: targets = {}, qualifier = 'I::'\n"}};
1915 
1916   for (const auto &C : Cases) {
1917     llvm::StringRef ExpectedCode = C.first;
1918     llvm::StringRef ExpectedRefs = C.second;
1919 
1920     auto Actual =
1921         annotateReferencesInFoo(llvm::Annotations(ExpectedCode).code());
1922     EXPECT_EQ(ExpectedCode, Actual.AnnotatedCode);
1923     EXPECT_EQ(ExpectedRefs, Actual.DumpedReferences) << ExpectedCode;
1924   }
1925 }
1926 
1927 } // namespace
1928 } // namespace clangd
1929 } // namespace clang
1930