blob: 5528fcbe7bad2ea6b0a32a8131742e593778ee25 [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 Biryukov940901e2017-12-13 12:51:22 +000014#include "Context.h"
Ilya Biryukov5a85b8e2017-12-13 12:53:16 +000015#include "Matchers.h"
Sam McCall9aad25f2017-12-05 07:20:26 +000016#include "Protocol.h"
Sam McCallb536a2a2017-12-19 12:23:48 +000017#include "SourceCode.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;
Sam McCall9aad25f2017-12-05 07:20:26 +000061
62class IgnoreDiagnostics : public DiagnosticsConsumer {
Ilya Biryukov95558392018-01-10 17:59:27 +000063 void
64 onDiagnosticsReady(const Context &Ctx, PathRef File,
65 Tagged<std::vector<DiagWithFixIts>> Diagnostics) override {
66 }
Sam McCall9aad25f2017-12-05 07:20:26 +000067};
68
Sam McCallf6ae3232017-12-05 20:11:29 +000069// GMock helpers for matching completion items.
70MATCHER_P(Named, Name, "") { return arg.insertText == Name; }
Sam McCall44fdcec22017-12-08 15:00:59 +000071MATCHER_P(Labeled, Label, "") { return arg.label == Label; }
72MATCHER_P(Kind, K, "") { return arg.kind == K; }
Eric Liu6f648df2017-12-19 16:50:37 +000073MATCHER_P(Filter, F, "") { return arg.filterText == F; }
Eric Liu76f6b442018-01-09 17:32:00 +000074MATCHER_P(Doc, D, "") { return arg.documentation == D; }
75MATCHER_P(Detail, D, "") { return arg.detail == D; }
Sam McCall44fdcec22017-12-08 15:00:59 +000076MATCHER_P(PlainText, Text, "") {
77 return arg.insertTextFormat == clangd::InsertTextFormat::PlainText &&
78 arg.insertText == Text;
79}
80MATCHER_P(Snippet, Text, "") {
81 return arg.insertTextFormat == clangd::InsertTextFormat::Snippet &&
82 arg.insertText == Text;
83}
Sam McCall545a20d2018-01-19 14:34:02 +000084MATCHER(NameContainsFilter, "") {
Ilya Biryukov5a5e1ca2017-12-29 14:59:22 +000085 if (arg.filterText.empty())
86 return true;
87 return llvm::StringRef(arg.insertText).contains(arg.filterText);
88}
Sam McCallf6ae3232017-12-05 20:11:29 +000089// Shorthand for Contains(Named(Name)).
90Matcher<const std::vector<CompletionItem> &> Has(std::string Name) {
91 return Contains(Named(std::move(Name)));
92}
Sam McCall44fdcec22017-12-08 15:00:59 +000093Matcher<const std::vector<CompletionItem> &> Has(std::string Name,
94 CompletionItemKind K) {
95 return Contains(AllOf(Named(std::move(Name)), Kind(K)));
Sam McCallf6ae3232017-12-05 20:11:29 +000096}
Sam McCall44fdcec22017-12-08 15:00:59 +000097MATCHER(IsDocumented, "") { return !arg.documentation.empty(); }
Sam McCall9aad25f2017-12-05 07:20:26 +000098
Sam McCalla15c2d62018-01-18 09:27:56 +000099std::unique_ptr<SymbolIndex> memIndex(std::vector<Symbol> Symbols) {
100 SymbolSlab::Builder Slab;
101 for (const auto &Sym : Symbols)
102 Slab.insert(Sym);
103 return MemIndex::build(std::move(Slab).build());
104}
105
106// Builds a server and runs code completion.
107// If IndexSymbols is non-empty, an index will be built and passed to opts.
Sam McCallf6ae3232017-12-05 20:11:29 +0000108CompletionList completions(StringRef Text,
Sam McCalla15c2d62018-01-18 09:27:56 +0000109 std::vector<Symbol> IndexSymbols = {},
Sam McCallf6ae3232017-12-05 20:11:29 +0000110 clangd::CodeCompleteOptions Opts = {}) {
Sam McCalla15c2d62018-01-18 09:27:56 +0000111 std::unique_ptr<SymbolIndex> OverrideIndex;
112 if (!IndexSymbols.empty()) {
113 assert(!Opts.Index && "both Index and IndexSymbols given!");
114 OverrideIndex = memIndex(std::move(IndexSymbols));
115 Opts.Index = OverrideIndex.get();
116 }
117
Sam McCall9aad25f2017-12-05 07:20:26 +0000118 MockFSProvider FS;
Sam McCall93cd9912017-12-05 07:34:35 +0000119 MockCompilationDatabase CDB;
Sam McCallf6ae3232017-12-05 20:11:29 +0000120 IgnoreDiagnostics DiagConsumer;
Sam McCall9aad25f2017-12-05 07:20:26 +0000121 ClangdServer Server(CDB, DiagConsumer, FS, getDefaultAsyncThreadsCount(),
Ilya Biryukov940901e2017-12-13 12:51:22 +0000122 /*StorePreamblesInMemory=*/true);
Sam McCallf6ae3232017-12-05 20:11:29 +0000123 auto File = getVirtualTestFilePath("foo.cpp");
Sam McCall328cbdb2017-12-20 16:06:05 +0000124 Annotations Test(Text);
Sam McCall3d139c52018-01-12 18:30:08 +0000125 Server.addDocument(Context::empty(), File, Test.code()).wait();
Ilya Biryukov5a5e1ca2017-12-29 14:59:22 +0000126 auto CompletionList =
127 Server.codeComplete(Context::empty(), File, Test.point(), Opts)
128 .get()
129 .second.Value;
130 // Sanity-check that filterText is valid.
Sam McCall545a20d2018-01-19 14:34:02 +0000131 EXPECT_THAT(CompletionList.items, Each(NameContainsFilter()));
Ilya Biryukov5a5e1ca2017-12-29 14:59:22 +0000132 return CompletionList;
Sam McCall9aad25f2017-12-05 07:20:26 +0000133}
134
Sam McCall545a20d2018-01-19 14:34:02 +0000135std::string replace(StringRef Haystack, StringRef Needle, StringRef Repl) {
136 std::string Result;
137 raw_string_ostream OS(Result);
138 std::pair<StringRef, StringRef> Split;
139 for (Split = Haystack.split(Needle); !Split.second.empty();
140 Split = Split.first.split(Needle))
141 OS << Split.first << Repl;
142 Result += Split.first;
143 OS.flush();
144 return Result;
145}
146
Sam McCalla15c2d62018-01-18 09:27:56 +0000147// Helpers to produce fake index symbols for memIndex() or completions().
Sam McCall545a20d2018-01-19 14:34:02 +0000148// USRFormat is a regex replacement string for the unqualified part of the USR.
149Symbol sym(StringRef QName, index::SymbolKind Kind, StringRef USRFormat) {
Sam McCalla15c2d62018-01-18 09:27:56 +0000150 Symbol Sym;
Sam McCall545a20d2018-01-19 14:34:02 +0000151 std::string USR = "c:"; // We synthesize a few simple cases of USRs by hand!
Sam McCalla15c2d62018-01-18 09:27:56 +0000152 size_t Pos = QName.rfind("::");
153 if (Pos == llvm::StringRef::npos) {
154 Sym.Name = QName;
155 Sym.Scope = "";
156 } else {
157 Sym.Name = QName.substr(Pos + 2);
Sam McCall8b2faee2018-01-19 22:18:21 +0000158 Sym.Scope = QName.substr(0, Pos + 2);
159 USR += "@N@" + replace(QName.substr(0, Pos), "::", "@N@"); // ns:: -> @N@ns
Sam McCalla15c2d62018-01-18 09:27:56 +0000160 }
Sam McCall545a20d2018-01-19 14:34:02 +0000161 USR += Regex("^.*$").sub(USRFormat, Sym.Name); // e.g. func -> @F@func#
162 Sym.ID = SymbolID(USR);
Sam McCalla15c2d62018-01-18 09:27:56 +0000163 Sym.CompletionPlainInsertText = Sym.Name;
Sam McCall545a20d2018-01-19 14:34:02 +0000164 Sym.CompletionSnippetInsertText = Sym.Name;
Sam McCalla15c2d62018-01-18 09:27:56 +0000165 Sym.CompletionLabel = Sym.Name;
166 Sym.SymInfo.Kind = Kind;
167 return Sym;
168}
Sam McCall545a20d2018-01-19 14:34:02 +0000169Symbol func(StringRef Name) { // Assumes the function has no args.
170 return sym(Name, index::SymbolKind::Function, "@F@\\0#"); // no args
171}
172Symbol cls(StringRef Name) {
173 return sym(Name, index::SymbolKind::Class, "@S@\\0@S@\\0");
174}
175Symbol var(StringRef Name) {
176 return sym(Name, index::SymbolKind::Variable, "@\\0");
177}
Sam McCalla15c2d62018-01-18 09:27:56 +0000178
Sam McCallf6ae3232017-12-05 20:11:29 +0000179TEST(CompletionTest, Limit) {
180 clangd::CodeCompleteOptions Opts;
181 Opts.Limit = 2;
182 auto Results = completions(R"cpp(
Sam McCall9aad25f2017-12-05 07:20:26 +0000183struct ClassWithMembers {
184 int AAA();
185 int BBB();
186 int CCC();
187}
Sam McCallf6ae3232017-12-05 20:11:29 +0000188int main() { ClassWithMembers().^ }
Sam McCall9aad25f2017-12-05 07:20:26 +0000189 )cpp",
Sam McCalla15c2d62018-01-18 09:27:56 +0000190 /*IndexSymbols=*/{}, Opts);
Sam McCall9aad25f2017-12-05 07:20:26 +0000191
192 EXPECT_TRUE(Results.isIncomplete);
Sam McCallf6ae3232017-12-05 20:11:29 +0000193 EXPECT_THAT(Results.items, ElementsAre(Named("AAA"), Named("BBB")));
Sam McCall9aad25f2017-12-05 07:20:26 +0000194}
195
Sam McCallf6ae3232017-12-05 20:11:29 +0000196TEST(CompletionTest, Filter) {
197 std::string Body = R"cpp(
Sam McCall9aad25f2017-12-05 07:20:26 +0000198 int Abracadabra;
199 int Alakazam;
200 struct S {
201 int FooBar;
202 int FooBaz;
203 int Qux;
204 };
205 )cpp";
Sam McCallf6ae3232017-12-05 20:11:29 +0000206 EXPECT_THAT(completions(Body + "int main() { S().Foba^ }").items,
207 AllOf(Has("FooBar"), 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().FR^ }").items,
210 AllOf(Has("FooBar"), Not(Has("FooBaz")), Not(Has("Qux"))));
Sam McCall9aad25f2017-12-05 07:20:26 +0000211
Sam McCallf6ae3232017-12-05 20:11:29 +0000212 EXPECT_THAT(completions(Body + "int main() { S().opr^ }").items,
213 Has("operator="));
Sam McCall9aad25f2017-12-05 07:20:26 +0000214
Sam McCallf6ae3232017-12-05 20:11:29 +0000215 EXPECT_THAT(completions(Body + "int main() { aaa^ }").items,
216 AllOf(Has("Abracadabra"), Has("Alakazam")));
Sam McCall9aad25f2017-12-05 07:20:26 +0000217
Sam McCallf6ae3232017-12-05 20:11:29 +0000218 EXPECT_THAT(completions(Body + "int main() { _a^ }").items,
219 AllOf(Has("static_cast"), Not(Has("Abracadabra"))));
Sam McCall9aad25f2017-12-05 07:20:26 +0000220}
221
Sam McCallf6ae3232017-12-05 20:11:29 +0000222void TestAfterDotCompletion(clangd::CodeCompleteOptions Opts) {
Sam McCall44fdcec22017-12-08 15:00:59 +0000223 auto Results = completions(
224 R"cpp(
225 #define MACRO X
Sam McCall9aad25f2017-12-05 07:20:26 +0000226
Sam McCall44fdcec22017-12-08 15:00:59 +0000227 int global_var;
Sam McCall9aad25f2017-12-05 07:20:26 +0000228
Sam McCall44fdcec22017-12-08 15:00:59 +0000229 int global_func();
Sam McCall9aad25f2017-12-05 07:20:26 +0000230
Sam McCall44fdcec22017-12-08 15:00:59 +0000231 struct GlobalClass {};
Sam McCall9aad25f2017-12-05 07:20:26 +0000232
Sam McCall44fdcec22017-12-08 15:00:59 +0000233 struct ClassWithMembers {
234 /// Doc for method.
235 int method();
Sam McCall9aad25f2017-12-05 07:20:26 +0000236
Sam McCall44fdcec22017-12-08 15:00:59 +0000237 int field;
238 private:
239 int private_field;
240 };
Sam McCall9aad25f2017-12-05 07:20:26 +0000241
Sam McCall44fdcec22017-12-08 15:00:59 +0000242 int test() {
243 struct LocalClass {};
Sam McCall9aad25f2017-12-05 07:20:26 +0000244
Sam McCall44fdcec22017-12-08 15:00:59 +0000245 /// Doc for local_var.
246 int local_var;
Sam McCall9aad25f2017-12-05 07:20:26 +0000247
Sam McCall44fdcec22017-12-08 15:00:59 +0000248 ClassWithMembers().^
249 }
250 )cpp",
Sam McCall545a20d2018-01-19 14:34:02 +0000251 {cls("IndexClass"), var("index_var"), func("index_func")}, Opts);
Sam McCall9aad25f2017-12-05 07:20:26 +0000252
Sam McCallf6ae3232017-12-05 20:11:29 +0000253 // Class members. The only items that must be present in after-dot
254 // completion.
Sam McCall44fdcec22017-12-08 15:00:59 +0000255 EXPECT_THAT(
256 Results.items,
257 AllOf(Has(Opts.EnableSnippets ? "method()" : "method"), Has("field")));
258 EXPECT_IFF(Opts.IncludeIneligibleResults, Results.items,
259 Has("private_field"));
Sam McCallf6ae3232017-12-05 20:11:29 +0000260 // Global items.
Sam McCall545a20d2018-01-19 14:34:02 +0000261 EXPECT_THAT(
262 Results.items,
263 Not(AnyOf(Has("global_var"), Has("index_var"), Has("global_func"),
264 Has("global_func()"), Has("index_func"), Has("GlobalClass"),
265 Has("IndexClass"), Has("MACRO"), Has("LocalClass"))));
Sam McCallf6ae3232017-12-05 20:11:29 +0000266 // There should be no code patterns (aka snippets) in after-dot
267 // completion. At least there aren't any we're aware of.
Sam McCall44fdcec22017-12-08 15:00:59 +0000268 EXPECT_THAT(Results.items, Not(Contains(Kind(CompletionItemKind::Snippet))));
Sam McCallf6ae3232017-12-05 20:11:29 +0000269 // Check documentation.
Sam McCall44fdcec22017-12-08 15:00:59 +0000270 EXPECT_IFF(Opts.IncludeBriefComments, Results.items,
271 Contains(IsDocumented()));
Sam McCallf6ae3232017-12-05 20:11:29 +0000272}
Sam McCall9aad25f2017-12-05 07:20:26 +0000273
Sam McCallf6ae3232017-12-05 20:11:29 +0000274void TestGlobalScopeCompletion(clangd::CodeCompleteOptions Opts) {
Sam McCall44fdcec22017-12-08 15:00:59 +0000275 auto Results = completions(
276 R"cpp(
277 #define MACRO X
Sam McCall9aad25f2017-12-05 07:20:26 +0000278
Sam McCall44fdcec22017-12-08 15:00:59 +0000279 int global_var;
280 int global_func();
Sam McCall9aad25f2017-12-05 07:20:26 +0000281
Sam McCall44fdcec22017-12-08 15:00:59 +0000282 struct GlobalClass {};
Sam McCall9aad25f2017-12-05 07:20:26 +0000283
Sam McCall44fdcec22017-12-08 15:00:59 +0000284 struct ClassWithMembers {
285 /// Doc for method.
286 int method();
287 };
Sam McCall9aad25f2017-12-05 07:20:26 +0000288
Sam McCall44fdcec22017-12-08 15:00:59 +0000289 int test() {
290 struct LocalClass {};
Sam McCall9aad25f2017-12-05 07:20:26 +0000291
Sam McCall44fdcec22017-12-08 15:00:59 +0000292 /// Doc for local_var.
293 int local_var;
Sam McCall9aad25f2017-12-05 07:20:26 +0000294
Sam McCall44fdcec22017-12-08 15:00:59 +0000295 ^
296 }
297 )cpp",
Sam McCall545a20d2018-01-19 14:34:02 +0000298 {cls("IndexClass"), var("index_var"), func("index_func")}, Opts);
Sam McCallf6ae3232017-12-05 20:11:29 +0000299
300 // Class members. Should never be present in global completions.
Sam McCall44fdcec22017-12-08 15:00:59 +0000301 EXPECT_THAT(Results.items,
Sam McCallf6ae3232017-12-05 20:11:29 +0000302 Not(AnyOf(Has("method"), Has("method()"), Has("field"))));
303 // Global items.
Sam McCalld8169a82018-01-18 15:31:30 +0000304 EXPECT_THAT(Results.items,
Sam McCall545a20d2018-01-19 14:34:02 +0000305 AllOf(Has("global_var"), Has("index_var"),
Sam McCalld8169a82018-01-18 15:31:30 +0000306 Has(Opts.EnableSnippets ? "global_func()" : "global_func"),
Sam McCall545a20d2018-01-19 14:34:02 +0000307 Has("index_func" /* our fake symbol doesn't include () */),
308 Has("GlobalClass"), Has("IndexClass")));
Sam McCallf6ae3232017-12-05 20:11:29 +0000309 // A macro.
Sam McCall44fdcec22017-12-08 15:00:59 +0000310 EXPECT_IFF(Opts.IncludeMacros, Results.items, Has("MACRO"));
Sam McCallf6ae3232017-12-05 20:11:29 +0000311 // Local items. Must be present always.
Ilya Biryukov9b5ffc22017-12-12 12:56:46 +0000312 EXPECT_THAT(Results.items,
313 AllOf(Has("local_var"), Has("LocalClass"),
314 Contains(Kind(CompletionItemKind::Snippet))));
Sam McCallf6ae3232017-12-05 20:11:29 +0000315 // Check documentation.
Sam McCall44fdcec22017-12-08 15:00:59 +0000316 EXPECT_IFF(Opts.IncludeBriefComments, Results.items,
317 Contains(IsDocumented()));
Sam McCallf6ae3232017-12-05 20:11:29 +0000318}
319
320TEST(CompletionTest, CompletionOptions) {
Sam McCall2c3849a2018-01-16 12:21:24 +0000321 auto Test = [&](const clangd::CodeCompleteOptions &Opts) {
322 TestAfterDotCompletion(Opts);
323 TestGlobalScopeCompletion(Opts);
324 };
325 // We used to test every combination of options, but that got too slow (2^N).
326 auto Flags = {
327 &clangd::CodeCompleteOptions::IncludeMacros,
Sam McCall2c3849a2018-01-16 12:21:24 +0000328 &clangd::CodeCompleteOptions::IncludeBriefComments,
329 &clangd::CodeCompleteOptions::EnableSnippets,
330 &clangd::CodeCompleteOptions::IncludeCodePatterns,
331 &clangd::CodeCompleteOptions::IncludeIneligibleResults,
332 };
333 // Test default options.
334 Test({});
335 // Test with one flag flipped.
336 for (auto &F : Flags) {
337 clangd::CodeCompleteOptions O;
338 O.*F ^= true;
339 Test(O);
Sam McCall9aad25f2017-12-05 07:20:26 +0000340 }
341}
342
Sam McCallf6ae3232017-12-05 20:11:29 +0000343// Check code completion works when the file contents are overridden.
344TEST(CompletionTest, CheckContentsOverride) {
345 MockFSProvider FS;
346 IgnoreDiagnostics DiagConsumer;
347 MockCompilationDatabase CDB;
348 ClangdServer Server(CDB, DiagConsumer, FS, getDefaultAsyncThreadsCount(),
Ilya Biryukov940901e2017-12-13 12:51:22 +0000349 /*StorePreamblesInMemory=*/true);
Sam McCallf6ae3232017-12-05 20:11:29 +0000350 auto File = getVirtualTestFilePath("foo.cpp");
Ilya Biryukov940901e2017-12-13 12:51:22 +0000351 Server.addDocument(Context::empty(), File, "ignored text!");
Sam McCallf6ae3232017-12-05 20:11:29 +0000352
Sam McCall328cbdb2017-12-20 16:06:05 +0000353 Annotations Example("int cbc; int b = ^;");
354 auto Results = Server
355 .codeComplete(Context::empty(), File, Example.point(),
356 clangd::CodeCompleteOptions(),
357 StringRef(Example.code()))
358 .get()
359 .second.Value;
Sam McCallf6ae3232017-12-05 20:11:29 +0000360 EXPECT_THAT(Results.items, Contains(Named("cbc")));
361}
362
Sam McCall44fdcec22017-12-08 15:00:59 +0000363TEST(CompletionTest, Priorities) {
364 auto Internal = completions(R"cpp(
365 class Foo {
366 public: void pub();
367 protected: void prot();
368 private: void priv();
369 };
370 void Foo::pub() { this->^ }
371 )cpp");
372 EXPECT_THAT(Internal.items,
373 HasSubsequence(Named("priv"), Named("prot"), Named("pub")));
374
375 auto External = completions(R"cpp(
376 class Foo {
377 public: void pub();
378 protected: void prot();
379 private: void priv();
380 };
381 void test() {
382 Foo F;
383 F.^
384 }
385 )cpp");
386 EXPECT_THAT(External.items,
387 AllOf(Has("pub"), Not(Has("prot")), Not(Has("priv"))));
388}
389
390TEST(CompletionTest, Qualifiers) {
391 auto Results = completions(R"cpp(
392 class Foo {
393 public: int foo() const;
394 int bar() const;
395 };
396 class Bar : public Foo {
397 int foo() const;
398 };
399 void test() { Bar().^ }
400 )cpp");
401 EXPECT_THAT(Results.items, HasSubsequence(Labeled("bar() const"),
402 Labeled("Foo::foo() const")));
403 EXPECT_THAT(Results.items, Not(Contains(Labeled("foo() const")))); // private
404}
405
406TEST(CompletionTest, Snippets) {
407 clangd::CodeCompleteOptions Opts;
408 Opts.EnableSnippets = true;
409 auto Results = completions(
410 R"cpp(
411 struct fake {
412 int a;
413 int f(int i, const float f) const;
414 };
415 int main() {
416 fake f;
417 f.^
418 }
419 )cpp",
Sam McCalla15c2d62018-01-18 09:27:56 +0000420 /*IndexSymbols=*/{}, Opts);
Sam McCall44fdcec22017-12-08 15:00:59 +0000421 EXPECT_THAT(Results.items,
Eric Liu63696e12017-12-20 17:24:31 +0000422 HasSubsequence(Snippet("a"),
Sam McCall44fdcec22017-12-08 15:00:59 +0000423 Snippet("f(${1:int i}, ${2:const float f})")));
424}
425
426TEST(CompletionTest, Kinds) {
Sam McCall545a20d2018-01-19 14:34:02 +0000427 auto Results = completions(
428 R"cpp(
429 #define MACRO X
430 int variable;
431 struct Struct {};
432 int function();
433 int X = ^
434 )cpp",
435 {func("indexFunction"), var("indexVariable"), cls("indexClass")});
436 EXPECT_THAT(Results.items,
437 AllOf(Has("function", CompletionItemKind::Function),
438 Has("variable", CompletionItemKind::Variable),
439 Has("int", CompletionItemKind::Keyword),
440 Has("Struct", CompletionItemKind::Class),
441 Has("MACRO", CompletionItemKind::Text),
442 Has("indexFunction", CompletionItemKind::Function),
443 Has("indexVariable", CompletionItemKind::Variable),
444 Has("indexClass", CompletionItemKind::Class)));
Sam McCall44fdcec22017-12-08 15:00:59 +0000445
Sam McCall44fdcec22017-12-08 15:00:59 +0000446 Results = completions("nam^");
447 EXPECT_THAT(Results.items, Has("namespace", CompletionItemKind::Snippet));
448}
449
Sam McCall84652cc2018-01-12 16:16:09 +0000450TEST(CompletionTest, NoDuplicates) {
Sam McCall545a20d2018-01-19 14:34:02 +0000451 auto Results = completions(
452 R"cpp(
453 class Adapter {
454 void method();
455 };
Sam McCall84652cc2018-01-12 16:16:09 +0000456
Sam McCall545a20d2018-01-19 14:34:02 +0000457 void Adapter::method() {
458 Adapter^
459 }
460 )cpp",
461 {cls("Adapter")});
Sam McCall84652cc2018-01-12 16:16:09 +0000462
463 // Make sure there are no duplicate entries of 'Adapter'.
Sam McCalld2a95922018-01-22 21:05:00 +0000464 EXPECT_THAT(Results.items, ElementsAre(Named("Adapter")));
Sam McCall84652cc2018-01-12 16:16:09 +0000465}
466
Sam McCall545a20d2018-01-19 14:34:02 +0000467TEST(CompletionTest, ScopedNoIndex) {
468 auto Results = completions(
469 R"cpp(
470 namespace fake { int BigBang, Babble, Ball; };
471 int main() { fake::bb^ }
472 ")cpp");
Sam McCall84652cc2018-01-12 16:16:09 +0000473 // BigBang is a better match than Babble. Ball doesn't match at all.
Sam McCall545a20d2018-01-19 14:34:02 +0000474 EXPECT_THAT(Results.items, ElementsAre(Named("BigBang"), Named("Babble")));
Sam McCall84652cc2018-01-12 16:16:09 +0000475}
476
Sam McCall545a20d2018-01-19 14:34:02 +0000477TEST(CompletionTest, Scoped) {
Sam McCalla15c2d62018-01-18 09:27:56 +0000478 auto Results = completions(
479 R"cpp(
Sam McCall545a20d2018-01-19 14:34:02 +0000480 namespace fake { int Babble, Ball; };
481 int main() { fake::bb^ }
482 ")cpp",
483 {var("fake::BigBang")});
484 EXPECT_THAT(Results.items, ElementsAre(Named("BigBang"), Named("Babble")));
Sam McCalla15c2d62018-01-18 09:27:56 +0000485}
486
Sam McCall545a20d2018-01-19 14:34:02 +0000487TEST(CompletionTest, ScopedWithFilter) {
Sam McCalla15c2d62018-01-18 09:27:56 +0000488 auto Results = completions(
489 R"cpp(
490 void f() { ns::x^ }
491 )cpp",
492 {cls("ns::XYZ"), func("ns::foo")});
493 EXPECT_THAT(Results.items,
494 UnorderedElementsAre(AllOf(Named("XYZ"), Filter("XYZ"))));
495}
496
Sam McCall545a20d2018-01-19 14:34:02 +0000497TEST(CompletionTest, GlobalQualified) {
Sam McCalla15c2d62018-01-18 09:27:56 +0000498 auto Results = completions(
499 R"cpp(
500 void f() { ::^ }
501 )cpp",
502 {cls("XYZ")});
503 EXPECT_THAT(Results.items, AllOf(Has("XYZ", CompletionItemKind::Class),
504 Has("f", CompletionItemKind::Function)));
505}
506
Sam McCall545a20d2018-01-19 14:34:02 +0000507TEST(CompletionTest, FullyQualified) {
Sam McCalla15c2d62018-01-18 09:27:56 +0000508 auto Results = completions(
509 R"cpp(
Sam McCall545a20d2018-01-19 14:34:02 +0000510 namespace ns { void bar(); }
Sam McCalla15c2d62018-01-18 09:27:56 +0000511 void f() { ::ns::^ }
512 )cpp",
513 {cls("ns::XYZ")});
Sam McCall545a20d2018-01-19 14:34:02 +0000514 EXPECT_THAT(Results.items, AllOf(Has("XYZ", CompletionItemKind::Class),
515 Has("bar", CompletionItemKind::Function)));
516}
517
518TEST(CompletionTest, SemaIndexMerge) {
519 auto Results = completions(
520 R"cpp(
521 namespace ns { int local; void both(); }
522 void f() { ::ns::^ }
523 )cpp",
524 {func("ns::both"), cls("ns::Index")});
525 // We get results from both index and sema, with no duplicates.
526 EXPECT_THAT(
527 Results.items,
528 UnorderedElementsAre(Named("local"), Named("Index"), Named("both")));
Sam McCalla15c2d62018-01-18 09:27:56 +0000529}
530
531TEST(CompletionTest, IndexSuppressesPreambleCompletions) {
532 MockFSProvider FS;
533 MockCompilationDatabase CDB;
534 IgnoreDiagnostics DiagConsumer;
535 ClangdServer Server(CDB, DiagConsumer, FS, getDefaultAsyncThreadsCount(),
536 /*StorePreamblesInMemory=*/true);
537
538 FS.Files[getVirtualTestFilePath("bar.h")] =
539 R"cpp(namespace ns { int preamble; })cpp";
540 auto File = getVirtualTestFilePath("foo.cpp");
541 Annotations Test(R"cpp(
542 #include "bar.h"
543 namespace ns { int local; }
544 void f() { ns::^ }
545 )cpp");
546 Server.addDocument(Context::empty(), File, Test.code()).wait();
547 clangd::CodeCompleteOptions Opts = {};
548
549 auto WithoutIndex =
550 Server.codeComplete(Context::empty(), File, Test.point(), Opts)
551 .get()
552 .second.Value;
553 EXPECT_THAT(WithoutIndex.items,
554 UnorderedElementsAre(Named("local"), Named("preamble")));
555
556 auto I = memIndex({var("ns::index")});
557 Opts.Index = I.get();
558 auto WithIndex =
559 Server.codeComplete(Context::empty(), File, Test.point(), Opts)
560 .get()
561 .second.Value;
562 EXPECT_THAT(WithIndex.items,
563 UnorderedElementsAre(Named("local"), Named("index")));
564}
565
566TEST(CompletionTest, DynamicIndexMultiFile) {
567 MockFSProvider FS;
568 MockCompilationDatabase CDB;
569 IgnoreDiagnostics DiagConsumer;
570 ClangdServer Server(CDB, DiagConsumer, FS, getDefaultAsyncThreadsCount(),
571 /*StorePreamblesInMemory=*/true,
572 /*BuildDynamicSymbolIndex=*/true);
573
574 Server
575 .addDocument(Context::empty(), getVirtualTestFilePath("foo.cpp"), R"cpp(
576 namespace ns { class XYZ {}; void foo(int x) {} }
577 )cpp")
578 .wait();
579
580 auto File = getVirtualTestFilePath("bar.cpp");
581 Annotations Test(R"cpp(
582 namespace ns {
583 class XXX {};
584 /// Doooc
585 void fooooo() {}
586 }
587 void f() { ns::^ }
588 )cpp");
589 Server.addDocument(Context::empty(), File, Test.code()).wait();
590
591 auto Results = Server.codeComplete(Context::empty(), File, Test.point(), {})
592 .get()
593 .second.Value;
594 // "XYZ" and "foo" are not included in the file being completed but are still
595 // visible through the index.
596 EXPECT_THAT(Results.items, Has("XYZ", CompletionItemKind::Class));
597 EXPECT_THAT(Results.items, Has("foo", CompletionItemKind::Function));
598 EXPECT_THAT(Results.items, Has("XXX", CompletionItemKind::Class));
599 EXPECT_THAT(Results.items, Contains(AllOf(Named("fooooo"), Filter("fooooo"),
600 Kind(CompletionItemKind::Function),
601 Doc("Doooc"), Detail("void"))));
602}
603
Sam McCall800d4372017-12-19 10:29:27 +0000604SignatureHelp signatures(StringRef Text) {
605 MockFSProvider FS;
606 MockCompilationDatabase CDB;
607 IgnoreDiagnostics DiagConsumer;
608 ClangdServer Server(CDB, DiagConsumer, FS, getDefaultAsyncThreadsCount(),
609 /*StorePreamblesInMemory=*/true);
610 auto File = getVirtualTestFilePath("foo.cpp");
Sam McCall328cbdb2017-12-20 16:06:05 +0000611 Annotations Test(Text);
612 Server.addDocument(Context::empty(), File, Test.code());
613 auto R = Server.signatureHelp(Context::empty(), File, Test.point());
Sam McCall800d4372017-12-19 10:29:27 +0000614 assert(R);
615 return R.get().Value;
616}
617
618MATCHER_P(ParamsAre, P, "") {
619 if (P.size() != arg.parameters.size())
620 return false;
621 for (unsigned I = 0; I < P.size(); ++I)
622 if (P[I] != arg.parameters[I].label)
623 return false;
624 return true;
625}
626
627Matcher<SignatureInformation> Sig(std::string Label,
628 std::vector<std::string> Params) {
629 return AllOf(Labeled(Label), ParamsAre(Params));
630}
631
632TEST(SignatureHelpTest, Overloads) {
633 auto Results = signatures(R"cpp(
634 void foo(int x, int y);
635 void foo(int x, float y);
636 void foo(float x, int y);
637 void foo(float x, float y);
638 void bar(int x, int y = 0);
639 int main() { foo(^); }
640 )cpp");
641 EXPECT_THAT(Results.signatures,
642 UnorderedElementsAre(
643 Sig("foo(float x, float y) -> void", {"float x", "float y"}),
644 Sig("foo(float x, int y) -> void", {"float x", "int y"}),
645 Sig("foo(int x, float y) -> void", {"int x", "float y"}),
646 Sig("foo(int x, int y) -> void", {"int x", "int y"})));
647 // We always prefer the first signature.
648 EXPECT_EQ(0, Results.activeSignature);
649 EXPECT_EQ(0, Results.activeParameter);
650}
651
652TEST(SignatureHelpTest, DefaultArgs) {
653 auto Results = signatures(R"cpp(
654 void bar(int x, int y = 0);
655 void bar(float x = 0, int y = 42);
656 int main() { bar(^
657 )cpp");
658 EXPECT_THAT(Results.signatures,
659 UnorderedElementsAre(
660 Sig("bar(int x, int y = 0) -> void", {"int x", "int y = 0"}),
661 Sig("bar(float x = 0, int y = 42) -> void",
662 {"float x = 0", "int y = 42"})));
663 EXPECT_EQ(0, Results.activeSignature);
664 EXPECT_EQ(0, Results.activeParameter);
665}
666
667TEST(SignatureHelpTest, ActiveArg) {
668 auto Results = signatures(R"cpp(
669 int baz(int a, int b, int c);
670 int main() { baz(baz(1,2,3), ^); }
671 )cpp");
672 EXPECT_THAT(Results.signatures,
673 ElementsAre(Sig("baz(int a, int b, int c) -> int",
674 {"int a", "int b", "int c"})));
675 EXPECT_EQ(0, Results.activeSignature);
676 EXPECT_EQ(1, Results.activeParameter);
677}
678
Sam McCall9aad25f2017-12-05 07:20:26 +0000679} // namespace
680} // namespace clangd
681} // namespace clang