clang-tools 19.0.0git
FindTargetTests.cpp
Go to the documentation of this file.
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/Annotations/Annotations.h"
19#include "gmock/gmock.h"
20#include "gtest/gtest.h"
21#include <initializer_list>
22
23namespace clang {
24namespace clangd {
25namespace {
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.
34struct 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};
51bool operator==(const PrintedDecl &L, const PrintedDecl &R) {
52 return std::tie(L.Name, L.Relations) == std::tie(R.Name, R.Relations);
53}
54llvm::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.
64class TargetDeclTest : public ::testing::Test {
65protected:
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 :
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
103using ExpectedDecls = std::vector<PrintedDecl>;
104
105TEST_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
152TEST_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
163TEST_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
173TEST_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
186TEST_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 // Using enum.
284 Flags.push_back("-std=c++20");
285 Code = R"cpp(
286 namespace ns { enum class A { X }; }
287 [[using enum ns::A]];
288 )cpp";
289 EXPECT_DECLS("UsingEnumDecl", "enum class A : int");
290
291 Code = R"cpp(
292 namespace ns { enum class A { X }; }
293 using enum ns::A;
294 auto m = [[X]];
295 )cpp";
296 EXPECT_DECLS("DeclRefExpr", "X");
297}
298
299TEST_F(TargetDeclTest, BaseSpecifier) {
300 Code = R"cpp(
301 struct X {};
302 struct Y : [[private]] X {};
303 )cpp";
304 EXPECT_DECLS("CXXBaseSpecifier", "struct X");
305 Code = R"cpp(
306 struct X {};
307 struct Y : [[private X]] {};
308 )cpp";
309 EXPECT_DECLS("CXXBaseSpecifier", "struct X");
310 Code = R"cpp(
311 struct X {};
312 struct Y : private [[X]] {};
313 )cpp";
314 EXPECT_DECLS("RecordTypeLoc", "struct X");
315}
316
317TEST_F(TargetDeclTest, ConstructorInitList) {
318 Code = R"cpp(
319 struct X {
320 int a;
321 X() : [[a]](42) {}
322 };
323 )cpp";
324 EXPECT_DECLS("CXXCtorInitializer", "int a");
325
326 Code = R"cpp(
327 struct X {
328 X() : [[X]](1) {}
329 X(int);
330 };
331 )cpp";
332 EXPECT_DECLS("RecordTypeLoc", "struct X");
333}
334
335TEST_F(TargetDeclTest, DesignatedInit) {
336 Flags = {"-xc"}; // array designators are a C99 extension.
337 Code = R"c(
338 struct X { int a; };
339 struct Y { int b; struct X c[2]; };
340 struct Y y = { .c[0].[[a]] = 1 };
341 )c";
342 EXPECT_DECLS("DesignatedInitExpr", "int a");
343}
344
345TEST_F(TargetDeclTest, NestedNameSpecifier) {
346 Code = R"cpp(
347 namespace a { namespace b { int c; } }
348 int x = a::[[b::]]c;
349 )cpp";
350 EXPECT_DECLS("NestedNameSpecifierLoc", "namespace b");
351
352 Code = R"cpp(
353 namespace a { struct X { enum { y }; }; }
354 int x = a::[[X::]]y;
355 )cpp";
356 EXPECT_DECLS("NestedNameSpecifierLoc", "struct X");
357
358 Code = R"cpp(
359 template <typename T>
360 int x = [[T::]]y;
361 )cpp";
362 EXPECT_DECLS("NestedNameSpecifierLoc", "typename T");
363
364 Code = R"cpp(
365 namespace a { int x; }
366 namespace b = a;
367 int y = [[b]]::x;
368 )cpp";
369 EXPECT_DECLS("NestedNameSpecifierLoc", {"namespace b = a", Rel::Alias},
370 {"namespace a", Rel::Underlying});
371}
372
373TEST_F(TargetDeclTest, Types) {
374 Code = R"cpp(
375 struct X{};
376 [[X]] x;
377 )cpp";
378 EXPECT_DECLS("RecordTypeLoc", "struct X");
379
380 Code = R"cpp(
381 struct S{};
382 typedef S X;
383 [[X]] x;
384 )cpp";
385 EXPECT_DECLS("TypedefTypeLoc", {"typedef S X", Rel::Alias},
386 {"struct S", Rel::Underlying});
387 Code = R"cpp(
388 namespace ns { struct S{}; }
389 typedef ns::S X;
390 [[X]] x;
391 )cpp";
392 EXPECT_DECLS("TypedefTypeLoc", {"typedef ns::S X", Rel::Alias},
393 {"struct S", Rel::Underlying});
394
395 Code = R"cpp(
396 template<class T>
397 void foo() { [[T]] x; }
398 )cpp";
399 EXPECT_DECLS("TemplateTypeParmTypeLoc", "class T");
400 Flags.clear();
401
402 Code = R"cpp(
403 template<template<typename> class T>
404 void foo() { [[T<int>]] x; }
405 )cpp";
406 EXPECT_DECLS("TemplateSpecializationTypeLoc", "template <typename> class T");
407 Flags.clear();
408
409 Code = R"cpp(
410 template<template<typename> class ...T>
411 class C {
412 C<[[T...]]> foo;
413 };
414 )cpp";
415 EXPECT_DECLS("TemplateArgumentLoc", {"template <typename> class ...T"});
416 Flags.clear();
417
418 Code = R"cpp(
419 struct S{};
420 S X;
421 [[decltype]](X) Y;
422 )cpp";
423 EXPECT_DECLS("DecltypeTypeLoc", {"struct S", Rel::Underlying});
424
425 Code = R"cpp(
426 struct S{};
427 [[auto]] X = S{};
428 )cpp";
429 // FIXME: deduced type missing in AST. https://llvm.org/PR42914
430 EXPECT_DECLS("AutoTypeLoc", );
431
432 Code = R"cpp(
433 template <typename... E>
434 struct S {
435 static const int size = sizeof...([[E]]);
436 };
437 )cpp";
438 EXPECT_DECLS("SizeOfPackExpr", "typename ...E");
439
440 Code = R"cpp(
441 template <typename T>
442 class Foo {
443 void f([[Foo]] x);
444 };
445 )cpp";
446 EXPECT_DECLS("InjectedClassNameTypeLoc", "class Foo");
447}
448
449TEST_F(TargetDeclTest, ClassTemplate) {
450 Code = R"cpp(
451 // Implicit specialization.
452 template<int x> class Foo{};
453 [[Foo<42>]] B;
454 )cpp";
455 EXPECT_DECLS("TemplateSpecializationTypeLoc",
456 {"template<> class Foo<42>", Rel::TemplateInstantiation},
457 {"class Foo", Rel::TemplatePattern});
458
459 Code = R"cpp(
460 template<typename T> class Foo {};
461 // The "Foo<int>" SpecializationDecl is incomplete, there is no
462 // instantiation happening.
463 void func([[Foo<int>]] *);
464 )cpp";
465 EXPECT_DECLS("TemplateSpecializationTypeLoc",
466 {"class Foo", Rel::TemplatePattern},
467 {"template<> class Foo<int>", Rel::TemplateInstantiation});
468
469 Code = R"cpp(
470 // Explicit specialization.
471 template<int x> class Foo{};
472 template<> class Foo<42>{};
473 [[Foo<42>]] B;
474 )cpp";
475 EXPECT_DECLS("TemplateSpecializationTypeLoc", "template<> class Foo<42>");
476
477 Code = R"cpp(
478 // Partial specialization.
479 template<typename T> class Foo{};
480 template<typename T> class Foo<T*>{};
481 [[Foo<int*>]] B;
482 )cpp";
483 EXPECT_DECLS("TemplateSpecializationTypeLoc",
484 {"template<> class Foo<int *>", Rel::TemplateInstantiation},
485 {"template <typename T> class Foo<T *>", Rel::TemplatePattern});
486
487 Code = R"cpp(
488 // Template template argument.
489 template<typename T> struct Vector {};
490 template <template <typename> class Container>
491 struct A {};
492 A<[[Vector]]> a;
493 )cpp";
494 EXPECT_DECLS("TemplateArgumentLoc", {"template <typename T> struct Vector"});
495
496 Flags.push_back("-std=c++17"); // for CTAD tests
497
498 Code = R"cpp(
499 // Class template argument deduction
500 template <typename T>
501 struct Test {
502 Test(T);
503 };
504 void foo() {
505 [[Test]] a(5);
506 }
507 )cpp";
508 EXPECT_DECLS("DeducedTemplateSpecializationTypeLoc",
509 {"struct Test", Rel::TemplatePattern});
510
511 Code = R"cpp(
512 // Deduction guide
513 template <typename T>
514 struct Test {
515 template <typename I>
516 Test(I, I);
517 };
518 template <typename I>
519 [[Test]](I, I) -> Test<typename I::type>;
520 )cpp";
521 EXPECT_DECLS("CXXDeductionGuideDecl", {"template <typename T> struct Test"});
522}
523
524TEST_F(TargetDeclTest, Concept) {
525 Flags.push_back("-std=c++20");
526
527 // FIXME: Should we truncate the pretty-printed form of a concept decl
528 // somewhere?
529
530 Code = R"cpp(
531 template <typename T>
532 concept Fooable = requires (T t) { t.foo(); };
533
534 template <typename T> requires [[Fooable]]<T>
535 void bar(T t) {
536 t.foo();
537 }
538 )cpp";
540 "ConceptReference",
541 {"template <typename T> concept Fooable = requires (T t) { t.foo(); }"});
542
543 // trailing requires clause
544 Code = R"cpp(
545 template <typename T>
546 concept Fooable = true;
547
548 template <typename T>
549 void foo() requires [[Fooable]]<T>;
550 )cpp";
551 EXPECT_DECLS("ConceptReference",
552 {"template <typename T> concept Fooable = true"});
553
554 // constrained-parameter
555 Code = R"cpp(
556 template <typename T>
557 concept Fooable = true;
558
559 template <[[Fooable]] T>
560 void bar(T t);
561 )cpp";
562 EXPECT_DECLS("ConceptReference",
563 {"template <typename T> concept Fooable = true"});
564
565 // partial-concept-id
566 Code = R"cpp(
567 template <typename T, typename U>
568 concept Fooable = true;
569
570 template <[[Fooable]]<int> T>
571 void bar(T t);
572 )cpp";
573 EXPECT_DECLS("ConceptReference",
574 {"template <typename T, typename U> concept Fooable = true"});
575}
576
577TEST_F(TargetDeclTest, Coroutine) {
578 Flags.push_back("-std=c++20");
579
580 Code = R"cpp(
581 namespace std {
582 template <typename, typename...> struct coroutine_traits;
583 template <typename> struct coroutine_handle {
584 template <typename U>
585 coroutine_handle(coroutine_handle<U>&&) noexcept;
586 static coroutine_handle from_address(void* __addr) noexcept;
587 };
588 } // namespace std
589
590 struct executor {};
591 struct awaitable {};
592 struct awaitable_frame {
593 awaitable get_return_object();
594 void return_void();
595 void unhandled_exception();
596 struct result_t {
597 ~result_t();
598 bool await_ready() const noexcept;
599 void await_suspend(std::coroutine_handle<void>) noexcept;
600 void await_resume() const noexcept;
601 };
602 result_t initial_suspend() noexcept;
603 result_t final_suspend() noexcept;
604 result_t await_transform(executor) noexcept;
605 };
606
607 namespace std {
608 template <>
609 struct coroutine_traits<awaitable> {
610 typedef awaitable_frame promise_type;
611 };
612 } // namespace std
613
614 awaitable foo() {
615 co_await [[executor]]();
616 }
617 )cpp";
618 EXPECT_DECLS("RecordTypeLoc", "struct executor");
619}
620
621TEST_F(TargetDeclTest, RewrittenBinaryOperator) {
622 Flags.push_back("-std=c++20");
623
624 Code = R"cpp(
625 namespace std {
626 struct strong_ordering {
627 int n;
628 constexpr operator int() const { return n; }
629 static const strong_ordering equal, greater, less;
630 };
631 constexpr strong_ordering strong_ordering::equal = {0};
632 constexpr strong_ordering strong_ordering::greater = {1};
633 constexpr strong_ordering strong_ordering::less = {-1};
634 }
635
636 struct Foo
637 {
638 int x;
639 auto operator<=>(const Foo&) const = default;
640 };
641
642 bool x = (Foo(1) [[!=]] Foo(2));
643 )cpp";
644 EXPECT_DECLS("CXXRewrittenBinaryOperator",
645 {"bool operator==(const Foo &) const noexcept = default"});
646}
647
648TEST_F(TargetDeclTest, FunctionTemplate) {
649 Code = R"cpp(
650 // Implicit specialization.
651 template<typename T> bool foo(T) { return false; };
652 bool x = [[foo]](42);
653 )cpp";
654 EXPECT_DECLS("DeclRefExpr",
655 {"template<> bool foo<int>(int)", Rel::TemplateInstantiation},
656 {"bool foo(T)", Rel::TemplatePattern});
657
658 Code = R"cpp(
659 // Explicit specialization.
660 template<typename T> bool foo(T) { return false; };
661 template<> bool foo<int>(int) { return false; };
662 bool x = [[foo]](42);
663 )cpp";
664 EXPECT_DECLS("DeclRefExpr", "template<> bool foo<int>(int)");
665}
666
667TEST_F(TargetDeclTest, VariableTemplate) {
668 // Pretty-printer doesn't do a very good job of variable templates :-(
669 Code = R"cpp(
670 // Implicit specialization.
671 template<typename T> int foo;
672 int x = [[foo]]<char>;
673 )cpp";
674 EXPECT_DECLS("DeclRefExpr", {"int foo", Rel::TemplateInstantiation},
675 {"int foo", Rel::TemplatePattern});
676
677 Code = R"cpp(
678 // Explicit specialization.
679 template<typename T> int foo;
680 template <> bool foo<char>;
681 int x = [[foo]]<char>;
682 )cpp";
683 EXPECT_DECLS("DeclRefExpr", "bool foo");
684
685 Code = R"cpp(
686 // Partial specialization.
687 template<typename T> int foo;
688 template<typename T> bool foo<T*>;
689 bool x = [[foo]]<char*>;
690 )cpp";
691 EXPECT_DECLS("DeclRefExpr", {"bool foo", Rel::TemplateInstantiation},
692 {"bool foo", Rel::TemplatePattern});
693}
694
695TEST_F(TargetDeclTest, TypeAliasTemplate) {
696 Code = R"cpp(
697 template<typename T, int X> class SmallVector {};
698 template<typename U> using TinyVector = SmallVector<U, 1>;
699 [[TinyVector<int>]] X;
700 )cpp";
701 EXPECT_DECLS("TemplateSpecializationTypeLoc",
702 {"template<> class SmallVector<int, 1>",
703 Rel::TemplateInstantiation | Rel::Underlying},
704 {"class SmallVector", Rel::TemplatePattern | Rel::Underlying},
705 {"using TinyVector = SmallVector<U, 1>",
706 Rel::Alias | Rel::TemplatePattern});
707}
708
709TEST_F(TargetDeclTest, BuiltinTemplates) {
710 Code = R"cpp(
711 template <class T, T... Index> struct integer_sequence {};
712 [[__make_integer_seq]]<integer_sequence, int, 3> X;
713 )cpp";
715 "TemplateSpecializationTypeLoc",
716 {"struct integer_sequence", Rel::TemplatePattern | Rel::Underlying},
717 {"template<> struct integer_sequence<int, <0, 1, 2>>",
718 Rel::TemplateInstantiation | Rel::Underlying});
719
720 // Dependent context.
721 Code = R"cpp(
722 template <class T, T... Index> struct integer_sequence;
723
724 template <class T, int N>
725 using make_integer_sequence = [[__make_integer_seq]]<integer_sequence, T, N>;
726 )cpp";
727 EXPECT_DECLS("TemplateSpecializationTypeLoc", );
728
729 Code = R"cpp(
730 template <int N, class... Pack>
731 using type_pack_element = [[__type_pack_element]]<N, Pack...>;
732 )cpp";
733 EXPECT_DECLS("TemplateSpecializationTypeLoc", );
734}
735
736TEST_F(TargetDeclTest, MemberOfTemplate) {
737 Code = R"cpp(
738 template <typename T> struct Foo {
739 int x(T);
740 };
741 int y = Foo<int>().[[x]](42);
742 )cpp";
743 EXPECT_DECLS("MemberExpr", {"int x(int)", Rel::TemplateInstantiation},
744 {"int x(T)", Rel::TemplatePattern});
745
746 Code = R"cpp(
747 template <typename T> struct Foo {
748 template <typename U>
749 int x(T, U);
750 };
751 int y = Foo<char>().[[x]]('c', 42);
752 )cpp";
753 EXPECT_DECLS("MemberExpr",
754 {"template<> int x<int>(char, int)", Rel::TemplateInstantiation},
755 {"int x(T, U)", Rel::TemplatePattern});
756}
757
758TEST_F(TargetDeclTest, Lambda) {
759 Code = R"cpp(
760 void foo(int x = 42) {
761 auto l = [ [[x]] ]{ return x + 1; };
762 };
763 )cpp";
764 EXPECT_DECLS("DeclRefExpr", "int x = 42");
765
766 // It seems like this should refer to another var, with the outer param being
767 // an underlying decl. But it doesn't seem to exist.
768 Code = R"cpp(
769 void foo(int x = 42) {
770 auto l = [x]{ return [[x]] + 1; };
771 };
772 )cpp";
773 EXPECT_DECLS("DeclRefExpr", "int x = 42");
774
775 Code = R"cpp(
776 void foo() {
777 auto l = [x = 1]{ return [[x]] + 1; };
778 };
779 )cpp";
780 // FIXME: why both auto and int?
781 EXPECT_DECLS("DeclRefExpr", "auto int x = 1");
782}
783
784TEST_F(TargetDeclTest, OverloadExpr) {
785 Flags.push_back("--target=x86_64-pc-linux-gnu");
786
787 Code = R"cpp(
788 void func(int*);
789 void func(char*);
790
791 template <class T>
792 void foo(T t) {
793 [[func]](t);
794 };
795 )cpp";
796 EXPECT_DECLS("UnresolvedLookupExpr", "void func(int *)", "void func(char *)");
797
798 Code = R"cpp(
799 struct X {
800 void func(int*);
801 void func(char*);
802 };
803
804 template <class T>
805 void foo(X x, T t) {
806 x.[[func]](t);
807 };
808 )cpp";
809 EXPECT_DECLS("UnresolvedMemberExpr", "void func(int *)", "void func(char *)");
810
811 Code = R"cpp(
812 struct X {
813 static void *operator new(unsigned long);
814 };
815 auto* k = [[new]] X();
816 )cpp";
817 EXPECT_DECLS("CXXNewExpr", "static void *operator new(unsigned long)");
818 Code = R"cpp(
819 void *operator new(unsigned long);
820 auto* k = [[new]] int();
821 )cpp";
822 EXPECT_DECLS("CXXNewExpr", "void *operator new(unsigned long)");
823
824 Code = R"cpp(
825 struct X {
826 static void operator delete(void *) noexcept;
827 };
828 void k(X* x) {
829 [[delete]] x;
830 }
831 )cpp";
832 EXPECT_DECLS("CXXDeleteExpr", "static void operator delete(void *) noexcept");
833 Code = R"cpp(
834 void operator delete(void *) noexcept;
835 void k(int* x) {
836 [[delete]] x;
837 }
838 )cpp";
839 // Sized deallocation is enabled by default in C++14 onwards.
840 EXPECT_DECLS("CXXDeleteExpr",
841 "void operator delete(void *, unsigned long) noexcept");
842}
843
844TEST_F(TargetDeclTest, DependentExprs) {
845 // Heuristic resolution of method of dependent field
846 Code = R"cpp(
847 struct A { void foo() {} };
848 template <typename T>
849 struct B {
850 A a;
851 void bar() {
852 this->a.[[foo]]();
853 }
854 };
855 )cpp";
856 EXPECT_DECLS("MemberExpr", "void foo()");
857
858 // Similar to above but base expression involves a function call.
859 Code = R"cpp(
860 struct A {
861 void foo() {}
862 };
863 struct B {
864 A getA();
865 };
866 template <typename T>
867 struct C {
868 B c;
869 void bar() {
870 this->c.getA().[[foo]]();
871 }
872 };
873 )cpp";
874 EXPECT_DECLS("MemberExpr", "void foo()");
875
876 // Similar to above but uses a function pointer.
877 Code = R"cpp(
878 struct A {
879 void foo() {}
880 };
881 struct B {
882 using FPtr = A(*)();
883 FPtr fptr;
884 };
885 template <typename T>
886 struct C {
887 B c;
888 void bar() {
889 this->c.fptr().[[foo]]();
890 }
891 };
892 )cpp";
893 EXPECT_DECLS("MemberExpr", "void foo()");
894
895 // Base expression involves a member access into this.
896 Code = R"cpp(
897 struct Bar {
898 int aaaa;
899 };
900 template <typename T> struct Foo {
901 Bar func(int);
902 void test() {
903 func(1).[[aaaa]];
904 }
905 };
906 )cpp";
907 EXPECT_DECLS("CXXDependentScopeMemberExpr", "int aaaa");
908
909 Code = R"cpp(
910 class Foo {
911 public:
912 static Foo k(int);
913 template <typename T> T convert() const;
914 };
915 template <typename T>
916 void test() {
917 Foo::k(T()).template [[convert]]<T>();
918 }
919 )cpp";
920 EXPECT_DECLS("CXXDependentScopeMemberExpr",
921 "template <typename T> T convert() const");
922
923 Code = R"cpp(
924 template <typename T>
925 struct Waldo {
926 void find();
927 };
928 template <typename T>
929 using Wally = Waldo<T>;
930 template <typename T>
931 void foo(Wally<T> w) {
932 w.[[find]]();
933 }
934 )cpp";
935 EXPECT_DECLS("CXXDependentScopeMemberExpr", "void find()");
936
937 Code = R"cpp(
938 template <typename T>
939 struct Waldo {
940 void find();
941 };
942 template <typename T>
943 struct MetaWaldo {
944 using Type = Waldo<T>;
945 };
946 template <typename T>
947 void foo(typename MetaWaldo<T>::Type w) {
948 w.[[find]]();
949 }
950 )cpp";
951 EXPECT_DECLS("CXXDependentScopeMemberExpr", "void find()");
952
953 Code = R"cpp(
954 struct Waldo {
955 void find();
956 };
957 template <typename T>
958 using Wally = Waldo;
959 template <typename>
960 struct S : Wally<int> {
961 void Foo() { this->[[find]](); }
962 };
963 )cpp";
964 EXPECT_DECLS("MemberExpr", "void find()");
965}
966
967TEST_F(TargetDeclTest, DependentTypes) {
968 // Heuristic resolution of dependent type name
969 Code = R"cpp(
970 template <typename>
971 struct A { struct B {}; };
972
973 template <typename T>
974 void foo(typename A<T>::[[B]]);
975 )cpp";
976 EXPECT_DECLS("DependentNameTypeLoc", "struct B");
977
978 // Heuristic resolution of dependent type name which doesn't get a TypeLoc
979 Code = R"cpp(
980 template <typename>
981 struct A { struct B { struct C {}; }; };
982
983 template <typename T>
984 void foo(typename A<T>::[[B]]::C);
985 )cpp";
986 EXPECT_DECLS("NestedNameSpecifierLoc", "struct B");
987
988 // Heuristic resolution of dependent type name whose qualifier is also
989 // dependent
990 Code = R"cpp(
991 template <typename>
992 struct A { struct B { struct C {}; }; };
993
994 template <typename T>
995 void foo(typename A<T>::B::[[C]]);
996 )cpp";
997 EXPECT_DECLS("DependentNameTypeLoc", "struct C");
998
999 // Heuristic resolution of dependent template name
1000 Code = R"cpp(
1001 template <typename>
1002 struct A {
1003 template <typename> struct B {};
1004 };
1005
1006 template <typename T>
1007 void foo(typename A<T>::template [[B]]<int>);
1008 )cpp";
1009 EXPECT_DECLS("DependentTemplateSpecializationTypeLoc",
1010 "template <typename> struct B");
1011
1012 // Dependent name with recursive definition. We don't expect a
1013 // result, but we shouldn't get into a stack overflow either.
1014 Code = R"cpp(
1015 template <int N>
1016 struct waldo {
1017 typedef typename waldo<N - 1>::type::[[next]] type;
1018 };
1019 )cpp";
1020 EXPECT_DECLS("DependentNameTypeLoc", );
1021
1022 // Similar to above but using mutually recursive templates.
1023 Code = R"cpp(
1024 template <int N>
1025 struct odd;
1026
1027 template <int N>
1028 struct even {
1029 using type = typename odd<N - 1>::type::next;
1030 };
1031
1032 template <int N>
1033 struct odd {
1034 using type = typename even<N - 1>::type::[[next]];
1035 };
1036 )cpp";
1037 EXPECT_DECLS("DependentNameTypeLoc", );
1038}
1039
1040TEST_F(TargetDeclTest, TypedefCascade) {
1041 Code = R"cpp(
1042 struct C {
1043 using type = int;
1044 };
1045 struct B {
1046 using type = C::type;
1047 };
1048 struct A {
1049 using type = B::type;
1050 };
1051 A::[[type]] waldo;
1052 )cpp";
1053 EXPECT_DECLS("TypedefTypeLoc",
1054 {"using type = int", Rel::Alias | Rel::Underlying},
1055 {"using type = C::type", Rel::Alias | Rel::Underlying},
1056 {"using type = B::type", Rel::Alias});
1057}
1058
1059TEST_F(TargetDeclTest, RecursiveTemplate) {
1060 Flags.push_back("-std=c++20"); // the test case uses concepts
1061
1062 Code = R"cpp(
1063 template <typename T>
1064 concept Leaf = false;
1065
1066 template <typename Tree>
1067 struct descend_left {
1068 using type = typename descend_left<typename Tree::left>::[[type]];
1069 };
1070
1071 template <Leaf Tree>
1072 struct descend_left<Tree> {
1073 using type = typename Tree::value;
1074 };
1075 )cpp";
1076 EXPECT_DECLS("DependentNameTypeLoc",
1077 {"using type = typename descend_left<typename Tree::left>::type",
1078 Rel::Alias | Rel::Underlying});
1079}
1080
1081TEST_F(TargetDeclTest, ObjC) {
1082 Flags = {"-xobjective-c"};
1083 Code = R"cpp(
1084 @interface Foo {}
1085 -(void)bar;
1086 @end
1087 void test(Foo *f) {
1088 [f [[bar]] ];
1089 }
1090 )cpp";
1091 EXPECT_DECLS("ObjCMessageExpr", "- (void)bar");
1092
1093 Code = R"cpp(
1094 @interface Foo { @public int bar; }
1095 @end
1096 int test(Foo *f) {
1097 return [[f->bar]];
1098 }
1099 )cpp";
1100 EXPECT_DECLS("ObjCIvarRefExpr", "int bar");
1101
1102 Code = R"cpp(
1103 @interface Foo {}
1104 -(int) x;
1105 -(void) setX:(int)x;
1106 @end
1107 void test(Foo *f) {
1108 [[f.x]] = 42;
1109 }
1110 )cpp";
1111 EXPECT_DECLS("ObjCPropertyRefExpr", "- (void)setX:(int)x");
1112
1113 Code = R"cpp(
1114 @interface I {}
1115 @property(retain) I* x;
1116 @property(retain) I* y;
1117 @end
1118 void test(I *f) {
1119 [[f.x]].y = 0;
1120 }
1121 )cpp";
1122 EXPECT_DECLS("ObjCPropertyRefExpr",
1123 "@property(atomic, retain, readwrite) I *x");
1124
1125 Code = R"cpp(
1126 @interface MYObject
1127 @end
1128 @interface Interface
1129 @property(retain) [[MYObject]] *x;
1130 @end
1131 )cpp";
1132 EXPECT_DECLS("ObjCInterfaceTypeLoc", "@interface MYObject");
1133
1134 Code = R"cpp(
1135 @interface MYObject2
1136 @end
1137 @interface Interface
1138 @property(retain, nonnull) [[MYObject2]] *x;
1139 @end
1140 )cpp";
1141 EXPECT_DECLS("ObjCInterfaceTypeLoc", "@interface MYObject2");
1142
1143 Code = R"cpp(
1144 @protocol Foo
1145 @end
1146 id test() {
1147 return [[@protocol(Foo)]];
1148 }
1149 )cpp";
1150 EXPECT_DECLS("ObjCProtocolExpr", "@protocol Foo");
1151
1152 Code = R"cpp(
1153 @interface Foo
1154 @end
1155 void test([[Foo]] *p);
1156 )cpp";
1157 EXPECT_DECLS("ObjCInterfaceTypeLoc", "@interface Foo");
1158
1159 Code = R"cpp(// Don't consider implicit interface as the target.
1160 @implementation [[Implicit]]
1161 @end
1162 )cpp";
1163 EXPECT_DECLS("ObjCImplementationDecl", "@implementation Implicit");
1164
1165 Code = R"cpp(
1166 @interface Foo
1167 @end
1168 @implementation [[Foo]]
1169 @end
1170 )cpp";
1171 EXPECT_DECLS("ObjCImplementationDecl", "@interface Foo");
1172
1173 Code = R"cpp(
1174 @interface Foo
1175 @end
1176 @interface Foo (Ext)
1177 @end
1178 @implementation [[Foo]] (Ext)
1179 @end
1180 )cpp";
1181 EXPECT_DECLS("ObjCCategoryImplDecl", "@interface Foo(Ext)");
1182
1183 Code = R"cpp(
1184 @interface Foo
1185 @end
1186 @interface Foo (Ext)
1187 @end
1188 @implementation Foo ([[Ext]])
1189 @end
1190 )cpp";
1191 EXPECT_DECLS("ObjCCategoryImplDecl", "@interface Foo(Ext)");
1192
1193 Code = R"cpp(
1194 void test(id</*error-ok*/[[InvalidProtocol]]> p);
1195 )cpp";
1196 EXPECT_DECLS("ParmVarDecl", "id p");
1197
1198 Code = R"cpp(
1199 @class C;
1200 @protocol Foo
1201 @end
1202 void test([[C]]<Foo> *p);
1203 )cpp";
1204 EXPECT_DECLS("ObjCInterfaceTypeLoc", "@class C;");
1205
1206 Code = R"cpp(
1207 @class C;
1208 @protocol Foo
1209 @end
1210 void test(C<[[Foo]]> *p);
1211 )cpp";
1212 EXPECT_DECLS("ObjCProtocolLoc", "@protocol Foo");
1213
1214 Code = R"cpp(
1215 @class C;
1216 @protocol Foo
1217 @end
1218 @protocol Bar
1219 @end
1220 void test(C<[[Foo]], Bar> *p);
1221 )cpp";
1222 EXPECT_DECLS("ObjCProtocolLoc", "@protocol Foo");
1223
1224 Code = R"cpp(
1225 @class C;
1226 @protocol Foo
1227 @end
1228 @protocol Bar
1229 @end
1230 void test(C<Foo, [[Bar]]> *p);
1231 )cpp";
1232 EXPECT_DECLS("ObjCProtocolLoc", "@protocol Bar");
1233
1234 Code = R"cpp(
1235 @interface Foo
1236 + (id)sharedInstance;
1237 @end
1238 @implementation Foo
1239 + (id)sharedInstance { return 0; }
1240 @end
1241 void test() {
1242 id value = [[Foo]].sharedInstance;
1243 }
1244 )cpp";
1245 EXPECT_DECLS("ObjCInterfaceTypeLoc", "@interface Foo");
1246
1247 Code = R"cpp(
1248 @interface Foo
1249 + (id)sharedInstance;
1250 @end
1251 @implementation Foo
1252 + (id)sharedInstance { return 0; }
1253 @end
1254 void test() {
1255 id value = Foo.[[sharedInstance]];
1256 }
1257 )cpp";
1258 EXPECT_DECLS("ObjCPropertyRefExpr", "+ (id)sharedInstance");
1259
1260 Code = R"cpp(
1261 @interface Foo
1262 + ([[id]])sharedInstance;
1263 @end
1264 )cpp";
1265 EXPECT_DECLS("TypedefTypeLoc", );
1266
1267 Code = R"cpp(
1268 @interface Foo
1269 + ([[instancetype]])sharedInstance;
1270 @end
1271 )cpp";
1272 EXPECT_DECLS("TypedefTypeLoc", );
1273}
1274
1275class FindExplicitReferencesTest : public ::testing::Test {
1276protected:
1277 struct AllRefs {
1278 std::string AnnotatedCode;
1279 std::string DumpedReferences;
1280 };
1281
1282 TestTU newTU(llvm::StringRef Code) {
1283 TestTU TU;
1284 TU.Code = std::string(Code);
1285
1286 // FIXME: Auto-completion in a template requires disabling delayed template
1287 // parsing.
1288 TU.ExtraArgs.push_back("-std=c++20");
1289 TU.ExtraArgs.push_back("-xobjective-c++");
1290
1291 return TU;
1292 }
1293
1294 AllRefs annotatedReferences(llvm::StringRef Code, ParsedAST &AST,
1295 std::vector<ReferenceLoc> Refs) {
1296 auto &SM = AST.getSourceManager();
1297 llvm::stable_sort(Refs, [&](const ReferenceLoc &L, const ReferenceLoc &R) {
1298 return SM.isBeforeInTranslationUnit(L.NameLoc, R.NameLoc);
1299 });
1300
1301 std::string AnnotatedCode;
1302 unsigned NextCodeChar = 0;
1303 for (unsigned I = 0; I < Refs.size(); ++I) {
1304 auto &R = Refs[I];
1305
1306 SourceLocation Pos = R.NameLoc;
1307 assert(Pos.isValid());
1308 if (Pos.isMacroID()) // FIXME: figure out how to show macro locations.
1309 Pos = SM.getExpansionLoc(Pos);
1310 assert(Pos.isFileID());
1311
1312 FileID File;
1313 unsigned Offset;
1314 std::tie(File, Offset) = SM.getDecomposedLoc(Pos);
1315 if (File == SM.getMainFileID()) {
1316 // Print the reference in a source code.
1317 assert(NextCodeChar <= Offset);
1318 AnnotatedCode += Code.substr(NextCodeChar, Offset - NextCodeChar);
1319 AnnotatedCode += "$" + std::to_string(I) + "^";
1320
1321 NextCodeChar = Offset;
1322 }
1323 }
1324 AnnotatedCode += Code.substr(NextCodeChar);
1325
1326 std::string DumpedReferences;
1327 for (unsigned I = 0; I < Refs.size(); ++I)
1328 DumpedReferences += std::string(llvm::formatv("{0}: {1}\n", I, Refs[I]));
1329
1330 return AllRefs{std::move(AnnotatedCode), std::move(DumpedReferences)};
1331 }
1332
1333 /// Parses \p Code, and annotates its body with results of
1334 /// findExplicitReferences on all top level decls.
1335 /// See actual tests for examples of annotation format.
1336 AllRefs annotateAllReferences(llvm::StringRef Code) {
1337 TestTU TU = newTU(Code);
1338 auto AST = TU.build();
1339
1340 std::vector<ReferenceLoc> Refs;
1341 for (auto *TopLevel : AST.getLocalTopLevelDecls())
1343 TopLevel, [&Refs](ReferenceLoc R) { Refs.push_back(std::move(R)); },
1344 AST.getHeuristicResolver());
1345 return annotatedReferences(Code, AST, std::move(Refs));
1346 }
1347
1348 /// Parses \p Code, finds function or namespace '::foo' and annotates its body
1349 /// with results of findExplicitReferences.
1350 /// See actual tests for examples of annotation format.
1351 AllRefs annotateReferencesInFoo(llvm::StringRef Code) {
1352 TestTU TU = newTU(Code);
1353 auto AST = TU.build();
1354 auto *TestDecl = &findDecl(AST, "foo");
1355 if (auto *T = llvm::dyn_cast<FunctionTemplateDecl>(TestDecl))
1356 TestDecl = T->getTemplatedDecl();
1357
1358 std::vector<ReferenceLoc> Refs;
1359 if (const auto *Func = llvm::dyn_cast<FunctionDecl>(TestDecl))
1361 Func->getBody(),
1362 [&Refs](ReferenceLoc R) { Refs.push_back(std::move(R)); },
1363 AST.getHeuristicResolver());
1364 else if (const auto *NS = llvm::dyn_cast<NamespaceDecl>(TestDecl))
1366 NS,
1367 [&Refs, &NS](ReferenceLoc R) {
1368 // Avoid adding the namespace foo decl to the results.
1369 if (R.Targets.size() == 1 && R.Targets.front() == NS)
1370 return;
1371 Refs.push_back(std::move(R));
1372 },
1373 AST.getHeuristicResolver());
1374 else if (const auto *OC = llvm::dyn_cast<ObjCContainerDecl>(TestDecl))
1376 OC, [&Refs](ReferenceLoc R) { Refs.push_back(std::move(R)); },
1377 AST.getHeuristicResolver());
1378 else
1379 ADD_FAILURE() << "Failed to find ::foo decl for test";
1380
1381 return annotatedReferences(Code, AST, std::move(Refs));
1382 }
1383};
1384
1385TEST_F(FindExplicitReferencesTest, AllRefsInFoo) {
1386 std::pair</*Code*/ llvm::StringRef, /*References*/ llvm::StringRef> Cases[] =
1387 {// Simple expressions.
1388 {R"cpp(
1389 int global;
1390 int func();
1391 void foo(int param) {
1392 $0^global = $1^param + $2^func();
1393 }
1394 )cpp",
1395 "0: targets = {global}\n"
1396 "1: targets = {param}\n"
1397 "2: targets = {func}\n"},
1398 {R"cpp(
1399 struct X { int a; };
1400 void foo(X x) {
1401 $0^x.$1^a = 10;
1402 }
1403 )cpp",
1404 "0: targets = {x}\n"
1405 "1: targets = {X::a}\n"},
1406 {R"cpp(
1407 // error-ok: testing with broken code
1408 int bar();
1409 int foo() {
1410 return $0^bar() + $1^bar(42);
1411 }
1412 )cpp",
1413 "0: targets = {bar}\n"
1414 "1: targets = {bar}\n"},
1415 // Namespaces and aliases.
1416 {R"cpp(
1417 namespace ns {}
1418 namespace alias = ns;
1419 void foo() {
1420 using namespace $0^ns;
1421 using namespace $1^alias;
1422 }
1423 )cpp",
1424 "0: targets = {ns}\n"
1425 "1: targets = {alias}\n"},
1426 // Using declarations.
1427 {R"cpp(
1428 namespace ns { int global; }
1429 void foo() {
1430 using $0^ns::$1^global;
1431 }
1432 )cpp",
1433 "0: targets = {ns}\n"
1434 "1: targets = {ns::global}, qualifier = 'ns::'\n"},
1435 // Using enum declarations.
1436 {R"cpp(
1437 namespace ns { enum class A {}; }
1438 void foo() {
1439 using enum $0^ns::$1^A;
1440 }
1441 )cpp",
1442 "0: targets = {ns}\n"
1443 "1: targets = {ns::A}, qualifier = 'ns::'\n"},
1444 // Simple types.
1445 {R"cpp(
1446 struct Struct { int a; };
1447 using Typedef = int;
1448 void foo() {
1449 $0^Struct $1^x;
1450 $2^Typedef $3^y;
1451 static_cast<$4^Struct*>(0);
1452 }
1453 )cpp",
1454 "0: targets = {Struct}\n"
1455 "1: targets = {x}, decl\n"
1456 "2: targets = {Typedef}\n"
1457 "3: targets = {y}, decl\n"
1458 "4: targets = {Struct}\n"},
1459 // Name qualifiers.
1460 {R"cpp(
1461 namespace a { namespace b { struct S { typedef int type; }; } }
1462 void foo() {
1463 $0^a::$1^b::$2^S $3^x;
1464 using namespace $4^a::$5^b;
1465 $6^S::$7^type $8^y;
1466 }
1467 )cpp",
1468 "0: targets = {a}\n"
1469 "1: targets = {a::b}, qualifier = 'a::'\n"
1470 "2: targets = {a::b::S}, qualifier = 'a::b::'\n"
1471 "3: targets = {x}, decl\n"
1472 "4: targets = {a}\n"
1473 "5: targets = {a::b}, qualifier = 'a::'\n"
1474 "6: targets = {a::b::S}\n"
1475 "7: targets = {a::b::S::type}, qualifier = 'struct S::'\n"
1476 "8: targets = {y}, decl\n"},
1477 {R"cpp(
1478 void foo() {
1479 $0^ten: // PRINT "HELLO WORLD!"
1480 goto $1^ten;
1481 }
1482 )cpp",
1483 "0: targets = {ten}, decl\n"
1484 "1: targets = {ten}\n"},
1485 // Simple templates.
1486 {R"cpp(
1487 template <class T> struct vector { using value_type = T; };
1488 template <> struct vector<bool> { using value_type = bool; };
1489 void foo() {
1490 $0^vector<int> $1^vi;
1491 $2^vector<bool> $3^vb;
1492 }
1493 )cpp",
1494 "0: targets = {vector<int>}\n"
1495 "1: targets = {vi}, decl\n"
1496 "2: targets = {vector<bool>}\n"
1497 "3: targets = {vb}, decl\n"},
1498 // Template type aliases.
1499 {R"cpp(
1500 template <class T> struct vector { using value_type = T; };
1501 template <> struct vector<bool> { using value_type = bool; };
1502 template <class T> using valias = vector<T>;
1503 void foo() {
1504 $0^valias<int> $1^vi;
1505 $2^valias<bool> $3^vb;
1506 }
1507 )cpp",
1508 "0: targets = {valias}\n"
1509 "1: targets = {vi}, decl\n"
1510 "2: targets = {valias}\n"
1511 "3: targets = {vb}, decl\n"},
1512 // Injected class name.
1513 {R"cpp(
1514 namespace foo {
1515 template <typename $0^T>
1516 class $1^Bar {
1517 ~$2^Bar();
1518 void $3^f($4^Bar);
1519 };
1520 }
1521 )cpp",
1522 "0: targets = {foo::Bar::T}, decl\n"
1523 "1: targets = {foo::Bar}, decl\n"
1524 "2: targets = {foo::Bar}\n"
1525 "3: targets = {foo::Bar::f}, decl\n"
1526 "4: targets = {foo::Bar}\n"},
1527 // MemberExpr should know their using declaration.
1528 {R"cpp(
1529 struct X { void func(int); };
1530 struct Y : X {
1531 using X::func;
1532 };
1533 void foo(Y y) {
1534 $0^y.$1^func(1);
1535 }
1536 )cpp",
1537 "0: targets = {y}\n"
1538 "1: targets = {Y::func}\n"},
1539 // DeclRefExpr should know their using declaration.
1540 {R"cpp(
1541 namespace ns { void bar(int); }
1542 using ns::bar;
1543
1544 void foo() {
1545 $0^bar(10);
1546 }
1547 )cpp",
1548 "0: targets = {bar}\n"},
1549 // References from a macro.
1550 {R"cpp(
1551 #define FOO a
1552 #define BAR b
1553
1554 void foo(int a, int b) {
1555 $0^FOO+$1^BAR;
1556 }
1557 )cpp",
1558 "0: targets = {a}\n"
1559 "1: targets = {b}\n"},
1560 // No references from implicit nodes.
1561 {R"cpp(
1562 struct vector {
1563 int *begin();
1564 int *end();
1565 };
1566
1567 void foo() {
1568 for (int $0^x : $1^vector()) {
1569 $2^x = 10;
1570 }
1571 }
1572 )cpp",
1573 "0: targets = {x}, decl\n"
1574 "1: targets = {vector}\n"
1575 "2: targets = {x}\n"},
1576 // Handle UnresolvedLookupExpr.
1577 {R"cpp(
1578 namespace ns1 { void func(char*); }
1579 namespace ns2 { void func(int*); }
1580 using namespace ns1;
1581 using namespace ns2;
1582
1583 template <class T>
1584 void foo(T t) {
1585 $0^func($1^t);
1586 }
1587 )cpp",
1588 "0: targets = {ns1::func, ns2::func}\n"
1589 "1: targets = {t}\n"},
1590 // Handle UnresolvedMemberExpr.
1591 {R"cpp(
1592 struct X {
1593 void func(char*);
1594 void func(int*);
1595 };
1596
1597 template <class T>
1598 void foo(X x, T t) {
1599 $0^x.$1^func($2^t);
1600 }
1601 )cpp",
1602 "0: targets = {x}\n"
1603 "1: targets = {X::func, X::func}\n"
1604 "2: targets = {t}\n"},
1605 // Handle DependentScopeDeclRefExpr.
1606 {R"cpp(
1607 template <class T>
1608 struct S {
1609 static int value;
1610 };
1611
1612 template <class T>
1613 void foo() {
1614 $0^S<$1^T>::$2^value;
1615 }
1616 )cpp",
1617 "0: targets = {S}\n"
1618 "1: targets = {T}\n"
1619 "2: targets = {S::value}, qualifier = 'S<T>::'\n"},
1620 // Handle CXXDependentScopeMemberExpr.
1621 {R"cpp(
1622 template <class T>
1623 struct S {
1624 int value;
1625 };
1626
1627 template <class T>
1628 void foo(S<T> t) {
1629 $0^t.$1^value;
1630 }
1631 )cpp",
1632 "0: targets = {t}\n"
1633 "1: targets = {S::value}\n"},
1634 // Type template parameters.
1635 {R"cpp(
1636 template <class T>
1637 void foo() {
1638 static_cast<$0^T>(0);
1639 $1^T();
1640 $2^T $3^t;
1641 }
1642 )cpp",
1643 "0: targets = {T}\n"
1644 "1: targets = {T}\n"
1645 "2: targets = {T}\n"
1646 "3: targets = {t}, decl\n"},
1647 // Non-type template parameters.
1648 {R"cpp(
1649 template <int I>
1650 void foo() {
1651 int $0^x = $1^I;
1652 }
1653 )cpp",
1654 "0: targets = {x}, decl\n"
1655 "1: targets = {I}\n"},
1656 // Template template parameters.
1657 {R"cpp(
1658 template <class T> struct vector {};
1659
1660 template <template<class> class TT, template<class> class ...TP>
1661 void foo() {
1662 $0^TT<int> $1^x;
1663 $2^foo<$3^TT>();
1664 $4^foo<$5^vector>();
1665 $6^foo<$7^TP...>();
1666 }
1667 )cpp",
1668 "0: targets = {TT}\n"
1669 "1: targets = {x}, decl\n"
1670 "2: targets = {foo}\n"
1671 "3: targets = {TT}\n"
1672 "4: targets = {foo}\n"
1673 "5: targets = {vector}\n"
1674 "6: targets = {foo}\n"
1675 "7: targets = {TP}\n"},
1676 // Non-type template parameters with declarations.
1677 {R"cpp(
1678 int func();
1679 template <int(*)()> struct wrapper {};
1680
1681 template <int(*FuncParam)()>
1682 void foo() {
1683 $0^wrapper<$1^func> $2^w;
1684 $3^FuncParam();
1685 }
1686 )cpp",
1687 "0: targets = {wrapper<&func>}\n"
1688 "1: targets = {func}\n"
1689 "2: targets = {w}, decl\n"
1690 "3: targets = {FuncParam}\n"},
1691 // declaration references.
1692 {R"cpp(
1693 namespace ns {}
1694 class S {};
1695 void foo() {
1696 class $0^Foo { $1^Foo(); ~$2^Foo(); int $3^field; };
1697 int $4^Var;
1698 enum $5^E { $6^ABC };
1699 typedef int $7^INT;
1700 using $8^INT2 = int;
1701 namespace $9^NS = $10^ns;
1702 }
1703 )cpp",
1704 "0: targets = {Foo}, decl\n"
1705 "1: targets = {foo()::Foo::Foo}, decl\n"
1706 "2: targets = {Foo}\n"
1707 "3: targets = {foo()::Foo::field}, decl\n"
1708 "4: targets = {Var}, decl\n"
1709 "5: targets = {E}, decl\n"
1710 "6: targets = {foo()::ABC}, decl\n"
1711 "7: targets = {INT}, decl\n"
1712 "8: targets = {INT2}, decl\n"
1713 "9: targets = {NS}, decl\n"
1714 "10: targets = {ns}\n"},
1715 // User-defined conversion operator.
1716 {R"cpp(
1717 void foo() {
1718 class $0^Bar {};
1719 class $1^Foo {
1720 public:
1721 // FIXME: This should have only one reference to Bar.
1722 $2^operator $3^$4^Bar();
1723 };
1724
1725 $5^Foo $6^f;
1726 $7^f.$8^operator $9^Bar();
1727 }
1728 )cpp",
1729 "0: targets = {Bar}, decl\n"
1730 "1: targets = {Foo}, decl\n"
1731 "2: targets = {foo()::Foo::operator Bar}, decl\n"
1732 "3: targets = {Bar}\n"
1733 "4: targets = {Bar}\n"
1734 "5: targets = {Foo}\n"
1735 "6: targets = {f}, decl\n"
1736 "7: targets = {f}\n"
1737 "8: targets = {foo()::Foo::operator Bar}\n"
1738 "9: targets = {Bar}\n"},
1739 // Destructor.
1740 {R"cpp(
1741 void foo() {
1742 class $0^Foo {
1743 public:
1744 ~$1^Foo() {}
1745
1746 void $2^destructMe() {
1747 this->~$3^Foo();
1748 }
1749 };
1750
1751 $4^Foo $5^f;
1752 $6^f.~ /*...*/ $7^Foo();
1753 }
1754 )cpp",
1755 "0: targets = {Foo}, decl\n"
1756 // FIXME: It's better to target destructor's FunctionDecl instead of
1757 // the type itself (similar to constructor).
1758 "1: targets = {Foo}\n"
1759 "2: targets = {foo()::Foo::destructMe}, decl\n"
1760 "3: targets = {Foo}\n"
1761 "4: targets = {Foo}\n"
1762 "5: targets = {f}, decl\n"
1763 "6: targets = {f}\n"
1764 "7: targets = {Foo}\n"},
1765 // cxx constructor initializer.
1766 {R"cpp(
1767 class Base {};
1768 void foo() {
1769 // member initializer
1770 class $0^X {
1771 int $1^abc;
1772 $2^X(): $3^abc() {}
1773 };
1774 // base initializer
1775 class $4^Derived : public $5^Base {
1776 $6^Base $7^B;
1777 $8^Derived() : $9^Base() {}
1778 };
1779 // delegating initializer
1780 class $10^Foo {
1781 $11^Foo(int);
1782 $12^Foo(): $13^Foo(111) {}
1783 };
1784 }
1785 )cpp",
1786 "0: targets = {X}, decl\n"
1787 "1: targets = {foo()::X::abc}, decl\n"
1788 "2: targets = {foo()::X::X}, decl\n"
1789 "3: targets = {foo()::X::abc}\n"
1790 "4: targets = {Derived}, decl\n"
1791 "5: targets = {Base}\n"
1792 "6: targets = {Base}\n"
1793 "7: targets = {foo()::Derived::B}, decl\n"
1794 "8: targets = {foo()::Derived::Derived}, decl\n"
1795 "9: targets = {Base}\n"
1796 "10: targets = {Foo}, decl\n"
1797 "11: targets = {foo()::Foo::Foo}, decl\n"
1798 "12: targets = {foo()::Foo::Foo}, decl\n"
1799 "13: targets = {Foo}\n"},
1800 // Anonymous entities should not be reported.
1801 {
1802 R"cpp(
1803 void foo() {
1804 $0^class {} $1^x;
1805 int (*$2^fptr)(int $3^a, int) = nullptr;
1806 }
1807 )cpp",
1808 "0: targets = {(unnamed)}\n"
1809 "1: targets = {x}, decl\n"
1810 "2: targets = {fptr}, decl\n"
1811 "3: targets = {a}, decl\n"},
1812 // Namespace aliases should be handled properly.
1813 {
1814 R"cpp(
1815 namespace ns { struct Type {}; }
1816 namespace alias = ns;
1817 namespace rec_alias = alias;
1818
1819 void foo() {
1820 $0^ns::$1^Type $2^a;
1821 $3^alias::$4^Type $5^b;
1822 $6^rec_alias::$7^Type $8^c;
1823 }
1824 )cpp",
1825 "0: targets = {ns}\n"
1826 "1: targets = {ns::Type}, qualifier = 'ns::'\n"
1827 "2: targets = {a}, decl\n"
1828 "3: targets = {alias}\n"
1829 "4: targets = {ns::Type}, qualifier = 'alias::'\n"
1830 "5: targets = {b}, decl\n"
1831 "6: targets = {rec_alias}\n"
1832 "7: targets = {ns::Type}, qualifier = 'rec_alias::'\n"
1833 "8: targets = {c}, decl\n"},
1834 // Handle SizeOfPackExpr.
1835 {
1836 R"cpp(
1837 template <typename... E>
1838 void foo() {
1839 constexpr int $0^size = sizeof...($1^E);
1840 };
1841 )cpp",
1842 "0: targets = {size}, decl\n"
1843 "1: targets = {E}\n"},
1844 // Class template argument deduction
1845 {
1846 R"cpp(
1847 template <typename T>
1848 struct Test {
1849 Test(T);
1850 };
1851 void foo() {
1852 $0^Test $1^a(5);
1853 }
1854 )cpp",
1855 "0: targets = {Test}\n"
1856 "1: targets = {a}, decl\n"},
1857 // Templates
1858 {R"cpp(
1859 namespace foo {
1860 template <typename $0^T>
1861 class $1^Bar {};
1862 }
1863 )cpp",
1864 "0: targets = {foo::Bar::T}, decl\n"
1865 "1: targets = {foo::Bar}, decl\n"},
1866 // Templates
1867 {R"cpp(
1868 namespace foo {
1869 template <typename $0^T>
1870 void $1^func();
1871 }
1872 )cpp",
1873 "0: targets = {T}, decl\n"
1874 "1: targets = {foo::func}, decl\n"},
1875 // Templates
1876 {R"cpp(
1877 namespace foo {
1878 template <typename $0^T>
1879 $1^T $2^x;
1880 }
1881 )cpp",
1882 "0: targets = {foo::T}, decl\n"
1883 "1: targets = {foo::T}\n"
1884 "2: targets = {foo::x}, decl\n"},
1885 // Templates
1886 {R"cpp(
1887 template<typename T> class vector {};
1888 namespace foo {
1889 template <typename $0^T>
1890 using $1^V = $2^vector<$3^T>;
1891 }
1892 )cpp",
1893 "0: targets = {foo::T}, decl\n"
1894 "1: targets = {foo::V}, decl\n"
1895 "2: targets = {vector}\n"
1896 "3: targets = {foo::T}\n"},
1897 // Concept
1898 {
1899 R"cpp(
1900 template <typename T>
1901 concept Drawable = requires (T t) { t.draw(); };
1902
1903 namespace foo {
1904 template <typename $0^T> requires $1^Drawable<$2^T>
1905 void $3^bar($4^T $5^t) {
1906 $6^t.$7^draw();
1907 }
1908 }
1909 )cpp",
1910 "0: targets = {T}, decl\n"
1911 "1: targets = {Drawable}\n"
1912 "2: targets = {T}\n"
1913 "3: targets = {foo::bar}, decl\n"
1914 "4: targets = {T}\n"
1915 "5: targets = {t}, decl\n"
1916 "6: targets = {t}\n"
1917 "7: targets = {}\n"},
1918 // Objective-C: instance variables
1919 {
1920 R"cpp(
1921 @interface I {
1922 @public
1923 I *_z;
1924 }
1925 @end
1926 I *f;
1927 void foo() {
1928 $0^f->$1^_z = 0;
1929 }
1930 )cpp",
1931 "0: targets = {f}\n"
1932 "1: targets = {I::_z}\n"},
1933 // Objective-C: properties
1934 {
1935 R"cpp(
1936 @interface I {}
1937 @property(retain) I* x;
1938 @property(retain) I* y;
1939 @end
1940 I *f;
1941 void foo() {
1942 $0^f.$1^x.$2^y = 0;
1943 }
1944 )cpp",
1945 "0: targets = {f}\n"
1946 "1: targets = {I::x}\n"
1947 "2: targets = {I::y}\n"},
1948 // Objective-C: implicit properties
1949 {
1950 R"cpp(
1951 @interface I {}
1952 -(I*)x;
1953 -(void)setY:(I*)y;
1954 @end
1955 I *f;
1956 void foo() {
1957 $0^f.$1^x.$2^y = 0;
1958 }
1959 )cpp",
1960 "0: targets = {f}\n"
1961 "1: targets = {I::x}\n"
1962 "2: targets = {I::setY:}\n"},
1963 // Objective-C: class properties
1964 {
1965 R"cpp(
1966 @interface I {}
1967 @property(class) I *x;
1968 @end
1969 id local;
1970 void foo() {
1971 $0^I.$1^x = 0;
1972 $2^local = $3^I.$4^x;
1973 }
1974 )cpp",
1975 "0: targets = {I}\n"
1976 "1: targets = {I::setX:}\n"
1977 "2: targets = {local}\n"
1978 "3: targets = {I}\n"
1979 "4: targets = {I::x}\n"},
1980 // Objective-C: implicit class properties
1981 {
1982 R"cpp(
1983 @interface I {}
1984 +(I*)x;
1985 +(void)setX:(I*)x;
1986 @end
1987 id local;
1988 void foo() {
1989 $0^I.$1^x = 0;
1990 $2^local = $3^I.$4^x;
1991 }
1992 )cpp",
1993 "0: targets = {I}\n"
1994 "1: targets = {I::setX:}\n"
1995 "2: targets = {local}\n"
1996 "3: targets = {I}\n"
1997 "4: targets = {I::x}\n"},
1998 {// Objective-C: methods
1999 R"cpp(
2000 @interface I
2001 -(void) a:(int)x b:(int)y;
2002 @end
2003 void foo(I *i) {
2004 [$0^i $1^a:1 b:2];
2005 }
2006 )cpp",
2007 "0: targets = {i}\n"
2008 "1: targets = {I::a:b:}\n"},
2009 {// Objective-C: protocols
2010 R"cpp(
2011 @interface I
2012 @end
2013 @protocol P
2014 @end
2015 void foo() {
2016 $0^I<$1^P> *$2^x;
2017 }
2018 )cpp",
2019 "0: targets = {I}\n"
2020 "1: targets = {P}\n"
2021 "2: targets = {x}, decl\n"},
2022
2023 // Designated initializers.
2024 {R"cpp(
2025 void foo() {
2026 struct $0^Foo {
2027 int $1^Bar;
2028 };
2029 $2^Foo $3^f { .$4^Bar = 42 };
2030 }
2031 )cpp",
2032 "0: targets = {Foo}, decl\n"
2033 "1: targets = {foo()::Foo::Bar}, decl\n"
2034 "2: targets = {Foo}\n"
2035 "3: targets = {f}, decl\n"
2036 "4: targets = {foo()::Foo::Bar}\n"},
2037 {R"cpp(
2038 void foo() {
2039 struct $0^Baz {
2040 int $1^Field;
2041 };
2042 struct $2^Bar {
2043 $3^Baz $4^Foo;
2044 };
2045 $5^Bar $6^bar { .$7^Foo.$8^Field = 42 };
2046 }
2047 )cpp",
2048 "0: targets = {Baz}, decl\n"
2049 "1: targets = {foo()::Baz::Field}, decl\n"
2050 "2: targets = {Bar}, decl\n"
2051 "3: targets = {Baz}\n"
2052 "4: targets = {foo()::Bar::Foo}, decl\n"
2053 "5: targets = {Bar}\n"
2054 "6: targets = {bar}, decl\n"
2055 "7: targets = {foo()::Bar::Foo}\n"
2056 "8: targets = {foo()::Baz::Field}\n"},
2057 {R"cpp(
2058 template<typename T>
2059 void crash(T);
2060 template<typename T>
2061 void foo() {
2062 $0^crash({.$1^x = $2^T()});
2063 }
2064 )cpp",
2065 "0: targets = {crash}\n"
2066 "1: targets = {}\n"
2067 "2: targets = {T}\n"},
2068 // unknown template name should not crash.
2069 {R"cpp(
2070 template <template <typename> typename T>
2071 struct Base {};
2072 namespace foo {
2073 template <typename $0^T>
2074 struct $1^Derive : $2^Base<$3^T::template $4^Unknown> {};
2075 }
2076 )cpp",
2077 "0: targets = {foo::Derive::T}, decl\n"
2078 "1: targets = {foo::Derive}, decl\n"
2079 "2: targets = {Base}\n"
2080 "3: targets = {foo::Derive::T}\n"
2081 "4: targets = {}, qualifier = 'T::'\n"},
2082 // deduction guide
2083 {R"cpp(
2084 namespace foo {
2085 template <typename $0^T>
2086 struct $1^Test {
2087 template <typename $2^I>
2088 $3^Test($4^I);
2089 };
2090 template <typename $5^I>
2091 $6^Test($7^I) -> $8^Test<typename $9^I::$10^type>;
2092 }
2093 )cpp",
2094 "0: targets = {T}, decl\n"
2095 "1: targets = {foo::Test}, decl\n"
2096 "2: targets = {I}, decl\n"
2097 "3: targets = {foo::Test::Test<T>}, decl\n"
2098 "4: targets = {I}\n"
2099 "5: targets = {I}, decl\n"
2100 "6: targets = {foo::Test}\n"
2101 "7: targets = {I}\n"
2102 "8: targets = {foo::Test}\n"
2103 "9: targets = {I}\n"
2104 "10: targets = {}, qualifier = 'I::'\n"}};
2105
2106 for (const auto &C : Cases) {
2107 llvm::StringRef ExpectedCode = C.first;
2108 llvm::StringRef ExpectedRefs = C.second;
2109
2110 auto Actual =
2111 annotateReferencesInFoo(llvm::Annotations(ExpectedCode).code());
2112 EXPECT_EQ(ExpectedCode, Actual.AnnotatedCode);
2113 EXPECT_EQ(ExpectedRefs, Actual.DumpedReferences) << ExpectedCode;
2114 }
2115}
2116
2117TEST_F(FindExplicitReferencesTest, AllRefs) {
2118 std::pair</*Code*/ llvm::StringRef, /*References*/ llvm::StringRef> Cases[] =
2119 {{R"cpp(
2120 @interface $0^MyClass
2121 @end
2122 @implementation $1^$2^MyClass
2123 @end
2124 )cpp",
2125 "0: targets = {MyClass}, decl\n"
2126 "1: targets = {MyClass}\n"
2127 "2: targets = {MyClass}, decl\n"},
2128 {R"cpp(
2129 @interface $0^MyClass
2130 @end
2131 @interface $1^MyClass ($2^Category)
2132 @end
2133 @implementation $3^MyClass ($4^$5^Category)
2134 @end
2135 )cpp",
2136 "0: targets = {MyClass}, decl\n"
2137 "1: targets = {MyClass}\n"
2138 "2: targets = {Category}, decl\n"
2139 "3: targets = {MyClass}\n"
2140 "4: targets = {Category}\n"
2141 "5: targets = {Category}, decl\n"}};
2142
2143 for (const auto &C : Cases) {
2144 llvm::StringRef ExpectedCode = C.first;
2145 llvm::StringRef ExpectedRefs = C.second;
2146
2147 auto Actual = annotateAllReferences(llvm::Annotations(ExpectedCode).code());
2148 EXPECT_EQ(ExpectedCode, Actual.AnnotatedCode);
2149 EXPECT_EQ(ExpectedRefs, Actual.DumpedReferences) << ExpectedCode;
2150 }
2151}
2152
2153} // namespace
2154} // namespace clangd
2155} // namespace clang
llvm::SmallString< 256U > Name
size_t Offset
#define EXPECT_DECLS(NodeType,...)
std::string Code
std::string AnnotatedCode
std::string DumpedReferences
const Criteria C
size_t Pos
llvm::raw_string_ostream OS
Definition: TraceTests.cpp:160
static SelectionTree createRight(ASTContext &AST, const syntax::TokenBuffer &Tokens, unsigned Begin, unsigned End)
Definition: Selection.cpp:1067
TEST_F(BackgroundIndexTest, NoCrashOnErrorFile)
const NamedDecl & findDecl(ParsedAST &AST, llvm::StringRef QName)
Definition: TestTU.cpp:219
llvm::SmallVector< std::pair< const NamedDecl *, DeclRelationSet >, 1 > allTargetDecls(const DynTypedNode &N, const HeuristicResolver *Resolver)
Similar to targetDecl(), however instead of applying a filter, all possible decls are returned along ...
Definition: FindTarget.cpp:552
void findExplicitReferences(const Stmt *S, llvm::function_ref< void(ReferenceLoc)> Out, const HeuristicResolver *Resolver)
Recursively traverse S and report all references explicitly written in the code.
bool operator==(const Inclusion &LHS, const Inclusion &RHS)
Definition: Headers.cpp:331
llvm::raw_ostream & operator<<(llvm::raw_ostream &OS, const CodeCompletion &C)
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
static TestTU withCode(llvm::StringRef Code)
Definition: TestTU.h:36