blob: e81be67da445f78869e28e55e43f70a133e81245 [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 Biryukov940901e2017-12-13 12:51:22 +000014#include "Context.h"
Ilya Biryukov5a85b8e2017-12-13 12:53:16 +000015#include "Matchers.h"
Sam McCall9aad25f2017-12-05 07:20:26 +000016#include "Protocol.h"
Sam McCallb536a2a2017-12-19 12:23:48 +000017#include "SourceCode.h"
Sam McCall9aad25f2017-12-05 07:20:26 +000018#include "TestFS.h"
Eric Liu6f648df2017-12-19 16:50:37 +000019#include "index/MemIndex.h"
Sam McCall0faecf02018-01-15 12:33:00 +000020#include "index/Merge.h"
Sam McCallf6ae3232017-12-05 20:11:29 +000021#include "gmock/gmock.h"
Sam McCall9aad25f2017-12-05 07:20:26 +000022#include "gtest/gtest.h"
23
24namespace clang {
25namespace clangd {
Sam McCall800d4372017-12-19 10:29:27 +000026// Let GMock print completion items and signature help.
Sam McCallf6ae3232017-12-05 20:11:29 +000027void PrintTo(const CompletionItem &I, std::ostream *O) {
28 llvm::raw_os_ostream OS(*O);
Sam McCall44fdcec22017-12-08 15:00:59 +000029 OS << I.label << " - " << toJSON(I);
30}
31void PrintTo(const std::vector<CompletionItem> &V, std::ostream *O) {
32 *O << "{\n";
33 for (const auto &I : V) {
34 *O << "\t";
35 PrintTo(I, O);
36 *O << "\n";
37 }
38 *O << "}";
Sam McCallf6ae3232017-12-05 20:11:29 +000039}
Sam McCall800d4372017-12-19 10:29:27 +000040void PrintTo(const SignatureInformation &I, std::ostream *O) {
41 llvm::raw_os_ostream OS(*O);
42 OS << I.label << " - " << toJSON(I);
43}
44void PrintTo(const std::vector<SignatureInformation> &V, std::ostream *O) {
45 *O << "{\n";
46 for (const auto &I : V) {
47 *O << "\t";
48 PrintTo(I, O);
49 *O << "\n";
50 }
51 *O << "}";
52}
Sam McCallf6ae3232017-12-05 20:11:29 +000053
Sam McCall9aad25f2017-12-05 07:20:26 +000054namespace {
55using namespace llvm;
Sam McCallf6ae3232017-12-05 20:11:29 +000056using ::testing::AllOf;
57using ::testing::Contains;
Ilya Biryukov5a5e1ca2017-12-29 14:59:22 +000058using ::testing::Each;
Sam McCallf6ae3232017-12-05 20:11:29 +000059using ::testing::ElementsAre;
Sam McCallf6ae3232017-12-05 20:11:29 +000060using ::testing::Not;
Sam McCall3d139c52018-01-12 18:30:08 +000061using ::testing::UnorderedElementsAre;
Sam McCall9aad25f2017-12-05 07:20:26 +000062
63class IgnoreDiagnostics : public DiagnosticsConsumer {
Ilya Biryukov95558392018-01-10 17:59:27 +000064 void
65 onDiagnosticsReady(const Context &Ctx, PathRef File,
66 Tagged<std::vector<DiagWithFixIts>> Diagnostics) override {
67 }
Sam McCall9aad25f2017-12-05 07:20:26 +000068};
69
Sam McCallf6ae3232017-12-05 20:11:29 +000070// GMock helpers for matching completion items.
71MATCHER_P(Named, Name, "") { return arg.insertText == Name; }
Sam McCall44fdcec22017-12-08 15:00:59 +000072MATCHER_P(Labeled, Label, "") { return arg.label == Label; }
73MATCHER_P(Kind, K, "") { return arg.kind == K; }
Eric Liu6f648df2017-12-19 16:50:37 +000074MATCHER_P(Filter, F, "") { return arg.filterText == F; }
Eric Liu76f6b442018-01-09 17:32:00 +000075MATCHER_P(Doc, D, "") { return arg.documentation == D; }
76MATCHER_P(Detail, D, "") { return arg.detail == D; }
Sam McCall44fdcec22017-12-08 15:00:59 +000077MATCHER_P(PlainText, Text, "") {
78 return arg.insertTextFormat == clangd::InsertTextFormat::PlainText &&
79 arg.insertText == Text;
80}
81MATCHER_P(Snippet, Text, "") {
82 return arg.insertTextFormat == clangd::InsertTextFormat::Snippet &&
83 arg.insertText == Text;
84}
Ilya Biryukov5a5e1ca2017-12-29 14:59:22 +000085MATCHER(FilterContainsName, "") {
86 if (arg.filterText.empty())
87 return true;
88 return llvm::StringRef(arg.insertText).contains(arg.filterText);
89}
Sam McCallf6ae3232017-12-05 20:11:29 +000090// Shorthand for Contains(Named(Name)).
91Matcher<const std::vector<CompletionItem> &> Has(std::string Name) {
92 return Contains(Named(std::move(Name)));
93}
Sam McCall44fdcec22017-12-08 15:00:59 +000094Matcher<const std::vector<CompletionItem> &> Has(std::string Name,
95 CompletionItemKind K) {
96 return Contains(AllOf(Named(std::move(Name)), Kind(K)));
Sam McCallf6ae3232017-12-05 20:11:29 +000097}
Sam McCall44fdcec22017-12-08 15:00:59 +000098MATCHER(IsDocumented, "") { return !arg.documentation.empty(); }
Sam McCall9aad25f2017-12-05 07:20:26 +000099
Sam McCalla15c2d62018-01-18 09:27:56 +0000100std::unique_ptr<SymbolIndex> memIndex(std::vector<Symbol> Symbols) {
101 SymbolSlab::Builder Slab;
102 for (const auto &Sym : Symbols)
103 Slab.insert(Sym);
104 return MemIndex::build(std::move(Slab).build());
105}
106
107// Builds a server and runs code completion.
108// If IndexSymbols is non-empty, an index will be built and passed to opts.
Sam McCallf6ae3232017-12-05 20:11:29 +0000109CompletionList completions(StringRef Text,
Sam McCalla15c2d62018-01-18 09:27:56 +0000110 std::vector<Symbol> IndexSymbols = {},
Sam McCallf6ae3232017-12-05 20:11:29 +0000111 clangd::CodeCompleteOptions Opts = {}) {
Sam McCalla15c2d62018-01-18 09:27:56 +0000112 std::unique_ptr<SymbolIndex> OverrideIndex;
113 if (!IndexSymbols.empty()) {
114 assert(!Opts.Index && "both Index and IndexSymbols given!");
115 OverrideIndex = memIndex(std::move(IndexSymbols));
116 Opts.Index = OverrideIndex.get();
117 }
118
Sam McCall9aad25f2017-12-05 07:20:26 +0000119 MockFSProvider FS;
Sam McCall93cd9912017-12-05 07:34:35 +0000120 MockCompilationDatabase CDB;
Sam McCallf6ae3232017-12-05 20:11:29 +0000121 IgnoreDiagnostics DiagConsumer;
Sam McCall9aad25f2017-12-05 07:20:26 +0000122 ClangdServer Server(CDB, DiagConsumer, FS, getDefaultAsyncThreadsCount(),
Ilya Biryukov940901e2017-12-13 12:51:22 +0000123 /*StorePreamblesInMemory=*/true);
Sam McCallf6ae3232017-12-05 20:11:29 +0000124 auto File = getVirtualTestFilePath("foo.cpp");
Sam McCall328cbdb2017-12-20 16:06:05 +0000125 Annotations Test(Text);
Sam McCall3d139c52018-01-12 18:30:08 +0000126 Server.addDocument(Context::empty(), File, Test.code()).wait();
Ilya Biryukov5a5e1ca2017-12-29 14:59:22 +0000127 auto CompletionList =
128 Server.codeComplete(Context::empty(), File, Test.point(), Opts)
129 .get()
130 .second.Value;
131 // Sanity-check that filterText is valid.
132 EXPECT_THAT(CompletionList.items, Each(FilterContainsName()));
133 return CompletionList;
Sam McCall9aad25f2017-12-05 07:20:26 +0000134}
135
Sam McCalla15c2d62018-01-18 09:27:56 +0000136// Helpers to produce fake index symbols for memIndex() or completions().
137Symbol sym(StringRef QName, index::SymbolKind Kind) {
138 Symbol Sym;
139 Sym.ID = SymbolID(QName);
140 size_t Pos = QName.rfind("::");
141 if (Pos == llvm::StringRef::npos) {
142 Sym.Name = QName;
143 Sym.Scope = "";
144 } else {
145 Sym.Name = QName.substr(Pos + 2);
146 Sym.Scope = QName.substr(0, Pos);
147 }
148 Sym.CompletionPlainInsertText = Sym.Name;
149 Sym.CompletionLabel = Sym.Name;
150 Sym.SymInfo.Kind = Kind;
151 return Sym;
152}
153Symbol func(StringRef Name) { return sym(Name, index::SymbolKind::Function); }
154Symbol cls(StringRef Name) { return sym(Name, index::SymbolKind::Class); }
155Symbol var(StringRef Name) { return sym(Name, index::SymbolKind::Variable); }
156
Sam McCallf6ae3232017-12-05 20:11:29 +0000157TEST(CompletionTest, Limit) {
158 clangd::CodeCompleteOptions Opts;
159 Opts.Limit = 2;
160 auto Results = completions(R"cpp(
Sam McCall9aad25f2017-12-05 07:20:26 +0000161struct ClassWithMembers {
162 int AAA();
163 int BBB();
164 int CCC();
165}
Sam McCallf6ae3232017-12-05 20:11:29 +0000166int main() { ClassWithMembers().^ }
Sam McCall9aad25f2017-12-05 07:20:26 +0000167 )cpp",
Sam McCalla15c2d62018-01-18 09:27:56 +0000168 /*IndexSymbols=*/{}, Opts);
Sam McCall9aad25f2017-12-05 07:20:26 +0000169
170 EXPECT_TRUE(Results.isIncomplete);
Sam McCallf6ae3232017-12-05 20:11:29 +0000171 EXPECT_THAT(Results.items, ElementsAre(Named("AAA"), Named("BBB")));
Sam McCall9aad25f2017-12-05 07:20:26 +0000172}
173
Sam McCallf6ae3232017-12-05 20:11:29 +0000174TEST(CompletionTest, Filter) {
175 std::string Body = R"cpp(
Sam McCall9aad25f2017-12-05 07:20:26 +0000176 int Abracadabra;
177 int Alakazam;
178 struct S {
179 int FooBar;
180 int FooBaz;
181 int Qux;
182 };
183 )cpp";
Sam McCallf6ae3232017-12-05 20:11:29 +0000184 EXPECT_THAT(completions(Body + "int main() { S().Foba^ }").items,
185 AllOf(Has("FooBar"), Has("FooBaz"), Not(Has("Qux"))));
Sam McCall9aad25f2017-12-05 07:20:26 +0000186
Sam McCallf6ae3232017-12-05 20:11:29 +0000187 EXPECT_THAT(completions(Body + "int main() { S().FR^ }").items,
188 AllOf(Has("FooBar"), Not(Has("FooBaz")), Not(Has("Qux"))));
Sam McCall9aad25f2017-12-05 07:20:26 +0000189
Sam McCallf6ae3232017-12-05 20:11:29 +0000190 EXPECT_THAT(completions(Body + "int main() { S().opr^ }").items,
191 Has("operator="));
Sam McCall9aad25f2017-12-05 07:20:26 +0000192
Sam McCallf6ae3232017-12-05 20:11:29 +0000193 EXPECT_THAT(completions(Body + "int main() { aaa^ }").items,
194 AllOf(Has("Abracadabra"), Has("Alakazam")));
Sam McCall9aad25f2017-12-05 07:20:26 +0000195
Sam McCallf6ae3232017-12-05 20:11:29 +0000196 EXPECT_THAT(completions(Body + "int main() { _a^ }").items,
197 AllOf(Has("static_cast"), Not(Has("Abracadabra"))));
Sam McCall9aad25f2017-12-05 07:20:26 +0000198}
199
Sam McCallf6ae3232017-12-05 20:11:29 +0000200void TestAfterDotCompletion(clangd::CodeCompleteOptions Opts) {
Sam McCall44fdcec22017-12-08 15:00:59 +0000201 auto Results = completions(
202 R"cpp(
203 #define MACRO X
Sam McCall9aad25f2017-12-05 07:20:26 +0000204
Sam McCall44fdcec22017-12-08 15:00:59 +0000205 int global_var;
Sam McCall9aad25f2017-12-05 07:20:26 +0000206
Sam McCall44fdcec22017-12-08 15:00:59 +0000207 int global_func();
Sam McCall9aad25f2017-12-05 07:20:26 +0000208
Sam McCall44fdcec22017-12-08 15:00:59 +0000209 struct GlobalClass {};
Sam McCall9aad25f2017-12-05 07:20:26 +0000210
Sam McCall44fdcec22017-12-08 15:00:59 +0000211 struct ClassWithMembers {
212 /// Doc for method.
213 int method();
Sam McCall9aad25f2017-12-05 07:20:26 +0000214
Sam McCall44fdcec22017-12-08 15:00:59 +0000215 int field;
216 private:
217 int private_field;
218 };
Sam McCall9aad25f2017-12-05 07:20:26 +0000219
Sam McCall44fdcec22017-12-08 15:00:59 +0000220 int test() {
221 struct LocalClass {};
Sam McCall9aad25f2017-12-05 07:20:26 +0000222
Sam McCall44fdcec22017-12-08 15:00:59 +0000223 /// Doc for local_var.
224 int local_var;
Sam McCall9aad25f2017-12-05 07:20:26 +0000225
Sam McCall44fdcec22017-12-08 15:00:59 +0000226 ClassWithMembers().^
227 }
228 )cpp",
Sam McCalla15c2d62018-01-18 09:27:56 +0000229 /*IndexSymbols=*/{}, Opts);
Sam McCall9aad25f2017-12-05 07:20:26 +0000230
Sam McCallf6ae3232017-12-05 20:11:29 +0000231 // Class members. The only items that must be present in after-dot
232 // completion.
Sam McCall44fdcec22017-12-08 15:00:59 +0000233 EXPECT_THAT(
234 Results.items,
235 AllOf(Has(Opts.EnableSnippets ? "method()" : "method"), Has("field")));
236 EXPECT_IFF(Opts.IncludeIneligibleResults, Results.items,
237 Has("private_field"));
Sam McCallf6ae3232017-12-05 20:11:29 +0000238 // Global items.
Sam McCall44fdcec22017-12-08 15:00:59 +0000239 EXPECT_THAT(Results.items, Not(AnyOf(Has("global_var"), Has("global_func"),
240 Has("global_func()"), Has("GlobalClass"),
241 Has("MACRO"), Has("LocalClass"))));
Sam McCallf6ae3232017-12-05 20:11:29 +0000242 // There should be no code patterns (aka snippets) in after-dot
243 // completion. At least there aren't any we're aware of.
Sam McCall44fdcec22017-12-08 15:00:59 +0000244 EXPECT_THAT(Results.items, Not(Contains(Kind(CompletionItemKind::Snippet))));
Sam McCallf6ae3232017-12-05 20:11:29 +0000245 // Check documentation.
Sam McCall44fdcec22017-12-08 15:00:59 +0000246 EXPECT_IFF(Opts.IncludeBriefComments, Results.items,
247 Contains(IsDocumented()));
Sam McCallf6ae3232017-12-05 20:11:29 +0000248}
Sam McCall9aad25f2017-12-05 07:20:26 +0000249
Sam McCallf6ae3232017-12-05 20:11:29 +0000250void TestGlobalScopeCompletion(clangd::CodeCompleteOptions Opts) {
Sam McCall44fdcec22017-12-08 15:00:59 +0000251 auto Results = completions(
252 R"cpp(
253 #define MACRO X
Sam McCall9aad25f2017-12-05 07:20:26 +0000254
Sam McCall44fdcec22017-12-08 15:00:59 +0000255 int global_var;
256 int global_func();
Sam McCall9aad25f2017-12-05 07:20:26 +0000257
Sam McCall44fdcec22017-12-08 15:00:59 +0000258 struct GlobalClass {};
Sam McCall9aad25f2017-12-05 07:20:26 +0000259
Sam McCall44fdcec22017-12-08 15:00:59 +0000260 struct ClassWithMembers {
261 /// Doc for method.
262 int method();
263 };
Sam McCall9aad25f2017-12-05 07:20:26 +0000264
Sam McCall44fdcec22017-12-08 15:00:59 +0000265 int test() {
266 struct LocalClass {};
Sam McCall9aad25f2017-12-05 07:20:26 +0000267
Sam McCall44fdcec22017-12-08 15:00:59 +0000268 /// Doc for local_var.
269 int local_var;
Sam McCall9aad25f2017-12-05 07:20:26 +0000270
Sam McCall44fdcec22017-12-08 15:00:59 +0000271 ^
272 }
273 )cpp",
Sam McCalla15c2d62018-01-18 09:27:56 +0000274 /*IndexSymbols=*/{}, Opts);
Sam McCallf6ae3232017-12-05 20:11:29 +0000275
276 // Class members. Should never be present in global completions.
Sam McCall44fdcec22017-12-08 15:00:59 +0000277 EXPECT_THAT(Results.items,
Sam McCallf6ae3232017-12-05 20:11:29 +0000278 Not(AnyOf(Has("method"), Has("method()"), Has("field"))));
279 // Global items.
Sam McCall44fdcec22017-12-08 15:00:59 +0000280 EXPECT_IFF(Opts.IncludeGlobals, Results.items,
Sam McCallf6ae3232017-12-05 20:11:29 +0000281 AllOf(Has("global_var"),
282 Has(Opts.EnableSnippets ? "global_func()" : "global_func"),
283 Has("GlobalClass")));
284 // A macro.
Sam McCall44fdcec22017-12-08 15:00:59 +0000285 EXPECT_IFF(Opts.IncludeMacros, Results.items, Has("MACRO"));
Sam McCallf6ae3232017-12-05 20:11:29 +0000286 // Local items. Must be present always.
Ilya Biryukov9b5ffc22017-12-12 12:56:46 +0000287 EXPECT_THAT(Results.items,
288 AllOf(Has("local_var"), Has("LocalClass"),
289 Contains(Kind(CompletionItemKind::Snippet))));
Sam McCallf6ae3232017-12-05 20:11:29 +0000290 // Check documentation.
Sam McCall44fdcec22017-12-08 15:00:59 +0000291 EXPECT_IFF(Opts.IncludeBriefComments, Results.items,
292 Contains(IsDocumented()));
Sam McCallf6ae3232017-12-05 20:11:29 +0000293}
294
295TEST(CompletionTest, CompletionOptions) {
Sam McCall2c3849a2018-01-16 12:21:24 +0000296 auto Test = [&](const clangd::CodeCompleteOptions &Opts) {
297 TestAfterDotCompletion(Opts);
298 TestGlobalScopeCompletion(Opts);
299 };
300 // We used to test every combination of options, but that got too slow (2^N).
301 auto Flags = {
302 &clangd::CodeCompleteOptions::IncludeMacros,
303 &clangd::CodeCompleteOptions::IncludeGlobals,
304 &clangd::CodeCompleteOptions::IncludeBriefComments,
305 &clangd::CodeCompleteOptions::EnableSnippets,
306 &clangd::CodeCompleteOptions::IncludeCodePatterns,
307 &clangd::CodeCompleteOptions::IncludeIneligibleResults,
308 };
309 // Test default options.
310 Test({});
311 // Test with one flag flipped.
312 for (auto &F : Flags) {
313 clangd::CodeCompleteOptions O;
314 O.*F ^= true;
315 Test(O);
Sam McCall9aad25f2017-12-05 07:20:26 +0000316 }
317}
318
Sam McCallf6ae3232017-12-05 20:11:29 +0000319// Check code completion works when the file contents are overridden.
320TEST(CompletionTest, CheckContentsOverride) {
321 MockFSProvider FS;
322 IgnoreDiagnostics DiagConsumer;
323 MockCompilationDatabase CDB;
324 ClangdServer Server(CDB, DiagConsumer, FS, getDefaultAsyncThreadsCount(),
Ilya Biryukov940901e2017-12-13 12:51:22 +0000325 /*StorePreamblesInMemory=*/true);
Sam McCallf6ae3232017-12-05 20:11:29 +0000326 auto File = getVirtualTestFilePath("foo.cpp");
Ilya Biryukov940901e2017-12-13 12:51:22 +0000327 Server.addDocument(Context::empty(), File, "ignored text!");
Sam McCallf6ae3232017-12-05 20:11:29 +0000328
Sam McCall328cbdb2017-12-20 16:06:05 +0000329 Annotations Example("int cbc; int b = ^;");
330 auto Results = Server
331 .codeComplete(Context::empty(), File, Example.point(),
332 clangd::CodeCompleteOptions(),
333 StringRef(Example.code()))
334 .get()
335 .second.Value;
Sam McCallf6ae3232017-12-05 20:11:29 +0000336 EXPECT_THAT(Results.items, Contains(Named("cbc")));
337}
338
Sam McCall44fdcec22017-12-08 15:00:59 +0000339TEST(CompletionTest, Priorities) {
340 auto Internal = completions(R"cpp(
341 class Foo {
342 public: void pub();
343 protected: void prot();
344 private: void priv();
345 };
346 void Foo::pub() { this->^ }
347 )cpp");
348 EXPECT_THAT(Internal.items,
349 HasSubsequence(Named("priv"), Named("prot"), Named("pub")));
350
351 auto External = completions(R"cpp(
352 class Foo {
353 public: void pub();
354 protected: void prot();
355 private: void priv();
356 };
357 void test() {
358 Foo F;
359 F.^
360 }
361 )cpp");
362 EXPECT_THAT(External.items,
363 AllOf(Has("pub"), Not(Has("prot")), Not(Has("priv"))));
364}
365
366TEST(CompletionTest, Qualifiers) {
367 auto Results = completions(R"cpp(
368 class Foo {
369 public: int foo() const;
370 int bar() const;
371 };
372 class Bar : public Foo {
373 int foo() const;
374 };
375 void test() { Bar().^ }
376 )cpp");
377 EXPECT_THAT(Results.items, HasSubsequence(Labeled("bar() const"),
378 Labeled("Foo::foo() const")));
379 EXPECT_THAT(Results.items, Not(Contains(Labeled("foo() const")))); // private
380}
381
382TEST(CompletionTest, Snippets) {
383 clangd::CodeCompleteOptions Opts;
384 Opts.EnableSnippets = true;
385 auto Results = completions(
386 R"cpp(
387 struct fake {
388 int a;
389 int f(int i, const float f) const;
390 };
391 int main() {
392 fake f;
393 f.^
394 }
395 )cpp",
Sam McCalla15c2d62018-01-18 09:27:56 +0000396 /*IndexSymbols=*/{}, Opts);
Sam McCall44fdcec22017-12-08 15:00:59 +0000397 EXPECT_THAT(Results.items,
Eric Liu63696e12017-12-20 17:24:31 +0000398 HasSubsequence(Snippet("a"),
Sam McCall44fdcec22017-12-08 15:00:59 +0000399 Snippet("f(${1:int i}, ${2:const float f})")));
400}
401
402TEST(CompletionTest, Kinds) {
403 auto Results = completions(R"cpp(
404 #define MACRO X
405 int variable;
406 struct Struct {};
407 int function();
408 int X = ^
409 )cpp");
410 EXPECT_THAT(Results.items, Has("function", CompletionItemKind::Function));
411 EXPECT_THAT(Results.items, Has("variable", CompletionItemKind::Variable));
412 EXPECT_THAT(Results.items, Has("int", CompletionItemKind::Keyword));
413 EXPECT_THAT(Results.items, Has("Struct", CompletionItemKind::Class));
414 EXPECT_THAT(Results.items, Has("MACRO", CompletionItemKind::Text));
415
Sam McCall44fdcec22017-12-08 15:00:59 +0000416 Results = completions("nam^");
417 EXPECT_THAT(Results.items, Has("namespace", CompletionItemKind::Snippet));
418}
419
Sam McCall84652cc2018-01-12 16:16:09 +0000420TEST(CompletionTest, NoDuplicates) {
421 auto Items = completions(R"cpp(
422struct Adapter {
423 void method();
424};
425
426void Adapter::method() {
427 Adapter^
428}
429 )cpp")
430 .items;
431
432 // Make sure there are no duplicate entries of 'Adapter'.
433 EXPECT_THAT(Items, ElementsAre(Named("Adapter"), Named("~Adapter")));
434}
435
436TEST(CompletionTest, FuzzyRanking) {
437 auto Items = completions(R"cpp(
438 struct fake { int BigBang, Babble, Ball; };
439 int main() { fake().bb^ }")cpp").items;
440 // BigBang is a better match than Babble. Ball doesn't match at all.
441 EXPECT_THAT(Items, ElementsAre(Named("BigBang"), Named("Babble")));
442}
443
Sam McCalla15c2d62018-01-18 09:27:56 +0000444TEST(CompletionTest, NoIndex) {
445 auto Results = completions(R"cpp(
446 namespace ns { class Local {}; }
447 void f() { ns::^ }
448 )cpp");
449 EXPECT_THAT(Results.items, Has("Local"));
450}
451
452TEST(CompletionTest, StaticAndDynamicIndex) {
453 clangd::CodeCompleteOptions Opts;
454 auto StaticIdx = memIndex({cls("ns::XYZ")});
455 auto DynamicIdx = memIndex({func("ns::foo")});
456 auto Merge = mergeIndex(DynamicIdx.get(), StaticIdx.get());
457 Opts.Index = Merge.get();
458
459 auto Results = completions(
460 R"cpp(
461 void f() { ::ns::^ }
462 )cpp",
463 /*IndexSymbols=*/{}, Opts);
464 EXPECT_THAT(Results.items, Contains(Labeled("[I]XYZ")));
465 EXPECT_THAT(Results.items, Contains(Labeled("[I]foo")));
466}
467
468TEST(CompletionTest, IndexScope) {
469 auto Results = completions(
470 R"cpp(
471 namespace ns { int local; }
472 void f() { ns::^ }
473 )cpp",
474 {cls("ns::XYZ"), cls("nx::XYZ"), func("ns::foo")});
475 EXPECT_THAT(Results.items,
476 UnorderedElementsAre(Named("XYZ"), Named("foo"), Named("local")));
477}
478
479TEST(CompletionTest, IndexBasedWithFilter) {
480 auto Results = completions(
481 R"cpp(
482 void f() { ns::x^ }
483 )cpp",
484 {cls("ns::XYZ"), func("ns::foo")});
485 EXPECT_THAT(Results.items,
486 UnorderedElementsAre(AllOf(Named("XYZ"), Filter("XYZ"))));
487}
488
489TEST(CompletionTest, IndexGlobalQualified) {
490 auto Results = completions(
491 R"cpp(
492 void f() { ::^ }
493 )cpp",
494 {cls("XYZ")});
495 EXPECT_THAT(Results.items, AllOf(Has("XYZ", CompletionItemKind::Class),
496 Has("f", CompletionItemKind::Function)));
497}
498
499TEST(CompletionTest, IndexFullyQualifiedScope) {
500 auto Results = completions(
501 R"cpp(
502 void f() { ::ns::^ }
503 )cpp",
504 {cls("ns::XYZ")});
505 EXPECT_THAT(Results.items, Has("XYZ", CompletionItemKind::Class));
506}
507
508TEST(CompletionTest, IndexSuppressesPreambleCompletions) {
509 MockFSProvider FS;
510 MockCompilationDatabase CDB;
511 IgnoreDiagnostics DiagConsumer;
512 ClangdServer Server(CDB, DiagConsumer, FS, getDefaultAsyncThreadsCount(),
513 /*StorePreamblesInMemory=*/true);
514
515 FS.Files[getVirtualTestFilePath("bar.h")] =
516 R"cpp(namespace ns { int preamble; })cpp";
517 auto File = getVirtualTestFilePath("foo.cpp");
518 Annotations Test(R"cpp(
519 #include "bar.h"
520 namespace ns { int local; }
521 void f() { ns::^ }
522 )cpp");
523 Server.addDocument(Context::empty(), File, Test.code()).wait();
524 clangd::CodeCompleteOptions Opts = {};
525
526 auto WithoutIndex =
527 Server.codeComplete(Context::empty(), File, Test.point(), Opts)
528 .get()
529 .second.Value;
530 EXPECT_THAT(WithoutIndex.items,
531 UnorderedElementsAre(Named("local"), Named("preamble")));
532
533 auto I = memIndex({var("ns::index")});
534 Opts.Index = I.get();
535 auto WithIndex =
536 Server.codeComplete(Context::empty(), File, Test.point(), Opts)
537 .get()
538 .second.Value;
539 EXPECT_THAT(WithIndex.items,
540 UnorderedElementsAre(Named("local"), Named("index")));
541}
542
543TEST(CompletionTest, DynamicIndexMultiFile) {
544 MockFSProvider FS;
545 MockCompilationDatabase CDB;
546 IgnoreDiagnostics DiagConsumer;
547 ClangdServer Server(CDB, DiagConsumer, FS, getDefaultAsyncThreadsCount(),
548 /*StorePreamblesInMemory=*/true,
549 /*BuildDynamicSymbolIndex=*/true);
550
551 Server
552 .addDocument(Context::empty(), getVirtualTestFilePath("foo.cpp"), R"cpp(
553 namespace ns { class XYZ {}; void foo(int x) {} }
554 )cpp")
555 .wait();
556
557 auto File = getVirtualTestFilePath("bar.cpp");
558 Annotations Test(R"cpp(
559 namespace ns {
560 class XXX {};
561 /// Doooc
562 void fooooo() {}
563 }
564 void f() { ns::^ }
565 )cpp");
566 Server.addDocument(Context::empty(), File, Test.code()).wait();
567
568 auto Results = Server.codeComplete(Context::empty(), File, Test.point(), {})
569 .get()
570 .second.Value;
571 // "XYZ" and "foo" are not included in the file being completed but are still
572 // visible through the index.
573 EXPECT_THAT(Results.items, Has("XYZ", CompletionItemKind::Class));
574 EXPECT_THAT(Results.items, Has("foo", CompletionItemKind::Function));
575 EXPECT_THAT(Results.items, Has("XXX", CompletionItemKind::Class));
576 EXPECT_THAT(Results.items, Contains(AllOf(Named("fooooo"), Filter("fooooo"),
577 Kind(CompletionItemKind::Function),
578 Doc("Doooc"), Detail("void"))));
579}
580
Sam McCall800d4372017-12-19 10:29:27 +0000581SignatureHelp signatures(StringRef Text) {
582 MockFSProvider FS;
583 MockCompilationDatabase CDB;
584 IgnoreDiagnostics DiagConsumer;
585 ClangdServer Server(CDB, DiagConsumer, FS, getDefaultAsyncThreadsCount(),
586 /*StorePreamblesInMemory=*/true);
587 auto File = getVirtualTestFilePath("foo.cpp");
Sam McCall328cbdb2017-12-20 16:06:05 +0000588 Annotations Test(Text);
589 Server.addDocument(Context::empty(), File, Test.code());
590 auto R = Server.signatureHelp(Context::empty(), File, Test.point());
Sam McCall800d4372017-12-19 10:29:27 +0000591 assert(R);
592 return R.get().Value;
593}
594
595MATCHER_P(ParamsAre, P, "") {
596 if (P.size() != arg.parameters.size())
597 return false;
598 for (unsigned I = 0; I < P.size(); ++I)
599 if (P[I] != arg.parameters[I].label)
600 return false;
601 return true;
602}
603
604Matcher<SignatureInformation> Sig(std::string Label,
605 std::vector<std::string> Params) {
606 return AllOf(Labeled(Label), ParamsAre(Params));
607}
608
609TEST(SignatureHelpTest, Overloads) {
610 auto Results = signatures(R"cpp(
611 void foo(int x, int y);
612 void foo(int x, float y);
613 void foo(float x, int y);
614 void foo(float x, float y);
615 void bar(int x, int y = 0);
616 int main() { foo(^); }
617 )cpp");
618 EXPECT_THAT(Results.signatures,
619 UnorderedElementsAre(
620 Sig("foo(float x, float y) -> void", {"float x", "float y"}),
621 Sig("foo(float x, int y) -> void", {"float x", "int y"}),
622 Sig("foo(int x, float y) -> void", {"int x", "float y"}),
623 Sig("foo(int x, int y) -> void", {"int x", "int y"})));
624 // We always prefer the first signature.
625 EXPECT_EQ(0, Results.activeSignature);
626 EXPECT_EQ(0, Results.activeParameter);
627}
628
629TEST(SignatureHelpTest, DefaultArgs) {
630 auto Results = signatures(R"cpp(
631 void bar(int x, int y = 0);
632 void bar(float x = 0, int y = 42);
633 int main() { bar(^
634 )cpp");
635 EXPECT_THAT(Results.signatures,
636 UnorderedElementsAre(
637 Sig("bar(int x, int y = 0) -> void", {"int x", "int y = 0"}),
638 Sig("bar(float x = 0, int y = 42) -> void",
639 {"float x = 0", "int y = 42"})));
640 EXPECT_EQ(0, Results.activeSignature);
641 EXPECT_EQ(0, Results.activeParameter);
642}
643
644TEST(SignatureHelpTest, ActiveArg) {
645 auto Results = signatures(R"cpp(
646 int baz(int a, int b, int c);
647 int main() { baz(baz(1,2,3), ^); }
648 )cpp");
649 EXPECT_THAT(Results.signatures,
650 ElementsAre(Sig("baz(int a, int b, int c) -> int",
651 {"int a", "int b", "int c"})));
652 EXPECT_EQ(0, Results.activeSignature);
653 EXPECT_EQ(1, Results.activeParameter);
654}
655
Sam McCall9aad25f2017-12-05 07:20:26 +0000656} // namespace
657} // namespace clangd
658} // namespace clang