blob: 18334614f3454fbafeed9cc23133e779fc33db68 [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;
Ilya Biryukov71028b82018-03-12 15:28:22 +000059using ::testing::Field;
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 Biryukov71028b82018-03-12 15:28:22 +000064 void onDiagnosticsReady(PathRef File,
Sam McCalla7bb0cc2018-03-12 23:22:35 +000065 std::vector<Diag> 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());
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000124 auto CompletionList =
125 cantFail(runCodeComplete(Server, File, Test.point(), Opts));
Ilya Biryukov5a5e1ca2017-12-29 14:59:22 +0000126 // Sanity-check that filterText is valid.
Sam McCall545a20d2018-01-19 14:34:02 +0000127 EXPECT_THAT(CompletionList.items, Each(NameContainsFilter()));
Ilya Biryukov5a5e1ca2017-12-29 14:59:22 +0000128 return CompletionList;
Sam McCall9aad25f2017-12-05 07:20:26 +0000129}
130
Sam McCall545a20d2018-01-19 14:34:02 +0000131std::string replace(StringRef Haystack, StringRef Needle, StringRef Repl) {
132 std::string Result;
133 raw_string_ostream OS(Result);
134 std::pair<StringRef, StringRef> Split;
135 for (Split = Haystack.split(Needle); !Split.second.empty();
136 Split = Split.first.split(Needle))
137 OS << Split.first << Repl;
138 Result += Split.first;
139 OS.flush();
140 return Result;
141}
142
Sam McCalla15c2d62018-01-18 09:27:56 +0000143// Helpers to produce fake index symbols for memIndex() or completions().
Sam McCall545a20d2018-01-19 14:34:02 +0000144// USRFormat is a regex replacement string for the unqualified part of the USR.
145Symbol sym(StringRef QName, index::SymbolKind Kind, StringRef USRFormat) {
Sam McCalla15c2d62018-01-18 09:27:56 +0000146 Symbol Sym;
Sam McCall545a20d2018-01-19 14:34:02 +0000147 std::string USR = "c:"; // We synthesize a few simple cases of USRs by hand!
Sam McCalla15c2d62018-01-18 09:27:56 +0000148 size_t Pos = QName.rfind("::");
149 if (Pos == llvm::StringRef::npos) {
150 Sym.Name = QName;
151 Sym.Scope = "";
152 } else {
153 Sym.Name = QName.substr(Pos + 2);
Sam McCall8b2faee2018-01-19 22:18:21 +0000154 Sym.Scope = QName.substr(0, Pos + 2);
155 USR += "@N@" + replace(QName.substr(0, Pos), "::", "@N@"); // ns:: -> @N@ns
Sam McCalla15c2d62018-01-18 09:27:56 +0000156 }
Sam McCall545a20d2018-01-19 14:34:02 +0000157 USR += Regex("^.*$").sub(USRFormat, Sym.Name); // e.g. func -> @F@func#
158 Sym.ID = SymbolID(USR);
Sam McCalla15c2d62018-01-18 09:27:56 +0000159 Sym.CompletionPlainInsertText = Sym.Name;
Sam McCall545a20d2018-01-19 14:34:02 +0000160 Sym.CompletionSnippetInsertText = Sym.Name;
Sam McCalla15c2d62018-01-18 09:27:56 +0000161 Sym.CompletionLabel = Sym.Name;
162 Sym.SymInfo.Kind = Kind;
163 return Sym;
164}
Sam McCall545a20d2018-01-19 14:34:02 +0000165Symbol func(StringRef Name) { // Assumes the function has no args.
166 return sym(Name, index::SymbolKind::Function, "@F@\\0#"); // no args
167}
168Symbol cls(StringRef Name) {
169 return sym(Name, index::SymbolKind::Class, "@S@\\0@S@\\0");
170}
171Symbol var(StringRef Name) {
172 return sym(Name, index::SymbolKind::Variable, "@\\0");
173}
Sam McCalla15c2d62018-01-18 09:27:56 +0000174
Sam McCallf6ae3232017-12-05 20:11:29 +0000175TEST(CompletionTest, Limit) {
176 clangd::CodeCompleteOptions Opts;
177 Opts.Limit = 2;
178 auto Results = completions(R"cpp(
Sam McCall9aad25f2017-12-05 07:20:26 +0000179struct ClassWithMembers {
180 int AAA();
181 int BBB();
182 int CCC();
183}
Sam McCallf6ae3232017-12-05 20:11:29 +0000184int main() { ClassWithMembers().^ }
Sam McCall9aad25f2017-12-05 07:20:26 +0000185 )cpp",
Sam McCalla15c2d62018-01-18 09:27:56 +0000186 /*IndexSymbols=*/{}, Opts);
Sam McCall9aad25f2017-12-05 07:20:26 +0000187
188 EXPECT_TRUE(Results.isIncomplete);
Sam McCallf6ae3232017-12-05 20:11:29 +0000189 EXPECT_THAT(Results.items, ElementsAre(Named("AAA"), Named("BBB")));
Sam McCall9aad25f2017-12-05 07:20:26 +0000190}
191
Sam McCallf6ae3232017-12-05 20:11:29 +0000192TEST(CompletionTest, Filter) {
193 std::string Body = R"cpp(
Sam McCall9aad25f2017-12-05 07:20:26 +0000194 int Abracadabra;
195 int Alakazam;
196 struct S {
197 int FooBar;
198 int FooBaz;
199 int Qux;
200 };
201 )cpp";
Sam McCallf6ae3232017-12-05 20:11:29 +0000202 EXPECT_THAT(completions(Body + "int main() { S().Foba^ }").items,
203 AllOf(Has("FooBar"), Has("FooBaz"), Not(Has("Qux"))));
Sam McCall9aad25f2017-12-05 07:20:26 +0000204
Sam McCallf6ae3232017-12-05 20:11:29 +0000205 EXPECT_THAT(completions(Body + "int main() { S().FR^ }").items,
206 AllOf(Has("FooBar"), Not(Has("FooBaz")), Not(Has("Qux"))));
Sam McCall9aad25f2017-12-05 07:20:26 +0000207
Sam McCallf6ae3232017-12-05 20:11:29 +0000208 EXPECT_THAT(completions(Body + "int main() { S().opr^ }").items,
209 Has("operator="));
Sam McCall9aad25f2017-12-05 07:20:26 +0000210
Sam McCallf6ae3232017-12-05 20:11:29 +0000211 EXPECT_THAT(completions(Body + "int main() { aaa^ }").items,
212 AllOf(Has("Abracadabra"), Has("Alakazam")));
Sam McCall9aad25f2017-12-05 07:20:26 +0000213
Sam McCallf6ae3232017-12-05 20:11:29 +0000214 EXPECT_THAT(completions(Body + "int main() { _a^ }").items,
215 AllOf(Has("static_cast"), Not(Has("Abracadabra"))));
Sam McCall9aad25f2017-12-05 07:20:26 +0000216}
217
Sam McCallf6ae3232017-12-05 20:11:29 +0000218void TestAfterDotCompletion(clangd::CodeCompleteOptions Opts) {
Sam McCall44fdcec22017-12-08 15:00:59 +0000219 auto Results = completions(
220 R"cpp(
221 #define MACRO X
Sam McCall9aad25f2017-12-05 07:20:26 +0000222
Sam McCall44fdcec22017-12-08 15:00:59 +0000223 int global_var;
Sam McCall9aad25f2017-12-05 07:20:26 +0000224
Sam McCall44fdcec22017-12-08 15:00:59 +0000225 int global_func();
Sam McCall9aad25f2017-12-05 07:20:26 +0000226
Sam McCall44fdcec22017-12-08 15:00:59 +0000227 struct GlobalClass {};
Sam McCall9aad25f2017-12-05 07:20:26 +0000228
Sam McCall44fdcec22017-12-08 15:00:59 +0000229 struct ClassWithMembers {
230 /// Doc for method.
231 int method();
Sam McCall9aad25f2017-12-05 07:20:26 +0000232
Sam McCall44fdcec22017-12-08 15:00:59 +0000233 int field;
234 private:
235 int private_field;
236 };
Sam McCall9aad25f2017-12-05 07:20:26 +0000237
Sam McCall44fdcec22017-12-08 15:00:59 +0000238 int test() {
239 struct LocalClass {};
Sam McCall9aad25f2017-12-05 07:20:26 +0000240
Sam McCall44fdcec22017-12-08 15:00:59 +0000241 /// Doc for local_var.
242 int local_var;
Sam McCall9aad25f2017-12-05 07:20:26 +0000243
Sam McCall44fdcec22017-12-08 15:00:59 +0000244 ClassWithMembers().^
245 }
246 )cpp",
Sam McCall545a20d2018-01-19 14:34:02 +0000247 {cls("IndexClass"), var("index_var"), func("index_func")}, Opts);
Sam McCall9aad25f2017-12-05 07:20:26 +0000248
Sam McCallf6ae3232017-12-05 20:11:29 +0000249 // Class members. The only items that must be present in after-dot
250 // completion.
Sam McCall44fdcec22017-12-08 15:00:59 +0000251 EXPECT_THAT(
252 Results.items,
253 AllOf(Has(Opts.EnableSnippets ? "method()" : "method"), Has("field")));
254 EXPECT_IFF(Opts.IncludeIneligibleResults, Results.items,
255 Has("private_field"));
Sam McCallf6ae3232017-12-05 20:11:29 +0000256 // Global items.
Sam McCall545a20d2018-01-19 14:34:02 +0000257 EXPECT_THAT(
258 Results.items,
259 Not(AnyOf(Has("global_var"), Has("index_var"), Has("global_func"),
260 Has("global_func()"), Has("index_func"), Has("GlobalClass"),
261 Has("IndexClass"), Has("MACRO"), Has("LocalClass"))));
Sam McCallf6ae3232017-12-05 20:11:29 +0000262 // There should be no code patterns (aka snippets) in after-dot
263 // completion. At least there aren't any we're aware of.
Sam McCall44fdcec22017-12-08 15:00:59 +0000264 EXPECT_THAT(Results.items, Not(Contains(Kind(CompletionItemKind::Snippet))));
Sam McCallf6ae3232017-12-05 20:11:29 +0000265 // Check documentation.
Sam McCall44fdcec22017-12-08 15:00:59 +0000266 EXPECT_IFF(Opts.IncludeBriefComments, Results.items,
267 Contains(IsDocumented()));
Sam McCallf6ae3232017-12-05 20:11:29 +0000268}
Sam McCall9aad25f2017-12-05 07:20:26 +0000269
Sam McCallf6ae3232017-12-05 20:11:29 +0000270void TestGlobalScopeCompletion(clangd::CodeCompleteOptions Opts) {
Sam McCall44fdcec22017-12-08 15:00:59 +0000271 auto Results = completions(
272 R"cpp(
273 #define MACRO X
Sam McCall9aad25f2017-12-05 07:20:26 +0000274
Sam McCall44fdcec22017-12-08 15:00:59 +0000275 int global_var;
276 int global_func();
Sam McCall9aad25f2017-12-05 07:20:26 +0000277
Sam McCall44fdcec22017-12-08 15:00:59 +0000278 struct GlobalClass {};
Sam McCall9aad25f2017-12-05 07:20:26 +0000279
Sam McCall44fdcec22017-12-08 15:00:59 +0000280 struct ClassWithMembers {
281 /// Doc for method.
282 int method();
283 };
Sam McCall9aad25f2017-12-05 07:20:26 +0000284
Sam McCall44fdcec22017-12-08 15:00:59 +0000285 int test() {
286 struct LocalClass {};
Sam McCall9aad25f2017-12-05 07:20:26 +0000287
Sam McCall44fdcec22017-12-08 15:00:59 +0000288 /// Doc for local_var.
289 int local_var;
Sam McCall9aad25f2017-12-05 07:20:26 +0000290
Sam McCall44fdcec22017-12-08 15:00:59 +0000291 ^
292 }
293 )cpp",
Sam McCall545a20d2018-01-19 14:34:02 +0000294 {cls("IndexClass"), var("index_var"), func("index_func")}, Opts);
Sam McCallf6ae3232017-12-05 20:11:29 +0000295
296 // Class members. Should never be present in global completions.
Sam McCall44fdcec22017-12-08 15:00:59 +0000297 EXPECT_THAT(Results.items,
Sam McCallf6ae3232017-12-05 20:11:29 +0000298 Not(AnyOf(Has("method"), Has("method()"), Has("field"))));
299 // Global items.
Sam McCalld8169a82018-01-18 15:31:30 +0000300 EXPECT_THAT(Results.items,
Sam McCall545a20d2018-01-19 14:34:02 +0000301 AllOf(Has("global_var"), Has("index_var"),
Sam McCalld8169a82018-01-18 15:31:30 +0000302 Has(Opts.EnableSnippets ? "global_func()" : "global_func"),
Sam McCall545a20d2018-01-19 14:34:02 +0000303 Has("index_func" /* our fake symbol doesn't include () */),
304 Has("GlobalClass"), Has("IndexClass")));
Sam McCallf6ae3232017-12-05 20:11:29 +0000305 // A macro.
Sam McCall44fdcec22017-12-08 15:00:59 +0000306 EXPECT_IFF(Opts.IncludeMacros, Results.items, Has("MACRO"));
Sam McCallf6ae3232017-12-05 20:11:29 +0000307 // Local items. Must be present always.
Ilya Biryukov9b5ffc22017-12-12 12:56:46 +0000308 EXPECT_THAT(Results.items,
309 AllOf(Has("local_var"), Has("LocalClass"),
310 Contains(Kind(CompletionItemKind::Snippet))));
Sam McCallf6ae3232017-12-05 20:11:29 +0000311 // Check documentation.
Sam McCall44fdcec22017-12-08 15:00:59 +0000312 EXPECT_IFF(Opts.IncludeBriefComments, Results.items,
313 Contains(IsDocumented()));
Sam McCallf6ae3232017-12-05 20:11:29 +0000314}
315
316TEST(CompletionTest, CompletionOptions) {
Sam McCall2c3849a2018-01-16 12:21:24 +0000317 auto Test = [&](const clangd::CodeCompleteOptions &Opts) {
318 TestAfterDotCompletion(Opts);
319 TestGlobalScopeCompletion(Opts);
320 };
321 // We used to test every combination of options, but that got too slow (2^N).
322 auto Flags = {
Ilya Biryukov71028b82018-03-12 15:28:22 +0000323 &clangd::CodeCompleteOptions::IncludeMacros,
324 &clangd::CodeCompleteOptions::IncludeBriefComments,
325 &clangd::CodeCompleteOptions::EnableSnippets,
326 &clangd::CodeCompleteOptions::IncludeCodePatterns,
327 &clangd::CodeCompleteOptions::IncludeIneligibleResults,
Sam McCall2c3849a2018-01-16 12:21:24 +0000328 };
329 // Test default options.
330 Test({});
331 // Test with one flag flipped.
332 for (auto &F : Flags) {
333 clangd::CodeCompleteOptions O;
334 O.*F ^= true;
335 Test(O);
Sam McCall9aad25f2017-12-05 07:20:26 +0000336 }
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) {
Sam McCall545a20d2018-01-19 14:34:02 +0000403 auto Results = completions(
404 R"cpp(
405 #define MACRO X
406 int variable;
407 struct Struct {};
408 int function();
409 int X = ^
410 )cpp",
411 {func("indexFunction"), var("indexVariable"), cls("indexClass")});
412 EXPECT_THAT(Results.items,
413 AllOf(Has("function", CompletionItemKind::Function),
414 Has("variable", CompletionItemKind::Variable),
415 Has("int", CompletionItemKind::Keyword),
416 Has("Struct", CompletionItemKind::Class),
417 Has("MACRO", CompletionItemKind::Text),
418 Has("indexFunction", CompletionItemKind::Function),
419 Has("indexVariable", CompletionItemKind::Variable),
420 Has("indexClass", CompletionItemKind::Class)));
Sam McCall44fdcec22017-12-08 15:00:59 +0000421
Sam McCall44fdcec22017-12-08 15:00:59 +0000422 Results = completions("nam^");
423 EXPECT_THAT(Results.items, Has("namespace", CompletionItemKind::Snippet));
424}
425
Sam McCall84652cc2018-01-12 16:16:09 +0000426TEST(CompletionTest, NoDuplicates) {
Sam McCall545a20d2018-01-19 14:34:02 +0000427 auto Results = completions(
428 R"cpp(
429 class Adapter {
430 void method();
431 };
Sam McCall84652cc2018-01-12 16:16:09 +0000432
Sam McCall545a20d2018-01-19 14:34:02 +0000433 void Adapter::method() {
434 Adapter^
435 }
436 )cpp",
437 {cls("Adapter")});
Sam McCall84652cc2018-01-12 16:16:09 +0000438
439 // Make sure there are no duplicate entries of 'Adapter'.
Sam McCalld2a95922018-01-22 21:05:00 +0000440 EXPECT_THAT(Results.items, ElementsAre(Named("Adapter")));
Sam McCall84652cc2018-01-12 16:16:09 +0000441}
442
Sam McCall545a20d2018-01-19 14:34:02 +0000443TEST(CompletionTest, ScopedNoIndex) {
444 auto Results = completions(
445 R"cpp(
446 namespace fake { int BigBang, Babble, Ball; };
447 int main() { fake::bb^ }
448 ")cpp");
Sam McCall84652cc2018-01-12 16:16:09 +0000449 // BigBang is a better match than Babble. Ball doesn't match at all.
Sam McCall545a20d2018-01-19 14:34:02 +0000450 EXPECT_THAT(Results.items, ElementsAre(Named("BigBang"), Named("Babble")));
Sam McCall84652cc2018-01-12 16:16:09 +0000451}
452
Sam McCall545a20d2018-01-19 14:34:02 +0000453TEST(CompletionTest, Scoped) {
Sam McCalla15c2d62018-01-18 09:27:56 +0000454 auto Results = completions(
455 R"cpp(
Sam McCall545a20d2018-01-19 14:34:02 +0000456 namespace fake { int Babble, Ball; };
457 int main() { fake::bb^ }
458 ")cpp",
459 {var("fake::BigBang")});
460 EXPECT_THAT(Results.items, ElementsAre(Named("BigBang"), Named("Babble")));
Sam McCalla15c2d62018-01-18 09:27:56 +0000461}
462
Sam McCall545a20d2018-01-19 14:34:02 +0000463TEST(CompletionTest, ScopedWithFilter) {
Sam McCalla15c2d62018-01-18 09:27:56 +0000464 auto Results = completions(
465 R"cpp(
466 void f() { ns::x^ }
467 )cpp",
468 {cls("ns::XYZ"), func("ns::foo")});
469 EXPECT_THAT(Results.items,
470 UnorderedElementsAre(AllOf(Named("XYZ"), Filter("XYZ"))));
471}
472
Sam McCall545a20d2018-01-19 14:34:02 +0000473TEST(CompletionTest, GlobalQualified) {
Sam McCalla15c2d62018-01-18 09:27:56 +0000474 auto Results = completions(
475 R"cpp(
476 void f() { ::^ }
477 )cpp",
478 {cls("XYZ")});
479 EXPECT_THAT(Results.items, AllOf(Has("XYZ", CompletionItemKind::Class),
480 Has("f", CompletionItemKind::Function)));
481}
482
Sam McCall545a20d2018-01-19 14:34:02 +0000483TEST(CompletionTest, FullyQualified) {
Sam McCalla15c2d62018-01-18 09:27:56 +0000484 auto Results = completions(
485 R"cpp(
Sam McCall545a20d2018-01-19 14:34:02 +0000486 namespace ns { void bar(); }
Sam McCalla15c2d62018-01-18 09:27:56 +0000487 void f() { ::ns::^ }
488 )cpp",
489 {cls("ns::XYZ")});
Sam McCall545a20d2018-01-19 14:34:02 +0000490 EXPECT_THAT(Results.items, AllOf(Has("XYZ", CompletionItemKind::Class),
491 Has("bar", CompletionItemKind::Function)));
492}
493
494TEST(CompletionTest, SemaIndexMerge) {
495 auto Results = completions(
496 R"cpp(
497 namespace ns { int local; void both(); }
498 void f() { ::ns::^ }
499 )cpp",
500 {func("ns::both"), cls("ns::Index")});
501 // We get results from both index and sema, with no duplicates.
502 EXPECT_THAT(
503 Results.items,
504 UnorderedElementsAre(Named("local"), Named("Index"), Named("both")));
Sam McCalla15c2d62018-01-18 09:27:56 +0000505}
506
Haojian Wu48b48652018-01-25 09:20:09 +0000507TEST(CompletionTest, SemaIndexMergeWithLimit) {
508 clangd::CodeCompleteOptions Opts;
509 Opts.Limit = 1;
510 auto Results = completions(
511 R"cpp(
512 namespace ns { int local; void both(); }
513 void f() { ::ns::^ }
514 )cpp",
515 {func("ns::both"), cls("ns::Index")}, Opts);
516 EXPECT_EQ(Results.items.size(), Opts.Limit);
517 EXPECT_TRUE(Results.isIncomplete);
518}
519
Sam McCalla15c2d62018-01-18 09:27:56 +0000520TEST(CompletionTest, IndexSuppressesPreambleCompletions) {
521 MockFSProvider FS;
522 MockCompilationDatabase CDB;
523 IgnoreDiagnostics DiagConsumer;
Sam McCall7363a2f2018-03-05 17:28:54 +0000524 ClangdServer Server(CDB, FS, DiagConsumer, ClangdServer::optsForTest());
Sam McCalla15c2d62018-01-18 09:27:56 +0000525
Sam McCallc1568062018-02-16 09:41:43 +0000526 FS.Files[testPath("bar.h")] =
Sam McCalld5ea3e32018-01-24 17:53:32 +0000527 R"cpp(namespace ns { struct preamble { int member; }; })cpp";
Sam McCallc1568062018-02-16 09:41:43 +0000528 auto File = testPath("foo.cpp");
Sam McCalla15c2d62018-01-18 09:27:56 +0000529 Annotations Test(R"cpp(
530 #include "bar.h"
531 namespace ns { int local; }
Sam McCalld5ea3e32018-01-24 17:53:32 +0000532 void f() { ns::^; }
533 void f() { ns::preamble().$2^; }
Sam McCalla15c2d62018-01-18 09:27:56 +0000534 )cpp");
Sam McCall7363a2f2018-03-05 17:28:54 +0000535 runAddDocument(Server, File, Test.code());
Sam McCalla15c2d62018-01-18 09:27:56 +0000536 clangd::CodeCompleteOptions Opts = {};
537
Sam McCalla15c2d62018-01-18 09:27:56 +0000538 auto I = memIndex({var("ns::index")});
539 Opts.Index = I.get();
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000540 auto WithIndex = cantFail(runCodeComplete(Server, File, Test.point(), Opts));
Sam McCalla15c2d62018-01-18 09:27:56 +0000541 EXPECT_THAT(WithIndex.items,
542 UnorderedElementsAre(Named("local"), Named("index")));
Sam McCalld5ea3e32018-01-24 17:53:32 +0000543 auto ClassFromPreamble =
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000544 cantFail(runCodeComplete(Server, File, Test.point("2"), Opts));
Sam McCalld5ea3e32018-01-24 17:53:32 +0000545 EXPECT_THAT(ClassFromPreamble.items, Contains(Named("member")));
Sam McCall0bb24cd2018-02-13 08:59:23 +0000546
547 Opts.Index = nullptr;
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000548 auto WithoutIndex =
549 cantFail(runCodeComplete(Server, File, Test.point(), Opts));
Sam McCall0bb24cd2018-02-13 08:59:23 +0000550 EXPECT_THAT(WithoutIndex.items,
551 UnorderedElementsAre(Named("local"), Named("preamble")));
Sam McCalla15c2d62018-01-18 09:27:56 +0000552}
553
554TEST(CompletionTest, DynamicIndexMultiFile) {
555 MockFSProvider FS;
556 MockCompilationDatabase CDB;
557 IgnoreDiagnostics DiagConsumer;
Sam McCall7363a2f2018-03-05 17:28:54 +0000558 auto Opts = ClangdServer::optsForTest();
559 Opts.BuildDynamicSymbolIndex = true;
560 ClangdServer Server(CDB, FS, DiagConsumer, Opts);
Sam McCalla15c2d62018-01-18 09:27:56 +0000561
Eric Liu709bde82018-02-19 18:48:44 +0000562 FS.Files[testPath("foo.h")] = R"cpp(
Sam McCalla15c2d62018-01-18 09:27:56 +0000563 namespace ns { class XYZ {}; void foo(int x) {} }
Eric Liu709bde82018-02-19 18:48:44 +0000564 )cpp";
Sam McCall7363a2f2018-03-05 17:28:54 +0000565 runAddDocument(Server, testPath("foo.cpp"), R"cpp(
Eric Liu709bde82018-02-19 18:48:44 +0000566 #include "foo.h"
Sam McCall0bb24cd2018-02-13 08:59:23 +0000567 )cpp");
Sam McCalla15c2d62018-01-18 09:27:56 +0000568
Sam McCallc1568062018-02-16 09:41:43 +0000569 auto File = testPath("bar.cpp");
Sam McCalla15c2d62018-01-18 09:27:56 +0000570 Annotations Test(R"cpp(
571 namespace ns {
572 class XXX {};
573 /// Doooc
574 void fooooo() {}
575 }
576 void f() { ns::^ }
577 )cpp");
Sam McCall7363a2f2018-03-05 17:28:54 +0000578 runAddDocument(Server, File, Test.code());
Sam McCalla15c2d62018-01-18 09:27:56 +0000579
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000580 auto Results = cantFail(runCodeComplete(Server, File, Test.point(), {}));
Sam McCalla15c2d62018-01-18 09:27:56 +0000581 // "XYZ" and "foo" are not included in the file being completed but are still
582 // visible through the index.
583 EXPECT_THAT(Results.items, Has("XYZ", CompletionItemKind::Class));
584 EXPECT_THAT(Results.items, Has("foo", CompletionItemKind::Function));
585 EXPECT_THAT(Results.items, Has("XXX", CompletionItemKind::Class));
586 EXPECT_THAT(Results.items, Contains(AllOf(Named("fooooo"), Filter("fooooo"),
587 Kind(CompletionItemKind::Function),
588 Doc("Doooc"), Detail("void"))));
589}
590
Haojian Wu58d208d2018-01-25 09:44:06 +0000591TEST(CodeCompleteTest, DisableTypoCorrection) {
592 auto Results = completions(R"cpp(
593 namespace clang { int v; }
594 void f() { clangd::^
595 )cpp");
596 EXPECT_TRUE(Results.items.empty());
597}
598
Ilya Biryukov53d6d932018-03-06 16:45:21 +0000599TEST(CodeCompleteTest, NoColonColonAtTheEnd) {
600 auto Results = completions(R"cpp(
601 namespace clang { }
602 void f() {
603 clan^
604 }
605 )cpp");
606
607 EXPECT_THAT(Results.items, Contains(Labeled("clang")));
608 EXPECT_THAT(Results.items, Not(Contains(Labeled("clang::"))));
609}
610
Sam McCall800d4372017-12-19 10:29:27 +0000611SignatureHelp signatures(StringRef Text) {
612 MockFSProvider FS;
613 MockCompilationDatabase CDB;
614 IgnoreDiagnostics DiagConsumer;
Sam McCall7363a2f2018-03-05 17:28:54 +0000615 ClangdServer Server(CDB, FS, DiagConsumer, ClangdServer::optsForTest());
Sam McCallc1568062018-02-16 09:41:43 +0000616 auto File = testPath("foo.cpp");
Sam McCall328cbdb2017-12-20 16:06:05 +0000617 Annotations Test(Text);
Sam McCall7363a2f2018-03-05 17:28:54 +0000618 runAddDocument(Server, File, Test.code());
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000619 return cantFail(runSignatureHelp(Server, File, Test.point()));
Sam McCall800d4372017-12-19 10:29:27 +0000620}
621
622MATCHER_P(ParamsAre, P, "") {
623 if (P.size() != arg.parameters.size())
624 return false;
625 for (unsigned I = 0; I < P.size(); ++I)
626 if (P[I] != arg.parameters[I].label)
627 return false;
628 return true;
629}
630
631Matcher<SignatureInformation> Sig(std::string Label,
632 std::vector<std::string> Params) {
633 return AllOf(Labeled(Label), ParamsAre(Params));
634}
635
636TEST(SignatureHelpTest, Overloads) {
637 auto Results = signatures(R"cpp(
638 void foo(int x, int y);
639 void foo(int x, float y);
640 void foo(float x, int y);
641 void foo(float x, float y);
642 void bar(int x, int y = 0);
643 int main() { foo(^); }
644 )cpp");
645 EXPECT_THAT(Results.signatures,
646 UnorderedElementsAre(
647 Sig("foo(float x, float y) -> void", {"float x", "float y"}),
648 Sig("foo(float x, int y) -> void", {"float x", "int y"}),
649 Sig("foo(int x, float y) -> void", {"int x", "float y"}),
650 Sig("foo(int x, int y) -> void", {"int x", "int y"})));
651 // We always prefer the first signature.
652 EXPECT_EQ(0, Results.activeSignature);
653 EXPECT_EQ(0, Results.activeParameter);
654}
655
656TEST(SignatureHelpTest, DefaultArgs) {
657 auto Results = signatures(R"cpp(
658 void bar(int x, int y = 0);
659 void bar(float x = 0, int y = 42);
660 int main() { bar(^
661 )cpp");
662 EXPECT_THAT(Results.signatures,
663 UnorderedElementsAre(
664 Sig("bar(int x, int y = 0) -> void", {"int x", "int y = 0"}),
665 Sig("bar(float x = 0, int y = 42) -> void",
666 {"float x = 0", "int y = 42"})));
667 EXPECT_EQ(0, Results.activeSignature);
668 EXPECT_EQ(0, Results.activeParameter);
669}
670
671TEST(SignatureHelpTest, ActiveArg) {
672 auto Results = signatures(R"cpp(
673 int baz(int a, int b, int c);
674 int main() { baz(baz(1,2,3), ^); }
675 )cpp");
676 EXPECT_THAT(Results.signatures,
677 ElementsAre(Sig("baz(int a, int b, int c) -> int",
678 {"int a", "int b", "int c"})));
679 EXPECT_EQ(0, Results.activeSignature);
680 EXPECT_EQ(1, Results.activeParameter);
681}
682
Haojian Wu061c73e2018-01-23 11:37:26 +0000683class IndexRequestCollector : public SymbolIndex {
684public:
685 bool
Sam McCalld1a7a372018-01-31 13:40:48 +0000686 fuzzyFind(const FuzzyFindRequest &Req,
Haojian Wu061c73e2018-01-23 11:37:26 +0000687 llvm::function_ref<void(const Symbol &)> Callback) const override {
688 Requests.push_back(Req);
Sam McCallab8e3932018-02-19 13:04:41 +0000689 return true;
Haojian Wu061c73e2018-01-23 11:37:26 +0000690 }
691
692 const std::vector<FuzzyFindRequest> allRequests() const { return Requests; }
693
694private:
695 mutable std::vector<FuzzyFindRequest> Requests;
696};
697
698std::vector<FuzzyFindRequest> captureIndexRequests(llvm::StringRef Code) {
699 clangd::CodeCompleteOptions Opts;
700 IndexRequestCollector Requests;
701 Opts.Index = &Requests;
702 completions(Code, {}, Opts);
703 return Requests.allRequests();
704}
705
706TEST(CompletionTest, UnqualifiedIdQuery) {
707 auto Requests = captureIndexRequests(R"cpp(
708 namespace std {}
709 using namespace std;
710 namespace ns {
711 void f() {
712 vec^
713 }
714 }
715 )cpp");
716
717 EXPECT_THAT(Requests,
718 ElementsAre(Field(&FuzzyFindRequest::Scopes,
719 UnorderedElementsAre("", "ns::", "std::"))));
720}
721
722TEST(CompletionTest, ResolvedQualifiedIdQuery) {
723 auto Requests = captureIndexRequests(R"cpp(
724 namespace ns1 {}
725 namespace ns2 {} // ignore
726 namespace ns3 { namespace nns3 {} }
727 namespace foo {
728 using namespace ns1;
729 using namespace ns3::nns3;
730 }
731 namespace ns {
732 void f() {
733 foo::^
734 }
735 }
736 )cpp");
737
738 EXPECT_THAT(Requests,
739 ElementsAre(Field(
740 &FuzzyFindRequest::Scopes,
741 UnorderedElementsAre("foo::", "ns1::", "ns3::nns3::"))));
742}
743
744TEST(CompletionTest, UnresolvedQualifierIdQuery) {
745 auto Requests = captureIndexRequests(R"cpp(
746 namespace a {}
747 using namespace a;
748 namespace ns {
749 void f() {
750 bar::^
751 }
752 } // namespace ns
753 )cpp");
754
755 EXPECT_THAT(Requests, ElementsAre(Field(&FuzzyFindRequest::Scopes,
756 UnorderedElementsAre("bar::"))));
757}
758
759TEST(CompletionTest, UnresolvedNestedQualifierIdQuery) {
760 auto Requests = captureIndexRequests(R"cpp(
761 namespace a {}
762 using namespace a;
763 namespace ns {
764 void f() {
765 ::a::bar::^
766 }
767 } // namespace ns
768 )cpp");
769
770 EXPECT_THAT(Requests, ElementsAre(Field(&FuzzyFindRequest::Scopes,
771 UnorderedElementsAre("a::bar::"))));
772}
773
774TEST(CompletionTest, EmptyQualifiedQuery) {
775 auto Requests = captureIndexRequests(R"cpp(
776 namespace ns {
777 void f() {
778 ^
779 }
780 } // namespace ns
781 )cpp");
782
783 EXPECT_THAT(Requests, ElementsAre(Field(&FuzzyFindRequest::Scopes,
784 UnorderedElementsAre("", "ns::"))));
785}
786
787TEST(CompletionTest, GlobalQualifiedQuery) {
788 auto Requests = captureIndexRequests(R"cpp(
789 namespace ns {
790 void f() {
791 ::^
792 }
793 } // namespace ns
794 )cpp");
795
796 EXPECT_THAT(Requests, ElementsAre(Field(&FuzzyFindRequest::Scopes,
797 UnorderedElementsAre(""))));
798}
799
Sam McCall9aad25f2017-12-05 07:20:26 +0000800} // namespace
801} // namespace clangd
802} // namespace clang