1 //===-- CodeCompleteTests.cpp -----------------------------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "Annotations.h"
10 #include "ClangdServer.h"
11 #include "CodeComplete.h"
12 #include "Compiler.h"
13 #include "Matchers.h"
14 #include "Protocol.h"
15 #include "Quality.h"
16 #include "SourceCode.h"
17 #include "SyncAPI.h"
18 #include "TestFS.h"
19 #include "TestIndex.h"
20 #include "TestTU.h"
21 #include "Threading.h"
22 #include "index/Index.h"
23 #include "index/MemIndex.h"
24 #include "clang/Sema/CodeCompleteConsumer.h"
25 #include "clang/Tooling/CompilationDatabase.h"
26 #include "llvm/Support/Error.h"
27 #include "llvm/Support/Path.h"
28 #include "llvm/Testing/Support/Error.h"
29 #include "gmock/gmock.h"
30 #include "gtest/gtest.h"
31 #include <condition_variable>
32 #include <mutex>
33 
34 namespace clang {
35 namespace clangd {
36 
37 namespace {
38 using ::llvm::Failed;
39 using ::testing::AllOf;
40 using ::testing::Contains;
41 using ::testing::ElementsAre;
42 using ::testing::Field;
43 using ::testing::HasSubstr;
44 using ::testing::IsEmpty;
45 using ::testing::Not;
46 using ::testing::UnorderedElementsAre;
47 
48 // GMock helpers for matching completion items.
49 MATCHER_P(Named, Name, "") { return arg.Name == Name; }
50 MATCHER_P(NameStartsWith, Prefix, "") {
51   return llvm::StringRef(arg.Name).startswith(Prefix);
52 }
53 MATCHER_P(Scope, S, "") { return arg.Scope == S; }
54 MATCHER_P(Qualifier, Q, "") { return arg.RequiredQualifier == Q; }
55 MATCHER_P(Labeled, Label, "") {
56   return arg.RequiredQualifier + arg.Name + arg.Signature == Label;
57 }
58 MATCHER_P(SigHelpLabeled, Label, "") { return arg.label == Label; }
59 MATCHER_P(Kind, K, "") { return arg.Kind == K; }
60 MATCHER_P(Doc, D, "") { return arg.Documentation == D; }
61 MATCHER_P(ReturnType, D, "") { return arg.ReturnType == D; }
62 MATCHER_P(HasInclude, IncludeHeader, "") {
63   return !arg.Includes.empty() && arg.Includes[0].Header == IncludeHeader;
64 }
65 MATCHER_P(InsertInclude, IncludeHeader, "") {
66   return !arg.Includes.empty() && arg.Includes[0].Header == IncludeHeader &&
67          bool(arg.Includes[0].Insertion);
68 }
69 MATCHER(InsertInclude, "") {
70   return !arg.Includes.empty() && bool(arg.Includes[0].Insertion);
71 }
72 MATCHER_P(SnippetSuffix, Text, "") { return arg.SnippetSuffix == Text; }
73 MATCHER_P(Origin, OriginSet, "") { return arg.Origin == OriginSet; }
74 MATCHER_P(Signature, S, "") { return arg.Signature == S; }
75 
76 // Shorthand for Contains(Named(Name)).
77 Matcher<const std::vector<CodeCompletion> &> Has(std::string Name) {
78   return Contains(Named(std::move(Name)));
79 }
80 Matcher<const std::vector<CodeCompletion> &> Has(std::string Name,
81                                                  CompletionItemKind K) {
82   return Contains(AllOf(Named(std::move(Name)), Kind(K)));
83 }
84 MATCHER(IsDocumented, "") { return !arg.Documentation.empty(); }
85 MATCHER(Deprecated, "") { return arg.Deprecated; }
86 
87 std::unique_ptr<SymbolIndex> memIndex(std::vector<Symbol> Symbols) {
88   SymbolSlab::Builder Slab;
89   for (const auto &Sym : Symbols)
90     Slab.insert(Sym);
91   return MemIndex::build(std::move(Slab).build(), RefSlab(), RelationSlab());
92 }
93 
94 CodeCompleteResult completions(ClangdServer &Server, llvm::StringRef TestCode,
95                                Position Point,
96                                std::vector<Symbol> IndexSymbols = {},
97                                clangd::CodeCompleteOptions Opts = {}) {
98   std::unique_ptr<SymbolIndex> OverrideIndex;
99   if (!IndexSymbols.empty()) {
100     assert(!Opts.Index && "both Index and IndexSymbols given!");
101     OverrideIndex = memIndex(std::move(IndexSymbols));
102     Opts.Index = OverrideIndex.get();
103   }
104 
105   auto File = testPath("foo.cpp");
106   runAddDocument(Server, File, TestCode);
107   auto CompletionList =
108       llvm::cantFail(runCodeComplete(Server, File, Point, Opts));
109   return CompletionList;
110 }
111 
112 CodeCompleteResult completions(ClangdServer &Server, llvm::StringRef Text,
113                                std::vector<Symbol> IndexSymbols = {},
114                                clangd::CodeCompleteOptions Opts = {},
115                                PathRef FilePath = "foo.cpp") {
116   std::unique_ptr<SymbolIndex> OverrideIndex;
117   if (!IndexSymbols.empty()) {
118     assert(!Opts.Index && "both Index and IndexSymbols given!");
119     OverrideIndex = memIndex(std::move(IndexSymbols));
120     Opts.Index = OverrideIndex.get();
121   }
122 
123   auto File = testPath(FilePath);
124   Annotations Test(Text);
125   runAddDocument(Server, File, Test.code());
126   auto CompletionList =
127       llvm::cantFail(runCodeComplete(Server, File, Test.point(), Opts));
128   return CompletionList;
129 }
130 
131 // Builds a server and runs code completion.
132 // If IndexSymbols is non-empty, an index will be built and passed to opts.
133 CodeCompleteResult completions(llvm::StringRef Text,
134                                std::vector<Symbol> IndexSymbols = {},
135                                clangd::CodeCompleteOptions Opts = {},
136                                PathRef FilePath = "foo.cpp") {
137   MockFSProvider FS;
138   MockCompilationDatabase CDB;
139   // To make sure our tests for completiopns inside templates work on Windows.
140   CDB.ExtraClangFlags = {"-fno-delayed-template-parsing"};
141   ClangdServer Server(CDB, FS, ClangdServer::optsForTest());
142   return completions(Server, Text, std::move(IndexSymbols), std::move(Opts),
143                      FilePath);
144 }
145 
146 // Builds a server and runs code completion.
147 // If IndexSymbols is non-empty, an index will be built and passed to opts.
148 CodeCompleteResult completionsNoCompile(llvm::StringRef Text,
149                                         std::vector<Symbol> IndexSymbols = {},
150                                         clangd::CodeCompleteOptions Opts = {},
151                                         PathRef FilePath = "foo.cpp") {
152   std::unique_ptr<SymbolIndex> OverrideIndex;
153   if (!IndexSymbols.empty()) {
154     assert(!Opts.Index && "both Index and IndexSymbols given!");
155     OverrideIndex = memIndex(std::move(IndexSymbols));
156     Opts.Index = OverrideIndex.get();
157   }
158 
159   MockFSProvider FS;
160   Annotations Test(Text);
161   return codeComplete(FilePath, tooling::CompileCommand(), /*Preamble=*/nullptr,
162                       Test.code(), Test.point(), FS.getFileSystem(), Opts);
163 }
164 
165 Symbol withReferences(int N, Symbol S) {
166   S.References = N;
167   return S;
168 }
169 
170 TEST(CompletionTest, Limit) {
171   clangd::CodeCompleteOptions Opts;
172   Opts.Limit = 2;
173   auto Results = completions(R"cpp(
174 struct ClassWithMembers {
175   int AAA();
176   int BBB();
177   int CCC();
178 };
179 
180 int main() { ClassWithMembers().^ }
181       )cpp",
182                              /*IndexSymbols=*/{}, Opts);
183 
184   EXPECT_TRUE(Results.HasMore);
185   EXPECT_THAT(Results.Completions, ElementsAre(Named("AAA"), Named("BBB")));
186 }
187 
188 TEST(CompletionTest, Filter) {
189   std::string Body = R"cpp(
190     #define MotorCar
191     int Car;
192     struct S {
193       int FooBar;
194       int FooBaz;
195       int Qux;
196     };
197   )cpp";
198 
199   // Only items matching the fuzzy query are returned.
200   EXPECT_THAT(completions(Body + "int main() { S().Foba^ }").Completions,
201               AllOf(Has("FooBar"), Has("FooBaz"), Not(Has("Qux"))));
202 
203   // Macros require  prefix match.
204   EXPECT_THAT(completions(Body + "int main() { C^ }").Completions,
205               AllOf(Has("Car"), Not(Has("MotorCar"))));
206 }
207 
208 void testAfterDotCompletion(clangd::CodeCompleteOptions Opts) {
209   auto Results = completions(
210       R"cpp(
211       int global_var;
212 
213       int global_func();
214 
215       // Make sure this is not in preamble.
216       #define MACRO X
217 
218       struct GlobalClass {};
219 
220       struct ClassWithMembers {
221         /// Doc for method.
222         int method();
223 
224         int field;
225       private:
226         int private_field;
227       };
228 
229       int test() {
230         struct LocalClass {};
231 
232         /// Doc for local_var.
233         int local_var;
234 
235         ClassWithMembers().^
236       }
237       )cpp",
238       {cls("IndexClass"), var("index_var"), func("index_func")}, Opts);
239 
240   EXPECT_TRUE(Results.RanParser);
241   // Class members. The only items that must be present in after-dot
242   // completion.
243   EXPECT_THAT(Results.Completions,
244               AllOf(Has("method"), Has("field"), Not(Has("ClassWithMembers")),
245                     Not(Has("operator=")), Not(Has("~ClassWithMembers"))));
246   EXPECT_IFF(Opts.IncludeIneligibleResults, Results.Completions,
247              Has("private_field"));
248   // Global items.
249   EXPECT_THAT(
250       Results.Completions,
251       Not(AnyOf(Has("global_var"), Has("index_var"), Has("global_func"),
252                 Has("global_func()"), Has("index_func"), Has("GlobalClass"),
253                 Has("IndexClass"), Has("MACRO"), Has("LocalClass"))));
254   // There should be no code patterns (aka snippets) in after-dot
255   // completion. At least there aren't any we're aware of.
256   EXPECT_THAT(Results.Completions,
257               Not(Contains(Kind(CompletionItemKind::Snippet))));
258   // Check documentation.
259   EXPECT_IFF(Opts.IncludeComments, Results.Completions,
260              Contains(IsDocumented()));
261 }
262 
263 void testGlobalScopeCompletion(clangd::CodeCompleteOptions Opts) {
264   auto Results = completions(
265       R"cpp(
266       int global_var;
267       int global_func();
268 
269       // Make sure this is not in preamble.
270       #define MACRO X
271 
272       struct GlobalClass {};
273 
274       struct ClassWithMembers {
275         /// Doc for method.
276         int method();
277       };
278 
279       int test() {
280         struct LocalClass {};
281 
282         /// Doc for local_var.
283         int local_var;
284 
285         ^
286       }
287       )cpp",
288       {cls("IndexClass"), var("index_var"), func("index_func")}, Opts);
289 
290   EXPECT_TRUE(Results.RanParser);
291   // Class members. Should never be present in global completions.
292   EXPECT_THAT(Results.Completions,
293               Not(AnyOf(Has("method"), Has("method()"), Has("field"))));
294   // Global items.
295   EXPECT_THAT(Results.Completions,
296               AllOf(Has("global_var"), Has("index_var"), Has("global_func"),
297                     Has("index_func" /* our fake symbol doesn't include () */),
298                     Has("GlobalClass"), Has("IndexClass")));
299   // A macro.
300   EXPECT_IFF(Opts.IncludeMacros, Results.Completions, Has("MACRO"));
301   // Local items. Must be present always.
302   EXPECT_THAT(Results.Completions,
303               AllOf(Has("local_var"), Has("LocalClass"),
304                     Contains(Kind(CompletionItemKind::Snippet))));
305   // Check documentation.
306   EXPECT_IFF(Opts.IncludeComments, Results.Completions,
307              Contains(IsDocumented()));
308 }
309 
310 TEST(CompletionTest, CompletionOptions) {
311   auto Test = [&](const clangd::CodeCompleteOptions &Opts) {
312     testAfterDotCompletion(Opts);
313     testGlobalScopeCompletion(Opts);
314   };
315   // We used to test every combination of options, but that got too slow (2^N).
316   auto Flags = {
317       &clangd::CodeCompleteOptions::IncludeMacros,
318       &clangd::CodeCompleteOptions::IncludeComments,
319       &clangd::CodeCompleteOptions::IncludeCodePatterns,
320       &clangd::CodeCompleteOptions::IncludeIneligibleResults,
321   };
322   // Test default options.
323   Test({});
324   // Test with one flag flipped.
325   for (auto &F : Flags) {
326     clangd::CodeCompleteOptions O;
327     O.*F ^= true;
328     Test(O);
329   }
330 }
331 
332 TEST(CompletionTest, Accessible) {
333   auto Internal = completions(R"cpp(
334       class Foo {
335         public: void pub();
336         protected: void prot();
337         private: void priv();
338       };
339       void Foo::pub() { this->^ }
340   )cpp");
341   EXPECT_THAT(Internal.Completions,
342               AllOf(Has("priv"), Has("prot"), Has("pub")));
343 
344   auto External = completions(R"cpp(
345       class Foo {
346         public: void pub();
347         protected: void prot();
348         private: void priv();
349       };
350       void test() {
351         Foo F;
352         F.^
353       }
354   )cpp");
355   EXPECT_THAT(External.Completions,
356               AllOf(Has("pub"), Not(Has("prot")), Not(Has("priv"))));
357 }
358 
359 TEST(CompletionTest, Qualifiers) {
360   auto Results = completions(R"cpp(
361       class Foo {
362         public: int foo() const;
363         int bar() const;
364       };
365       class Bar : public Foo {
366         int foo() const;
367       };
368       void test() { Bar().^ }
369   )cpp");
370   EXPECT_THAT(Results.Completions,
371               Contains(AllOf(Qualifier(""), Named("bar"))));
372   // Hidden members are not shown.
373   EXPECT_THAT(Results.Completions,
374               Not(Contains(AllOf(Qualifier("Foo::"), Named("foo")))));
375   // Private members are not shown.
376   EXPECT_THAT(Results.Completions,
377               Not(Contains(AllOf(Qualifier(""), Named("foo")))));
378 }
379 
380 TEST(CompletionTest, InjectedTypename) {
381   // These are suppressed when accessed as a member...
382   EXPECT_THAT(completions("struct X{}; void foo(){ X().^ }").Completions,
383               Not(Has("X")));
384   EXPECT_THAT(completions("struct X{ void foo(){ this->^ } };").Completions,
385               Not(Has("X")));
386   // ...but accessible in other, more useful cases.
387   EXPECT_THAT(completions("struct X{ void foo(){ ^ } };").Completions,
388               Has("X"));
389   EXPECT_THAT(
390       completions("struct Y{}; struct X:Y{ void foo(){ ^ } };").Completions,
391       Has("Y"));
392   EXPECT_THAT(
393       completions(
394           "template<class> struct Y{}; struct X:Y<int>{ void foo(){ ^ } };")
395           .Completions,
396       Has("Y"));
397   // This case is marginal (`using X::X` is useful), we allow it for now.
398   EXPECT_THAT(completions("struct X{}; void foo(){ X::^ }").Completions,
399               Has("X"));
400 }
401 
402 TEST(CompletionTest, SkipInjectedWhenUnqualified) {
403   EXPECT_THAT(completions("struct X { void f() { X^ }};").Completions,
404               ElementsAre(Named("X"), Named("~X")));
405 }
406 
407 TEST(CompletionTest, Snippets) {
408   clangd::CodeCompleteOptions Opts;
409   auto Results = completions(
410       R"cpp(
411       struct fake {
412         int a;
413         int f(int i, const float f) const;
414       };
415       int main() {
416         fake f;
417         f.^
418       }
419       )cpp",
420       /*IndexSymbols=*/{}, Opts);
421   EXPECT_THAT(
422       Results.Completions,
423       HasSubsequence(Named("a"),
424                      SnippetSuffix("(${1:int i}, ${2:const float f})")));
425 }
426 
427 TEST(CompletionTest, NoSnippetsInUsings) {
428   clangd::CodeCompleteOptions Opts;
429   Opts.EnableSnippets = true;
430   auto Results = completions(
431       R"cpp(
432       namespace ns {
433         int func(int a, int b);
434       }
435 
436       using ns::^;
437       )cpp",
438       /*IndexSymbols=*/{}, Opts);
439   EXPECT_THAT(Results.Completions,
440               ElementsAre(AllOf(Named("func"), Labeled("func(int a, int b)"),
441                                 SnippetSuffix(""))));
442 
443   // Check index completions too.
444   auto Func = func("ns::func");
445   Func.CompletionSnippetSuffix = "(${1:int a}, ${2: int b})";
446   Func.Signature = "(int a, int b)";
447   Func.ReturnType = "void";
448 
449   Results = completions(R"cpp(
450       namespace ns {}
451       using ns::^;
452   )cpp",
453                         /*IndexSymbols=*/{Func}, Opts);
454   EXPECT_THAT(Results.Completions,
455               ElementsAre(AllOf(Named("func"), Labeled("func(int a, int b)"),
456                                 SnippetSuffix(""))));
457 
458   // Check all-scopes completions too.
459   Opts.AllScopes = true;
460   Results = completions(R"cpp(
461       using ^;
462   )cpp",
463                         /*IndexSymbols=*/{Func}, Opts);
464   EXPECT_THAT(Results.Completions,
465               Contains(AllOf(Named("func"), Labeled("ns::func(int a, int b)"),
466                              SnippetSuffix(""))));
467 }
468 
469 TEST(CompletionTest, Kinds) {
470   auto Results = completions(
471       R"cpp(
472           int variable;
473           struct Struct {};
474           int function();
475           // make sure MACRO is not included in preamble.
476           #define MACRO 10
477           int X = ^
478       )cpp",
479       {func("indexFunction"), var("indexVariable"), cls("indexClass")});
480   EXPECT_THAT(Results.Completions,
481               AllOf(Has("function", CompletionItemKind::Function),
482                     Has("variable", CompletionItemKind::Variable),
483                     Has("int", CompletionItemKind::Keyword),
484                     Has("Struct", CompletionItemKind::Struct),
485                     Has("MACRO", CompletionItemKind::Text),
486                     Has("indexFunction", CompletionItemKind::Function),
487                     Has("indexVariable", CompletionItemKind::Variable),
488                     Has("indexClass", CompletionItemKind::Class)));
489 
490   Results = completions("nam^");
491   EXPECT_THAT(Results.Completions,
492               Has("namespace", CompletionItemKind::Snippet));
493 
494   // Members of anonymous unions are of kind 'field'.
495   Results = completions(
496       R"cpp(
497         struct X{
498             union {
499               void *a;
500             };
501         };
502         auto u = X().^
503       )cpp");
504   EXPECT_THAT(
505       Results.Completions,
506       UnorderedElementsAre(AllOf(Named("a"), Kind(CompletionItemKind::Field))));
507 
508   // Completion kinds for templates should not be unknown.
509   Results = completions(
510       R"cpp(
511         template <class T> struct complete_class {};
512         template <class T> void complete_function();
513         template <class T> using complete_type_alias = int;
514         template <class T> int complete_variable = 10;
515 
516         struct X {
517           template <class T> static int complete_static_member = 10;
518 
519           static auto x = complete_^
520         }
521       )cpp");
522   EXPECT_THAT(
523       Results.Completions,
524       UnorderedElementsAre(
525           AllOf(Named("complete_class"), Kind(CompletionItemKind::Class)),
526           AllOf(Named("complete_function"), Kind(CompletionItemKind::Function)),
527           AllOf(Named("complete_type_alias"),
528                 Kind(CompletionItemKind::Interface)),
529           AllOf(Named("complete_variable"), Kind(CompletionItemKind::Variable)),
530           AllOf(Named("complete_static_member"),
531                 Kind(CompletionItemKind::Property))));
532 
533    Results = completions(
534       R"cpp(
535         enum Color {
536           Red
537         };
538         Color u = ^
539       )cpp");
540    EXPECT_THAT(Results.Completions,
541                Contains(
542                    AllOf(Named("Red"), Kind(CompletionItemKind::EnumMember))));
543 }
544 
545 TEST(CompletionTest, NoDuplicates) {
546   auto Results = completions(
547       R"cpp(
548           class Adapter {
549           };
550 
551           void f() {
552             Adapter^
553           }
554       )cpp",
555       {cls("Adapter")});
556 
557   // Make sure there are no duplicate entries of 'Adapter'.
558   EXPECT_THAT(Results.Completions, ElementsAre(Named("Adapter")));
559 }
560 
561 TEST(CompletionTest, ScopedNoIndex) {
562   auto Results = completions(
563       R"cpp(
564           namespace fake { int BigBang, Babble, Box; };
565           int main() { fake::ba^ }
566       ")cpp");
567   // Babble is a better match than BigBang. Box doesn't match at all.
568   EXPECT_THAT(Results.Completions,
569               ElementsAre(Named("Babble"), Named("BigBang")));
570 }
571 
572 TEST(CompletionTest, Scoped) {
573   auto Results = completions(
574       R"cpp(
575           namespace fake { int Babble, Box; };
576           int main() { fake::ba^ }
577       ")cpp",
578       {var("fake::BigBang")});
579   EXPECT_THAT(Results.Completions,
580               ElementsAre(Named("Babble"), Named("BigBang")));
581 }
582 
583 TEST(CompletionTest, ScopedWithFilter) {
584   auto Results = completions(
585       R"cpp(
586           void f() { ns::x^ }
587       )cpp",
588       {cls("ns::XYZ"), func("ns::foo")});
589   EXPECT_THAT(Results.Completions, UnorderedElementsAre(Named("XYZ")));
590 }
591 
592 TEST(CompletionTest, ReferencesAffectRanking) {
593   auto Results = completions("int main() { abs^ }", {ns("absl"), func("absb")});
594   EXPECT_THAT(Results.Completions,
595               HasSubsequence(Named("absb"), Named("absl")));
596   Results = completions("int main() { abs^ }",
597                         {withReferences(10000, ns("absl")), func("absb")});
598   EXPECT_THAT(Results.Completions,
599               HasSubsequence(Named("absl"), Named("absb")));
600 }
601 
602 TEST(CompletionTest, ContextWords) {
603   auto Results = completions(R"cpp(
604   enum class Color { RED, YELLOW, BLUE };
605 
606   // (blank lines so the definition above isn't "context")
607 
608   // "It was a yellow car," he said. "Big yellow car, new."
609   auto Finish = Color::^
610   )cpp");
611   // Yellow would normally sort last (alphabetic).
612   // But the recent mention shuold bump it up.
613   ASSERT_THAT(Results.Completions,
614               HasSubsequence(Named("YELLOW"), Named("BLUE")));
615 }
616 
617 TEST(CompletionTest, GlobalQualified) {
618   auto Results = completions(
619       R"cpp(
620           void f() { ::^ }
621       )cpp",
622       {cls("XYZ")});
623   EXPECT_THAT(Results.Completions,
624               AllOf(Has("XYZ", CompletionItemKind::Class),
625                     Has("f", CompletionItemKind::Function)));
626 }
627 
628 TEST(CompletionTest, FullyQualified) {
629   auto Results = completions(
630       R"cpp(
631           namespace ns { void bar(); }
632           void f() { ::ns::^ }
633       )cpp",
634       {cls("ns::XYZ")});
635   EXPECT_THAT(Results.Completions,
636               AllOf(Has("XYZ", CompletionItemKind::Class),
637                     Has("bar", CompletionItemKind::Function)));
638 }
639 
640 TEST(CompletionTest, SemaIndexMerge) {
641   auto Results = completions(
642       R"cpp(
643           namespace ns { int local; void both(); }
644           void f() { ::ns::^ }
645       )cpp",
646       {func("ns::both"), cls("ns::Index")});
647   // We get results from both index and sema, with no duplicates.
648   EXPECT_THAT(Results.Completions,
649               UnorderedElementsAre(
650                   AllOf(Named("local"), Origin(SymbolOrigin::AST)),
651                   AllOf(Named("Index"), Origin(SymbolOrigin::Static)),
652                   AllOf(Named("both"),
653                         Origin(SymbolOrigin::AST | SymbolOrigin::Static))));
654 }
655 
656 TEST(CompletionTest, SemaIndexMergeWithLimit) {
657   clangd::CodeCompleteOptions Opts;
658   Opts.Limit = 1;
659   auto Results = completions(
660       R"cpp(
661           namespace ns { int local; void both(); }
662           void f() { ::ns::^ }
663       )cpp",
664       {func("ns::both"), cls("ns::Index")}, Opts);
665   EXPECT_EQ(Results.Completions.size(), Opts.Limit);
666   EXPECT_TRUE(Results.HasMore);
667 }
668 
669 TEST(CompletionTest, IncludeInsertionPreprocessorIntegrationTests) {
670   MockFSProvider FS;
671   MockCompilationDatabase CDB;
672   std::string Subdir = testPath("sub");
673   std::string SearchDirArg = (Twine("-I") + Subdir).str();
674   CDB.ExtraClangFlags = {SearchDirArg.c_str()};
675   std::string BarHeader = testPath("sub/bar.h");
676   FS.Files[BarHeader] = "";
677 
678   ClangdServer Server(CDB, FS, ClangdServer::optsForTest());
679   auto BarURI = URI::create(BarHeader).toString();
680   Symbol Sym = cls("ns::X");
681   Sym.CanonicalDeclaration.FileURI = BarURI.c_str();
682   Sym.IncludeHeaders.emplace_back(BarURI, 1);
683   // Shoten include path based on search directory and insert.
684   auto Results = completions(Server,
685                              R"cpp(
686           int main() { ns::^ }
687       )cpp",
688                              {Sym});
689   EXPECT_THAT(Results.Completions,
690               ElementsAre(AllOf(Named("X"), InsertInclude("\"bar.h\""))));
691   // Can be disabled via option.
692   CodeCompleteOptions NoInsertion;
693   NoInsertion.InsertIncludes = CodeCompleteOptions::NeverInsert;
694   Results = completions(Server,
695                         R"cpp(
696           int main() { ns::^ }
697       )cpp",
698                         {Sym}, NoInsertion);
699   EXPECT_THAT(Results.Completions,
700               ElementsAre(AllOf(Named("X"), Not(InsertInclude()))));
701   // Duplicate based on inclusions in preamble.
702   Results = completions(Server,
703                         R"cpp(
704           #include "sub/bar.h"  // not shortest, so should only match resolved.
705           int main() { ns::^ }
706       )cpp",
707                         {Sym});
708   EXPECT_THAT(Results.Completions, ElementsAre(AllOf(Named("X"), Labeled("X"),
709                                                      Not(InsertInclude()))));
710 }
711 
712 TEST(CompletionTest, NoIncludeInsertionWhenDeclFoundInFile) {
713   MockFSProvider FS;
714   MockCompilationDatabase CDB;
715 
716   ClangdServer Server(CDB, FS, ClangdServer::optsForTest());
717   Symbol SymX = cls("ns::X");
718   Symbol SymY = cls("ns::Y");
719   std::string BarHeader = testPath("bar.h");
720   auto BarURI = URI::create(BarHeader).toString();
721   SymX.CanonicalDeclaration.FileURI = BarURI.c_str();
722   SymY.CanonicalDeclaration.FileURI = BarURI.c_str();
723   SymX.IncludeHeaders.emplace_back("<bar>", 1);
724   SymY.IncludeHeaders.emplace_back("<bar>", 1);
725   // Shoten include path based on search directory and insert.
726   auto Results = completions(Server,
727                              R"cpp(
728           namespace ns {
729             class X;
730             class Y {};
731           }
732           int main() { ns::^ }
733       )cpp",
734                              {SymX, SymY});
735   EXPECT_THAT(Results.Completions,
736               ElementsAre(AllOf(Named("X"), Not(InsertInclude())),
737                           AllOf(Named("Y"), Not(InsertInclude()))));
738 }
739 
740 TEST(CompletionTest, IndexSuppressesPreambleCompletions) {
741   MockFSProvider FS;
742   MockCompilationDatabase CDB;
743   ClangdServer Server(CDB, FS, ClangdServer::optsForTest());
744 
745   FS.Files[testPath("bar.h")] =
746       R"cpp(namespace ns { struct preamble { int member; }; })cpp";
747   auto File = testPath("foo.cpp");
748   Annotations Test(R"cpp(
749       #include "bar.h"
750       namespace ns { int local; }
751       void f() { ns::^; }
752       void f2() { ns::preamble().$2^; }
753   )cpp");
754   runAddDocument(Server, File, Test.code());
755   clangd::CodeCompleteOptions Opts = {};
756 
757   auto I = memIndex({var("ns::index")});
758   Opts.Index = I.get();
759   auto WithIndex = cantFail(runCodeComplete(Server, File, Test.point(), Opts));
760   EXPECT_THAT(WithIndex.Completions,
761               UnorderedElementsAre(Named("local"), Named("index")));
762   auto ClassFromPreamble =
763       cantFail(runCodeComplete(Server, File, Test.point("2"), Opts));
764   EXPECT_THAT(ClassFromPreamble.Completions, Contains(Named("member")));
765 
766   Opts.Index = nullptr;
767   auto WithoutIndex =
768       cantFail(runCodeComplete(Server, File, Test.point(), Opts));
769   EXPECT_THAT(WithoutIndex.Completions,
770               UnorderedElementsAre(Named("local"), Named("preamble")));
771 }
772 
773 // This verifies that we get normal preprocessor completions in the preamble.
774 // This is a regression test for an old bug: if we override the preamble and
775 // try to complete inside it, clang kicks our completion point just outside the
776 // preamble, resulting in always getting top-level completions.
777 TEST(CompletionTest, CompletionInPreamble) {
778   auto Results = completions(R"cpp(
779     #ifnd^ef FOO_H_
780     #define BAR_H_
781     #include <bar.h>
782     int foo() {}
783     #endif
784     )cpp")
785                      .Completions;
786   EXPECT_THAT(Results, ElementsAre(Named("ifndef")));
787 }
788 
789 TEST(CompletionTest, DynamicIndexIncludeInsertion) {
790   MockFSProvider FS;
791   MockCompilationDatabase CDB;
792   ClangdServer::Options Opts = ClangdServer::optsForTest();
793   Opts.BuildDynamicSymbolIndex = true;
794   ClangdServer Server(CDB, FS, Opts);
795 
796   FS.Files[testPath("foo_header.h")] = R"cpp(
797     #pragma once
798     struct Foo {
799        // Member doc
800        int foo();
801     };
802   )cpp";
803   const std::string FileContent(R"cpp(
804     #include "foo_header.h"
805     int Foo::foo() {
806       return 42;
807     }
808   )cpp");
809   Server.addDocument(testPath("foo_impl.cpp"), FileContent);
810   // Wait for the dynamic index being built.
811   ASSERT_TRUE(Server.blockUntilIdleForTest());
812   EXPECT_THAT(completions(Server, "Foo^ foo;").Completions,
813               ElementsAre(AllOf(Named("Foo"), HasInclude("\"foo_header.h\""),
814                                 InsertInclude())));
815 }
816 
817 TEST(CompletionTest, DynamicIndexMultiFile) {
818   MockFSProvider FS;
819   MockCompilationDatabase CDB;
820   auto Opts = ClangdServer::optsForTest();
821   Opts.BuildDynamicSymbolIndex = true;
822   ClangdServer Server(CDB, FS, Opts);
823 
824   FS.Files[testPath("foo.h")] = R"cpp(
825       namespace ns { class XYZ {}; void foo(int x) {} }
826   )cpp";
827   runAddDocument(Server, testPath("foo.cpp"), R"cpp(
828       #include "foo.h"
829   )cpp");
830 
831   auto File = testPath("bar.cpp");
832   Annotations Test(R"cpp(
833       namespace ns {
834       class XXX {};
835       /// Doooc
836       void fooooo() {}
837       }
838       void f() { ns::^ }
839   )cpp");
840   runAddDocument(Server, File, Test.code());
841 
842   auto Results = cantFail(runCodeComplete(Server, File, Test.point(), {}));
843   // "XYZ" and "foo" are not included in the file being completed but are still
844   // visible through the index.
845   EXPECT_THAT(Results.Completions, Has("XYZ", CompletionItemKind::Class));
846   EXPECT_THAT(Results.Completions, Has("foo", CompletionItemKind::Function));
847   EXPECT_THAT(Results.Completions, Has("XXX", CompletionItemKind::Class));
848   EXPECT_THAT(Results.Completions,
849               Contains((Named("fooooo"), Kind(CompletionItemKind::Function),
850                         Doc("Doooc"), ReturnType("void"))));
851 }
852 
853 TEST(CompletionTest, Documentation) {
854   auto Results = completions(
855       R"cpp(
856       // Non-doxygen comment.
857       int foo();
858       /// Doxygen comment.
859       /// \param int a
860       int bar(int a);
861       /* Multi-line
862          block comment
863       */
864       int baz();
865 
866       int x = ^
867      )cpp");
868   EXPECT_THAT(Results.Completions,
869               Contains(AllOf(Named("foo"), Doc("Non-doxygen comment."))));
870   EXPECT_THAT(
871       Results.Completions,
872       Contains(AllOf(Named("bar"), Doc("Doxygen comment.\n\\param int a"))));
873   EXPECT_THAT(Results.Completions,
874               Contains(AllOf(Named("baz"), Doc("Multi-line\nblock comment"))));
875 }
876 
877 TEST(CompletionTest, CommentsFromSystemHeaders) {
878   MockFSProvider FS;
879   MockCompilationDatabase CDB;
880 
881   auto Opts = ClangdServer::optsForTest();
882   Opts.BuildDynamicSymbolIndex = true;
883 
884   ClangdServer Server(CDB, FS, Opts);
885 
886   FS.Files[testPath("foo.h")] = R"cpp(
887     #pragma GCC system_header
888 
889     // This comment should be retained!
890     int foo();
891   )cpp";
892 
893   auto Results = completions(Server,
894                              R"cpp(
895 #include "foo.h"
896 int x = foo^
897      )cpp");
898   EXPECT_THAT(
899       Results.Completions,
900       Contains(AllOf(Named("foo"), Doc("This comment should be retained!"))));
901 }
902 
903 TEST(CompletionTest, GlobalCompletionFiltering) {
904 
905   Symbol Class = cls("XYZ");
906   Class.Flags = static_cast<Symbol::SymbolFlag>(
907       Class.Flags & ~(Symbol::IndexedForCodeCompletion));
908   Symbol Func = func("XYZ::foooo");
909   Func.Flags = static_cast<Symbol::SymbolFlag>(
910       Func.Flags & ~(Symbol::IndexedForCodeCompletion));
911 
912   auto Results = completions(R"(//      void f() {
913       XYZ::foooo^
914       })",
915                              {Class, Func});
916   EXPECT_THAT(Results.Completions, IsEmpty());
917 }
918 
919 TEST(CodeCompleteTest, DisableTypoCorrection) {
920   auto Results = completions(R"cpp(
921      namespace clang { int v; }
922      void f() { clangd::^
923   )cpp");
924   EXPECT_TRUE(Results.Completions.empty());
925 }
926 
927 TEST(CodeCompleteTest, NoColonColonAtTheEnd) {
928   auto Results = completions(R"cpp(
929     namespace clang { }
930     void f() {
931       clan^
932     }
933   )cpp");
934 
935   EXPECT_THAT(Results.Completions, Contains(Labeled("clang")));
936   EXPECT_THAT(Results.Completions, Not(Contains(Labeled("clang::"))));
937 }
938 
939 TEST(CompletionTest, BacktrackCrashes) {
940   // Sema calls code completion callbacks twice in these cases.
941   auto Results = completions(R"cpp(
942       namespace ns {
943       struct FooBarBaz {};
944       } // namespace ns
945 
946      int foo(ns::FooBar^
947   )cpp");
948 
949   EXPECT_THAT(Results.Completions, ElementsAre(Labeled("FooBarBaz")));
950 
951   // Check we don't crash in that case too.
952   completions(R"cpp(
953     struct FooBarBaz {};
954     void test() {
955       if (FooBarBaz * x^) {}
956     }
957 )cpp");
958 }
959 
960 TEST(CompletionTest, CompleteInMacroWithStringification) {
961   auto Results = completions(R"cpp(
962 void f(const char *, int x);
963 #define F(x) f(#x, x)
964 
965 namespace ns {
966 int X;
967 int Y;
968 }  // namespace ns
969 
970 int f(int input_num) {
971   F(ns::^)
972 }
973 )cpp");
974 
975   EXPECT_THAT(Results.Completions,
976               UnorderedElementsAre(Named("X"), Named("Y")));
977 }
978 
979 TEST(CompletionTest, CompleteInMacroAndNamespaceWithStringification) {
980   auto Results = completions(R"cpp(
981 void f(const char *, int x);
982 #define F(x) f(#x, x)
983 
984 namespace ns {
985 int X;
986 
987 int f(int input_num) {
988   F(^)
989 }
990 }  // namespace ns
991 )cpp");
992 
993   EXPECT_THAT(Results.Completions, Contains(Named("X")));
994 }
995 
996 TEST(CompletionTest, IgnoreCompleteInExcludedPPBranchWithRecoveryContext) {
997   auto Results = completions(R"cpp(
998     int bar(int param_in_bar) {
999     }
1000 
1001     int foo(int param_in_foo) {
1002 #if 0
1003   // In recorvery mode, "param_in_foo" will also be suggested among many other
1004   // unrelated symbols; however, this is really a special case where this works.
1005   // If the #if block is outside of the function, "param_in_foo" is still
1006   // suggested, but "bar" and "foo" are missing. So the recovery mode doesn't
1007   // really provide useful results in excluded branches.
1008   par^
1009 #endif
1010     }
1011 )cpp");
1012 
1013   EXPECT_TRUE(Results.Completions.empty());
1014 }
1015 
1016 TEST(CompletionTest, DefaultArgs) {
1017   clangd::CodeCompleteOptions Opts;
1018   std::string Context = R"cpp(
1019     int X(int A = 0);
1020     int Y(int A, int B = 0);
1021     int Z(int A, int B = 0, int C = 0, int D = 0);
1022   )cpp";
1023   EXPECT_THAT(completions(Context + "int y = X^", {}, Opts).Completions,
1024               UnorderedElementsAre(Labeled("X(int A = 0)")));
1025   EXPECT_THAT(completions(Context + "int y = Y^", {}, Opts).Completions,
1026               UnorderedElementsAre(AllOf(Labeled("Y(int A, int B = 0)"),
1027                                          SnippetSuffix("(${1:int A})"))));
1028   EXPECT_THAT(completions(Context + "int y = Z^", {}, Opts).Completions,
1029               UnorderedElementsAre(
1030                   AllOf(Labeled("Z(int A, int B = 0, int C = 0, int D = 0)"),
1031                         SnippetSuffix("(${1:int A})"))));
1032 }
1033 
1034 TEST(CompletionTest, NoCrashWithTemplateParamsAndPreferredTypes) {
1035   auto Completions = completions(R"cpp(
1036 template <template <class> class TT> int foo() {
1037   int a = ^
1038 }
1039 )cpp")
1040                          .Completions;
1041   EXPECT_THAT(Completions, Contains(Named("TT")));
1042 }
1043 
1044 SignatureHelp signatures(llvm::StringRef Text, Position Point,
1045                          std::vector<Symbol> IndexSymbols = {}) {
1046   std::unique_ptr<SymbolIndex> Index;
1047   if (!IndexSymbols.empty())
1048     Index = memIndex(IndexSymbols);
1049 
1050   MockFSProvider FS;
1051   MockCompilationDatabase CDB;
1052   ClangdServer::Options Opts = ClangdServer::optsForTest();
1053   Opts.StaticIndex = Index.get();
1054 
1055   ClangdServer Server(CDB, FS, Opts);
1056   auto File = testPath("foo.cpp");
1057   runAddDocument(Server, File, Text);
1058   return llvm::cantFail(runSignatureHelp(Server, File, Point));
1059 }
1060 
1061 SignatureHelp signatures(llvm::StringRef Text,
1062                          std::vector<Symbol> IndexSymbols = {}) {
1063   Annotations Test(Text);
1064   return signatures(Test.code(), Test.point(), std::move(IndexSymbols));
1065 }
1066 
1067 struct ExpectedParameter {
1068   std::string Text;
1069   std::pair<unsigned, unsigned> Offsets;
1070 };
1071 MATCHER_P(ParamsAre, P, "") {
1072   if (P.size() != arg.parameters.size())
1073     return false;
1074   for (unsigned I = 0; I < P.size(); ++I) {
1075     if (P[I].Text != arg.parameters[I].labelString ||
1076         P[I].Offsets != arg.parameters[I].labelOffsets)
1077       return false;
1078   }
1079   return true;
1080 }
1081 MATCHER_P(SigDoc, Doc, "") { return arg.documentation == Doc; }
1082 
1083 /// \p AnnotatedLabel is a signature label with ranges marking parameters, e.g.
1084 ///    foo([[int p1]], [[double p2]]) -> void
1085 Matcher<SignatureInformation> Sig(llvm::StringRef AnnotatedLabel) {
1086   llvm::Annotations A(AnnotatedLabel);
1087   std::string Label = std::string(A.code());
1088   std::vector<ExpectedParameter> Parameters;
1089   for (auto Range : A.ranges()) {
1090     Parameters.emplace_back();
1091 
1092     ExpectedParameter &P = Parameters.back();
1093     P.Text = Label.substr(Range.Begin, Range.End - Range.Begin);
1094     P.Offsets.first = lspLength(llvm::StringRef(Label).substr(0, Range.Begin));
1095     P.Offsets.second = lspLength(llvm::StringRef(Label).substr(1, Range.End));
1096   }
1097   return AllOf(SigHelpLabeled(Label), ParamsAre(Parameters));
1098 }
1099 
1100 TEST(SignatureHelpTest, Overloads) {
1101   auto Results = signatures(R"cpp(
1102     void foo(int x, int y);
1103     void foo(int x, float y);
1104     void foo(float x, int y);
1105     void foo(float x, float y);
1106     void bar(int x, int y = 0);
1107     int main() { foo(^); }
1108   )cpp");
1109   EXPECT_THAT(Results.signatures,
1110               UnorderedElementsAre(Sig("foo([[float x]], [[float y]]) -> void"),
1111                                    Sig("foo([[float x]], [[int y]]) -> void"),
1112                                    Sig("foo([[int x]], [[float y]]) -> void"),
1113                                    Sig("foo([[int x]], [[int y]]) -> void")));
1114   // We always prefer the first signature.
1115   EXPECT_EQ(0, Results.activeSignature);
1116   EXPECT_EQ(0, Results.activeParameter);
1117 }
1118 
1119 TEST(SignatureHelpTest, DefaultArgs) {
1120   auto Results = signatures(R"cpp(
1121     void bar(int x, int y = 0);
1122     void bar(float x = 0, int y = 42);
1123     int main() { bar(^
1124   )cpp");
1125   EXPECT_THAT(Results.signatures,
1126               UnorderedElementsAre(
1127                   Sig("bar([[int x]], [[int y = 0]]) -> void"),
1128                   Sig("bar([[float x = 0]], [[int y = 42]]) -> void")));
1129   EXPECT_EQ(0, Results.activeSignature);
1130   EXPECT_EQ(0, Results.activeParameter);
1131 }
1132 
1133 TEST(SignatureHelpTest, ActiveArg) {
1134   auto Results = signatures(R"cpp(
1135     int baz(int a, int b, int c);
1136     int main() { baz(baz(1,2,3), ^); }
1137   )cpp");
1138   EXPECT_THAT(Results.signatures,
1139               ElementsAre(Sig("baz([[int a]], [[int b]], [[int c]]) -> int")));
1140   EXPECT_EQ(0, Results.activeSignature);
1141   EXPECT_EQ(1, Results.activeParameter);
1142 }
1143 
1144 TEST(SignatureHelpTest, OpeningParen) {
1145   llvm::StringLiteral Tests[] = {// Recursive function call.
1146                                  R"cpp(
1147     int foo(int a, int b, int c);
1148     int main() {
1149       foo(foo $p^( foo(10, 10, 10), ^ )));
1150     })cpp",
1151                                  // Functional type cast.
1152                                  R"cpp(
1153     struct Foo {
1154       Foo(int a, int b, int c);
1155     };
1156     int main() {
1157       Foo $p^( 10, ^ );
1158     })cpp",
1159                                  // New expression.
1160                                  R"cpp(
1161     struct Foo {
1162       Foo(int a, int b, int c);
1163     };
1164     int main() {
1165       new Foo $p^( 10, ^ );
1166     })cpp",
1167                                  // Macro expansion.
1168                                  R"cpp(
1169     int foo(int a, int b, int c);
1170     #define FOO foo(
1171 
1172     int main() {
1173       // Macro expansions.
1174       $p^FOO 10, ^ );
1175     })cpp",
1176                                  // Macro arguments.
1177                                  R"cpp(
1178     int foo(int a, int b, int c);
1179     int main() {
1180     #define ID(X) X
1181       ID(foo $p^( foo(10), ^ ))
1182     })cpp"};
1183 
1184   for (auto Test : Tests) {
1185     Annotations Code(Test);
1186     EXPECT_EQ(signatures(Code.code(), Code.point()).argListStart,
1187               Code.point("p"))
1188         << "Test source:" << Test;
1189   }
1190 }
1191 
1192 class IndexRequestCollector : public SymbolIndex {
1193 public:
1194   bool
1195   fuzzyFind(const FuzzyFindRequest &Req,
1196             llvm::function_ref<void(const Symbol &)> Callback) const override {
1197     std::unique_lock<std::mutex> Lock(Mut);
1198     Requests.push_back(Req);
1199     ReceivedRequestCV.notify_one();
1200     return true;
1201   }
1202 
1203   void lookup(const LookupRequest &,
1204               llvm::function_ref<void(const Symbol &)>) const override {}
1205 
1206   bool refs(const RefsRequest &,
1207             llvm::function_ref<void(const Ref &)>) const override {
1208     return false;
1209   }
1210 
1211   void relations(const RelationsRequest &,
1212                  llvm::function_ref<void(const SymbolID &, const Symbol &)>)
1213       const override {}
1214 
1215   // This is incorrect, but IndexRequestCollector is not an actual index and it
1216   // isn't used in production code.
1217   size_t estimateMemoryUsage() const override { return 0; }
1218 
1219   const std::vector<FuzzyFindRequest> consumeRequests(size_t Num) const {
1220     std::unique_lock<std::mutex> Lock(Mut);
1221     EXPECT_TRUE(wait(Lock, ReceivedRequestCV, timeoutSeconds(30),
1222                      [this, Num] { return Requests.size() == Num; }));
1223     auto Reqs = std::move(Requests);
1224     Requests = {};
1225     return Reqs;
1226   }
1227 
1228 private:
1229   // We need a mutex to handle async fuzzy find requests.
1230   mutable std::condition_variable ReceivedRequestCV;
1231   mutable std::mutex Mut;
1232   mutable std::vector<FuzzyFindRequest> Requests;
1233 };
1234 
1235 // Clients have to consume exactly Num requests.
1236 std::vector<FuzzyFindRequest> captureIndexRequests(llvm::StringRef Code,
1237                                                    size_t Num = 1) {
1238   clangd::CodeCompleteOptions Opts;
1239   IndexRequestCollector Requests;
1240   Opts.Index = &Requests;
1241   completions(Code, {}, Opts);
1242   const auto Reqs = Requests.consumeRequests(Num);
1243   EXPECT_EQ(Reqs.size(), Num);
1244   return Reqs;
1245 }
1246 
1247 TEST(CompletionTest, UnqualifiedIdQuery) {
1248   auto Requests = captureIndexRequests(R"cpp(
1249       namespace std {}
1250       using namespace std;
1251       namespace ns {
1252       void f() {
1253         vec^
1254       }
1255       }
1256   )cpp");
1257 
1258   EXPECT_THAT(Requests,
1259               ElementsAre(Field(&FuzzyFindRequest::Scopes,
1260                                 UnorderedElementsAre("", "ns::", "std::"))));
1261 }
1262 
1263 TEST(CompletionTest, EnclosingScopeComesFirst) {
1264   auto Requests = captureIndexRequests(R"cpp(
1265       namespace std {}
1266       using namespace std;
1267       namespace nx {
1268       namespace ns {
1269       namespace {
1270       void f() {
1271         vec^
1272       }
1273       }
1274       }
1275       }
1276   )cpp");
1277 
1278   EXPECT_THAT(Requests,
1279               ElementsAre(Field(
1280                   &FuzzyFindRequest::Scopes,
1281                   UnorderedElementsAre("", "std::", "nx::ns::", "nx::"))));
1282   EXPECT_EQ(Requests[0].Scopes[0], "nx::ns::");
1283 }
1284 
1285 TEST(CompletionTest, ResolvedQualifiedIdQuery) {
1286   auto Requests = captureIndexRequests(R"cpp(
1287       namespace ns1 {}
1288       namespace ns2 {} // ignore
1289       namespace ns3 { namespace nns3 {} }
1290       namespace foo {
1291       using namespace ns1;
1292       using namespace ns3::nns3;
1293       }
1294       namespace ns {
1295       void f() {
1296         foo::^
1297       }
1298       }
1299   )cpp");
1300 
1301   EXPECT_THAT(Requests,
1302               ElementsAre(Field(
1303                   &FuzzyFindRequest::Scopes,
1304                   UnorderedElementsAre("foo::", "ns1::", "ns3::nns3::"))));
1305 }
1306 
1307 TEST(CompletionTest, UnresolvedQualifierIdQuery) {
1308   auto Requests = captureIndexRequests(R"cpp(
1309       namespace a {}
1310       using namespace a;
1311       namespace ns {
1312       void f() {
1313       bar::^
1314       }
1315       } // namespace ns
1316   )cpp");
1317 
1318   EXPECT_THAT(Requests,
1319               ElementsAre(Field(
1320                   &FuzzyFindRequest::Scopes,
1321                   UnorderedElementsAre("a::bar::", "ns::bar::", "bar::"))));
1322 }
1323 
1324 TEST(CompletionTest, UnresolvedNestedQualifierIdQuery) {
1325   auto Requests = captureIndexRequests(R"cpp(
1326       namespace a {}
1327       using namespace a;
1328       namespace ns {
1329       void f() {
1330       ::a::bar::^
1331       }
1332       } // namespace ns
1333   )cpp");
1334 
1335   EXPECT_THAT(Requests, ElementsAre(Field(&FuzzyFindRequest::Scopes,
1336                                           UnorderedElementsAre("a::bar::"))));
1337 }
1338 
1339 TEST(CompletionTest, EmptyQualifiedQuery) {
1340   auto Requests = captureIndexRequests(R"cpp(
1341       namespace ns {
1342       void f() {
1343       ^
1344       }
1345       } // namespace ns
1346   )cpp");
1347 
1348   EXPECT_THAT(Requests, ElementsAre(Field(&FuzzyFindRequest::Scopes,
1349                                           UnorderedElementsAre("", "ns::"))));
1350 }
1351 
1352 TEST(CompletionTest, GlobalQualifiedQuery) {
1353   auto Requests = captureIndexRequests(R"cpp(
1354       namespace ns {
1355       void f() {
1356       ::^
1357       }
1358       } // namespace ns
1359   )cpp");
1360 
1361   EXPECT_THAT(Requests, ElementsAre(Field(&FuzzyFindRequest::Scopes,
1362                                           UnorderedElementsAre(""))));
1363 }
1364 
1365 TEST(CompletionTest, NoDuplicatedQueryScopes) {
1366   auto Requests = captureIndexRequests(R"cpp(
1367       namespace {}
1368 
1369       namespace na {
1370       namespace {}
1371       namespace nb {
1372       ^
1373       } // namespace nb
1374       } // namespace na
1375   )cpp");
1376 
1377   EXPECT_THAT(Requests,
1378               ElementsAre(Field(&FuzzyFindRequest::Scopes,
1379                                 UnorderedElementsAre("na::", "na::nb::", ""))));
1380 }
1381 
1382 TEST(CompletionTest, NoIndexCompletionsInsideClasses) {
1383   auto Completions = completions(
1384       R"cpp(
1385     struct Foo {
1386       int SomeNameOfField;
1387       typedef int SomeNameOfTypedefField;
1388     };
1389 
1390     Foo::^)cpp",
1391       {func("::SomeNameInTheIndex"), func("::Foo::SomeNameInTheIndex")});
1392 
1393   EXPECT_THAT(Completions.Completions,
1394               AllOf(Contains(Labeled("SomeNameOfField")),
1395                     Contains(Labeled("SomeNameOfTypedefField")),
1396                     Not(Contains(Labeled("SomeNameInTheIndex")))));
1397 }
1398 
1399 TEST(CompletionTest, NoIndexCompletionsInsideDependentCode) {
1400   {
1401     auto Completions = completions(
1402         R"cpp(
1403       template <class T>
1404       void foo() {
1405         T::^
1406       }
1407       )cpp",
1408         {func("::SomeNameInTheIndex")});
1409 
1410     EXPECT_THAT(Completions.Completions,
1411                 Not(Contains(Labeled("SomeNameInTheIndex"))));
1412   }
1413 
1414   {
1415     auto Completions = completions(
1416         R"cpp(
1417       template <class T>
1418       void foo() {
1419         T::template Y<int>::^
1420       }
1421       )cpp",
1422         {func("::SomeNameInTheIndex")});
1423 
1424     EXPECT_THAT(Completions.Completions,
1425                 Not(Contains(Labeled("SomeNameInTheIndex"))));
1426   }
1427 
1428   {
1429     auto Completions = completions(
1430         R"cpp(
1431       template <class T>
1432       void foo() {
1433         T::foo::^
1434       }
1435       )cpp",
1436         {func("::SomeNameInTheIndex")});
1437 
1438     EXPECT_THAT(Completions.Completions,
1439                 Not(Contains(Labeled("SomeNameInTheIndex"))));
1440   }
1441 }
1442 
1443 TEST(CompletionTest, OverloadBundling) {
1444   clangd::CodeCompleteOptions Opts;
1445   Opts.BundleOverloads = true;
1446 
1447   std::string Context = R"cpp(
1448     struct X {
1449       // Overload with int
1450       int a(int);
1451       // Overload with bool
1452       int a(bool);
1453       int b(float);
1454     };
1455     int GFuncC(int);
1456     int GFuncD(int);
1457   )cpp";
1458 
1459   // Member completions are bundled.
1460   EXPECT_THAT(completions(Context + "int y = X().^", {}, Opts).Completions,
1461               UnorderedElementsAre(Labeled("a(…)"), Labeled("b(float)")));
1462 
1463   // Non-member completions are bundled, including index+sema.
1464   Symbol NoArgsGFunc = func("GFuncC");
1465   EXPECT_THAT(
1466       completions(Context + "int y = GFunc^", {NoArgsGFunc}, Opts).Completions,
1467       UnorderedElementsAre(Labeled("GFuncC(…)"), Labeled("GFuncD(int)")));
1468 
1469   // Differences in header-to-insert suppress bundling.
1470   std::string DeclFile = URI::create(testPath("foo")).toString();
1471   NoArgsGFunc.CanonicalDeclaration.FileURI = DeclFile.c_str();
1472   NoArgsGFunc.IncludeHeaders.emplace_back("<foo>", 1);
1473   EXPECT_THAT(
1474       completions(Context + "int y = GFunc^", {NoArgsGFunc}, Opts).Completions,
1475       UnorderedElementsAre(AllOf(Named("GFuncC"), InsertInclude("<foo>")),
1476                            Labeled("GFuncC(int)"), Labeled("GFuncD(int)")));
1477 
1478   // Examine a bundled completion in detail.
1479   auto A =
1480       completions(Context + "int y = X().a^", {}, Opts).Completions.front();
1481   EXPECT_EQ(A.Name, "a");
1482   EXPECT_EQ(A.Signature, "(…)");
1483   EXPECT_EQ(A.BundleSize, 2u);
1484   EXPECT_EQ(A.Kind, CompletionItemKind::Method);
1485   EXPECT_EQ(A.ReturnType, "int"); // All overloads return int.
1486   // For now we just return one of the doc strings arbitrarily.
1487   EXPECT_THAT(A.Documentation, AnyOf(HasSubstr("Overload with int"),
1488                                      HasSubstr("Overload with bool")));
1489   EXPECT_EQ(A.SnippetSuffix, "($0)");
1490 }
1491 
1492 TEST(CompletionTest, DocumentationFromChangedFileCrash) {
1493   MockFSProvider FS;
1494   auto FooH = testPath("foo.h");
1495   auto FooCpp = testPath("foo.cpp");
1496   FS.Files[FooH] = R"cpp(
1497     // this is my documentation comment.
1498     int func();
1499   )cpp";
1500   FS.Files[FooCpp] = "";
1501 
1502   MockCompilationDatabase CDB;
1503   ClangdServer Server(CDB, FS, ClangdServer::optsForTest());
1504 
1505   Annotations Source(R"cpp(
1506     #include "foo.h"
1507     int func() {
1508       // This makes sure we have func from header in the AST.
1509     }
1510     int a = fun^
1511   )cpp");
1512   Server.addDocument(FooCpp, Source.code(), WantDiagnostics::Yes);
1513   // We need to wait for preamble to build.
1514   ASSERT_TRUE(Server.blockUntilIdleForTest());
1515 
1516   // Change the header file. Completion will reuse the old preamble!
1517   FS.Files[FooH] = R"cpp(
1518     int func();
1519   )cpp";
1520 
1521   clangd::CodeCompleteOptions Opts;
1522   Opts.IncludeComments = true;
1523   CodeCompleteResult Completions =
1524       cantFail(runCodeComplete(Server, FooCpp, Source.point(), Opts));
1525   // We shouldn't crash. Unfortunately, current workaround is to not produce
1526   // comments for symbols from headers.
1527   EXPECT_THAT(Completions.Completions,
1528               Contains(AllOf(Not(IsDocumented()), Named("func"))));
1529 }
1530 
1531 TEST(CompletionTest, NonDocComments) {
1532   MockFSProvider FS;
1533   auto FooCpp = testPath("foo.cpp");
1534   FS.Files[FooCpp] = "";
1535 
1536   MockCompilationDatabase CDB;
1537   ClangdServer Server(CDB, FS, ClangdServer::optsForTest());
1538 
1539   Annotations Source(R"cpp(
1540     // We ignore namespace comments, for rationale see CodeCompletionStrings.h.
1541     namespace comments_ns {
1542     }
1543 
1544     // ------------------
1545     int comments_foo();
1546 
1547     // A comment and a decl are separated by newlines.
1548     // Therefore, the comment shouldn't show up as doc comment.
1549 
1550     int comments_bar();
1551 
1552     // this comment should be in the results.
1553     int comments_baz();
1554 
1555 
1556     template <class T>
1557     struct Struct {
1558       int comments_qux();
1559       int comments_quux();
1560     };
1561 
1562 
1563     // This comment should not be there.
1564 
1565     template <class T>
1566     int Struct<T>::comments_qux() {
1567     }
1568 
1569     // This comment **should** be in results.
1570     template <class T>
1571     int Struct<T>::comments_quux() {
1572       int a = comments^;
1573     }
1574   )cpp");
1575   // FIXME: Auto-completion in a template requires disabling delayed template
1576   // parsing.
1577   CDB.ExtraClangFlags.push_back("-fno-delayed-template-parsing");
1578   runAddDocument(Server, FooCpp, Source.code(), WantDiagnostics::Yes);
1579   CodeCompleteResult Completions = cantFail(runCodeComplete(
1580       Server, FooCpp, Source.point(), clangd::CodeCompleteOptions()));
1581 
1582   // We should not get any of those comments in completion.
1583   EXPECT_THAT(
1584       Completions.Completions,
1585       UnorderedElementsAre(AllOf(Not(IsDocumented()), Named("comments_foo")),
1586                            AllOf(IsDocumented(), Named("comments_baz")),
1587                            AllOf(IsDocumented(), Named("comments_quux")),
1588                            AllOf(Not(IsDocumented()), Named("comments_ns")),
1589                            // FIXME(ibiryukov): the following items should have
1590                            // empty documentation, since they are separated from
1591                            // a comment with an empty line. Unfortunately, I
1592                            // couldn't make Sema tests pass if we ignore those.
1593                            AllOf(IsDocumented(), Named("comments_bar")),
1594                            AllOf(IsDocumented(), Named("comments_qux"))));
1595 }
1596 
1597 TEST(CompletionTest, CompleteOnInvalidLine) {
1598   auto FooCpp = testPath("foo.cpp");
1599 
1600   MockCompilationDatabase CDB;
1601   MockFSProvider FS;
1602   FS.Files[FooCpp] = "// empty file";
1603 
1604   ClangdServer Server(CDB, FS, ClangdServer::optsForTest());
1605   // Run completion outside the file range.
1606   Position Pos;
1607   Pos.line = 100;
1608   Pos.character = 0;
1609   EXPECT_THAT_EXPECTED(
1610       runCodeComplete(Server, FooCpp, Pos, clangd::CodeCompleteOptions()),
1611       Failed());
1612 }
1613 
1614 TEST(CompletionTest, QualifiedNames) {
1615   auto Results = completions(
1616       R"cpp(
1617           namespace ns { int local; void both(); }
1618           void f() { ::ns::^ }
1619       )cpp",
1620       {func("ns::both"), cls("ns::Index")});
1621   // We get results from both index and sema, with no duplicates.
1622   EXPECT_THAT(
1623       Results.Completions,
1624       UnorderedElementsAre(Scope("ns::"), Scope("ns::"), Scope("ns::")));
1625 }
1626 
1627 TEST(CompletionTest, Render) {
1628   CodeCompletion C;
1629   C.Name = "x";
1630   C.Signature = "(bool) const";
1631   C.SnippetSuffix = "(${0:bool})";
1632   C.ReturnType = "int";
1633   C.RequiredQualifier = "Foo::";
1634   C.Scope = "ns::Foo::";
1635   C.Documentation = "This is x().";
1636   C.Includes.emplace_back();
1637   auto &Include = C.Includes.back();
1638   Include.Header = "\"foo.h\"";
1639   C.Kind = CompletionItemKind::Method;
1640   C.Score.Total = 1.0;
1641   C.Score.ExcludingName = .5;
1642   C.Origin = SymbolOrigin::AST | SymbolOrigin::Static;
1643 
1644   CodeCompleteOptions Opts;
1645   Opts.IncludeIndicator.Insert = "^";
1646   Opts.IncludeIndicator.NoInsert = "";
1647   Opts.EnableSnippets = false;
1648 
1649   auto R = C.render(Opts);
1650   EXPECT_EQ(R.label, "Foo::x(bool) const");
1651   EXPECT_EQ(R.insertText, "Foo::x");
1652   EXPECT_EQ(R.insertTextFormat, InsertTextFormat::PlainText);
1653   EXPECT_EQ(R.filterText, "x");
1654   EXPECT_EQ(R.detail, "int\n\"foo.h\"");
1655   EXPECT_EQ(R.documentation, "This is x().");
1656   EXPECT_THAT(R.additionalTextEdits, IsEmpty());
1657   EXPECT_EQ(R.sortText, sortText(1.0, "x"));
1658   EXPECT_FALSE(R.deprecated);
1659   EXPECT_EQ(R.score, .5f);
1660 
1661   Opts.EnableSnippets = true;
1662   R = C.render(Opts);
1663   EXPECT_EQ(R.insertText, "Foo::x(${0:bool})");
1664   EXPECT_EQ(R.insertTextFormat, InsertTextFormat::Snippet);
1665 
1666   Include.Insertion.emplace();
1667   R = C.render(Opts);
1668   EXPECT_EQ(R.label, "^Foo::x(bool) const");
1669   EXPECT_THAT(R.additionalTextEdits, Not(IsEmpty()));
1670 
1671   Opts.ShowOrigins = true;
1672   R = C.render(Opts);
1673   EXPECT_EQ(R.label, "^[AS]Foo::x(bool) const");
1674 
1675   C.BundleSize = 2;
1676   R = C.render(Opts);
1677   EXPECT_EQ(R.detail, "[2 overloads]\n\"foo.h\"");
1678 
1679   C.Deprecated = true;
1680   R = C.render(Opts);
1681   EXPECT_TRUE(R.deprecated);
1682 }
1683 
1684 TEST(CompletionTest, IgnoreRecoveryResults) {
1685   auto Results = completions(
1686       R"cpp(
1687           namespace ns { int NotRecovered() { return 0; } }
1688           void f() {
1689             // Sema enters recovery mode first and then normal mode.
1690             if (auto x = ns::NotRecover^)
1691           }
1692       )cpp");
1693   EXPECT_THAT(Results.Completions, UnorderedElementsAre(Named("NotRecovered")));
1694 }
1695 
1696 TEST(CompletionTest, ScopeOfClassFieldInConstructorInitializer) {
1697   auto Results = completions(
1698       R"cpp(
1699         namespace ns {
1700           class X { public: X(); int x_; };
1701           X::X() : x_^(0) {}
1702         }
1703       )cpp");
1704   EXPECT_THAT(Results.Completions,
1705               UnorderedElementsAre(AllOf(Scope("ns::X::"), Named("x_"))));
1706 }
1707 
1708 TEST(CompletionTest, CodeCompletionContext) {
1709   auto Results = completions(
1710       R"cpp(
1711         namespace ns {
1712           class X { public: X(); int x_; };
1713           void f() {
1714             X x;
1715             x.^;
1716           }
1717         }
1718       )cpp");
1719 
1720   EXPECT_THAT(Results.Context, CodeCompletionContext::CCC_DotMemberAccess);
1721 }
1722 
1723 TEST(CompletionTest, FixItForArrowToDot) {
1724   MockFSProvider FS;
1725   MockCompilationDatabase CDB;
1726   ClangdServer Server(CDB, FS, ClangdServer::optsForTest());
1727 
1728   CodeCompleteOptions Opts;
1729   Opts.IncludeFixIts = true;
1730   Annotations TestCode(
1731       R"cpp(
1732         class Auxilary {
1733          public:
1734           void AuxFunction();
1735         };
1736         class ClassWithPtr {
1737          public:
1738           void MemberFunction();
1739           Auxilary* operator->() const;
1740           Auxilary* Aux;
1741         };
1742         void f() {
1743           ClassWithPtr x;
1744           x[[->]]^;
1745         }
1746       )cpp");
1747   auto Results =
1748       completions(Server, TestCode.code(), TestCode.point(), {}, Opts);
1749   EXPECT_EQ(Results.Completions.size(), 3u);
1750 
1751   TextEdit ReplacementEdit;
1752   ReplacementEdit.range = TestCode.range();
1753   ReplacementEdit.newText = ".";
1754   for (const auto &C : Results.Completions) {
1755     EXPECT_TRUE(C.FixIts.size() == 1u || C.Name == "AuxFunction");
1756     if (!C.FixIts.empty()) {
1757       EXPECT_THAT(C.FixIts, ElementsAre(ReplacementEdit));
1758     }
1759   }
1760 }
1761 
1762 TEST(CompletionTest, FixItForDotToArrow) {
1763   MockFSProvider FS;
1764   MockCompilationDatabase CDB;
1765   ClangdServer Server(CDB, FS, ClangdServer::optsForTest());
1766 
1767   CodeCompleteOptions Opts;
1768   Opts.IncludeFixIts = true;
1769   Annotations TestCode(
1770       R"cpp(
1771         class Auxilary {
1772          public:
1773           void AuxFunction();
1774         };
1775         class ClassWithPtr {
1776          public:
1777           void MemberFunction();
1778           Auxilary* operator->() const;
1779           Auxilary* Aux;
1780         };
1781         void f() {
1782           ClassWithPtr x;
1783           x[[.]]^;
1784         }
1785       )cpp");
1786   auto Results =
1787       completions(Server, TestCode.code(), TestCode.point(), {}, Opts);
1788   EXPECT_EQ(Results.Completions.size(), 3u);
1789 
1790   TextEdit ReplacementEdit;
1791   ReplacementEdit.range = TestCode.range();
1792   ReplacementEdit.newText = "->";
1793   for (const auto &C : Results.Completions) {
1794     EXPECT_TRUE(C.FixIts.empty() || C.Name == "AuxFunction");
1795     if (!C.FixIts.empty()) {
1796       EXPECT_THAT(C.FixIts, ElementsAre(ReplacementEdit));
1797     }
1798   }
1799 }
1800 
1801 TEST(CompletionTest, RenderWithFixItMerged) {
1802   TextEdit FixIt;
1803   FixIt.range.end.character = 5;
1804   FixIt.newText = "->";
1805 
1806   CodeCompletion C;
1807   C.Name = "x";
1808   C.RequiredQualifier = "Foo::";
1809   C.FixIts = {FixIt};
1810   C.CompletionTokenRange.start.character = 5;
1811 
1812   CodeCompleteOptions Opts;
1813   Opts.IncludeFixIts = true;
1814 
1815   auto R = C.render(Opts);
1816   EXPECT_TRUE(R.textEdit);
1817   EXPECT_EQ(R.textEdit->newText, "->Foo::x");
1818   EXPECT_TRUE(R.additionalTextEdits.empty());
1819 }
1820 
1821 TEST(CompletionTest, RenderWithFixItNonMerged) {
1822   TextEdit FixIt;
1823   FixIt.range.end.character = 4;
1824   FixIt.newText = "->";
1825 
1826   CodeCompletion C;
1827   C.Name = "x";
1828   C.RequiredQualifier = "Foo::";
1829   C.FixIts = {FixIt};
1830   C.CompletionTokenRange.start.character = 5;
1831 
1832   CodeCompleteOptions Opts;
1833   Opts.IncludeFixIts = true;
1834 
1835   auto R = C.render(Opts);
1836   EXPECT_TRUE(R.textEdit);
1837   EXPECT_EQ(R.textEdit->newText, "Foo::x");
1838   EXPECT_THAT(R.additionalTextEdits, UnorderedElementsAre(FixIt));
1839 }
1840 
1841 TEST(CompletionTest, CompletionTokenRange) {
1842   MockFSProvider FS;
1843   MockCompilationDatabase CDB;
1844   ClangdServer Server(CDB, FS, ClangdServer::optsForTest());
1845 
1846   constexpr const char *TestCodes[] = {
1847       R"cpp(
1848         class Auxilary {
1849          public:
1850           void AuxFunction();
1851         };
1852         void f() {
1853           Auxilary x;
1854           x.[[Aux]]^;
1855         }
1856       )cpp",
1857       R"cpp(
1858         class Auxilary {
1859          public:
1860           void AuxFunction();
1861         };
1862         void f() {
1863           Auxilary x;
1864           x.[[]]^;
1865         }
1866       )cpp"};
1867   for (const auto &Text : TestCodes) {
1868     Annotations TestCode(Text);
1869     auto Results = completions(Server, TestCode.code(), TestCode.point());
1870 
1871     if (Results.Completions.size() != 1) {
1872       ADD_FAILURE() << "Results.Completions.size() != 1";
1873       continue;
1874     }
1875     EXPECT_THAT(Results.Completions.front().CompletionTokenRange,
1876                 TestCode.range());
1877   }
1878 }
1879 
1880 TEST(SignatureHelpTest, OverloadsOrdering) {
1881   const auto Results = signatures(R"cpp(
1882     void foo(int x);
1883     void foo(int x, float y);
1884     void foo(float x, int y);
1885     void foo(float x, float y);
1886     void foo(int x, int y = 0);
1887     int main() { foo(^); }
1888   )cpp");
1889   EXPECT_THAT(Results.signatures,
1890               ElementsAre(Sig("foo([[int x]]) -> void"),
1891                           Sig("foo([[int x]], [[int y = 0]]) -> void"),
1892                           Sig("foo([[float x]], [[int y]]) -> void"),
1893                           Sig("foo([[int x]], [[float y]]) -> void"),
1894                           Sig("foo([[float x]], [[float y]]) -> void")));
1895   // We always prefer the first signature.
1896   EXPECT_EQ(0, Results.activeSignature);
1897   EXPECT_EQ(0, Results.activeParameter);
1898 }
1899 
1900 TEST(SignatureHelpTest, InstantiatedSignatures) {
1901   StringRef Sig0 = R"cpp(
1902     template <class T>
1903     void foo(T, T, T);
1904 
1905     int main() {
1906       foo<int>(^);
1907     }
1908   )cpp";
1909 
1910   EXPECT_THAT(signatures(Sig0).signatures,
1911               ElementsAre(Sig("foo([[T]], [[T]], [[T]]) -> void")));
1912 
1913   StringRef Sig1 = R"cpp(
1914     template <class T>
1915     void foo(T, T, T);
1916 
1917     int main() {
1918       foo(10, ^);
1919     })cpp";
1920 
1921   EXPECT_THAT(signatures(Sig1).signatures,
1922               ElementsAre(Sig("foo([[T]], [[T]], [[T]]) -> void")));
1923 
1924   StringRef Sig2 = R"cpp(
1925     template <class ...T>
1926     void foo(T...);
1927 
1928     int main() {
1929       foo<int>(^);
1930     }
1931   )cpp";
1932 
1933   EXPECT_THAT(signatures(Sig2).signatures,
1934               ElementsAre(Sig("foo([[T...]]) -> void")));
1935 
1936   // It is debatable whether we should substitute the outer template parameter
1937   // ('T') in that case. Currently we don't substitute it in signature help, but
1938   // do substitute in code complete.
1939   // FIXME: make code complete and signature help consistent, figure out which
1940   // way is better.
1941   StringRef Sig3 = R"cpp(
1942     template <class T>
1943     struct X {
1944       template <class U>
1945       void foo(T, U);
1946     };
1947 
1948     int main() {
1949       X<int>().foo<double>(^)
1950     }
1951   )cpp";
1952 
1953   EXPECT_THAT(signatures(Sig3).signatures,
1954               ElementsAre(Sig("foo([[T]], [[U]]) -> void")));
1955 }
1956 
1957 TEST(SignatureHelpTest, IndexDocumentation) {
1958   Symbol Foo0 = sym("foo", index::SymbolKind::Function, "@F@\\0#");
1959   Foo0.Documentation = "Doc from the index";
1960   Symbol Foo1 = sym("foo", index::SymbolKind::Function, "@F@\\0#I#");
1961   Foo1.Documentation = "Doc from the index";
1962   Symbol Foo2 = sym("foo", index::SymbolKind::Function, "@F@\\0#I#I#");
1963 
1964   StringRef Sig0 = R"cpp(
1965     int foo();
1966     int foo(double);
1967 
1968     void test() {
1969       foo(^);
1970     }
1971   )cpp";
1972 
1973   EXPECT_THAT(
1974       signatures(Sig0, {Foo0}).signatures,
1975       ElementsAre(AllOf(Sig("foo() -> int"), SigDoc("Doc from the index")),
1976                   AllOf(Sig("foo([[double]]) -> int"), SigDoc(""))));
1977 
1978   StringRef Sig1 = R"cpp(
1979     int foo();
1980     // Overriden doc from sema
1981     int foo(int);
1982     // Doc from sema
1983     int foo(int, int);
1984 
1985     void test() {
1986       foo(^);
1987     }
1988   )cpp";
1989 
1990   EXPECT_THAT(
1991       signatures(Sig1, {Foo0, Foo1, Foo2}).signatures,
1992       ElementsAre(
1993           AllOf(Sig("foo() -> int"), SigDoc("Doc from the index")),
1994           AllOf(Sig("foo([[int]]) -> int"), SigDoc("Overriden doc from sema")),
1995           AllOf(Sig("foo([[int]], [[int]]) -> int"), SigDoc("Doc from sema"))));
1996 }
1997 
1998 TEST(SignatureHelpTest, DynamicIndexDocumentation) {
1999   MockFSProvider FS;
2000   MockCompilationDatabase CDB;
2001   ClangdServer::Options Opts = ClangdServer::optsForTest();
2002   Opts.BuildDynamicSymbolIndex = true;
2003   ClangdServer Server(CDB, FS, Opts);
2004 
2005   FS.Files[testPath("foo.h")] = R"cpp(
2006     struct Foo {
2007        // Member doc
2008        int foo();
2009     };
2010   )cpp";
2011   Annotations FileContent(R"cpp(
2012     #include "foo.h"
2013     void test() {
2014       Foo f;
2015       f.foo(^);
2016     }
2017   )cpp");
2018   auto File = testPath("test.cpp");
2019   Server.addDocument(File, FileContent.code());
2020   // Wait for the dynamic index being built.
2021   ASSERT_TRUE(Server.blockUntilIdleForTest());
2022   EXPECT_THAT(
2023       llvm::cantFail(runSignatureHelp(Server, File, FileContent.point()))
2024           .signatures,
2025       ElementsAre(AllOf(Sig("foo() -> int"), SigDoc("Member doc"))));
2026 }
2027 
2028 TEST(CompletionTest, CompletionFunctionArgsDisabled) {
2029   CodeCompleteOptions Opts;
2030   Opts.EnableSnippets = true;
2031   Opts.EnableFunctionArgSnippets = false;
2032 
2033   {
2034     auto Results = completions(
2035         R"cpp(
2036       void xfoo();
2037       void xfoo(int x, int y);
2038       void f() { xfo^ })cpp",
2039         {}, Opts);
2040     EXPECT_THAT(
2041         Results.Completions,
2042         UnorderedElementsAre(AllOf(Named("xfoo"), SnippetSuffix("()")),
2043                              AllOf(Named("xfoo"), SnippetSuffix("($0)"))));
2044   }
2045   {
2046     auto Results = completions(
2047         R"cpp(
2048       void xbar();
2049       void f() { xba^ })cpp",
2050         {}, Opts);
2051     EXPECT_THAT(Results.Completions, UnorderedElementsAre(AllOf(
2052                                          Named("xbar"), SnippetSuffix("()"))));
2053   }
2054   {
2055     Opts.BundleOverloads = true;
2056     auto Results = completions(
2057         R"cpp(
2058       void xfoo();
2059       void xfoo(int x, int y);
2060       void f() { xfo^ })cpp",
2061         {}, Opts);
2062     EXPECT_THAT(
2063         Results.Completions,
2064         UnorderedElementsAre(AllOf(Named("xfoo"), SnippetSuffix("($0)"))));
2065   }
2066   {
2067     auto Results = completions(
2068         R"cpp(
2069       template <class T, class U>
2070       void xfoo(int a, U b);
2071       void f() { xfo^ })cpp",
2072         {}, Opts);
2073     EXPECT_THAT(
2074         Results.Completions,
2075         UnorderedElementsAre(AllOf(Named("xfoo"), SnippetSuffix("<$1>($0)"))));
2076   }
2077   {
2078     auto Results = completions(
2079         R"cpp(
2080       template <class T>
2081       class foo_class{};
2082       template <class T>
2083       using foo_alias = T**;
2084       void f() { foo_^ })cpp",
2085         {}, Opts);
2086     EXPECT_THAT(
2087         Results.Completions,
2088         UnorderedElementsAre(AllOf(Named("foo_class"), SnippetSuffix("<$0>")),
2089                              AllOf(Named("foo_alias"), SnippetSuffix("<$0>"))));
2090   }
2091 }
2092 
2093 TEST(CompletionTest, SuggestOverrides) {
2094   constexpr const char *const Text(R"cpp(
2095   class A {
2096    public:
2097     virtual void vfunc(bool param);
2098     virtual void vfunc(bool param, int p);
2099     void func(bool param);
2100   };
2101   class B : public A {
2102   virtual void ttt(bool param) const;
2103   void vfunc(bool param, int p) override;
2104   };
2105   class C : public B {
2106    public:
2107     void vfunc(bool param) override;
2108     ^
2109   };
2110   )cpp");
2111   const auto Results = completions(Text);
2112   EXPECT_THAT(
2113       Results.Completions,
2114       AllOf(Contains(AllOf(Labeled("void vfunc(bool param, int p) override"),
2115                            NameStartsWith("vfunc"))),
2116             Contains(AllOf(Labeled("void ttt(bool param) const override"),
2117                            NameStartsWith("ttt"))),
2118             Not(Contains(Labeled("void vfunc(bool param) override")))));
2119 }
2120 
2121 TEST(CompletionTest, OverridesNonIdentName) {
2122   // Check the completions call does not crash.
2123   completions(R"cpp(
2124     struct Base {
2125       virtual ~Base() = 0;
2126       virtual operator int() = 0;
2127       virtual Base& operator+(Base&) = 0;
2128     };
2129 
2130     struct Derived : Base {
2131       ^
2132     };
2133   )cpp");
2134 }
2135 
2136 TEST(GuessCompletionPrefix, Filters) {
2137   for (llvm::StringRef Case : {
2138            "[[scope::]][[ident]]^",
2139            "[[]][[]]^",
2140            "\n[[]][[]]^",
2141            "[[]][[ab]]^",
2142            "x.[[]][[ab]]^",
2143            "x.[[]][[]]^",
2144            "[[x::]][[ab]]^",
2145            "[[x::]][[]]^",
2146            "[[::x::]][[ab]]^",
2147            "some text [[scope::more::]][[identif]]^ier",
2148            "some text [[scope::]][[mor]]^e::identifier",
2149            "weird case foo::[[::bar::]][[baz]]^",
2150            "/* [[]][[]]^ */",
2151        }) {
2152     Annotations F(Case);
2153     auto Offset = cantFail(positionToOffset(F.code(), F.point()));
2154     auto ToStringRef = [&](Range R) {
2155       return F.code().slice(cantFail(positionToOffset(F.code(), R.start)),
2156                             cantFail(positionToOffset(F.code(), R.end)));
2157     };
2158     auto WantQualifier = ToStringRef(F.ranges()[0]),
2159          WantName = ToStringRef(F.ranges()[1]);
2160 
2161     auto Prefix = guessCompletionPrefix(F.code(), Offset);
2162     // Even when components are empty, check their offsets are correct.
2163     EXPECT_EQ(WantQualifier, Prefix.Qualifier) << Case;
2164     EXPECT_EQ(WantQualifier.begin(), Prefix.Qualifier.begin()) << Case;
2165     EXPECT_EQ(WantName, Prefix.Name) << Case;
2166     EXPECT_EQ(WantName.begin(), Prefix.Name.begin()) << Case;
2167   }
2168 }
2169 
2170 TEST(CompletionTest, EnableSpeculativeIndexRequest) {
2171   MockFSProvider FS;
2172   MockCompilationDatabase CDB;
2173   ClangdServer Server(CDB, FS, ClangdServer::optsForTest());
2174 
2175   auto File = testPath("foo.cpp");
2176   Annotations Test(R"cpp(
2177       namespace ns1 { int abc; }
2178       namespace ns2 { int abc; }
2179       void f() { ns1::ab$1^; ns1::ab$2^; }
2180       void f2() { ns2::ab$3^; }
2181   )cpp");
2182   runAddDocument(Server, File, Test.code());
2183   clangd::CodeCompleteOptions Opts = {};
2184 
2185   IndexRequestCollector Requests;
2186   Opts.Index = &Requests;
2187   Opts.SpeculativeIndexRequest = true;
2188 
2189   auto CompleteAtPoint = [&](StringRef P) {
2190     cantFail(runCodeComplete(Server, File, Test.point(P), Opts));
2191   };
2192 
2193   CompleteAtPoint("1");
2194   auto Reqs1 = Requests.consumeRequests(1);
2195   ASSERT_EQ(Reqs1.size(), 1u);
2196   EXPECT_THAT(Reqs1[0].Scopes, UnorderedElementsAre("ns1::"));
2197 
2198   CompleteAtPoint("2");
2199   auto Reqs2 = Requests.consumeRequests(1);
2200   // Speculation succeeded. Used speculative index result.
2201   ASSERT_EQ(Reqs2.size(), 1u);
2202   EXPECT_EQ(Reqs2[0], Reqs1[0]);
2203 
2204   CompleteAtPoint("3");
2205   // Speculation failed. Sent speculative index request and the new index
2206   // request after sema.
2207   auto Reqs3 = Requests.consumeRequests(2);
2208   ASSERT_EQ(Reqs3.size(), 2u);
2209 }
2210 
2211 TEST(CompletionTest, InsertTheMostPopularHeader) {
2212   std::string DeclFile = URI::create(testPath("foo")).toString();
2213   Symbol Sym = func("Func");
2214   Sym.CanonicalDeclaration.FileURI = DeclFile.c_str();
2215   Sym.IncludeHeaders.emplace_back("\"foo.h\"", 2);
2216   Sym.IncludeHeaders.emplace_back("\"bar.h\"", 1000);
2217 
2218   auto Results = completions("Fun^", {Sym}).Completions;
2219   assert(!Results.empty());
2220   EXPECT_THAT(Results[0], AllOf(Named("Func"), InsertInclude("\"bar.h\"")));
2221   EXPECT_EQ(Results[0].Includes.size(), 2u);
2222 }
2223 
2224 TEST(CompletionTest, NoInsertIncludeIfOnePresent) {
2225   MockFSProvider FS;
2226   MockCompilationDatabase CDB;
2227 
2228   std::string FooHeader = testPath("foo.h");
2229   FS.Files[FooHeader] = "";
2230 
2231   ClangdServer Server(CDB, FS, ClangdServer::optsForTest());
2232 
2233   std::string DeclFile = URI::create(testPath("foo")).toString();
2234   Symbol Sym = func("Func");
2235   Sym.CanonicalDeclaration.FileURI = DeclFile.c_str();
2236   Sym.IncludeHeaders.emplace_back("\"foo.h\"", 2);
2237   Sym.IncludeHeaders.emplace_back("\"bar.h\"", 1000);
2238 
2239   EXPECT_THAT(
2240       completions(Server, "#include \"foo.h\"\nFun^", {Sym}).Completions,
2241       UnorderedElementsAre(
2242           AllOf(Named("Func"), HasInclude("\"foo.h\""), Not(InsertInclude()))));
2243 }
2244 
2245 TEST(CompletionTest, MergeMacrosFromIndexAndSema) {
2246   Symbol Sym;
2247   Sym.Name = "Clangd_Macro_Test";
2248   Sym.ID = SymbolID("c:foo.cpp@8@macro@Clangd_Macro_Test");
2249   Sym.SymInfo.Kind = index::SymbolKind::Macro;
2250   Sym.Flags |= Symbol::IndexedForCodeCompletion;
2251   EXPECT_THAT(completions("#define Clangd_Macro_Test\nClangd_Macro_T^", {Sym})
2252                   .Completions,
2253               UnorderedElementsAre(Named("Clangd_Macro_Test")));
2254 }
2255 
2256 TEST(CompletionTest, MacroFromPreamble) {
2257   MockFSProvider FS;
2258   MockCompilationDatabase CDB;
2259   std::string FooHeader = testPath("foo.h");
2260   FS.Files[FooHeader] = "#define CLANGD_PREAMBLE_HEADER x\n";
2261   ClangdServer Server(CDB, FS, ClangdServer::optsForTest());
2262   auto Results = completions(
2263       R"cpp(#include "foo.h"
2264           #define CLANGD_PREAMBLE_MAIN x
2265 
2266           int x = 0;
2267           #define CLANGD_MAIN x
2268           void f() { CLANGD_^ }
2269       )cpp",
2270       {func("CLANGD_INDEX")});
2271   // We should get results from the main file, including the preamble section.
2272   // However no results from included files (the index should cover them).
2273   EXPECT_THAT(Results.Completions,
2274               UnorderedElementsAre(Named("CLANGD_PREAMBLE_MAIN"),
2275                                    Named("CLANGD_MAIN"),
2276                                    Named("CLANGD_INDEX")));
2277 }
2278 
2279 TEST(CompletionTest, DeprecatedResults) {
2280   std::string Body = R"cpp(
2281     void TestClangd();
2282     void TestClangc() __attribute__((deprecated("", "")));
2283   )cpp";
2284 
2285   EXPECT_THAT(
2286       completions(Body + "int main() { TestClang^ }").Completions,
2287       UnorderedElementsAre(AllOf(Named("TestClangd"), Not(Deprecated())),
2288                            AllOf(Named("TestClangc"), Deprecated())));
2289 }
2290 
2291 TEST(SignatureHelpTest, PartialSpec) {
2292   const auto Results = signatures(R"cpp(
2293       template <typename T> struct Foo {};
2294       template <typename T> struct Foo<T*> { Foo(T); };
2295       Foo<int*> F(^);)cpp");
2296   EXPECT_THAT(Results.signatures, Contains(Sig("Foo([[T]])")));
2297   EXPECT_EQ(0, Results.activeParameter);
2298 }
2299 
2300 TEST(SignatureHelpTest, InsideArgument) {
2301   {
2302     const auto Results = signatures(R"cpp(
2303       void foo(int x);
2304       void foo(int x, int y);
2305       int main() { foo(1+^); }
2306     )cpp");
2307     EXPECT_THAT(Results.signatures,
2308                 ElementsAre(Sig("foo([[int x]]) -> void"),
2309                             Sig("foo([[int x]], [[int y]]) -> void")));
2310     EXPECT_EQ(0, Results.activeParameter);
2311   }
2312   {
2313     const auto Results = signatures(R"cpp(
2314       void foo(int x);
2315       void foo(int x, int y);
2316       int main() { foo(1^); }
2317     )cpp");
2318     EXPECT_THAT(Results.signatures,
2319                 ElementsAre(Sig("foo([[int x]]) -> void"),
2320                             Sig("foo([[int x]], [[int y]]) -> void")));
2321     EXPECT_EQ(0, Results.activeParameter);
2322   }
2323   {
2324     const auto Results = signatures(R"cpp(
2325       void foo(int x);
2326       void foo(int x, int y);
2327       int main() { foo(1^0); }
2328     )cpp");
2329     EXPECT_THAT(Results.signatures,
2330                 ElementsAre(Sig("foo([[int x]]) -> void"),
2331                             Sig("foo([[int x]], [[int y]]) -> void")));
2332     EXPECT_EQ(0, Results.activeParameter);
2333   }
2334   {
2335     const auto Results = signatures(R"cpp(
2336       void foo(int x);
2337       void foo(int x, int y);
2338       int bar(int x, int y);
2339       int main() { bar(foo(2, 3^)); }
2340     )cpp");
2341     EXPECT_THAT(Results.signatures,
2342                 ElementsAre(Sig("foo([[int x]], [[int y]]) -> void")));
2343     EXPECT_EQ(1, Results.activeParameter);
2344   }
2345 }
2346 
2347 TEST(SignatureHelpTest, ConstructorInitializeFields) {
2348   {
2349     const auto Results = signatures(R"cpp(
2350       struct A {
2351         A(int);
2352       };
2353       struct B {
2354         B() : a_elem(^) {}
2355         A a_elem;
2356       };
2357     )cpp");
2358     EXPECT_THAT(Results.signatures,
2359                 UnorderedElementsAre(Sig("A([[int]])"), Sig("A([[A &&]])"),
2360                                      Sig("A([[const A &]])")));
2361   }
2362   {
2363     const auto Results = signatures(R"cpp(
2364       struct A {
2365         A(int);
2366       };
2367       struct C {
2368         C(int);
2369         C(A);
2370       };
2371       struct B {
2372         B() : c_elem(A(1^)) {}
2373         C c_elem;
2374       };
2375     )cpp");
2376     EXPECT_THAT(Results.signatures,
2377                 UnorderedElementsAre(Sig("A([[int]])"), Sig("A([[A &&]])"),
2378                                      Sig("A([[const A &]])")));
2379   }
2380 }
2381 
2382 TEST(CompletionTest, IncludedCompletionKinds) {
2383   MockFSProvider FS;
2384   MockCompilationDatabase CDB;
2385   std::string Subdir = testPath("sub");
2386   std::string SearchDirArg = (Twine("-I") + Subdir).str();
2387   CDB.ExtraClangFlags = {SearchDirArg.c_str()};
2388   std::string BarHeader = testPath("sub/bar.h");
2389   FS.Files[BarHeader] = "";
2390   ClangdServer Server(CDB, FS, ClangdServer::optsForTest());
2391   auto Results = completions(Server,
2392                              R"cpp(
2393         #include "^"
2394       )cpp");
2395   EXPECT_THAT(Results.Completions,
2396               AllOf(Has("sub/", CompletionItemKind::Folder),
2397                     Has("bar.h\"", CompletionItemKind::File)));
2398 }
2399 
2400 TEST(CompletionTest, NoCrashAtNonAlphaIncludeHeader) {
2401   auto Results = completions(
2402       R"cpp(
2403         #include "./^"
2404       )cpp");
2405   EXPECT_TRUE(Results.Completions.empty());
2406 }
2407 
2408 TEST(CompletionTest, NoAllScopesCompletionWhenQualified) {
2409   clangd::CodeCompleteOptions Opts = {};
2410   Opts.AllScopes = true;
2411 
2412   auto Results = completions(
2413       R"cpp(
2414     void f() { na::Clangd^ }
2415   )cpp",
2416       {cls("na::ClangdA"), cls("nx::ClangdX"), cls("Clangd3")}, Opts);
2417   EXPECT_THAT(Results.Completions,
2418               UnorderedElementsAre(
2419                   AllOf(Qualifier(""), Scope("na::"), Named("ClangdA"))));
2420 }
2421 
2422 TEST(CompletionTest, AllScopesCompletion) {
2423   clangd::CodeCompleteOptions Opts = {};
2424   Opts.AllScopes = true;
2425 
2426   auto Results = completions(
2427       R"cpp(
2428     namespace na {
2429     void f() { Clangd^ }
2430     }
2431   )cpp",
2432       {cls("nx::Clangd1"), cls("ny::Clangd2"), cls("Clangd3"),
2433        cls("na::nb::Clangd4")},
2434       Opts);
2435   EXPECT_THAT(
2436       Results.Completions,
2437       UnorderedElementsAre(AllOf(Qualifier("nx::"), Named("Clangd1")),
2438                            AllOf(Qualifier("ny::"), Named("Clangd2")),
2439                            AllOf(Qualifier(""), Scope(""), Named("Clangd3")),
2440                            AllOf(Qualifier("nb::"), Named("Clangd4"))));
2441 }
2442 
2443 TEST(CompletionTest, NoQualifierIfShadowed) {
2444   clangd::CodeCompleteOptions Opts = {};
2445   Opts.AllScopes = true;
2446 
2447   auto Results = completions(R"cpp(
2448     namespace nx { class Clangd1 {}; }
2449     using nx::Clangd1;
2450     void f() { Clangd^ }
2451   )cpp",
2452                              {cls("nx::Clangd1"), cls("nx::Clangd2")}, Opts);
2453   // Although Clangd1 is from another namespace, Sema tells us it's in-scope and
2454   // needs no qualifier.
2455   EXPECT_THAT(Results.Completions,
2456               UnorderedElementsAre(AllOf(Qualifier(""), Named("Clangd1")),
2457                                    AllOf(Qualifier("nx::"), Named("Clangd2"))));
2458 }
2459 
2460 TEST(CompletionTest, NoCompletionsForNewNames) {
2461   clangd::CodeCompleteOptions Opts;
2462   Opts.AllScopes = true;
2463   auto Results = completions(R"cpp(
2464       void f() { int n^ }
2465     )cpp",
2466                              {cls("naber"), cls("nx::naber")}, Opts);
2467   EXPECT_THAT(Results.Completions, UnorderedElementsAre());
2468 }
2469 
2470 TEST(CompletionTest, Lambda) {
2471   clangd::CodeCompleteOptions Opts = {};
2472 
2473   auto Results = completions(R"cpp(
2474     void function() {
2475       auto Lambda = [](int a, const double &b) {return 1.f;};
2476       Lam^
2477     }
2478   )cpp",
2479                              {}, Opts);
2480 
2481   ASSERT_EQ(Results.Completions.size(), 1u);
2482   const auto &A = Results.Completions.front();
2483   EXPECT_EQ(A.Name, "Lambda");
2484   EXPECT_EQ(A.Signature, "(int a, const double &b) const");
2485   EXPECT_EQ(A.Kind, CompletionItemKind::Variable);
2486   EXPECT_EQ(A.ReturnType, "float");
2487   EXPECT_EQ(A.SnippetSuffix, "(${1:int a}, ${2:const double &b})");
2488 }
2489 
2490 TEST(CompletionTest, ObjectiveCMethodNoArguments) {
2491   auto Results = completions(R"objc(
2492       @interface Foo
2493       @property(nonatomic, setter=setXToIgnoreComplete:) int value;
2494       @end
2495       Foo *foo = [Foo new]; int y = [foo v^]
2496     )objc",
2497                              /*IndexSymbols=*/{},
2498                              /*Opts=*/{}, "Foo.m");
2499 
2500   auto C = Results.Completions;
2501   EXPECT_THAT(C, ElementsAre(Named("value")));
2502   EXPECT_THAT(C, ElementsAre(Kind(CompletionItemKind::Method)));
2503   EXPECT_THAT(C, ElementsAre(ReturnType("int")));
2504   EXPECT_THAT(C, ElementsAre(Signature("")));
2505   EXPECT_THAT(C, ElementsAre(SnippetSuffix("")));
2506 }
2507 
2508 TEST(CompletionTest, ObjectiveCMethodOneArgument) {
2509   auto Results = completions(R"objc(
2510       @interface Foo
2511       - (int)valueForCharacter:(char)c;
2512       @end
2513       Foo *foo = [Foo new]; int y = [foo v^]
2514     )objc",
2515                              /*IndexSymbols=*/{},
2516                              /*Opts=*/{}, "Foo.m");
2517 
2518   auto C = Results.Completions;
2519   EXPECT_THAT(C, ElementsAre(Named("valueForCharacter:")));
2520   EXPECT_THAT(C, ElementsAre(Kind(CompletionItemKind::Method)));
2521   EXPECT_THAT(C, ElementsAre(ReturnType("int")));
2522   EXPECT_THAT(C, ElementsAre(Signature("(char)")));
2523   EXPECT_THAT(C, ElementsAre(SnippetSuffix("${1:(char)}")));
2524 }
2525 
2526 TEST(CompletionTest, ObjectiveCMethodTwoArgumentsFromBeginning) {
2527   auto Results = completions(R"objc(
2528       @interface Foo
2529       + (id)fooWithValue:(int)value fooey:(unsigned int)fooey;
2530       @end
2531       id val = [Foo foo^]
2532     )objc",
2533                              /*IndexSymbols=*/{},
2534                              /*Opts=*/{}, "Foo.m");
2535 
2536   auto C = Results.Completions;
2537   EXPECT_THAT(C, ElementsAre(Named("fooWithValue:")));
2538   EXPECT_THAT(C, ElementsAre(Kind(CompletionItemKind::Method)));
2539   EXPECT_THAT(C, ElementsAre(ReturnType("id")));
2540   EXPECT_THAT(C, ElementsAre(Signature("(int) fooey:(unsigned int)")));
2541   EXPECT_THAT(
2542       C, ElementsAre(SnippetSuffix("${1:(int)} fooey:${2:(unsigned int)}")));
2543 }
2544 
2545 TEST(CompletionTest, ObjectiveCMethodTwoArgumentsFromMiddle) {
2546   auto Results = completions(R"objc(
2547       @interface Foo
2548       + (id)fooWithValue:(int)value fooey:(unsigned int)fooey;
2549       @end
2550       id val = [Foo fooWithValue:10 f^]
2551     )objc",
2552                              /*IndexSymbols=*/{},
2553                              /*Opts=*/{}, "Foo.m");
2554 
2555   auto C = Results.Completions;
2556   EXPECT_THAT(C, ElementsAre(Named("fooey:")));
2557   EXPECT_THAT(C, ElementsAre(Kind(CompletionItemKind::Method)));
2558   EXPECT_THAT(C, ElementsAre(ReturnType("id")));
2559   EXPECT_THAT(C, ElementsAre(Signature("(unsigned int)")));
2560   EXPECT_THAT(C, ElementsAre(SnippetSuffix("${1:(unsigned int)}")));
2561 }
2562 
2563 TEST(CompletionTest, CursorInSnippets) {
2564   clangd::CodeCompleteOptions Options;
2565   Options.EnableSnippets = true;
2566   auto Results = completions(
2567       R"cpp(
2568     void while_foo(int a, int b);
2569     void test() {
2570       whil^
2571     })cpp",
2572       /*IndexSymbols=*/{}, Options);
2573 
2574   // Last placeholder in code patterns should be $0 to put the cursor there.
2575   EXPECT_THAT(Results.Completions,
2576               Contains(AllOf(
2577                   Named("while"),
2578                   SnippetSuffix(" (${1:condition}) {\n${0:statements}\n}"))));
2579   // However, snippets for functions must *not* end with $0.
2580   EXPECT_THAT(Results.Completions,
2581               Contains(AllOf(Named("while_foo"),
2582                              SnippetSuffix("(${1:int a}, ${2:int b})"))));
2583 }
2584 
2585 TEST(CompletionTest, WorksWithNullType) {
2586   auto R = completions(R"cpp(
2587     int main() {
2588       for (auto [loopVar] : y ) { // y has to be unresolved.
2589         int z = loopV^;
2590       }
2591     }
2592   )cpp");
2593   EXPECT_THAT(R.Completions, ElementsAre(Named("loopVar")));
2594 }
2595 
2596 TEST(CompletionTest, UsingDecl) {
2597   const char *Header(R"cpp(
2598     void foo(int);
2599     namespace std {
2600       using ::foo;
2601     })cpp");
2602   const char *Source(R"cpp(
2603     void bar() {
2604       std::^;
2605     })cpp");
2606   auto Index = TestTU::withHeaderCode(Header).index();
2607   clangd::CodeCompleteOptions Opts;
2608   Opts.Index = Index.get();
2609   Opts.AllScopes = true;
2610   auto R = completions(Source, {}, Opts);
2611   EXPECT_THAT(R.Completions,
2612               ElementsAre(AllOf(Scope("std::"), Named("foo"),
2613                                 Kind(CompletionItemKind::Reference))));
2614 }
2615 
2616 TEST(CompletionTest, ScopeIsUnresolved) {
2617   clangd::CodeCompleteOptions Opts = {};
2618   Opts.AllScopes = true;
2619 
2620   auto Results = completions(R"cpp(
2621     namespace a {
2622     void f() { b::X^ }
2623     }
2624   )cpp",
2625                              {cls("a::b::XYZ")}, Opts);
2626   EXPECT_THAT(Results.Completions,
2627               UnorderedElementsAre(AllOf(Qualifier(""), Named("XYZ"))));
2628 }
2629 
2630 TEST(CompletionTest, NestedScopeIsUnresolved) {
2631   clangd::CodeCompleteOptions Opts = {};
2632   Opts.AllScopes = true;
2633 
2634   auto Results = completions(R"cpp(
2635     namespace a {
2636     namespace b {}
2637     void f() { b::c::X^ }
2638     }
2639   )cpp",
2640                              {cls("a::b::c::XYZ")}, Opts);
2641   EXPECT_THAT(Results.Completions,
2642               UnorderedElementsAre(AllOf(Qualifier(""), Named("XYZ"))));
2643 }
2644 
2645 // Clang parser gets confused here and doesn't report the ns:: prefix.
2646 // Naive behavior is to insert it again. We examine the source and recover.
2647 TEST(CompletionTest, NamespaceDoubleInsertion) {
2648   clangd::CodeCompleteOptions Opts = {};
2649 
2650   auto Results = completions(R"cpp(
2651     namespace foo {
2652     namespace ns {}
2653     #define M(X) < X
2654     M(ns::ABC^
2655     }
2656   )cpp",
2657                              {cls("foo::ns::ABCDE")}, Opts);
2658   EXPECT_THAT(Results.Completions,
2659               UnorderedElementsAre(AllOf(Qualifier(""), Named("ABCDE"))));
2660 }
2661 
2662 TEST(CompletionTest, DerivedMethodsAreAlwaysVisible) {
2663   // Despite the fact that base method matches the ref-qualifier better,
2664   // completion results should only include the derived method.
2665   auto Completions = completions(R"cpp(
2666     struct deque_base {
2667       float size();
2668       double size() const;
2669     };
2670     struct deque : deque_base {
2671         int size() const;
2672     };
2673 
2674     auto x = deque().^
2675   )cpp")
2676                          .Completions;
2677   EXPECT_THAT(Completions,
2678               ElementsAre(AllOf(ReturnType("int"), Named("size"))));
2679 }
2680 
2681 TEST(CompletionTest, NoCrashWithIncompleteLambda) {
2682   auto Completions = completions("auto&& x = []{^").Completions;
2683   // The completion of x itself can cause a problem: in the code completion
2684   // callback, its type is not known, which affects the linkage calculation.
2685   // A bad linkage value gets cached, and subsequently updated.
2686   EXPECT_THAT(Completions, Contains(Named("x")));
2687 
2688   auto Signatures = signatures("auto x() { x(^").signatures;
2689   EXPECT_THAT(Signatures, Contains(Sig("x() -> auto")));
2690 }
2691 
2692 TEST(CompletionTest, CompletionRange) {
2693   const char *WithRange = "auto x = [[abc]]^";
2694   auto Completions = completions(WithRange);
2695   EXPECT_EQ(Completions.CompletionRange, Annotations(WithRange).range());
2696   Completions = completionsNoCompile(WithRange);
2697   EXPECT_EQ(Completions.CompletionRange, Annotations(WithRange).range());
2698 
2699   const char *EmptyRange = "auto x = [[]]^";
2700   Completions = completions(EmptyRange);
2701   EXPECT_EQ(Completions.CompletionRange, Annotations(EmptyRange).range());
2702   Completions = completionsNoCompile(EmptyRange);
2703   EXPECT_EQ(Completions.CompletionRange, Annotations(EmptyRange).range());
2704 
2705   // Sema doesn't trigger at all here, while the no-sema completion runs
2706   // heuristics as normal and reports a range. It'd be nice to be consistent.
2707   const char *NoCompletion = "/* [[]]^ */";
2708   Completions = completions(NoCompletion);
2709   EXPECT_EQ(Completions.CompletionRange, llvm::None);
2710   Completions = completionsNoCompile(NoCompletion);
2711   EXPECT_EQ(Completions.CompletionRange, Annotations(NoCompletion).range());
2712 }
2713 
2714 TEST(NoCompileCompletionTest, Basic) {
2715   auto Results = completionsNoCompile(R"cpp(
2716     void func() {
2717       int xyz;
2718       int abc;
2719       ^
2720     }
2721   )cpp");
2722   EXPECT_FALSE(Results.RanParser);
2723   EXPECT_THAT(Results.Completions,
2724               UnorderedElementsAre(Named("void"), Named("func"), Named("int"),
2725                                    Named("xyz"), Named("abc")));
2726 }
2727 
2728 TEST(NoCompileCompletionTest, WithFilter) {
2729   auto Results = completionsNoCompile(R"cpp(
2730     void func() {
2731       int sym1;
2732       int sym2;
2733       int xyz1;
2734       int xyz2;
2735       sy^
2736     }
2737   )cpp");
2738   EXPECT_THAT(Results.Completions,
2739               UnorderedElementsAre(Named("sym1"), Named("sym2")));
2740 }
2741 
2742 TEST(NoCompileCompletionTest, WithIndex) {
2743   std::vector<Symbol> Syms = {func("xxx"), func("a::xxx"), func("ns::b::xxx"),
2744                               func("c::xxx"), func("ns::d::xxx")};
2745   auto Results = completionsNoCompile(
2746       R"cpp(
2747         // Current-scopes, unqualified completion.
2748         using namespace a;
2749         namespace ns {
2750         using namespace b;
2751         void foo() {
2752         xx^
2753         }
2754         }
2755       )cpp",
2756       Syms);
2757   EXPECT_THAT(Results.Completions,
2758               UnorderedElementsAre(AllOf(Qualifier(""), Scope("")),
2759                                    AllOf(Qualifier(""), Scope("a::")),
2760                                    AllOf(Qualifier(""), Scope("ns::b::"))));
2761   CodeCompleteOptions Opts;
2762   Opts.AllScopes = true;
2763   Results = completionsNoCompile(
2764       R"cpp(
2765         // All-scopes unqualified completion.
2766         using namespace a;
2767         namespace ns {
2768         using namespace b;
2769         void foo() {
2770         xx^
2771         }
2772         }
2773       )cpp",
2774       Syms, Opts);
2775   EXPECT_THAT(Results.Completions,
2776               UnorderedElementsAre(AllOf(Qualifier(""), Scope("")),
2777                                    AllOf(Qualifier(""), Scope("a::")),
2778                                    AllOf(Qualifier(""), Scope("ns::b::")),
2779                                    AllOf(Qualifier("c::"), Scope("c::")),
2780                                    AllOf(Qualifier("d::"), Scope("ns::d::"))));
2781   Results = completionsNoCompile(
2782       R"cpp(
2783         // Qualified completion.
2784         using namespace a;
2785         namespace ns {
2786         using namespace b;
2787         void foo() {
2788         b::xx^
2789         }
2790         }
2791       )cpp",
2792       Syms, Opts);
2793   EXPECT_THAT(Results.Completions,
2794               ElementsAre(AllOf(Qualifier(""), Scope("ns::b::"))));
2795   Results = completionsNoCompile(
2796       R"cpp(
2797         // Absolutely qualified completion.
2798         using namespace a;
2799         namespace ns {
2800         using namespace b;
2801         void foo() {
2802         ::a::xx^
2803         }
2804         }
2805       )cpp",
2806       Syms, Opts);
2807   EXPECT_THAT(Results.Completions,
2808               ElementsAre(AllOf(Qualifier(""), Scope("a::"))));
2809 }
2810 
2811 } // namespace
2812 } // namespace clangd
2813 } // namespace clang
2814