19#include "clang/AST/Decl.h"
20#include "clang/Basic/SourceLocation.h"
21#include "llvm/ADT/StringRef.h"
22#include "llvm/Support/Casting.h"
23#include "llvm/Support/Error.h"
24#include "llvm/Support/Path.h"
25#include "llvm/Support/ScopedPrinter.h"
26#include "gmock/gmock.h"
27#include "gtest/gtest.h"
36using ::testing::AllOf;
37using ::testing::ElementsAre;
39using ::testing::IsEmpty;
40using ::testing::Matcher;
41using ::testing::UnorderedElementsAre;
42using ::testing::UnorderedElementsAreArray;
43using ::testing::UnorderedPointwise;
45std::string guard(llvm::StringRef Code) {
46 return "#pragma once\n" + Code.str();
55 return Sym.PreferredDeclaration.range ==
Range;
60 return Sym.Definition.value_or(Sym.PreferredDeclaration).range ==
Range;
65Matcher<const std::vector<DocumentHighlight> &>
67 std::vector<DocumentHighlight> Expected;
69 Expected.emplace_back();
70 Expected.back().range = R;
71 Expected.back().kind = K;
73 for (
const auto &
Range : Test.ranges())
75 for (
const auto &
Range : Test.ranges(
"read"))
77 for (
const auto &
Range : Test.ranges(
"write"))
79 return UnorderedElementsAreArray(Expected);
83 const char *Tests[] = {
84 R
"cpp(// Local variable
87 $write[[^bonjour]] = 2;
88 int test1 = $read[[bonjour]];
95 static void foo([[MyClass]]*) {}
99 ns1::[[My^Class]]* Params;
104 int [[^foo]](int) { return 0; }
106 [[foo]]([[foo]](42));
111 R"cpp(// Function parameter in decl
112 void foo(int [[^bar]]);
114 R"cpp(// Not touching any identifiers.
123 R"cpp(// ObjC methods with split selectors.
125 +(void) [[x]]:(int)a [[y]]:(int)b;
128 +(void) [[x]]:(int)a [[y]]:(int)b {}
131 [Foo [[x]]:2 [[^y]]:4];
142 for (
const char *Test : Tests) {
145 TU.ExtraArgs.push_back(
"-xobjective-c++");
146 auto AST = TU.build();
152TEST(HighlightsTest, ControlFlow) {
153 const char *Tests[] = {
155 // Highlight same-function returns.
156 int fib(unsigned n) {
157 if (n <= 1) [[ret^urn]] 1;
158 [[return]] fib(n - 1) + fib(n - 2);
160 // Returns from other functions not highlighted.
161 auto Lambda = [] { return; };
162 class LocalClass { void x() { return; } };
167 #define FAIL() return false
170 if (n < 0) [[FAIL]]();
176 // Highlight loop control flow
179 [[^for]] (char c : "fruit loops!") {
180 if (c == ' ') [[continue]];
182 if (c == '!') [[break]];
183 if (c == '?') [[return]] -1;
190 // Highlight loop and same-loop control flow
193 if (false) [[bre^ak]];
201 // Highlight switch for break (but not other breaks).
202 void describe(unsigned n) {
213 // Highlight case and exits for switch-break (but not other cases).
214 void describe(unsigned n) {
227 // Highlight exits and switch for case
228 void describe(unsigned n) {
241 // Highlight nothing for switch.
242 void describe(unsigned n) {
255 // FIXME: match exception type against catch blocks
257 try { // wrong: highlight try with matching catch
258 try { // correct: has no matching catch
260 } catch (int) { } // correct: catch doesn't match type
261 [[return]] -1; // correct: exits the matching catch
262 } catch (const char*) { } // wrong: highlight matching catch
263 [[return]] 42; // wrong: throw doesn't exit function
268 // Loop highlights goto exiting the loop, but not jumping within it.
279 for (
const char *Test : Tests) {
282 TU.ExtraArgs.push_back(
"-fexceptions");
283 auto AST = TU.build();
289MATCHER_P3(
sym, Name, Decl, DefOrNone,
"") {
290 std::optional<Range> Def = DefOrNone;
291 if (Name != arg.Name) {
292 *result_listener <<
"Name is " << arg.Name;
295 if (Decl != arg.PreferredDeclaration.range) {
296 *result_listener <<
"Declaration is "
297 << llvm::to_string(arg.PreferredDeclaration);
300 if (!Def && !arg.Definition)
302 if (Def && !arg.Definition) {
303 *result_listener <<
"Has no definition";
306 if (!Def && arg.Definition) {
307 *result_listener <<
"Definition is " << llvm::to_string(*arg.Definition);
310 if (arg.Definition->range != *Def) {
311 *result_listener <<
"Definition is " << llvm::to_string(*arg.Definition);
319MATCHER_P(rangeIs, R,
"") {
return arg.Loc.range == R; }
320MATCHER_P(fileIs, F,
"") {
return arg.Loc.uri.file() == F; }
322 return arg.Loc.containerName.value_or(
"") ==
C;
324MATCHER_P(attrsAre, A,
"") {
return arg.Attributes ==
A; }
325MATCHER_P(hasID, ID,
"") {
return arg.ID == ID; }
327TEST(LocateSymbol, WithIndex) {
329 class $forward[[Forward]];
330 class $foo[[Foo]] {};
334 inline void $f2[[f2]]() {}
337 class $forward[[forward]] {};
342 TU.Code = std::string(SymbolCpp.code());
343 TU.HeaderCode = std::string(SymbolHeader.code());
344 auto Index = TU.index();
345 auto LocateWithIndex = [&Index](
const Annotations &Main) {
356 EXPECT_THAT(LocateWithIndex(Test),
357 ElementsAre(sym("f1", Test.range(), SymbolCpp.range(
"f1"))));
365 EXPECT_THAT(LocateWithIndex(Test),
366 ElementsAre(sym("f1", SymbolHeader.range(
"f1"), Test.range())));
368 Test =
Annotations(R
"cpp(// forward declaration in AST.
372 EXPECT_THAT(LocateWithIndex(Test),
373 ElementsAre(sym("Foo", Test.range(), SymbolHeader.range(
"foo"))));
376 class [[Forward]] {};
380 LocateWithIndex(Test),
381 ElementsAre(sym("Forward", SymbolHeader.range(
"forward"), Test.range())));
384TEST(LocateSymbol, AnonymousStructFields) {
387 struct { int $1[[x]]; };
389 // Make sure the implicit base is skipped.
393 // Check that we don't skip explicit bases.
397 auto AST = TU.build();
399 UnorderedElementsAre(
sym(
"x", Code.range(
"1"), Code.range(
"1"))));
402 UnorderedElementsAre(
sym(
"Foo", Code.range(
"2"), Code.range(
"2"))));
405TEST(LocateSymbol, FindOverrides) {
408 virtual void $1[[fo^o]]() = 0;
410 class Bar : public Foo {
411 void $2[[foo]]() override;
415 auto AST = TU.build();
417 UnorderedElementsAre(
sym(
"foo", Code.range(
"1"), std::nullopt),
418 sym(
"foo", Code.range(
"2"), std::nullopt)));
421TEST(LocateSymbol, FindOverridesFromDefObjC) {
429 @interface Foo : Base<Fooey>
437 - (void)$3[[fo^o]] {}
441 TU.ExtraArgs.push_back("-xobjective-c++");
442 auto AST = TU.build();
445 UnorderedElementsAre(
sym(
"foo", Code.range(
"1"), std::nullopt),
446 sym(
"foo", Code.range(
"2"), Code.range(
"3"))));
449TEST(LocateSymbol, NoOverridesFromDeclObjC) {
457 @interface Foo : Base<Fooey>
469 TU.ExtraArgs.push_back("-xobjective-c++");
470 auto AST = TU.build();
473 UnorderedElementsAre(
sym(
"foo", Code.range(
"2"), Code.range(
"3"))));
476TEST(LocateSymbol, ObjCNoOverridesOnUsage) {
488 void doSomething(Bar *bar) {
493 TU.ExtraArgs.push_back("-xobjective-c++");
494 auto AST = TU.build();
497 UnorderedElementsAre(
sym(
"foo", Code.range(
"1"), Code.range(
"2"))));
500TEST(LocateSymbol, WithIndexPreferredLocation) {
502 class $p[[Proto]] {};
503 void $f[[func]]() {};
506 TU.HeaderCode = std::string(SymbolHeader.code());
507 TU.HeaderFilename = "x.proto";
508 auto Index = TU.index();
511 // Shift to make range different.
523 auto CodeGenLoc = SymbolHeader.range(
"p");
524 EXPECT_THAT(Locs, ElementsAre(
sym(
"Proto", CodeGenLoc, CodeGenLoc)));
528 auto CodeGenLoc = SymbolHeader.range(
"f");
529 EXPECT_THAT(Locs, ElementsAre(
sym(
"func", CodeGenLoc, CodeGenLoc)));
538 const char *Tests[] = {
551 R"cpp(// Local variable
561 struct [[MyClass]] {};
564 ns1::My^Class* Params;
568 R"cpp(// Function definition via pointer
575 R"cpp(// Function declaration via call
576 int $decl[[foo]](int);
583 struct Foo { int [[x]]; };
590 R"cpp(// Field, member initializer
597 R"cpp(// Field, field designator
598 struct Foo { int [[x]]; };
600 Foo bar = { .^x = 2 };
605 struct Foo { int $decl[[x]](); };
613 typedef int $decl[[Foo]];
619 R"cpp(// Template type parameter
620 template <typename [[T]]>
624 R"cpp(// Template template type parameter
625 template <template<typename> class [[T]]>
626 void foo() { ^T<int> t; }
630 namespace $decl[[ns]] {
631 struct Foo { static void bar(); };
633 int main() { ^ns::Foo::bar(); }
637 class TTT { public: int a; };
638 #define [[FF]](S) if (int b = S.a) {}
645 R"cpp(// Macro argument
647 #define ADDRESSOF(X) &X;
648 int *j = ADDRESSOF(^i);
650 R"cpp(// Macro argument appearing multiple times in expansion
651 #define VALIDATE_TYPE(x) (void)x;
652 #define ASSERT(expr) \
654 VALIDATE_TYPE(expr); \
657 bool [[waldo]]() { return true; }
662 R"cpp(// Symbol concatenated inside macro (not supported)
664 #define POINTER(X) p ## X;
665 int x = *POINTER(^i);
668 R"cpp(// Forward class declaration
670 class $def[[Foo]] {};
674 R"cpp(// Function declaration
677 void $def[[foo]]() {}
681 #define FF(name) class name##_Test {};
683 void f() { my^_Test a; }
687 #define FF() class [[Test]] {};
689 void f() { T^est a; }
692 R"cpp(// explicit template specialization
693 template <typename T>
694 struct Foo { void bar() {} };
697 struct [[Foo]]<int> { void bar() {} };
705 R"cpp(// implicit template specialization
706 template <typename T>
707 struct [[Foo]] { void bar() {} };
709 struct Foo<int> { void bar() {} };
716 R"cpp(// partial template specialization
717 template <typename T>
718 struct Foo { void bar() {} };
719 template <typename T>
720 struct [[Foo]]<T*> { void bar() {} };
724 R"cpp(// function template specializations
734 R"cpp(// variable template decls
739 double [[var]]<int> = 10;
741 double y = va^r<int>;
744 R"cpp(// No implicit constructors
756 X& $decl[[operator]]++();
764 struct S1 { void f(); };
765 struct S2 { S1 * $decl[[operator]]->(); };
771 R"cpp(// Declaration of explicit template specialization
772 template <typename T>
773 struct $decl[[$def[[Foo]]]] {};
779 R"cpp(// Declaration of partial template specialization
780 template <typename T>
781 struct $decl[[$def[[Foo]]]] {};
783 template <typename T>
787 R"cpp(// Definition on ClassTemplateDecl
789 // Forward declaration.
793 template <typename T>
794 struct $def[[Foo]] {};
800 R"cpp(// auto builtin type (not supported)
804 R"cpp(// auto on lambda
809 R"cpp(// auto on struct
817 R"cpp(// decltype on struct
826 R"cpp(// decltype(auto) on struct
833 ^decltype(auto) k = j;
836 R"cpp(// auto on template class
837 template<typename T> class [[Foo]] {};
839 ^auto x = Foo<int>();
842 R"cpp(// auto on template class with forward declared class
843 template<typename T> class [[Foo]] {};
849 R"cpp(// auto on specialized template class
850 template<typename T> class Foo {};
851 template<> class [[Foo]]<int> {};
853 ^auto x = Foo<int>();
856 R"cpp(// auto on initializer list.
860 class [[initializer_list]] { const _E *a, *b; };
866 R"cpp(// auto function return with trailing type
868 ^auto test() -> decltype(Bar()) {
873 R"cpp(// decltype in trailing return type
875 auto test() -> ^decltype(Bar()) {
880 R"cpp(// auto in function return
887 R"cpp(// auto& in function return
895 R"cpp(// auto* in function return
903 R"cpp(// const auto& in function return
905 const ^auto& test() {
911 R"cpp(// auto lambda param where there's a single instantiation
913 auto Lambda = [](^auto){ return 0; };
914 int x = Lambda(Bar{});
917 R"cpp(// decltype(auto) in function return
919 ^decltype(auto) test() {
924 R"cpp(// decltype of function with trailing return type.
926 auto test() -> decltype(Bar()) {
930 ^decltype(test()) i = test();
934 R"cpp(// auto with dependent type
937 template <typename T>
943 R"cpp(// Override specifier jumps to overridden method
944 class Y { virtual void $decl[[a]]() = 0; };
945 class X : Y { void a() ^override {} };
947 R"cpp(// Final specifier jumps to overridden method
948 class Y { virtual void $decl[[a]]() = 0; };
949 class X : Y { void a() ^final {} };
952 R"cpp(// Heuristic resolution of dependent method
953 template <typename T>
958 template <typename T>
964 R"cpp(// Heuristic resolution of dependent method via this->
965 template <typename T>
973 R"cpp(// Heuristic resolution of dependent static method
974 template <typename T>
976 static void [[bar]]() {}
979 template <typename T>
985 R"cpp(// Heuristic resolution of dependent method
986 // invoked via smart pointer
987 template <typename> struct S { void [[foo]]() {} };
988 template <typename T> struct unique_ptr {
991 template <typename T>
992 void test(unique_ptr<S<T>>& V) {
997 R"cpp(// Heuristic resolution of dependent enumerator
998 template <typename T>
1000 enum class E { [[A]], B };
1006 typedef int $decl[[MyTypeDef]];
1007 enum Foo : My^TypeDef {};
1010 typedef int $decl[[MyTypeDef]];
1011 enum Foo : My^TypeDef;
1014 using $decl[[MyTypeDef]] = int;
1015 enum Foo : My^TypeDef {};
1020 @protocol $decl[[Dog]]
1023 id<Do^g> getDoggo() {
1033 @interface $decl[[Cat]] (Exte^nsion)
1036 @implementation $def[[Cat]] (Extension)
1042 @class $decl[[Foo]];
1048 R"objc(// Prefer interface definition over forward declaration
1050 @interface $decl[[Foo]]
1059 @interface $decl[[Foo]]
1061 @implementation $def[[Foo]]
1068 R"objc(// Method decl and definition for ObjC class.
1070 - (void)$decl[[meow]];
1073 - (void)$def[[meow]] {}
1075 void makeNoise(Cat *kitty) {
1080 R"objc(// Method decl and definition for ObjC category.
1083 @interface Dog (Play)
1084 - (void)$decl[[runAround]];
1086 @implementation Dog (Play)
1087 - (void)$def[[runAround]] {}
1089 void play(Dog *dog) {
1094 R"objc(// Method decl and definition for ObjC class extension.
1098 - (void)$decl[[howl]];
1101 - (void)$def[[howl]] {}
1103 void play(Dog *dog) {
1108 struct PointerIntPairInfo {
1109 static void *$decl[[getPointer]](void *Value);
1112 template <typename Info = PointerIntPairInfo> struct PointerIntPair {
1114 void *getPointer() const { return Info::get^Pointer(Value); }
1117 R"cpp(// Deducing this
1123 int x = wa^ldo.bar();
1126 for (
const char *Test : Tests) {
1128 std::optional<Range> WantDecl;
1129 std::optional<Range> WantDef;
1130 if (!
T.ranges().empty())
1131 WantDecl = WantDef =
T.range();
1132 if (!
T.ranges(
"decl").empty())
1133 WantDecl =
T.range(
"decl");
1134 if (!
T.ranges(
"def").empty())
1135 WantDef =
T.range(
"def");
1138 TU.
Code = std::string(
T.code());
1140 TU.ExtraArgs.push_back(
"-xobjective-c++");
1141 TU.ExtraArgs.push_back(
"-std=c++23");
1143 auto AST = TU.build();
1147 EXPECT_THAT(Results, IsEmpty()) << Test;
1149 ASSERT_THAT(Results, ::testing::SizeIs(1)) << Test;
1150 EXPECT_EQ(Results[0].PreferredDeclaration.range, *WantDecl) << Test;
1151 EXPECT_TRUE(Results[0].ID) << Test;
1152 std::optional<Range> GotDef;
1154 GotDef = Results[0].Definition->range;
1155 EXPECT_EQ(WantDef, GotDef) << Test;
1159TEST(LocateSymbol, ValidSymbolID) {
1161 #define MACRO(x, y) ((x) + (y))
1162 int add(int x, int y) { return $MACRO^MACRO(x, y); }
1163 int sum = $add^add(1, 2);
1167 auto AST = TU.build();
1168 auto Index = TU.index();
1170 ElementsAre(AllOf(
sym(
"add"),
1174 ElementsAre(AllOf(
sym(
"MACRO"),
1178TEST(LocateSymbol, AllMulti) {
1185 struct ExpectedRanges {
1187 std::optional<Range> WantDef;
1189 const char *Tests[] = {
1191 @interface $decl0[[Cat]]
1193 @implementation $def0[[Cat]]
1195 @interface $decl1[[Ca^t]] (Extension)
1198 @implementation $def1[[Cat]] (Extension)
1204 @interface $decl0[[Cat]]
1206 @implementation $def0[[Cat]]
1208 @interface $decl1[[Cat]] (Extension)
1211 @implementation $def1[[Ca^t]] (Extension)
1217 @interface $decl0[[Cat]]
1219 @interface $decl1[[Ca^t]] ()
1222 @implementation $def0[[$def1[[Cat]]]]
1227 for (
const char *Test : Tests) {
1229 std::vector<ExpectedRanges> Ranges;
1230 for (
int Idx = 0;
true; Idx++) {
1231 bool HasDecl = !
T.ranges(
"decl" + std::to_string(Idx)).empty();
1232 bool HasDef = !
T.ranges(
"def" + std::to_string(Idx)).empty();
1233 if (!HasDecl && !HasDef)
1235 ExpectedRanges
Range;
1237 Range.WantDecl =
T.range(
"decl" + std::to_string(Idx));
1239 Range.WantDef =
T.range(
"def" + std::to_string(Idx));
1240 Ranges.push_back(
Range);
1244 TU.
Code = std::string(
T.code());
1245 TU.ExtraArgs.push_back(
"-xobjective-c++");
1247 auto AST = TU.build();
1250 ASSERT_THAT(Results, ::testing::SizeIs(Ranges.size())) << Test;
1251 for (
size_t Idx = 0; Idx < Ranges.size(); Idx++) {
1252 EXPECT_EQ(Results[Idx].PreferredDeclaration.range, Ranges[Idx].WantDecl)
1253 <<
"($decl" << Idx <<
")" << Test;
1254 std::optional<Range> GotDef;
1256 GotDef = Results[Idx].Definition->range;
1257 EXPECT_EQ(GotDef, Ranges[Idx].WantDef) <<
"($def" << Idx <<
")" << Test;
1265TEST(LocateSymbol, Warnings) {
1266 const char *Tests[] = {
1267 R
"cpp(// Field, GNU old-style field designator
1268 struct Foo { int [[x]]; };
1270 Foo bar = { ^x : 1 };
1277 int main() { return ^MACRO; }
1283 for (
const char *Test : Tests) {
1285 std::optional<Range> WantDecl;
1286 std::optional<Range> WantDef;
1287 if (!
T.ranges().empty())
1288 WantDecl = WantDef =
T.range();
1289 if (!
T.ranges(
"decl").empty())
1290 WantDecl =
T.range(
"decl");
1291 if (!
T.ranges(
"def").empty())
1292 WantDef =
T.range(
"def");
1295 TU.
Code = std::string(
T.code());
1297 auto AST = TU.build();
1301 EXPECT_THAT(Results, IsEmpty()) << Test;
1303 ASSERT_THAT(Results, ::testing::SizeIs(1)) << Test;
1304 EXPECT_EQ(Results[0].PreferredDeclaration.range, *WantDecl) << Test;
1305 std::optional<Range> GotDef;
1307 GotDef = Results[0].Definition->range;
1308 EXPECT_EQ(WantDef, GotDef) << Test;
1313TEST(LocateSymbol, TextualSmoke) {
1316 struct [[MyClass]] {};
1317 // Comment mentioning M^yClass
1321 auto AST = TU.build();
1322 auto Index = TU.index();
1325 ElementsAre(AllOf(
sym(
"MyClass",
T.range(),
T.range()),
1329TEST(LocateSymbol, Textual) {
1330 const char *Tests[] = {
1332 struct [[MyClass]] {};
1333 // Comment mentioning M^yClass
1337 // Not triggered for string literal tokens.
1338 const char* s = "String literal mentioning M^yClass";
1340 R"cpp(// Ifdef'ed out code
1341 struct [[MyClass]] {};
1346 R"cpp(// Macro definition
1347 struct [[MyClass]] {};
1348 #define DECLARE_MYCLASS_OBJ(name) M^yClass name;
1350 R"cpp(// Invalid code
1352 int myFunction(int);
1353 // Not triggered for token which survived preprocessing.
1354 int var = m^yFunction();
1357 for (
const char *Test : Tests) {
1359 std::optional<Range> WantDecl;
1360 if (!
T.ranges().empty())
1361 WantDecl =
T.range();
1365 auto AST = TU.build();
1366 auto Index = TU.index();
1369 AST.getTokens(),
AST.getLangOpts());
1371 ADD_FAILURE() <<
"No word touching point!" << Test;
1375 testPath(TU.Filename), ASTNodeKind());
1378 EXPECT_THAT(Results, IsEmpty()) << Test;
1380 ASSERT_THAT(Results, ::testing::SizeIs(1)) << Test;
1381 EXPECT_EQ(Results[0].PreferredDeclaration.range, *WantDecl) << Test;
1386TEST(LocateSymbol, Ambiguous) {
1391 $ConstructorLoc[[Foo]](const char*);
1399 const char* str = "123";
1401 Foo b = Foo($2^str);
1406 Foo ab$8^cd("asdf");
1407 Foo foox = Fo$9^o("asdf");
1408 Foo abcde$10^("asdf");
1409 Foo foox2 = Foo$11^("asdf");
1412 template <typename T>
1414 void $NonstaticOverload1[[bar]](int);
1415 void $NonstaticOverload2[[bar]](float);
1417 static void $StaticOverload1[[baz]](int);
1418 static void $StaticOverload2[[baz]](float);
1421 template <typename T, typename U>
1422 void dependent_call(S<T> s, U u) {
1430 TU.ExtraArgs.push_back(
"-fno-delayed-template-parsing");
1431 auto AST = TU.build();
1446 ElementsAre(
sym(
"Foo",
T.range(
"ConstructorLoc"), std::nullopt)));
1448 ElementsAre(
sym(
"Foo",
T.range(
"ConstructorLoc"), std::nullopt)));
1453 UnorderedElementsAre(
1454 sym(
"bar",
T.range(
"NonstaticOverload1"), std::nullopt),
1455 sym(
"bar",
T.range(
"NonstaticOverload2"), std::nullopt)));
1457 UnorderedElementsAre(
1458 sym(
"baz",
T.range(
"StaticOverload1"), std::nullopt),
1459 sym(
"baz",
T.range(
"StaticOverload2"), std::nullopt)));
1462TEST(LocateSymbol, TextualDependent) {
1468 void $FooLoc[[uniqueMethodName]]();
1471 void $BarLoc[[uniqueMethodName]]();
1475 template <typename T>
1477 t.u^niqueMethodName();
1481 TU.Code = std::string(Source.code());
1482 TU.HeaderCode = std::string(Header.code());
1483 auto AST = TU.build();
1484 auto Index = TU.index();
1491 UnorderedElementsAre(
1492 sym(
"uniqueMethodName", Header.range(
"FooLoc"), std::nullopt),
1493 sym(
"uniqueMethodName", Header.range(
"BarLoc"), std::nullopt)));
1497 const char *Tests[] = {
1499 template <class T> struct function {};
1500 template <class T> using [[callback]] = function<T()>;
1509 typedef Foo [[Bar]];
1515 using [[Bar]] = Foo; // definition
1528 namespace ns { class [[Foo]] {}; }
1533 namespace ns { int [[x]](char); int [[x]](double); }
1538 namespace ns { int [[x]](char); int x(double); }
1544 namespace ns { class [[Foo]] {}; }
1552 typedef Foo [[Ba^r]];
1556 using [[B^ar]] = Foo;
1561 template <typename T>
1565 template <typename T>
1566 struct Derived : Base<T> {
1567 using Base<T>::w^aldo;
1572 for (
const auto *Case : Tests) {
1577 UnorderedPointwise(declRange(),
T.ranges()));
1581TEST(LocateSymbol, RelPathsInCompileCommand) {
1586#include "header_in_preamble.h"
1588#include "header_not_in_preamble.h"
1589int baz = f$p1^oo + bar_pre$p2^amble + bar_not_pre$p3^amble;
1593int [[bar_preamble]];
1597int [[bar_not_preamble]];
1602 SmallString<32> RelPathPrefix(
"..");
1603 llvm::sys::path::append(RelPathPrefix,
"src");
1604 std::string BuildDir =
testPath(
"build");
1611 auto FooCpp =
testPath(
"src/foo.cpp");
1612 FS.Files[FooCpp] =
"";
1613 auto HeaderInPreambleH =
testPath(
"src/header_in_preamble.h");
1614 FS.Files[HeaderInPreambleH] = std::string(HeaderInPreambleAnnotations.code());
1615 auto HeaderNotInPreambleH =
testPath(
"src/header_not_in_preamble.h");
1616 FS.Files[HeaderNotInPreambleH] =
1617 std::string(HeaderNotInPreambleAnnotations.code());
1624 EXPECT_TRUE(
bool(Locations)) <<
"findDefinitions returned an error";
1625 EXPECT_THAT(*Locations, ElementsAre(
sym(
"foo", SourceAnnotations.range(),
1626 SourceAnnotations.range())));
1630 EXPECT_TRUE(
bool(Locations)) <<
"findDefinitions returned an error";
1633 ElementsAre(
sym(
"bar_preamble", HeaderInPreambleAnnotations.range(),
1634 HeaderInPreambleAnnotations.range())));
1638 EXPECT_TRUE(
bool(Locations)) <<
"findDefinitions returned an error";
1639 EXPECT_THAT(*Locations,
1640 ElementsAre(
sym(
"bar_not_preamble",
1641 HeaderNotInPreambleAnnotations.range(),
1642 HeaderNotInPreambleAnnotations.range())));
1651 const char *SourceContents = R
"cpp(
1652 #include ^"$2^foo.h$3^"
1653 #include "$4^invalid.h"
1657 #in$5^clude "$6^foo.h"$7^
1660 FS.Files[FooCpp] = std::string(SourceAnnotations.code());
1667 FS.Files[FooH] = std::string(HeaderAnnotations.code());
1674 ASSERT_TRUE(
bool(Locations)) <<
"locateSymbolAt returned an error";
1675 EXPECT_THAT(*Locations, ElementsAre(
sym(
"foo.h", HeaderAnnotations.range(),
1676 HeaderAnnotations.range())));
1680 ASSERT_TRUE(
bool(Locations)) <<
"locateSymbolAt returned an error";
1681 EXPECT_THAT(*Locations, ElementsAre(
sym(
"foo.h", HeaderAnnotations.range(),
1682 HeaderAnnotations.range())));
1685 ASSERT_TRUE(
bool(Locations)) <<
"locateSymbolAt returned an error";
1686 EXPECT_THAT(*Locations, ElementsAre(
sym(
"foo.h", HeaderAnnotations.range(),
1687 HeaderAnnotations.range())));
1691 ASSERT_TRUE(
bool(Locations)) <<
"locateSymbolAt returned an error";
1692 EXPECT_THAT(*Locations, ElementsAre(
sym(
"foo.h", HeaderAnnotations.range(),
1693 HeaderAnnotations.range())));
1697 ASSERT_TRUE(
bool(Locations)) <<
"locateSymbolAt returned an error";
1698 EXPECT_THAT(*Locations, IsEmpty());
1701 ASSERT_TRUE(
bool(Locations)) <<
"locateSymbolAt returned an error";
1702 EXPECT_THAT(*Locations, ElementsAre(
sym(
"foo.h", HeaderAnnotations.range(),
1703 HeaderAnnotations.range())));
1706 ASSERT_TRUE(
bool(Locations)) <<
"locateSymbolAt returned an error";
1707 EXPECT_THAT(*Locations, ElementsAre(
sym(
"foo.h", HeaderAnnotations.range(),
1708 HeaderAnnotations.range())));
1715 FS.Files[FooM] = std::string(ObjC.code());
1719 ASSERT_TRUE(
bool(Locations)) <<
"locateSymbolAt returned an error";
1720 EXPECT_THAT(*Locations, ElementsAre(
sym(
"foo.h", HeaderAnnotations.range(),
1721 HeaderAnnotations.range())));
1724TEST(LocateSymbol, WithPreamble) {
1733 Annotations FooWithHeader(R
"cpp(#include "fo^o.h")cpp");
1734 Annotations FooWithoutHeader(R"cpp(double [[fo^o]]();)cpp");
1736 FS.Files[FooCpp] = std::string(FooWithHeader.code());
1740 FS.Files[FooH] = std::string(FooHeader.code());
1746 ElementsAre(
sym(
"foo.h", FooHeader.range(), FooHeader.range())));
1749 Server.addDocument(FooCpp, FooWithoutHeader.code(),
"null",
1755 ElementsAre(
sym(
"foo", FooWithoutHeader.range(), std::nullopt)));
1760 Server.addDocument(FooCpp, FooWithoutHeader.code(),
"null",
1765 ElementsAre(
sym(
"foo", FooWithoutHeader.range(), std::nullopt)));
1768TEST(LocateSymbol, NearbyTokenSmoke) {
1770 // prints e^rr and crashes
1771 void die(const char* [[err]]);
1776 ElementsAre(
sym(
"err",
T.range(),
T.range())));
1779TEST(LocateSymbol, NearbyIdentifier) {
1780 const char *Tests[] = {
1782 // regular identifiers (won't trigger)
1787 // disabled preprocessor sections
1799 // not triggered by string literals
1801 const char* greeting = "h^ello, world";
1805 // can refer to macro invocations
1812 // can refer to macro invocations (even if they expand to nothing)
1819 // prefer nearest occurrence, backwards is worse than forwards
1828 // short identifiers find near results
1833 // short identifiers don't find far results
1846 // prefer nearest occurrence even if several matched tokens
1847 // have the same value of `floor(log2(<token line> - <word line>))`.
1849 int x = hello, y = hello;
1853 for (
const char *Test : Tests) {
1856 const auto &SM =
AST.getSourceManager();
1857 std::optional<Range> Nearby;
1860 AST.getTokens(),
AST.getLangOpts());
1862 ADD_FAILURE() <<
"No word at point! " << Test;
1867 Tok->location(), Tok->endLocation()));
1868 if (
T.ranges().empty())
1869 EXPECT_THAT(Nearby, Eq(std::nullopt)) << Test;
1871 EXPECT_EQ(Nearby,
T.range()) << Test;
1875TEST(FindImplementations, Inheritance) {
1876 llvm::StringRef Test = R
"cpp(
1878 virtual void F$1^oo();
1881 struct $0[[Child1]] : Base {
1882 void $1[[Fo$3^o]]() override;
1883 virtual void B$2^ar();
1884 void Concrete(); // No implementations for concrete methods.
1886 struct $0[[Child2]] : Child1 {
1887 void $1[[$3[[Foo]]]]() override;
1888 void $2[[Bar]]() override;
1890 void FromReference() {
1899 // CRTP should work.
1900 template<typename T>
1901 struct $5^TemplateBase {};
1902 struct $5[[Child3]] : public TemplateBase<Child3> {};
1905 void LocationFunction() {
1906 struct $0[[LocalClass1]] : Base {
1907 void $1[[Foo]]() override;
1909 struct $6^LocalBase {
1910 virtual void $7^Bar();
1912 struct $6[[LocalClass2]]: LocalBase {
1913 void $7[[Bar]]() override;
1920 auto AST = TU.build();
1921 auto Index = TU.index();
1922 for (StringRef
Label : {
"0",
"1",
"2",
"3",
"4",
"5",
"6",
"7"}) {
1923 for (
const auto &Point : Code.points(
Label)) {
1925 UnorderedPointwise(declRange(), Code.ranges(
Label)))
1926 << Code.code() <<
" at " << Point <<
" for Label " <<
Label;
1931TEST(FindImplementations, InheritanceRecursion) {
1933 llvm::StringRef Test = R
"cpp(
1942 static const bool value = true;
1947 static const bool value = false;
1951 struct [[Even]] : Odd<I - 1> {};
1954 struct [[Odd]] : Even<I - 1> {};
1956 constexpr bool Answer = Even<42>::value;
1961 auto AST = TU.build();
1962 auto Index = TU.index();
1964 UnorderedPointwise(defRange(), Code.ranges()));
1967TEST(FindImplementations, InheritanceObjC) {
1968 llvm::StringRef Test = R
"objc(
1969 @interface $base^Base
1973 - (void)$protocol^protocol;
1975 @interface $ChildDecl[[Child]] : Base <Protocol>
1977 - (void)$fooDecl[[foo]];
1979 @implementation $ChildDef[[Child]]
1981 - (void)$fooDef[[foo]] {}
1982 - (void)$protocolDef[[protocol]] {}
1988 TU.ExtraArgs.push_back(
"-xobjective-c++");
1989 auto AST = TU.build();
1990 auto Index = TU.index();
1992 UnorderedElementsAre(
sym(
"Child", Code.range(
"ChildDecl"),
1993 Code.range(
"ChildDef"))));
1995 UnorderedElementsAre(
1996 sym(
"foo", Code.range(
"fooDecl"), Code.range(
"fooDef"))));
1998 UnorderedElementsAre(
sym(
"protocol", Code.range(
"protocolDef"),
1999 Code.range(
"protocolDef"))));
2002TEST(FindImplementations, CaptureDefinition) {
2003 llvm::StringRef Test = R
"cpp(
2005 virtual void F^oo();
2007 struct Child1 : Base {
2008 void $Decl[[Foo]]() override;
2010 struct Child2 : Base {
2011 void $Child2[[Foo]]() override;
2013 void Child1::$Def[[Foo]]() { /* Definition */ }
2017 auto AST = TU.build();
2020 UnorderedElementsAre(
sym(
"Foo", Code.range(
"Decl"), Code.range(
"Def")),
2021 sym(
"Foo", Code.range(
"Child2"), std::nullopt)))
2027 struct $Target[[Target]] { operator int() const; };
2028 struct Aggregate { Target a, b; };
2032 template <typename T> struct $smart_ptr[[smart_ptr]] {
2039 for (
const llvm::StringRef Case : {
2043 "a^uto x = Target{};",
2044 "namespace m { Target tgt; } auto x = m^::tgt;",
2045 "Target funcCall(); auto x = ^funcCall();",
2046 "Aggregate a = { {}, ^{} };",
2047 "Aggregate a = { ^.a=t, };",
2048 "struct X { Target a; X() : ^a() {} };",
2049 "^using T = Target; ^T foo();",
2050 "^template <int> Target foo();",
2051 "void x() { try {} ^catch(Target e) {} }",
2052 "void x() { ^throw t; }",
2053 "int x() { ^return t; }",
2054 "void x() { ^switch(t) {} }",
2055 "void x() { ^delete (Target*)nullptr; }",
2056 "Target& ^tref = t;",
2057 "void x() { ^if (t) {} }",
2058 "void x() { ^while (t) {} }",
2059 "void x() { ^do { } while (t); }",
2060 "void x() { ^make(); }",
2061 "void x(smart_ptr<Target> &t) { t.^get(); }",
2062 "^auto x = []() { return t; };",
2063 "Target* ^tptr = &t;",
2064 "Target ^tarray[3];",
2067 TU.Code =
A.code().str();
2070 ASSERT_GT(
A.points().size(), 0u) << Case;
2071 for (
auto Pos :
A.points())
2074 sym(
"Target", HeaderA.range(
"Target"), HeaderA.range(
"Target"))))
2078 for (
const llvm::StringRef Case : {
2079 "smart_ptr<Target> ^tsmart;",
2082 TU.Code =
A.code().str();
2086 UnorderedElementsAre(
2087 sym(
"Target", HeaderA.range(
"Target"), HeaderA.range(
"Target")),
2088 sym(
"smart_ptr", HeaderA.range(
"smart_ptr"), HeaderA.range(
"smart_ptr"))
2104 ElementsAre(
sym(
"X",
A.range(
"decl"),
A.range(
"def"))));
2107TEST(FindType, Index) {
2109 // This definition is only available through the index.
2113 DefTU.HeaderFilename = "def.h";
2114 auto DefIdx = DefTU.index();
2124 ElementsAre(
sym(
"X",
A.range(), Def.range())));
2127void checkFindRefs(llvm::StringRef Test,
bool UseIndex =
false) {
2130 TU.ExtraArgs.push_back(
"-std=c++20");
2131 TU.ExtraArgs.push_back(
"-xobjective-c++");
2133 auto AST = TU.build();
2134 std::vector<Matcher<ReferencesResult::Reference>> ExpectedLocations;
2135 for (
const auto &[R,
Context] :
T.rangesWithPayload())
2136 ExpectedLocations.push_back(
2137 AllOf(rangeIs(R), containerIs(
Context), attrsAre(0u)));
2140 for (
const auto &[R,
Context] :
T.rangesWithPayload(
"def"))
2141 ExpectedLocations.push_back(AllOf(rangeIs(R), containerIs(
Context),
2144 for (
const auto &[R,
Context] :
T.rangesWithPayload(
"decl"))
2145 ExpectedLocations.push_back(AllOf(rangeIs(R), containerIs(
Context),
2147 for (
const auto &[R,
Context] :
T.rangesWithPayload(
"overridedecl"))
2148 ExpectedLocations.push_back(AllOf(
2149 rangeIs(R), containerIs(
Context),
2151 for (
const auto &[R,
Context] :
T.rangesWithPayload(
"overridedef"))
2152 ExpectedLocations.push_back(AllOf(rangeIs(R), containerIs(
Context),
2156 for (
const auto &P :
T.points()) {
2160 UnorderedElementsAreArray(ExpectedLocations))
2161 <<
"Failed for Refs at " <<
P <<
"\n"
2166TEST(FindReferences, WithinAST) {
2167 const char *Tests[] = {
2168 R
"cpp(// Local variable
2170 int $def(main)[[foo]];
2171 $(main)[[^foo]] = 2;
2172 int test1 = $(main)[[foo]];
2178 struct $def(ns1)[[Foo]] {};
2181 ns1::$(main)[[Fo^o]]* Params;
2185 R"cpp(// Forward declaration
2187 class $def[[Foo]] {};
2189 $(main)[[Fo^o]] foo;
2194 int $def[[foo]](int) { return 0; }
2196 auto *X = &$(main)[[^foo]];
2203 int $def(Foo)[[foo]];
2204 Foo() : $(Foo::Foo)[[foo]](0) {}
2208 f.$(main)[[f^oo]] = 1;
2212 R"cpp(// Method call
2213 struct Foo { int $decl(Foo)[[foo]](); };
2214 int Foo::$def(Foo)[[foo]]() { return 0; }
2217 f.$(main)[[^foo]]();
2221 R"cpp(// Constructor
2223 $decl(Foo)[[F^oo]](int);
2226 Foo f = $(foo)[[Foo]](42);
2231 typedef int $def[[Foo]];
2233 $(main)[[^Foo]] bar;
2238 namespace $decl[[ns]] { // FIXME: def?
2241 int main() { $(main)[[^ns]]::Foo foo; }
2247 #define CAT(X, Y) X##Y
2248 class $def[[Fo^o]] {};
2250 TYPE($(test)[[Foo]]) foo;
2251 $(test)[[FOO]] foo2;
2252 TYPE(TYPE($(test)[[Foo]])) foo3;
2253 $(test)[[CAT]](Fo, o) foo4;
2258 #define $def[[MA^CRO]](X) (X+1)
2260 int x = $[[MACRO]]($[[MACRO]](1));
2264 R"cpp(// Macro outside preamble
2266 #define $def[[MA^CRO]](X) (X+1)
2268 int x = $[[MACRO]]($[[MACRO]](1));
2273 int $def[[v^ar]] = 0;
2274 void foo(int s = $(foo)[[var]]);
2278 template <typename T>
2279 class $def[[Fo^o]] {};
2280 void func($(func)[[Foo]]<int>);
2284 template <typename T>
2285 class $def[[Foo]] {};
2286 void func($(func)[[Fo^o]]<int>);
2288 R"cpp(// Not touching any identifiers.
2290 $def(Foo)[[~]]Foo() {};
2294 f.$(foo)[[^~]]Foo();
2297 R"cpp(// Lambda capture initializer
2299 int $def(foo)[[w^aldo]] = 42;
2300 auto lambda = [x = $(foo)[[waldo]]](){};
2303 R"cpp(// Renaming alias
2304 template <typename> class Vector {};
2305 using $def[[^X]] = Vector<int>;
2310 R"cpp(// Dependent code
2311 template <typename T> void $decl[[foo]](T t);
2312 template <typename T> void bar(T t) { $(bar)[[foo]](t); } // foo in bar is uninstantiated.
2313 void baz(int x) { $(baz)[[f^oo]](x); }
2318 void $decl(ns)[[foo]](S s);
2320 template <typename T> void foo(T t);
2321 // FIXME: Maybe report this foo as a ref to ns::foo (because of ADL)
2322 // when bar<ns::S> is instantiated?
2323 template <typename T> void bar(T t) { foo(t); }
2330 R"cpp(// unresolved member expression
2332 template <typename T> void $decl(Foo)[[b^ar]](T t);
2334 template <typename T> void test(Foo F, T t) {
2335 F.$(test)[[bar]](t);
2341 typedef int $def[[MyTypeD^ef]];
2342 enum MyEnum : $(MyEnum)[[MyTy^peDef]] { };
2345 typedef int $def[[MyType^Def]];
2346 enum MyEnum : $(MyEnum)[[MyTypeD^ef]];
2349 using $def[[MyTypeD^ef]] = int;
2350 enum MyEnum : $(MyEnum)[[MyTy^peDef]] { };
2354 bool $decl[[operator]]"" _u^dl(unsigned long long value);
2355 bool x = $(x)[[1_udl]];
2360 static void $decl(S)[[operator]] delete(void *);
2361 static void deleteObject(S *S) {
2362 $(S::deleteObject)[[de^lete]] S;
2368 const int $def[[F^oo]] = 0;
2370 [$(Bar)[[F^oo]]...$(Bar)[[Fo^o]] + 1] = 0,
2371 [$(Bar)[[^Foo]] + 2] = 1
2374 for (
const char *Test : Tests)
2375 checkFindRefs(Test);
2378TEST(FindReferences, ConceptsWithinAST) {
2379 constexpr llvm::StringLiteral Code = R
"cpp(
2381 concept $def[[IsSmal^l]] = sizeof(T) <= 8;
2384 concept IsSmallPtr = requires(T x) {
2385 { *x } -> $(IsSmallPtr)[[IsSmal^l]];
2388 $(i)[[IsSmall]] auto i = 'c';
2389 template<$(foo)[[IsSmal^l]] U> void foo();
2390 template<class U> void bar() requires $(bar)[[IsSmal^l]]<U>;
2391 template<class U> requires $(baz)[[IsSmal^l]]<U> void baz();
2392 static_assert([[IsSma^ll]]<char>);
2394 checkFindRefs(Code);
2397TEST(FindReferences, ConceptReq) {
2398 constexpr llvm::StringLiteral Code = R
"cpp(
2400 concept $def[[IsSmal^l]] = sizeof(T) <= 8;
2403 concept IsSmallPtr = requires(T x) {
2404 { *x } -> $(IsSmallPtr)[[IsSmal^l]];
2407 checkFindRefs(Code);
2410TEST(FindReferences, RequiresExprParameters) {
2411 constexpr llvm::StringLiteral Code = R
"cpp(
2413 concept IsSmall = sizeof(T) <= 8;
2416 concept IsSmallPtr = requires(T $def[[^x]]) {
2417 { *$(IsSmallPtr)[[^x]] } -> IsSmall;
2420 checkFindRefs(Code);
2423TEST(FindReferences, IncludeOverrides) {
2424 llvm::StringRef Test =
2428 virtu^al void $decl(Base)[[f^unc]]() ^= ^0;
2430 class Derived : public Base {
2432 void $overridedecl(Derived::func)[[func]]() override;
2434 void Derived::$overridedef[[func]]() {}
2435 class Derived2 : public Base {
2436 void $overridedef(Derived2::func)[[func]]() override {}
2438 void test(Derived* D, Base* B) {
2439 D->func(); // No references to the overrides.
2440 B->$(test)[[func]]();
2442 checkFindRefs(Test, true);
2445TEST(FindReferences, IncludeOverridesObjC) {
2446 llvm::StringRef Test =
2449 - (void)$decl(Base)[[f^unc]];
2451 @interface Derived : Base
2452 - (void)$overridedecl(Derived::func)[[func]];
2454 @implementation Derived
2455 - (void)$overridedef[[func]] {}
2457 void test(Derived *derived, Base *base) {
2458 [derived func]; // No references to the overrides.
2459 [base $(test)[[func]]];
2461 checkFindRefs(Test, true);
2464TEST(FindReferences, RefsToBaseMethod) {
2465 llvm::StringRef Test =
2469 virtual void $(BaseBase)[[func]]();
2471 class Base : public BaseBase {
2473 void $(Base)[[func]]() override;
2475 class Derived : public Base {
2477 void $decl(Derived)[[fu^nc]]() over^ride;
2479 void test(BaseBase* BB, Base* B, Derived* D) {
2480 // refs to overridden methods in complete type hierarchy are reported.
2481 BB->$(test)[[func]]();
2482 B->$(test)[[func]]();
2483 D->$(test)[[fu^nc]]();
2485 checkFindRefs(Test, true);
2488TEST(FindReferences, RefsToBaseMethodObjC) {
2489 llvm::StringRef Test =
2492 - (void)$(BaseBase)[[func]];
2494 @interface Base : BaseBase
2495 - (void)$(Base)[[func]];
2497 @interface Derived : Base
2498 - (void)$decl(Derived)[[fu^nc]];
2500 void test(BaseBase *bb, Base *b, Derived *d) {
2501 // refs to overridden methods in complete type hierarchy are reported.
2502 [bb $(test)[[func]]];
2503 [b $(test)[[func]]];
2504 [d $(test)[[fu^nc]]];
2506 checkFindRefs(Test, true);
2509TEST(FindReferences, MainFileReferencesOnly) {
2510 llvm::StringRef Test =
2514 // refs not from main file should not be included.
2520 TU.AdditionalFiles[
"foo.inc"] = R
"cpp(
2523 auto AST = TU.build();
2525 std::vector<Matcher<ReferencesResult::Reference>> ExpectedLocations;
2526 for (
const auto &R : Code.ranges())
2527 ExpectedLocations.push_back(rangeIs(R));
2529 ElementsAreArray(ExpectedLocations))
2533TEST(FindReferences, ExplicitSymbols) {
2534 const char *Tests[] = {
2536 struct Foo { Foo* $decl(Foo)[[self]]() const; };
2539 if (Foo* T = foo.$(f)[[^self]]()) {} // Foo member call expr.
2544 struct Foo { Foo(int); };
2547 return $(f)[[^b]]; // Foo constructor expr.
2556 g($(call)[[^f]]()); // Foo constructor expr.
2561 void $decl[[foo]](int);
2562 void $decl[[foo]](double);
2565 using ::$decl(ns)[[fo^o]];
2576 $(test)[[a]].operator bool();
2577 if ($(test)[[a^]]) {} // ignore implicit conversion-operator AST node
2582 for (
const char *Test : Tests)
2583 checkFindRefs(Test);
2586TEST(FindReferences, UsedSymbolsFromInclude) {
2587 const char *Tests[] = {
2588 R
"cpp( [[#include ^"bar.h"]]
2590 int fstBar = [[bar1]]();
2591 int sndBar = [[bar2]]();
2593 int macroBar = [[BAR]];
2594 std::vector<int> vec;
2597 R"cpp([[#in^clude <vector>]]
2598 std::[[vector]]<int> vec;
2602 [[#include ^"udl_header.h"]]
2606 for (
const char *Test : Tests) {
2609 TU.ExtraArgs.push_back(
"-std=c++20");
2610 TU.AdditionalFiles[
"bar.h"] = guard(R
"cpp(
2616 TU.AdditionalFiles["system/vector"] = guard(R
"cpp(
2622 TU.AdditionalFiles["udl_header.h"] = guard(R
"cpp(
2623 bool operator"" _b(unsigned long long value);
2625 TU.ExtraArgs.push_back("-isystem" +
testPath(
"system"));
2627 auto AST = TU.build();
2628 std::vector<Matcher<ReferencesResult::Reference>> ExpectedLocations;
2629 for (
const auto &R :
T.ranges())
2630 ExpectedLocations.push_back(AllOf(rangeIs(R), attrsAre(0u)));
2631 for (
const auto &P :
T.points())
2633 UnorderedElementsAreArray(ExpectedLocations))
2634 <<
"Failed for Refs at " <<
P <<
"\n"
2639TEST(FindReferences, NeedsIndexForSymbols) {
2640 const char *Header =
"int foo();";
2643 TU.
Code = std::string(Main.code());
2644 TU.HeaderCode = Header;
2645 auto AST = TU.build();
2650 ElementsAre(rangeIs(Main.range())));
2652 int $decl[[foo]]() { return 42; }
2653 void bar() { $bar(bar)[[foo]](); }
2654 struct S { void bar() { $S(S::bar)[[foo]](); } };
2655 namespace N { void bar() { $N(N::bar)[[foo]](); } }
2660 IndexedTU.
Code = std::string(IndexedMain.code());
2661 IndexedTU.Filename =
"Indexed.cpp";
2662 IndexedTU.HeaderCode = Header;
2668 rangeIs(Main.range()),
2669 AllOf(rangeIs(IndexedMain.range(
"decl")),
2672 AllOf(rangeIs(IndexedMain.range(
"bar")), containerIs(
"bar")),
2673 AllOf(rangeIs(IndexedMain.range(
"S")), containerIs(
"S::bar")),
2674 AllOf(rangeIs(IndexedMain.range(
"N")), containerIs(
"N::bar"))));
2677 EXPECT_EQ(1u, LimitRefs.References.size());
2678 EXPECT_TRUE(LimitRefs.HasMore);
2681 TU.Code = (
"\n\n" + Main.code()).str();
2683 ElementsAre(rangeIs(Main.range())));
2686TEST(FindReferences, NeedsIndexForMacro) {
2687 const char *Header =
"#define MACRO(X) (X+1)";
2690 int a = [[MA^CRO]](1);
2694 TU.Code = std::string(Main.code());
2695 TU.HeaderCode = Header;
2696 auto AST = TU.build();
2701 ElementsAre(rangeIs(Main.range())));
2704 int indexed_main() {
2705 int a = [[MACRO]](1);
2712 IndexedTU.
Code = std::string(IndexedMain.code());
2713 IndexedTU.Filename =
"Indexed.cpp";
2714 IndexedTU.HeaderCode = Header;
2717 ElementsAre(rangeIs(Main.range()), rangeIs(IndexedMain.range())));
2720 EXPECT_EQ(1u, LimitRefs.References.size());
2721 EXPECT_TRUE(LimitRefs.HasMore);
2724TEST(FindReferences, NoQueryForLocalSymbols) {
2725 struct RecordingIndex :
public MemIndex {
2726 mutable std::optional<llvm::DenseSet<SymbolID>> RefIDs;
2727 bool refs(
const RefsRequest &Req,
2728 llvm::function_ref<
void(
const Ref &)>)
const override {
2735 StringRef AnnotatedCode;
2740 {
"namespace { int ^x; }",
true},
2741 {
"static int ^x;",
true},
2743 {
"void foo() { int ^x; }",
false},
2744 {
"void foo() { struct ^x{}; }",
false},
2745 {
"auto lambda = []{ int ^x; };",
false},
2747 for (Test T : Tests) {
2753 EXPECT_NE(Rec.RefIDs, std::nullopt) <<
T.AnnotatedCode;
2755 EXPECT_EQ(Rec.RefIDs, std::nullopt) <<
T.AnnotatedCode;
2759TEST(FindReferences, ConstructorForwardingInAST) {
2762 template <class T> T &&forward(T &t);
2763 template <class T, class... Args> T *make_unique(Args &&...args) {
2764 return new T(std::forward<Args>(args)...);
2769 $Constructor[[T^est]](){}
2773 auto a = std::$Caller[[make_unique]]<Test>();
2777 TU.Code = std::string(Main.code());
2778 auto AST = TU.build();
2781 ElementsAre(rangeIs(Main.range(
"Constructor")),
2782 rangeIs(Main.range(
"Caller"))));
2785TEST(FindReferences, ConstructorForwardingInASTChained) {
2788 template <class T> T &&forward(T &t);
2789 template <class T, class... Args> T *make_unique(Args &&...args) {
2790 return new T(forward<Args>(args)...);
2792 template <class T, class... Args> T *make_unique2(Args &&...args) {
2793 return make_unique<T>(forward<Args>(args)...);
2795 template <class T, class... Args> T *make_unique3(Args &&...args) {
2796 return make_unique2<T>(forward<Args>(args)...);
2801 $Constructor[[T^est]](){}
2805 auto a = std::$Caller[[make_unique3]]<Test>();
2809 TU.Code = std::string(Main.code());
2810 auto AST = TU.build();
2813 ElementsAre(rangeIs(Main.range(
"Constructor")),
2814 rangeIs(Main.range(
"Caller"))));
2817TEST(FindReferences, ConstructorForwardingInIndex) {
2820 template <class T> T &&forward(T &t);
2821 template <class T, class... Args> T *make_unique(Args &&...args) {
2822 return new T(std::forward<Args>(args)...);
2830 #include "header.hpp"
2832 auto a = std::[[make_unique]]<Test>();
2836 TW.addSource("header.hpp", Header.code());
2837 TW.addMainFile(
"main.cpp", Main.code());
2838 auto AST = TW.openFile(
"header.hpp").value();
2839 auto Index = TW.index();
2846 AllOf(rangeIs(Header.range()), fileIs(
testPath(
"header.hpp"))),
2847 AllOf(rangeIs(Main.range()), fileIs(
testPath(
"main.cpp")))));
2850TEST(FindReferences, TemplatedConstructorForwarding) {
2853 template <class T> T &&forward(T &t);
2854 template <class T, class... Args> T *make_unique(Args &&...args) {
2855 return new T(std::forward<Args>(args)...);
2860 template <typename T>
2861 $Constructor[[W$Waldo^aldo]](T);
2863 template <typename T>
2865 $Constructor2[[W$Waldo2^aldo2]](int);
2871 Waldo $Caller[[w]](s);
2872 std::$ForwardedCaller[[make_unique]]<Waldo>(s);
2874 Waldo2<int> $Caller2[[w2]](42);
2875 std::$ForwardedCaller2[[make_unique]]<Waldo2<int>>(42);
2879 TU.Code = std::string(Main.code());
2880 auto AST = TU.build();
2883 ElementsAre(rangeIs(Main.range(
"Constructor")),
2884 rangeIs(Main.range(
"Caller")),
2885 rangeIs(Main.range(
"ForwardedCaller"))));
2888 ElementsAre(rangeIs(Main.range(
"Constructor2")),
2889 rangeIs(Main.range(
"Caller2")),
2890 rangeIs(Main.range(
"ForwardedCaller2"))));
2893TEST(GetNonLocalDeclRefs,
All) {
2895 llvm::StringRef AnnotatedCode;
2896 std::vector<std::string> ExpectedDecls;
2902 void ^foo(int baz) {
2911 class Foo { public: void foo(); };
2921 {"Bar",
"Bar::bar",
"Foo",
"Foo::foo"},
2927 class Foo { public: void foo() {} };
2928 class Bar { public: void bar() {} };
2939 template <typename T, template<typename> class Q>
2947 for (
const Case &C : Cases) {
2950 SourceLocation SL = llvm::cantFail(
2953 const FunctionDecl *FD =
2954 llvm::dyn_cast<FunctionDecl>(&
findDecl(
AST, [SL](
const NamedDecl &ND) {
2955 return ND.getLocation() == SL && llvm::isa<FunctionDecl>(ND);
2957 ASSERT_NE(FD,
nullptr);
2960 std::vector<std::string> Names;
2961 for (
const Decl *D : NonLocalDeclRefs) {
2962 if (
const auto *ND = llvm::dyn_cast<NamedDecl>(D))
2963 Names.push_back(ND->getQualifiedNameAsString());
2965 EXPECT_THAT(Names, UnorderedElementsAreArray(
C.ExpectedDecls))
2972 #define HEADER_AA "faa.h"
2973 #define HEADER_BB "fbb.h"
2974 #define GET_HEADER(X) HEADER_ ## X
2976 #/*comments*/include /*comments*/ $foo[["foo.h"]] //more comments
2977 int end_of_preamble = 0;
2978 #include $bar[[<bar.h>]]
2979 #include $AA[[GET_HEADER]](AA) // Some comment !
2980 # /* What about */ \
2981 include /* multiple line */ \
2982 $BB[[GET_HEADER]]( /* statements ? */ \
2987 TU.Code = std::string(MainCpp.code());
2988 TU.AdditionalFiles = {
2989 {"faa.h",
""}, {
"fbb.h",
""}, {
"foo.h",
""}, {
"bar.h",
""}};
2990 TU.ExtraArgs = {
"-isystem."};
2991 auto AST = TU.build();
std::vector< HeaderEntry > HeaderContents
Same as llvm::Annotations, but adjusts functions to LSP-specific types for positions and ranges.
Manages a collection of source files and derived data (ASTs, indexes), and provides language-aware fe...
static Options optsForTest()
A context is an immutable container for per-request data that must be propagated through layers that ...
MemIndex is a naive in-memory index suitable for a small set of symbols.
Stores and provides access to parsed AST.
void addSource(llvm::StringRef Filename, llvm::StringRef Code)
FIXME: Skip testing on windows temporarily due to the different escaping code mode.
SymbolID getSymbolID(const Decl *D)
Gets the symbol ID for a declaration. Returned SymbolID might be null.
const NamedDecl & findDecl(ParsedAST &AST, llvm::StringRef QName)
Range halfOpenToRange(const SourceManager &SM, CharSourceRange R)
std::vector< DocumentHighlight > findDocumentHighlights(ParsedAST &AST, Position Pos)
Returns highlights for all usages of a symbol at Pos.
Symbol sym(llvm::StringRef QName, index::SymbolKind Kind, llvm::StringRef USRFormat, llvm::StringRef Signature)
std::vector< LocatedSymbol > locateSymbolTextually(const SpelledWord &Word, ParsedAST &AST, const SymbolIndex *Index, llvm::StringRef MainFilePath, ASTNodeKind NodeKind)
std::vector< DocumentLink > getDocumentLinks(ParsedAST &AST)
Get all document links.
MATCHER_P2(hasFlag, Flag, Path, "")
std::vector< LocatedSymbol > findType(ParsedAST &AST, Position Pos, const SymbolIndex *Index)
Returns symbols for types referenced at Pos.
ReferencesResult findReferences(ParsedAST &AST, Position Pos, uint32_t Limit, const SymbolIndex *Index, bool AddContext)
Returns references of the symbol at a specified Pos.
std::string testPath(PathRef File, llvm::sys::path::Style Style)
std::vector< LocatedSymbol > locateSymbolAt(ParsedAST &AST, Position Pos, const SymbolIndex *Index)
Get definition of symbol at a specified Pos.
TEST(BackgroundQueueTest, Priority)
const syntax::Token * findNearbyIdentifier(const SpelledWord &Word, const syntax::TokenBuffer &TB)
void runAddDocument(ClangdServer &Server, PathRef File, llvm::StringRef Contents, llvm::StringRef Version, WantDiagnostics WantDiags, bool ForceRebuild)
llvm::Expected< std::vector< LocatedSymbol > > runLocateSymbolAt(ClangdServer &Server, PathRef File, Position Pos)
const Symbol & findSymbol(const SymbolSlab &Slab, llvm::StringRef QName)
llvm::Expected< SourceLocation > sourceLocationInMainFile(const SourceManager &SM, Position P)
Return the file location, corresponding to P.
@ No
Diagnostics must be generated for this snapshot.
std::vector< LocatedSymbol > findImplementations(ParsedAST &AST, Position Pos, const SymbolIndex *Index)
Returns implementations at a specified Pos:
llvm::DenseSet< const Decl * > getNonLocalDeclRefs(ParsedAST &AST, const FunctionDecl *FD)
Returns all decls that are referenced in the FD except local symbols.
@ Alias
This declaration is an alias that was referred to.
cppcoreguidelines::ProBoundsAvoidUncheckedContainerAccessCheck P
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
A range in a text document that links to an internal or external resource, like another text document...
std::vector< Reference > References
static std::optional< SpelledWord > touching(SourceLocation SpelledLoc, const syntax::TokenBuffer &TB, const LangOptions &LangOpts)
SymbolID ID
The ID of the symbol.
static TestTU withHeaderCode(llvm::StringRef HeaderCode)
static TestTU withCode(llvm::StringRef Code)
static URIForFile canonicalize(llvm::StringRef AbsPath, llvm::StringRef TUPath)
Canonicalizes AbsPath via URI.