blob: 9f456ee75a694a80083aeafd10a9893d9bf6e549 [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 McCall9aad25f2017-12-05 07:20:26 +0000120 ClangdServer Server(CDB, DiagConsumer, FS, getDefaultAsyncThreadsCount(),
Ilya Biryukov940901e2017-12-13 12:51:22 +0000121 /*StorePreamblesInMemory=*/true);
Sam McCallf6ae3232017-12-05 20:11:29 +0000122 auto File = getVirtualTestFilePath("foo.cpp");
Sam McCall328cbdb2017-12-20 16:06:05 +0000123 Annotations Test(Text);
Sam McCalld1a7a372018-01-31 13:40:48 +0000124 Server.addDocument(File, Test.code()).wait();
Ilya Biryukovcd5eb002018-02-12 11:37:28 +0000125 auto CompletionList = runCodeComplete(Server, File, Test.point(), Opts).Value;
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 = {
323 &clangd::CodeCompleteOptions::IncludeMacros,
Sam McCall2c3849a2018-01-16 12:21:24 +0000324 &clangd::CodeCompleteOptions::IncludeBriefComments,
325 &clangd::CodeCompleteOptions::EnableSnippets,
326 &clangd::CodeCompleteOptions::IncludeCodePatterns,
327 &clangd::CodeCompleteOptions::IncludeIneligibleResults,
328 };
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 McCallf6ae3232017-12-05 20:11:29 +0000339// Check code completion works when the file contents are overridden.
340TEST(CompletionTest, CheckContentsOverride) {
341 MockFSProvider FS;
342 IgnoreDiagnostics DiagConsumer;
343 MockCompilationDatabase CDB;
344 ClangdServer Server(CDB, DiagConsumer, FS, getDefaultAsyncThreadsCount(),
Ilya Biryukov940901e2017-12-13 12:51:22 +0000345 /*StorePreamblesInMemory=*/true);
Sam McCallf6ae3232017-12-05 20:11:29 +0000346 auto File = getVirtualTestFilePath("foo.cpp");
Sam McCalld1a7a372018-01-31 13:40:48 +0000347 Server.addDocument(File, "ignored text!");
Sam McCallf6ae3232017-12-05 20:11:29 +0000348
Sam McCall328cbdb2017-12-20 16:06:05 +0000349 Annotations Example("int cbc; int b = ^;");
Sam McCalld1a7a372018-01-31 13:40:48 +0000350 auto Results =
Ilya Biryukovcd5eb002018-02-12 11:37:28 +0000351 runCodeComplete(Server, File, Example.point(),
352 clangd::CodeCompleteOptions(), StringRef(Example.code()))
Sam McCalld1a7a372018-01-31 13:40:48 +0000353 .Value;
Sam McCallf6ae3232017-12-05 20:11:29 +0000354 EXPECT_THAT(Results.items, Contains(Named("cbc")));
355}
356
Sam McCall44fdcec22017-12-08 15:00:59 +0000357TEST(CompletionTest, Priorities) {
358 auto Internal = completions(R"cpp(
359 class Foo {
360 public: void pub();
361 protected: void prot();
362 private: void priv();
363 };
364 void Foo::pub() { this->^ }
365 )cpp");
366 EXPECT_THAT(Internal.items,
367 HasSubsequence(Named("priv"), Named("prot"), Named("pub")));
368
369 auto External = completions(R"cpp(
370 class Foo {
371 public: void pub();
372 protected: void prot();
373 private: void priv();
374 };
375 void test() {
376 Foo F;
377 F.^
378 }
379 )cpp");
380 EXPECT_THAT(External.items,
381 AllOf(Has("pub"), Not(Has("prot")), Not(Has("priv"))));
382}
383
384TEST(CompletionTest, Qualifiers) {
385 auto Results = completions(R"cpp(
386 class Foo {
387 public: int foo() const;
388 int bar() const;
389 };
390 class Bar : public Foo {
391 int foo() const;
392 };
393 void test() { Bar().^ }
394 )cpp");
395 EXPECT_THAT(Results.items, HasSubsequence(Labeled("bar() const"),
396 Labeled("Foo::foo() const")));
397 EXPECT_THAT(Results.items, Not(Contains(Labeled("foo() const")))); // private
398}
399
400TEST(CompletionTest, Snippets) {
401 clangd::CodeCompleteOptions Opts;
402 Opts.EnableSnippets = true;
403 auto Results = completions(
404 R"cpp(
405 struct fake {
406 int a;
407 int f(int i, const float f) const;
408 };
409 int main() {
410 fake f;
411 f.^
412 }
413 )cpp",
Sam McCalla15c2d62018-01-18 09:27:56 +0000414 /*IndexSymbols=*/{}, Opts);
Sam McCall44fdcec22017-12-08 15:00:59 +0000415 EXPECT_THAT(Results.items,
Eric Liu63696e12017-12-20 17:24:31 +0000416 HasSubsequence(Snippet("a"),
Sam McCall44fdcec22017-12-08 15:00:59 +0000417 Snippet("f(${1:int i}, ${2:const float f})")));
418}
419
420TEST(CompletionTest, Kinds) {
Sam McCall545a20d2018-01-19 14:34:02 +0000421 auto Results = completions(
422 R"cpp(
423 #define MACRO X
424 int variable;
425 struct Struct {};
426 int function();
427 int X = ^
428 )cpp",
429 {func("indexFunction"), var("indexVariable"), cls("indexClass")});
430 EXPECT_THAT(Results.items,
431 AllOf(Has("function", CompletionItemKind::Function),
432 Has("variable", CompletionItemKind::Variable),
433 Has("int", CompletionItemKind::Keyword),
434 Has("Struct", CompletionItemKind::Class),
435 Has("MACRO", CompletionItemKind::Text),
436 Has("indexFunction", CompletionItemKind::Function),
437 Has("indexVariable", CompletionItemKind::Variable),
438 Has("indexClass", CompletionItemKind::Class)));
Sam McCall44fdcec22017-12-08 15:00:59 +0000439
Sam McCall44fdcec22017-12-08 15:00:59 +0000440 Results = completions("nam^");
441 EXPECT_THAT(Results.items, Has("namespace", CompletionItemKind::Snippet));
442}
443
Sam McCall84652cc2018-01-12 16:16:09 +0000444TEST(CompletionTest, NoDuplicates) {
Sam McCall545a20d2018-01-19 14:34:02 +0000445 auto Results = completions(
446 R"cpp(
447 class Adapter {
448 void method();
449 };
Sam McCall84652cc2018-01-12 16:16:09 +0000450
Sam McCall545a20d2018-01-19 14:34:02 +0000451 void Adapter::method() {
452 Adapter^
453 }
454 )cpp",
455 {cls("Adapter")});
Sam McCall84652cc2018-01-12 16:16:09 +0000456
457 // Make sure there are no duplicate entries of 'Adapter'.
Sam McCalld2a95922018-01-22 21:05:00 +0000458 EXPECT_THAT(Results.items, ElementsAre(Named("Adapter")));
Sam McCall84652cc2018-01-12 16:16:09 +0000459}
460
Sam McCall545a20d2018-01-19 14:34:02 +0000461TEST(CompletionTest, ScopedNoIndex) {
462 auto Results = completions(
463 R"cpp(
464 namespace fake { int BigBang, Babble, Ball; };
465 int main() { fake::bb^ }
466 ")cpp");
Sam McCall84652cc2018-01-12 16:16:09 +0000467 // BigBang is a better match than Babble. Ball doesn't match at all.
Sam McCall545a20d2018-01-19 14:34:02 +0000468 EXPECT_THAT(Results.items, ElementsAre(Named("BigBang"), Named("Babble")));
Sam McCall84652cc2018-01-12 16:16:09 +0000469}
470
Sam McCall545a20d2018-01-19 14:34:02 +0000471TEST(CompletionTest, Scoped) {
Sam McCalla15c2d62018-01-18 09:27:56 +0000472 auto Results = completions(
473 R"cpp(
Sam McCall545a20d2018-01-19 14:34:02 +0000474 namespace fake { int Babble, Ball; };
475 int main() { fake::bb^ }
476 ")cpp",
477 {var("fake::BigBang")});
478 EXPECT_THAT(Results.items, ElementsAre(Named("BigBang"), Named("Babble")));
Sam McCalla15c2d62018-01-18 09:27:56 +0000479}
480
Sam McCall545a20d2018-01-19 14:34:02 +0000481TEST(CompletionTest, ScopedWithFilter) {
Sam McCalla15c2d62018-01-18 09:27:56 +0000482 auto Results = completions(
483 R"cpp(
484 void f() { ns::x^ }
485 )cpp",
486 {cls("ns::XYZ"), func("ns::foo")});
487 EXPECT_THAT(Results.items,
488 UnorderedElementsAre(AllOf(Named("XYZ"), Filter("XYZ"))));
489}
490
Sam McCall545a20d2018-01-19 14:34:02 +0000491TEST(CompletionTest, GlobalQualified) {
Sam McCalla15c2d62018-01-18 09:27:56 +0000492 auto Results = completions(
493 R"cpp(
494 void f() { ::^ }
495 )cpp",
496 {cls("XYZ")});
497 EXPECT_THAT(Results.items, AllOf(Has("XYZ", CompletionItemKind::Class),
498 Has("f", CompletionItemKind::Function)));
499}
500
Sam McCall545a20d2018-01-19 14:34:02 +0000501TEST(CompletionTest, FullyQualified) {
Sam McCalla15c2d62018-01-18 09:27:56 +0000502 auto Results = completions(
503 R"cpp(
Sam McCall545a20d2018-01-19 14:34:02 +0000504 namespace ns { void bar(); }
Sam McCalla15c2d62018-01-18 09:27:56 +0000505 void f() { ::ns::^ }
506 )cpp",
507 {cls("ns::XYZ")});
Sam McCall545a20d2018-01-19 14:34:02 +0000508 EXPECT_THAT(Results.items, AllOf(Has("XYZ", CompletionItemKind::Class),
509 Has("bar", CompletionItemKind::Function)));
510}
511
512TEST(CompletionTest, SemaIndexMerge) {
513 auto Results = completions(
514 R"cpp(
515 namespace ns { int local; void both(); }
516 void f() { ::ns::^ }
517 )cpp",
518 {func("ns::both"), cls("ns::Index")});
519 // We get results from both index and sema, with no duplicates.
520 EXPECT_THAT(
521 Results.items,
522 UnorderedElementsAre(Named("local"), Named("Index"), Named("both")));
Sam McCalla15c2d62018-01-18 09:27:56 +0000523}
524
Haojian Wu48b48652018-01-25 09:20:09 +0000525TEST(CompletionTest, SemaIndexMergeWithLimit) {
526 clangd::CodeCompleteOptions Opts;
527 Opts.Limit = 1;
528 auto Results = completions(
529 R"cpp(
530 namespace ns { int local; void both(); }
531 void f() { ::ns::^ }
532 )cpp",
533 {func("ns::both"), cls("ns::Index")}, Opts);
534 EXPECT_EQ(Results.items.size(), Opts.Limit);
535 EXPECT_TRUE(Results.isIncomplete);
536}
537
Sam McCalla15c2d62018-01-18 09:27:56 +0000538TEST(CompletionTest, IndexSuppressesPreambleCompletions) {
539 MockFSProvider FS;
540 MockCompilationDatabase CDB;
541 IgnoreDiagnostics DiagConsumer;
542 ClangdServer Server(CDB, DiagConsumer, FS, getDefaultAsyncThreadsCount(),
543 /*StorePreamblesInMemory=*/true);
544
545 FS.Files[getVirtualTestFilePath("bar.h")] =
Sam McCalld5ea3e32018-01-24 17:53:32 +0000546 R"cpp(namespace ns { struct preamble { int member; }; })cpp";
Sam McCalla15c2d62018-01-18 09:27:56 +0000547 auto File = getVirtualTestFilePath("foo.cpp");
548 Annotations Test(R"cpp(
549 #include "bar.h"
550 namespace ns { int local; }
Sam McCalld5ea3e32018-01-24 17:53:32 +0000551 void f() { ns::^; }
552 void f() { ns::preamble().$2^; }
Sam McCalla15c2d62018-01-18 09:27:56 +0000553 )cpp");
Sam McCalld1a7a372018-01-31 13:40:48 +0000554 Server.addDocument(File, Test.code()).wait();
Sam McCalla15c2d62018-01-18 09:27:56 +0000555 clangd::CodeCompleteOptions Opts = {};
556
Ilya Biryukovcd5eb002018-02-12 11:37:28 +0000557 auto WithoutIndex = runCodeComplete(Server, File, Test.point(), Opts).Value;
Sam McCalla15c2d62018-01-18 09:27:56 +0000558 EXPECT_THAT(WithoutIndex.items,
559 UnorderedElementsAre(Named("local"), Named("preamble")));
560
561 auto I = memIndex({var("ns::index")});
562 Opts.Index = I.get();
Ilya Biryukovcd5eb002018-02-12 11:37:28 +0000563 auto WithIndex = runCodeComplete(Server, File, Test.point(), Opts).Value;
Sam McCalla15c2d62018-01-18 09:27:56 +0000564 EXPECT_THAT(WithIndex.items,
565 UnorderedElementsAre(Named("local"), Named("index")));
Sam McCalld5ea3e32018-01-24 17:53:32 +0000566 auto ClassFromPreamble =
Ilya Biryukovcd5eb002018-02-12 11:37:28 +0000567 runCodeComplete(Server, File, Test.point("2"), Opts).Value;
Sam McCalld5ea3e32018-01-24 17:53:32 +0000568 EXPECT_THAT(ClassFromPreamble.items, Contains(Named("member")));
Sam McCalla15c2d62018-01-18 09:27:56 +0000569}
570
571TEST(CompletionTest, DynamicIndexMultiFile) {
572 MockFSProvider FS;
573 MockCompilationDatabase CDB;
574 IgnoreDiagnostics DiagConsumer;
575 ClangdServer Server(CDB, DiagConsumer, FS, getDefaultAsyncThreadsCount(),
576 /*StorePreamblesInMemory=*/true,
577 /*BuildDynamicSymbolIndex=*/true);
578
579 Server
Sam McCalld1a7a372018-01-31 13:40:48 +0000580 .addDocument(getVirtualTestFilePath("foo.cpp"), R"cpp(
Sam McCalla15c2d62018-01-18 09:27:56 +0000581 namespace ns { class XYZ {}; void foo(int x) {} }
582 )cpp")
583 .wait();
584
585 auto File = getVirtualTestFilePath("bar.cpp");
586 Annotations Test(R"cpp(
587 namespace ns {
588 class XXX {};
589 /// Doooc
590 void fooooo() {}
591 }
592 void f() { ns::^ }
593 )cpp");
Sam McCalld1a7a372018-01-31 13:40:48 +0000594 Server.addDocument(File, Test.code()).wait();
Sam McCalla15c2d62018-01-18 09:27:56 +0000595
Ilya Biryukovcd5eb002018-02-12 11:37:28 +0000596 auto Results = runCodeComplete(Server, File, Test.point(), {}).Value;
Sam McCalla15c2d62018-01-18 09:27:56 +0000597 // "XYZ" and "foo" are not included in the file being completed but are still
598 // visible through the index.
599 EXPECT_THAT(Results.items, Has("XYZ", CompletionItemKind::Class));
600 EXPECT_THAT(Results.items, Has("foo", CompletionItemKind::Function));
601 EXPECT_THAT(Results.items, Has("XXX", CompletionItemKind::Class));
602 EXPECT_THAT(Results.items, Contains(AllOf(Named("fooooo"), Filter("fooooo"),
603 Kind(CompletionItemKind::Function),
604 Doc("Doooc"), Detail("void"))));
605}
606
Haojian Wu58d208d2018-01-25 09:44:06 +0000607TEST(CodeCompleteTest, DisableTypoCorrection) {
608 auto Results = completions(R"cpp(
609 namespace clang { int v; }
610 void f() { clangd::^
611 )cpp");
612 EXPECT_TRUE(Results.items.empty());
613}
614
Sam McCall800d4372017-12-19 10:29:27 +0000615SignatureHelp signatures(StringRef Text) {
616 MockFSProvider FS;
617 MockCompilationDatabase CDB;
618 IgnoreDiagnostics DiagConsumer;
619 ClangdServer Server(CDB, DiagConsumer, FS, getDefaultAsyncThreadsCount(),
620 /*StorePreamblesInMemory=*/true);
621 auto File = getVirtualTestFilePath("foo.cpp");
Sam McCall328cbdb2017-12-20 16:06:05 +0000622 Annotations Test(Text);
Sam McCalld1a7a372018-01-31 13:40:48 +0000623 Server.addDocument(File, Test.code());
624 auto R = Server.signatureHelp(File, Test.point());
Sam McCall800d4372017-12-19 10:29:27 +0000625 assert(R);
626 return R.get().Value;
627}
628
629MATCHER_P(ParamsAre, P, "") {
630 if (P.size() != arg.parameters.size())
631 return false;
632 for (unsigned I = 0; I < P.size(); ++I)
633 if (P[I] != arg.parameters[I].label)
634 return false;
635 return true;
636}
637
638Matcher<SignatureInformation> Sig(std::string Label,
639 std::vector<std::string> Params) {
640 return AllOf(Labeled(Label), ParamsAre(Params));
641}
642
643TEST(SignatureHelpTest, Overloads) {
644 auto Results = signatures(R"cpp(
645 void foo(int x, int y);
646 void foo(int x, float y);
647 void foo(float x, int y);
648 void foo(float x, float y);
649 void bar(int x, int y = 0);
650 int main() { foo(^); }
651 )cpp");
652 EXPECT_THAT(Results.signatures,
653 UnorderedElementsAre(
654 Sig("foo(float x, float y) -> void", {"float x", "float y"}),
655 Sig("foo(float x, int y) -> void", {"float x", "int y"}),
656 Sig("foo(int x, float y) -> void", {"int x", "float y"}),
657 Sig("foo(int x, int y) -> void", {"int x", "int y"})));
658 // We always prefer the first signature.
659 EXPECT_EQ(0, Results.activeSignature);
660 EXPECT_EQ(0, Results.activeParameter);
661}
662
663TEST(SignatureHelpTest, DefaultArgs) {
664 auto Results = signatures(R"cpp(
665 void bar(int x, int y = 0);
666 void bar(float x = 0, int y = 42);
667 int main() { bar(^
668 )cpp");
669 EXPECT_THAT(Results.signatures,
670 UnorderedElementsAre(
671 Sig("bar(int x, int y = 0) -> void", {"int x", "int y = 0"}),
672 Sig("bar(float x = 0, int y = 42) -> void",
673 {"float x = 0", "int y = 42"})));
674 EXPECT_EQ(0, Results.activeSignature);
675 EXPECT_EQ(0, Results.activeParameter);
676}
677
678TEST(SignatureHelpTest, ActiveArg) {
679 auto Results = signatures(R"cpp(
680 int baz(int a, int b, int c);
681 int main() { baz(baz(1,2,3), ^); }
682 )cpp");
683 EXPECT_THAT(Results.signatures,
684 ElementsAre(Sig("baz(int a, int b, int c) -> int",
685 {"int a", "int b", "int c"})));
686 EXPECT_EQ(0, Results.activeSignature);
687 EXPECT_EQ(1, Results.activeParameter);
688}
689
Haojian Wu061c73e2018-01-23 11:37:26 +0000690class IndexRequestCollector : public SymbolIndex {
691public:
692 bool
Sam McCalld1a7a372018-01-31 13:40:48 +0000693 fuzzyFind(const FuzzyFindRequest &Req,
Haojian Wu061c73e2018-01-23 11:37:26 +0000694 llvm::function_ref<void(const Symbol &)> Callback) const override {
695 Requests.push_back(Req);
696 return false;
697 }
698
699 const std::vector<FuzzyFindRequest> allRequests() const { return Requests; }
700
701private:
702 mutable std::vector<FuzzyFindRequest> Requests;
703};
704
705std::vector<FuzzyFindRequest> captureIndexRequests(llvm::StringRef Code) {
706 clangd::CodeCompleteOptions Opts;
707 IndexRequestCollector Requests;
708 Opts.Index = &Requests;
709 completions(Code, {}, Opts);
710 return Requests.allRequests();
711}
712
713TEST(CompletionTest, UnqualifiedIdQuery) {
714 auto Requests = captureIndexRequests(R"cpp(
715 namespace std {}
716 using namespace std;
717 namespace ns {
718 void f() {
719 vec^
720 }
721 }
722 )cpp");
723
724 EXPECT_THAT(Requests,
725 ElementsAre(Field(&FuzzyFindRequest::Scopes,
726 UnorderedElementsAre("", "ns::", "std::"))));
727}
728
729TEST(CompletionTest, ResolvedQualifiedIdQuery) {
730 auto Requests = captureIndexRequests(R"cpp(
731 namespace ns1 {}
732 namespace ns2 {} // ignore
733 namespace ns3 { namespace nns3 {} }
734 namespace foo {
735 using namespace ns1;
736 using namespace ns3::nns3;
737 }
738 namespace ns {
739 void f() {
740 foo::^
741 }
742 }
743 )cpp");
744
745 EXPECT_THAT(Requests,
746 ElementsAre(Field(
747 &FuzzyFindRequest::Scopes,
748 UnorderedElementsAre("foo::", "ns1::", "ns3::nns3::"))));
749}
750
751TEST(CompletionTest, UnresolvedQualifierIdQuery) {
752 auto Requests = captureIndexRequests(R"cpp(
753 namespace a {}
754 using namespace a;
755 namespace ns {
756 void f() {
757 bar::^
758 }
759 } // namespace ns
760 )cpp");
761
762 EXPECT_THAT(Requests, ElementsAre(Field(&FuzzyFindRequest::Scopes,
763 UnorderedElementsAre("bar::"))));
764}
765
766TEST(CompletionTest, UnresolvedNestedQualifierIdQuery) {
767 auto Requests = captureIndexRequests(R"cpp(
768 namespace a {}
769 using namespace a;
770 namespace ns {
771 void f() {
772 ::a::bar::^
773 }
774 } // namespace ns
775 )cpp");
776
777 EXPECT_THAT(Requests, ElementsAre(Field(&FuzzyFindRequest::Scopes,
778 UnorderedElementsAre("a::bar::"))));
779}
780
781TEST(CompletionTest, EmptyQualifiedQuery) {
782 auto Requests = captureIndexRequests(R"cpp(
783 namespace ns {
784 void f() {
785 ^
786 }
787 } // namespace ns
788 )cpp");
789
790 EXPECT_THAT(Requests, ElementsAre(Field(&FuzzyFindRequest::Scopes,
791 UnorderedElementsAre("", "ns::"))));
792}
793
794TEST(CompletionTest, GlobalQualifiedQuery) {
795 auto Requests = captureIndexRequests(R"cpp(
796 namespace ns {
797 void f() {
798 ::^
799 }
800 } // namespace ns
801 )cpp");
802
803 EXPECT_THAT(Requests, ElementsAre(Field(&FuzzyFindRequest::Scopes,
804 UnorderedElementsAre(""))));
805}
806
Sam McCall9aad25f2017-12-05 07:20:26 +0000807} // namespace
808} // namespace clangd
809} // namespace clang