blob: 80e5f91430e8a7731f973116efde67b12c732562 [file] [log] [blame]
Sam McCall9aad25f2017-12-05 07:20:26 +00001//===-- CodeCompleteTests.cpp -----------------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
Eric Liu6f648df2017-12-19 16:50:37 +00009
Sam McCall328cbdb2017-12-20 16:06:05 +000010#include "Annotations.h"
Sam McCall9aad25f2017-12-05 07:20:26 +000011#include "ClangdServer.h"
Sam McCall328cbdb2017-12-20 16:06:05 +000012#include "CodeComplete.h"
Sam McCall9aad25f2017-12-05 07:20:26 +000013#include "Compiler.h"
Ilya Biryukov5a85b8e2017-12-13 12:53:16 +000014#include "Matchers.h"
Sam McCall9aad25f2017-12-05 07:20:26 +000015#include "Protocol.h"
Sam McCalle746a2b2018-07-02 11:13:16 +000016#include "Quality.h"
Sam McCallb536a2a2017-12-19 12:23:48 +000017#include "SourceCode.h"
Ilya Biryukovcd5eb002018-02-12 11:37:28 +000018#include "SyncAPI.h"
Sam McCall9aad25f2017-12-05 07:20:26 +000019#include "TestFS.h"
Eric Liu6f648df2017-12-19 16:50:37 +000020#include "index/MemIndex.h"
Eric Liu5d2a8072018-07-23 10:56:37 +000021#include "clang/Sema/CodeCompleteConsumer.h"
Ilya Biryukovbe0eb8f2018-05-24 14:49:23 +000022#include "llvm/Support/Error.h"
Ilya Biryukov981a35d2018-05-28 12:11:37 +000023#include "llvm/Testing/Support/Error.h"
Sam McCallf6ae3232017-12-05 20:11:29 +000024#include "gmock/gmock.h"
Sam McCall9aad25f2017-12-05 07:20:26 +000025#include "gtest/gtest.h"
26
27namespace clang {
28namespace clangd {
Sam McCallf6ae3232017-12-05 20:11:29 +000029
Sam McCall9aad25f2017-12-05 07:20:26 +000030namespace {
31using namespace llvm;
Sam McCallf6ae3232017-12-05 20:11:29 +000032using ::testing::AllOf;
33using ::testing::Contains;
Ilya Biryukov5a5e1ca2017-12-29 14:59:22 +000034using ::testing::Each;
Sam McCallf6ae3232017-12-05 20:11:29 +000035using ::testing::ElementsAre;
Ilya Biryukov71028b82018-03-12 15:28:22 +000036using ::testing::Field;
Sam McCallc18c2802018-06-15 11:06:29 +000037using ::testing::HasSubstr;
Marc-Andre Laperle945b5a32018-06-05 14:01:40 +000038using ::testing::IsEmpty;
Sam McCallf6ae3232017-12-05 20:11:29 +000039using ::testing::Not;
Sam McCall3d139c52018-01-12 18:30:08 +000040using ::testing::UnorderedElementsAre;
Sam McCall9aad25f2017-12-05 07:20:26 +000041
42class IgnoreDiagnostics : public DiagnosticsConsumer {
Ilya Biryukov71028b82018-03-12 15:28:22 +000043 void onDiagnosticsReady(PathRef File,
Sam McCalla7bb0cc2018-03-12 23:22:35 +000044 std::vector<Diag> Diagnostics) override {}
Sam McCall9aad25f2017-12-05 07:20:26 +000045};
46
Sam McCallf6ae3232017-12-05 20:11:29 +000047// GMock helpers for matching completion items.
Sam McCalle746a2b2018-07-02 11:13:16 +000048MATCHER_P(Named, Name, "") { return arg.Name == Name; }
49MATCHER_P(Scope, S, "") { return arg.Scope == S; }
50MATCHER_P(Qualifier, Q, "") { return arg.RequiredQualifier == Q; }
Eric Liu8f3678d2018-06-15 13:34:18 +000051MATCHER_P(Labeled, Label, "") {
Sam McCalle746a2b2018-07-02 11:13:16 +000052 return arg.RequiredQualifier + arg.Name + arg.Signature == Label;
Eric Liu8f3678d2018-06-15 13:34:18 +000053}
54MATCHER_P(SigHelpLabeled, Label, "") { return arg.label == Label; }
Sam McCalle746a2b2018-07-02 11:13:16 +000055MATCHER_P(Kind, K, "") { return arg.Kind == K; }
56MATCHER_P(Doc, D, "") { return arg.Documentation == D; }
57MATCHER_P(ReturnType, D, "") { return arg.ReturnType == D; }
Eric Liu83f63e42018-09-03 10:18:21 +000058MATCHER_P(HasInclude, IncludeHeader, "") {
59 return !arg.Includes.empty() && arg.Includes[0].Header == IncludeHeader;
Eric Liu63f419a2018-05-15 15:29:32 +000060}
Eric Liu83f63e42018-09-03 10:18:21 +000061MATCHER_P(InsertInclude, IncludeHeader, "") {
62 return !arg.Includes.empty() && arg.Includes[0].Header == IncludeHeader &&
63 bool(arg.Includes[0].Insertion);
64}
65MATCHER(InsertInclude, "") {
66 return !arg.Includes.empty() && bool(arg.Includes[0].Insertion);
67}
Sam McCalle746a2b2018-07-02 11:13:16 +000068MATCHER_P(SnippetSuffix, Text, "") { return arg.SnippetSuffix == Text; }
Sam McCall2161ec72018-07-05 06:20:41 +000069MATCHER_P(Origin, OriginSet, "") { return arg.Origin == OriginSet; }
Eric Liu63f419a2018-05-15 15:29:32 +000070
Sam McCallf6ae3232017-12-05 20:11:29 +000071// Shorthand for Contains(Named(Name)).
Sam McCalle746a2b2018-07-02 11:13:16 +000072Matcher<const std::vector<CodeCompletion> &> Has(std::string Name) {
Sam McCallf6ae3232017-12-05 20:11:29 +000073 return Contains(Named(std::move(Name)));
74}
Sam McCalle746a2b2018-07-02 11:13:16 +000075Matcher<const std::vector<CodeCompletion> &> Has(std::string Name,
Sam McCall44fdcec22017-12-08 15:00:59 +000076 CompletionItemKind K) {
77 return Contains(AllOf(Named(std::move(Name)), Kind(K)));
Sam McCallf6ae3232017-12-05 20:11:29 +000078}
Sam McCalle746a2b2018-07-02 11:13:16 +000079MATCHER(IsDocumented, "") { return !arg.Documentation.empty(); }
Sam McCall9aad25f2017-12-05 07:20:26 +000080
Sam McCalla15c2d62018-01-18 09:27:56 +000081std::unique_ptr<SymbolIndex> memIndex(std::vector<Symbol> Symbols) {
82 SymbolSlab::Builder Slab;
83 for (const auto &Sym : Symbols)
84 Slab.insert(Sym);
Haojian Wue8064b62018-08-31 19:53:37 +000085 return MemIndex::build(std::move(Slab).build(),
86 SymbolOccurrenceSlab::createEmpty());
Sam McCalla15c2d62018-01-18 09:27:56 +000087}
88
Kadir Cetinkaya2f84d912018-08-08 08:59:29 +000089CodeCompleteResult completions(ClangdServer &Server, StringRef TestCode,
90 Position point,
91 std::vector<Symbol> IndexSymbols = {},
92 clangd::CodeCompleteOptions Opts = {}) {
93 std::unique_ptr<SymbolIndex> OverrideIndex;
94 if (!IndexSymbols.empty()) {
95 assert(!Opts.Index && "both Index and IndexSymbols given!");
96 OverrideIndex = memIndex(std::move(IndexSymbols));
97 Opts.Index = OverrideIndex.get();
98 }
99
100 auto File = testPath("foo.cpp");
101 runAddDocument(Server, File, TestCode);
102 auto CompletionList = cantFail(runCodeComplete(Server, File, point, Opts));
103 return CompletionList;
104}
105
Sam McCalle746a2b2018-07-02 11:13:16 +0000106CodeCompleteResult completions(ClangdServer &Server, StringRef Text,
107 std::vector<Symbol> IndexSymbols = {},
108 clangd::CodeCompleteOptions Opts = {}) {
Sam McCalla15c2d62018-01-18 09:27:56 +0000109 std::unique_ptr<SymbolIndex> OverrideIndex;
110 if (!IndexSymbols.empty()) {
111 assert(!Opts.Index && "both Index and IndexSymbols given!");
112 OverrideIndex = memIndex(std::move(IndexSymbols));
113 Opts.Index = OverrideIndex.get();
114 }
115
Sam McCallc1568062018-02-16 09:41:43 +0000116 auto File = testPath("foo.cpp");
Sam McCall328cbdb2017-12-20 16:06:05 +0000117 Annotations Test(Text);
Sam McCall7363a2f2018-03-05 17:28:54 +0000118 runAddDocument(Server, File, Test.code());
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000119 auto CompletionList =
120 cantFail(runCodeComplete(Server, File, Test.point(), Opts));
Ilya Biryukov5a5e1ca2017-12-29 14:59:22 +0000121 return CompletionList;
Sam McCall9aad25f2017-12-05 07:20:26 +0000122}
123
Eric Liu63f419a2018-05-15 15:29:32 +0000124// Builds a server and runs code completion.
125// If IndexSymbols is non-empty, an index will be built and passed to opts.
Sam McCalle746a2b2018-07-02 11:13:16 +0000126CodeCompleteResult completions(StringRef Text,
127 std::vector<Symbol> IndexSymbols = {},
128 clangd::CodeCompleteOptions Opts = {}) {
Eric Liu63f419a2018-05-15 15:29:32 +0000129 MockFSProvider FS;
130 MockCompilationDatabase CDB;
131 IgnoreDiagnostics DiagConsumer;
132 ClangdServer Server(CDB, FS, DiagConsumer, ClangdServer::optsForTest());
133 return completions(Server, Text, std::move(IndexSymbols), std::move(Opts));
134}
135
Sam McCall545a20d2018-01-19 14:34:02 +0000136std::string replace(StringRef Haystack, StringRef Needle, StringRef Repl) {
137 std::string Result;
138 raw_string_ostream OS(Result);
139 std::pair<StringRef, StringRef> Split;
140 for (Split = Haystack.split(Needle); !Split.second.empty();
141 Split = Split.first.split(Needle))
142 OS << Split.first << Repl;
143 Result += Split.first;
144 OS.flush();
145 return Result;
146}
147
Sam McCalla15c2d62018-01-18 09:27:56 +0000148// Helpers to produce fake index symbols for memIndex() or completions().
Sam McCall545a20d2018-01-19 14:34:02 +0000149// USRFormat is a regex replacement string for the unqualified part of the USR.
150Symbol sym(StringRef QName, index::SymbolKind Kind, StringRef USRFormat) {
Sam McCalla15c2d62018-01-18 09:27:56 +0000151 Symbol Sym;
Sam McCall545a20d2018-01-19 14:34:02 +0000152 std::string USR = "c:"; // We synthesize a few simple cases of USRs by hand!
Sam McCalla15c2d62018-01-18 09:27:56 +0000153 size_t Pos = QName.rfind("::");
154 if (Pos == llvm::StringRef::npos) {
155 Sym.Name = QName;
156 Sym.Scope = "";
157 } else {
158 Sym.Name = QName.substr(Pos + 2);
Sam McCall8b2faee2018-01-19 22:18:21 +0000159 Sym.Scope = QName.substr(0, Pos + 2);
160 USR += "@N@" + replace(QName.substr(0, Pos), "::", "@N@"); // ns:: -> @N@ns
Sam McCalla15c2d62018-01-18 09:27:56 +0000161 }
Sam McCall545a20d2018-01-19 14:34:02 +0000162 USR += Regex("^.*$").sub(USRFormat, Sym.Name); // e.g. func -> @F@func#
163 Sym.ID = SymbolID(USR);
Sam McCalla15c2d62018-01-18 09:27:56 +0000164 Sym.SymInfo.Kind = Kind;
Marc-Andre Laperle945b5a32018-06-05 14:01:40 +0000165 Sym.IsIndexedForCodeCompletion = true;
Sam McCall2161ec72018-07-05 06:20:41 +0000166 Sym.Origin = SymbolOrigin::Static;
Sam McCalla15c2d62018-01-18 09:27:56 +0000167 return Sym;
168}
Sam McCall545a20d2018-01-19 14:34:02 +0000169Symbol func(StringRef Name) { // Assumes the function has no args.
170 return sym(Name, index::SymbolKind::Function, "@F@\\0#"); // no args
171}
172Symbol cls(StringRef Name) {
Eric Liu9b3cba72018-05-30 09:03:39 +0000173 return sym(Name, index::SymbolKind::Class, "@S@\\0");
Sam McCall545a20d2018-01-19 14:34:02 +0000174}
175Symbol var(StringRef Name) {
176 return sym(Name, index::SymbolKind::Variable, "@\\0");
177}
Sam McCalldc8abc42018-05-03 14:53:02 +0000178Symbol ns(StringRef Name) {
179 return sym(Name, index::SymbolKind::Namespace, "@N@\\0");
180}
181Symbol withReferences(int N, Symbol S) {
182 S.References = N;
183 return S;
184}
Sam McCalla15c2d62018-01-18 09:27:56 +0000185
Sam McCallf6ae3232017-12-05 20:11:29 +0000186TEST(CompletionTest, Limit) {
187 clangd::CodeCompleteOptions Opts;
188 Opts.Limit = 2;
189 auto Results = completions(R"cpp(
Sam McCall9aad25f2017-12-05 07:20:26 +0000190struct ClassWithMembers {
191 int AAA();
192 int BBB();
193 int CCC();
194}
Sam McCallf6ae3232017-12-05 20:11:29 +0000195int main() { ClassWithMembers().^ }
Sam McCall9aad25f2017-12-05 07:20:26 +0000196 )cpp",
Sam McCalla15c2d62018-01-18 09:27:56 +0000197 /*IndexSymbols=*/{}, Opts);
Sam McCall9aad25f2017-12-05 07:20:26 +0000198
Sam McCalle746a2b2018-07-02 11:13:16 +0000199 EXPECT_TRUE(Results.HasMore);
200 EXPECT_THAT(Results.Completions, ElementsAre(Named("AAA"), Named("BBB")));
Sam McCall9aad25f2017-12-05 07:20:26 +0000201}
202
Sam McCallf6ae3232017-12-05 20:11:29 +0000203TEST(CompletionTest, Filter) {
204 std::string Body = R"cpp(
Sam McCall8b2dcc12018-06-14 13:50:30 +0000205 #define MotorCar
206 int Car;
Sam McCall9aad25f2017-12-05 07:20:26 +0000207 struct S {
208 int FooBar;
209 int FooBaz;
210 int Qux;
211 };
212 )cpp";
Sam McCall8b2dcc12018-06-14 13:50:30 +0000213
214 // Only items matching the fuzzy query are returned.
Sam McCalle746a2b2018-07-02 11:13:16 +0000215 EXPECT_THAT(completions(Body + "int main() { S().Foba^ }").Completions,
Sam McCall8b2dcc12018-06-14 13:50:30 +0000216 AllOf(Has("FooBar"), Has("FooBaz"), Not(Has("Qux"))));
Sam McCall9aad25f2017-12-05 07:20:26 +0000217
Sam McCall8b2dcc12018-06-14 13:50:30 +0000218 // Macros require prefix match.
Sam McCalle746a2b2018-07-02 11:13:16 +0000219 EXPECT_THAT(completions(Body + "int main() { C^ }").Completions,
Sam McCall8b2dcc12018-06-14 13:50:30 +0000220 AllOf(Has("Car"), Not(Has("MotorCar"))));
Sam McCall9aad25f2017-12-05 07:20:26 +0000221}
222
Sam McCallf6ae3232017-12-05 20:11:29 +0000223void TestAfterDotCompletion(clangd::CodeCompleteOptions Opts) {
Sam McCall44fdcec22017-12-08 15:00:59 +0000224 auto Results = completions(
225 R"cpp(
226 #define MACRO X
Sam McCall9aad25f2017-12-05 07:20:26 +0000227
Sam McCall44fdcec22017-12-08 15:00:59 +0000228 int global_var;
Sam McCall9aad25f2017-12-05 07:20:26 +0000229
Sam McCall44fdcec22017-12-08 15:00:59 +0000230 int global_func();
Sam McCall9aad25f2017-12-05 07:20:26 +0000231
Sam McCall44fdcec22017-12-08 15:00:59 +0000232 struct GlobalClass {};
Sam McCall9aad25f2017-12-05 07:20:26 +0000233
Sam McCall44fdcec22017-12-08 15:00:59 +0000234 struct ClassWithMembers {
235 /// Doc for method.
236 int method();
Sam McCall9aad25f2017-12-05 07:20:26 +0000237
Sam McCall44fdcec22017-12-08 15:00:59 +0000238 int field;
239 private:
240 int private_field;
241 };
Sam McCall9aad25f2017-12-05 07:20:26 +0000242
Sam McCall44fdcec22017-12-08 15:00:59 +0000243 int test() {
244 struct LocalClass {};
Sam McCall9aad25f2017-12-05 07:20:26 +0000245
Sam McCall44fdcec22017-12-08 15:00:59 +0000246 /// Doc for local_var.
247 int local_var;
Sam McCall9aad25f2017-12-05 07:20:26 +0000248
Sam McCall44fdcec22017-12-08 15:00:59 +0000249 ClassWithMembers().^
250 }
251 )cpp",
Sam McCall545a20d2018-01-19 14:34:02 +0000252 {cls("IndexClass"), var("index_var"), func("index_func")}, Opts);
Sam McCall9aad25f2017-12-05 07:20:26 +0000253
Sam McCallf6ae3232017-12-05 20:11:29 +0000254 // Class members. The only items that must be present in after-dot
255 // completion.
Sam McCalle746a2b2018-07-02 11:13:16 +0000256 EXPECT_THAT(Results.Completions,
257 AllOf(Has("method"), Has("field"), Not(Has("ClassWithMembers")),
Sam McCall4caa8512018-06-07 12:49:17 +0000258 Not(Has("operator=")), Not(Has("~ClassWithMembers"))));
Sam McCalle746a2b2018-07-02 11:13:16 +0000259 EXPECT_IFF(Opts.IncludeIneligibleResults, Results.Completions,
Sam McCall44fdcec22017-12-08 15:00:59 +0000260 Has("private_field"));
Sam McCallf6ae3232017-12-05 20:11:29 +0000261 // Global items.
Sam McCall545a20d2018-01-19 14:34:02 +0000262 EXPECT_THAT(
Sam McCalle746a2b2018-07-02 11:13:16 +0000263 Results.Completions,
Sam McCall545a20d2018-01-19 14:34:02 +0000264 Not(AnyOf(Has("global_var"), Has("index_var"), Has("global_func"),
265 Has("global_func()"), Has("index_func"), Has("GlobalClass"),
266 Has("IndexClass"), Has("MACRO"), Has("LocalClass"))));
Sam McCallf6ae3232017-12-05 20:11:29 +0000267 // There should be no code patterns (aka snippets) in after-dot
268 // completion. At least there aren't any we're aware of.
Sam McCalle746a2b2018-07-02 11:13:16 +0000269 EXPECT_THAT(Results.Completions,
270 Not(Contains(Kind(CompletionItemKind::Snippet))));
Sam McCallf6ae3232017-12-05 20:11:29 +0000271 // Check documentation.
Sam McCalle746a2b2018-07-02 11:13:16 +0000272 EXPECT_IFF(Opts.IncludeComments, Results.Completions,
273 Contains(IsDocumented()));
Sam McCallf6ae3232017-12-05 20:11:29 +0000274}
Sam McCall9aad25f2017-12-05 07:20:26 +0000275
Sam McCallf6ae3232017-12-05 20:11:29 +0000276void TestGlobalScopeCompletion(clangd::CodeCompleteOptions Opts) {
Sam McCall44fdcec22017-12-08 15:00:59 +0000277 auto Results = completions(
278 R"cpp(
279 #define MACRO X
Sam McCall9aad25f2017-12-05 07:20:26 +0000280
Sam McCall44fdcec22017-12-08 15:00:59 +0000281 int global_var;
282 int global_func();
Sam McCall9aad25f2017-12-05 07:20:26 +0000283
Sam McCall44fdcec22017-12-08 15:00:59 +0000284 struct GlobalClass {};
Sam McCall9aad25f2017-12-05 07:20:26 +0000285
Sam McCall44fdcec22017-12-08 15:00:59 +0000286 struct ClassWithMembers {
287 /// Doc for method.
288 int method();
289 };
Sam McCall9aad25f2017-12-05 07:20:26 +0000290
Sam McCall44fdcec22017-12-08 15:00:59 +0000291 int test() {
292 struct LocalClass {};
Sam McCall9aad25f2017-12-05 07:20:26 +0000293
Sam McCall44fdcec22017-12-08 15:00:59 +0000294 /// Doc for local_var.
295 int local_var;
Sam McCall9aad25f2017-12-05 07:20:26 +0000296
Sam McCall44fdcec22017-12-08 15:00:59 +0000297 ^
298 }
299 )cpp",
Sam McCall545a20d2018-01-19 14:34:02 +0000300 {cls("IndexClass"), var("index_var"), func("index_func")}, Opts);
Sam McCallf6ae3232017-12-05 20:11:29 +0000301
302 // Class members. Should never be present in global completions.
Sam McCalle746a2b2018-07-02 11:13:16 +0000303 EXPECT_THAT(Results.Completions,
Sam McCallf6ae3232017-12-05 20:11:29 +0000304 Not(AnyOf(Has("method"), Has("method()"), Has("field"))));
305 // Global items.
Sam McCalle746a2b2018-07-02 11:13:16 +0000306 EXPECT_THAT(Results.Completions,
307 AllOf(Has("global_var"), Has("index_var"), Has("global_func"),
Sam McCall545a20d2018-01-19 14:34:02 +0000308 Has("index_func" /* our fake symbol doesn't include () */),
309 Has("GlobalClass"), Has("IndexClass")));
Sam McCallf6ae3232017-12-05 20:11:29 +0000310 // A macro.
Sam McCalle746a2b2018-07-02 11:13:16 +0000311 EXPECT_IFF(Opts.IncludeMacros, Results.Completions, Has("MACRO"));
Sam McCallf6ae3232017-12-05 20:11:29 +0000312 // Local items. Must be present always.
Sam McCalle746a2b2018-07-02 11:13:16 +0000313 EXPECT_THAT(Results.Completions,
Ilya Biryukov9b5ffc22017-12-12 12:56:46 +0000314 AllOf(Has("local_var"), Has("LocalClass"),
315 Contains(Kind(CompletionItemKind::Snippet))));
Sam McCallf6ae3232017-12-05 20:11:29 +0000316 // Check documentation.
Sam McCalle746a2b2018-07-02 11:13:16 +0000317 EXPECT_IFF(Opts.IncludeComments, Results.Completions,
318 Contains(IsDocumented()));
Sam McCallf6ae3232017-12-05 20:11:29 +0000319}
320
321TEST(CompletionTest, CompletionOptions) {
Sam McCall2c3849a2018-01-16 12:21:24 +0000322 auto Test = [&](const clangd::CodeCompleteOptions &Opts) {
323 TestAfterDotCompletion(Opts);
324 TestGlobalScopeCompletion(Opts);
325 };
326 // We used to test every combination of options, but that got too slow (2^N).
327 auto Flags = {
Ilya Biryukov71028b82018-03-12 15:28:22 +0000328 &clangd::CodeCompleteOptions::IncludeMacros,
Ilya Biryukov43714502018-05-16 12:32:44 +0000329 &clangd::CodeCompleteOptions::IncludeComments,
Ilya Biryukov71028b82018-03-12 15:28:22 +0000330 &clangd::CodeCompleteOptions::IncludeCodePatterns,
331 &clangd::CodeCompleteOptions::IncludeIneligibleResults,
Sam McCall2c3849a2018-01-16 12:21:24 +0000332 };
333 // Test default options.
334 Test({});
335 // Test with one flag flipped.
336 for (auto &F : Flags) {
337 clangd::CodeCompleteOptions O;
338 O.*F ^= true;
339 Test(O);
Sam McCall9aad25f2017-12-05 07:20:26 +0000340 }
341}
342
Sam McCall44fdcec22017-12-08 15:00:59 +0000343TEST(CompletionTest, Priorities) {
344 auto Internal = completions(R"cpp(
345 class Foo {
346 public: void pub();
347 protected: void prot();
348 private: void priv();
349 };
350 void Foo::pub() { this->^ }
351 )cpp");
Sam McCalle746a2b2018-07-02 11:13:16 +0000352 EXPECT_THAT(Internal.Completions,
Sam McCall44fdcec22017-12-08 15:00:59 +0000353 HasSubsequence(Named("priv"), Named("prot"), Named("pub")));
354
355 auto External = completions(R"cpp(
356 class Foo {
357 public: void pub();
358 protected: void prot();
359 private: void priv();
360 };
361 void test() {
362 Foo F;
363 F.^
364 }
365 )cpp");
Sam McCalle746a2b2018-07-02 11:13:16 +0000366 EXPECT_THAT(External.Completions,
Sam McCall44fdcec22017-12-08 15:00:59 +0000367 AllOf(Has("pub"), Not(Has("prot")), Not(Has("priv"))));
368}
369
370TEST(CompletionTest, Qualifiers) {
371 auto Results = completions(R"cpp(
372 class Foo {
373 public: int foo() const;
374 int bar() const;
375 };
376 class Bar : public Foo {
377 int foo() const;
378 };
379 void test() { Bar().^ }
380 )cpp");
Sam McCalle746a2b2018-07-02 11:13:16 +0000381 EXPECT_THAT(Results.Completions,
382 HasSubsequence(AllOf(Qualifier(""), Named("bar")),
383 AllOf(Qualifier("Foo::"), Named("foo"))));
384 EXPECT_THAT(Results.Completions,
385 Not(Contains(AllOf(Qualifier(""), Named("foo"))))); // private
Sam McCall44fdcec22017-12-08 15:00:59 +0000386}
387
Sam McCall4caa8512018-06-07 12:49:17 +0000388TEST(CompletionTest, InjectedTypename) {
389 // These are suppressed when accessed as a member...
Sam McCalle746a2b2018-07-02 11:13:16 +0000390 EXPECT_THAT(completions("struct X{}; void foo(){ X().^ }").Completions,
Sam McCall4caa8512018-06-07 12:49:17 +0000391 Not(Has("X")));
Sam McCalle746a2b2018-07-02 11:13:16 +0000392 EXPECT_THAT(completions("struct X{ void foo(){ this->^ } };").Completions,
Sam McCall4caa8512018-06-07 12:49:17 +0000393 Not(Has("X")));
394 // ...but accessible in other, more useful cases.
Sam McCalle746a2b2018-07-02 11:13:16 +0000395 EXPECT_THAT(completions("struct X{ void foo(){ ^ } };").Completions,
396 Has("X"));
397 EXPECT_THAT(
398 completions("struct Y{}; struct X:Y{ void foo(){ ^ } };").Completions,
399 Has("Y"));
Sam McCall4caa8512018-06-07 12:49:17 +0000400 EXPECT_THAT(
401 completions(
402 "template<class> struct Y{}; struct X:Y<int>{ void foo(){ ^ } };")
Sam McCalle746a2b2018-07-02 11:13:16 +0000403 .Completions,
Sam McCall4caa8512018-06-07 12:49:17 +0000404 Has("Y"));
405 // This case is marginal (`using X::X` is useful), we allow it for now.
Sam McCalle746a2b2018-07-02 11:13:16 +0000406 EXPECT_THAT(completions("struct X{}; void foo(){ X::^ }").Completions,
407 Has("X"));
Sam McCall4caa8512018-06-07 12:49:17 +0000408}
409
Sam McCall44fdcec22017-12-08 15:00:59 +0000410TEST(CompletionTest, Snippets) {
411 clangd::CodeCompleteOptions Opts;
Sam McCall44fdcec22017-12-08 15:00:59 +0000412 auto Results = completions(
413 R"cpp(
414 struct fake {
415 int a;
416 int f(int i, const float f) const;
417 };
418 int main() {
419 fake f;
420 f.^
421 }
422 )cpp",
Sam McCalla15c2d62018-01-18 09:27:56 +0000423 /*IndexSymbols=*/{}, Opts);
Sam McCalle746a2b2018-07-02 11:13:16 +0000424 EXPECT_THAT(
425 Results.Completions,
426 HasSubsequence(Named("a"),
427 SnippetSuffix("(${1:int i}, ${2:const float f})")));
Sam McCall44fdcec22017-12-08 15:00:59 +0000428}
429
430TEST(CompletionTest, Kinds) {
Sam McCall545a20d2018-01-19 14:34:02 +0000431 auto Results = completions(
432 R"cpp(
433 #define MACRO X
434 int variable;
435 struct Struct {};
436 int function();
437 int X = ^
438 )cpp",
439 {func("indexFunction"), var("indexVariable"), cls("indexClass")});
Sam McCalle746a2b2018-07-02 11:13:16 +0000440 EXPECT_THAT(Results.Completions,
Sam McCall545a20d2018-01-19 14:34:02 +0000441 AllOf(Has("function", CompletionItemKind::Function),
442 Has("variable", CompletionItemKind::Variable),
443 Has("int", CompletionItemKind::Keyword),
444 Has("Struct", CompletionItemKind::Class),
445 Has("MACRO", CompletionItemKind::Text),
446 Has("indexFunction", CompletionItemKind::Function),
447 Has("indexVariable", CompletionItemKind::Variable),
448 Has("indexClass", CompletionItemKind::Class)));
Sam McCall44fdcec22017-12-08 15:00:59 +0000449
Sam McCall44fdcec22017-12-08 15:00:59 +0000450 Results = completions("nam^");
Sam McCalle746a2b2018-07-02 11:13:16 +0000451 EXPECT_THAT(Results.Completions,
452 Has("namespace", CompletionItemKind::Snippet));
Sam McCall44fdcec22017-12-08 15:00:59 +0000453}
454
Sam McCall84652cc2018-01-12 16:16:09 +0000455TEST(CompletionTest, NoDuplicates) {
Sam McCall545a20d2018-01-19 14:34:02 +0000456 auto Results = completions(
457 R"cpp(
458 class Adapter {
Sam McCall545a20d2018-01-19 14:34:02 +0000459 };
Sam McCall84652cc2018-01-12 16:16:09 +0000460
Eric Liu9b3cba72018-05-30 09:03:39 +0000461 void f() {
Sam McCall545a20d2018-01-19 14:34:02 +0000462 Adapter^
463 }
464 )cpp",
465 {cls("Adapter")});
Sam McCall84652cc2018-01-12 16:16:09 +0000466
467 // Make sure there are no duplicate entries of 'Adapter'.
Sam McCalle746a2b2018-07-02 11:13:16 +0000468 EXPECT_THAT(Results.Completions, ElementsAre(Named("Adapter")));
Sam McCall84652cc2018-01-12 16:16:09 +0000469}
470
Sam McCall545a20d2018-01-19 14:34:02 +0000471TEST(CompletionTest, ScopedNoIndex) {
472 auto Results = completions(
473 R"cpp(
Sam McCall8b2dcc12018-06-14 13:50:30 +0000474 namespace fake { int BigBang, Babble, Box; };
475 int main() { fake::ba^ }
Sam McCall545a20d2018-01-19 14:34:02 +0000476 ")cpp");
Sam McCall8b2dcc12018-06-14 13:50:30 +0000477 // Babble is a better match than BigBang. Box doesn't match at all.
Sam McCalle746a2b2018-07-02 11:13:16 +0000478 EXPECT_THAT(Results.Completions,
479 ElementsAre(Named("Babble"), Named("BigBang")));
Sam McCall84652cc2018-01-12 16:16:09 +0000480}
481
Sam McCall545a20d2018-01-19 14:34:02 +0000482TEST(CompletionTest, Scoped) {
Sam McCalla15c2d62018-01-18 09:27:56 +0000483 auto Results = completions(
484 R"cpp(
Sam McCall8b2dcc12018-06-14 13:50:30 +0000485 namespace fake { int Babble, Box; };
486 int main() { fake::ba^ }
Sam McCall545a20d2018-01-19 14:34:02 +0000487 ")cpp",
488 {var("fake::BigBang")});
Sam McCalle746a2b2018-07-02 11:13:16 +0000489 EXPECT_THAT(Results.Completions,
490 ElementsAre(Named("Babble"), Named("BigBang")));
Sam McCalla15c2d62018-01-18 09:27:56 +0000491}
492
Sam McCall545a20d2018-01-19 14:34:02 +0000493TEST(CompletionTest, ScopedWithFilter) {
Sam McCalla15c2d62018-01-18 09:27:56 +0000494 auto Results = completions(
495 R"cpp(
496 void f() { ns::x^ }
497 )cpp",
498 {cls("ns::XYZ"), func("ns::foo")});
Sam McCalle746a2b2018-07-02 11:13:16 +0000499 EXPECT_THAT(Results.Completions, UnorderedElementsAre(Named("XYZ")));
Sam McCalla15c2d62018-01-18 09:27:56 +0000500}
501
Sam McCalldc8abc42018-05-03 14:53:02 +0000502TEST(CompletionTest, ReferencesAffectRanking) {
Eric Liu84bd5db2018-07-25 11:26:35 +0000503 auto Results = completions("int main() { abs^ }", {ns("absl"), func("absb")});
504 EXPECT_THAT(Results.Completions, HasSubsequence(Named("absb"), Named("absl")));
Sam McCalldc8abc42018-05-03 14:53:02 +0000505 Results = completions("int main() { abs^ }",
Eric Liu84bd5db2018-07-25 11:26:35 +0000506 {withReferences(10000, ns("absl")), func("absb")});
507 EXPECT_THAT(Results.Completions,
508 HasSubsequence(Named("absl"), Named("absb")));
Sam McCalldc8abc42018-05-03 14:53:02 +0000509}
510
Sam McCall545a20d2018-01-19 14:34:02 +0000511TEST(CompletionTest, GlobalQualified) {
Sam McCalla15c2d62018-01-18 09:27:56 +0000512 auto Results = completions(
513 R"cpp(
514 void f() { ::^ }
515 )cpp",
516 {cls("XYZ")});
Sam McCalle746a2b2018-07-02 11:13:16 +0000517 EXPECT_THAT(Results.Completions,
518 AllOf(Has("XYZ", CompletionItemKind::Class),
519 Has("f", CompletionItemKind::Function)));
Sam McCalla15c2d62018-01-18 09:27:56 +0000520}
521
Sam McCall545a20d2018-01-19 14:34:02 +0000522TEST(CompletionTest, FullyQualified) {
Sam McCalla15c2d62018-01-18 09:27:56 +0000523 auto Results = completions(
524 R"cpp(
Sam McCall545a20d2018-01-19 14:34:02 +0000525 namespace ns { void bar(); }
Sam McCalla15c2d62018-01-18 09:27:56 +0000526 void f() { ::ns::^ }
527 )cpp",
528 {cls("ns::XYZ")});
Sam McCalle746a2b2018-07-02 11:13:16 +0000529 EXPECT_THAT(Results.Completions,
530 AllOf(Has("XYZ", CompletionItemKind::Class),
531 Has("bar", CompletionItemKind::Function)));
Sam McCall545a20d2018-01-19 14:34:02 +0000532}
533
534TEST(CompletionTest, SemaIndexMerge) {
535 auto Results = completions(
536 R"cpp(
537 namespace ns { int local; void both(); }
538 void f() { ::ns::^ }
539 )cpp",
540 {func("ns::both"), cls("ns::Index")});
541 // We get results from both index and sema, with no duplicates.
Sam McCall2161ec72018-07-05 06:20:41 +0000542 EXPECT_THAT(Results.Completions,
543 UnorderedElementsAre(
544 AllOf(Named("local"), Origin(SymbolOrigin::AST)),
545 AllOf(Named("Index"), Origin(SymbolOrigin::Static)),
546 AllOf(Named("both"),
547 Origin(SymbolOrigin::AST | SymbolOrigin::Static))));
Sam McCalla15c2d62018-01-18 09:27:56 +0000548}
549
Haojian Wu48b48652018-01-25 09:20:09 +0000550TEST(CompletionTest, SemaIndexMergeWithLimit) {
551 clangd::CodeCompleteOptions Opts;
552 Opts.Limit = 1;
553 auto Results = completions(
554 R"cpp(
555 namespace ns { int local; void both(); }
556 void f() { ::ns::^ }
557 )cpp",
558 {func("ns::both"), cls("ns::Index")}, Opts);
Sam McCalle746a2b2018-07-02 11:13:16 +0000559 EXPECT_EQ(Results.Completions.size(), Opts.Limit);
560 EXPECT_TRUE(Results.HasMore);
Haojian Wu48b48652018-01-25 09:20:09 +0000561}
562
Eric Liu63f419a2018-05-15 15:29:32 +0000563TEST(CompletionTest, IncludeInsertionPreprocessorIntegrationTests) {
564 MockFSProvider FS;
565 MockCompilationDatabase CDB;
566 std::string Subdir = testPath("sub");
567 std::string SearchDirArg = (llvm::Twine("-I") + Subdir).str();
568 CDB.ExtraClangFlags = {SearchDirArg.c_str()};
569 std::string BarHeader = testPath("sub/bar.h");
570 FS.Files[BarHeader] = "";
571
572 IgnoreDiagnostics DiagConsumer;
573 ClangdServer Server(CDB, FS, DiagConsumer, ClangdServer::optsForTest());
Eric Liu63f419a2018-05-15 15:29:32 +0000574 auto BarURI = URI::createFile(BarHeader).toString();
575 Symbol Sym = cls("ns::X");
576 Sym.CanonicalDeclaration.FileURI = BarURI;
Eric Liu83f63e42018-09-03 10:18:21 +0000577 Sym.IncludeHeaders.emplace_back(BarURI, 1);
Eric Liu63f419a2018-05-15 15:29:32 +0000578 // Shoten include path based on search dirctory and insert.
579 auto Results = completions(Server,
580 R"cpp(
581 int main() { ns::^ }
582 )cpp",
583 {Sym});
Sam McCalle746a2b2018-07-02 11:13:16 +0000584 EXPECT_THAT(Results.Completions,
585 ElementsAre(AllOf(Named("X"), InsertInclude("\"bar.h\""))));
Eric Liu63f419a2018-05-15 15:29:32 +0000586 // Duplicate based on inclusions in preamble.
587 Results = completions(Server,
588 R"cpp(
589 #include "sub/bar.h" // not shortest, so should only match resolved.
590 int main() { ns::^ }
591 )cpp",
592 {Sym});
Sam McCalle746a2b2018-07-02 11:13:16 +0000593 EXPECT_THAT(Results.Completions, ElementsAre(AllOf(Named("X"), Labeled("X"),
594 Not(InsertInclude()))));
Eric Liu63f419a2018-05-15 15:29:32 +0000595}
596
Eric Liu9b3cba72018-05-30 09:03:39 +0000597TEST(CompletionTest, NoIncludeInsertionWhenDeclFoundInFile) {
598 MockFSProvider FS;
599 MockCompilationDatabase CDB;
600
601 IgnoreDiagnostics DiagConsumer;
602 ClangdServer Server(CDB, FS, DiagConsumer, ClangdServer::optsForTest());
Eric Liu9b3cba72018-05-30 09:03:39 +0000603 Symbol SymX = cls("ns::X");
604 Symbol SymY = cls("ns::Y");
605 std::string BarHeader = testPath("bar.h");
606 auto BarURI = URI::createFile(BarHeader).toString();
607 SymX.CanonicalDeclaration.FileURI = BarURI;
608 SymY.CanonicalDeclaration.FileURI = BarURI;
Eric Liu83f63e42018-09-03 10:18:21 +0000609 SymX.IncludeHeaders.emplace_back("<bar>", 1);
610 SymY.IncludeHeaders.emplace_back("<bar>", 1);
Eric Liu9b3cba72018-05-30 09:03:39 +0000611 // Shoten include path based on search dirctory and insert.
612 auto Results = completions(Server,
613 R"cpp(
614 namespace ns {
615 class X;
616 class Y {}
617 }
618 int main() { ns::^ }
619 )cpp",
620 {SymX, SymY});
Sam McCalle746a2b2018-07-02 11:13:16 +0000621 EXPECT_THAT(Results.Completions,
622 ElementsAre(AllOf(Named("X"), Not(InsertInclude())),
623 AllOf(Named("Y"), Not(InsertInclude()))));
Eric Liu9b3cba72018-05-30 09:03:39 +0000624}
625
Sam McCalla15c2d62018-01-18 09:27:56 +0000626TEST(CompletionTest, IndexSuppressesPreambleCompletions) {
627 MockFSProvider FS;
628 MockCompilationDatabase CDB;
629 IgnoreDiagnostics DiagConsumer;
Sam McCall7363a2f2018-03-05 17:28:54 +0000630 ClangdServer Server(CDB, FS, DiagConsumer, ClangdServer::optsForTest());
Sam McCalla15c2d62018-01-18 09:27:56 +0000631
Sam McCallc1568062018-02-16 09:41:43 +0000632 FS.Files[testPath("bar.h")] =
Sam McCalld5ea3e32018-01-24 17:53:32 +0000633 R"cpp(namespace ns { struct preamble { int member; }; })cpp";
Sam McCallc1568062018-02-16 09:41:43 +0000634 auto File = testPath("foo.cpp");
Sam McCalla15c2d62018-01-18 09:27:56 +0000635 Annotations Test(R"cpp(
636 #include "bar.h"
637 namespace ns { int local; }
Sam McCalld5ea3e32018-01-24 17:53:32 +0000638 void f() { ns::^; }
639 void f() { ns::preamble().$2^; }
Sam McCalla15c2d62018-01-18 09:27:56 +0000640 )cpp");
Sam McCall7363a2f2018-03-05 17:28:54 +0000641 runAddDocument(Server, File, Test.code());
Sam McCalla15c2d62018-01-18 09:27:56 +0000642 clangd::CodeCompleteOptions Opts = {};
643
Sam McCalla15c2d62018-01-18 09:27:56 +0000644 auto I = memIndex({var("ns::index")});
645 Opts.Index = I.get();
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000646 auto WithIndex = cantFail(runCodeComplete(Server, File, Test.point(), Opts));
Sam McCalle746a2b2018-07-02 11:13:16 +0000647 EXPECT_THAT(WithIndex.Completions,
Sam McCalla15c2d62018-01-18 09:27:56 +0000648 UnorderedElementsAre(Named("local"), Named("index")));
Sam McCalld5ea3e32018-01-24 17:53:32 +0000649 auto ClassFromPreamble =
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000650 cantFail(runCodeComplete(Server, File, Test.point("2"), Opts));
Sam McCalle746a2b2018-07-02 11:13:16 +0000651 EXPECT_THAT(ClassFromPreamble.Completions, Contains(Named("member")));
Sam McCall0bb24cd2018-02-13 08:59:23 +0000652
653 Opts.Index = nullptr;
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000654 auto WithoutIndex =
655 cantFail(runCodeComplete(Server, File, Test.point(), Opts));
Sam McCalle746a2b2018-07-02 11:13:16 +0000656 EXPECT_THAT(WithoutIndex.Completions,
Sam McCall0bb24cd2018-02-13 08:59:23 +0000657 UnorderedElementsAre(Named("local"), Named("preamble")));
Sam McCalla15c2d62018-01-18 09:27:56 +0000658}
659
660TEST(CompletionTest, DynamicIndexMultiFile) {
661 MockFSProvider FS;
662 MockCompilationDatabase CDB;
663 IgnoreDiagnostics DiagConsumer;
Sam McCall7363a2f2018-03-05 17:28:54 +0000664 auto Opts = ClangdServer::optsForTest();
665 Opts.BuildDynamicSymbolIndex = true;
666 ClangdServer Server(CDB, FS, DiagConsumer, Opts);
Sam McCalla15c2d62018-01-18 09:27:56 +0000667
Eric Liu709bde82018-02-19 18:48:44 +0000668 FS.Files[testPath("foo.h")] = R"cpp(
Sam McCalla15c2d62018-01-18 09:27:56 +0000669 namespace ns { class XYZ {}; void foo(int x) {} }
Eric Liu709bde82018-02-19 18:48:44 +0000670 )cpp";
Sam McCall7363a2f2018-03-05 17:28:54 +0000671 runAddDocument(Server, testPath("foo.cpp"), R"cpp(
Eric Liu709bde82018-02-19 18:48:44 +0000672 #include "foo.h"
Sam McCall0bb24cd2018-02-13 08:59:23 +0000673 )cpp");
Sam McCalla15c2d62018-01-18 09:27:56 +0000674
Sam McCallc1568062018-02-16 09:41:43 +0000675 auto File = testPath("bar.cpp");
Sam McCalla15c2d62018-01-18 09:27:56 +0000676 Annotations Test(R"cpp(
677 namespace ns {
678 class XXX {};
679 /// Doooc
680 void fooooo() {}
681 }
682 void f() { ns::^ }
683 )cpp");
Sam McCall7363a2f2018-03-05 17:28:54 +0000684 runAddDocument(Server, File, Test.code());
Sam McCalla15c2d62018-01-18 09:27:56 +0000685
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000686 auto Results = cantFail(runCodeComplete(Server, File, Test.point(), {}));
Sam McCalla15c2d62018-01-18 09:27:56 +0000687 // "XYZ" and "foo" are not included in the file being completed but are still
688 // visible through the index.
Sam McCalle746a2b2018-07-02 11:13:16 +0000689 EXPECT_THAT(Results.Completions, Has("XYZ", CompletionItemKind::Class));
690 EXPECT_THAT(Results.Completions, Has("foo", CompletionItemKind::Function));
691 EXPECT_THAT(Results.Completions, Has("XXX", CompletionItemKind::Class));
692 EXPECT_THAT(Results.Completions,
693 Contains((Named("fooooo"), Kind(CompletionItemKind::Function),
694 Doc("Doooc"), ReturnType("void"))));
Sam McCalla15c2d62018-01-18 09:27:56 +0000695}
696
Ilya Biryukovc22d3442018-05-16 12:32:49 +0000697TEST(CompletionTest, Documentation) {
698 auto Results = completions(
699 R"cpp(
700 // Non-doxygen comment.
701 int foo();
702 /// Doxygen comment.
703 /// \param int a
704 int bar(int a);
705 /* Multi-line
706 block comment
707 */
708 int baz();
709
710 int x = ^
711 )cpp");
Sam McCalle746a2b2018-07-02 11:13:16 +0000712 EXPECT_THAT(Results.Completions,
Ilya Biryukovc22d3442018-05-16 12:32:49 +0000713 Contains(AllOf(Named("foo"), Doc("Non-doxygen comment."))));
714 EXPECT_THAT(
Sam McCalle746a2b2018-07-02 11:13:16 +0000715 Results.Completions,
Ilya Biryukovc22d3442018-05-16 12:32:49 +0000716 Contains(AllOf(Named("bar"), Doc("Doxygen comment.\n\\param int a"))));
Sam McCalle746a2b2018-07-02 11:13:16 +0000717 EXPECT_THAT(Results.Completions,
Ilya Biryukovc22d3442018-05-16 12:32:49 +0000718 Contains(AllOf(Named("baz"), Doc("Multi-line\nblock comment"))));
719}
720
Marc-Andre Laperle945b5a32018-06-05 14:01:40 +0000721TEST(CompletionTest, GlobalCompletionFiltering) {
722
723 Symbol Class = cls("XYZ");
724 Class.IsIndexedForCodeCompletion = false;
725 Symbol Func = func("XYZ::foooo");
726 Func.IsIndexedForCodeCompletion = false;
727
728 auto Results = completions(R"(// void f() {
729 XYZ::foooo^
730 })",
731 {Class, Func});
Sam McCalle746a2b2018-07-02 11:13:16 +0000732 EXPECT_THAT(Results.Completions, IsEmpty());
Marc-Andre Laperle945b5a32018-06-05 14:01:40 +0000733}
734
Haojian Wu58d208d2018-01-25 09:44:06 +0000735TEST(CodeCompleteTest, DisableTypoCorrection) {
736 auto Results = completions(R"cpp(
737 namespace clang { int v; }
738 void f() { clangd::^
739 )cpp");
Sam McCalle746a2b2018-07-02 11:13:16 +0000740 EXPECT_TRUE(Results.Completions.empty());
Haojian Wu58d208d2018-01-25 09:44:06 +0000741}
742
Ilya Biryukov53d6d932018-03-06 16:45:21 +0000743TEST(CodeCompleteTest, NoColonColonAtTheEnd) {
744 auto Results = completions(R"cpp(
745 namespace clang { }
746 void f() {
747 clan^
748 }
749 )cpp");
750
Sam McCalle746a2b2018-07-02 11:13:16 +0000751 EXPECT_THAT(Results.Completions, Contains(Labeled("clang")));
752 EXPECT_THAT(Results.Completions, Not(Contains(Labeled("clang::"))));
Ilya Biryukov53d6d932018-03-06 16:45:21 +0000753}
754
Ilya Biryukov94da7bd2018-03-16 15:23:44 +0000755TEST(CompletionTest, BacktrackCrashes) {
756 // Sema calls code completion callbacks twice in these cases.
757 auto Results = completions(R"cpp(
758 namespace ns {
759 struct FooBarBaz {};
760 } // namespace ns
761
762 int foo(ns::FooBar^
763 )cpp");
764
Sam McCalle746a2b2018-07-02 11:13:16 +0000765 EXPECT_THAT(Results.Completions, ElementsAre(Labeled("FooBarBaz")));
Ilya Biryukov94da7bd2018-03-16 15:23:44 +0000766
767 // Check we don't crash in that case too.
768 completions(R"cpp(
769 struct FooBarBaz {};
770 void test() {
771 if (FooBarBaz * x^) {}
772 }
773)cpp");
774}
775
Eric Liu42abe412018-05-24 11:20:19 +0000776TEST(CompletionTest, CompleteInMacroWithStringification) {
777 auto Results = completions(R"cpp(
778void f(const char *, int x);
779#define F(x) f(#x, x)
780
781namespace ns {
782int X;
783int Y;
784} // namespace ns
785
786int f(int input_num) {
787 F(ns::^)
788}
789)cpp");
790
Sam McCalle746a2b2018-07-02 11:13:16 +0000791 EXPECT_THAT(Results.Completions,
Eric Liu42abe412018-05-24 11:20:19 +0000792 UnorderedElementsAre(Named("X"), Named("Y")));
793}
794
795TEST(CompletionTest, CompleteInMacroAndNamespaceWithStringification) {
796 auto Results = completions(R"cpp(
797void f(const char *, int x);
798#define F(x) f(#x, x)
799
800namespace ns {
801int X;
802
803int f(int input_num) {
804 F(^)
805}
806} // namespace ns
807)cpp");
808
Sam McCalle746a2b2018-07-02 11:13:16 +0000809 EXPECT_THAT(Results.Completions, Contains(Named("X")));
Eric Liu42abe412018-05-24 11:20:19 +0000810}
811
Eric Liu485074f2018-07-11 13:15:31 +0000812TEST(CompletionTest, IgnoreCompleteInExcludedPPBranchWithRecoveryContext) {
Ilya Biryukov94da7bd2018-03-16 15:23:44 +0000813 auto Results = completions(R"cpp(
814 int bar(int param_in_bar) {
815 }
816
817 int foo(int param_in_foo) {
818#if 0
Eric Liu485074f2018-07-11 13:15:31 +0000819 // In recorvery mode, "param_in_foo" will also be suggested among many other
820 // unrelated symbols; however, this is really a special case where this works.
821 // If the #if block is outside of the function, "param_in_foo" is still
822 // suggested, but "bar" and "foo" are missing. So the recovery mode doesn't
823 // really provide useful results in excluded branches.
Ilya Biryukov94da7bd2018-03-16 15:23:44 +0000824 par^
825#endif
826 }
827)cpp");
828
Eric Liu485074f2018-07-11 13:15:31 +0000829 EXPECT_TRUE(Results.Completions.empty());
Ilya Biryukov94da7bd2018-03-16 15:23:44 +0000830}
Ilya Biryukov43c292c2018-08-30 13:14:31 +0000831SignatureHelp signatures(StringRef Text, Position Point,
Ilya Biryukov8a0f76b2018-08-17 09:32:30 +0000832 std::vector<Symbol> IndexSymbols = {}) {
833 std::unique_ptr<SymbolIndex> Index;
834 if (!IndexSymbols.empty())
835 Index = memIndex(IndexSymbols);
836
Sam McCall800d4372017-12-19 10:29:27 +0000837 MockFSProvider FS;
838 MockCompilationDatabase CDB;
839 IgnoreDiagnostics DiagConsumer;
Ilya Biryukov8a0f76b2018-08-17 09:32:30 +0000840 ClangdServer::Options Opts = ClangdServer::optsForTest();
841 Opts.StaticIndex = Index.get();
842
843 ClangdServer Server(CDB, FS, DiagConsumer, Opts);
Sam McCallc1568062018-02-16 09:41:43 +0000844 auto File = testPath("foo.cpp");
Ilya Biryukov43c292c2018-08-30 13:14:31 +0000845 runAddDocument(Server, File, Text);
846 return cantFail(runSignatureHelp(Server, File, Point));
847}
848
849SignatureHelp signatures(StringRef Text,
850 std::vector<Symbol> IndexSymbols = {}) {
Sam McCall328cbdb2017-12-20 16:06:05 +0000851 Annotations Test(Text);
Ilya Biryukov43c292c2018-08-30 13:14:31 +0000852 return signatures(Test.code(), Test.point(), std::move(IndexSymbols));
Sam McCall800d4372017-12-19 10:29:27 +0000853}
854
855MATCHER_P(ParamsAre, P, "") {
856 if (P.size() != arg.parameters.size())
857 return false;
858 for (unsigned I = 0; I < P.size(); ++I)
859 if (P[I] != arg.parameters[I].label)
860 return false;
861 return true;
862}
Ilya Biryukov8a0f76b2018-08-17 09:32:30 +0000863MATCHER_P(SigDoc, Doc, "") { return arg.documentation == Doc; }
Sam McCall800d4372017-12-19 10:29:27 +0000864
865Matcher<SignatureInformation> Sig(std::string Label,
866 std::vector<std::string> Params) {
Eric Liu8f3678d2018-06-15 13:34:18 +0000867 return AllOf(SigHelpLabeled(Label), ParamsAre(Params));
Sam McCall800d4372017-12-19 10:29:27 +0000868}
869
870TEST(SignatureHelpTest, Overloads) {
871 auto Results = signatures(R"cpp(
872 void foo(int x, int y);
873 void foo(int x, float y);
874 void foo(float x, int y);
875 void foo(float x, float y);
876 void bar(int x, int y = 0);
877 int main() { foo(^); }
878 )cpp");
879 EXPECT_THAT(Results.signatures,
880 UnorderedElementsAre(
881 Sig("foo(float x, float y) -> void", {"float x", "float y"}),
882 Sig("foo(float x, int y) -> void", {"float x", "int y"}),
883 Sig("foo(int x, float y) -> void", {"int x", "float y"}),
884 Sig("foo(int x, int y) -> void", {"int x", "int y"})));
885 // We always prefer the first signature.
886 EXPECT_EQ(0, Results.activeSignature);
887 EXPECT_EQ(0, Results.activeParameter);
888}
889
890TEST(SignatureHelpTest, DefaultArgs) {
891 auto Results = signatures(R"cpp(
892 void bar(int x, int y = 0);
893 void bar(float x = 0, int y = 42);
894 int main() { bar(^
895 )cpp");
896 EXPECT_THAT(Results.signatures,
897 UnorderedElementsAre(
898 Sig("bar(int x, int y = 0) -> void", {"int x", "int y = 0"}),
899 Sig("bar(float x = 0, int y = 42) -> void",
900 {"float x = 0", "int y = 42"})));
901 EXPECT_EQ(0, Results.activeSignature);
902 EXPECT_EQ(0, Results.activeParameter);
903}
904
905TEST(SignatureHelpTest, ActiveArg) {
906 auto Results = signatures(R"cpp(
907 int baz(int a, int b, int c);
908 int main() { baz(baz(1,2,3), ^); }
909 )cpp");
910 EXPECT_THAT(Results.signatures,
911 ElementsAre(Sig("baz(int a, int b, int c) -> int",
912 {"int a", "int b", "int c"})));
913 EXPECT_EQ(0, Results.activeSignature);
914 EXPECT_EQ(1, Results.activeParameter);
915}
916
Ilya Biryukov43c292c2018-08-30 13:14:31 +0000917TEST(SignatureHelpTest, OpeningParen) {
918 llvm::StringLiteral Tests[] = {// Recursive function call.
919 R"cpp(
920 int foo(int a, int b, int c);
921 int main() {
922 foo(foo $p^( foo(10, 10, 10), ^ )));
923 })cpp",
924 // Functional type cast.
925 R"cpp(
926 struct Foo {
927 Foo(int a, int b, int c);
928 };
929 int main() {
930 Foo $p^( 10, ^ );
931 })cpp",
932 // New expression.
933 R"cpp(
934 struct Foo {
935 Foo(int a, int b, int c);
936 };
937 int main() {
938 new Foo $p^( 10, ^ );
939 })cpp",
940 // Macro expansion.
941 R"cpp(
942 int foo(int a, int b, int c);
943 #define FOO foo(
944
945 int main() {
946 // Macro expansions.
947 $p^FOO 10, ^ );
948 })cpp",
949 // Macro arguments.
950 R"cpp(
951 int foo(int a, int b, int c);
952 int main() {
953 #define ID(X) X
954 ID(foo $p^( foo(10), ^ ))
955 })cpp"};
956
957 for (auto Test : Tests) {
958 Annotations Code(Test);
959 EXPECT_EQ(signatures(Code.code(), Code.point()).argListStart,
960 Code.point("p"))
961 << "Test source:" << Test;
962 }
963}
964
Haojian Wu061c73e2018-01-23 11:37:26 +0000965class IndexRequestCollector : public SymbolIndex {
966public:
967 bool
Sam McCalld1a7a372018-01-31 13:40:48 +0000968 fuzzyFind(const FuzzyFindRequest &Req,
Haojian Wu061c73e2018-01-23 11:37:26 +0000969 llvm::function_ref<void(const Symbol &)> Callback) const override {
970 Requests.push_back(Req);
Sam McCallab8e3932018-02-19 13:04:41 +0000971 return true;
Haojian Wu061c73e2018-01-23 11:37:26 +0000972 }
973
Eric Liu9ec459f2018-03-14 09:48:05 +0000974 void lookup(const LookupRequest &,
975 llvm::function_ref<void(const Symbol &)>) const override {}
976
Haojian Wu65ac3212018-08-06 13:14:32 +0000977 void findOccurrences(const OccurrencesRequest &Req,
978 llvm::function_ref<void(const SymbolOccurrence &)>
979 Callback) const override {}
980
Kirill Bobyrevfc890012018-08-24 09:12:54 +0000981 // This is incorrect, but IndexRequestCollector is not an actual index and it
982 // isn't used in production code.
983 size_t estimateMemoryUsage() const override { return 0; }
984
Eric Liu25d74e92018-08-24 11:23:56 +0000985 const std::vector<FuzzyFindRequest> consumeRequests() const {
986 auto Reqs = std::move(Requests);
987 Requests = {};
988 return Reqs;
989 }
Haojian Wu061c73e2018-01-23 11:37:26 +0000990
991private:
992 mutable std::vector<FuzzyFindRequest> Requests;
993};
994
995std::vector<FuzzyFindRequest> captureIndexRequests(llvm::StringRef Code) {
996 clangd::CodeCompleteOptions Opts;
997 IndexRequestCollector Requests;
998 Opts.Index = &Requests;
999 completions(Code, {}, Opts);
Eric Liu25d74e92018-08-24 11:23:56 +00001000 return Requests.consumeRequests();
Haojian Wu061c73e2018-01-23 11:37:26 +00001001}
1002
1003TEST(CompletionTest, UnqualifiedIdQuery) {
1004 auto Requests = captureIndexRequests(R"cpp(
1005 namespace std {}
1006 using namespace std;
1007 namespace ns {
1008 void f() {
1009 vec^
1010 }
1011 }
1012 )cpp");
1013
1014 EXPECT_THAT(Requests,
1015 ElementsAre(Field(&FuzzyFindRequest::Scopes,
1016 UnorderedElementsAre("", "ns::", "std::"))));
1017}
1018
1019TEST(CompletionTest, ResolvedQualifiedIdQuery) {
1020 auto Requests = captureIndexRequests(R"cpp(
1021 namespace ns1 {}
1022 namespace ns2 {} // ignore
1023 namespace ns3 { namespace nns3 {} }
1024 namespace foo {
1025 using namespace ns1;
1026 using namespace ns3::nns3;
1027 }
1028 namespace ns {
1029 void f() {
1030 foo::^
1031 }
1032 }
1033 )cpp");
1034
1035 EXPECT_THAT(Requests,
1036 ElementsAre(Field(
1037 &FuzzyFindRequest::Scopes,
1038 UnorderedElementsAre("foo::", "ns1::", "ns3::nns3::"))));
1039}
1040
1041TEST(CompletionTest, UnresolvedQualifierIdQuery) {
1042 auto Requests = captureIndexRequests(R"cpp(
1043 namespace a {}
1044 using namespace a;
1045 namespace ns {
1046 void f() {
1047 bar::^
1048 }
1049 } // namespace ns
1050 )cpp");
1051
1052 EXPECT_THAT(Requests, ElementsAre(Field(&FuzzyFindRequest::Scopes,
1053 UnorderedElementsAre("bar::"))));
1054}
1055
1056TEST(CompletionTest, UnresolvedNestedQualifierIdQuery) {
1057 auto Requests = captureIndexRequests(R"cpp(
1058 namespace a {}
1059 using namespace a;
1060 namespace ns {
1061 void f() {
1062 ::a::bar::^
1063 }
1064 } // namespace ns
1065 )cpp");
1066
1067 EXPECT_THAT(Requests, ElementsAre(Field(&FuzzyFindRequest::Scopes,
1068 UnorderedElementsAre("a::bar::"))));
1069}
1070
1071TEST(CompletionTest, EmptyQualifiedQuery) {
1072 auto Requests = captureIndexRequests(R"cpp(
1073 namespace ns {
1074 void f() {
1075 ^
1076 }
1077 } // namespace ns
1078 )cpp");
1079
1080 EXPECT_THAT(Requests, ElementsAre(Field(&FuzzyFindRequest::Scopes,
1081 UnorderedElementsAre("", "ns::"))));
1082}
1083
1084TEST(CompletionTest, GlobalQualifiedQuery) {
1085 auto Requests = captureIndexRequests(R"cpp(
1086 namespace ns {
1087 void f() {
1088 ::^
1089 }
1090 } // namespace ns
1091 )cpp");
1092
1093 EXPECT_THAT(Requests, ElementsAre(Field(&FuzzyFindRequest::Scopes,
1094 UnorderedElementsAre(""))));
1095}
1096
Ilya Biryukova907ba42018-05-14 10:50:04 +00001097TEST(CompletionTest, NoIndexCompletionsInsideClasses) {
1098 auto Completions = completions(
1099 R"cpp(
1100 struct Foo {
1101 int SomeNameOfField;
1102 typedef int SomeNameOfTypedefField;
1103 };
1104
1105 Foo::^)cpp",
1106 {func("::SomeNameInTheIndex"), func("::Foo::SomeNameInTheIndex")});
1107
Sam McCalle746a2b2018-07-02 11:13:16 +00001108 EXPECT_THAT(Completions.Completions,
Ilya Biryukova907ba42018-05-14 10:50:04 +00001109 AllOf(Contains(Labeled("SomeNameOfField")),
1110 Contains(Labeled("SomeNameOfTypedefField")),
1111 Not(Contains(Labeled("SomeNameInTheIndex")))));
1112}
1113
1114TEST(CompletionTest, NoIndexCompletionsInsideDependentCode) {
1115 {
1116 auto Completions = completions(
1117 R"cpp(
1118 template <class T>
1119 void foo() {
1120 T::^
1121 }
1122 )cpp",
1123 {func("::SomeNameInTheIndex")});
1124
Sam McCalle746a2b2018-07-02 11:13:16 +00001125 EXPECT_THAT(Completions.Completions,
Ilya Biryukova907ba42018-05-14 10:50:04 +00001126 Not(Contains(Labeled("SomeNameInTheIndex"))));
1127 }
1128
1129 {
1130 auto Completions = completions(
1131 R"cpp(
1132 template <class T>
1133 void foo() {
1134 T::template Y<int>::^
1135 }
1136 )cpp",
1137 {func("::SomeNameInTheIndex")});
1138
Sam McCalle746a2b2018-07-02 11:13:16 +00001139 EXPECT_THAT(Completions.Completions,
Ilya Biryukova907ba42018-05-14 10:50:04 +00001140 Not(Contains(Labeled("SomeNameInTheIndex"))));
1141 }
1142
1143 {
1144 auto Completions = completions(
1145 R"cpp(
1146 template <class T>
1147 void foo() {
1148 T::foo::^
1149 }
1150 )cpp",
1151 {func("::SomeNameInTheIndex")});
1152
Sam McCalle746a2b2018-07-02 11:13:16 +00001153 EXPECT_THAT(Completions.Completions,
Ilya Biryukova907ba42018-05-14 10:50:04 +00001154 Not(Contains(Labeled("SomeNameInTheIndex"))));
1155 }
1156}
1157
Sam McCallc18c2802018-06-15 11:06:29 +00001158TEST(CompletionTest, OverloadBundling) {
1159 clangd::CodeCompleteOptions Opts;
1160 Opts.BundleOverloads = true;
1161
1162 std::string Context = R"cpp(
1163 struct X {
1164 // Overload with int
1165 int a(int);
1166 // Overload with bool
1167 int a(bool);
1168 int b(float);
1169 };
1170 int GFuncC(int);
1171 int GFuncD(int);
1172 )cpp";
1173
1174 // Member completions are bundled.
Sam McCalle746a2b2018-07-02 11:13:16 +00001175 EXPECT_THAT(completions(Context + "int y = X().^", {}, Opts).Completions,
Sam McCallc18c2802018-06-15 11:06:29 +00001176 UnorderedElementsAre(Labeled("a(…)"), Labeled("b(float)")));
1177
1178 // Non-member completions are bundled, including index+sema.
1179 Symbol NoArgsGFunc = func("GFuncC");
1180 EXPECT_THAT(
Sam McCalle746a2b2018-07-02 11:13:16 +00001181 completions(Context + "int y = GFunc^", {NoArgsGFunc}, Opts).Completions,
Sam McCallc18c2802018-06-15 11:06:29 +00001182 UnorderedElementsAre(Labeled("GFuncC(…)"), Labeled("GFuncD(int)")));
1183
1184 // Differences in header-to-insert suppress bundling.
Sam McCallc18c2802018-06-15 11:06:29 +00001185 std::string DeclFile = URI::createFile(testPath("foo")).toString();
1186 NoArgsGFunc.CanonicalDeclaration.FileURI = DeclFile;
Eric Liu83f63e42018-09-03 10:18:21 +00001187 NoArgsGFunc.IncludeHeaders.emplace_back("<foo>", 1);
Sam McCallc18c2802018-06-15 11:06:29 +00001188 EXPECT_THAT(
Sam McCalle746a2b2018-07-02 11:13:16 +00001189 completions(Context + "int y = GFunc^", {NoArgsGFunc}, Opts).Completions,
1190 UnorderedElementsAre(AllOf(Named("GFuncC"), InsertInclude("<foo>")),
1191 Labeled("GFuncC(int)"), Labeled("GFuncD(int)")));
Sam McCallc18c2802018-06-15 11:06:29 +00001192
1193 // Examine a bundled completion in detail.
Sam McCalle746a2b2018-07-02 11:13:16 +00001194 auto A =
1195 completions(Context + "int y = X().a^", {}, Opts).Completions.front();
1196 EXPECT_EQ(A.Name, "a");
1197 EXPECT_EQ(A.Signature, "(…)");
1198 EXPECT_EQ(A.BundleSize, 2u);
1199 EXPECT_EQ(A.Kind, CompletionItemKind::Method);
1200 EXPECT_EQ(A.ReturnType, "int"); // All overloads return int.
Sam McCallc18c2802018-06-15 11:06:29 +00001201 // For now we just return one of the doc strings arbitrarily.
Sam McCalle746a2b2018-07-02 11:13:16 +00001202 EXPECT_THAT(A.Documentation, AnyOf(HasSubstr("Overload with int"),
Sam McCallc18c2802018-06-15 11:06:29 +00001203 HasSubstr("Overload with bool")));
Kadir Cetinkaya516fcda2018-08-23 12:19:39 +00001204 EXPECT_EQ(A.SnippetSuffix, "($0)");
Sam McCallc18c2802018-06-15 11:06:29 +00001205}
1206
Ilya Biryukov30b04b12018-05-28 09:54:51 +00001207TEST(CompletionTest, DocumentationFromChangedFileCrash) {
Ilya Biryukovbe0eb8f2018-05-24 14:49:23 +00001208 MockFSProvider FS;
1209 auto FooH = testPath("foo.h");
1210 auto FooCpp = testPath("foo.cpp");
1211 FS.Files[FooH] = R"cpp(
1212 // this is my documentation comment.
1213 int func();
1214 )cpp";
1215 FS.Files[FooCpp] = "";
1216
1217 MockCompilationDatabase CDB;
1218 IgnoreDiagnostics DiagConsumer;
1219 ClangdServer Server(CDB, FS, DiagConsumer, ClangdServer::optsForTest());
1220
1221 Annotations Source(R"cpp(
1222 #include "foo.h"
1223 int func() {
1224 // This makes sure we have func from header in the AST.
1225 }
1226 int a = fun^
1227 )cpp");
1228 Server.addDocument(FooCpp, Source.code(), WantDiagnostics::Yes);
1229 // We need to wait for preamble to build.
1230 ASSERT_TRUE(Server.blockUntilIdleForTest());
1231
1232 // Change the header file. Completion will reuse the old preamble!
1233 FS.Files[FooH] = R"cpp(
1234 int func();
1235 )cpp";
1236
1237 clangd::CodeCompleteOptions Opts;
1238 Opts.IncludeComments = true;
Sam McCalle746a2b2018-07-02 11:13:16 +00001239 CodeCompleteResult Completions =
Ilya Biryukovbe0eb8f2018-05-24 14:49:23 +00001240 cantFail(runCodeComplete(Server, FooCpp, Source.point(), Opts));
1241 // We shouldn't crash. Unfortunately, current workaround is to not produce
1242 // comments for symbols from headers.
Sam McCalle746a2b2018-07-02 11:13:16 +00001243 EXPECT_THAT(Completions.Completions,
Ilya Biryukovbe0eb8f2018-05-24 14:49:23 +00001244 Contains(AllOf(Not(IsDocumented()), Named("func"))));
1245}
1246
Ilya Biryukov89fcf6b2018-06-15 08:31:17 +00001247TEST(CompletionTest, NonDocComments) {
1248 MockFSProvider FS;
1249 auto FooCpp = testPath("foo.cpp");
1250 FS.Files[FooCpp] = "";
1251
1252 MockCompilationDatabase CDB;
1253 IgnoreDiagnostics DiagConsumer;
1254 ClangdServer Server(CDB, FS, DiagConsumer, ClangdServer::optsForTest());
1255
1256 Annotations Source(R"cpp(
Ilya Biryukovda8dd8b2018-06-27 09:47:20 +00001257 // We ignore namespace comments, for rationale see CodeCompletionStrings.h.
1258 namespace comments_ns {
1259 }
1260
Ilya Biryukov89fcf6b2018-06-15 08:31:17 +00001261 // ------------------
1262 int comments_foo();
1263
1264 // A comment and a decl are separated by newlines.
1265 // Therefore, the comment shouldn't show up as doc comment.
1266
1267 int comments_bar();
1268
1269 // this comment should be in the results.
1270 int comments_baz();
1271
1272
1273 template <class T>
1274 struct Struct {
1275 int comments_qux();
1276 int comments_quux();
1277 };
1278
1279
1280 // This comment should not be there.
1281
1282 template <class T>
1283 int Struct<T>::comments_qux() {
1284 }
1285
1286 // This comment **should** be in results.
1287 template <class T>
1288 int Struct<T>::comments_quux() {
1289 int a = comments^;
1290 }
1291 )cpp");
Reid Kleckner80274b12018-06-18 18:55:10 +00001292 // FIXME: Auto-completion in a template requires disabling delayed template
1293 // parsing.
1294 CDB.ExtraClangFlags.push_back("-fno-delayed-template-parsing");
Ilya Biryukov89fcf6b2018-06-15 08:31:17 +00001295 Server.addDocument(FooCpp, Source.code(), WantDiagnostics::Yes);
Sam McCalle746a2b2018-07-02 11:13:16 +00001296 CodeCompleteResult Completions = cantFail(runCodeComplete(
Ilya Biryukov89fcf6b2018-06-15 08:31:17 +00001297 Server, FooCpp, Source.point(), clangd::CodeCompleteOptions()));
1298
1299 // We should not get any of those comments in completion.
1300 EXPECT_THAT(
Sam McCalle746a2b2018-07-02 11:13:16 +00001301 Completions.Completions,
Ilya Biryukov89fcf6b2018-06-15 08:31:17 +00001302 UnorderedElementsAre(AllOf(Not(IsDocumented()), Named("comments_foo")),
1303 AllOf(IsDocumented(), Named("comments_baz")),
1304 AllOf(IsDocumented(), Named("comments_quux")),
Ilya Biryukovda8dd8b2018-06-27 09:47:20 +00001305 AllOf(Not(IsDocumented()), Named("comments_ns")),
Ilya Biryukov89fcf6b2018-06-15 08:31:17 +00001306 // FIXME(ibiryukov): the following items should have
1307 // empty documentation, since they are separated from
1308 // a comment with an empty line. Unfortunately, I
1309 // couldn't make Sema tests pass if we ignore those.
1310 AllOf(IsDocumented(), Named("comments_bar")),
1311 AllOf(IsDocumented(), Named("comments_qux"))));
1312}
1313
Ilya Biryukov981a35d2018-05-28 12:11:37 +00001314TEST(CompletionTest, CompleteOnInvalidLine) {
1315 auto FooCpp = testPath("foo.cpp");
1316
1317 MockCompilationDatabase CDB;
1318 IgnoreDiagnostics DiagConsumer;
1319 MockFSProvider FS;
1320 FS.Files[FooCpp] = "// empty file";
1321
1322 ClangdServer Server(CDB, FS, DiagConsumer, ClangdServer::optsForTest());
1323 // Run completion outside the file range.
1324 Position Pos;
1325 Pos.line = 100;
1326 Pos.character = 0;
1327 EXPECT_THAT_EXPECTED(
1328 runCodeComplete(Server, FooCpp, Pos, clangd::CodeCompleteOptions()),
1329 Failed());
1330}
1331
Eric Liu7ad16962018-06-22 10:46:59 +00001332TEST(CompletionTest, QualifiedNames) {
1333 auto Results = completions(
1334 R"cpp(
1335 namespace ns { int local; void both(); }
1336 void f() { ::ns::^ }
1337 )cpp",
1338 {func("ns::both"), cls("ns::Index")});
1339 // We get results from both index and sema, with no duplicates.
Sam McCalle746a2b2018-07-02 11:13:16 +00001340 EXPECT_THAT(
1341 Results.Completions,
1342 UnorderedElementsAre(Scope("ns::"), Scope("ns::"), Scope("ns::")));
1343}
1344
1345TEST(CompletionTest, Render) {
1346 CodeCompletion C;
1347 C.Name = "x";
1348 C.Signature = "(bool) const";
1349 C.SnippetSuffix = "(${0:bool})";
1350 C.ReturnType = "int";
1351 C.RequiredQualifier = "Foo::";
1352 C.Scope = "ns::Foo::";
1353 C.Documentation = "This is x().";
Eric Liu83f63e42018-09-03 10:18:21 +00001354 C.Includes.emplace_back();
1355 auto &Include = C.Includes.back();
1356 Include.Header = "\"foo.h\"";
Sam McCalle746a2b2018-07-02 11:13:16 +00001357 C.Kind = CompletionItemKind::Method;
1358 C.Score.Total = 1.0;
Sam McCall4e5742a2018-07-06 11:50:49 +00001359 C.Origin = SymbolOrigin::AST | SymbolOrigin::Static;
Sam McCalle746a2b2018-07-02 11:13:16 +00001360
1361 CodeCompleteOptions Opts;
1362 Opts.IncludeIndicator.Insert = "^";
1363 Opts.IncludeIndicator.NoInsert = "";
1364 Opts.EnableSnippets = false;
1365
1366 auto R = C.render(Opts);
1367 EXPECT_EQ(R.label, "Foo::x(bool) const");
1368 EXPECT_EQ(R.insertText, "Foo::x");
1369 EXPECT_EQ(R.insertTextFormat, InsertTextFormat::PlainText);
1370 EXPECT_EQ(R.filterText, "x");
1371 EXPECT_EQ(R.detail, "int\n\"foo.h\"");
1372 EXPECT_EQ(R.documentation, "This is x().");
1373 EXPECT_THAT(R.additionalTextEdits, IsEmpty());
Sam McCalle746a2b2018-07-02 11:13:16 +00001374 EXPECT_EQ(R.sortText, sortText(1.0, "x"));
1375
1376 Opts.EnableSnippets = true;
1377 R = C.render(Opts);
1378 EXPECT_EQ(R.insertText, "Foo::x(${0:bool})");
1379 EXPECT_EQ(R.insertTextFormat, InsertTextFormat::Snippet);
1380
Eric Liu83f63e42018-09-03 10:18:21 +00001381 Include.Insertion.emplace();
Sam McCalle746a2b2018-07-02 11:13:16 +00001382 R = C.render(Opts);
1383 EXPECT_EQ(R.label, "^Foo::x(bool) const");
1384 EXPECT_THAT(R.additionalTextEdits, Not(IsEmpty()));
1385
Sam McCall2161ec72018-07-05 06:20:41 +00001386 Opts.ShowOrigins = true;
1387 R = C.render(Opts);
1388 EXPECT_EQ(R.label, "^[AS]Foo::x(bool) const");
1389
Sam McCalle746a2b2018-07-02 11:13:16 +00001390 C.BundleSize = 2;
1391 R = C.render(Opts);
1392 EXPECT_EQ(R.detail, "[2 overloads]\n\"foo.h\"");
Eric Liu7ad16962018-06-22 10:46:59 +00001393}
Ilya Biryukov981a35d2018-05-28 12:11:37 +00001394
Eric Liu485074f2018-07-11 13:15:31 +00001395TEST(CompletionTest, IgnoreRecoveryResults) {
1396 auto Results = completions(
1397 R"cpp(
1398 namespace ns { int NotRecovered() { return 0; } }
1399 void f() {
1400 // Sema enters recovery mode first and then normal mode.
1401 if (auto x = ns::NotRecover^)
1402 }
1403 )cpp");
1404 EXPECT_THAT(Results.Completions, UnorderedElementsAre(Named("NotRecovered")));
1405}
1406
Eric Liuf433c2d2018-07-18 15:31:14 +00001407TEST(CompletionTest, ScopeOfClassFieldInConstructorInitializer) {
1408 auto Results = completions(
1409 R"cpp(
1410 namespace ns {
1411 class X { public: X(); int x_; };
1412 X::X() : x_^(0) {}
1413 }
1414 )cpp");
1415 EXPECT_THAT(Results.Completions,
1416 UnorderedElementsAre(AllOf(Scope("ns::X::"), Named("x_"))));
1417}
1418
Eric Liu5d2a8072018-07-23 10:56:37 +00001419TEST(CompletionTest, CodeCompletionContext) {
1420 auto Results = completions(
1421 R"cpp(
1422 namespace ns {
1423 class X { public: X(); int x_; };
1424 void f() {
1425 X x;
1426 x.^;
1427 }
1428 }
1429 )cpp");
1430
1431 EXPECT_THAT(Results.Context, CodeCompletionContext::CCC_DotMemberAccess);
1432}
1433
Kadir Cetinkaya2f84d912018-08-08 08:59:29 +00001434TEST(CompletionTest, FixItForArrowToDot) {
1435 MockFSProvider FS;
1436 MockCompilationDatabase CDB;
1437 IgnoreDiagnostics DiagConsumer;
1438 ClangdServer Server(CDB, FS, DiagConsumer, ClangdServer::optsForTest());
1439
1440 CodeCompleteOptions Opts;
1441 Opts.IncludeFixIts = true;
1442 Annotations TestCode(
1443 R"cpp(
1444 class Auxilary {
1445 public:
1446 void AuxFunction();
1447 };
1448 class ClassWithPtr {
1449 public:
1450 void MemberFunction();
1451 Auxilary* operator->() const;
1452 Auxilary* Aux;
1453 };
1454 void f() {
1455 ClassWithPtr x;
1456 x[[->]]^;
1457 }
1458 )cpp");
1459 auto Results =
1460 completions(Server, TestCode.code(), TestCode.point(), {}, Opts);
1461 EXPECT_EQ(Results.Completions.size(), 3u);
1462
1463 TextEdit ReplacementEdit;
1464 ReplacementEdit.range = TestCode.range();
1465 ReplacementEdit.newText = ".";
1466 for (const auto &C : Results.Completions) {
1467 EXPECT_TRUE(C.FixIts.size() == 1u || C.Name == "AuxFunction");
Haojian Wu1793bc92018-08-10 08:34:16 +00001468 if (!C.FixIts.empty()) {
Kadir Cetinkaya2f84d912018-08-08 08:59:29 +00001469 EXPECT_THAT(C.FixIts, ElementsAre(ReplacementEdit));
Haojian Wu1793bc92018-08-10 08:34:16 +00001470 }
Kadir Cetinkaya2f84d912018-08-08 08:59:29 +00001471 }
1472}
1473
1474TEST(CompletionTest, FixItForDotToArrow) {
1475 MockFSProvider FS;
1476 MockCompilationDatabase CDB;
1477 IgnoreDiagnostics DiagConsumer;
1478 ClangdServer Server(CDB, FS, DiagConsumer, ClangdServer::optsForTest());
1479
1480 CodeCompleteOptions Opts;
1481 Opts.IncludeFixIts = true;
1482 Annotations TestCode(
1483 R"cpp(
1484 class Auxilary {
1485 public:
1486 void AuxFunction();
1487 };
1488 class ClassWithPtr {
1489 public:
1490 void MemberFunction();
1491 Auxilary* operator->() const;
1492 Auxilary* Aux;
1493 };
1494 void f() {
1495 ClassWithPtr x;
1496 x[[.]]^;
1497 }
1498 )cpp");
1499 auto Results =
1500 completions(Server, TestCode.code(), TestCode.point(), {}, Opts);
1501 EXPECT_EQ(Results.Completions.size(), 3u);
1502
1503 TextEdit ReplacementEdit;
1504 ReplacementEdit.range = TestCode.range();
1505 ReplacementEdit.newText = "->";
1506 for (const auto &C : Results.Completions) {
1507 EXPECT_TRUE(C.FixIts.empty() || C.Name == "AuxFunction");
1508 if (!C.FixIts.empty()) {
1509 EXPECT_THAT(C.FixIts, ElementsAre(ReplacementEdit));
1510 }
1511 }
1512}
1513
Kadir Cetinkayaa9c9d002018-08-13 08:23:01 +00001514TEST(CompletionTest, RenderWithFixItMerged) {
1515 TextEdit FixIt;
1516 FixIt.range.end.character = 5;
1517 FixIt.newText = "->";
1518
1519 CodeCompletion C;
1520 C.Name = "x";
1521 C.RequiredQualifier = "Foo::";
1522 C.FixIts = {FixIt};
1523 C.CompletionTokenRange.start.character = 5;
1524
1525 CodeCompleteOptions Opts;
1526 Opts.IncludeFixIts = true;
1527
1528 auto R = C.render(Opts);
1529 EXPECT_TRUE(R.textEdit);
1530 EXPECT_EQ(R.textEdit->newText, "->Foo::x");
1531 EXPECT_TRUE(R.additionalTextEdits.empty());
1532}
1533
1534TEST(CompletionTest, RenderWithFixItNonMerged) {
1535 TextEdit FixIt;
1536 FixIt.range.end.character = 4;
1537 FixIt.newText = "->";
1538
1539 CodeCompletion C;
1540 C.Name = "x";
1541 C.RequiredQualifier = "Foo::";
1542 C.FixIts = {FixIt};
1543 C.CompletionTokenRange.start.character = 5;
1544
1545 CodeCompleteOptions Opts;
1546 Opts.IncludeFixIts = true;
1547
1548 auto R = C.render(Opts);
1549 EXPECT_TRUE(R.textEdit);
1550 EXPECT_EQ(R.textEdit->newText, "Foo::x");
1551 EXPECT_THAT(R.additionalTextEdits, UnorderedElementsAre(FixIt));
1552}
1553
1554TEST(CompletionTest, CompletionTokenRange) {
1555 MockFSProvider FS;
1556 MockCompilationDatabase CDB;
1557 IgnoreDiagnostics DiagConsumer;
1558 ClangdServer Server(CDB, FS, DiagConsumer, ClangdServer::optsForTest());
1559
1560 constexpr const char *TestCodes[] = {
1561 R"cpp(
1562 class Auxilary {
1563 public:
1564 void AuxFunction();
1565 };
1566 void f() {
1567 Auxilary x;
1568 x.[[Aux]]^;
1569 }
1570 )cpp",
1571 R"cpp(
1572 class Auxilary {
1573 public:
1574 void AuxFunction();
1575 };
1576 void f() {
1577 Auxilary x;
1578 x.[[]]^;
1579 }
1580 )cpp"};
1581 for (const auto &Text : TestCodes) {
1582 Annotations TestCode(Text);
1583 auto Results = completions(Server, TestCode.code(), TestCode.point());
1584
1585 EXPECT_EQ(Results.Completions.size(), 1u);
1586 EXPECT_THAT(Results.Completions.front().CompletionTokenRange, TestCode.range());
1587 }
1588}
1589
Kadir Cetinkayae486e372018-08-13 08:40:05 +00001590TEST(SignatureHelpTest, OverloadsOrdering) {
1591 const auto Results = signatures(R"cpp(
1592 void foo(int x);
1593 void foo(int x, float y);
1594 void foo(float x, int y);
1595 void foo(float x, float y);
1596 void foo(int x, int y = 0);
1597 int main() { foo(^); }
1598 )cpp");
1599 EXPECT_THAT(
1600 Results.signatures,
1601 ElementsAre(
1602 Sig("foo(int x) -> void", {"int x"}),
1603 Sig("foo(int x, int y = 0) -> void", {"int x", "int y = 0"}),
1604 Sig("foo(float x, int y) -> void", {"float x", "int y"}),
1605 Sig("foo(int x, float y) -> void", {"int x", "float y"}),
1606 Sig("foo(float x, float y) -> void", {"float x", "float y"})));
1607 // We always prefer the first signature.
1608 EXPECT_EQ(0, Results.activeSignature);
1609 EXPECT_EQ(0, Results.activeParameter);
1610}
1611
Ilya Biryukov8fd44bb2018-08-14 09:36:32 +00001612TEST(SignatureHelpTest, InstantiatedSignatures) {
Simon Pilgrim83552ee2018-08-16 11:41:19 +00001613 StringRef Sig0 = R"cpp(
Ilya Biryukov8fd44bb2018-08-14 09:36:32 +00001614 template <class T>
1615 void foo(T, T, T);
1616
1617 int main() {
1618 foo<int>(^);
1619 }
Simon Pilgrim83552ee2018-08-16 11:41:19 +00001620 )cpp";
1621
1622 EXPECT_THAT(signatures(Sig0).signatures,
Ilya Biryukov8fd44bb2018-08-14 09:36:32 +00001623 ElementsAre(Sig("foo(T, T, T) -> void", {"T", "T", "T"})));
1624
Simon Pilgrim83552ee2018-08-16 11:41:19 +00001625 StringRef Sig1 = R"cpp(
Ilya Biryukov8fd44bb2018-08-14 09:36:32 +00001626 template <class T>
1627 void foo(T, T, T);
1628
1629 int main() {
1630 foo(10, ^);
Simon Pilgrim83552ee2018-08-16 11:41:19 +00001631 })cpp";
1632
1633 EXPECT_THAT(signatures(Sig1).signatures,
Ilya Biryukov8fd44bb2018-08-14 09:36:32 +00001634 ElementsAre(Sig("foo(T, T, T) -> void", {"T", "T", "T"})));
1635
Simon Pilgrim83552ee2018-08-16 11:41:19 +00001636 StringRef Sig2 = R"cpp(
Ilya Biryukov8fd44bb2018-08-14 09:36:32 +00001637 template <class ...T>
1638 void foo(T...);
1639
1640 int main() {
1641 foo<int>(^);
1642 }
Simon Pilgrim83552ee2018-08-16 11:41:19 +00001643 )cpp";
1644
1645 EXPECT_THAT(signatures(Sig2).signatures,
Ilya Biryukov8fd44bb2018-08-14 09:36:32 +00001646 ElementsAre(Sig("foo(T...) -> void", {"T..."})));
1647
1648 // It is debatable whether we should substitute the outer template parameter
1649 // ('T') in that case. Currently we don't substitute it in signature help, but
1650 // do substitute in code complete.
1651 // FIXME: make code complete and signature help consistent, figure out which
1652 // way is better.
Simon Pilgrim83552ee2018-08-16 11:41:19 +00001653 StringRef Sig3 = R"cpp(
Ilya Biryukov8fd44bb2018-08-14 09:36:32 +00001654 template <class T>
1655 struct X {
1656 template <class U>
1657 void foo(T, U);
1658 };
1659
1660 int main() {
1661 X<int>().foo<double>(^)
1662 }
Simon Pilgrim83552ee2018-08-16 11:41:19 +00001663 )cpp";
1664
1665 EXPECT_THAT(signatures(Sig3).signatures,
Ilya Biryukov8fd44bb2018-08-14 09:36:32 +00001666 ElementsAre(Sig("foo(T, U) -> void", {"T", "U"})));
1667}
1668
Ilya Biryukov8a0f76b2018-08-17 09:32:30 +00001669TEST(SignatureHelpTest, IndexDocumentation) {
Ilya Biryukov8a0f76b2018-08-17 09:32:30 +00001670 Symbol Foo0 = sym("foo", index::SymbolKind::Function, "@F@\\0#");
Sam McCall2e5700f2018-08-31 13:55:01 +00001671 Foo0.Documentation = "Doc from the index";
Ilya Biryukov8a0f76b2018-08-17 09:32:30 +00001672 Symbol Foo1 = sym("foo", index::SymbolKind::Function, "@F@\\0#I#");
Sam McCall2e5700f2018-08-31 13:55:01 +00001673 Foo1.Documentation = "Doc from the index";
Ilya Biryukov8a0f76b2018-08-17 09:32:30 +00001674 Symbol Foo2 = sym("foo", index::SymbolKind::Function, "@F@\\0#I#I#");
1675
Simon Pilgrim24d34922018-08-17 10:40:05 +00001676 StringRef Sig0 = R"cpp(
Ilya Biryukov8a0f76b2018-08-17 09:32:30 +00001677 int foo();
1678 int foo(double);
1679
1680 void test() {
1681 foo(^);
1682 }
Simon Pilgrim24d34922018-08-17 10:40:05 +00001683 )cpp";
1684
1685 EXPECT_THAT(
1686 signatures(Sig0, {Foo0}).signatures,
Ilya Biryukov8a0f76b2018-08-17 09:32:30 +00001687 ElementsAre(AllOf(Sig("foo() -> int", {}), SigDoc("Doc from the index")),
1688 AllOf(Sig("foo(double) -> int", {"double"}), SigDoc(""))));
1689
Simon Pilgrim24d34922018-08-17 10:40:05 +00001690 StringRef Sig1 = R"cpp(
Ilya Biryukov8a0f76b2018-08-17 09:32:30 +00001691 int foo();
1692 // Overriden doc from sema
1693 int foo(int);
1694 // Doc from sema
1695 int foo(int, int);
1696
1697 void test() {
1698 foo(^);
1699 }
Simon Pilgrim24d34922018-08-17 10:40:05 +00001700 )cpp";
1701
1702 EXPECT_THAT(
1703 signatures(Sig1, {Foo0, Foo1, Foo2}).signatures,
Ilya Biryukov8a0f76b2018-08-17 09:32:30 +00001704 ElementsAre(AllOf(Sig("foo() -> int", {}), SigDoc("Doc from the index")),
1705 AllOf(Sig("foo(int) -> int", {"int"}),
1706 SigDoc("Overriden doc from sema")),
1707 AllOf(Sig("foo(int, int) -> int", {"int", "int"}),
1708 SigDoc("Doc from sema"))));
1709}
1710
Kadir Cetinkaya516fcda2018-08-23 12:19:39 +00001711TEST(CompletionTest, CompletionFunctionArgsDisabled) {
Kadir Cetinkaya6c9f15c2018-08-17 15:42:54 +00001712 CodeCompleteOptions Opts;
Kadir Cetinkaya6c9f15c2018-08-17 15:42:54 +00001713 Opts.EnableSnippets = true;
1714 Opts.EnableFunctionArgSnippets = false;
Kadir Cetinkaya516fcda2018-08-23 12:19:39 +00001715 const std::string Header =
1716 R"cpp(
1717 void xfoo();
1718 void xfoo(int x, int y);
1719 void xbar();
1720 void f() {
1721 )cpp";
Kadir Cetinkaya6c9f15c2018-08-17 15:42:54 +00001722 {
Kadir Cetinkaya516fcda2018-08-23 12:19:39 +00001723 auto Results = completions(Header + "\nxfo^", {}, Opts);
1724 EXPECT_THAT(
1725 Results.Completions,
1726 UnorderedElementsAre(AllOf(Named("xfoo"), SnippetSuffix("()")),
1727 AllOf(Named("xfoo"), SnippetSuffix("($0)"))));
Kadir Cetinkaya6c9f15c2018-08-17 15:42:54 +00001728 }
Kadir Cetinkaya6c9f15c2018-08-17 15:42:54 +00001729 {
Kadir Cetinkaya516fcda2018-08-23 12:19:39 +00001730 auto Results = completions(Header + "\nxba^", {}, Opts);
1731 EXPECT_THAT(Results.Completions, UnorderedElementsAre(AllOf(
1732 Named("xbar"), SnippetSuffix("()"))));
Kadir Cetinkaya6c9f15c2018-08-17 15:42:54 +00001733 }
Kadir Cetinkaya6c9f15c2018-08-17 15:42:54 +00001734 {
Kadir Cetinkaya516fcda2018-08-23 12:19:39 +00001735 Opts.BundleOverloads = true;
1736 auto Results = completions(Header + "\nxfo^", {}, Opts);
1737 EXPECT_THAT(
1738 Results.Completions,
1739 UnorderedElementsAre(AllOf(Named("xfoo"), SnippetSuffix("($0)"))));
Kadir Cetinkaya6c9f15c2018-08-17 15:42:54 +00001740 }
1741}
1742
Kadir Cetinkayaf8b85a32018-08-23 13:14:50 +00001743TEST(CompletionTest, SuggestOverrides) {
1744 constexpr const char *const Text(R"cpp(
1745 class A {
1746 public:
1747 virtual void vfunc(bool param);
1748 virtual void vfunc(bool param, int p);
1749 void func(bool param);
1750 };
1751 class B : public A {
1752 virtual void ttt(bool param) const;
1753 void vfunc(bool param, int p) override;
1754 };
1755 class C : public B {
1756 public:
1757 void vfunc(bool param) override;
1758 ^
1759 };
1760 )cpp");
1761 const auto Results = completions(Text);
1762 EXPECT_THAT(Results.Completions,
1763 AllOf(Contains(Labeled("void vfunc(bool param, int p) override")),
1764 Contains(Labeled("void ttt(bool param) const override")),
1765 Not(Contains(Labeled("void vfunc(bool param) override")))));
1766}
1767
Eric Liu25d74e92018-08-24 11:23:56 +00001768TEST(SpeculateCompletionFilter, Filters) {
1769 Annotations F(R"cpp($bof^
1770 $bol^
1771 ab$ab^
1772 x.ab$dot^
1773 x.$dotempty^
1774 x::ab$scoped^
1775 x::$scopedempty^
1776
1777 )cpp");
1778 auto speculate = [&](StringRef PointName) {
1779 auto Filter = speculateCompletionFilter(F.code(), F.point(PointName));
1780 assert(Filter);
1781 return *Filter;
1782 };
1783 EXPECT_EQ(speculate("bof"), "");
1784 EXPECT_EQ(speculate("bol"), "");
1785 EXPECT_EQ(speculate("ab"), "ab");
1786 EXPECT_EQ(speculate("dot"), "ab");
1787 EXPECT_EQ(speculate("dotempty"), "");
1788 EXPECT_EQ(speculate("scoped"), "ab");
1789 EXPECT_EQ(speculate("scopedempty"), "");
1790}
1791
1792TEST(CompletionTest, EnableSpeculativeIndexRequest) {
1793 MockFSProvider FS;
1794 MockCompilationDatabase CDB;
1795 IgnoreDiagnostics DiagConsumer;
1796 ClangdServer Server(CDB, FS, DiagConsumer, ClangdServer::optsForTest());
1797
1798 auto File = testPath("foo.cpp");
1799 Annotations Test(R"cpp(
1800 namespace ns1 { int abc; }
1801 namespace ns2 { int abc; }
1802 void f() { ns1::ab$1^; ns1::ab$2^; }
1803 void f() { ns2::ab$3^; }
1804 )cpp");
1805 runAddDocument(Server, File, Test.code());
1806 clangd::CodeCompleteOptions Opts = {};
1807
1808 IndexRequestCollector Requests;
1809 Opts.Index = &Requests;
1810 Opts.SpeculativeIndexRequest = true;
1811
1812 auto CompleteAtPoint = [&](StringRef P) {
1813 cantFail(runCodeComplete(Server, File, Test.point(P), Opts));
1814 // Sleep for a while to make sure asynchronous call (if applicable) is also
1815 // triggered before callback is invoked.
1816 std::this_thread::sleep_for(std::chrono::milliseconds(100));
1817 };
1818
1819 CompleteAtPoint("1");
1820 auto Reqs1 = Requests.consumeRequests();
1821 ASSERT_EQ(Reqs1.size(), 1u);
1822 EXPECT_THAT(Reqs1[0].Scopes, UnorderedElementsAre("ns1::"));
1823
1824 CompleteAtPoint("2");
1825 auto Reqs2 = Requests.consumeRequests();
1826 // Speculation succeeded. Used speculative index result.
1827 ASSERT_EQ(Reqs2.size(), 1u);
1828 EXPECT_EQ(Reqs2[0], Reqs1[0]);
1829
1830 CompleteAtPoint("3");
1831 // Speculation failed. Sent speculative index request and the new index
1832 // request after sema.
1833 auto Reqs3 = Requests.consumeRequests();
1834 ASSERT_EQ(Reqs3.size(), 2u);
1835}
1836
Eric Liu83f63e42018-09-03 10:18:21 +00001837TEST(CompletionTest, InsertTheMostPopularHeader) {
1838 std::string DeclFile = URI::createFile(testPath("foo")).toString();
1839 Symbol sym = func("Func");
1840 sym.CanonicalDeclaration.FileURI = DeclFile;
1841 sym.IncludeHeaders.emplace_back("\"foo.h\"", 2);
1842 sym.IncludeHeaders.emplace_back("\"bar.h\"", 1000);
1843
1844 auto Results = completions("Fun^", {sym}).Completions;
1845 assert(!Results.empty());
1846 EXPECT_THAT(Results[0], AllOf(Named("Func"), InsertInclude("\"bar.h\"")));
1847 EXPECT_EQ(Results[0].Includes.size(), 2u);
1848}
1849
1850TEST(CompletionTest, NoInsertIncludeIfOnePresent) {
1851 MockFSProvider FS;
1852 MockCompilationDatabase CDB;
1853
1854 std::string FooHeader = testPath("foo.h");
1855 FS.Files[FooHeader] = "";
1856
1857 IgnoreDiagnostics DiagConsumer;
1858 ClangdServer Server(CDB, FS, DiagConsumer, ClangdServer::optsForTest());
1859
1860 std::string DeclFile = URI::createFile(testPath("foo")).toString();
1861 Symbol sym = func("Func");
1862 sym.CanonicalDeclaration.FileURI = DeclFile;
1863 sym.IncludeHeaders.emplace_back("\"foo.h\"", 2);
1864 sym.IncludeHeaders.emplace_back("\"bar.h\"", 1000);
1865
1866 EXPECT_THAT(
1867 completions(Server, "#include \"foo.h\"\nFun^", {sym}).Completions,
1868 UnorderedElementsAre(
1869 AllOf(Named("Func"), HasInclude("\"foo.h\""), Not(InsertInclude()))));
1870}
1871
Sam McCall9aad25f2017-12-05 07:20:26 +00001872} // namespace
1873} // namespace clangd
1874} // namespace clang