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 {
35   PrintedDecl(const char *Name, DeclRelationSet Relations = {})
36       : Name(Name), Relations(Relations) {}
37   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 =
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 };
51 bool operator==(const PrintedDecl &L, const PrintedDecl &R) {
52   return std::tie(L.Name, L.Relations) == std::tie(R.Name, R.Relations);
53 }
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().
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 : allTargetDecls(N->ASTNode))
90       ActualDecls.emplace_back(Entry.first, Entry.second);
91     return ActualDecls;
92   }
93 };
94 
95 // This is a macro to preserve line numbers in assertion failures.
96 // It takes the expected decls as varargs to work around comma-in-macro issues.
97 #define EXPECT_DECLS(NodeType, ...)                                            \
98   EXPECT_THAT(assertNodeAndPrintDecls(NodeType),                               \
99               ::testing::UnorderedElementsAreArray(                            \
100                   std::vector<PrintedDecl>({__VA_ARGS__})))                    \
101       << Code
102 using ExpectedDecls = std::vector<PrintedDecl>;
103 
104 TEST_F(TargetDeclTest, Exprs) {
105   Code = R"cpp(
106     int f();
107     int x = [[f]]();
108   )cpp";
109   EXPECT_DECLS("DeclRefExpr", "int f()");
110 
111   Code = R"cpp(
112     struct S { S operator+(S) const; };
113     auto X = S() [[+]] S();
114   )cpp";
115   EXPECT_DECLS("DeclRefExpr", "S operator+(S) const");
116 
117   Code = R"cpp(
118     int foo();
119     int s = foo[[()]];
120   )cpp";
121   EXPECT_DECLS("CallExpr", "int foo()");
122 
123   Code = R"cpp(
124     struct X {
125     void operator()(int n);
126     };
127     void test() {
128       X x;
129       x[[(123)]];
130     }
131   )cpp";
132   EXPECT_DECLS("CXXOperatorCallExpr", "void operator()(int n)");
133 
134   Code = R"cpp(
135     void test() {
136       goto [[label]];
137     label:
138       return;
139     }
140   )cpp";
141   EXPECT_DECLS("GotoStmt", "label:");
142   Code = R"cpp(
143     void test() {
144     [[label]]:
145       return;
146     }
147   )cpp";
148   EXPECT_DECLS("LabelStmt", "label:");
149 }
150 
151 TEST_F(TargetDeclTest, Recovery) {
152   Code = R"cpp(
153     // error-ok: testing behavior on broken code
154     int f();
155     int f(int, int);
156     int x = [[f]](42);
157   )cpp";
158   EXPECT_DECLS("UnresolvedLookupExpr", "int f()", "int f(int, int)");
159 }
160 
161 TEST_F(TargetDeclTest, UsingDecl) {
162   Code = R"cpp(
163     namespace foo {
164       int f(int);
165       int f(char);
166     }
167     using foo::f;
168     int x = [[f]](42);
169   )cpp";
170   // f(char) is not referenced!
171   EXPECT_DECLS("DeclRefExpr", {"using foo::f", Rel::Alias},
172                {"int f(int)", Rel::Underlying});
173 
174   Code = R"cpp(
175     namespace foo {
176       int f(int);
177       int f(char);
178     }
179     [[using foo::f]];
180   )cpp";
181   // All overloads are referenced.
182   EXPECT_DECLS("UsingDecl", {"using foo::f", Rel::Alias},
183                {"int f(int)", Rel::Underlying},
184                {"int f(char)", Rel::Underlying});
185 
186   Code = R"cpp(
187     struct X {
188       int foo();
189     };
190     struct Y : X {
191       using X::foo;
192     };
193     int x = Y().[[foo]]();
194   )cpp";
195   EXPECT_DECLS("MemberExpr", {"using X::foo", Rel::Alias},
196                {"int foo()", Rel::Underlying});
197 }
198 
199 TEST_F(TargetDeclTest, ConstructorInitList) {
200   Code = R"cpp(
201     struct X {
202       int a;
203       X() : [[a]](42) {}
204     };
205   )cpp";
206   EXPECT_DECLS("CXXCtorInitializer", "int a");
207 
208   Code = R"cpp(
209     struct X {
210       X() : [[X]](1) {}
211       X(int);
212     };
213   )cpp";
214   EXPECT_DECLS("RecordTypeLoc", "struct X");
215 }
216 
217 TEST_F(TargetDeclTest, DesignatedInit) {
218   Flags = {"-xc"}; // array designators are a C99 extension.
219   Code = R"c(
220     struct X { int a; };
221     struct Y { int b; struct X c[2]; };
222     struct Y y = { .c[0].[[a]] = 1 };
223   )c";
224   EXPECT_DECLS("DesignatedInitExpr", "int a");
225 }
226 
227 TEST_F(TargetDeclTest, NestedNameSpecifier) {
228   Code = R"cpp(
229     namespace a { namespace b { int c; } }
230     int x = a::[[b::]]c;
231   )cpp";
232   EXPECT_DECLS("NestedNameSpecifierLoc", "namespace b");
233 
234   Code = R"cpp(
235     namespace a { struct X { enum { y }; }; }
236     int x = a::[[X::]]y;
237   )cpp";
238   EXPECT_DECLS("NestedNameSpecifierLoc", "struct X");
239 
240   Code = R"cpp(
241     template <typename T>
242     int x = [[T::]]y;
243   )cpp";
244   EXPECT_DECLS("NestedNameSpecifierLoc", "typename T");
245 
246   Code = R"cpp(
247     namespace a { int x; }
248     namespace b = a;
249     int y = [[b]]::x;
250   )cpp";
251   EXPECT_DECLS("NestedNameSpecifierLoc", {"namespace b = a", Rel::Alias},
252                {"namespace a", Rel::Underlying});
253 }
254 
255 TEST_F(TargetDeclTest, Types) {
256   Code = R"cpp(
257     struct X{};
258     [[X]] x;
259   )cpp";
260   EXPECT_DECLS("RecordTypeLoc", "struct X");
261 
262   Code = R"cpp(
263     struct S{};
264     typedef S X;
265     [[X]] x;
266   )cpp";
267   EXPECT_DECLS("TypedefTypeLoc", {"typedef S X", Rel::Alias},
268                {"struct S", Rel::Underlying});
269   Code = R"cpp(
270     namespace ns { struct S{}; }
271     typedef ns::S X;
272     [[X]] x;
273   )cpp";
274   EXPECT_DECLS("TypedefTypeLoc", {"typedef ns::S X", Rel::Alias},
275                {"struct S", Rel::Underlying});
276 
277   // FIXME: Auto-completion in a template requires disabling delayed template
278   // parsing.
279   Flags = {"-fno-delayed-template-parsing"};
280   Code = R"cpp(
281     template<class T>
282     void foo() { [[T]] x; }
283   )cpp";
284   EXPECT_DECLS("TemplateTypeParmTypeLoc", "class T");
285   Flags.clear();
286 
287   // FIXME: Auto-completion in a template requires disabling delayed template
288   // parsing.
289   Flags = {"-fno-delayed-template-parsing"};
290   Code = R"cpp(
291     template<template<typename> class T>
292     void foo() { [[T<int>]] x; }
293   )cpp";
294   EXPECT_DECLS("TemplateSpecializationTypeLoc", "template <typename> class T");
295   Flags.clear();
296 
297   Code = R"cpp(
298     struct S{};
299     S X;
300     [[decltype]](X) Y;
301   )cpp";
302   EXPECT_DECLS("DecltypeTypeLoc", {"struct S", Rel::Underlying});
303 
304   Code = R"cpp(
305     struct S{};
306     [[auto]] X = S{};
307   )cpp";
308   // FIXME: deduced type missing in AST. https://llvm.org/PR42914
309   EXPECT_DECLS("AutoTypeLoc");
310 
311   Code = R"cpp(
312     template <typename... E>
313     struct S {
314       static const int size = sizeof...([[E]]);
315     };
316   )cpp";
317   EXPECT_DECLS("SizeOfPackExpr", "typename ...E");
318 
319   Code = R"cpp(
320     template <typename T>
321     class Foo {
322       void f([[Foo]] x);
323     };
324   )cpp";
325   EXPECT_DECLS("InjectedClassNameTypeLoc", "class Foo");
326 }
327 
328 TEST_F(TargetDeclTest, ClassTemplate) {
329   Code = R"cpp(
330     // Implicit specialization.
331     template<int x> class Foo{};
332     [[Foo<42>]] B;
333   )cpp";
334   EXPECT_DECLS("TemplateSpecializationTypeLoc",
335                {"template<> class Foo<42>", Rel::TemplateInstantiation},
336                {"class Foo", Rel::TemplatePattern});
337 
338   Code = R"cpp(
339     template<typename T> class Foo {};
340     // The "Foo<int>" SpecializationDecl is incomplete, there is no
341     // instantiation happening.
342     void func([[Foo<int>]] *);
343   )cpp";
344   EXPECT_DECLS("TemplateSpecializationTypeLoc",
345                {"class Foo", Rel::TemplatePattern},
346                {"template<> class Foo<int>", Rel::TemplateInstantiation});
347 
348   Code = R"cpp(
349     // Explicit specialization.
350     template<int x> class Foo{};
351     template<> class Foo<42>{};
352     [[Foo<42>]] B;
353   )cpp";
354   EXPECT_DECLS("TemplateSpecializationTypeLoc", "template<> class Foo<42>");
355 
356   Code = R"cpp(
357     // Partial specialization.
358     template<typename T> class Foo{};
359     template<typename T> class Foo<T*>{};
360     [[Foo<int*>]] B;
361   )cpp";
362   EXPECT_DECLS("TemplateSpecializationTypeLoc",
363                {"template<> class Foo<int *>", Rel::TemplateInstantiation},
364                {"template <typename T> class Foo<T *>", Rel::TemplatePattern});
365 
366   Code = R"cpp(
367     // Class template argument deduction
368     template <typename T>
369     struct Test {
370       Test(T);
371     };
372     void foo() {
373       [[Test]] a(5);
374     }
375   )cpp";
376   Flags.push_back("-std=c++17");
377   EXPECT_DECLS("DeducedTemplateSpecializationTypeLoc",
378                {"struct Test", Rel::TemplatePattern});
379 }
380 
381 TEST_F(TargetDeclTest, Concept) {
382   Code = R"cpp(
383     template <typename T>
384     concept Fooable = requires (T t) { t.foo(); };
385 
386     template <typename T> requires [[Fooable]]<T>
387     void bar(T t) {
388       t.foo();
389     }
390   )cpp";
391   Flags.push_back("-std=c++2a");
392   EXPECT_DECLS(
393       "ConceptSpecializationExpr",
394       // FIXME: Should we truncate the pretty-printed form of a concept decl
395       // somewhere?
396       {"template <typename T> concept Fooable = requires (T t) { t.foo(); };"});
397 }
398 
399 TEST_F(TargetDeclTest, FunctionTemplate) {
400   Code = R"cpp(
401     // Implicit specialization.
402     template<typename T> bool foo(T) { return false; };
403     bool x = [[foo]](42);
404   )cpp";
405   EXPECT_DECLS("DeclRefExpr",
406                {"template<> bool foo<int>(int)", Rel::TemplateInstantiation},
407                {"bool foo(T)", Rel::TemplatePattern});
408 
409   Code = R"cpp(
410     // Explicit specialization.
411     template<typename T> bool foo(T) { return false; };
412     template<> bool foo<int>(int) { return false; };
413     bool x = [[foo]](42);
414   )cpp";
415   EXPECT_DECLS("DeclRefExpr", "template<> bool foo<int>(int)");
416 }
417 
418 TEST_F(TargetDeclTest, VariableTemplate) {
419   // Pretty-printer doesn't do a very good job of variable templates :-(
420   Code = R"cpp(
421     // Implicit specialization.
422     template<typename T> int foo;
423     int x = [[foo]]<char>;
424   )cpp";
425   EXPECT_DECLS("DeclRefExpr", {"int foo", Rel::TemplateInstantiation},
426                {"int foo", Rel::TemplatePattern});
427 
428   Code = R"cpp(
429     // Explicit specialization.
430     template<typename T> int foo;
431     template <> bool foo<char>;
432     int x = [[foo]]<char>;
433   )cpp";
434   EXPECT_DECLS("DeclRefExpr", "bool foo");
435 
436   Code = R"cpp(
437     // Partial specialization.
438     template<typename T> int foo;
439     template<typename T> bool foo<T*>;
440     bool x = [[foo]]<char*>;
441   )cpp";
442   EXPECT_DECLS("DeclRefExpr", {"bool foo", Rel::TemplateInstantiation},
443                {"bool foo", Rel::TemplatePattern});
444 }
445 
446 TEST_F(TargetDeclTest, TypeAliasTemplate) {
447   Code = R"cpp(
448     template<typename T, int X> class SmallVector {};
449     template<typename U> using TinyVector = SmallVector<U, 1>;
450     [[TinyVector<int>]] X;
451   )cpp";
452   EXPECT_DECLS("TemplateSpecializationTypeLoc",
453                {"template<> class SmallVector<int, 1>",
454                 Rel::TemplateInstantiation | Rel::Underlying},
455                {"class SmallVector", Rel::TemplatePattern | Rel::Underlying},
456                {"using TinyVector = SmallVector<U, 1>",
457                 Rel::Alias | Rel::TemplatePattern});
458 }
459 
460 TEST_F(TargetDeclTest, MemberOfTemplate) {
461   Code = R"cpp(
462     template <typename T> struct Foo {
463       int x(T);
464     };
465     int y = Foo<int>().[[x]](42);
466   )cpp";
467   EXPECT_DECLS("MemberExpr", {"int x(int)", Rel::TemplateInstantiation},
468                {"int x(T)", Rel::TemplatePattern});
469 
470   Code = R"cpp(
471     template <typename T> struct Foo {
472       template <typename U>
473       int x(T, U);
474     };
475     int y = Foo<char>().[[x]]('c', 42);
476   )cpp";
477   EXPECT_DECLS("MemberExpr",
478                {"template<> int x<int>(char, int)", Rel::TemplateInstantiation},
479                {"int x(T, U)", Rel::TemplatePattern});
480 }
481 
482 TEST_F(TargetDeclTest, Lambda) {
483   Code = R"cpp(
484     void foo(int x = 42) {
485       auto l = [ [[x]] ]{ return x + 1; };
486     };
487   )cpp";
488   EXPECT_DECLS("DeclRefExpr", "int x = 42");
489 
490   // It seems like this should refer to another var, with the outer param being
491   // an underlying decl. But it doesn't seem to exist.
492   Code = R"cpp(
493     void foo(int x = 42) {
494       auto l = [x]{ return [[x]] + 1; };
495     };
496   )cpp";
497   EXPECT_DECLS("DeclRefExpr", "int x = 42");
498 
499   Code = R"cpp(
500     void foo() {
501       auto l = [x = 1]{ return [[x]] + 1; };
502     };
503   )cpp";
504   // FIXME: why both auto and int?
505   EXPECT_DECLS("DeclRefExpr", "auto int x = 1");
506 }
507 
508 TEST_F(TargetDeclTest, OverloadExpr) {
509   // FIXME: Auto-completion in a template requires disabling delayed template
510   // parsing.
511   Flags = {"-fno-delayed-template-parsing"};
512 
513   Code = R"cpp(
514     void func(int*);
515     void func(char*);
516 
517     template <class T>
518     void foo(T t) {
519       [[func]](t);
520     };
521   )cpp";
522   EXPECT_DECLS("UnresolvedLookupExpr", "void func(int *)", "void func(char *)");
523 
524   Code = R"cpp(
525     struct X {
526       void func(int*);
527       void func(char*);
528     };
529 
530     template <class T>
531     void foo(X x, T t) {
532       x.[[func]](t);
533     };
534   )cpp";
535   EXPECT_DECLS("UnresolvedMemberExpr", "void func(int *)", "void func(char *)");
536 }
537 
538 TEST_F(TargetDeclTest, ObjC) {
539   Flags = {"-xobjective-c"};
540   Code = R"cpp(
541     @interface Foo {}
542     -(void)bar;
543     @end
544     void test(Foo *f) {
545       [f [[bar]] ];
546     }
547   )cpp";
548   EXPECT_DECLS("ObjCMessageExpr", "- (void)bar");
549 
550   Code = R"cpp(
551     @interface Foo { @public int bar; }
552     @end
553     int test(Foo *f) {
554       return [[f->bar]];
555     }
556   )cpp";
557   EXPECT_DECLS("ObjCIvarRefExpr", "int bar");
558 
559   Code = R"cpp(
560     @interface Foo {}
561     -(int) x;
562     -(void) setX:(int)x;
563     @end
564     void test(Foo *f) {
565       [[f.x]] = 42;
566     }
567   )cpp";
568   EXPECT_DECLS("ObjCPropertyRefExpr", "- (void)setX:(int)x");
569 
570   Code = R"cpp(
571     @interface I {}
572     @property(retain) I* x;
573     @property(retain) I* y;
574     @end
575     void test(I *f) {
576       [[f.x]].y = 0;
577     }
578   )cpp";
579   EXPECT_DECLS("ObjCPropertyRefExpr",
580                "@property(atomic, retain, readwrite) I *x");
581 
582   Code = R"cpp(
583     @protocol Foo
584     @end
585     id test() {
586       return [[@protocol(Foo)]];
587     }
588   )cpp";
589   EXPECT_DECLS("ObjCProtocolExpr", "@protocol Foo");
590 
591   Code = R"cpp(
592     @interface Foo
593     @end
594     void test([[Foo]] *p);
595   )cpp";
596   EXPECT_DECLS("ObjCInterfaceTypeLoc", "@interface Foo");
597 
598   Code = R"cpp(
599     @protocol Foo
600     @end
601     void test([[id<Foo>]] p);
602   )cpp";
603   EXPECT_DECLS("ObjCObjectTypeLoc", "@protocol Foo");
604 
605   Code = R"cpp(
606     @class C;
607     @protocol Foo
608     @end
609     void test(C<[[Foo]]> *p);
610   )cpp";
611   // FIXME: there's no AST node corresponding to 'Foo', so we're stuck.
612   EXPECT_DECLS("ObjCObjectTypeLoc");
613 }
614 
615 class FindExplicitReferencesTest : public ::testing::Test {
616 protected:
617   struct AllRefs {
618     std::string AnnotatedCode;
619     std::string DumpedReferences;
620   };
621 
622   /// Parses \p Code, finds function or namespace '::foo' and annotates its body
623   /// with results of findExplicitReferences.
624   /// See actual tests for examples of annotation format.
625   AllRefs annotateReferencesInFoo(llvm::StringRef Code) {
626     TestTU TU;
627     TU.Code = std::string(Code);
628 
629     // FIXME: Auto-completion in a template requires disabling delayed template
630     // parsing.
631     TU.ExtraArgs.push_back("-fno-delayed-template-parsing");
632     TU.ExtraArgs.push_back("-std=c++2a");
633     TU.ExtraArgs.push_back("-xobjective-c++");
634 
635     auto AST = TU.build();
636     auto *TestDecl = &findDecl(AST, "foo");
637     if (auto *T = llvm::dyn_cast<FunctionTemplateDecl>(TestDecl))
638       TestDecl = T->getTemplatedDecl();
639 
640     std::vector<ReferenceLoc> Refs;
641     if (const auto *Func = llvm::dyn_cast<FunctionDecl>(TestDecl))
642       findExplicitReferences(Func->getBody(), [&Refs](ReferenceLoc R) {
643         Refs.push_back(std::move(R));
644       });
645     else if (const auto *NS = llvm::dyn_cast<NamespaceDecl>(TestDecl))
646       findExplicitReferences(NS, [&Refs, &NS](ReferenceLoc R) {
647         // Avoid adding the namespace foo decl to the results.
648         if (R.Targets.size() == 1 && R.Targets.front() == NS)
649           return;
650         Refs.push_back(std::move(R));
651       });
652     else
653       ADD_FAILURE() << "Failed to find ::foo decl for test";
654 
655     auto &SM = AST.getSourceManager();
656     llvm::sort(Refs, [&](const ReferenceLoc &L, const ReferenceLoc &R) {
657       return SM.isBeforeInTranslationUnit(L.NameLoc, R.NameLoc);
658     });
659 
660     std::string AnnotatedCode;
661     unsigned NextCodeChar = 0;
662     for (unsigned I = 0; I < Refs.size(); ++I) {
663       auto &R = Refs[I];
664 
665       SourceLocation Pos = R.NameLoc;
666       assert(Pos.isValid());
667       if (Pos.isMacroID()) // FIXME: figure out how to show macro locations.
668         Pos = SM.getExpansionLoc(Pos);
669       assert(Pos.isFileID());
670 
671       FileID File;
672       unsigned Offset;
673       std::tie(File, Offset) = SM.getDecomposedLoc(Pos);
674       if (File == SM.getMainFileID()) {
675         // Print the reference in a source code.
676         assert(NextCodeChar <= Offset);
677         AnnotatedCode += Code.substr(NextCodeChar, Offset - NextCodeChar);
678         AnnotatedCode += "$" + std::to_string(I) + "^";
679 
680         NextCodeChar = Offset;
681       }
682     }
683     AnnotatedCode += Code.substr(NextCodeChar);
684 
685     std::string DumpedReferences;
686     for (unsigned I = 0; I < Refs.size(); ++I)
687       DumpedReferences += std::string(llvm::formatv("{0}: {1}\n", I, Refs[I]));
688 
689     return AllRefs{std::move(AnnotatedCode), std::move(DumpedReferences)};
690   }
691 };
692 
693 TEST_F(FindExplicitReferencesTest, All) {
694   std::pair</*Code*/ llvm::StringRef, /*References*/ llvm::StringRef> Cases[] =
695       {// Simple expressions.
696        {R"cpp(
697         int global;
698         int func();
699         void foo(int param) {
700           $0^global = $1^param + $2^func();
701         }
702         )cpp",
703         "0: targets = {global}\n"
704         "1: targets = {param}\n"
705         "2: targets = {func}\n"},
706        {R"cpp(
707         struct X { int a; };
708         void foo(X x) {
709           $0^x.$1^a = 10;
710         }
711         )cpp",
712         "0: targets = {x}\n"
713         "1: targets = {X::a}\n"},
714        {R"cpp(
715         // error-ok: testing with broken code
716         int bar();
717         int foo() {
718           return $0^bar() + $1^bar(42);
719         }
720         )cpp",
721         "0: targets = {bar}\n"
722         "1: targets = {bar}\n"},
723        // Namespaces and aliases.
724        {R"cpp(
725           namespace ns {}
726           namespace alias = ns;
727           void foo() {
728             using namespace $0^ns;
729             using namespace $1^alias;
730           }
731         )cpp",
732         "0: targets = {ns}\n"
733         "1: targets = {alias}\n"},
734        // Using declarations.
735        {R"cpp(
736           namespace ns { int global; }
737           void foo() {
738             using $0^ns::$1^global;
739           }
740         )cpp",
741         "0: targets = {ns}\n"
742         "1: targets = {ns::global}, qualifier = 'ns::'\n"},
743        // Simple types.
744        {R"cpp(
745          struct Struct { int a; };
746          using Typedef = int;
747          void foo() {
748            $0^Struct $1^x;
749            $2^Typedef $3^y;
750            static_cast<$4^Struct*>(0);
751          }
752        )cpp",
753         "0: targets = {Struct}\n"
754         "1: targets = {x}, decl\n"
755         "2: targets = {Typedef}\n"
756         "3: targets = {y}, decl\n"
757         "4: targets = {Struct}\n"},
758        // Name qualifiers.
759        {R"cpp(
760          namespace a { namespace b { struct S { typedef int type; }; } }
761          void foo() {
762            $0^a::$1^b::$2^S $3^x;
763            using namespace $4^a::$5^b;
764            $6^S::$7^type $8^y;
765          }
766         )cpp",
767         "0: targets = {a}\n"
768         "1: targets = {a::b}, qualifier = 'a::'\n"
769         "2: targets = {a::b::S}, qualifier = 'a::b::'\n"
770         "3: targets = {x}, decl\n"
771         "4: targets = {a}\n"
772         "5: targets = {a::b}, qualifier = 'a::'\n"
773         "6: targets = {a::b::S}\n"
774         "7: targets = {a::b::S::type}, qualifier = 'struct S::'\n"
775         "8: targets = {y}, decl\n"},
776        // Simple templates.
777        {R"cpp(
778           template <class T> struct vector { using value_type = T; };
779           template <> struct vector<bool> { using value_type = bool; };
780           void foo() {
781             $0^vector<int> $1^vi;
782             $2^vector<bool> $3^vb;
783           }
784         )cpp",
785         "0: targets = {vector<int>}\n"
786         "1: targets = {vi}, decl\n"
787         "2: targets = {vector<bool>}\n"
788         "3: targets = {vb}, decl\n"},
789        // Template type aliases.
790        {R"cpp(
791             template <class T> struct vector { using value_type = T; };
792             template <> struct vector<bool> { using value_type = bool; };
793             template <class T> using valias = vector<T>;
794             void foo() {
795               $0^valias<int> $1^vi;
796               $2^valias<bool> $3^vb;
797             }
798           )cpp",
799         "0: targets = {valias}\n"
800         "1: targets = {vi}, decl\n"
801         "2: targets = {valias}\n"
802         "3: targets = {vb}, decl\n"},
803        // Injected class name.
804        {R"cpp(
805             namespace foo {
806               template <typename $0^T>
807               class $1^Bar {
808                 ~$2^Bar();
809                 void $3^f($4^Bar);
810               };
811             }
812           )cpp",
813         "0: targets = {foo::Bar::T}, decl\n"
814         "1: targets = {foo::Bar}, decl\n"
815         "2: targets = {foo::Bar}\n"
816         "3: targets = {foo::Bar::f}, decl\n"
817         "4: targets = {foo::Bar}\n"},
818        // MemberExpr should know their using declaration.
819        {R"cpp(
820             struct X { void func(int); };
821             struct Y : X {
822               using X::func;
823             };
824             void foo(Y y) {
825               $0^y.$1^func(1);
826             }
827         )cpp",
828         "0: targets = {y}\n"
829         "1: targets = {Y::func}\n"},
830        // DeclRefExpr should know their using declaration.
831        {R"cpp(
832             namespace ns { void bar(int); }
833             using ns::bar;
834 
835             void foo() {
836               $0^bar(10);
837             }
838         )cpp",
839         "0: targets = {bar}\n"},
840        // References from a macro.
841        {R"cpp(
842             #define FOO a
843             #define BAR b
844 
845             void foo(int a, int b) {
846               $0^FOO+$1^BAR;
847             }
848         )cpp",
849         "0: targets = {a}\n"
850         "1: targets = {b}\n"},
851        // No references from implicit nodes.
852        {R"cpp(
853             struct vector {
854               int *begin();
855               int *end();
856             };
857 
858             void foo() {
859               for (int $0^x : $1^vector()) {
860                 $2^x = 10;
861               }
862             }
863         )cpp",
864         "0: targets = {x}, decl\n"
865         "1: targets = {vector}\n"
866         "2: targets = {x}\n"},
867 // Handle UnresolvedLookupExpr.
868 // FIXME
869 // This case fails when expensive checks are enabled.
870 // Seems like the order of ns1::func and ns2::func isn't defined.
871 #ifndef EXPENSIVE_CHECKS
872        {R"cpp(
873             namespace ns1 { void func(char*); }
874             namespace ns2 { void func(int*); }
875             using namespace ns1;
876             using namespace ns2;
877 
878             template <class T>
879             void foo(T t) {
880               $0^func($1^t);
881             }
882         )cpp",
883         "0: targets = {ns1::func, ns2::func}\n"
884         "1: targets = {t}\n"},
885 #endif
886        // Handle UnresolvedMemberExpr.
887        {R"cpp(
888             struct X {
889               void func(char*);
890               void func(int*);
891             };
892 
893             template <class T>
894             void foo(X x, T t) {
895               $0^x.$1^func($2^t);
896             }
897         )cpp",
898         "0: targets = {x}\n"
899         "1: targets = {X::func, X::func}\n"
900         "2: targets = {t}\n"},
901        // Handle DependentScopeDeclRefExpr.
902        {R"cpp(
903             template <class T>
904             struct S {
905               static int value;
906             };
907 
908             template <class T>
909             void foo() {
910               $0^S<$1^T>::$2^value;
911             }
912        )cpp",
913         "0: targets = {S}\n"
914         "1: targets = {T}\n"
915         "2: targets = {S::value}, qualifier = 'S<T>::'\n"},
916        // Handle CXXDependentScopeMemberExpr.
917        {R"cpp(
918             template <class T>
919             struct S {
920               int value;
921             };
922 
923             template <class T>
924             void foo(S<T> t) {
925               $0^t.$1^value;
926             }
927        )cpp",
928         "0: targets = {t}\n"
929         "1: targets = {S::value}\n"},
930        // Type template parameters.
931        {R"cpp(
932             template <class T>
933             void foo() {
934               static_cast<$0^T>(0);
935               $1^T();
936               $2^T $3^t;
937             }
938         )cpp",
939         "0: targets = {T}\n"
940         "1: targets = {T}\n"
941         "2: targets = {T}\n"
942         "3: targets = {t}, decl\n"},
943        // Non-type template parameters.
944        {R"cpp(
945             template <int I>
946             void foo() {
947               int $0^x = $1^I;
948             }
949         )cpp",
950         "0: targets = {x}, decl\n"
951         "1: targets = {I}\n"},
952        // Template template parameters.
953        {R"cpp(
954             template <class T> struct vector {};
955 
956             template <template<class> class TT, template<class> class ...TP>
957             void foo() {
958               $0^TT<int> $1^x;
959               $2^foo<$3^TT>();
960               $4^foo<$5^vector>();
961               $6^foo<$7^TP...>();
962             }
963         )cpp",
964         "0: targets = {TT}\n"
965         "1: targets = {x}, decl\n"
966         "2: targets = {foo}\n"
967         "3: targets = {TT}\n"
968         "4: targets = {foo}\n"
969         "5: targets = {vector}\n"
970         "6: targets = {foo}\n"
971         "7: targets = {TP}\n"},
972        // Non-type template parameters with declarations.
973        {R"cpp(
974             int func();
975             template <int(*)()> struct wrapper {};
976 
977             template <int(*FuncParam)()>
978             void foo() {
979               $0^wrapper<$1^func> $2^w;
980               $3^FuncParam();
981             }
982         )cpp",
983         "0: targets = {wrapper<&func>}\n"
984         "1: targets = {func}\n"
985         "2: targets = {w}, decl\n"
986         "3: targets = {FuncParam}\n"},
987        // declaration references.
988        {R"cpp(
989              namespace ns {}
990              class S {};
991              void foo() {
992                class $0^Foo { $1^Foo(); ~$2^Foo(); int $3^field; };
993                int $4^Var;
994                enum $5^E { $6^ABC };
995                typedef int $7^INT;
996                using $8^INT2 = int;
997                namespace $9^NS = $10^ns;
998              }
999            )cpp",
1000         "0: targets = {Foo}, decl\n"
1001         "1: targets = {foo()::Foo::Foo}, decl\n"
1002         "2: targets = {Foo}\n"
1003         "3: targets = {foo()::Foo::field}, decl\n"
1004         "4: targets = {Var}, decl\n"
1005         "5: targets = {E}, decl\n"
1006         "6: targets = {foo()::ABC}, decl\n"
1007         "7: targets = {INT}, decl\n"
1008         "8: targets = {INT2}, decl\n"
1009         "9: targets = {NS}, decl\n"
1010         "10: targets = {ns}\n"},
1011        // User-defined conversion operator.
1012        {R"cpp(
1013             void foo() {
1014                class $0^Bar {};
1015                class $1^Foo {
1016                public:
1017                  // FIXME: This should have only one reference to Bar.
1018                  $2^operator $3^$4^Bar();
1019                };
1020 
1021                $5^Foo $6^f;
1022                $7^f.$8^operator $9^Bar();
1023             }
1024         )cpp",
1025         "0: targets = {Bar}, decl\n"
1026         "1: targets = {Foo}, decl\n"
1027         "2: targets = {foo()::Foo::operator Bar}, decl\n"
1028         "3: targets = {Bar}\n"
1029         "4: targets = {Bar}\n"
1030         "5: targets = {Foo}\n"
1031         "6: targets = {f}, decl\n"
1032         "7: targets = {f}\n"
1033         "8: targets = {foo()::Foo::operator Bar}\n"
1034         "9: targets = {Bar}\n"},
1035        // Destructor.
1036        {R"cpp(
1037              void foo() {
1038                class $0^Foo {
1039                public:
1040                  ~$1^Foo() {}
1041 
1042                  void $2^destructMe() {
1043                    this->~$3^Foo();
1044                  }
1045                };
1046 
1047                $4^Foo $5^f;
1048                $6^f.~ /*...*/ $7^Foo();
1049              }
1050            )cpp",
1051         "0: targets = {Foo}, decl\n"
1052         // FIXME: It's better to target destructor's FunctionDecl instead of
1053         // the type itself (similar to constructor).
1054         "1: targets = {Foo}\n"
1055         "2: targets = {foo()::Foo::destructMe}, decl\n"
1056         "3: targets = {Foo}\n"
1057         "4: targets = {Foo}\n"
1058         "5: targets = {f}, decl\n"
1059         "6: targets = {f}\n"
1060         "7: targets = {Foo}\n"},
1061        // cxx constructor initializer.
1062        {R"cpp(
1063              class Base {};
1064              void foo() {
1065                // member initializer
1066                class $0^X {
1067                  int $1^abc;
1068                  $2^X(): $3^abc() {}
1069                };
1070                // base initializer
1071                class $4^Derived : public $5^Base {
1072                  $6^Base $7^B;
1073                  $8^Derived() : $9^Base() {}
1074                };
1075                // delegating initializer
1076                class $10^Foo {
1077                  $11^Foo(int);
1078                  $12^Foo(): $13^Foo(111) {}
1079                };
1080              }
1081            )cpp",
1082         "0: targets = {X}, decl\n"
1083         "1: targets = {foo()::X::abc}, decl\n"
1084         "2: targets = {foo()::X::X}, decl\n"
1085         "3: targets = {foo()::X::abc}\n"
1086         "4: targets = {Derived}, decl\n"
1087         "5: targets = {Base}\n"
1088         "6: targets = {Base}\n"
1089         "7: targets = {foo()::Derived::B}, decl\n"
1090         "8: targets = {foo()::Derived::Derived}, decl\n"
1091         "9: targets = {Base}\n"
1092         "10: targets = {Foo}, decl\n"
1093         "11: targets = {foo()::Foo::Foo}, decl\n"
1094         "12: targets = {foo()::Foo::Foo}, decl\n"
1095         "13: targets = {Foo}\n"},
1096        // Anonymous entities should not be reported.
1097        {
1098            R"cpp(
1099              void foo() {
1100               class {} $0^x;
1101               int (*$1^fptr)(int $2^a, int) = nullptr;
1102              }
1103            )cpp",
1104            "0: targets = {x}, decl\n"
1105            "1: targets = {fptr}, decl\n"
1106            "2: targets = {a}, decl\n"},
1107        // Namespace aliases should be handled properly.
1108        {
1109            R"cpp(
1110                 namespace ns { struct Type {}; }
1111                 namespace alias = ns;
1112                 namespace rec_alias = alias;
1113 
1114                 void foo() {
1115                   $0^ns::$1^Type $2^a;
1116                   $3^alias::$4^Type $5^b;
1117                   $6^rec_alias::$7^Type $8^c;
1118                 }
1119            )cpp",
1120            "0: targets = {ns}\n"
1121            "1: targets = {ns::Type}, qualifier = 'ns::'\n"
1122            "2: targets = {a}, decl\n"
1123            "3: targets = {alias}\n"
1124            "4: targets = {ns::Type}, qualifier = 'alias::'\n"
1125            "5: targets = {b}, decl\n"
1126            "6: targets = {rec_alias}\n"
1127            "7: targets = {ns::Type}, qualifier = 'rec_alias::'\n"
1128            "8: targets = {c}, decl\n"},
1129        // Handle SizeOfPackExpr.
1130        {
1131            R"cpp(
1132                 template <typename... E>
1133                 void foo() {
1134                   constexpr int $0^size = sizeof...($1^E);
1135                 };
1136             )cpp",
1137            "0: targets = {size}, decl\n"
1138            "1: targets = {E}\n"},
1139        // Class template argument deduction
1140        {
1141            R"cpp(
1142                 template <typename T>
1143                 struct Test {
1144                 Test(T);
1145               };
1146               void foo() {
1147                 $0^Test $1^a(5);
1148               }
1149             )cpp",
1150            "0: targets = {Test}\n"
1151            "1: targets = {a}, decl\n"},
1152        // Templates
1153        {R"cpp(
1154             namespace foo {
1155               template <typename $0^T>
1156               class $1^Bar {};
1157             }
1158           )cpp",
1159         "0: targets = {foo::Bar::T}, decl\n"
1160         "1: targets = {foo::Bar}, decl\n"},
1161        // Templates
1162        {R"cpp(
1163             namespace foo {
1164               template <typename $0^T>
1165               void $1^func();
1166             }
1167           )cpp",
1168         "0: targets = {T}, decl\n"
1169         "1: targets = {foo::func}, decl\n"},
1170        // Templates
1171        {R"cpp(
1172             namespace foo {
1173               template <typename $0^T>
1174               $1^T $2^x;
1175             }
1176           )cpp",
1177         "0: targets = {foo::T}, decl\n"
1178         "1: targets = {foo::T}\n"
1179         "2: targets = {foo::x}, decl\n"},
1180        // Templates
1181        {R"cpp(
1182             template<typename T> class vector {};
1183             namespace foo {
1184               template <typename $0^T>
1185               using $1^V = $2^vector<$3^T>;
1186             }
1187           )cpp",
1188         "0: targets = {foo::T}, decl\n"
1189         "1: targets = {foo::V}, decl\n"
1190         "2: targets = {vector}\n"
1191         "3: targets = {foo::T}\n"},
1192        // Concept
1193        {
1194            R"cpp(
1195               template <typename T>
1196               concept Drawable = requires (T t) { t.draw(); };
1197 
1198               namespace foo {
1199                 template <typename $0^T> requires $1^Drawable<$2^T>
1200                 void $3^bar($4^T $5^t) {
1201                   $6^t.$7^draw();
1202                 }
1203               }
1204           )cpp",
1205            "0: targets = {T}, decl\n"
1206            "1: targets = {Drawable}\n"
1207            "2: targets = {T}\n"
1208            "3: targets = {foo::bar}, decl\n"
1209            "4: targets = {T}\n"
1210            "5: targets = {t}, decl\n"
1211            "6: targets = {t}\n"
1212            "7: targets = {}\n"},
1213        // Objective-C: properties
1214        {
1215            R"cpp(
1216             @interface I {}
1217             @property(retain) I* x;
1218             @property(retain) I* y;
1219             @end
1220             I *f;
1221             void foo() {
1222               $0^f.$1^x.$2^y = 0;
1223             }
1224           )cpp",
1225            "0: targets = {f}\n"
1226            "1: targets = {I::x}\n"
1227            "2: targets = {I::y}\n"},
1228        // Objective-C: implicit properties
1229        {
1230            R"cpp(
1231             @interface I {}
1232             -(I*)x;
1233             -(void)setY:(I*)y;
1234             @end
1235             I *f;
1236             void foo() {
1237               $0^f.$1^x.$2^y = 0;
1238             }
1239           )cpp",
1240            "0: targets = {f}\n"
1241            "1: targets = {I::x}\n"
1242            "2: targets = {I::setY:}\n"},
1243        // Designated initializers.
1244        {R"cpp(
1245             void foo() {
1246               struct $0^Foo {
1247                 int $1^Bar;
1248               };
1249               $2^Foo $3^f { .$4^Bar = 42 };
1250             }
1251         )cpp",
1252         "0: targets = {Foo}, decl\n"
1253         "1: targets = {foo()::Foo::Bar}, decl\n"
1254         "2: targets = {Foo}\n"
1255         "3: targets = {f}, decl\n"
1256         "4: targets = {foo()::Foo::Bar}\n"},
1257        {R"cpp(
1258             void foo() {
1259               struct $0^Baz {
1260                 int $1^Field;
1261               };
1262               struct $2^Bar {
1263                 $3^Baz $4^Foo;
1264               };
1265               $5^Bar $6^bar { .$7^Foo.$8^Field = 42 };
1266             }
1267         )cpp",
1268         "0: targets = {Baz}, decl\n"
1269         "1: targets = {foo()::Baz::Field}, decl\n"
1270         "2: targets = {Bar}, decl\n"
1271         "3: targets = {Baz}\n"
1272         "4: targets = {foo()::Bar::Foo}, decl\n"
1273         "5: targets = {Bar}\n"
1274         "6: targets = {bar}, decl\n"
1275         "7: targets = {foo()::Bar::Foo}\n"
1276         "8: targets = {foo()::Baz::Field}\n"},
1277       {R"cpp(
1278            template<typename T>
1279            void crash(T);
1280            template<typename T>
1281            void foo() {
1282              $0^crash({.$1^x = $2^T()});
1283            }
1284         )cpp",
1285         "0: targets = {crash}\n"
1286         "1: targets = {}\n"
1287         "2: targets = {T}\n"
1288       },
1289       // unknown template name should not crash.
1290       {R"cpp(
1291         template <template <typename> typename T>
1292         struct Base {};
1293         namespace foo {
1294         template <typename $0^T>
1295         struct $1^Derive : $2^Base<$3^T::template $4^Unknown> {};
1296         }
1297       )cpp",
1298       "0: targets = {foo::Derive::T}, decl\n"
1299       "1: targets = {foo::Derive}, decl\n"
1300       "2: targets = {Base}\n"
1301       "3: targets = {foo::Derive::T}\n"
1302       "4: targets = {}, qualifier = 'T::'\n"},
1303     };
1304 
1305   for (const auto &C : Cases) {
1306     llvm::StringRef ExpectedCode = C.first;
1307     llvm::StringRef ExpectedRefs = C.second;
1308 
1309     auto Actual =
1310         annotateReferencesInFoo(llvm::Annotations(ExpectedCode).code());
1311     EXPECT_EQ(ExpectedCode, Actual.AnnotatedCode);
1312     EXPECT_EQ(ExpectedRefs, Actual.DumpedReferences) << ExpectedCode;
1313   }
1314 }
1315 
1316 } // namespace
1317 } // namespace clangd
1318 } // namespace clang
1319