blob: d4c9d7d1e2996536b452b070a441ceb9b5fbfe92 [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 McCallc1568062018-02-16 09:41:43 +0000122 auto File = testPath("foo.cpp");
Sam McCall328cbdb2017-12-20 16:06:05 +0000123 Annotations Test(Text);
Sam McCall0bb24cd2018-02-13 08:59:23 +0000124 Server.addDocument(File, Test.code());
125 EXPECT_TRUE(Server.blockUntilIdleForTest()) << "Waiting for preamble";
Ilya Biryukovcd5eb002018-02-12 11:37:28 +0000126 auto CompletionList = runCodeComplete(Server, File, Test.point(), Opts).Value;
Ilya Biryukov5a5e1ca2017-12-29 14:59:22 +0000127 // Sanity-check that filterText is valid.
Sam McCall545a20d2018-01-19 14:34:02 +0000128 EXPECT_THAT(CompletionList.items, Each(NameContainsFilter()));
Ilya Biryukov5a5e1ca2017-12-29 14:59:22 +0000129 return CompletionList;
Sam McCall9aad25f2017-12-05 07:20:26 +0000130}
131
Sam McCall545a20d2018-01-19 14:34:02 +0000132std::string replace(StringRef Haystack, StringRef Needle, StringRef Repl) {
133 std::string Result;
134 raw_string_ostream OS(Result);
135 std::pair<StringRef, StringRef> Split;
136 for (Split = Haystack.split(Needle); !Split.second.empty();
137 Split = Split.first.split(Needle))
138 OS << Split.first << Repl;
139 Result += Split.first;
140 OS.flush();
141 return Result;
142}
143
Sam McCalla15c2d62018-01-18 09:27:56 +0000144// Helpers to produce fake index symbols for memIndex() or completions().
Sam McCall545a20d2018-01-19 14:34:02 +0000145// USRFormat is a regex replacement string for the unqualified part of the USR.
146Symbol sym(StringRef QName, index::SymbolKind Kind, StringRef USRFormat) {
Sam McCalla15c2d62018-01-18 09:27:56 +0000147 Symbol Sym;
Sam McCall545a20d2018-01-19 14:34:02 +0000148 std::string USR = "c:"; // We synthesize a few simple cases of USRs by hand!
Sam McCalla15c2d62018-01-18 09:27:56 +0000149 size_t Pos = QName.rfind("::");
150 if (Pos == llvm::StringRef::npos) {
151 Sym.Name = QName;
152 Sym.Scope = "";
153 } else {
154 Sym.Name = QName.substr(Pos + 2);
Sam McCall8b2faee2018-01-19 22:18:21 +0000155 Sym.Scope = QName.substr(0, Pos + 2);
156 USR += "@N@" + replace(QName.substr(0, Pos), "::", "@N@"); // ns:: -> @N@ns
Sam McCalla15c2d62018-01-18 09:27:56 +0000157 }
Sam McCall545a20d2018-01-19 14:34:02 +0000158 USR += Regex("^.*$").sub(USRFormat, Sym.Name); // e.g. func -> @F@func#
159 Sym.ID = SymbolID(USR);
Sam McCalla15c2d62018-01-18 09:27:56 +0000160 Sym.CompletionPlainInsertText = Sym.Name;
Sam McCall545a20d2018-01-19 14:34:02 +0000161 Sym.CompletionSnippetInsertText = Sym.Name;
Sam McCalla15c2d62018-01-18 09:27:56 +0000162 Sym.CompletionLabel = Sym.Name;
163 Sym.SymInfo.Kind = Kind;
164 return Sym;
165}
Sam McCall545a20d2018-01-19 14:34:02 +0000166Symbol func(StringRef Name) { // Assumes the function has no args.
167 return sym(Name, index::SymbolKind::Function, "@F@\\0#"); // no args
168}
169Symbol cls(StringRef Name) {
170 return sym(Name, index::SymbolKind::Class, "@S@\\0@S@\\0");
171}
172Symbol var(StringRef Name) {
173 return sym(Name, index::SymbolKind::Variable, "@\\0");
174}
Sam McCalla15c2d62018-01-18 09:27:56 +0000175
Sam McCallf6ae3232017-12-05 20:11:29 +0000176TEST(CompletionTest, Limit) {
177 clangd::CodeCompleteOptions Opts;
178 Opts.Limit = 2;
179 auto Results = completions(R"cpp(
Sam McCall9aad25f2017-12-05 07:20:26 +0000180struct ClassWithMembers {
181 int AAA();
182 int BBB();
183 int CCC();
184}
Sam McCallf6ae3232017-12-05 20:11:29 +0000185int main() { ClassWithMembers().^ }
Sam McCall9aad25f2017-12-05 07:20:26 +0000186 )cpp",
Sam McCalla15c2d62018-01-18 09:27:56 +0000187 /*IndexSymbols=*/{}, Opts);
Sam McCall9aad25f2017-12-05 07:20:26 +0000188
189 EXPECT_TRUE(Results.isIncomplete);
Sam McCallf6ae3232017-12-05 20:11:29 +0000190 EXPECT_THAT(Results.items, ElementsAre(Named("AAA"), Named("BBB")));
Sam McCall9aad25f2017-12-05 07:20:26 +0000191}
192
Sam McCallf6ae3232017-12-05 20:11:29 +0000193TEST(CompletionTest, Filter) {
194 std::string Body = R"cpp(
Sam McCall9aad25f2017-12-05 07:20:26 +0000195 int Abracadabra;
196 int Alakazam;
197 struct S {
198 int FooBar;
199 int FooBaz;
200 int Qux;
201 };
202 )cpp";
Sam McCallf6ae3232017-12-05 20:11:29 +0000203 EXPECT_THAT(completions(Body + "int main() { S().Foba^ }").items,
204 AllOf(Has("FooBar"), Has("FooBaz"), Not(Has("Qux"))));
Sam McCall9aad25f2017-12-05 07:20:26 +0000205
Sam McCallf6ae3232017-12-05 20:11:29 +0000206 EXPECT_THAT(completions(Body + "int main() { S().FR^ }").items,
207 AllOf(Has("FooBar"), Not(Has("FooBaz")), Not(Has("Qux"))));
Sam McCall9aad25f2017-12-05 07:20:26 +0000208
Sam McCallf6ae3232017-12-05 20:11:29 +0000209 EXPECT_THAT(completions(Body + "int main() { S().opr^ }").items,
210 Has("operator="));
Sam McCall9aad25f2017-12-05 07:20:26 +0000211
Sam McCallf6ae3232017-12-05 20:11:29 +0000212 EXPECT_THAT(completions(Body + "int main() { aaa^ }").items,
213 AllOf(Has("Abracadabra"), Has("Alakazam")));
Sam McCall9aad25f2017-12-05 07:20:26 +0000214
Sam McCallf6ae3232017-12-05 20:11:29 +0000215 EXPECT_THAT(completions(Body + "int main() { _a^ }").items,
216 AllOf(Has("static_cast"), Not(Has("Abracadabra"))));
Sam McCall9aad25f2017-12-05 07:20:26 +0000217}
218
Sam McCallf6ae3232017-12-05 20:11:29 +0000219void TestAfterDotCompletion(clangd::CodeCompleteOptions Opts) {
Sam McCall44fdcec22017-12-08 15:00:59 +0000220 auto Results = completions(
221 R"cpp(
222 #define MACRO X
Sam McCall9aad25f2017-12-05 07:20:26 +0000223
Sam McCall44fdcec22017-12-08 15:00:59 +0000224 int global_var;
Sam McCall9aad25f2017-12-05 07:20:26 +0000225
Sam McCall44fdcec22017-12-08 15:00:59 +0000226 int global_func();
Sam McCall9aad25f2017-12-05 07:20:26 +0000227
Sam McCall44fdcec22017-12-08 15:00:59 +0000228 struct GlobalClass {};
Sam McCall9aad25f2017-12-05 07:20:26 +0000229
Sam McCall44fdcec22017-12-08 15:00:59 +0000230 struct ClassWithMembers {
231 /// Doc for method.
232 int method();
Sam McCall9aad25f2017-12-05 07:20:26 +0000233
Sam McCall44fdcec22017-12-08 15:00:59 +0000234 int field;
235 private:
236 int private_field;
237 };
Sam McCall9aad25f2017-12-05 07:20:26 +0000238
Sam McCall44fdcec22017-12-08 15:00:59 +0000239 int test() {
240 struct LocalClass {};
Sam McCall9aad25f2017-12-05 07:20:26 +0000241
Sam McCall44fdcec22017-12-08 15:00:59 +0000242 /// Doc for local_var.
243 int local_var;
Sam McCall9aad25f2017-12-05 07:20:26 +0000244
Sam McCall44fdcec22017-12-08 15:00:59 +0000245 ClassWithMembers().^
246 }
247 )cpp",
Sam McCall545a20d2018-01-19 14:34:02 +0000248 {cls("IndexClass"), var("index_var"), func("index_func")}, Opts);
Sam McCall9aad25f2017-12-05 07:20:26 +0000249
Sam McCallf6ae3232017-12-05 20:11:29 +0000250 // Class members. The only items that must be present in after-dot
251 // completion.
Sam McCall44fdcec22017-12-08 15:00:59 +0000252 EXPECT_THAT(
253 Results.items,
254 AllOf(Has(Opts.EnableSnippets ? "method()" : "method"), Has("field")));
255 EXPECT_IFF(Opts.IncludeIneligibleResults, Results.items,
256 Has("private_field"));
Sam McCallf6ae3232017-12-05 20:11:29 +0000257 // Global items.
Sam McCall545a20d2018-01-19 14:34:02 +0000258 EXPECT_THAT(
259 Results.items,
260 Not(AnyOf(Has("global_var"), Has("index_var"), Has("global_func"),
261 Has("global_func()"), Has("index_func"), Has("GlobalClass"),
262 Has("IndexClass"), Has("MACRO"), Has("LocalClass"))));
Sam McCallf6ae3232017-12-05 20:11:29 +0000263 // There should be no code patterns (aka snippets) in after-dot
264 // completion. At least there aren't any we're aware of.
Sam McCall44fdcec22017-12-08 15:00:59 +0000265 EXPECT_THAT(Results.items, Not(Contains(Kind(CompletionItemKind::Snippet))));
Sam McCallf6ae3232017-12-05 20:11:29 +0000266 // Check documentation.
Sam McCall44fdcec22017-12-08 15:00:59 +0000267 EXPECT_IFF(Opts.IncludeBriefComments, Results.items,
268 Contains(IsDocumented()));
Sam McCallf6ae3232017-12-05 20:11:29 +0000269}
Sam McCall9aad25f2017-12-05 07:20:26 +0000270
Sam McCallf6ae3232017-12-05 20:11:29 +0000271void TestGlobalScopeCompletion(clangd::CodeCompleteOptions Opts) {
Sam McCall44fdcec22017-12-08 15:00:59 +0000272 auto Results = completions(
273 R"cpp(
274 #define MACRO X
Sam McCall9aad25f2017-12-05 07:20:26 +0000275
Sam McCall44fdcec22017-12-08 15:00:59 +0000276 int global_var;
277 int global_func();
Sam McCall9aad25f2017-12-05 07:20:26 +0000278
Sam McCall44fdcec22017-12-08 15:00:59 +0000279 struct GlobalClass {};
Sam McCall9aad25f2017-12-05 07:20:26 +0000280
Sam McCall44fdcec22017-12-08 15:00:59 +0000281 struct ClassWithMembers {
282 /// Doc for method.
283 int method();
284 };
Sam McCall9aad25f2017-12-05 07:20:26 +0000285
Sam McCall44fdcec22017-12-08 15:00:59 +0000286 int test() {
287 struct LocalClass {};
Sam McCall9aad25f2017-12-05 07:20:26 +0000288
Sam McCall44fdcec22017-12-08 15:00:59 +0000289 /// Doc for local_var.
290 int local_var;
Sam McCall9aad25f2017-12-05 07:20:26 +0000291
Sam McCall44fdcec22017-12-08 15:00:59 +0000292 ^
293 }
294 )cpp",
Sam McCall545a20d2018-01-19 14:34:02 +0000295 {cls("IndexClass"), var("index_var"), func("index_func")}, Opts);
Sam McCallf6ae3232017-12-05 20:11:29 +0000296
297 // Class members. Should never be present in global completions.
Sam McCall44fdcec22017-12-08 15:00:59 +0000298 EXPECT_THAT(Results.items,
Sam McCallf6ae3232017-12-05 20:11:29 +0000299 Not(AnyOf(Has("method"), Has("method()"), Has("field"))));
300 // Global items.
Sam McCalld8169a82018-01-18 15:31:30 +0000301 EXPECT_THAT(Results.items,
Sam McCall545a20d2018-01-19 14:34:02 +0000302 AllOf(Has("global_var"), Has("index_var"),
Sam McCalld8169a82018-01-18 15:31:30 +0000303 Has(Opts.EnableSnippets ? "global_func()" : "global_func"),
Sam McCall545a20d2018-01-19 14:34:02 +0000304 Has("index_func" /* our fake symbol doesn't include () */),
305 Has("GlobalClass"), Has("IndexClass")));
Sam McCallf6ae3232017-12-05 20:11:29 +0000306 // A macro.
Sam McCall44fdcec22017-12-08 15:00:59 +0000307 EXPECT_IFF(Opts.IncludeMacros, Results.items, Has("MACRO"));
Sam McCallf6ae3232017-12-05 20:11:29 +0000308 // Local items. Must be present always.
Ilya Biryukov9b5ffc22017-12-12 12:56:46 +0000309 EXPECT_THAT(Results.items,
310 AllOf(Has("local_var"), Has("LocalClass"),
311 Contains(Kind(CompletionItemKind::Snippet))));
Sam McCallf6ae3232017-12-05 20:11:29 +0000312 // Check documentation.
Sam McCall44fdcec22017-12-08 15:00:59 +0000313 EXPECT_IFF(Opts.IncludeBriefComments, Results.items,
314 Contains(IsDocumented()));
Sam McCallf6ae3232017-12-05 20:11:29 +0000315}
316
317TEST(CompletionTest, CompletionOptions) {
Sam McCall2c3849a2018-01-16 12:21:24 +0000318 auto Test = [&](const clangd::CodeCompleteOptions &Opts) {
319 TestAfterDotCompletion(Opts);
320 TestGlobalScopeCompletion(Opts);
321 };
322 // We used to test every combination of options, but that got too slow (2^N).
323 auto Flags = {
324 &clangd::CodeCompleteOptions::IncludeMacros,
Sam McCall2c3849a2018-01-16 12:21:24 +0000325 &clangd::CodeCompleteOptions::IncludeBriefComments,
326 &clangd::CodeCompleteOptions::EnableSnippets,
327 &clangd::CodeCompleteOptions::IncludeCodePatterns,
328 &clangd::CodeCompleteOptions::IncludeIneligibleResults,
329 };
330 // Test default options.
331 Test({});
332 // Test with one flag flipped.
333 for (auto &F : Flags) {
334 clangd::CodeCompleteOptions O;
335 O.*F ^= true;
336 Test(O);
Sam McCall9aad25f2017-12-05 07:20:26 +0000337 }
338}
339
Sam McCallf6ae3232017-12-05 20:11:29 +0000340// Check code completion works when the file contents are overridden.
341TEST(CompletionTest, CheckContentsOverride) {
342 MockFSProvider FS;
343 IgnoreDiagnostics DiagConsumer;
344 MockCompilationDatabase CDB;
345 ClangdServer Server(CDB, DiagConsumer, FS, getDefaultAsyncThreadsCount(),
Ilya Biryukov940901e2017-12-13 12:51:22 +0000346 /*StorePreamblesInMemory=*/true);
Sam McCallc1568062018-02-16 09:41:43 +0000347 auto File = testPath("foo.cpp");
Sam McCalld1a7a372018-01-31 13:40:48 +0000348 Server.addDocument(File, "ignored text!");
Sam McCallf6ae3232017-12-05 20:11:29 +0000349
Sam McCall328cbdb2017-12-20 16:06:05 +0000350 Annotations Example("int cbc; int b = ^;");
Sam McCalld1a7a372018-01-31 13:40:48 +0000351 auto Results =
Ilya Biryukovcd5eb002018-02-12 11:37:28 +0000352 runCodeComplete(Server, File, Example.point(),
353 clangd::CodeCompleteOptions(), StringRef(Example.code()))
Sam McCalld1a7a372018-01-31 13:40:48 +0000354 .Value;
Sam McCallf6ae3232017-12-05 20:11:29 +0000355 EXPECT_THAT(Results.items, Contains(Named("cbc")));
356}
357
Sam McCall44fdcec22017-12-08 15:00:59 +0000358TEST(CompletionTest, Priorities) {
359 auto Internal = completions(R"cpp(
360 class Foo {
361 public: void pub();
362 protected: void prot();
363 private: void priv();
364 };
365 void Foo::pub() { this->^ }
366 )cpp");
367 EXPECT_THAT(Internal.items,
368 HasSubsequence(Named("priv"), Named("prot"), Named("pub")));
369
370 auto External = completions(R"cpp(
371 class Foo {
372 public: void pub();
373 protected: void prot();
374 private: void priv();
375 };
376 void test() {
377 Foo F;
378 F.^
379 }
380 )cpp");
381 EXPECT_THAT(External.items,
382 AllOf(Has("pub"), Not(Has("prot")), Not(Has("priv"))));
383}
384
385TEST(CompletionTest, Qualifiers) {
386 auto Results = completions(R"cpp(
387 class Foo {
388 public: int foo() const;
389 int bar() const;
390 };
391 class Bar : public Foo {
392 int foo() const;
393 };
394 void test() { Bar().^ }
395 )cpp");
396 EXPECT_THAT(Results.items, HasSubsequence(Labeled("bar() const"),
397 Labeled("Foo::foo() const")));
398 EXPECT_THAT(Results.items, Not(Contains(Labeled("foo() const")))); // private
399}
400
401TEST(CompletionTest, Snippets) {
402 clangd::CodeCompleteOptions Opts;
403 Opts.EnableSnippets = true;
404 auto Results = completions(
405 R"cpp(
406 struct fake {
407 int a;
408 int f(int i, const float f) const;
409 };
410 int main() {
411 fake f;
412 f.^
413 }
414 )cpp",
Sam McCalla15c2d62018-01-18 09:27:56 +0000415 /*IndexSymbols=*/{}, Opts);
Sam McCall44fdcec22017-12-08 15:00:59 +0000416 EXPECT_THAT(Results.items,
Eric Liu63696e12017-12-20 17:24:31 +0000417 HasSubsequence(Snippet("a"),
Sam McCall44fdcec22017-12-08 15:00:59 +0000418 Snippet("f(${1:int i}, ${2:const float f})")));
419}
420
421TEST(CompletionTest, Kinds) {
Sam McCall545a20d2018-01-19 14:34:02 +0000422 auto Results = completions(
423 R"cpp(
424 #define MACRO X
425 int variable;
426 struct Struct {};
427 int function();
428 int X = ^
429 )cpp",
430 {func("indexFunction"), var("indexVariable"), cls("indexClass")});
431 EXPECT_THAT(Results.items,
432 AllOf(Has("function", CompletionItemKind::Function),
433 Has("variable", CompletionItemKind::Variable),
434 Has("int", CompletionItemKind::Keyword),
435 Has("Struct", CompletionItemKind::Class),
436 Has("MACRO", CompletionItemKind::Text),
437 Has("indexFunction", CompletionItemKind::Function),
438 Has("indexVariable", CompletionItemKind::Variable),
439 Has("indexClass", CompletionItemKind::Class)));
Sam McCall44fdcec22017-12-08 15:00:59 +0000440
Sam McCall44fdcec22017-12-08 15:00:59 +0000441 Results = completions("nam^");
442 EXPECT_THAT(Results.items, Has("namespace", CompletionItemKind::Snippet));
443}
444
Sam McCall84652cc2018-01-12 16:16:09 +0000445TEST(CompletionTest, NoDuplicates) {
Sam McCall545a20d2018-01-19 14:34:02 +0000446 auto Results = completions(
447 R"cpp(
448 class Adapter {
449 void method();
450 };
Sam McCall84652cc2018-01-12 16:16:09 +0000451
Sam McCall545a20d2018-01-19 14:34:02 +0000452 void Adapter::method() {
453 Adapter^
454 }
455 )cpp",
456 {cls("Adapter")});
Sam McCall84652cc2018-01-12 16:16:09 +0000457
458 // Make sure there are no duplicate entries of 'Adapter'.
Sam McCalld2a95922018-01-22 21:05:00 +0000459 EXPECT_THAT(Results.items, ElementsAre(Named("Adapter")));
Sam McCall84652cc2018-01-12 16:16:09 +0000460}
461
Sam McCall545a20d2018-01-19 14:34:02 +0000462TEST(CompletionTest, ScopedNoIndex) {
463 auto Results = completions(
464 R"cpp(
465 namespace fake { int BigBang, Babble, Ball; };
466 int main() { fake::bb^ }
467 ")cpp");
Sam McCall84652cc2018-01-12 16:16:09 +0000468 // BigBang is a better match than Babble. Ball doesn't match at all.
Sam McCall545a20d2018-01-19 14:34:02 +0000469 EXPECT_THAT(Results.items, ElementsAre(Named("BigBang"), Named("Babble")));
Sam McCall84652cc2018-01-12 16:16:09 +0000470}
471
Sam McCall545a20d2018-01-19 14:34:02 +0000472TEST(CompletionTest, Scoped) {
Sam McCalla15c2d62018-01-18 09:27:56 +0000473 auto Results = completions(
474 R"cpp(
Sam McCall545a20d2018-01-19 14:34:02 +0000475 namespace fake { int Babble, Ball; };
476 int main() { fake::bb^ }
477 ")cpp",
478 {var("fake::BigBang")});
479 EXPECT_THAT(Results.items, ElementsAre(Named("BigBang"), Named("Babble")));
Sam McCalla15c2d62018-01-18 09:27:56 +0000480}
481
Sam McCall545a20d2018-01-19 14:34:02 +0000482TEST(CompletionTest, ScopedWithFilter) {
Sam McCalla15c2d62018-01-18 09:27:56 +0000483 auto Results = completions(
484 R"cpp(
485 void f() { ns::x^ }
486 )cpp",
487 {cls("ns::XYZ"), func("ns::foo")});
488 EXPECT_THAT(Results.items,
489 UnorderedElementsAre(AllOf(Named("XYZ"), Filter("XYZ"))));
490}
491
Sam McCall545a20d2018-01-19 14:34:02 +0000492TEST(CompletionTest, GlobalQualified) {
Sam McCalla15c2d62018-01-18 09:27:56 +0000493 auto Results = completions(
494 R"cpp(
495 void f() { ::^ }
496 )cpp",
497 {cls("XYZ")});
498 EXPECT_THAT(Results.items, AllOf(Has("XYZ", CompletionItemKind::Class),
499 Has("f", CompletionItemKind::Function)));
500}
501
Sam McCall545a20d2018-01-19 14:34:02 +0000502TEST(CompletionTest, FullyQualified) {
Sam McCalla15c2d62018-01-18 09:27:56 +0000503 auto Results = completions(
504 R"cpp(
Sam McCall545a20d2018-01-19 14:34:02 +0000505 namespace ns { void bar(); }
Sam McCalla15c2d62018-01-18 09:27:56 +0000506 void f() { ::ns::^ }
507 )cpp",
508 {cls("ns::XYZ")});
Sam McCall545a20d2018-01-19 14:34:02 +0000509 EXPECT_THAT(Results.items, AllOf(Has("XYZ", CompletionItemKind::Class),
510 Has("bar", CompletionItemKind::Function)));
511}
512
513TEST(CompletionTest, SemaIndexMerge) {
514 auto Results = completions(
515 R"cpp(
516 namespace ns { int local; void both(); }
517 void f() { ::ns::^ }
518 )cpp",
519 {func("ns::both"), cls("ns::Index")});
520 // We get results from both index and sema, with no duplicates.
521 EXPECT_THAT(
522 Results.items,
523 UnorderedElementsAre(Named("local"), Named("Index"), Named("both")));
Sam McCalla15c2d62018-01-18 09:27:56 +0000524}
525
Haojian Wu48b48652018-01-25 09:20:09 +0000526TEST(CompletionTest, SemaIndexMergeWithLimit) {
527 clangd::CodeCompleteOptions Opts;
528 Opts.Limit = 1;
529 auto Results = completions(
530 R"cpp(
531 namespace ns { int local; void both(); }
532 void f() { ::ns::^ }
533 )cpp",
534 {func("ns::both"), cls("ns::Index")}, Opts);
535 EXPECT_EQ(Results.items.size(), Opts.Limit);
536 EXPECT_TRUE(Results.isIncomplete);
537}
538
Sam McCalla15c2d62018-01-18 09:27:56 +0000539TEST(CompletionTest, IndexSuppressesPreambleCompletions) {
540 MockFSProvider FS;
541 MockCompilationDatabase CDB;
542 IgnoreDiagnostics DiagConsumer;
543 ClangdServer Server(CDB, DiagConsumer, FS, getDefaultAsyncThreadsCount(),
544 /*StorePreamblesInMemory=*/true);
545
Sam McCallc1568062018-02-16 09:41:43 +0000546 FS.Files[testPath("bar.h")] =
Sam McCalld5ea3e32018-01-24 17:53:32 +0000547 R"cpp(namespace ns { struct preamble { int member; }; })cpp";
Sam McCallc1568062018-02-16 09:41:43 +0000548 auto File = testPath("foo.cpp");
Sam McCalla15c2d62018-01-18 09:27:56 +0000549 Annotations Test(R"cpp(
550 #include "bar.h"
551 namespace ns { int local; }
Sam McCalld5ea3e32018-01-24 17:53:32 +0000552 void f() { ns::^; }
553 void f() { ns::preamble().$2^; }
Sam McCalla15c2d62018-01-18 09:27:56 +0000554 )cpp");
Sam McCall0bb24cd2018-02-13 08:59:23 +0000555 Server.addDocument(File, Test.code());
556 ASSERT_TRUE(Server.blockUntilIdleForTest()) << "Waiting for preamble";
Sam McCalla15c2d62018-01-18 09:27:56 +0000557 clangd::CodeCompleteOptions Opts = {};
558
Sam McCalla15c2d62018-01-18 09:27:56 +0000559 auto I = memIndex({var("ns::index")});
560 Opts.Index = I.get();
Ilya Biryukovcd5eb002018-02-12 11:37:28 +0000561 auto WithIndex = runCodeComplete(Server, File, Test.point(), Opts).Value;
Sam McCalla15c2d62018-01-18 09:27:56 +0000562 EXPECT_THAT(WithIndex.items,
563 UnorderedElementsAre(Named("local"), Named("index")));
Sam McCalld5ea3e32018-01-24 17:53:32 +0000564 auto ClassFromPreamble =
Ilya Biryukovcd5eb002018-02-12 11:37:28 +0000565 runCodeComplete(Server, File, Test.point("2"), Opts).Value;
Sam McCalld5ea3e32018-01-24 17:53:32 +0000566 EXPECT_THAT(ClassFromPreamble.items, Contains(Named("member")));
Sam McCall0bb24cd2018-02-13 08:59:23 +0000567
568 Opts.Index = nullptr;
569 auto WithoutIndex = runCodeComplete(Server, File, Test.point(), Opts).Value;
570 EXPECT_THAT(WithoutIndex.items,
571 UnorderedElementsAre(Named("local"), Named("preamble")));
572
Sam McCalla15c2d62018-01-18 09:27:56 +0000573}
574
575TEST(CompletionTest, DynamicIndexMultiFile) {
576 MockFSProvider FS;
577 MockCompilationDatabase CDB;
578 IgnoreDiagnostics DiagConsumer;
579 ClangdServer Server(CDB, DiagConsumer, FS, getDefaultAsyncThreadsCount(),
580 /*StorePreamblesInMemory=*/true,
581 /*BuildDynamicSymbolIndex=*/true);
582
Eric Liu709bde82018-02-19 18:48:44 +0000583 FS.Files[testPath("foo.h")] = R"cpp(
Sam McCalla15c2d62018-01-18 09:27:56 +0000584 namespace ns { class XYZ {}; void foo(int x) {} }
Eric Liu709bde82018-02-19 18:48:44 +0000585 )cpp";
586 Server.addDocument(testPath("foo.cpp"), R"cpp(
587 #include "foo.h"
Sam McCall0bb24cd2018-02-13 08:59:23 +0000588 )cpp");
589 ASSERT_TRUE(Server.blockUntilIdleForTest()) << "Waiting for preamble";
Sam McCalla15c2d62018-01-18 09:27:56 +0000590
Sam McCallc1568062018-02-16 09:41:43 +0000591 auto File = testPath("bar.cpp");
Sam McCalla15c2d62018-01-18 09:27:56 +0000592 Annotations Test(R"cpp(
593 namespace ns {
594 class XXX {};
595 /// Doooc
596 void fooooo() {}
597 }
598 void f() { ns::^ }
599 )cpp");
Sam McCall0bb24cd2018-02-13 08:59:23 +0000600 Server.addDocument(File, Test.code());
601 ASSERT_TRUE(Server.blockUntilIdleForTest()) << "Waiting for preamble";
Sam McCalla15c2d62018-01-18 09:27:56 +0000602
Ilya Biryukovcd5eb002018-02-12 11:37:28 +0000603 auto Results = runCodeComplete(Server, File, Test.point(), {}).Value;
Sam McCalla15c2d62018-01-18 09:27:56 +0000604 // "XYZ" and "foo" are not included in the file being completed but are still
605 // visible through the index.
606 EXPECT_THAT(Results.items, Has("XYZ", CompletionItemKind::Class));
607 EXPECT_THAT(Results.items, Has("foo", CompletionItemKind::Function));
608 EXPECT_THAT(Results.items, Has("XXX", CompletionItemKind::Class));
609 EXPECT_THAT(Results.items, Contains(AllOf(Named("fooooo"), Filter("fooooo"),
610 Kind(CompletionItemKind::Function),
611 Doc("Doooc"), Detail("void"))));
612}
613
Haojian Wu58d208d2018-01-25 09:44:06 +0000614TEST(CodeCompleteTest, DisableTypoCorrection) {
615 auto Results = completions(R"cpp(
616 namespace clang { int v; }
617 void f() { clangd::^
618 )cpp");
619 EXPECT_TRUE(Results.items.empty());
620}
621
Sam McCall800d4372017-12-19 10:29:27 +0000622SignatureHelp signatures(StringRef Text) {
623 MockFSProvider FS;
624 MockCompilationDatabase CDB;
625 IgnoreDiagnostics DiagConsumer;
626 ClangdServer Server(CDB, DiagConsumer, FS, getDefaultAsyncThreadsCount(),
627 /*StorePreamblesInMemory=*/true);
Sam McCallc1568062018-02-16 09:41:43 +0000628 auto File = testPath("foo.cpp");
Sam McCall328cbdb2017-12-20 16:06:05 +0000629 Annotations Test(Text);
Sam McCalld1a7a372018-01-31 13:40:48 +0000630 Server.addDocument(File, Test.code());
Sam McCall0bb24cd2018-02-13 08:59:23 +0000631 EXPECT_TRUE(Server.blockUntilIdleForTest()) << "Waiting for preamble";
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000632 auto R = runSignatureHelp(Server, File, Test.point());
Sam McCall800d4372017-12-19 10:29:27 +0000633 assert(R);
634 return R.get().Value;
635}
636
637MATCHER_P(ParamsAre, P, "") {
638 if (P.size() != arg.parameters.size())
639 return false;
640 for (unsigned I = 0; I < P.size(); ++I)
641 if (P[I] != arg.parameters[I].label)
642 return false;
643 return true;
644}
645
646Matcher<SignatureInformation> Sig(std::string Label,
647 std::vector<std::string> Params) {
648 return AllOf(Labeled(Label), ParamsAre(Params));
649}
650
651TEST(SignatureHelpTest, Overloads) {
652 auto Results = signatures(R"cpp(
653 void foo(int x, int y);
654 void foo(int x, float y);
655 void foo(float x, int y);
656 void foo(float x, float y);
657 void bar(int x, int y = 0);
658 int main() { foo(^); }
659 )cpp");
660 EXPECT_THAT(Results.signatures,
661 UnorderedElementsAre(
662 Sig("foo(float x, float y) -> void", {"float x", "float y"}),
663 Sig("foo(float x, int y) -> void", {"float x", "int y"}),
664 Sig("foo(int x, float y) -> void", {"int x", "float y"}),
665 Sig("foo(int x, int y) -> void", {"int x", "int y"})));
666 // We always prefer the first signature.
667 EXPECT_EQ(0, Results.activeSignature);
668 EXPECT_EQ(0, Results.activeParameter);
669}
670
671TEST(SignatureHelpTest, DefaultArgs) {
672 auto Results = signatures(R"cpp(
673 void bar(int x, int y = 0);
674 void bar(float x = 0, int y = 42);
675 int main() { bar(^
676 )cpp");
677 EXPECT_THAT(Results.signatures,
678 UnorderedElementsAre(
679 Sig("bar(int x, int y = 0) -> void", {"int x", "int y = 0"}),
680 Sig("bar(float x = 0, int y = 42) -> void",
681 {"float x = 0", "int y = 42"})));
682 EXPECT_EQ(0, Results.activeSignature);
683 EXPECT_EQ(0, Results.activeParameter);
684}
685
686TEST(SignatureHelpTest, ActiveArg) {
687 auto Results = signatures(R"cpp(
688 int baz(int a, int b, int c);
689 int main() { baz(baz(1,2,3), ^); }
690 )cpp");
691 EXPECT_THAT(Results.signatures,
692 ElementsAre(Sig("baz(int a, int b, int c) -> int",
693 {"int a", "int b", "int c"})));
694 EXPECT_EQ(0, Results.activeSignature);
695 EXPECT_EQ(1, Results.activeParameter);
696}
697
Haojian Wu061c73e2018-01-23 11:37:26 +0000698class IndexRequestCollector : public SymbolIndex {
699public:
700 bool
Sam McCalld1a7a372018-01-31 13:40:48 +0000701 fuzzyFind(const FuzzyFindRequest &Req,
Haojian Wu061c73e2018-01-23 11:37:26 +0000702 llvm::function_ref<void(const Symbol &)> Callback) const override {
703 Requests.push_back(Req);
Sam McCallab8e3932018-02-19 13:04:41 +0000704 return true;
Haojian Wu061c73e2018-01-23 11:37:26 +0000705 }
706
707 const std::vector<FuzzyFindRequest> allRequests() const { return Requests; }
708
709private:
710 mutable std::vector<FuzzyFindRequest> Requests;
711};
712
713std::vector<FuzzyFindRequest> captureIndexRequests(llvm::StringRef Code) {
714 clangd::CodeCompleteOptions Opts;
715 IndexRequestCollector Requests;
716 Opts.Index = &Requests;
717 completions(Code, {}, Opts);
718 return Requests.allRequests();
719}
720
721TEST(CompletionTest, UnqualifiedIdQuery) {
722 auto Requests = captureIndexRequests(R"cpp(
723 namespace std {}
724 using namespace std;
725 namespace ns {
726 void f() {
727 vec^
728 }
729 }
730 )cpp");
731
732 EXPECT_THAT(Requests,
733 ElementsAre(Field(&FuzzyFindRequest::Scopes,
734 UnorderedElementsAre("", "ns::", "std::"))));
735}
736
737TEST(CompletionTest, ResolvedQualifiedIdQuery) {
738 auto Requests = captureIndexRequests(R"cpp(
739 namespace ns1 {}
740 namespace ns2 {} // ignore
741 namespace ns3 { namespace nns3 {} }
742 namespace foo {
743 using namespace ns1;
744 using namespace ns3::nns3;
745 }
746 namespace ns {
747 void f() {
748 foo::^
749 }
750 }
751 )cpp");
752
753 EXPECT_THAT(Requests,
754 ElementsAre(Field(
755 &FuzzyFindRequest::Scopes,
756 UnorderedElementsAre("foo::", "ns1::", "ns3::nns3::"))));
757}
758
759TEST(CompletionTest, UnresolvedQualifierIdQuery) {
760 auto Requests = captureIndexRequests(R"cpp(
761 namespace a {}
762 using namespace a;
763 namespace ns {
764 void f() {
765 bar::^
766 }
767 } // namespace ns
768 )cpp");
769
770 EXPECT_THAT(Requests, ElementsAre(Field(&FuzzyFindRequest::Scopes,
771 UnorderedElementsAre("bar::"))));
772}
773
774TEST(CompletionTest, UnresolvedNestedQualifierIdQuery) {
775 auto Requests = captureIndexRequests(R"cpp(
776 namespace a {}
777 using namespace a;
778 namespace ns {
779 void f() {
780 ::a::bar::^
781 }
782 } // namespace ns
783 )cpp");
784
785 EXPECT_THAT(Requests, ElementsAre(Field(&FuzzyFindRequest::Scopes,
786 UnorderedElementsAre("a::bar::"))));
787}
788
789TEST(CompletionTest, EmptyQualifiedQuery) {
790 auto Requests = captureIndexRequests(R"cpp(
791 namespace ns {
792 void f() {
793 ^
794 }
795 } // namespace ns
796 )cpp");
797
798 EXPECT_THAT(Requests, ElementsAre(Field(&FuzzyFindRequest::Scopes,
799 UnorderedElementsAre("", "ns::"))));
800}
801
802TEST(CompletionTest, GlobalQualifiedQuery) {
803 auto Requests = captureIndexRequests(R"cpp(
804 namespace ns {
805 void f() {
806 ::^
807 }
808 } // namespace ns
809 )cpp");
810
811 EXPECT_THAT(Requests, ElementsAre(Field(&FuzzyFindRequest::Scopes,
812 UnorderedElementsAre(""))));
813}
814
Sam McCall9aad25f2017-12-05 07:20:26 +0000815} // namespace
816} // namespace clangd
817} // namespace clang