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;
60Matcher<const std::vector<DocumentHighlight> &>
62 std::vector<DocumentHighlight> Expected;
64 Expected.emplace_back();
65 Expected.back().range = R;
66 Expected.back().kind = K;
68 for (
const auto &
Range : Test.ranges())
70 for (
const auto &
Range : Test.ranges(
"read"))
72 for (
const auto &
Range : Test.ranges(
"write"))
74 return UnorderedElementsAreArray(Expected);
78 const char *Tests[] = {
79 R
"cpp(// Local variable
82 $write[[^bonjour]] = 2;
83 int test1 = $read[[bonjour]];
90 static void foo([[MyClass]]*) {}
94 ns1::[[My^Class]]* Params;
99 int [[^foo]](int) { return 0; }
101 [[foo]]([[foo]](42));
106 R"cpp(// Function parameter in decl
107 void foo(int [[^bar]]);
109 R"cpp(// Not touching any identifiers.
118 R"cpp(// ObjC methods with split selectors.
120 +(void) [[x]]:(int)a [[y]]:(int)b;
123 +(void) [[x]]:(int)a [[y]]:(int)b {}
126 [Foo [[x]]:2 [[^y]]:4];
137 for (
const char *Test : Tests) {
140 TU.ExtraArgs.push_back(
"-xobjective-c++");
141 auto AST = TU.build();
147TEST(HighlightsTest, ControlFlow) {
148 const char *Tests[] = {
150 // Highlight same-function returns.
151 int fib(unsigned n) {
152 if (n <= 1) [[ret^urn]] 1;
153 [[return]] fib(n - 1) + fib(n - 2);
155 // Returns from other functions not highlighted.
156 auto Lambda = [] { return; };
157 class LocalClass { void x() { return; } };
162 #define FAIL() return false
165 if (n < 0) [[FAIL]]();
171 // Highlight loop control flow
174 [[^for]] (char c : "fruit loops!") {
175 if (c == ' ') [[continue]];
177 if (c == '!') [[break]];
178 if (c == '?') [[return]] -1;
185 // Highlight loop and same-loop control flow
188 if (false) [[bre^ak]];
196 // Highlight switch for break (but not other breaks).
197 void describe(unsigned n) {
208 // Highlight case and exits for switch-break (but not other cases).
209 void describe(unsigned n) {
222 // Highlight exits and switch for case
223 void describe(unsigned n) {
236 // Highlight nothing for switch.
237 void describe(unsigned n) {
250 // FIXME: match exception type against catch blocks
252 try { // wrong: highlight try with matching catch
253 try { // correct: has no matching catch
255 } catch (int) { } // correct: catch doesn't match type
256 [[return]] -1; // correct: exits the matching catch
257 } catch (const char*) { } // wrong: highlight matching catch
258 [[return]] 42; // wrong: throw doesn't exit function
263 // Loop highlights goto exiting the loop, but not jumping within it.
274 for (
const char *Test : Tests) {
277 TU.ExtraArgs.push_back(
"-fexceptions");
278 auto AST = TU.build();
284MATCHER_P3(
sym, Name, Decl, DefOrNone,
"") {
285 std::optional<Range> Def = DefOrNone;
286 if (Name != arg.Name) {
287 *result_listener <<
"Name is " << arg.Name;
290 if (Decl != arg.PreferredDeclaration.range) {
291 *result_listener <<
"Declaration is "
292 << llvm::to_string(arg.PreferredDeclaration);
295 if (!Def && !arg.Definition)
297 if (Def && !arg.Definition) {
298 *result_listener <<
"Has no definition";
301 if (!Def && arg.Definition) {
302 *result_listener <<
"Definition is " << llvm::to_string(*arg.Definition);
305 if (arg.Definition->range != *Def) {
306 *result_listener <<
"Definition is " << llvm::to_string(*arg.Definition);
314MATCHER_P(rangeIs, R,
"") {
return arg.Loc.range == R; }
315MATCHER_P(fileIs, F,
"") {
return arg.Loc.uri.file() == F; }
317 return arg.Loc.containerName.value_or(
"") ==
C;
319MATCHER_P(attrsAre, A,
"") {
return arg.Attributes ==
A; }
320MATCHER_P(hasID, ID,
"") {
return arg.ID == ID; }
322TEST(LocateSymbol, WithIndex) {
324 class $forward[[Forward]];
325 class $foo[[Foo]] {};
329 inline void $f2[[f2]]() {}
332 class $forward[[forward]] {};
337 TU.Code = std::string(SymbolCpp.code());
338 TU.HeaderCode = std::string(SymbolHeader.code());
339 auto Index = TU.index();
340 auto LocateWithIndex = [&Index](
const Annotations &Main) {
351 EXPECT_THAT(LocateWithIndex(Test),
352 ElementsAre(sym("f1", Test.range(), SymbolCpp.range(
"f1"))));
360 EXPECT_THAT(LocateWithIndex(Test),
361 ElementsAre(sym("f1", SymbolHeader.range(
"f1"), Test.range())));
363 Test =
Annotations(R
"cpp(// forward declaration in AST.
367 EXPECT_THAT(LocateWithIndex(Test),
368 ElementsAre(sym("Foo", Test.range(), SymbolHeader.range(
"foo"))));
371 class [[Forward]] {};
375 LocateWithIndex(Test),
376 ElementsAre(sym("Forward", SymbolHeader.range(
"forward"), Test.range())));
379TEST(LocateSymbol, AnonymousStructFields) {
382 struct { int $1[[x]]; };
384 // Make sure the implicit base is skipped.
388 // Check that we don't skip explicit bases.
392 auto AST = TU.build();
394 UnorderedElementsAre(
sym(
"x", Code.range(
"1"), Code.range(
"1"))));
397 UnorderedElementsAre(
sym(
"Foo", Code.range(
"2"), Code.range(
"2"))));
400TEST(LocateSymbol, FindOverrides) {
403 virtual void $1[[fo^o]]() = 0;
405 class Bar : public Foo {
406 void $2[[foo]]() override;
410 auto AST = TU.build();
412 UnorderedElementsAre(
sym(
"foo", Code.range(
"1"), std::nullopt),
413 sym(
"foo", Code.range(
"2"), std::nullopt)));
416TEST(LocateSymbol, FindOverridesFromDefObjC) {
424 @interface Foo : Base<Fooey>
432 - (void)$3[[fo^o]] {}
436 TU.ExtraArgs.push_back("-xobjective-c++");
437 auto AST = TU.build();
440 UnorderedElementsAre(
sym(
"foo", Code.range(
"1"), std::nullopt),
441 sym(
"foo", Code.range(
"2"), Code.range(
"3"))));
444TEST(LocateSymbol, NoOverridesFromDeclObjC) {
452 @interface Foo : Base<Fooey>
464 TU.ExtraArgs.push_back("-xobjective-c++");
465 auto AST = TU.build();
468 UnorderedElementsAre(
sym(
"foo", Code.range(
"2"), Code.range(
"3"))));
471TEST(LocateSymbol, ObjCNoOverridesOnUsage) {
483 void doSomething(Bar *bar) {
488 TU.ExtraArgs.push_back("-xobjective-c++");
489 auto AST = TU.build();
492 UnorderedElementsAre(
sym(
"foo", Code.range(
"1"), Code.range(
"2"))));
495TEST(LocateSymbol, WithIndexPreferredLocation) {
497 class $p[[Proto]] {};
498 void $f[[func]]() {};
501 TU.HeaderCode = std::string(SymbolHeader.code());
502 TU.HeaderFilename = "x.proto";
503 auto Index = TU.index();
506 // Shift to make range different.
518 auto CodeGenLoc = SymbolHeader.range(
"p");
519 EXPECT_THAT(Locs, ElementsAre(
sym(
"Proto", CodeGenLoc, CodeGenLoc)));
523 auto CodeGenLoc = SymbolHeader.range(
"f");
524 EXPECT_THAT(Locs, ElementsAre(
sym(
"func", CodeGenLoc, CodeGenLoc)));
533 const char *Tests[] = {
546 R"cpp(// Local variable
556 struct [[MyClass]] {};
559 ns1::My^Class* Params;
563 R"cpp(// Function definition via pointer
570 R"cpp(// Function declaration via call
571 int $decl[[foo]](int);
578 struct Foo { int [[x]]; };
585 R"cpp(// Field, member initializer
592 R"cpp(// Field, field designator
593 struct Foo { int [[x]]; };
595 Foo bar = { .^x = 2 };
600 struct Foo { int $decl[[x]](); };
608 typedef int $decl[[Foo]];
614 R"cpp(// Template type parameter
615 template <typename [[T]]>
619 R"cpp(// Template template type parameter
620 template <template<typename> class [[T]]>
621 void foo() { ^T<int> t; }
625 namespace $decl[[ns]] {
626 struct Foo { static void bar(); };
628 int main() { ^ns::Foo::bar(); }
632 class TTT { public: int a; };
633 #define [[FF]](S) if (int b = S.a) {}
640 R"cpp(// Macro argument
642 #define ADDRESSOF(X) &X;
643 int *j = ADDRESSOF(^i);
645 R"cpp(// Macro argument appearing multiple times in expansion
646 #define VALIDATE_TYPE(x) (void)x;
647 #define ASSERT(expr) \
649 VALIDATE_TYPE(expr); \
652 bool [[waldo]]() { return true; }
657 R"cpp(// Symbol concatenated inside macro (not supported)
659 #define POINTER(X) p ## X;
660 int x = *POINTER(^i);
663 R"cpp(// Forward class declaration
665 class $def[[Foo]] {};
669 R"cpp(// Function declaration
672 void $def[[foo]]() {}
676 #define FF(name) class name##_Test {};
678 void f() { my^_Test a; }
682 #define FF() class [[Test]] {};
684 void f() { T^est a; }
687 R"cpp(// explicit template specialization
688 template <typename T>
689 struct Foo { void bar() {} };
692 struct [[Foo]]<int> { void bar() {} };
700 R"cpp(// implicit template specialization
701 template <typename T>
702 struct [[Foo]] { void bar() {} };
704 struct Foo<int> { void bar() {} };
711 R"cpp(// partial template specialization
712 template <typename T>
713 struct Foo { void bar() {} };
714 template <typename T>
715 struct [[Foo]]<T*> { void bar() {} };
719 R"cpp(// function template specializations
729 R"cpp(// variable template decls
734 double [[var]]<int> = 10;
736 double y = va^r<int>;
739 R"cpp(// No implicit constructors
751 X& $decl[[operator]]++();
759 struct S1 { void f(); };
760 struct S2 { S1 * $decl[[operator]]->(); };
766 R"cpp(// Declaration of explicit template specialization
767 template <typename T>
768 struct $decl[[$def[[Foo]]]] {};
774 R"cpp(// Declaration of partial template specialization
775 template <typename T>
776 struct $decl[[$def[[Foo]]]] {};
778 template <typename T>
782 R"cpp(// Definition on ClassTemplateDecl
784 // Forward declaration.
788 template <typename T>
789 struct $def[[Foo]] {};
795 R"cpp(// auto builtin type (not supported)
799 R"cpp(// auto on lambda
804 R"cpp(// auto on struct
812 R"cpp(// decltype on struct
821 R"cpp(// decltype(auto) on struct
828 ^decltype(auto) k = j;
831 R"cpp(// auto on template class
832 template<typename T> class [[Foo]] {};
834 ^auto x = Foo<int>();
837 R"cpp(// auto on template class with forward declared class
838 template<typename T> class [[Foo]] {};
844 R"cpp(// auto on specialized template class
845 template<typename T> class Foo {};
846 template<> class [[Foo]]<int> {};
848 ^auto x = Foo<int>();
851 R"cpp(// auto on initializer list.
855 class [[initializer_list]] { const _E *a, *b; };
861 R"cpp(// auto function return with trailing type
863 ^auto test() -> decltype(Bar()) {
868 R"cpp(// decltype in trailing return type
870 auto test() -> ^decltype(Bar()) {
875 R"cpp(// auto in function return
882 R"cpp(// auto& in function return
890 R"cpp(// auto* in function return
898 R"cpp(// const auto& in function return
900 const ^auto& test() {
906 R"cpp(// auto lambda param where there's a single instantiation
908 auto Lambda = [](^auto){ return 0; };
909 int x = Lambda(Bar{});
912 R"cpp(// decltype(auto) in function return
914 ^decltype(auto) test() {
919 R"cpp(// decltype of function with trailing return type.
921 auto test() -> decltype(Bar()) {
925 ^decltype(test()) i = test();
929 R"cpp(// auto with dependent type
932 template <typename T>
938 R"cpp(// Override specifier jumps to overridden method
939 class Y { virtual void $decl[[a]]() = 0; };
940 class X : Y { void a() ^override {} };
942 R"cpp(// Final specifier jumps to overridden method
943 class Y { virtual void $decl[[a]]() = 0; };
944 class X : Y { void a() ^final {} };
947 R"cpp(// Heuristic resolution of dependent method
948 template <typename T>
953 template <typename T>
959 R"cpp(// Heuristic resolution of dependent method via this->
960 template <typename T>
968 R"cpp(// Heuristic resolution of dependent static method
969 template <typename T>
971 static void [[bar]]() {}
974 template <typename T>
980 R"cpp(// Heuristic resolution of dependent method
981 // invoked via smart pointer
982 template <typename> struct S { void [[foo]]() {} };
983 template <typename T> struct unique_ptr {
986 template <typename T>
987 void test(unique_ptr<S<T>>& V) {
992 R"cpp(// Heuristic resolution of dependent enumerator
993 template <typename T>
995 enum class E { [[A]], B };
1001 typedef int $decl[[MyTypeDef]];
1002 enum Foo : My^TypeDef {};
1005 typedef int $decl[[MyTypeDef]];
1006 enum Foo : My^TypeDef;
1009 using $decl[[MyTypeDef]] = int;
1010 enum Foo : My^TypeDef {};
1015 @protocol $decl[[Dog]]
1018 id<Do^g> getDoggo() {
1028 @interface $decl[[Cat]] (Exte^nsion)
1031 @implementation $def[[Cat]] (Extension)
1037 @class $decl[[Foo]];
1043 R"objc(// Prefer interface definition over forward declaration
1045 @interface $decl[[Foo]]
1054 @interface $decl[[Foo]]
1056 @implementation $def[[Foo]]
1063 R"objc(// Method decl and definition for ObjC class.
1065 - (void)$decl[[meow]];
1068 - (void)$def[[meow]] {}
1070 void makeNoise(Cat *kitty) {
1075 R"objc(// Method decl and definition for ObjC category.
1078 @interface Dog (Play)
1079 - (void)$decl[[runAround]];
1081 @implementation Dog (Play)
1082 - (void)$def[[runAround]] {}
1084 void play(Dog *dog) {
1089 R"objc(// Method decl and definition for ObjC class extension.
1093 - (void)$decl[[howl]];
1096 - (void)$def[[howl]] {}
1098 void play(Dog *dog) {
1103 struct PointerIntPairInfo {
1104 static void *$decl[[getPointer]](void *Value);
1107 template <typename Info = PointerIntPairInfo> struct PointerIntPair {
1109 void *getPointer() const { return Info::get^Pointer(Value); }
1112 R"cpp(// Deducing this
1118 int x = wa^ldo.bar();
1121 for (
const char *Test : Tests) {
1123 std::optional<Range> WantDecl;
1124 std::optional<Range> WantDef;
1125 if (!
T.ranges().empty())
1126 WantDecl = WantDef =
T.range();
1127 if (!
T.ranges(
"decl").empty())
1128 WantDecl =
T.range(
"decl");
1129 if (!
T.ranges(
"def").empty())
1130 WantDef =
T.range(
"def");
1133 TU.
Code = std::string(
T.code());
1135 TU.ExtraArgs.push_back(
"-xobjective-c++");
1136 TU.ExtraArgs.push_back(
"-std=c++23");
1138 auto AST = TU.build();
1142 EXPECT_THAT(Results, IsEmpty()) << Test;
1144 ASSERT_THAT(Results, ::testing::SizeIs(1)) << Test;
1145 EXPECT_EQ(Results[0].PreferredDeclaration.range, *WantDecl) << Test;
1146 EXPECT_TRUE(Results[0].ID) << Test;
1147 std::optional<Range> GotDef;
1149 GotDef = Results[0].Definition->range;
1150 EXPECT_EQ(WantDef, GotDef) << Test;
1154TEST(LocateSymbol, ValidSymbolID) {
1156 #define MACRO(x, y) ((x) + (y))
1157 int add(int x, int y) { return $MACRO^MACRO(x, y); }
1158 int sum = $add^add(1, 2);
1162 auto AST = TU.build();
1163 auto Index = TU.index();
1165 ElementsAre(AllOf(
sym(
"add"),
1169 ElementsAre(AllOf(
sym(
"MACRO"),
1173TEST(LocateSymbol, AllMulti) {
1180 struct ExpectedRanges {
1182 std::optional<Range> WantDef;
1184 const char *Tests[] = {
1186 @interface $decl0[[Cat]]
1188 @implementation $def0[[Cat]]
1190 @interface $decl1[[Ca^t]] (Extension)
1193 @implementation $def1[[Cat]] (Extension)
1199 @interface $decl0[[Cat]]
1201 @implementation $def0[[Cat]]
1203 @interface $decl1[[Cat]] (Extension)
1206 @implementation $def1[[Ca^t]] (Extension)
1212 @interface $decl0[[Cat]]
1214 @interface $decl1[[Ca^t]] ()
1217 @implementation $def0[[$def1[[Cat]]]]
1222 for (
const char *Test : Tests) {
1224 std::vector<ExpectedRanges> Ranges;
1225 for (
int Idx = 0;
true; Idx++) {
1226 bool HasDecl = !
T.ranges(
"decl" + std::to_string(Idx)).empty();
1227 bool HasDef = !
T.ranges(
"def" + std::to_string(Idx)).empty();
1228 if (!HasDecl && !HasDef)
1230 ExpectedRanges
Range;
1232 Range.WantDecl =
T.range(
"decl" + std::to_string(Idx));
1234 Range.WantDef =
T.range(
"def" + std::to_string(Idx));
1235 Ranges.push_back(
Range);
1239 TU.
Code = std::string(
T.code());
1240 TU.ExtraArgs.push_back(
"-xobjective-c++");
1242 auto AST = TU.build();
1245 ASSERT_THAT(Results, ::testing::SizeIs(Ranges.size())) << Test;
1246 for (
size_t Idx = 0; Idx < Ranges.size(); Idx++) {
1247 EXPECT_EQ(Results[Idx].PreferredDeclaration.range, Ranges[Idx].WantDecl)
1248 <<
"($decl" << Idx <<
")" << Test;
1249 std::optional<Range> GotDef;
1251 GotDef = Results[Idx].Definition->range;
1252 EXPECT_EQ(GotDef, Ranges[Idx].WantDef) <<
"($def" << Idx <<
")" << Test;
1260TEST(LocateSymbol, Warnings) {
1261 const char *Tests[] = {
1262 R
"cpp(// Field, GNU old-style field designator
1263 struct Foo { int [[x]]; };
1265 Foo bar = { ^x : 1 };
1272 int main() { return ^MACRO; }
1278 for (
const char *Test : Tests) {
1280 std::optional<Range> WantDecl;
1281 std::optional<Range> WantDef;
1282 if (!
T.ranges().empty())
1283 WantDecl = WantDef =
T.range();
1284 if (!
T.ranges(
"decl").empty())
1285 WantDecl =
T.range(
"decl");
1286 if (!
T.ranges(
"def").empty())
1287 WantDef =
T.range(
"def");
1290 TU.
Code = std::string(
T.code());
1292 auto AST = TU.build();
1296 EXPECT_THAT(Results, IsEmpty()) << Test;
1298 ASSERT_THAT(Results, ::testing::SizeIs(1)) << Test;
1299 EXPECT_EQ(Results[0].PreferredDeclaration.range, *WantDecl) << Test;
1300 std::optional<Range> GotDef;
1302 GotDef = Results[0].Definition->range;
1303 EXPECT_EQ(WantDef, GotDef) << Test;
1308TEST(LocateSymbol, TextualSmoke) {
1311 struct [[MyClass]] {};
1312 // Comment mentioning M^yClass
1316 auto AST = TU.build();
1317 auto Index = TU.index();
1320 ElementsAre(AllOf(
sym(
"MyClass",
T.range(),
T.range()),
1324TEST(LocateSymbol, Textual) {
1325 const char *Tests[] = {
1327 struct [[MyClass]] {};
1328 // Comment mentioning M^yClass
1332 // Not triggered for string literal tokens.
1333 const char* s = "String literal mentioning M^yClass";
1335 R"cpp(// Ifdef'ed out code
1336 struct [[MyClass]] {};
1341 R"cpp(// Macro definition
1342 struct [[MyClass]] {};
1343 #define DECLARE_MYCLASS_OBJ(name) M^yClass name;
1345 R"cpp(// Invalid code
1347 int myFunction(int);
1348 // Not triggered for token which survived preprocessing.
1349 int var = m^yFunction();
1352 for (
const char *Test : Tests) {
1354 std::optional<Range> WantDecl;
1355 if (!
T.ranges().empty())
1356 WantDecl =
T.range();
1360 auto AST = TU.build();
1361 auto Index = TU.index();
1364 AST.getTokens(),
AST.getLangOpts());
1366 ADD_FAILURE() <<
"No word touching point!" << Test;
1370 testPath(TU.Filename), ASTNodeKind());
1373 EXPECT_THAT(Results, IsEmpty()) << Test;
1375 ASSERT_THAT(Results, ::testing::SizeIs(1)) << Test;
1376 EXPECT_EQ(Results[0].PreferredDeclaration.range, *WantDecl) << Test;
1381TEST(LocateSymbol, Ambiguous) {
1386 $ConstructorLoc[[Foo]](const char*);
1394 const char* str = "123";
1396 Foo b = Foo($2^str);
1401 Foo ab$8^cd("asdf");
1402 Foo foox = Fo$9^o("asdf");
1403 Foo abcde$10^("asdf");
1404 Foo foox2 = Foo$11^("asdf");
1407 template <typename T>
1409 void $NonstaticOverload1[[bar]](int);
1410 void $NonstaticOverload2[[bar]](float);
1412 static void $StaticOverload1[[baz]](int);
1413 static void $StaticOverload2[[baz]](float);
1416 template <typename T, typename U>
1417 void dependent_call(S<T> s, U u) {
1425 TU.ExtraArgs.push_back(
"-fno-delayed-template-parsing");
1426 auto AST = TU.build();
1441 ElementsAre(
sym(
"Foo",
T.range(
"ConstructorLoc"), std::nullopt)));
1443 ElementsAre(
sym(
"Foo",
T.range(
"ConstructorLoc"), std::nullopt)));
1448 UnorderedElementsAre(
1449 sym(
"bar",
T.range(
"NonstaticOverload1"), std::nullopt),
1450 sym(
"bar",
T.range(
"NonstaticOverload2"), std::nullopt)));
1452 UnorderedElementsAre(
1453 sym(
"baz",
T.range(
"StaticOverload1"), std::nullopt),
1454 sym(
"baz",
T.range(
"StaticOverload2"), std::nullopt)));
1457TEST(LocateSymbol, TextualDependent) {
1463 void $FooLoc[[uniqueMethodName]]();
1466 void $BarLoc[[uniqueMethodName]]();
1470 template <typename T>
1472 t.u^niqueMethodName();
1476 TU.Code = std::string(Source.code());
1477 TU.HeaderCode = std::string(Header.code());
1478 auto AST = TU.build();
1479 auto Index = TU.index();
1486 UnorderedElementsAre(
1487 sym(
"uniqueMethodName", Header.range(
"FooLoc"), std::nullopt),
1488 sym(
"uniqueMethodName", Header.range(
"BarLoc"), std::nullopt)));
1492 const char *Tests[] = {
1494 template <class T> struct function {};
1495 template <class T> using [[callback]] = function<T()>;
1504 typedef Foo [[Bar]];
1510 using [[Bar]] = Foo; // definition
1523 namespace ns { class [[Foo]] {}; }
1528 namespace ns { int [[x]](char); int [[x]](double); }
1533 namespace ns { int [[x]](char); int x(double); }
1539 namespace ns { class [[Foo]] {}; }
1547 typedef Foo [[Ba^r]];
1551 using [[B^ar]] = Foo;
1556 template <typename T>
1560 template <typename T>
1561 struct Derived : Base<T> {
1562 using Base<T>::w^aldo;
1567 for (
const auto *Case : Tests) {
1572 UnorderedPointwise(declRange(),
T.ranges()));
1576TEST(LocateSymbol, RelPathsInCompileCommand) {
1581#include "header_in_preamble.h"
1583#include "header_not_in_preamble.h"
1584int baz = f$p1^oo + bar_pre$p2^amble + bar_not_pre$p3^amble;
1588int [[bar_preamble]];
1592int [[bar_not_preamble]];
1597 SmallString<32> RelPathPrefix(
"..");
1598 llvm::sys::path::append(RelPathPrefix,
"src");
1599 std::string BuildDir =
testPath(
"build");
1606 auto FooCpp =
testPath(
"src/foo.cpp");
1607 FS.Files[FooCpp] =
"";
1608 auto HeaderInPreambleH =
testPath(
"src/header_in_preamble.h");
1609 FS.Files[HeaderInPreambleH] = std::string(HeaderInPreambleAnnotations.code());
1610 auto HeaderNotInPreambleH =
testPath(
"src/header_not_in_preamble.h");
1611 FS.Files[HeaderNotInPreambleH] =
1612 std::string(HeaderNotInPreambleAnnotations.code());
1619 EXPECT_TRUE(
bool(Locations)) <<
"findDefinitions returned an error";
1620 EXPECT_THAT(*Locations, ElementsAre(
sym(
"foo", SourceAnnotations.range(),
1621 SourceAnnotations.range())));
1625 EXPECT_TRUE(
bool(Locations)) <<
"findDefinitions returned an error";
1628 ElementsAre(
sym(
"bar_preamble", HeaderInPreambleAnnotations.range(),
1629 HeaderInPreambleAnnotations.range())));
1633 EXPECT_TRUE(
bool(Locations)) <<
"findDefinitions returned an error";
1634 EXPECT_THAT(*Locations,
1635 ElementsAre(
sym(
"bar_not_preamble",
1636 HeaderNotInPreambleAnnotations.range(),
1637 HeaderNotInPreambleAnnotations.range())));
1646 const char *SourceContents = R
"cpp(
1647 #include ^"$2^foo.h$3^"
1648 #include "$4^invalid.h"
1652 #in$5^clude "$6^foo.h"$7^
1655 FS.Files[FooCpp] = std::string(SourceAnnotations.code());
1662 FS.Files[FooH] = std::string(HeaderAnnotations.code());
1669 ASSERT_TRUE(
bool(Locations)) <<
"locateSymbolAt returned an error";
1670 EXPECT_THAT(*Locations, ElementsAre(
sym(
"foo.h", HeaderAnnotations.range(),
1671 HeaderAnnotations.range())));
1675 ASSERT_TRUE(
bool(Locations)) <<
"locateSymbolAt returned an error";
1676 EXPECT_THAT(*Locations, ElementsAre(
sym(
"foo.h", HeaderAnnotations.range(),
1677 HeaderAnnotations.range())));
1680 ASSERT_TRUE(
bool(Locations)) <<
"locateSymbolAt returned an error";
1681 EXPECT_THAT(*Locations, ElementsAre(
sym(
"foo.h", HeaderAnnotations.range(),
1682 HeaderAnnotations.range())));
1686 ASSERT_TRUE(
bool(Locations)) <<
"locateSymbolAt returned an error";
1687 EXPECT_THAT(*Locations, ElementsAre(
sym(
"foo.h", HeaderAnnotations.range(),
1688 HeaderAnnotations.range())));
1692 ASSERT_TRUE(
bool(Locations)) <<
"locateSymbolAt returned an error";
1693 EXPECT_THAT(*Locations, IsEmpty());
1696 ASSERT_TRUE(
bool(Locations)) <<
"locateSymbolAt returned an error";
1697 EXPECT_THAT(*Locations, ElementsAre(
sym(
"foo.h", HeaderAnnotations.range(),
1698 HeaderAnnotations.range())));
1701 ASSERT_TRUE(
bool(Locations)) <<
"locateSymbolAt returned an error";
1702 EXPECT_THAT(*Locations, ElementsAre(
sym(
"foo.h", HeaderAnnotations.range(),
1703 HeaderAnnotations.range())));
1710 FS.Files[FooM] = std::string(ObjC.code());
1714 ASSERT_TRUE(
bool(Locations)) <<
"locateSymbolAt returned an error";
1715 EXPECT_THAT(*Locations, ElementsAre(
sym(
"foo.h", HeaderAnnotations.range(),
1716 HeaderAnnotations.range())));
1719TEST(LocateSymbol, WithPreamble) {
1728 Annotations FooWithHeader(R
"cpp(#include "fo^o.h")cpp");
1729 Annotations FooWithoutHeader(R"cpp(double [[fo^o]]();)cpp");
1731 FS.Files[FooCpp] = std::string(FooWithHeader.code());
1735 FS.Files[FooH] = std::string(FooHeader.code());
1741 ElementsAre(
sym(
"foo.h", FooHeader.range(), FooHeader.range())));
1744 Server.addDocument(FooCpp, FooWithoutHeader.code(),
"null",
1750 ElementsAre(
sym(
"foo", FooWithoutHeader.range(), std::nullopt)));
1755 Server.addDocument(FooCpp, FooWithoutHeader.code(),
"null",
1760 ElementsAre(
sym(
"foo", FooWithoutHeader.range(), std::nullopt)));
1763TEST(LocateSymbol, NearbyTokenSmoke) {
1765 // prints e^rr and crashes
1766 void die(const char* [[err]]);
1771 ElementsAre(
sym(
"err",
T.range(),
T.range())));
1774TEST(LocateSymbol, NearbyIdentifier) {
1775 const char *Tests[] = {
1777 // regular identifiers (won't trigger)
1782 // disabled preprocessor sections
1794 // not triggered by string literals
1796 const char* greeting = "h^ello, world";
1800 // can refer to macro invocations
1807 // can refer to macro invocations (even if they expand to nothing)
1814 // prefer nearest occurrence, backwards is worse than forwards
1823 // short identifiers find near results
1828 // short identifiers don't find far results
1841 // prefer nearest occurrence even if several matched tokens
1842 // have the same value of `floor(log2(<token line> - <word line>))`.
1844 int x = hello, y = hello;
1848 for (
const char *Test : Tests) {
1851 const auto &SM =
AST.getSourceManager();
1852 std::optional<Range> Nearby;
1855 AST.getTokens(),
AST.getLangOpts());
1857 ADD_FAILURE() <<
"No word at point! " << Test;
1862 Tok->location(), Tok->endLocation()));
1863 if (
T.ranges().empty())
1864 EXPECT_THAT(Nearby, Eq(std::nullopt)) << Test;
1866 EXPECT_EQ(Nearby,
T.range()) << Test;
1870TEST(FindImplementations, Inheritance) {
1871 llvm::StringRef Test = R
"cpp(
1873 virtual void F$1^oo();
1876 struct $0[[Child1]] : Base {
1877 void $1[[Fo$3^o]]() override;
1878 virtual void B$2^ar();
1879 void Concrete(); // No implementations for concrete methods.
1881 struct Child2 : Child1 {
1882 void $3[[Foo]]() override;
1883 void $2[[Bar]]() override;
1885 void FromReference() {
1894 // CRTP should work.
1895 template<typename T>
1896 struct $5^TemplateBase {};
1897 struct $5[[Child3]] : public TemplateBase<Child3> {};
1900 void LocationFunction() {
1901 struct $0[[LocalClass1]] : Base {
1902 void $1[[Foo]]() override;
1904 struct $6^LocalBase {
1905 virtual void $7^Bar();
1907 struct $6[[LocalClass2]]: LocalBase {
1908 void $7[[Bar]]() override;
1915 auto AST = TU.build();
1916 auto Index = TU.index();
1917 for (StringRef
Label : {
"0",
"1",
"2",
"3",
"4",
"5",
"6",
"7"}) {
1918 for (
const auto &Point : Code.points(
Label)) {
1920 UnorderedPointwise(declRange(), Code.ranges(
Label)))
1921 << Code.code() <<
" at " << Point <<
" for Label " <<
Label;
1926TEST(FindImplementations, InheritanceObjC) {
1927 llvm::StringRef Test = R
"objc(
1928 @interface $base^Base
1932 - (void)$protocol^protocol;
1934 @interface $ChildDecl[[Child]] : Base <Protocol>
1936 - (void)$fooDecl[[foo]];
1938 @implementation $ChildDef[[Child]]
1940 - (void)$fooDef[[foo]] {}
1941 - (void)$protocolDef[[protocol]] {}
1947 TU.ExtraArgs.push_back(
"-xobjective-c++");
1948 auto AST = TU.build();
1949 auto Index = TU.index();
1951 UnorderedElementsAre(
sym(
"Child", Code.range(
"ChildDecl"),
1952 Code.range(
"ChildDef"))));
1954 UnorderedElementsAre(
1955 sym(
"foo", Code.range(
"fooDecl"), Code.range(
"fooDef"))));
1957 UnorderedElementsAre(
sym(
"protocol", Code.range(
"protocolDef"),
1958 Code.range(
"protocolDef"))));
1961TEST(FindImplementations, CaptureDefinition) {
1962 llvm::StringRef Test = R
"cpp(
1964 virtual void F^oo();
1966 struct Child1 : Base {
1967 void $Decl[[Foo]]() override;
1969 struct Child2 : Base {
1970 void $Child2[[Foo]]() override;
1972 void Child1::$Def[[Foo]]() { /* Definition */ }
1976 auto AST = TU.build();
1979 UnorderedElementsAre(
sym(
"Foo", Code.range(
"Decl"), Code.range(
"Def")),
1980 sym(
"Foo", Code.range(
"Child2"), std::nullopt)))
1986 struct $Target[[Target]] { operator int() const; };
1987 struct Aggregate { Target a, b; };
1991 template <typename T> struct $smart_ptr[[smart_ptr]] {
1998 for (
const llvm::StringRef Case : {
2002 "a^uto x = Target{};",
2003 "namespace m { Target tgt; } auto x = m^::tgt;",
2004 "Target funcCall(); auto x = ^funcCall();",
2005 "Aggregate a = { {}, ^{} };",
2006 "Aggregate a = { ^.a=t, };",
2007 "struct X { Target a; X() : ^a() {} };",
2008 "^using T = Target; ^T foo();",
2009 "^template <int> Target foo();",
2010 "void x() { try {} ^catch(Target e) {} }",
2011 "void x() { ^throw t; }",
2012 "int x() { ^return t; }",
2013 "void x() { ^switch(t) {} }",
2014 "void x() { ^delete (Target*)nullptr; }",
2015 "Target& ^tref = t;",
2016 "void x() { ^if (t) {} }",
2017 "void x() { ^while (t) {} }",
2018 "void x() { ^do { } while (t); }",
2019 "void x() { ^make(); }",
2020 "void x(smart_ptr<Target> &t) { t.^get(); }",
2021 "^auto x = []() { return t; };",
2022 "Target* ^tptr = &t;",
2023 "Target ^tarray[3];",
2026 TU.Code =
A.code().str();
2029 ASSERT_GT(
A.points().size(), 0u) << Case;
2030 for (
auto Pos :
A.points())
2033 sym(
"Target", HeaderA.range(
"Target"), HeaderA.range(
"Target"))))
2037 for (
const llvm::StringRef Case : {
2038 "smart_ptr<Target> ^tsmart;",
2041 TU.Code =
A.code().str();
2045 UnorderedElementsAre(
2046 sym(
"Target", HeaderA.range(
"Target"), HeaderA.range(
"Target")),
2047 sym(
"smart_ptr", HeaderA.range(
"smart_ptr"), HeaderA.range(
"smart_ptr"))
2063 ElementsAre(
sym(
"X",
A.range(
"decl"),
A.range(
"def"))));
2066TEST(FindType, Index) {
2068 // This definition is only available through the index.
2072 DefTU.HeaderFilename = "def.h";
2073 auto DefIdx = DefTU.index();
2083 ElementsAre(
sym(
"X",
A.range(), Def.range())));
2086void checkFindRefs(llvm::StringRef Test,
bool UseIndex =
false) {
2089 TU.ExtraArgs.push_back(
"-std=c++20");
2090 TU.ExtraArgs.push_back(
"-xobjective-c++");
2092 auto AST = TU.build();
2093 std::vector<Matcher<ReferencesResult::Reference>> ExpectedLocations;
2094 for (
const auto &[R,
Context] :
T.rangesWithPayload())
2095 ExpectedLocations.push_back(
2096 AllOf(rangeIs(R), containerIs(
Context), attrsAre(0u)));
2099 for (
const auto &[R,
Context] :
T.rangesWithPayload(
"def"))
2100 ExpectedLocations.push_back(AllOf(rangeIs(R), containerIs(
Context),
2103 for (
const auto &[R,
Context] :
T.rangesWithPayload(
"decl"))
2104 ExpectedLocations.push_back(AllOf(rangeIs(R), containerIs(
Context),
2106 for (
const auto &[R,
Context] :
T.rangesWithPayload(
"overridedecl"))
2107 ExpectedLocations.push_back(AllOf(
2108 rangeIs(R), containerIs(
Context),
2110 for (
const auto &[R,
Context] :
T.rangesWithPayload(
"overridedef"))
2111 ExpectedLocations.push_back(AllOf(rangeIs(R), containerIs(
Context),
2115 for (
const auto &P :
T.points()) {
2119 UnorderedElementsAreArray(ExpectedLocations))
2120 <<
"Failed for Refs at " <<
P <<
"\n"
2125TEST(FindReferences, WithinAST) {
2126 const char *Tests[] = {
2127 R
"cpp(// Local variable
2129 int $def(main)[[foo]];
2130 $(main)[[^foo]] = 2;
2131 int test1 = $(main)[[foo]];
2137 struct $def(ns1)[[Foo]] {};
2140 ns1::$(main)[[Fo^o]]* Params;
2144 R"cpp(// Forward declaration
2146 class $def[[Foo]] {};
2148 $(main)[[Fo^o]] foo;
2153 int $def[[foo]](int) { return 0; }
2155 auto *X = &$(main)[[^foo]];
2162 int $def(Foo)[[foo]];
2163 Foo() : $(Foo::Foo)[[foo]](0) {}
2167 f.$(main)[[f^oo]] = 1;
2171 R"cpp(// Method call
2172 struct Foo { int $decl(Foo)[[foo]](); };
2173 int Foo::$def(Foo)[[foo]]() { return 0; }
2176 f.$(main)[[^foo]]();
2180 R"cpp(// Constructor
2182 $decl(Foo)[[F^oo]](int);
2185 Foo f = $(foo)[[Foo]](42);
2190 typedef int $def[[Foo]];
2192 $(main)[[^Foo]] bar;
2197 namespace $decl[[ns]] { // FIXME: def?
2200 int main() { $(main)[[^ns]]::Foo foo; }
2206 #define CAT(X, Y) X##Y
2207 class $def[[Fo^o]] {};
2209 TYPE($(test)[[Foo]]) foo;
2210 $(test)[[FOO]] foo2;
2211 TYPE(TYPE($(test)[[Foo]])) foo3;
2212 $(test)[[CAT]](Fo, o) foo4;
2217 #define $def[[MA^CRO]](X) (X+1)
2219 int x = $[[MACRO]]($[[MACRO]](1));
2223 R"cpp(// Macro outside preamble
2225 #define $def[[MA^CRO]](X) (X+1)
2227 int x = $[[MACRO]]($[[MACRO]](1));
2232 int $def[[v^ar]] = 0;
2233 void foo(int s = $(foo)[[var]]);
2237 template <typename T>
2238 class $def[[Fo^o]] {};
2239 void func($(func)[[Foo]]<int>);
2243 template <typename T>
2244 class $def[[Foo]] {};
2245 void func($(func)[[Fo^o]]<int>);
2247 R"cpp(// Not touching any identifiers.
2249 $def(Foo)[[~]]Foo() {};
2253 f.$(foo)[[^~]]Foo();
2256 R"cpp(// Lambda capture initializer
2258 int $def(foo)[[w^aldo]] = 42;
2259 auto lambda = [x = $(foo)[[waldo]]](){};
2262 R"cpp(// Renaming alias
2263 template <typename> class Vector {};
2264 using $def[[^X]] = Vector<int>;
2269 R"cpp(// Dependent code
2270 template <typename T> void $decl[[foo]](T t);
2271 template <typename T> void bar(T t) { $(bar)[[foo]](t); } // foo in bar is uninstantiated.
2272 void baz(int x) { $(baz)[[f^oo]](x); }
2277 void $decl(ns)[[foo]](S s);
2279 template <typename T> void foo(T t);
2280 // FIXME: Maybe report this foo as a ref to ns::foo (because of ADL)
2281 // when bar<ns::S> is instantiated?
2282 template <typename T> void bar(T t) { foo(t); }
2289 R"cpp(// unresolved member expression
2291 template <typename T> void $decl(Foo)[[b^ar]](T t);
2293 template <typename T> void test(Foo F, T t) {
2294 F.$(test)[[bar]](t);
2300 typedef int $def[[MyTypeD^ef]];
2301 enum MyEnum : $(MyEnum)[[MyTy^peDef]] { };
2304 typedef int $def[[MyType^Def]];
2305 enum MyEnum : $(MyEnum)[[MyTypeD^ef]];
2308 using $def[[MyTypeD^ef]] = int;
2309 enum MyEnum : $(MyEnum)[[MyTy^peDef]] { };
2313 bool $decl[[operator]]"" _u^dl(unsigned long long value);
2314 bool x = $(x)[[1_udl]];
2319 static void $decl(S)[[operator]] delete(void *);
2320 static void deleteObject(S *S) {
2321 $(S::deleteObject)[[de^lete]] S;
2327 const int $def[[F^oo]] = 0;
2329 [$(Bar)[[F^oo]]...$(Bar)[[Fo^o]] + 1] = 0,
2330 [$(Bar)[[^Foo]] + 2] = 1
2333 for (
const char *Test : Tests)
2334 checkFindRefs(Test);
2337TEST(FindReferences, ConceptsWithinAST) {
2338 constexpr llvm::StringLiteral Code = R
"cpp(
2340 concept $def[[IsSmal^l]] = sizeof(T) <= 8;
2343 concept IsSmallPtr = requires(T x) {
2344 { *x } -> $(IsSmallPtr)[[IsSmal^l]];
2347 $(i)[[IsSmall]] auto i = 'c';
2348 template<$(foo)[[IsSmal^l]] U> void foo();
2349 template<class U> void bar() requires $(bar)[[IsSmal^l]]<U>;
2350 template<class U> requires $(baz)[[IsSmal^l]]<U> void baz();
2351 static_assert([[IsSma^ll]]<char>);
2353 checkFindRefs(Code);
2356TEST(FindReferences, ConceptReq) {
2357 constexpr llvm::StringLiteral Code = R
"cpp(
2359 concept $def[[IsSmal^l]] = sizeof(T) <= 8;
2362 concept IsSmallPtr = requires(T x) {
2363 { *x } -> $(IsSmallPtr)[[IsSmal^l]];
2366 checkFindRefs(Code);
2369TEST(FindReferences, RequiresExprParameters) {
2370 constexpr llvm::StringLiteral Code = R
"cpp(
2372 concept IsSmall = sizeof(T) <= 8;
2375 concept IsSmallPtr = requires(T $def[[^x]]) {
2376 { *$(IsSmallPtr)[[^x]] } -> IsSmall;
2379 checkFindRefs(Code);
2382TEST(FindReferences, IncludeOverrides) {
2383 llvm::StringRef Test =
2387 virtu^al void $decl(Base)[[f^unc]]() ^= ^0;
2389 class Derived : public Base {
2391 void $overridedecl(Derived::func)[[func]]() override;
2393 void Derived::$overridedef[[func]]() {}
2394 class Derived2 : public Base {
2395 void $overridedef(Derived2::func)[[func]]() override {}
2397 void test(Derived* D, Base* B) {
2398 D->func(); // No references to the overrides.
2399 B->$(test)[[func]]();
2401 checkFindRefs(Test, true);
2404TEST(FindReferences, IncludeOverridesObjC) {
2405 llvm::StringRef Test =
2408 - (void)$decl(Base)[[f^unc]];
2410 @interface Derived : Base
2411 - (void)$overridedecl(Derived::func)[[func]];
2413 @implementation Derived
2414 - (void)$overridedef[[func]] {}
2416 void test(Derived *derived, Base *base) {
2417 [derived func]; // No references to the overrides.
2418 [base $(test)[[func]]];
2420 checkFindRefs(Test, true);
2423TEST(FindReferences, RefsToBaseMethod) {
2424 llvm::StringRef Test =
2428 virtual void $(BaseBase)[[func]]();
2430 class Base : public BaseBase {
2432 void $(Base)[[func]]() override;
2434 class Derived : public Base {
2436 void $decl(Derived)[[fu^nc]]() over^ride;
2438 void test(BaseBase* BB, Base* B, Derived* D) {
2439 // refs to overridden methods in complete type hierarchy are reported.
2440 BB->$(test)[[func]]();
2441 B->$(test)[[func]]();
2442 D->$(test)[[fu^nc]]();
2444 checkFindRefs(Test, true);
2447TEST(FindReferences, RefsToBaseMethodObjC) {
2448 llvm::StringRef Test =
2451 - (void)$(BaseBase)[[func]];
2453 @interface Base : BaseBase
2454 - (void)$(Base)[[func]];
2456 @interface Derived : Base
2457 - (void)$decl(Derived)[[fu^nc]];
2459 void test(BaseBase *bb, Base *b, Derived *d) {
2460 // refs to overridden methods in complete type hierarchy are reported.
2461 [bb $(test)[[func]]];
2462 [b $(test)[[func]]];
2463 [d $(test)[[fu^nc]]];
2465 checkFindRefs(Test, true);
2468TEST(FindReferences, MainFileReferencesOnly) {
2469 llvm::StringRef Test =
2473 // refs not from main file should not be included.
2479 TU.AdditionalFiles[
"foo.inc"] = R
"cpp(
2482 auto AST = TU.build();
2484 std::vector<Matcher<ReferencesResult::Reference>> ExpectedLocations;
2485 for (
const auto &R : Code.ranges())
2486 ExpectedLocations.push_back(rangeIs(R));
2488 ElementsAreArray(ExpectedLocations))
2492TEST(FindReferences, ExplicitSymbols) {
2493 const char *Tests[] = {
2495 struct Foo { Foo* $decl(Foo)[[self]]() const; };
2498 if (Foo* T = foo.$(f)[[^self]]()) {} // Foo member call expr.
2503 struct Foo { Foo(int); };
2506 return $(f)[[^b]]; // Foo constructor expr.
2515 g($(call)[[^f]]()); // Foo constructor expr.
2520 void $decl[[foo]](int);
2521 void $decl[[foo]](double);
2524 using ::$decl(ns)[[fo^o]];
2535 $(test)[[a]].operator bool();
2536 if ($(test)[[a^]]) {} // ignore implicit conversion-operator AST node
2541 for (
const char *Test : Tests)
2542 checkFindRefs(Test);
2545TEST(FindReferences, UsedSymbolsFromInclude) {
2546 const char *Tests[] = {
2547 R
"cpp( [[#include ^"bar.h"]]
2549 int fstBar = [[bar1]]();
2550 int sndBar = [[bar2]]();
2552 int macroBar = [[BAR]];
2553 std::vector<int> vec;
2556 R"cpp([[#in^clude <vector>]]
2557 std::[[vector]]<int> vec;
2561 [[#include ^"udl_header.h"]]
2565 for (
const char *Test : Tests) {
2568 TU.ExtraArgs.push_back(
"-std=c++20");
2569 TU.AdditionalFiles[
"bar.h"] = guard(R
"cpp(
2575 TU.AdditionalFiles["system/vector"] = guard(R
"cpp(
2581 TU.AdditionalFiles["udl_header.h"] = guard(R
"cpp(
2582 bool operator"" _b(unsigned long long value);
2584 TU.ExtraArgs.push_back("-isystem" +
testPath(
"system"));
2586 auto AST = TU.build();
2587 std::vector<Matcher<ReferencesResult::Reference>> ExpectedLocations;
2588 for (
const auto &R :
T.ranges())
2589 ExpectedLocations.push_back(AllOf(rangeIs(R), attrsAre(0u)));
2590 for (
const auto &P :
T.points())
2592 UnorderedElementsAreArray(ExpectedLocations))
2593 <<
"Failed for Refs at " <<
P <<
"\n"
2598TEST(FindReferences, NeedsIndexForSymbols) {
2599 const char *Header =
"int foo();";
2602 TU.
Code = std::string(Main.code());
2603 TU.HeaderCode = Header;
2604 auto AST = TU.build();
2609 ElementsAre(rangeIs(Main.range())));
2611 int $decl[[foo]]() { return 42; }
2612 void bar() { $bar(bar)[[foo]](); }
2613 struct S { void bar() { $S(S::bar)[[foo]](); } };
2614 namespace N { void bar() { $N(N::bar)[[foo]](); } }
2619 IndexedTU.
Code = std::string(IndexedMain.code());
2620 IndexedTU.Filename =
"Indexed.cpp";
2621 IndexedTU.HeaderCode = Header;
2627 rangeIs(Main.range()),
2628 AllOf(rangeIs(IndexedMain.range(
"decl")),
2631 AllOf(rangeIs(IndexedMain.range(
"bar")), containerIs(
"bar")),
2632 AllOf(rangeIs(IndexedMain.range(
"S")), containerIs(
"S::bar")),
2633 AllOf(rangeIs(IndexedMain.range(
"N")), containerIs(
"N::bar"))));
2636 EXPECT_EQ(1u, LimitRefs.References.size());
2637 EXPECT_TRUE(LimitRefs.HasMore);
2640 TU.Code = (
"\n\n" + Main.code()).str();
2642 ElementsAre(rangeIs(Main.range())));
2645TEST(FindReferences, NeedsIndexForMacro) {
2646 const char *Header =
"#define MACRO(X) (X+1)";
2649 int a = [[MA^CRO]](1);
2653 TU.Code = std::string(Main.code());
2654 TU.HeaderCode = Header;
2655 auto AST = TU.build();
2660 ElementsAre(rangeIs(Main.range())));
2663 int indexed_main() {
2664 int a = [[MACRO]](1);
2671 IndexedTU.
Code = std::string(IndexedMain.code());
2672 IndexedTU.Filename =
"Indexed.cpp";
2673 IndexedTU.HeaderCode = Header;
2676 ElementsAre(rangeIs(Main.range()), rangeIs(IndexedMain.range())));
2679 EXPECT_EQ(1u, LimitRefs.References.size());
2680 EXPECT_TRUE(LimitRefs.HasMore);
2683TEST(FindReferences, NoQueryForLocalSymbols) {
2684 struct RecordingIndex :
public MemIndex {
2685 mutable std::optional<llvm::DenseSet<SymbolID>> RefIDs;
2686 bool refs(
const RefsRequest &Req,
2687 llvm::function_ref<
void(
const Ref &)>)
const override {
2694 StringRef AnnotatedCode;
2699 {
"namespace { int ^x; }",
true},
2700 {
"static int ^x;",
true},
2702 {
"void foo() { int ^x; }",
false},
2703 {
"void foo() { struct ^x{}; }",
false},
2704 {
"auto lambda = []{ int ^x; };",
false},
2706 for (Test T : Tests) {
2712 EXPECT_NE(Rec.RefIDs, std::nullopt) <<
T.AnnotatedCode;
2714 EXPECT_EQ(Rec.RefIDs, std::nullopt) <<
T.AnnotatedCode;
2718TEST(FindReferences, ConstructorForwardingInAST) {
2721 template <class T> T &&forward(T &t);
2722 template <class T, class... Args> T *make_unique(Args &&...args) {
2723 return new T(std::forward<Args>(args)...);
2728 $Constructor[[T^est]](){}
2732 auto a = std::$Caller[[make_unique]]<Test>();
2736 TU.Code = std::string(Main.code());
2737 auto AST = TU.build();
2740 ElementsAre(rangeIs(Main.range(
"Constructor")),
2741 rangeIs(Main.range(
"Caller"))));
2744TEST(FindReferences, ConstructorForwardingInASTChained) {
2747 template <class T> T &&forward(T &t);
2748 template <class T, class... Args> T *make_unique(Args &&...args) {
2749 return new T(forward<Args>(args)...);
2751 template <class T, class... Args> T *make_unique2(Args &&...args) {
2752 return make_unique<T>(forward<Args>(args)...);
2754 template <class T, class... Args> T *make_unique3(Args &&...args) {
2755 return make_unique2<T>(forward<Args>(args)...);
2760 $Constructor[[T^est]](){}
2764 auto a = std::$Caller[[make_unique3]]<Test>();
2768 TU.Code = std::string(Main.code());
2769 auto AST = TU.build();
2772 ElementsAre(rangeIs(Main.range(
"Constructor")),
2773 rangeIs(Main.range(
"Caller"))));
2776TEST(FindReferences, ConstructorForwardingInIndex) {
2779 template <class T> T &&forward(T &t);
2780 template <class T, class... Args> T *make_unique(Args &&...args) {
2781 return new T(std::forward<Args>(args)...);
2789 #include "header.hpp"
2791 auto a = std::[[make_unique]]<Test>();
2795 TW.addSource("header.hpp", Header.code());
2796 TW.addMainFile(
"main.cpp", Main.code());
2797 auto AST = TW.openFile(
"header.hpp").value();
2798 auto Index = TW.index();
2805 AllOf(rangeIs(Header.range()), fileIs(
testPath(
"header.hpp"))),
2806 AllOf(rangeIs(Main.range()), fileIs(
testPath(
"main.cpp")))));
2809TEST(FindReferences, TemplatedConstructorForwarding) {
2812 template <class T> T &&forward(T &t);
2813 template <class T, class... Args> T *make_unique(Args &&...args) {
2814 return new T(std::forward<Args>(args)...);
2819 template <typename T>
2820 $Constructor[[W$Waldo^aldo]](T);
2822 template <typename T>
2824 $Constructor2[[W$Waldo2^aldo2]](int);
2830 Waldo $Caller[[w]](s);
2831 std::$ForwardedCaller[[make_unique]]<Waldo>(s);
2833 Waldo2<int> $Caller2[[w2]](42);
2834 std::$ForwardedCaller2[[make_unique]]<Waldo2<int>>(42);
2838 TU.Code = std::string(Main.code());
2839 auto AST = TU.build();
2842 ElementsAre(rangeIs(Main.range(
"Constructor")),
2843 rangeIs(Main.range(
"Caller")),
2844 rangeIs(Main.range(
"ForwardedCaller"))));
2847 ElementsAre(rangeIs(Main.range(
"Constructor2")),
2848 rangeIs(Main.range(
"Caller2")),
2849 rangeIs(Main.range(
"ForwardedCaller2"))));
2852TEST(GetNonLocalDeclRefs,
All) {
2854 llvm::StringRef AnnotatedCode;
2855 std::vector<std::string> ExpectedDecls;
2861 void ^foo(int baz) {
2870 class Foo { public: void foo(); };
2880 {"Bar",
"Bar::bar",
"Foo",
"Foo::foo"},
2886 class Foo { public: void foo() {} };
2887 class Bar { public: void bar() {} };
2898 template <typename T, template<typename> class Q>
2906 for (
const Case &C : Cases) {
2909 SourceLocation SL = llvm::cantFail(
2912 const FunctionDecl *FD =
2913 llvm::dyn_cast<FunctionDecl>(&
findDecl(
AST, [SL](
const NamedDecl &ND) {
2914 return ND.getLocation() == SL && llvm::isa<FunctionDecl>(ND);
2916 ASSERT_NE(FD,
nullptr);
2919 std::vector<std::string> Names;
2920 for (
const Decl *D : NonLocalDeclRefs) {
2921 if (
const auto *ND = llvm::dyn_cast<NamedDecl>(D))
2922 Names.push_back(ND->getQualifiedNameAsString());
2924 EXPECT_THAT(Names, UnorderedElementsAreArray(
C.ExpectedDecls))
2931 #define HEADER_AA "faa.h"
2932 #define HEADER_BB "fbb.h"
2933 #define GET_HEADER(X) HEADER_ ## X
2935 #/*comments*/include /*comments*/ $foo[["foo.h"]] //more comments
2936 int end_of_preamble = 0;
2937 #include $bar[[<bar.h>]]
2938 #include $AA[[GET_HEADER]](AA) // Some comment !
2939 # /* What about */ \
2940 include /* multiple line */ \
2941 $BB[[GET_HEADER]]( /* statements ? */ \
2946 TU.Code = std::string(MainCpp.code());
2947 TU.AdditionalFiles = {
2948 {"faa.h",
""}, {
"fbb.h",
""}, {
"foo.h",
""}, {
"bar.h",
""}};
2949 TU.ExtraArgs = {
"-isystem."};
2950 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.