blob: 7ffff71a006f0b887b8aac2000daad94718b3bca [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 McCallb536a2a2017-12-19 12:23:48 +000016#include "SourceCode.h"
Ilya Biryukovcd5eb002018-02-12 11:37:28 +000017#include "SyncAPI.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 McCallf6ae3232017-12-05 20:11:29 +000020#include "gmock/gmock.h"
Sam McCall9aad25f2017-12-05 07:20:26 +000021#include "gtest/gtest.h"
22
23namespace clang {
24namespace clangd {
Sam McCall800d4372017-12-19 10:29:27 +000025// Let GMock print completion items and signature help.
Sam McCallf6ae3232017-12-05 20:11:29 +000026void PrintTo(const CompletionItem &I, std::ostream *O) {
27 llvm::raw_os_ostream OS(*O);
Sam McCall44fdcec22017-12-08 15:00:59 +000028 OS << I.label << " - " << toJSON(I);
29}
30void PrintTo(const std::vector<CompletionItem> &V, std::ostream *O) {
31 *O << "{\n";
32 for (const auto &I : V) {
33 *O << "\t";
34 PrintTo(I, O);
35 *O << "\n";
36 }
37 *O << "}";
Sam McCallf6ae3232017-12-05 20:11:29 +000038}
Sam McCall800d4372017-12-19 10:29:27 +000039void PrintTo(const SignatureInformation &I, std::ostream *O) {
40 llvm::raw_os_ostream OS(*O);
41 OS << I.label << " - " << toJSON(I);
42}
43void PrintTo(const std::vector<SignatureInformation> &V, std::ostream *O) {
44 *O << "{\n";
45 for (const auto &I : V) {
46 *O << "\t";
47 PrintTo(I, O);
48 *O << "\n";
49 }
50 *O << "}";
51}
Sam McCallf6ae3232017-12-05 20:11:29 +000052
Sam McCall9aad25f2017-12-05 07:20:26 +000053namespace {
54using namespace llvm;
Sam McCallf6ae3232017-12-05 20:11:29 +000055using ::testing::AllOf;
56using ::testing::Contains;
Ilya Biryukov5a5e1ca2017-12-29 14:59:22 +000057using ::testing::Each;
Sam McCallf6ae3232017-12-05 20:11:29 +000058using ::testing::ElementsAre;
Sam McCallf6ae3232017-12-05 20:11:29 +000059using ::testing::Not;
Sam McCall3d139c52018-01-12 18:30:08 +000060using ::testing::UnorderedElementsAre;
Haojian Wu061c73e2018-01-23 11:37:26 +000061using ::testing::Field;
Sam McCall9aad25f2017-12-05 07:20:26 +000062
63class IgnoreDiagnostics : public DiagnosticsConsumer {
Sam McCalld1a7a372018-01-31 13:40:48 +000064 void onDiagnosticsReady(
65 PathRef File, Tagged<std::vector<DiagWithFixIts>> Diagnostics) override {}
Sam McCall9aad25f2017-12-05 07:20:26 +000066};
67
Sam McCallf6ae3232017-12-05 20:11:29 +000068// GMock helpers for matching completion items.
69MATCHER_P(Named, Name, "") { return arg.insertText == Name; }
Sam McCall44fdcec22017-12-08 15:00:59 +000070MATCHER_P(Labeled, Label, "") { return arg.label == Label; }
71MATCHER_P(Kind, K, "") { return arg.kind == K; }
Eric Liu6f648df2017-12-19 16:50:37 +000072MATCHER_P(Filter, F, "") { return arg.filterText == F; }
Eric Liu76f6b442018-01-09 17:32:00 +000073MATCHER_P(Doc, D, "") { return arg.documentation == D; }
74MATCHER_P(Detail, D, "") { return arg.detail == D; }
Sam McCall44fdcec22017-12-08 15:00:59 +000075MATCHER_P(PlainText, Text, "") {
76 return arg.insertTextFormat == clangd::InsertTextFormat::PlainText &&
77 arg.insertText == Text;
78}
79MATCHER_P(Snippet, Text, "") {
80 return arg.insertTextFormat == clangd::InsertTextFormat::Snippet &&
81 arg.insertText == Text;
82}
Sam McCall545a20d2018-01-19 14:34:02 +000083MATCHER(NameContainsFilter, "") {
Ilya Biryukov5a5e1ca2017-12-29 14:59:22 +000084 if (arg.filterText.empty())
85 return true;
86 return llvm::StringRef(arg.insertText).contains(arg.filterText);
87}
Sam McCallf6ae3232017-12-05 20:11:29 +000088// Shorthand for Contains(Named(Name)).
89Matcher<const std::vector<CompletionItem> &> Has(std::string Name) {
90 return Contains(Named(std::move(Name)));
91}
Sam McCall44fdcec22017-12-08 15:00:59 +000092Matcher<const std::vector<CompletionItem> &> Has(std::string Name,
93 CompletionItemKind K) {
94 return Contains(AllOf(Named(std::move(Name)), Kind(K)));
Sam McCallf6ae3232017-12-05 20:11:29 +000095}
Sam McCall44fdcec22017-12-08 15:00:59 +000096MATCHER(IsDocumented, "") { return !arg.documentation.empty(); }
Sam McCall9aad25f2017-12-05 07:20:26 +000097
Sam McCalla15c2d62018-01-18 09:27:56 +000098std::unique_ptr<SymbolIndex> memIndex(std::vector<Symbol> Symbols) {
99 SymbolSlab::Builder Slab;
100 for (const auto &Sym : Symbols)
101 Slab.insert(Sym);
102 return MemIndex::build(std::move(Slab).build());
103}
104
105// Builds a server and runs code completion.
106// If IndexSymbols is non-empty, an index will be built and passed to opts.
Sam McCallf6ae3232017-12-05 20:11:29 +0000107CompletionList completions(StringRef Text,
Sam McCalla15c2d62018-01-18 09:27:56 +0000108 std::vector<Symbol> IndexSymbols = {},
Sam McCallf6ae3232017-12-05 20:11:29 +0000109 clangd::CodeCompleteOptions Opts = {}) {
Sam McCalla15c2d62018-01-18 09:27:56 +0000110 std::unique_ptr<SymbolIndex> OverrideIndex;
111 if (!IndexSymbols.empty()) {
112 assert(!Opts.Index && "both Index and IndexSymbols given!");
113 OverrideIndex = memIndex(std::move(IndexSymbols));
114 Opts.Index = OverrideIndex.get();
115 }
116
Sam McCall9aad25f2017-12-05 07:20:26 +0000117 MockFSProvider FS;
Sam McCall93cd9912017-12-05 07:34:35 +0000118 MockCompilationDatabase CDB;
Sam McCallf6ae3232017-12-05 20:11:29 +0000119 IgnoreDiagnostics DiagConsumer;
Sam McCall7363a2f2018-03-05 17:28:54 +0000120 ClangdServer Server(CDB, FS, DiagConsumer, ClangdServer::optsForTest());
Sam McCallc1568062018-02-16 09:41:43 +0000121 auto File = testPath("foo.cpp");
Sam McCall328cbdb2017-12-20 16:06:05 +0000122 Annotations Test(Text);
Sam McCall7363a2f2018-03-05 17:28:54 +0000123 runAddDocument(Server, File, Test.code());
Ilya Biryukovcd5eb002018-02-12 11:37:28 +0000124 auto CompletionList = runCodeComplete(Server, File, Test.point(), Opts).Value;
Ilya Biryukov5a5e1ca2017-12-29 14:59:22 +0000125 // Sanity-check that filterText is valid.
Sam McCall545a20d2018-01-19 14:34:02 +0000126 EXPECT_THAT(CompletionList.items, Each(NameContainsFilter()));
Ilya Biryukov5a5e1ca2017-12-29 14:59:22 +0000127 return CompletionList;
Sam McCall9aad25f2017-12-05 07:20:26 +0000128}
129
Sam McCall545a20d2018-01-19 14:34:02 +0000130std::string replace(StringRef Haystack, StringRef Needle, StringRef Repl) {
131 std::string Result;
132 raw_string_ostream OS(Result);
133 std::pair<StringRef, StringRef> Split;
134 for (Split = Haystack.split(Needle); !Split.second.empty();
135 Split = Split.first.split(Needle))
136 OS << Split.first << Repl;
137 Result += Split.first;
138 OS.flush();
139 return Result;
140}
141
Sam McCalla15c2d62018-01-18 09:27:56 +0000142// Helpers to produce fake index symbols for memIndex() or completions().
Sam McCall545a20d2018-01-19 14:34:02 +0000143// USRFormat is a regex replacement string for the unqualified part of the USR.
144Symbol sym(StringRef QName, index::SymbolKind Kind, StringRef USRFormat) {
Sam McCalla15c2d62018-01-18 09:27:56 +0000145 Symbol Sym;
Sam McCall545a20d2018-01-19 14:34:02 +0000146 std::string USR = "c:"; // We synthesize a few simple cases of USRs by hand!
Sam McCalla15c2d62018-01-18 09:27:56 +0000147 size_t Pos = QName.rfind("::");
148 if (Pos == llvm::StringRef::npos) {
149 Sym.Name = QName;
150 Sym.Scope = "";
151 } else {
152 Sym.Name = QName.substr(Pos + 2);
Sam McCall8b2faee2018-01-19 22:18:21 +0000153 Sym.Scope = QName.substr(0, Pos + 2);
154 USR += "@N@" + replace(QName.substr(0, Pos), "::", "@N@"); // ns:: -> @N@ns
Sam McCalla15c2d62018-01-18 09:27:56 +0000155 }
Sam McCall545a20d2018-01-19 14:34:02 +0000156 USR += Regex("^.*$").sub(USRFormat, Sym.Name); // e.g. func -> @F@func#
157 Sym.ID = SymbolID(USR);
Sam McCalla15c2d62018-01-18 09:27:56 +0000158 Sym.CompletionPlainInsertText = Sym.Name;
Sam McCall545a20d2018-01-19 14:34:02 +0000159 Sym.CompletionSnippetInsertText = Sym.Name;
Sam McCalla15c2d62018-01-18 09:27:56 +0000160 Sym.CompletionLabel = Sym.Name;
161 Sym.SymInfo.Kind = Kind;
162 return Sym;
163}
Sam McCall545a20d2018-01-19 14:34:02 +0000164Symbol func(StringRef Name) { // Assumes the function has no args.
165 return sym(Name, index::SymbolKind::Function, "@F@\\0#"); // no args
166}
167Symbol cls(StringRef Name) {
168 return sym(Name, index::SymbolKind::Class, "@S@\\0@S@\\0");
169}
170Symbol var(StringRef Name) {
171 return sym(Name, index::SymbolKind::Variable, "@\\0");
172}
Sam McCalla15c2d62018-01-18 09:27:56 +0000173
Sam McCallf6ae3232017-12-05 20:11:29 +0000174TEST(CompletionTest, Limit) {
175 clangd::CodeCompleteOptions Opts;
176 Opts.Limit = 2;
177 auto Results = completions(R"cpp(
Sam McCall9aad25f2017-12-05 07:20:26 +0000178struct ClassWithMembers {
179 int AAA();
180 int BBB();
181 int CCC();
182}
Sam McCallf6ae3232017-12-05 20:11:29 +0000183int main() { ClassWithMembers().^ }
Sam McCall9aad25f2017-12-05 07:20:26 +0000184 )cpp",
Sam McCalla15c2d62018-01-18 09:27:56 +0000185 /*IndexSymbols=*/{}, Opts);
Sam McCall9aad25f2017-12-05 07:20:26 +0000186
187 EXPECT_TRUE(Results.isIncomplete);
Sam McCallf6ae3232017-12-05 20:11:29 +0000188 EXPECT_THAT(Results.items, ElementsAre(Named("AAA"), Named("BBB")));
Sam McCall9aad25f2017-12-05 07:20:26 +0000189}
190
Sam McCallf6ae3232017-12-05 20:11:29 +0000191TEST(CompletionTest, Filter) {
192 std::string Body = R"cpp(
Sam McCall9aad25f2017-12-05 07:20:26 +0000193 int Abracadabra;
194 int Alakazam;
195 struct S {
196 int FooBar;
197 int FooBaz;
198 int Qux;
199 };
200 )cpp";
Sam McCallf6ae3232017-12-05 20:11:29 +0000201 EXPECT_THAT(completions(Body + "int main() { S().Foba^ }").items,
202 AllOf(Has("FooBar"), Has("FooBaz"), Not(Has("Qux"))));
Sam McCall9aad25f2017-12-05 07:20:26 +0000203
Sam McCallf6ae3232017-12-05 20:11:29 +0000204 EXPECT_THAT(completions(Body + "int main() { S().FR^ }").items,
205 AllOf(Has("FooBar"), Not(Has("FooBaz")), Not(Has("Qux"))));
Sam McCall9aad25f2017-12-05 07:20:26 +0000206
Sam McCallf6ae3232017-12-05 20:11:29 +0000207 EXPECT_THAT(completions(Body + "int main() { S().opr^ }").items,
208 Has("operator="));
Sam McCall9aad25f2017-12-05 07:20:26 +0000209
Sam McCallf6ae3232017-12-05 20:11:29 +0000210 EXPECT_THAT(completions(Body + "int main() { aaa^ }").items,
211 AllOf(Has("Abracadabra"), Has("Alakazam")));
Sam McCall9aad25f2017-12-05 07:20:26 +0000212
Sam McCallf6ae3232017-12-05 20:11:29 +0000213 EXPECT_THAT(completions(Body + "int main() { _a^ }").items,
214 AllOf(Has("static_cast"), Not(Has("Abracadabra"))));
Sam McCall9aad25f2017-12-05 07:20:26 +0000215}
216
Sam McCallf6ae3232017-12-05 20:11:29 +0000217void TestAfterDotCompletion(clangd::CodeCompleteOptions Opts) {
Sam McCall44fdcec22017-12-08 15:00:59 +0000218 auto Results = completions(
219 R"cpp(
220 #define MACRO X
Sam McCall9aad25f2017-12-05 07:20:26 +0000221
Sam McCall44fdcec22017-12-08 15:00:59 +0000222 int global_var;
Sam McCall9aad25f2017-12-05 07:20:26 +0000223
Sam McCall44fdcec22017-12-08 15:00:59 +0000224 int global_func();
Sam McCall9aad25f2017-12-05 07:20:26 +0000225
Sam McCall44fdcec22017-12-08 15:00:59 +0000226 struct GlobalClass {};
Sam McCall9aad25f2017-12-05 07:20:26 +0000227
Sam McCall44fdcec22017-12-08 15:00:59 +0000228 struct ClassWithMembers {
229 /// Doc for method.
230 int method();
Sam McCall9aad25f2017-12-05 07:20:26 +0000231
Sam McCall44fdcec22017-12-08 15:00:59 +0000232 int field;
233 private:
234 int private_field;
235 };
Sam McCall9aad25f2017-12-05 07:20:26 +0000236
Sam McCall44fdcec22017-12-08 15:00:59 +0000237 int test() {
238 struct LocalClass {};
Sam McCall9aad25f2017-12-05 07:20:26 +0000239
Sam McCall44fdcec22017-12-08 15:00:59 +0000240 /// Doc for local_var.
241 int local_var;
Sam McCall9aad25f2017-12-05 07:20:26 +0000242
Sam McCall44fdcec22017-12-08 15:00:59 +0000243 ClassWithMembers().^
244 }
245 )cpp",
Sam McCall545a20d2018-01-19 14:34:02 +0000246 {cls("IndexClass"), var("index_var"), func("index_func")}, Opts);
Sam McCall9aad25f2017-12-05 07:20:26 +0000247
Sam McCallf6ae3232017-12-05 20:11:29 +0000248 // Class members. The only items that must be present in after-dot
249 // completion.
Sam McCall44fdcec22017-12-08 15:00:59 +0000250 EXPECT_THAT(
251 Results.items,
252 AllOf(Has(Opts.EnableSnippets ? "method()" : "method"), Has("field")));
253 EXPECT_IFF(Opts.IncludeIneligibleResults, Results.items,
254 Has("private_field"));
Sam McCallf6ae3232017-12-05 20:11:29 +0000255 // Global items.
Sam McCall545a20d2018-01-19 14:34:02 +0000256 EXPECT_THAT(
257 Results.items,
258 Not(AnyOf(Has("global_var"), Has("index_var"), Has("global_func"),
259 Has("global_func()"), Has("index_func"), Has("GlobalClass"),
260 Has("IndexClass"), Has("MACRO"), Has("LocalClass"))));
Sam McCallf6ae3232017-12-05 20:11:29 +0000261 // There should be no code patterns (aka snippets) in after-dot
262 // completion. At least there aren't any we're aware of.
Sam McCall44fdcec22017-12-08 15:00:59 +0000263 EXPECT_THAT(Results.items, Not(Contains(Kind(CompletionItemKind::Snippet))));
Sam McCallf6ae3232017-12-05 20:11:29 +0000264 // Check documentation.
Sam McCall44fdcec22017-12-08 15:00:59 +0000265 EXPECT_IFF(Opts.IncludeBriefComments, Results.items,
266 Contains(IsDocumented()));
Sam McCallf6ae3232017-12-05 20:11:29 +0000267}
Sam McCall9aad25f2017-12-05 07:20:26 +0000268
Sam McCallf6ae3232017-12-05 20:11:29 +0000269void TestGlobalScopeCompletion(clangd::CodeCompleteOptions Opts) {
Sam McCall44fdcec22017-12-08 15:00:59 +0000270 auto Results = completions(
271 R"cpp(
272 #define MACRO X
Sam McCall9aad25f2017-12-05 07:20:26 +0000273
Sam McCall44fdcec22017-12-08 15:00:59 +0000274 int global_var;
275 int global_func();
Sam McCall9aad25f2017-12-05 07:20:26 +0000276
Sam McCall44fdcec22017-12-08 15:00:59 +0000277 struct GlobalClass {};
Sam McCall9aad25f2017-12-05 07:20:26 +0000278
Sam McCall44fdcec22017-12-08 15:00:59 +0000279 struct ClassWithMembers {
280 /// Doc for method.
281 int method();
282 };
Sam McCall9aad25f2017-12-05 07:20:26 +0000283
Sam McCall44fdcec22017-12-08 15:00:59 +0000284 int test() {
285 struct LocalClass {};
Sam McCall9aad25f2017-12-05 07:20:26 +0000286
Sam McCall44fdcec22017-12-08 15:00:59 +0000287 /// Doc for local_var.
288 int local_var;
Sam McCall9aad25f2017-12-05 07:20:26 +0000289
Sam McCall44fdcec22017-12-08 15:00:59 +0000290 ^
291 }
292 )cpp",
Sam McCall545a20d2018-01-19 14:34:02 +0000293 {cls("IndexClass"), var("index_var"), func("index_func")}, Opts);
Sam McCallf6ae3232017-12-05 20:11:29 +0000294
295 // Class members. Should never be present in global completions.
Sam McCall44fdcec22017-12-08 15:00:59 +0000296 EXPECT_THAT(Results.items,
Sam McCallf6ae3232017-12-05 20:11:29 +0000297 Not(AnyOf(Has("method"), Has("method()"), Has("field"))));
298 // Global items.
Sam McCalld8169a82018-01-18 15:31:30 +0000299 EXPECT_THAT(Results.items,
Sam McCall545a20d2018-01-19 14:34:02 +0000300 AllOf(Has("global_var"), Has("index_var"),
Sam McCalld8169a82018-01-18 15:31:30 +0000301 Has(Opts.EnableSnippets ? "global_func()" : "global_func"),
Sam McCall545a20d2018-01-19 14:34:02 +0000302 Has("index_func" /* our fake symbol doesn't include () */),
303 Has("GlobalClass"), Has("IndexClass")));
Sam McCallf6ae3232017-12-05 20:11:29 +0000304 // A macro.
Sam McCall44fdcec22017-12-08 15:00:59 +0000305 EXPECT_IFF(Opts.IncludeMacros, Results.items, Has("MACRO"));
Sam McCallf6ae3232017-12-05 20:11:29 +0000306 // Local items. Must be present always.
Ilya Biryukov9b5ffc22017-12-12 12:56:46 +0000307 EXPECT_THAT(Results.items,
308 AllOf(Has("local_var"), Has("LocalClass"),
309 Contains(Kind(CompletionItemKind::Snippet))));
Sam McCallf6ae3232017-12-05 20:11:29 +0000310 // Check documentation.
Sam McCall44fdcec22017-12-08 15:00:59 +0000311 EXPECT_IFF(Opts.IncludeBriefComments, Results.items,
312 Contains(IsDocumented()));
Sam McCallf6ae3232017-12-05 20:11:29 +0000313}
314
315TEST(CompletionTest, CompletionOptions) {
Sam McCall2c3849a2018-01-16 12:21:24 +0000316 auto Test = [&](const clangd::CodeCompleteOptions &Opts) {
317 TestAfterDotCompletion(Opts);
318 TestGlobalScopeCompletion(Opts);
319 };
320 // We used to test every combination of options, but that got too slow (2^N).
321 auto Flags = {
322 &clangd::CodeCompleteOptions::IncludeMacros,
Sam McCall2c3849a2018-01-16 12:21:24 +0000323 &clangd::CodeCompleteOptions::IncludeBriefComments,
324 &clangd::CodeCompleteOptions::EnableSnippets,
325 &clangd::CodeCompleteOptions::IncludeCodePatterns,
326 &clangd::CodeCompleteOptions::IncludeIneligibleResults,
327 };
328 // Test default options.
329 Test({});
330 // Test with one flag flipped.
331 for (auto &F : Flags) {
332 clangd::CodeCompleteOptions O;
333 O.*F ^= true;
334 Test(O);
Sam McCall9aad25f2017-12-05 07:20:26 +0000335 }
336}
337
Sam McCall44fdcec22017-12-08 15:00:59 +0000338TEST(CompletionTest, Priorities) {
339 auto Internal = completions(R"cpp(
340 class Foo {
341 public: void pub();
342 protected: void prot();
343 private: void priv();
344 };
345 void Foo::pub() { this->^ }
346 )cpp");
347 EXPECT_THAT(Internal.items,
348 HasSubsequence(Named("priv"), Named("prot"), Named("pub")));
349
350 auto External = completions(R"cpp(
351 class Foo {
352 public: void pub();
353 protected: void prot();
354 private: void priv();
355 };
356 void test() {
357 Foo F;
358 F.^
359 }
360 )cpp");
361 EXPECT_THAT(External.items,
362 AllOf(Has("pub"), Not(Has("prot")), Not(Has("priv"))));
363}
364
365TEST(CompletionTest, Qualifiers) {
366 auto Results = completions(R"cpp(
367 class Foo {
368 public: int foo() const;
369 int bar() const;
370 };
371 class Bar : public Foo {
372 int foo() const;
373 };
374 void test() { Bar().^ }
375 )cpp");
376 EXPECT_THAT(Results.items, HasSubsequence(Labeled("bar() const"),
377 Labeled("Foo::foo() const")));
378 EXPECT_THAT(Results.items, Not(Contains(Labeled("foo() const")))); // private
379}
380
381TEST(CompletionTest, Snippets) {
382 clangd::CodeCompleteOptions Opts;
383 Opts.EnableSnippets = true;
384 auto Results = completions(
385 R"cpp(
386 struct fake {
387 int a;
388 int f(int i, const float f) const;
389 };
390 int main() {
391 fake f;
392 f.^
393 }
394 )cpp",
Sam McCalla15c2d62018-01-18 09:27:56 +0000395 /*IndexSymbols=*/{}, Opts);
Sam McCall44fdcec22017-12-08 15:00:59 +0000396 EXPECT_THAT(Results.items,
Eric Liu63696e12017-12-20 17:24:31 +0000397 HasSubsequence(Snippet("a"),
Sam McCall44fdcec22017-12-08 15:00:59 +0000398 Snippet("f(${1:int i}, ${2:const float f})")));
399}
400
401TEST(CompletionTest, Kinds) {
Sam McCall545a20d2018-01-19 14:34:02 +0000402 auto Results = completions(
403 R"cpp(
404 #define MACRO X
405 int variable;
406 struct Struct {};
407 int function();
408 int X = ^
409 )cpp",
410 {func("indexFunction"), var("indexVariable"), cls("indexClass")});
411 EXPECT_THAT(Results.items,
412 AllOf(Has("function", CompletionItemKind::Function),
413 Has("variable", CompletionItemKind::Variable),
414 Has("int", CompletionItemKind::Keyword),
415 Has("Struct", CompletionItemKind::Class),
416 Has("MACRO", CompletionItemKind::Text),
417 Has("indexFunction", CompletionItemKind::Function),
418 Has("indexVariable", CompletionItemKind::Variable),
419 Has("indexClass", CompletionItemKind::Class)));
Sam McCall44fdcec22017-12-08 15:00:59 +0000420
Sam McCall44fdcec22017-12-08 15:00:59 +0000421 Results = completions("nam^");
422 EXPECT_THAT(Results.items, Has("namespace", CompletionItemKind::Snippet));
423}
424
Sam McCall84652cc2018-01-12 16:16:09 +0000425TEST(CompletionTest, NoDuplicates) {
Sam McCall545a20d2018-01-19 14:34:02 +0000426 auto Results = completions(
427 R"cpp(
428 class Adapter {
429 void method();
430 };
Sam McCall84652cc2018-01-12 16:16:09 +0000431
Sam McCall545a20d2018-01-19 14:34:02 +0000432 void Adapter::method() {
433 Adapter^
434 }
435 )cpp",
436 {cls("Adapter")});
Sam McCall84652cc2018-01-12 16:16:09 +0000437
438 // Make sure there are no duplicate entries of 'Adapter'.
Sam McCalld2a95922018-01-22 21:05:00 +0000439 EXPECT_THAT(Results.items, ElementsAre(Named("Adapter")));
Sam McCall84652cc2018-01-12 16:16:09 +0000440}
441
Sam McCall545a20d2018-01-19 14:34:02 +0000442TEST(CompletionTest, ScopedNoIndex) {
443 auto Results = completions(
444 R"cpp(
445 namespace fake { int BigBang, Babble, Ball; };
446 int main() { fake::bb^ }
447 ")cpp");
Sam McCall84652cc2018-01-12 16:16:09 +0000448 // BigBang is a better match than Babble. Ball doesn't match at all.
Sam McCall545a20d2018-01-19 14:34:02 +0000449 EXPECT_THAT(Results.items, ElementsAre(Named("BigBang"), Named("Babble")));
Sam McCall84652cc2018-01-12 16:16:09 +0000450}
451
Sam McCall545a20d2018-01-19 14:34:02 +0000452TEST(CompletionTest, Scoped) {
Sam McCalla15c2d62018-01-18 09:27:56 +0000453 auto Results = completions(
454 R"cpp(
Sam McCall545a20d2018-01-19 14:34:02 +0000455 namespace fake { int Babble, Ball; };
456 int main() { fake::bb^ }
457 ")cpp",
458 {var("fake::BigBang")});
459 EXPECT_THAT(Results.items, ElementsAre(Named("BigBang"), Named("Babble")));
Sam McCalla15c2d62018-01-18 09:27:56 +0000460}
461
Sam McCall545a20d2018-01-19 14:34:02 +0000462TEST(CompletionTest, ScopedWithFilter) {
Sam McCalla15c2d62018-01-18 09:27:56 +0000463 auto Results = completions(
464 R"cpp(
465 void f() { ns::x^ }
466 )cpp",
467 {cls("ns::XYZ"), func("ns::foo")});
468 EXPECT_THAT(Results.items,
469 UnorderedElementsAre(AllOf(Named("XYZ"), Filter("XYZ"))));
470}
471
Sam McCall545a20d2018-01-19 14:34:02 +0000472TEST(CompletionTest, GlobalQualified) {
Sam McCalla15c2d62018-01-18 09:27:56 +0000473 auto Results = completions(
474 R"cpp(
475 void f() { ::^ }
476 )cpp",
477 {cls("XYZ")});
478 EXPECT_THAT(Results.items, AllOf(Has("XYZ", CompletionItemKind::Class),
479 Has("f", CompletionItemKind::Function)));
480}
481
Sam McCall545a20d2018-01-19 14:34:02 +0000482TEST(CompletionTest, FullyQualified) {
Sam McCalla15c2d62018-01-18 09:27:56 +0000483 auto Results = completions(
484 R"cpp(
Sam McCall545a20d2018-01-19 14:34:02 +0000485 namespace ns { void bar(); }
Sam McCalla15c2d62018-01-18 09:27:56 +0000486 void f() { ::ns::^ }
487 )cpp",
488 {cls("ns::XYZ")});
Sam McCall545a20d2018-01-19 14:34:02 +0000489 EXPECT_THAT(Results.items, AllOf(Has("XYZ", CompletionItemKind::Class),
490 Has("bar", CompletionItemKind::Function)));
491}
492
493TEST(CompletionTest, SemaIndexMerge) {
494 auto Results = completions(
495 R"cpp(
496 namespace ns { int local; void both(); }
497 void f() { ::ns::^ }
498 )cpp",
499 {func("ns::both"), cls("ns::Index")});
500 // We get results from both index and sema, with no duplicates.
501 EXPECT_THAT(
502 Results.items,
503 UnorderedElementsAre(Named("local"), Named("Index"), Named("both")));
Sam McCalla15c2d62018-01-18 09:27:56 +0000504}
505
Haojian Wu48b48652018-01-25 09:20:09 +0000506TEST(CompletionTest, SemaIndexMergeWithLimit) {
507 clangd::CodeCompleteOptions Opts;
508 Opts.Limit = 1;
509 auto Results = completions(
510 R"cpp(
511 namespace ns { int local; void both(); }
512 void f() { ::ns::^ }
513 )cpp",
514 {func("ns::both"), cls("ns::Index")}, Opts);
515 EXPECT_EQ(Results.items.size(), Opts.Limit);
516 EXPECT_TRUE(Results.isIncomplete);
517}
518
Sam McCalla15c2d62018-01-18 09:27:56 +0000519TEST(CompletionTest, IndexSuppressesPreambleCompletions) {
520 MockFSProvider FS;
521 MockCompilationDatabase CDB;
522 IgnoreDiagnostics DiagConsumer;
Sam McCall7363a2f2018-03-05 17:28:54 +0000523 ClangdServer Server(CDB, FS, DiagConsumer, ClangdServer::optsForTest());
Sam McCalla15c2d62018-01-18 09:27:56 +0000524
Sam McCallc1568062018-02-16 09:41:43 +0000525 FS.Files[testPath("bar.h")] =
Sam McCalld5ea3e32018-01-24 17:53:32 +0000526 R"cpp(namespace ns { struct preamble { int member; }; })cpp";
Sam McCallc1568062018-02-16 09:41:43 +0000527 auto File = testPath("foo.cpp");
Sam McCalla15c2d62018-01-18 09:27:56 +0000528 Annotations Test(R"cpp(
529 #include "bar.h"
530 namespace ns { int local; }
Sam McCalld5ea3e32018-01-24 17:53:32 +0000531 void f() { ns::^; }
532 void f() { ns::preamble().$2^; }
Sam McCalla15c2d62018-01-18 09:27:56 +0000533 )cpp");
Sam McCall7363a2f2018-03-05 17:28:54 +0000534 runAddDocument(Server, File, Test.code());
Sam McCalla15c2d62018-01-18 09:27:56 +0000535 clangd::CodeCompleteOptions Opts = {};
536
Sam McCalla15c2d62018-01-18 09:27:56 +0000537 auto I = memIndex({var("ns::index")});
538 Opts.Index = I.get();
Ilya Biryukovcd5eb002018-02-12 11:37:28 +0000539 auto WithIndex = runCodeComplete(Server, File, Test.point(), Opts).Value;
Sam McCalla15c2d62018-01-18 09:27:56 +0000540 EXPECT_THAT(WithIndex.items,
541 UnorderedElementsAre(Named("local"), Named("index")));
Sam McCalld5ea3e32018-01-24 17:53:32 +0000542 auto ClassFromPreamble =
Ilya Biryukovcd5eb002018-02-12 11:37:28 +0000543 runCodeComplete(Server, File, Test.point("2"), Opts).Value;
Sam McCalld5ea3e32018-01-24 17:53:32 +0000544 EXPECT_THAT(ClassFromPreamble.items, Contains(Named("member")));
Sam McCall0bb24cd2018-02-13 08:59:23 +0000545
546 Opts.Index = nullptr;
547 auto WithoutIndex = runCodeComplete(Server, File, Test.point(), Opts).Value;
548 EXPECT_THAT(WithoutIndex.items,
549 UnorderedElementsAre(Named("local"), Named("preamble")));
550
Sam McCalla15c2d62018-01-18 09:27:56 +0000551}
552
553TEST(CompletionTest, DynamicIndexMultiFile) {
554 MockFSProvider FS;
555 MockCompilationDatabase CDB;
556 IgnoreDiagnostics DiagConsumer;
Sam McCall7363a2f2018-03-05 17:28:54 +0000557 auto Opts = ClangdServer::optsForTest();
558 Opts.BuildDynamicSymbolIndex = true;
559 ClangdServer Server(CDB, FS, DiagConsumer, Opts);
Sam McCalla15c2d62018-01-18 09:27:56 +0000560
Eric Liu709bde82018-02-19 18:48:44 +0000561 FS.Files[testPath("foo.h")] = R"cpp(
Sam McCalla15c2d62018-01-18 09:27:56 +0000562 namespace ns { class XYZ {}; void foo(int x) {} }
Eric Liu709bde82018-02-19 18:48:44 +0000563 )cpp";
Sam McCall7363a2f2018-03-05 17:28:54 +0000564 runAddDocument(Server, testPath("foo.cpp"), R"cpp(
Eric Liu709bde82018-02-19 18:48:44 +0000565 #include "foo.h"
Sam McCall0bb24cd2018-02-13 08:59:23 +0000566 )cpp");
Sam McCalla15c2d62018-01-18 09:27:56 +0000567
Sam McCallc1568062018-02-16 09:41:43 +0000568 auto File = testPath("bar.cpp");
Sam McCalla15c2d62018-01-18 09:27:56 +0000569 Annotations Test(R"cpp(
570 namespace ns {
571 class XXX {};
572 /// Doooc
573 void fooooo() {}
574 }
575 void f() { ns::^ }
576 )cpp");
Sam McCall7363a2f2018-03-05 17:28:54 +0000577 runAddDocument(Server, File, Test.code());
Sam McCalla15c2d62018-01-18 09:27:56 +0000578
Ilya Biryukovcd5eb002018-02-12 11:37:28 +0000579 auto Results = runCodeComplete(Server, File, Test.point(), {}).Value;
Sam McCalla15c2d62018-01-18 09:27:56 +0000580 // "XYZ" and "foo" are not included in the file being completed but are still
581 // visible through the index.
582 EXPECT_THAT(Results.items, Has("XYZ", CompletionItemKind::Class));
583 EXPECT_THAT(Results.items, Has("foo", CompletionItemKind::Function));
584 EXPECT_THAT(Results.items, Has("XXX", CompletionItemKind::Class));
585 EXPECT_THAT(Results.items, Contains(AllOf(Named("fooooo"), Filter("fooooo"),
586 Kind(CompletionItemKind::Function),
587 Doc("Doooc"), Detail("void"))));
588}
589
Haojian Wu58d208d2018-01-25 09:44:06 +0000590TEST(CodeCompleteTest, DisableTypoCorrection) {
591 auto Results = completions(R"cpp(
592 namespace clang { int v; }
593 void f() { clangd::^
594 )cpp");
595 EXPECT_TRUE(Results.items.empty());
596}
597
Ilya Biryukov53d6d932018-03-06 16:45:21 +0000598TEST(CodeCompleteTest, NoColonColonAtTheEnd) {
599 auto Results = completions(R"cpp(
600 namespace clang { }
601 void f() {
602 clan^
603 }
604 )cpp");
605
606 EXPECT_THAT(Results.items, Contains(Labeled("clang")));
607 EXPECT_THAT(Results.items, Not(Contains(Labeled("clang::"))));
608}
609
Sam McCall800d4372017-12-19 10:29:27 +0000610SignatureHelp signatures(StringRef Text) {
611 MockFSProvider FS;
612 MockCompilationDatabase CDB;
613 IgnoreDiagnostics DiagConsumer;
Sam McCall7363a2f2018-03-05 17:28:54 +0000614 ClangdServer Server(CDB, FS, DiagConsumer, ClangdServer::optsForTest());
Sam McCallc1568062018-02-16 09:41:43 +0000615 auto File = testPath("foo.cpp");
Sam McCall328cbdb2017-12-20 16:06:05 +0000616 Annotations Test(Text);
Sam McCall7363a2f2018-03-05 17:28:54 +0000617 runAddDocument(Server, File, Test.code());
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000618 auto R = runSignatureHelp(Server, File, Test.point());
Sam McCall800d4372017-12-19 10:29:27 +0000619 assert(R);
620 return R.get().Value;
621}
622
623MATCHER_P(ParamsAre, P, "") {
624 if (P.size() != arg.parameters.size())
625 return false;
626 for (unsigned I = 0; I < P.size(); ++I)
627 if (P[I] != arg.parameters[I].label)
628 return false;
629 return true;
630}
631
632Matcher<SignatureInformation> Sig(std::string Label,
633 std::vector<std::string> Params) {
634 return AllOf(Labeled(Label), ParamsAre(Params));
635}
636
637TEST(SignatureHelpTest, Overloads) {
638 auto Results = signatures(R"cpp(
639 void foo(int x, int y);
640 void foo(int x, float y);
641 void foo(float x, int y);
642 void foo(float x, float y);
643 void bar(int x, int y = 0);
644 int main() { foo(^); }
645 )cpp");
646 EXPECT_THAT(Results.signatures,
647 UnorderedElementsAre(
648 Sig("foo(float x, float y) -> void", {"float x", "float y"}),
649 Sig("foo(float x, int y) -> void", {"float x", "int y"}),
650 Sig("foo(int x, float y) -> void", {"int x", "float y"}),
651 Sig("foo(int x, int y) -> void", {"int x", "int y"})));
652 // We always prefer the first signature.
653 EXPECT_EQ(0, Results.activeSignature);
654 EXPECT_EQ(0, Results.activeParameter);
655}
656
657TEST(SignatureHelpTest, DefaultArgs) {
658 auto Results = signatures(R"cpp(
659 void bar(int x, int y = 0);
660 void bar(float x = 0, int y = 42);
661 int main() { bar(^
662 )cpp");
663 EXPECT_THAT(Results.signatures,
664 UnorderedElementsAre(
665 Sig("bar(int x, int y = 0) -> void", {"int x", "int y = 0"}),
666 Sig("bar(float x = 0, int y = 42) -> void",
667 {"float x = 0", "int y = 42"})));
668 EXPECT_EQ(0, Results.activeSignature);
669 EXPECT_EQ(0, Results.activeParameter);
670}
671
672TEST(SignatureHelpTest, ActiveArg) {
673 auto Results = signatures(R"cpp(
674 int baz(int a, int b, int c);
675 int main() { baz(baz(1,2,3), ^); }
676 )cpp");
677 EXPECT_THAT(Results.signatures,
678 ElementsAre(Sig("baz(int a, int b, int c) -> int",
679 {"int a", "int b", "int c"})));
680 EXPECT_EQ(0, Results.activeSignature);
681 EXPECT_EQ(1, Results.activeParameter);
682}
683
Haojian Wu061c73e2018-01-23 11:37:26 +0000684class IndexRequestCollector : public SymbolIndex {
685public:
686 bool
Sam McCalld1a7a372018-01-31 13:40:48 +0000687 fuzzyFind(const FuzzyFindRequest &Req,
Haojian Wu061c73e2018-01-23 11:37:26 +0000688 llvm::function_ref<void(const Symbol &)> Callback) const override {
689 Requests.push_back(Req);
Sam McCallab8e3932018-02-19 13:04:41 +0000690 return true;
Haojian Wu061c73e2018-01-23 11:37:26 +0000691 }
692
693 const std::vector<FuzzyFindRequest> allRequests() const { return Requests; }
694
695private:
696 mutable std::vector<FuzzyFindRequest> Requests;
697};
698
699std::vector<FuzzyFindRequest> captureIndexRequests(llvm::StringRef Code) {
700 clangd::CodeCompleteOptions Opts;
701 IndexRequestCollector Requests;
702 Opts.Index = &Requests;
703 completions(Code, {}, Opts);
704 return Requests.allRequests();
705}
706
707TEST(CompletionTest, UnqualifiedIdQuery) {
708 auto Requests = captureIndexRequests(R"cpp(
709 namespace std {}
710 using namespace std;
711 namespace ns {
712 void f() {
713 vec^
714 }
715 }
716 )cpp");
717
718 EXPECT_THAT(Requests,
719 ElementsAre(Field(&FuzzyFindRequest::Scopes,
720 UnorderedElementsAre("", "ns::", "std::"))));
721}
722
723TEST(CompletionTest, ResolvedQualifiedIdQuery) {
724 auto Requests = captureIndexRequests(R"cpp(
725 namespace ns1 {}
726 namespace ns2 {} // ignore
727 namespace ns3 { namespace nns3 {} }
728 namespace foo {
729 using namespace ns1;
730 using namespace ns3::nns3;
731 }
732 namespace ns {
733 void f() {
734 foo::^
735 }
736 }
737 )cpp");
738
739 EXPECT_THAT(Requests,
740 ElementsAre(Field(
741 &FuzzyFindRequest::Scopes,
742 UnorderedElementsAre("foo::", "ns1::", "ns3::nns3::"))));
743}
744
745TEST(CompletionTest, UnresolvedQualifierIdQuery) {
746 auto Requests = captureIndexRequests(R"cpp(
747 namespace a {}
748 using namespace a;
749 namespace ns {
750 void f() {
751 bar::^
752 }
753 } // namespace ns
754 )cpp");
755
756 EXPECT_THAT(Requests, ElementsAre(Field(&FuzzyFindRequest::Scopes,
757 UnorderedElementsAre("bar::"))));
758}
759
760TEST(CompletionTest, UnresolvedNestedQualifierIdQuery) {
761 auto Requests = captureIndexRequests(R"cpp(
762 namespace a {}
763 using namespace a;
764 namespace ns {
765 void f() {
766 ::a::bar::^
767 }
768 } // namespace ns
769 )cpp");
770
771 EXPECT_THAT(Requests, ElementsAre(Field(&FuzzyFindRequest::Scopes,
772 UnorderedElementsAre("a::bar::"))));
773}
774
775TEST(CompletionTest, EmptyQualifiedQuery) {
776 auto Requests = captureIndexRequests(R"cpp(
777 namespace ns {
778 void f() {
779 ^
780 }
781 } // namespace ns
782 )cpp");
783
784 EXPECT_THAT(Requests, ElementsAre(Field(&FuzzyFindRequest::Scopes,
785 UnorderedElementsAre("", "ns::"))));
786}
787
788TEST(CompletionTest, GlobalQualifiedQuery) {
789 auto Requests = captureIndexRequests(R"cpp(
790 namespace ns {
791 void f() {
792 ::^
793 }
794 } // namespace ns
795 )cpp");
796
797 EXPECT_THAT(Requests, ElementsAre(Field(&FuzzyFindRequest::Scopes,
798 UnorderedElementsAre(""))));
799}
800
Sam McCall9aad25f2017-12-05 07:20:26 +0000801} // namespace
802} // namespace clangd
803} // namespace clang