blob: acbed8830a40ce17eae7a9e56d737926131ef179 [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"
Sam McCall9aad25f2017-12-05 07:20:26 +000017#include "TestFS.h"
Eric Liu6f648df2017-12-19 16:50:37 +000018#include "index/MemIndex.h"
Sam McCallf6ae3232017-12-05 20:11:29 +000019#include "gmock/gmock.h"
Sam McCall9aad25f2017-12-05 07:20:26 +000020#include "gtest/gtest.h"
21
22namespace clang {
23namespace clangd {
Sam McCall800d4372017-12-19 10:29:27 +000024// Let GMock print completion items and signature help.
Sam McCallf6ae3232017-12-05 20:11:29 +000025void PrintTo(const CompletionItem &I, std::ostream *O) {
26 llvm::raw_os_ostream OS(*O);
Sam McCall44fdcec22017-12-08 15:00:59 +000027 OS << I.label << " - " << toJSON(I);
28}
29void PrintTo(const std::vector<CompletionItem> &V, std::ostream *O) {
30 *O << "{\n";
31 for (const auto &I : V) {
32 *O << "\t";
33 PrintTo(I, O);
34 *O << "\n";
35 }
36 *O << "}";
Sam McCallf6ae3232017-12-05 20:11:29 +000037}
Sam McCall800d4372017-12-19 10:29:27 +000038void PrintTo(const SignatureInformation &I, std::ostream *O) {
39 llvm::raw_os_ostream OS(*O);
40 OS << I.label << " - " << toJSON(I);
41}
42void PrintTo(const std::vector<SignatureInformation> &V, std::ostream *O) {
43 *O << "{\n";
44 for (const auto &I : V) {
45 *O << "\t";
46 PrintTo(I, O);
47 *O << "\n";
48 }
49 *O << "}";
50}
Sam McCallf6ae3232017-12-05 20:11:29 +000051
Sam McCall9aad25f2017-12-05 07:20:26 +000052namespace {
53using namespace llvm;
Sam McCallf6ae3232017-12-05 20:11:29 +000054using ::testing::AllOf;
55using ::testing::Contains;
Ilya Biryukov5a5e1ca2017-12-29 14:59:22 +000056using ::testing::Each;
Sam McCallf6ae3232017-12-05 20:11:29 +000057using ::testing::ElementsAre;
Sam McCallf6ae3232017-12-05 20:11:29 +000058using ::testing::Not;
Sam McCall3d139c52018-01-12 18:30:08 +000059using ::testing::UnorderedElementsAre;
Haojian Wu061c73e2018-01-23 11:37:26 +000060using ::testing::Field;
Sam McCall9aad25f2017-12-05 07:20:26 +000061
62class IgnoreDiagnostics : public DiagnosticsConsumer {
Sam McCalld1a7a372018-01-31 13:40:48 +000063 void onDiagnosticsReady(
64 PathRef File, Tagged<std::vector<DiagWithFixIts>> Diagnostics) override {}
Sam McCall9aad25f2017-12-05 07:20:26 +000065};
66
Sam McCallf6ae3232017-12-05 20:11:29 +000067// GMock helpers for matching completion items.
68MATCHER_P(Named, Name, "") { return arg.insertText == Name; }
Sam McCall44fdcec22017-12-08 15:00:59 +000069MATCHER_P(Labeled, Label, "") { return arg.label == Label; }
70MATCHER_P(Kind, K, "") { return arg.kind == K; }
Eric Liu6f648df2017-12-19 16:50:37 +000071MATCHER_P(Filter, F, "") { return arg.filterText == F; }
Eric Liu76f6b442018-01-09 17:32:00 +000072MATCHER_P(Doc, D, "") { return arg.documentation == D; }
73MATCHER_P(Detail, D, "") { return arg.detail == D; }
Sam McCall44fdcec22017-12-08 15:00:59 +000074MATCHER_P(PlainText, Text, "") {
75 return arg.insertTextFormat == clangd::InsertTextFormat::PlainText &&
76 arg.insertText == Text;
77}
78MATCHER_P(Snippet, Text, "") {
79 return arg.insertTextFormat == clangd::InsertTextFormat::Snippet &&
80 arg.insertText == Text;
81}
Sam McCall545a20d2018-01-19 14:34:02 +000082MATCHER(NameContainsFilter, "") {
Ilya Biryukov5a5e1ca2017-12-29 14:59:22 +000083 if (arg.filterText.empty())
84 return true;
85 return llvm::StringRef(arg.insertText).contains(arg.filterText);
86}
Sam McCallf6ae3232017-12-05 20:11:29 +000087// Shorthand for Contains(Named(Name)).
88Matcher<const std::vector<CompletionItem> &> Has(std::string Name) {
89 return Contains(Named(std::move(Name)));
90}
Sam McCall44fdcec22017-12-08 15:00:59 +000091Matcher<const std::vector<CompletionItem> &> Has(std::string Name,
92 CompletionItemKind K) {
93 return Contains(AllOf(Named(std::move(Name)), Kind(K)));
Sam McCallf6ae3232017-12-05 20:11:29 +000094}
Sam McCall44fdcec22017-12-08 15:00:59 +000095MATCHER(IsDocumented, "") { return !arg.documentation.empty(); }
Sam McCall9aad25f2017-12-05 07:20:26 +000096
Sam McCalla15c2d62018-01-18 09:27:56 +000097std::unique_ptr<SymbolIndex> memIndex(std::vector<Symbol> Symbols) {
98 SymbolSlab::Builder Slab;
99 for (const auto &Sym : Symbols)
100 Slab.insert(Sym);
101 return MemIndex::build(std::move(Slab).build());
102}
103
104// Builds a server and runs code completion.
105// If IndexSymbols is non-empty, an index will be built and passed to opts.
Sam McCallf6ae3232017-12-05 20:11:29 +0000106CompletionList completions(StringRef Text,
Sam McCalla15c2d62018-01-18 09:27:56 +0000107 std::vector<Symbol> IndexSymbols = {},
Sam McCallf6ae3232017-12-05 20:11:29 +0000108 clangd::CodeCompleteOptions Opts = {}) {
Sam McCalla15c2d62018-01-18 09:27:56 +0000109 std::unique_ptr<SymbolIndex> OverrideIndex;
110 if (!IndexSymbols.empty()) {
111 assert(!Opts.Index && "both Index and IndexSymbols given!");
112 OverrideIndex = memIndex(std::move(IndexSymbols));
113 Opts.Index = OverrideIndex.get();
114 }
115
Sam McCall9aad25f2017-12-05 07:20:26 +0000116 MockFSProvider FS;
Sam McCall93cd9912017-12-05 07:34:35 +0000117 MockCompilationDatabase CDB;
Sam McCallf6ae3232017-12-05 20:11:29 +0000118 IgnoreDiagnostics DiagConsumer;
Sam McCall9aad25f2017-12-05 07:20:26 +0000119 ClangdServer Server(CDB, DiagConsumer, FS, getDefaultAsyncThreadsCount(),
Ilya Biryukov940901e2017-12-13 12:51:22 +0000120 /*StorePreamblesInMemory=*/true);
Sam McCallf6ae3232017-12-05 20:11:29 +0000121 auto File = getVirtualTestFilePath("foo.cpp");
Sam McCall328cbdb2017-12-20 16:06:05 +0000122 Annotations Test(Text);
Sam McCalld1a7a372018-01-31 13:40:48 +0000123 Server.addDocument(File, Test.code()).wait();
Ilya Biryukov5a5e1ca2017-12-29 14:59:22 +0000124 auto CompletionList =
Sam McCalld1a7a372018-01-31 13:40:48 +0000125 Server.codeComplete(File, Test.point(), Opts).get().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 =
351 Server
352 .codeComplete(File, Example.point(), clangd::CodeCompleteOptions(),
353 StringRef(Example.code()))
354 .get()
355 .Value;
Sam McCallf6ae3232017-12-05 20:11:29 +0000356 EXPECT_THAT(Results.items, Contains(Named("cbc")));
357}
358
Sam McCall44fdcec22017-12-08 15:00:59 +0000359TEST(CompletionTest, Priorities) {
360 auto Internal = completions(R"cpp(
361 class Foo {
362 public: void pub();
363 protected: void prot();
364 private: void priv();
365 };
366 void Foo::pub() { this->^ }
367 )cpp");
368 EXPECT_THAT(Internal.items,
369 HasSubsequence(Named("priv"), Named("prot"), Named("pub")));
370
371 auto External = completions(R"cpp(
372 class Foo {
373 public: void pub();
374 protected: void prot();
375 private: void priv();
376 };
377 void test() {
378 Foo F;
379 F.^
380 }
381 )cpp");
382 EXPECT_THAT(External.items,
383 AllOf(Has("pub"), Not(Has("prot")), Not(Has("priv"))));
384}
385
386TEST(CompletionTest, Qualifiers) {
387 auto Results = completions(R"cpp(
388 class Foo {
389 public: int foo() const;
390 int bar() const;
391 };
392 class Bar : public Foo {
393 int foo() const;
394 };
395 void test() { Bar().^ }
396 )cpp");
397 EXPECT_THAT(Results.items, HasSubsequence(Labeled("bar() const"),
398 Labeled("Foo::foo() const")));
399 EXPECT_THAT(Results.items, Not(Contains(Labeled("foo() const")))); // private
400}
401
402TEST(CompletionTest, Snippets) {
403 clangd::CodeCompleteOptions Opts;
404 Opts.EnableSnippets = true;
405 auto Results = completions(
406 R"cpp(
407 struct fake {
408 int a;
409 int f(int i, const float f) const;
410 };
411 int main() {
412 fake f;
413 f.^
414 }
415 )cpp",
Sam McCalla15c2d62018-01-18 09:27:56 +0000416 /*IndexSymbols=*/{}, Opts);
Sam McCall44fdcec22017-12-08 15:00:59 +0000417 EXPECT_THAT(Results.items,
Eric Liu63696e12017-12-20 17:24:31 +0000418 HasSubsequence(Snippet("a"),
Sam McCall44fdcec22017-12-08 15:00:59 +0000419 Snippet("f(${1:int i}, ${2:const float f})")));
420}
421
422TEST(CompletionTest, Kinds) {
Sam McCall545a20d2018-01-19 14:34:02 +0000423 auto Results = completions(
424 R"cpp(
425 #define MACRO X
426 int variable;
427 struct Struct {};
428 int function();
429 int X = ^
430 )cpp",
431 {func("indexFunction"), var("indexVariable"), cls("indexClass")});
432 EXPECT_THAT(Results.items,
433 AllOf(Has("function", CompletionItemKind::Function),
434 Has("variable", CompletionItemKind::Variable),
435 Has("int", CompletionItemKind::Keyword),
436 Has("Struct", CompletionItemKind::Class),
437 Has("MACRO", CompletionItemKind::Text),
438 Has("indexFunction", CompletionItemKind::Function),
439 Has("indexVariable", CompletionItemKind::Variable),
440 Has("indexClass", CompletionItemKind::Class)));
Sam McCall44fdcec22017-12-08 15:00:59 +0000441
Sam McCall44fdcec22017-12-08 15:00:59 +0000442 Results = completions("nam^");
443 EXPECT_THAT(Results.items, Has("namespace", CompletionItemKind::Snippet));
444}
445
Sam McCall84652cc2018-01-12 16:16:09 +0000446TEST(CompletionTest, NoDuplicates) {
Sam McCall545a20d2018-01-19 14:34:02 +0000447 auto Results = completions(
448 R"cpp(
449 class Adapter {
450 void method();
451 };
Sam McCall84652cc2018-01-12 16:16:09 +0000452
Sam McCall545a20d2018-01-19 14:34:02 +0000453 void Adapter::method() {
454 Adapter^
455 }
456 )cpp",
457 {cls("Adapter")});
Sam McCall84652cc2018-01-12 16:16:09 +0000458
459 // Make sure there are no duplicate entries of 'Adapter'.
Sam McCalld2a95922018-01-22 21:05:00 +0000460 EXPECT_THAT(Results.items, ElementsAre(Named("Adapter")));
Sam McCall84652cc2018-01-12 16:16:09 +0000461}
462
Sam McCall545a20d2018-01-19 14:34:02 +0000463TEST(CompletionTest, ScopedNoIndex) {
464 auto Results = completions(
465 R"cpp(
466 namespace fake { int BigBang, Babble, Ball; };
467 int main() { fake::bb^ }
468 ")cpp");
Sam McCall84652cc2018-01-12 16:16:09 +0000469 // BigBang is a better match than Babble. Ball doesn't match at all.
Sam McCall545a20d2018-01-19 14:34:02 +0000470 EXPECT_THAT(Results.items, ElementsAre(Named("BigBang"), Named("Babble")));
Sam McCall84652cc2018-01-12 16:16:09 +0000471}
472
Sam McCall545a20d2018-01-19 14:34:02 +0000473TEST(CompletionTest, Scoped) {
Sam McCalla15c2d62018-01-18 09:27:56 +0000474 auto Results = completions(
475 R"cpp(
Sam McCall545a20d2018-01-19 14:34:02 +0000476 namespace fake { int Babble, Ball; };
477 int main() { fake::bb^ }
478 ")cpp",
479 {var("fake::BigBang")});
480 EXPECT_THAT(Results.items, ElementsAre(Named("BigBang"), Named("Babble")));
Sam McCalla15c2d62018-01-18 09:27:56 +0000481}
482
Sam McCall545a20d2018-01-19 14:34:02 +0000483TEST(CompletionTest, ScopedWithFilter) {
Sam McCalla15c2d62018-01-18 09:27:56 +0000484 auto Results = completions(
485 R"cpp(
486 void f() { ns::x^ }
487 )cpp",
488 {cls("ns::XYZ"), func("ns::foo")});
489 EXPECT_THAT(Results.items,
490 UnorderedElementsAre(AllOf(Named("XYZ"), Filter("XYZ"))));
491}
492
Sam McCall545a20d2018-01-19 14:34:02 +0000493TEST(CompletionTest, GlobalQualified) {
Sam McCalla15c2d62018-01-18 09:27:56 +0000494 auto Results = completions(
495 R"cpp(
496 void f() { ::^ }
497 )cpp",
498 {cls("XYZ")});
499 EXPECT_THAT(Results.items, AllOf(Has("XYZ", CompletionItemKind::Class),
500 Has("f", CompletionItemKind::Function)));
501}
502
Sam McCall545a20d2018-01-19 14:34:02 +0000503TEST(CompletionTest, FullyQualified) {
Sam McCalla15c2d62018-01-18 09:27:56 +0000504 auto Results = completions(
505 R"cpp(
Sam McCall545a20d2018-01-19 14:34:02 +0000506 namespace ns { void bar(); }
Sam McCalla15c2d62018-01-18 09:27:56 +0000507 void f() { ::ns::^ }
508 )cpp",
509 {cls("ns::XYZ")});
Sam McCall545a20d2018-01-19 14:34:02 +0000510 EXPECT_THAT(Results.items, AllOf(Has("XYZ", CompletionItemKind::Class),
511 Has("bar", CompletionItemKind::Function)));
512}
513
514TEST(CompletionTest, SemaIndexMerge) {
515 auto Results = completions(
516 R"cpp(
517 namespace ns { int local; void both(); }
518 void f() { ::ns::^ }
519 )cpp",
520 {func("ns::both"), cls("ns::Index")});
521 // We get results from both index and sema, with no duplicates.
522 EXPECT_THAT(
523 Results.items,
524 UnorderedElementsAre(Named("local"), Named("Index"), Named("both")));
Sam McCalla15c2d62018-01-18 09:27:56 +0000525}
526
Haojian Wu48b48652018-01-25 09:20:09 +0000527TEST(CompletionTest, SemaIndexMergeWithLimit) {
528 clangd::CodeCompleteOptions Opts;
529 Opts.Limit = 1;
530 auto Results = completions(
531 R"cpp(
532 namespace ns { int local; void both(); }
533 void f() { ::ns::^ }
534 )cpp",
535 {func("ns::both"), cls("ns::Index")}, Opts);
536 EXPECT_EQ(Results.items.size(), Opts.Limit);
537 EXPECT_TRUE(Results.isIncomplete);
538}
539
Sam McCalla15c2d62018-01-18 09:27:56 +0000540TEST(CompletionTest, IndexSuppressesPreambleCompletions) {
541 MockFSProvider FS;
542 MockCompilationDatabase CDB;
543 IgnoreDiagnostics DiagConsumer;
544 ClangdServer Server(CDB, DiagConsumer, FS, getDefaultAsyncThreadsCount(),
545 /*StorePreamblesInMemory=*/true);
546
547 FS.Files[getVirtualTestFilePath("bar.h")] =
Sam McCalld5ea3e32018-01-24 17:53:32 +0000548 R"cpp(namespace ns { struct preamble { int member; }; })cpp";
Sam McCalla15c2d62018-01-18 09:27:56 +0000549 auto File = getVirtualTestFilePath("foo.cpp");
550 Annotations Test(R"cpp(
551 #include "bar.h"
552 namespace ns { int local; }
Sam McCalld5ea3e32018-01-24 17:53:32 +0000553 void f() { ns::^; }
554 void f() { ns::preamble().$2^; }
Sam McCalla15c2d62018-01-18 09:27:56 +0000555 )cpp");
Sam McCalld1a7a372018-01-31 13:40:48 +0000556 Server.addDocument(File, Test.code()).wait();
Sam McCalla15c2d62018-01-18 09:27:56 +0000557 clangd::CodeCompleteOptions Opts = {};
558
Sam McCalld1a7a372018-01-31 13:40:48 +0000559 auto WithoutIndex = Server.codeComplete(File, Test.point(), Opts).get().Value;
Sam McCalla15c2d62018-01-18 09:27:56 +0000560 EXPECT_THAT(WithoutIndex.items,
561 UnorderedElementsAre(Named("local"), Named("preamble")));
562
563 auto I = memIndex({var("ns::index")});
564 Opts.Index = I.get();
Sam McCalld1a7a372018-01-31 13:40:48 +0000565 auto WithIndex = Server.codeComplete(File, Test.point(), Opts).get().Value;
Sam McCalla15c2d62018-01-18 09:27:56 +0000566 EXPECT_THAT(WithIndex.items,
567 UnorderedElementsAre(Named("local"), Named("index")));
Sam McCalld5ea3e32018-01-24 17:53:32 +0000568 auto ClassFromPreamble =
Sam McCalld1a7a372018-01-31 13:40:48 +0000569 Server.codeComplete(File, Test.point("2"), Opts).get().Value;
Sam McCalld5ea3e32018-01-24 17:53:32 +0000570 EXPECT_THAT(ClassFromPreamble.items, Contains(Named("member")));
Sam McCalla15c2d62018-01-18 09:27:56 +0000571}
572
573TEST(CompletionTest, DynamicIndexMultiFile) {
574 MockFSProvider FS;
575 MockCompilationDatabase CDB;
576 IgnoreDiagnostics DiagConsumer;
577 ClangdServer Server(CDB, DiagConsumer, FS, getDefaultAsyncThreadsCount(),
578 /*StorePreamblesInMemory=*/true,
579 /*BuildDynamicSymbolIndex=*/true);
580
581 Server
Sam McCalld1a7a372018-01-31 13:40:48 +0000582 .addDocument(getVirtualTestFilePath("foo.cpp"), R"cpp(
Sam McCalla15c2d62018-01-18 09:27:56 +0000583 namespace ns { class XYZ {}; void foo(int x) {} }
584 )cpp")
585 .wait();
586
587 auto File = getVirtualTestFilePath("bar.cpp");
588 Annotations Test(R"cpp(
589 namespace ns {
590 class XXX {};
591 /// Doooc
592 void fooooo() {}
593 }
594 void f() { ns::^ }
595 )cpp");
Sam McCalld1a7a372018-01-31 13:40:48 +0000596 Server.addDocument(File, Test.code()).wait();
Sam McCalla15c2d62018-01-18 09:27:56 +0000597
Sam McCalld1a7a372018-01-31 13:40:48 +0000598 auto Results = Server.codeComplete(File, Test.point(), {}).get().Value;
Sam McCalla15c2d62018-01-18 09:27:56 +0000599 // "XYZ" and "foo" are not included in the file being completed but are still
600 // visible through the index.
601 EXPECT_THAT(Results.items, Has("XYZ", CompletionItemKind::Class));
602 EXPECT_THAT(Results.items, Has("foo", CompletionItemKind::Function));
603 EXPECT_THAT(Results.items, Has("XXX", CompletionItemKind::Class));
604 EXPECT_THAT(Results.items, Contains(AllOf(Named("fooooo"), Filter("fooooo"),
605 Kind(CompletionItemKind::Function),
606 Doc("Doooc"), Detail("void"))));
607}
608
Haojian Wu58d208d2018-01-25 09:44:06 +0000609TEST(CodeCompleteTest, DisableTypoCorrection) {
610 auto Results = completions(R"cpp(
611 namespace clang { int v; }
612 void f() { clangd::^
613 )cpp");
614 EXPECT_TRUE(Results.items.empty());
615}
616
Sam McCall800d4372017-12-19 10:29:27 +0000617SignatureHelp signatures(StringRef Text) {
618 MockFSProvider FS;
619 MockCompilationDatabase CDB;
620 IgnoreDiagnostics DiagConsumer;
621 ClangdServer Server(CDB, DiagConsumer, FS, getDefaultAsyncThreadsCount(),
622 /*StorePreamblesInMemory=*/true);
623 auto File = getVirtualTestFilePath("foo.cpp");
Sam McCall328cbdb2017-12-20 16:06:05 +0000624 Annotations Test(Text);
Sam McCalld1a7a372018-01-31 13:40:48 +0000625 Server.addDocument(File, Test.code());
626 auto R = Server.signatureHelp(File, Test.point());
Sam McCall800d4372017-12-19 10:29:27 +0000627 assert(R);
628 return R.get().Value;
629}
630
631MATCHER_P(ParamsAre, P, "") {
632 if (P.size() != arg.parameters.size())
633 return false;
634 for (unsigned I = 0; I < P.size(); ++I)
635 if (P[I] != arg.parameters[I].label)
636 return false;
637 return true;
638}
639
640Matcher<SignatureInformation> Sig(std::string Label,
641 std::vector<std::string> Params) {
642 return AllOf(Labeled(Label), ParamsAre(Params));
643}
644
645TEST(SignatureHelpTest, Overloads) {
646 auto Results = signatures(R"cpp(
647 void foo(int x, int y);
648 void foo(int x, float y);
649 void foo(float x, int y);
650 void foo(float x, float y);
651 void bar(int x, int y = 0);
652 int main() { foo(^); }
653 )cpp");
654 EXPECT_THAT(Results.signatures,
655 UnorderedElementsAre(
656 Sig("foo(float x, float y) -> void", {"float x", "float y"}),
657 Sig("foo(float x, int y) -> void", {"float x", "int y"}),
658 Sig("foo(int x, float y) -> void", {"int x", "float y"}),
659 Sig("foo(int x, int y) -> void", {"int x", "int y"})));
660 // We always prefer the first signature.
661 EXPECT_EQ(0, Results.activeSignature);
662 EXPECT_EQ(0, Results.activeParameter);
663}
664
665TEST(SignatureHelpTest, DefaultArgs) {
666 auto Results = signatures(R"cpp(
667 void bar(int x, int y = 0);
668 void bar(float x = 0, int y = 42);
669 int main() { bar(^
670 )cpp");
671 EXPECT_THAT(Results.signatures,
672 UnorderedElementsAre(
673 Sig("bar(int x, int y = 0) -> void", {"int x", "int y = 0"}),
674 Sig("bar(float x = 0, int y = 42) -> void",
675 {"float x = 0", "int y = 42"})));
676 EXPECT_EQ(0, Results.activeSignature);
677 EXPECT_EQ(0, Results.activeParameter);
678}
679
680TEST(SignatureHelpTest, ActiveArg) {
681 auto Results = signatures(R"cpp(
682 int baz(int a, int b, int c);
683 int main() { baz(baz(1,2,3), ^); }
684 )cpp");
685 EXPECT_THAT(Results.signatures,
686 ElementsAre(Sig("baz(int a, int b, int c) -> int",
687 {"int a", "int b", "int c"})));
688 EXPECT_EQ(0, Results.activeSignature);
689 EXPECT_EQ(1, Results.activeParameter);
690}
691
Haojian Wu061c73e2018-01-23 11:37:26 +0000692class IndexRequestCollector : public SymbolIndex {
693public:
694 bool
Sam McCalld1a7a372018-01-31 13:40:48 +0000695 fuzzyFind(const FuzzyFindRequest &Req,
Haojian Wu061c73e2018-01-23 11:37:26 +0000696 llvm::function_ref<void(const Symbol &)> Callback) const override {
697 Requests.push_back(Req);
698 return false;
699 }
700
701 const std::vector<FuzzyFindRequest> allRequests() const { return Requests; }
702
703private:
704 mutable std::vector<FuzzyFindRequest> Requests;
705};
706
707std::vector<FuzzyFindRequest> captureIndexRequests(llvm::StringRef Code) {
708 clangd::CodeCompleteOptions Opts;
709 IndexRequestCollector Requests;
710 Opts.Index = &Requests;
711 completions(Code, {}, Opts);
712 return Requests.allRequests();
713}
714
715TEST(CompletionTest, UnqualifiedIdQuery) {
716 auto Requests = captureIndexRequests(R"cpp(
717 namespace std {}
718 using namespace std;
719 namespace ns {
720 void f() {
721 vec^
722 }
723 }
724 )cpp");
725
726 EXPECT_THAT(Requests,
727 ElementsAre(Field(&FuzzyFindRequest::Scopes,
728 UnorderedElementsAre("", "ns::", "std::"))));
729}
730
731TEST(CompletionTest, ResolvedQualifiedIdQuery) {
732 auto Requests = captureIndexRequests(R"cpp(
733 namespace ns1 {}
734 namespace ns2 {} // ignore
735 namespace ns3 { namespace nns3 {} }
736 namespace foo {
737 using namespace ns1;
738 using namespace ns3::nns3;
739 }
740 namespace ns {
741 void f() {
742 foo::^
743 }
744 }
745 )cpp");
746
747 EXPECT_THAT(Requests,
748 ElementsAre(Field(
749 &FuzzyFindRequest::Scopes,
750 UnorderedElementsAre("foo::", "ns1::", "ns3::nns3::"))));
751}
752
753TEST(CompletionTest, UnresolvedQualifierIdQuery) {
754 auto Requests = captureIndexRequests(R"cpp(
755 namespace a {}
756 using namespace a;
757 namespace ns {
758 void f() {
759 bar::^
760 }
761 } // namespace ns
762 )cpp");
763
764 EXPECT_THAT(Requests, ElementsAre(Field(&FuzzyFindRequest::Scopes,
765 UnorderedElementsAre("bar::"))));
766}
767
768TEST(CompletionTest, UnresolvedNestedQualifierIdQuery) {
769 auto Requests = captureIndexRequests(R"cpp(
770 namespace a {}
771 using namespace a;
772 namespace ns {
773 void f() {
774 ::a::bar::^
775 }
776 } // namespace ns
777 )cpp");
778
779 EXPECT_THAT(Requests, ElementsAre(Field(&FuzzyFindRequest::Scopes,
780 UnorderedElementsAre("a::bar::"))));
781}
782
783TEST(CompletionTest, EmptyQualifiedQuery) {
784 auto Requests = captureIndexRequests(R"cpp(
785 namespace ns {
786 void f() {
787 ^
788 }
789 } // namespace ns
790 )cpp");
791
792 EXPECT_THAT(Requests, ElementsAre(Field(&FuzzyFindRequest::Scopes,
793 UnorderedElementsAre("", "ns::"))));
794}
795
796TEST(CompletionTest, GlobalQualifiedQuery) {
797 auto Requests = captureIndexRequests(R"cpp(
798 namespace ns {
799 void f() {
800 ::^
801 }
802 } // namespace ns
803 )cpp");
804
805 EXPECT_THAT(Requests, ElementsAre(Field(&FuzzyFindRequest::Scopes,
806 UnorderedElementsAre(""))));
807}
808
Sam McCall9aad25f2017-12-05 07:20:26 +0000809} // namespace
810} // namespace clangd
811} // namespace clang