blob: cb0e9a3e515a5381c299669ffb786e348f28e44d [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 McCalle746a2b2018-07-02 11:13:16 +000016#include "Quality.h"
Sam McCallb536a2a2017-12-19 12:23:48 +000017#include "SourceCode.h"
Ilya Biryukovcd5eb002018-02-12 11:37:28 +000018#include "SyncAPI.h"
Sam McCall9aad25f2017-12-05 07:20:26 +000019#include "TestFS.h"
Eric Liu6f648df2017-12-19 16:50:37 +000020#include "index/MemIndex.h"
Eric Liu5d2a8072018-07-23 10:56:37 +000021#include "clang/Sema/CodeCompleteConsumer.h"
Ilya Biryukovbe0eb8f2018-05-24 14:49:23 +000022#include "llvm/Support/Error.h"
Ilya Biryukov981a35d2018-05-28 12:11:37 +000023#include "llvm/Testing/Support/Error.h"
Sam McCallf6ae3232017-12-05 20:11:29 +000024#include "gmock/gmock.h"
Sam McCall9aad25f2017-12-05 07:20:26 +000025#include "gtest/gtest.h"
26
27namespace clang {
28namespace clangd {
Sam McCallf6ae3232017-12-05 20:11:29 +000029
Sam McCall9aad25f2017-12-05 07:20:26 +000030namespace {
31using namespace llvm;
Sam McCallf6ae3232017-12-05 20:11:29 +000032using ::testing::AllOf;
33using ::testing::Contains;
Ilya Biryukov5a5e1ca2017-12-29 14:59:22 +000034using ::testing::Each;
Sam McCallf6ae3232017-12-05 20:11:29 +000035using ::testing::ElementsAre;
Ilya Biryukov71028b82018-03-12 15:28:22 +000036using ::testing::Field;
Sam McCallc18c2802018-06-15 11:06:29 +000037using ::testing::HasSubstr;
Marc-Andre Laperle945b5a32018-06-05 14:01:40 +000038using ::testing::IsEmpty;
Sam McCallf6ae3232017-12-05 20:11:29 +000039using ::testing::Not;
Sam McCall3d139c52018-01-12 18:30:08 +000040using ::testing::UnorderedElementsAre;
Sam McCall9aad25f2017-12-05 07:20:26 +000041
42class IgnoreDiagnostics : public DiagnosticsConsumer {
Ilya Biryukov71028b82018-03-12 15:28:22 +000043 void onDiagnosticsReady(PathRef File,
Sam McCalla7bb0cc2018-03-12 23:22:35 +000044 std::vector<Diag> Diagnostics) override {}
Sam McCall9aad25f2017-12-05 07:20:26 +000045};
46
Sam McCallf6ae3232017-12-05 20:11:29 +000047// GMock helpers for matching completion items.
Sam McCalle746a2b2018-07-02 11:13:16 +000048MATCHER_P(Named, Name, "") { return arg.Name == Name; }
49MATCHER_P(Scope, S, "") { return arg.Scope == S; }
50MATCHER_P(Qualifier, Q, "") { return arg.RequiredQualifier == Q; }
Eric Liu8f3678d2018-06-15 13:34:18 +000051MATCHER_P(Labeled, Label, "") {
Sam McCalle746a2b2018-07-02 11:13:16 +000052 return arg.RequiredQualifier + arg.Name + arg.Signature == Label;
Eric Liu8f3678d2018-06-15 13:34:18 +000053}
54MATCHER_P(SigHelpLabeled, Label, "") { return arg.label == Label; }
Sam McCalle746a2b2018-07-02 11:13:16 +000055MATCHER_P(Kind, K, "") { return arg.Kind == K; }
56MATCHER_P(Doc, D, "") { return arg.Documentation == D; }
57MATCHER_P(ReturnType, D, "") { return arg.ReturnType == D; }
Eric Liu63f419a2018-05-15 15:29:32 +000058MATCHER_P(InsertInclude, IncludeHeader, "") {
Sam McCalle746a2b2018-07-02 11:13:16 +000059 return arg.Header == IncludeHeader && bool(arg.HeaderInsertion);
Eric Liu63f419a2018-05-15 15:29:32 +000060}
Sam McCalle746a2b2018-07-02 11:13:16 +000061MATCHER(InsertInclude, "") { return bool(arg.HeaderInsertion); }
62MATCHER_P(SnippetSuffix, Text, "") { return arg.SnippetSuffix == Text; }
Sam McCall2161ec72018-07-05 06:20:41 +000063MATCHER_P(Origin, OriginSet, "") { return arg.Origin == OriginSet; }
Eric Liu63f419a2018-05-15 15:29:32 +000064
Sam McCallf6ae3232017-12-05 20:11:29 +000065// Shorthand for Contains(Named(Name)).
Sam McCalle746a2b2018-07-02 11:13:16 +000066Matcher<const std::vector<CodeCompletion> &> Has(std::string Name) {
Sam McCallf6ae3232017-12-05 20:11:29 +000067 return Contains(Named(std::move(Name)));
68}
Sam McCalle746a2b2018-07-02 11:13:16 +000069Matcher<const std::vector<CodeCompletion> &> Has(std::string Name,
Sam McCall44fdcec22017-12-08 15:00:59 +000070 CompletionItemKind K) {
71 return Contains(AllOf(Named(std::move(Name)), Kind(K)));
Sam McCallf6ae3232017-12-05 20:11:29 +000072}
Sam McCalle746a2b2018-07-02 11:13:16 +000073MATCHER(IsDocumented, "") { return !arg.Documentation.empty(); }
Sam McCall9aad25f2017-12-05 07:20:26 +000074
Sam McCalla15c2d62018-01-18 09:27:56 +000075std::unique_ptr<SymbolIndex> memIndex(std::vector<Symbol> Symbols) {
76 SymbolSlab::Builder Slab;
77 for (const auto &Sym : Symbols)
78 Slab.insert(Sym);
79 return MemIndex::build(std::move(Slab).build());
80}
81
Kadir Cetinkaya2f84d912018-08-08 08:59:29 +000082CodeCompleteResult completions(ClangdServer &Server, StringRef TestCode,
83 Position point,
84 std::vector<Symbol> IndexSymbols = {},
85 clangd::CodeCompleteOptions Opts = {}) {
86 std::unique_ptr<SymbolIndex> OverrideIndex;
87 if (!IndexSymbols.empty()) {
88 assert(!Opts.Index && "both Index and IndexSymbols given!");
89 OverrideIndex = memIndex(std::move(IndexSymbols));
90 Opts.Index = OverrideIndex.get();
91 }
92
93 auto File = testPath("foo.cpp");
94 runAddDocument(Server, File, TestCode);
95 auto CompletionList = cantFail(runCodeComplete(Server, File, point, Opts));
96 return CompletionList;
97}
98
Sam McCalle746a2b2018-07-02 11:13:16 +000099CodeCompleteResult completions(ClangdServer &Server, StringRef Text,
100 std::vector<Symbol> IndexSymbols = {},
101 clangd::CodeCompleteOptions Opts = {}) {
Sam McCalla15c2d62018-01-18 09:27:56 +0000102 std::unique_ptr<SymbolIndex> OverrideIndex;
103 if (!IndexSymbols.empty()) {
104 assert(!Opts.Index && "both Index and IndexSymbols given!");
105 OverrideIndex = memIndex(std::move(IndexSymbols));
106 Opts.Index = OverrideIndex.get();
107 }
108
Sam McCallc1568062018-02-16 09:41:43 +0000109 auto File = testPath("foo.cpp");
Sam McCall328cbdb2017-12-20 16:06:05 +0000110 Annotations Test(Text);
Sam McCall7363a2f2018-03-05 17:28:54 +0000111 runAddDocument(Server, File, Test.code());
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000112 auto CompletionList =
113 cantFail(runCodeComplete(Server, File, Test.point(), Opts));
Ilya Biryukov5a5e1ca2017-12-29 14:59:22 +0000114 return CompletionList;
Sam McCall9aad25f2017-12-05 07:20:26 +0000115}
116
Eric Liu63f419a2018-05-15 15:29:32 +0000117// Builds a server and runs code completion.
118// If IndexSymbols is non-empty, an index will be built and passed to opts.
Sam McCalle746a2b2018-07-02 11:13:16 +0000119CodeCompleteResult completions(StringRef Text,
120 std::vector<Symbol> IndexSymbols = {},
121 clangd::CodeCompleteOptions Opts = {}) {
Eric Liu63f419a2018-05-15 15:29:32 +0000122 MockFSProvider FS;
123 MockCompilationDatabase CDB;
124 IgnoreDiagnostics DiagConsumer;
125 ClangdServer Server(CDB, FS, DiagConsumer, ClangdServer::optsForTest());
126 return completions(Server, Text, std::move(IndexSymbols), std::move(Opts));
127}
128
Sam McCall545a20d2018-01-19 14:34:02 +0000129std::string replace(StringRef Haystack, StringRef Needle, StringRef Repl) {
130 std::string Result;
131 raw_string_ostream OS(Result);
132 std::pair<StringRef, StringRef> Split;
133 for (Split = Haystack.split(Needle); !Split.second.empty();
134 Split = Split.first.split(Needle))
135 OS << Split.first << Repl;
136 Result += Split.first;
137 OS.flush();
138 return Result;
139}
140
Sam McCalla15c2d62018-01-18 09:27:56 +0000141// Helpers to produce fake index symbols for memIndex() or completions().
Sam McCall545a20d2018-01-19 14:34:02 +0000142// USRFormat is a regex replacement string for the unqualified part of the USR.
143Symbol sym(StringRef QName, index::SymbolKind Kind, StringRef USRFormat) {
Sam McCalla15c2d62018-01-18 09:27:56 +0000144 Symbol Sym;
Sam McCall545a20d2018-01-19 14:34:02 +0000145 std::string USR = "c:"; // We synthesize a few simple cases of USRs by hand!
Sam McCalla15c2d62018-01-18 09:27:56 +0000146 size_t Pos = QName.rfind("::");
147 if (Pos == llvm::StringRef::npos) {
148 Sym.Name = QName;
149 Sym.Scope = "";
150 } else {
151 Sym.Name = QName.substr(Pos + 2);
Sam McCall8b2faee2018-01-19 22:18:21 +0000152 Sym.Scope = QName.substr(0, Pos + 2);
153 USR += "@N@" + replace(QName.substr(0, Pos), "::", "@N@"); // ns:: -> @N@ns
Sam McCalla15c2d62018-01-18 09:27:56 +0000154 }
Sam McCall545a20d2018-01-19 14:34:02 +0000155 USR += Regex("^.*$").sub(USRFormat, Sym.Name); // e.g. func -> @F@func#
156 Sym.ID = SymbolID(USR);
Sam McCalla15c2d62018-01-18 09:27:56 +0000157 Sym.SymInfo.Kind = Kind;
Marc-Andre Laperle945b5a32018-06-05 14:01:40 +0000158 Sym.IsIndexedForCodeCompletion = true;
Sam McCall2161ec72018-07-05 06:20:41 +0000159 Sym.Origin = SymbolOrigin::Static;
Sam McCalla15c2d62018-01-18 09:27:56 +0000160 return Sym;
161}
Sam McCall545a20d2018-01-19 14:34:02 +0000162Symbol func(StringRef Name) { // Assumes the function has no args.
163 return sym(Name, index::SymbolKind::Function, "@F@\\0#"); // no args
164}
165Symbol cls(StringRef Name) {
Eric Liu9b3cba72018-05-30 09:03:39 +0000166 return sym(Name, index::SymbolKind::Class, "@S@\\0");
Sam McCall545a20d2018-01-19 14:34:02 +0000167}
168Symbol var(StringRef Name) {
169 return sym(Name, index::SymbolKind::Variable, "@\\0");
170}
Sam McCalldc8abc42018-05-03 14:53:02 +0000171Symbol ns(StringRef Name) {
172 return sym(Name, index::SymbolKind::Namespace, "@N@\\0");
173}
174Symbol withReferences(int N, Symbol S) {
175 S.References = N;
176 return S;
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
Sam McCalle746a2b2018-07-02 11:13:16 +0000192 EXPECT_TRUE(Results.HasMore);
193 EXPECT_THAT(Results.Completions, 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 McCall8b2dcc12018-06-14 13:50:30 +0000198 #define MotorCar
199 int Car;
Sam McCall9aad25f2017-12-05 07:20:26 +0000200 struct S {
201 int FooBar;
202 int FooBaz;
203 int Qux;
204 };
205 )cpp";
Sam McCall8b2dcc12018-06-14 13:50:30 +0000206
207 // Only items matching the fuzzy query are returned.
Sam McCalle746a2b2018-07-02 11:13:16 +0000208 EXPECT_THAT(completions(Body + "int main() { S().Foba^ }").Completions,
Sam McCall8b2dcc12018-06-14 13:50:30 +0000209 AllOf(Has("FooBar"), Has("FooBaz"), Not(Has("Qux"))));
Sam McCall9aad25f2017-12-05 07:20:26 +0000210
Sam McCall8b2dcc12018-06-14 13:50:30 +0000211 // Macros require prefix match.
Sam McCalle746a2b2018-07-02 11:13:16 +0000212 EXPECT_THAT(completions(Body + "int main() { C^ }").Completions,
Sam McCall8b2dcc12018-06-14 13:50:30 +0000213 AllOf(Has("Car"), Not(Has("MotorCar"))));
Sam McCall9aad25f2017-12-05 07:20:26 +0000214}
215
Sam McCallf6ae3232017-12-05 20:11:29 +0000216void TestAfterDotCompletion(clangd::CodeCompleteOptions Opts) {
Sam McCall44fdcec22017-12-08 15:00:59 +0000217 auto Results = completions(
218 R"cpp(
219 #define MACRO X
Sam McCall9aad25f2017-12-05 07:20:26 +0000220
Sam McCall44fdcec22017-12-08 15:00:59 +0000221 int global_var;
Sam McCall9aad25f2017-12-05 07:20:26 +0000222
Sam McCall44fdcec22017-12-08 15:00:59 +0000223 int global_func();
Sam McCall9aad25f2017-12-05 07:20:26 +0000224
Sam McCall44fdcec22017-12-08 15:00:59 +0000225 struct GlobalClass {};
Sam McCall9aad25f2017-12-05 07:20:26 +0000226
Sam McCall44fdcec22017-12-08 15:00:59 +0000227 struct ClassWithMembers {
228 /// Doc for method.
229 int method();
Sam McCall9aad25f2017-12-05 07:20:26 +0000230
Sam McCall44fdcec22017-12-08 15:00:59 +0000231 int field;
232 private:
233 int private_field;
234 };
Sam McCall9aad25f2017-12-05 07:20:26 +0000235
Sam McCall44fdcec22017-12-08 15:00:59 +0000236 int test() {
237 struct LocalClass {};
Sam McCall9aad25f2017-12-05 07:20:26 +0000238
Sam McCall44fdcec22017-12-08 15:00:59 +0000239 /// Doc for local_var.
240 int local_var;
Sam McCall9aad25f2017-12-05 07:20:26 +0000241
Sam McCall44fdcec22017-12-08 15:00:59 +0000242 ClassWithMembers().^
243 }
244 )cpp",
Sam McCall545a20d2018-01-19 14:34:02 +0000245 {cls("IndexClass"), var("index_var"), func("index_func")}, Opts);
Sam McCall9aad25f2017-12-05 07:20:26 +0000246
Sam McCallf6ae3232017-12-05 20:11:29 +0000247 // Class members. The only items that must be present in after-dot
248 // completion.
Sam McCalle746a2b2018-07-02 11:13:16 +0000249 EXPECT_THAT(Results.Completions,
250 AllOf(Has("method"), Has("field"), Not(Has("ClassWithMembers")),
Sam McCall4caa8512018-06-07 12:49:17 +0000251 Not(Has("operator=")), Not(Has("~ClassWithMembers"))));
Sam McCalle746a2b2018-07-02 11:13:16 +0000252 EXPECT_IFF(Opts.IncludeIneligibleResults, Results.Completions,
Sam McCall44fdcec22017-12-08 15:00:59 +0000253 Has("private_field"));
Sam McCallf6ae3232017-12-05 20:11:29 +0000254 // Global items.
Sam McCall545a20d2018-01-19 14:34:02 +0000255 EXPECT_THAT(
Sam McCalle746a2b2018-07-02 11:13:16 +0000256 Results.Completions,
Sam McCall545a20d2018-01-19 14:34:02 +0000257 Not(AnyOf(Has("global_var"), Has("index_var"), Has("global_func"),
258 Has("global_func()"), Has("index_func"), Has("GlobalClass"),
259 Has("IndexClass"), Has("MACRO"), Has("LocalClass"))));
Sam McCallf6ae3232017-12-05 20:11:29 +0000260 // There should be no code patterns (aka snippets) in after-dot
261 // completion. At least there aren't any we're aware of.
Sam McCalle746a2b2018-07-02 11:13:16 +0000262 EXPECT_THAT(Results.Completions,
263 Not(Contains(Kind(CompletionItemKind::Snippet))));
Sam McCallf6ae3232017-12-05 20:11:29 +0000264 // Check documentation.
Sam McCalle746a2b2018-07-02 11:13:16 +0000265 EXPECT_IFF(Opts.IncludeComments, Results.Completions,
266 Contains(IsDocumented()));
Sam McCallf6ae3232017-12-05 20:11:29 +0000267}
Sam McCall9aad25f2017-12-05 07:20:26 +0000268
Sam McCallf6ae3232017-12-05 20:11:29 +0000269void TestGlobalScopeCompletion(clangd::CodeCompleteOptions Opts) {
Sam McCall44fdcec22017-12-08 15:00:59 +0000270 auto Results = completions(
271 R"cpp(
272 #define MACRO X
Sam McCall9aad25f2017-12-05 07:20:26 +0000273
Sam McCall44fdcec22017-12-08 15:00:59 +0000274 int global_var;
275 int global_func();
Sam McCall9aad25f2017-12-05 07:20:26 +0000276
Sam McCall44fdcec22017-12-08 15:00:59 +0000277 struct GlobalClass {};
Sam McCall9aad25f2017-12-05 07:20:26 +0000278
Sam McCall44fdcec22017-12-08 15:00:59 +0000279 struct ClassWithMembers {
280 /// Doc for method.
281 int method();
282 };
Sam McCall9aad25f2017-12-05 07:20:26 +0000283
Sam McCall44fdcec22017-12-08 15:00:59 +0000284 int test() {
285 struct LocalClass {};
Sam McCall9aad25f2017-12-05 07:20:26 +0000286
Sam McCall44fdcec22017-12-08 15:00:59 +0000287 /// Doc for local_var.
288 int local_var;
Sam McCall9aad25f2017-12-05 07:20:26 +0000289
Sam McCall44fdcec22017-12-08 15:00:59 +0000290 ^
291 }
292 )cpp",
Sam McCall545a20d2018-01-19 14:34:02 +0000293 {cls("IndexClass"), var("index_var"), func("index_func")}, Opts);
Sam McCallf6ae3232017-12-05 20:11:29 +0000294
295 // Class members. Should never be present in global completions.
Sam McCalle746a2b2018-07-02 11:13:16 +0000296 EXPECT_THAT(Results.Completions,
Sam McCallf6ae3232017-12-05 20:11:29 +0000297 Not(AnyOf(Has("method"), Has("method()"), Has("field"))));
298 // Global items.
Sam McCalle746a2b2018-07-02 11:13:16 +0000299 EXPECT_THAT(Results.Completions,
300 AllOf(Has("global_var"), Has("index_var"), Has("global_func"),
Sam McCall545a20d2018-01-19 14:34:02 +0000301 Has("index_func" /* our fake symbol doesn't include () */),
302 Has("GlobalClass"), Has("IndexClass")));
Sam McCallf6ae3232017-12-05 20:11:29 +0000303 // A macro.
Sam McCalle746a2b2018-07-02 11:13:16 +0000304 EXPECT_IFF(Opts.IncludeMacros, Results.Completions, Has("MACRO"));
Sam McCallf6ae3232017-12-05 20:11:29 +0000305 // Local items. Must be present always.
Sam McCalle746a2b2018-07-02 11:13:16 +0000306 EXPECT_THAT(Results.Completions,
Ilya Biryukov9b5ffc22017-12-12 12:56:46 +0000307 AllOf(Has("local_var"), Has("LocalClass"),
308 Contains(Kind(CompletionItemKind::Snippet))));
Sam McCallf6ae3232017-12-05 20:11:29 +0000309 // Check documentation.
Sam McCalle746a2b2018-07-02 11:13:16 +0000310 EXPECT_IFF(Opts.IncludeComments, Results.Completions,
311 Contains(IsDocumented()));
Sam McCallf6ae3232017-12-05 20:11:29 +0000312}
313
314TEST(CompletionTest, CompletionOptions) {
Sam McCall2c3849a2018-01-16 12:21:24 +0000315 auto Test = [&](const clangd::CodeCompleteOptions &Opts) {
316 TestAfterDotCompletion(Opts);
317 TestGlobalScopeCompletion(Opts);
318 };
319 // We used to test every combination of options, but that got too slow (2^N).
320 auto Flags = {
Ilya Biryukov71028b82018-03-12 15:28:22 +0000321 &clangd::CodeCompleteOptions::IncludeMacros,
Ilya Biryukov43714502018-05-16 12:32:44 +0000322 &clangd::CodeCompleteOptions::IncludeComments,
Ilya Biryukov71028b82018-03-12 15:28:22 +0000323 &clangd::CodeCompleteOptions::IncludeCodePatterns,
324 &clangd::CodeCompleteOptions::IncludeIneligibleResults,
Sam McCall2c3849a2018-01-16 12:21:24 +0000325 };
326 // Test default options.
327 Test({});
328 // Test with one flag flipped.
329 for (auto &F : Flags) {
330 clangd::CodeCompleteOptions O;
331 O.*F ^= true;
332 Test(O);
Sam McCall9aad25f2017-12-05 07:20:26 +0000333 }
334}
335
Sam McCall44fdcec22017-12-08 15:00:59 +0000336TEST(CompletionTest, Priorities) {
337 auto Internal = completions(R"cpp(
338 class Foo {
339 public: void pub();
340 protected: void prot();
341 private: void priv();
342 };
343 void Foo::pub() { this->^ }
344 )cpp");
Sam McCalle746a2b2018-07-02 11:13:16 +0000345 EXPECT_THAT(Internal.Completions,
Sam McCall44fdcec22017-12-08 15:00:59 +0000346 HasSubsequence(Named("priv"), Named("prot"), Named("pub")));
347
348 auto External = completions(R"cpp(
349 class Foo {
350 public: void pub();
351 protected: void prot();
352 private: void priv();
353 };
354 void test() {
355 Foo F;
356 F.^
357 }
358 )cpp");
Sam McCalle746a2b2018-07-02 11:13:16 +0000359 EXPECT_THAT(External.Completions,
Sam McCall44fdcec22017-12-08 15:00:59 +0000360 AllOf(Has("pub"), Not(Has("prot")), Not(Has("priv"))));
361}
362
363TEST(CompletionTest, Qualifiers) {
364 auto Results = completions(R"cpp(
365 class Foo {
366 public: int foo() const;
367 int bar() const;
368 };
369 class Bar : public Foo {
370 int foo() const;
371 };
372 void test() { Bar().^ }
373 )cpp");
Sam McCalle746a2b2018-07-02 11:13:16 +0000374 EXPECT_THAT(Results.Completions,
375 HasSubsequence(AllOf(Qualifier(""), Named("bar")),
376 AllOf(Qualifier("Foo::"), Named("foo"))));
377 EXPECT_THAT(Results.Completions,
378 Not(Contains(AllOf(Qualifier(""), Named("foo"))))); // private
Sam McCall44fdcec22017-12-08 15:00:59 +0000379}
380
Sam McCall4caa8512018-06-07 12:49:17 +0000381TEST(CompletionTest, InjectedTypename) {
382 // These are suppressed when accessed as a member...
Sam McCalle746a2b2018-07-02 11:13:16 +0000383 EXPECT_THAT(completions("struct X{}; void foo(){ X().^ }").Completions,
Sam McCall4caa8512018-06-07 12:49:17 +0000384 Not(Has("X")));
Sam McCalle746a2b2018-07-02 11:13:16 +0000385 EXPECT_THAT(completions("struct X{ void foo(){ this->^ } };").Completions,
Sam McCall4caa8512018-06-07 12:49:17 +0000386 Not(Has("X")));
387 // ...but accessible in other, more useful cases.
Sam McCalle746a2b2018-07-02 11:13:16 +0000388 EXPECT_THAT(completions("struct X{ void foo(){ ^ } };").Completions,
389 Has("X"));
390 EXPECT_THAT(
391 completions("struct Y{}; struct X:Y{ void foo(){ ^ } };").Completions,
392 Has("Y"));
Sam McCall4caa8512018-06-07 12:49:17 +0000393 EXPECT_THAT(
394 completions(
395 "template<class> struct Y{}; struct X:Y<int>{ void foo(){ ^ } };")
Sam McCalle746a2b2018-07-02 11:13:16 +0000396 .Completions,
Sam McCall4caa8512018-06-07 12:49:17 +0000397 Has("Y"));
398 // This case is marginal (`using X::X` is useful), we allow it for now.
Sam McCalle746a2b2018-07-02 11:13:16 +0000399 EXPECT_THAT(completions("struct X{}; void foo(){ X::^ }").Completions,
400 Has("X"));
Sam McCall4caa8512018-06-07 12:49:17 +0000401}
402
Sam McCall44fdcec22017-12-08 15:00:59 +0000403TEST(CompletionTest, Snippets) {
404 clangd::CodeCompleteOptions Opts;
Sam McCall44fdcec22017-12-08 15:00:59 +0000405 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 McCalle746a2b2018-07-02 11:13:16 +0000417 EXPECT_THAT(
418 Results.Completions,
419 HasSubsequence(Named("a"),
420 SnippetSuffix("(${1:int i}, ${2:const float f})")));
Sam McCall44fdcec22017-12-08 15:00:59 +0000421}
422
423TEST(CompletionTest, Kinds) {
Sam McCall545a20d2018-01-19 14:34:02 +0000424 auto Results = completions(
425 R"cpp(
426 #define MACRO X
427 int variable;
428 struct Struct {};
429 int function();
430 int X = ^
431 )cpp",
432 {func("indexFunction"), var("indexVariable"), cls("indexClass")});
Sam McCalle746a2b2018-07-02 11:13:16 +0000433 EXPECT_THAT(Results.Completions,
Sam McCall545a20d2018-01-19 14:34:02 +0000434 AllOf(Has("function", CompletionItemKind::Function),
435 Has("variable", CompletionItemKind::Variable),
436 Has("int", CompletionItemKind::Keyword),
437 Has("Struct", CompletionItemKind::Class),
438 Has("MACRO", CompletionItemKind::Text),
439 Has("indexFunction", CompletionItemKind::Function),
440 Has("indexVariable", CompletionItemKind::Variable),
441 Has("indexClass", CompletionItemKind::Class)));
Sam McCall44fdcec22017-12-08 15:00:59 +0000442
Sam McCall44fdcec22017-12-08 15:00:59 +0000443 Results = completions("nam^");
Sam McCalle746a2b2018-07-02 11:13:16 +0000444 EXPECT_THAT(Results.Completions,
445 Has("namespace", CompletionItemKind::Snippet));
Sam McCall44fdcec22017-12-08 15:00:59 +0000446}
447
Sam McCall84652cc2018-01-12 16:16:09 +0000448TEST(CompletionTest, NoDuplicates) {
Sam McCall545a20d2018-01-19 14:34:02 +0000449 auto Results = completions(
450 R"cpp(
451 class Adapter {
Sam McCall545a20d2018-01-19 14:34:02 +0000452 };
Sam McCall84652cc2018-01-12 16:16:09 +0000453
Eric Liu9b3cba72018-05-30 09:03:39 +0000454 void f() {
Sam McCall545a20d2018-01-19 14:34:02 +0000455 Adapter^
456 }
457 )cpp",
458 {cls("Adapter")});
Sam McCall84652cc2018-01-12 16:16:09 +0000459
460 // Make sure there are no duplicate entries of 'Adapter'.
Sam McCalle746a2b2018-07-02 11:13:16 +0000461 EXPECT_THAT(Results.Completions, ElementsAre(Named("Adapter")));
Sam McCall84652cc2018-01-12 16:16:09 +0000462}
463
Sam McCall545a20d2018-01-19 14:34:02 +0000464TEST(CompletionTest, ScopedNoIndex) {
465 auto Results = completions(
466 R"cpp(
Sam McCall8b2dcc12018-06-14 13:50:30 +0000467 namespace fake { int BigBang, Babble, Box; };
468 int main() { fake::ba^ }
Sam McCall545a20d2018-01-19 14:34:02 +0000469 ")cpp");
Sam McCall8b2dcc12018-06-14 13:50:30 +0000470 // Babble is a better match than BigBang. Box doesn't match at all.
Sam McCalle746a2b2018-07-02 11:13:16 +0000471 EXPECT_THAT(Results.Completions,
472 ElementsAre(Named("Babble"), Named("BigBang")));
Sam McCall84652cc2018-01-12 16:16:09 +0000473}
474
Sam McCall545a20d2018-01-19 14:34:02 +0000475TEST(CompletionTest, Scoped) {
Sam McCalla15c2d62018-01-18 09:27:56 +0000476 auto Results = completions(
477 R"cpp(
Sam McCall8b2dcc12018-06-14 13:50:30 +0000478 namespace fake { int Babble, Box; };
479 int main() { fake::ba^ }
Sam McCall545a20d2018-01-19 14:34:02 +0000480 ")cpp",
481 {var("fake::BigBang")});
Sam McCalle746a2b2018-07-02 11:13:16 +0000482 EXPECT_THAT(Results.Completions,
483 ElementsAre(Named("Babble"), Named("BigBang")));
Sam McCalla15c2d62018-01-18 09:27:56 +0000484}
485
Sam McCall545a20d2018-01-19 14:34:02 +0000486TEST(CompletionTest, ScopedWithFilter) {
Sam McCalla15c2d62018-01-18 09:27:56 +0000487 auto Results = completions(
488 R"cpp(
489 void f() { ns::x^ }
490 )cpp",
491 {cls("ns::XYZ"), func("ns::foo")});
Sam McCalle746a2b2018-07-02 11:13:16 +0000492 EXPECT_THAT(Results.Completions, UnorderedElementsAre(Named("XYZ")));
Sam McCalla15c2d62018-01-18 09:27:56 +0000493}
494
Sam McCalldc8abc42018-05-03 14:53:02 +0000495TEST(CompletionTest, ReferencesAffectRanking) {
Eric Liu84bd5db2018-07-25 11:26:35 +0000496 auto Results = completions("int main() { abs^ }", {ns("absl"), func("absb")});
497 EXPECT_THAT(Results.Completions, HasSubsequence(Named("absb"), Named("absl")));
Sam McCalldc8abc42018-05-03 14:53:02 +0000498 Results = completions("int main() { abs^ }",
Eric Liu84bd5db2018-07-25 11:26:35 +0000499 {withReferences(10000, ns("absl")), func("absb")});
500 EXPECT_THAT(Results.Completions,
501 HasSubsequence(Named("absl"), Named("absb")));
Sam McCalldc8abc42018-05-03 14:53:02 +0000502}
503
Sam McCall545a20d2018-01-19 14:34:02 +0000504TEST(CompletionTest, GlobalQualified) {
Sam McCalla15c2d62018-01-18 09:27:56 +0000505 auto Results = completions(
506 R"cpp(
507 void f() { ::^ }
508 )cpp",
509 {cls("XYZ")});
Sam McCalle746a2b2018-07-02 11:13:16 +0000510 EXPECT_THAT(Results.Completions,
511 AllOf(Has("XYZ", CompletionItemKind::Class),
512 Has("f", CompletionItemKind::Function)));
Sam McCalla15c2d62018-01-18 09:27:56 +0000513}
514
Sam McCall545a20d2018-01-19 14:34:02 +0000515TEST(CompletionTest, FullyQualified) {
Sam McCalla15c2d62018-01-18 09:27:56 +0000516 auto Results = completions(
517 R"cpp(
Sam McCall545a20d2018-01-19 14:34:02 +0000518 namespace ns { void bar(); }
Sam McCalla15c2d62018-01-18 09:27:56 +0000519 void f() { ::ns::^ }
520 )cpp",
521 {cls("ns::XYZ")});
Sam McCalle746a2b2018-07-02 11:13:16 +0000522 EXPECT_THAT(Results.Completions,
523 AllOf(Has("XYZ", CompletionItemKind::Class),
524 Has("bar", CompletionItemKind::Function)));
Sam McCall545a20d2018-01-19 14:34:02 +0000525}
526
527TEST(CompletionTest, SemaIndexMerge) {
528 auto Results = completions(
529 R"cpp(
530 namespace ns { int local; void both(); }
531 void f() { ::ns::^ }
532 )cpp",
533 {func("ns::both"), cls("ns::Index")});
534 // We get results from both index and sema, with no duplicates.
Sam McCall2161ec72018-07-05 06:20:41 +0000535 EXPECT_THAT(Results.Completions,
536 UnorderedElementsAre(
537 AllOf(Named("local"), Origin(SymbolOrigin::AST)),
538 AllOf(Named("Index"), Origin(SymbolOrigin::Static)),
539 AllOf(Named("both"),
540 Origin(SymbolOrigin::AST | SymbolOrigin::Static))));
Sam McCalla15c2d62018-01-18 09:27:56 +0000541}
542
Haojian Wu48b48652018-01-25 09:20:09 +0000543TEST(CompletionTest, SemaIndexMergeWithLimit) {
544 clangd::CodeCompleteOptions Opts;
545 Opts.Limit = 1;
546 auto Results = completions(
547 R"cpp(
548 namespace ns { int local; void both(); }
549 void f() { ::ns::^ }
550 )cpp",
551 {func("ns::both"), cls("ns::Index")}, Opts);
Sam McCalle746a2b2018-07-02 11:13:16 +0000552 EXPECT_EQ(Results.Completions.size(), Opts.Limit);
553 EXPECT_TRUE(Results.HasMore);
Haojian Wu48b48652018-01-25 09:20:09 +0000554}
555
Eric Liu63f419a2018-05-15 15:29:32 +0000556TEST(CompletionTest, IncludeInsertionPreprocessorIntegrationTests) {
557 MockFSProvider FS;
558 MockCompilationDatabase CDB;
559 std::string Subdir = testPath("sub");
560 std::string SearchDirArg = (llvm::Twine("-I") + Subdir).str();
561 CDB.ExtraClangFlags = {SearchDirArg.c_str()};
562 std::string BarHeader = testPath("sub/bar.h");
563 FS.Files[BarHeader] = "";
564
565 IgnoreDiagnostics DiagConsumer;
566 ClangdServer Server(CDB, FS, DiagConsumer, ClangdServer::optsForTest());
567 Symbol::Details Scratch;
568 auto BarURI = URI::createFile(BarHeader).toString();
569 Symbol Sym = cls("ns::X");
570 Sym.CanonicalDeclaration.FileURI = BarURI;
571 Scratch.IncludeHeader = BarURI;
572 Sym.Detail = &Scratch;
573 // Shoten include path based on search dirctory and insert.
574 auto Results = completions(Server,
575 R"cpp(
576 int main() { ns::^ }
577 )cpp",
578 {Sym});
Sam McCalle746a2b2018-07-02 11:13:16 +0000579 EXPECT_THAT(Results.Completions,
580 ElementsAre(AllOf(Named("X"), InsertInclude("\"bar.h\""))));
Eric Liu63f419a2018-05-15 15:29:32 +0000581 // Duplicate based on inclusions in preamble.
582 Results = completions(Server,
583 R"cpp(
584 #include "sub/bar.h" // not shortest, so should only match resolved.
585 int main() { ns::^ }
586 )cpp",
587 {Sym});
Sam McCalle746a2b2018-07-02 11:13:16 +0000588 EXPECT_THAT(Results.Completions, ElementsAre(AllOf(Named("X"), Labeled("X"),
589 Not(InsertInclude()))));
Eric Liu63f419a2018-05-15 15:29:32 +0000590}
591
Eric Liu9b3cba72018-05-30 09:03:39 +0000592TEST(CompletionTest, NoIncludeInsertionWhenDeclFoundInFile) {
593 MockFSProvider FS;
594 MockCompilationDatabase CDB;
595
596 IgnoreDiagnostics DiagConsumer;
597 ClangdServer Server(CDB, FS, DiagConsumer, ClangdServer::optsForTest());
598 Symbol::Details Scratch;
599 Symbol SymX = cls("ns::X");
600 Symbol SymY = cls("ns::Y");
601 std::string BarHeader = testPath("bar.h");
602 auto BarURI = URI::createFile(BarHeader).toString();
603 SymX.CanonicalDeclaration.FileURI = BarURI;
604 SymY.CanonicalDeclaration.FileURI = BarURI;
605 Scratch.IncludeHeader = "<bar>";
606 SymX.Detail = &Scratch;
607 SymY.Detail = &Scratch;
608 // Shoten include path based on search dirctory and insert.
609 auto Results = completions(Server,
610 R"cpp(
611 namespace ns {
612 class X;
613 class Y {}
614 }
615 int main() { ns::^ }
616 )cpp",
617 {SymX, SymY});
Sam McCalle746a2b2018-07-02 11:13:16 +0000618 EXPECT_THAT(Results.Completions,
619 ElementsAre(AllOf(Named("X"), Not(InsertInclude())),
620 AllOf(Named("Y"), Not(InsertInclude()))));
Eric Liu9b3cba72018-05-30 09:03:39 +0000621}
622
Sam McCalla15c2d62018-01-18 09:27:56 +0000623TEST(CompletionTest, IndexSuppressesPreambleCompletions) {
624 MockFSProvider FS;
625 MockCompilationDatabase CDB;
626 IgnoreDiagnostics DiagConsumer;
Sam McCall7363a2f2018-03-05 17:28:54 +0000627 ClangdServer Server(CDB, FS, DiagConsumer, ClangdServer::optsForTest());
Sam McCalla15c2d62018-01-18 09:27:56 +0000628
Sam McCallc1568062018-02-16 09:41:43 +0000629 FS.Files[testPath("bar.h")] =
Sam McCalld5ea3e32018-01-24 17:53:32 +0000630 R"cpp(namespace ns { struct preamble { int member; }; })cpp";
Sam McCallc1568062018-02-16 09:41:43 +0000631 auto File = testPath("foo.cpp");
Sam McCalla15c2d62018-01-18 09:27:56 +0000632 Annotations Test(R"cpp(
633 #include "bar.h"
634 namespace ns { int local; }
Sam McCalld5ea3e32018-01-24 17:53:32 +0000635 void f() { ns::^; }
636 void f() { ns::preamble().$2^; }
Sam McCalla15c2d62018-01-18 09:27:56 +0000637 )cpp");
Sam McCall7363a2f2018-03-05 17:28:54 +0000638 runAddDocument(Server, File, Test.code());
Sam McCalla15c2d62018-01-18 09:27:56 +0000639 clangd::CodeCompleteOptions Opts = {};
640
Sam McCalla15c2d62018-01-18 09:27:56 +0000641 auto I = memIndex({var("ns::index")});
642 Opts.Index = I.get();
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000643 auto WithIndex = cantFail(runCodeComplete(Server, File, Test.point(), Opts));
Sam McCalle746a2b2018-07-02 11:13:16 +0000644 EXPECT_THAT(WithIndex.Completions,
Sam McCalla15c2d62018-01-18 09:27:56 +0000645 UnorderedElementsAre(Named("local"), Named("index")));
Sam McCalld5ea3e32018-01-24 17:53:32 +0000646 auto ClassFromPreamble =
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000647 cantFail(runCodeComplete(Server, File, Test.point("2"), Opts));
Sam McCalle746a2b2018-07-02 11:13:16 +0000648 EXPECT_THAT(ClassFromPreamble.Completions, Contains(Named("member")));
Sam McCall0bb24cd2018-02-13 08:59:23 +0000649
650 Opts.Index = nullptr;
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000651 auto WithoutIndex =
652 cantFail(runCodeComplete(Server, File, Test.point(), Opts));
Sam McCalle746a2b2018-07-02 11:13:16 +0000653 EXPECT_THAT(WithoutIndex.Completions,
Sam McCall0bb24cd2018-02-13 08:59:23 +0000654 UnorderedElementsAre(Named("local"), Named("preamble")));
Sam McCalla15c2d62018-01-18 09:27:56 +0000655}
656
657TEST(CompletionTest, DynamicIndexMultiFile) {
658 MockFSProvider FS;
659 MockCompilationDatabase CDB;
660 IgnoreDiagnostics DiagConsumer;
Sam McCall7363a2f2018-03-05 17:28:54 +0000661 auto Opts = ClangdServer::optsForTest();
662 Opts.BuildDynamicSymbolIndex = true;
663 ClangdServer Server(CDB, FS, DiagConsumer, Opts);
Sam McCalla15c2d62018-01-18 09:27:56 +0000664
Eric Liu709bde82018-02-19 18:48:44 +0000665 FS.Files[testPath("foo.h")] = R"cpp(
Sam McCalla15c2d62018-01-18 09:27:56 +0000666 namespace ns { class XYZ {}; void foo(int x) {} }
Eric Liu709bde82018-02-19 18:48:44 +0000667 )cpp";
Sam McCall7363a2f2018-03-05 17:28:54 +0000668 runAddDocument(Server, testPath("foo.cpp"), R"cpp(
Eric Liu709bde82018-02-19 18:48:44 +0000669 #include "foo.h"
Sam McCall0bb24cd2018-02-13 08:59:23 +0000670 )cpp");
Sam McCalla15c2d62018-01-18 09:27:56 +0000671
Sam McCallc1568062018-02-16 09:41:43 +0000672 auto File = testPath("bar.cpp");
Sam McCalla15c2d62018-01-18 09:27:56 +0000673 Annotations Test(R"cpp(
674 namespace ns {
675 class XXX {};
676 /// Doooc
677 void fooooo() {}
678 }
679 void f() { ns::^ }
680 )cpp");
Sam McCall7363a2f2018-03-05 17:28:54 +0000681 runAddDocument(Server, File, Test.code());
Sam McCalla15c2d62018-01-18 09:27:56 +0000682
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000683 auto Results = cantFail(runCodeComplete(Server, File, Test.point(), {}));
Sam McCalla15c2d62018-01-18 09:27:56 +0000684 // "XYZ" and "foo" are not included in the file being completed but are still
685 // visible through the index.
Sam McCalle746a2b2018-07-02 11:13:16 +0000686 EXPECT_THAT(Results.Completions, Has("XYZ", CompletionItemKind::Class));
687 EXPECT_THAT(Results.Completions, Has("foo", CompletionItemKind::Function));
688 EXPECT_THAT(Results.Completions, Has("XXX", CompletionItemKind::Class));
689 EXPECT_THAT(Results.Completions,
690 Contains((Named("fooooo"), Kind(CompletionItemKind::Function),
691 Doc("Doooc"), ReturnType("void"))));
Sam McCalla15c2d62018-01-18 09:27:56 +0000692}
693
Ilya Biryukovc22d3442018-05-16 12:32:49 +0000694TEST(CompletionTest, Documentation) {
695 auto Results = completions(
696 R"cpp(
697 // Non-doxygen comment.
698 int foo();
699 /// Doxygen comment.
700 /// \param int a
701 int bar(int a);
702 /* Multi-line
703 block comment
704 */
705 int baz();
706
707 int x = ^
708 )cpp");
Sam McCalle746a2b2018-07-02 11:13:16 +0000709 EXPECT_THAT(Results.Completions,
Ilya Biryukovc22d3442018-05-16 12:32:49 +0000710 Contains(AllOf(Named("foo"), Doc("Non-doxygen comment."))));
711 EXPECT_THAT(
Sam McCalle746a2b2018-07-02 11:13:16 +0000712 Results.Completions,
Ilya Biryukovc22d3442018-05-16 12:32:49 +0000713 Contains(AllOf(Named("bar"), Doc("Doxygen comment.\n\\param int a"))));
Sam McCalle746a2b2018-07-02 11:13:16 +0000714 EXPECT_THAT(Results.Completions,
Ilya Biryukovc22d3442018-05-16 12:32:49 +0000715 Contains(AllOf(Named("baz"), Doc("Multi-line\nblock comment"))));
716}
717
Marc-Andre Laperle945b5a32018-06-05 14:01:40 +0000718TEST(CompletionTest, GlobalCompletionFiltering) {
719
720 Symbol Class = cls("XYZ");
721 Class.IsIndexedForCodeCompletion = false;
722 Symbol Func = func("XYZ::foooo");
723 Func.IsIndexedForCodeCompletion = false;
724
725 auto Results = completions(R"(// void f() {
726 XYZ::foooo^
727 })",
728 {Class, Func});
Sam McCalle746a2b2018-07-02 11:13:16 +0000729 EXPECT_THAT(Results.Completions, IsEmpty());
Marc-Andre Laperle945b5a32018-06-05 14:01:40 +0000730}
731
Haojian Wu58d208d2018-01-25 09:44:06 +0000732TEST(CodeCompleteTest, DisableTypoCorrection) {
733 auto Results = completions(R"cpp(
734 namespace clang { int v; }
735 void f() { clangd::^
736 )cpp");
Sam McCalle746a2b2018-07-02 11:13:16 +0000737 EXPECT_TRUE(Results.Completions.empty());
Haojian Wu58d208d2018-01-25 09:44:06 +0000738}
739
Ilya Biryukov53d6d932018-03-06 16:45:21 +0000740TEST(CodeCompleteTest, NoColonColonAtTheEnd) {
741 auto Results = completions(R"cpp(
742 namespace clang { }
743 void f() {
744 clan^
745 }
746 )cpp");
747
Sam McCalle746a2b2018-07-02 11:13:16 +0000748 EXPECT_THAT(Results.Completions, Contains(Labeled("clang")));
749 EXPECT_THAT(Results.Completions, Not(Contains(Labeled("clang::"))));
Ilya Biryukov53d6d932018-03-06 16:45:21 +0000750}
751
Ilya Biryukov94da7bd2018-03-16 15:23:44 +0000752TEST(CompletionTest, BacktrackCrashes) {
753 // Sema calls code completion callbacks twice in these cases.
754 auto Results = completions(R"cpp(
755 namespace ns {
756 struct FooBarBaz {};
757 } // namespace ns
758
759 int foo(ns::FooBar^
760 )cpp");
761
Sam McCalle746a2b2018-07-02 11:13:16 +0000762 EXPECT_THAT(Results.Completions, ElementsAre(Labeled("FooBarBaz")));
Ilya Biryukov94da7bd2018-03-16 15:23:44 +0000763
764 // Check we don't crash in that case too.
765 completions(R"cpp(
766 struct FooBarBaz {};
767 void test() {
768 if (FooBarBaz * x^) {}
769 }
770)cpp");
771}
772
Eric Liu42abe412018-05-24 11:20:19 +0000773TEST(CompletionTest, CompleteInMacroWithStringification) {
774 auto Results = completions(R"cpp(
775void f(const char *, int x);
776#define F(x) f(#x, x)
777
778namespace ns {
779int X;
780int Y;
781} // namespace ns
782
783int f(int input_num) {
784 F(ns::^)
785}
786)cpp");
787
Sam McCalle746a2b2018-07-02 11:13:16 +0000788 EXPECT_THAT(Results.Completions,
Eric Liu42abe412018-05-24 11:20:19 +0000789 UnorderedElementsAre(Named("X"), Named("Y")));
790}
791
792TEST(CompletionTest, CompleteInMacroAndNamespaceWithStringification) {
793 auto Results = completions(R"cpp(
794void f(const char *, int x);
795#define F(x) f(#x, x)
796
797namespace ns {
798int X;
799
800int f(int input_num) {
801 F(^)
802}
803} // namespace ns
804)cpp");
805
Sam McCalle746a2b2018-07-02 11:13:16 +0000806 EXPECT_THAT(Results.Completions, Contains(Named("X")));
Eric Liu42abe412018-05-24 11:20:19 +0000807}
808
Eric Liu485074f2018-07-11 13:15:31 +0000809TEST(CompletionTest, IgnoreCompleteInExcludedPPBranchWithRecoveryContext) {
Ilya Biryukov94da7bd2018-03-16 15:23:44 +0000810 auto Results = completions(R"cpp(
811 int bar(int param_in_bar) {
812 }
813
814 int foo(int param_in_foo) {
815#if 0
Eric Liu485074f2018-07-11 13:15:31 +0000816 // In recorvery mode, "param_in_foo" will also be suggested among many other
817 // unrelated symbols; however, this is really a special case where this works.
818 // If the #if block is outside of the function, "param_in_foo" is still
819 // suggested, but "bar" and "foo" are missing. So the recovery mode doesn't
820 // really provide useful results in excluded branches.
Ilya Biryukov94da7bd2018-03-16 15:23:44 +0000821 par^
822#endif
823 }
824)cpp");
825
Eric Liu485074f2018-07-11 13:15:31 +0000826 EXPECT_TRUE(Results.Completions.empty());
Ilya Biryukov94da7bd2018-03-16 15:23:44 +0000827}
Ilya Biryukov43c292c2018-08-30 13:14:31 +0000828SignatureHelp signatures(StringRef Text, Position Point,
Ilya Biryukov8a0f76b2018-08-17 09:32:30 +0000829 std::vector<Symbol> IndexSymbols = {}) {
830 std::unique_ptr<SymbolIndex> Index;
831 if (!IndexSymbols.empty())
832 Index = memIndex(IndexSymbols);
833
Sam McCall800d4372017-12-19 10:29:27 +0000834 MockFSProvider FS;
835 MockCompilationDatabase CDB;
836 IgnoreDiagnostics DiagConsumer;
Ilya Biryukov8a0f76b2018-08-17 09:32:30 +0000837 ClangdServer::Options Opts = ClangdServer::optsForTest();
838 Opts.StaticIndex = Index.get();
839
840 ClangdServer Server(CDB, FS, DiagConsumer, Opts);
Sam McCallc1568062018-02-16 09:41:43 +0000841 auto File = testPath("foo.cpp");
Ilya Biryukov43c292c2018-08-30 13:14:31 +0000842 runAddDocument(Server, File, Text);
843 return cantFail(runSignatureHelp(Server, File, Point));
844}
845
846SignatureHelp signatures(StringRef Text,
847 std::vector<Symbol> IndexSymbols = {}) {
Sam McCall328cbdb2017-12-20 16:06:05 +0000848 Annotations Test(Text);
Ilya Biryukov43c292c2018-08-30 13:14:31 +0000849 return signatures(Test.code(), Test.point(), std::move(IndexSymbols));
Sam McCall800d4372017-12-19 10:29:27 +0000850}
851
852MATCHER_P(ParamsAre, P, "") {
853 if (P.size() != arg.parameters.size())
854 return false;
855 for (unsigned I = 0; I < P.size(); ++I)
856 if (P[I] != arg.parameters[I].label)
857 return false;
858 return true;
859}
Ilya Biryukov8a0f76b2018-08-17 09:32:30 +0000860MATCHER_P(SigDoc, Doc, "") { return arg.documentation == Doc; }
Sam McCall800d4372017-12-19 10:29:27 +0000861
862Matcher<SignatureInformation> Sig(std::string Label,
863 std::vector<std::string> Params) {
Eric Liu8f3678d2018-06-15 13:34:18 +0000864 return AllOf(SigHelpLabeled(Label), ParamsAre(Params));
Sam McCall800d4372017-12-19 10:29:27 +0000865}
866
867TEST(SignatureHelpTest, Overloads) {
868 auto Results = signatures(R"cpp(
869 void foo(int x, int y);
870 void foo(int x, float y);
871 void foo(float x, int y);
872 void foo(float x, float y);
873 void bar(int x, int y = 0);
874 int main() { foo(^); }
875 )cpp");
876 EXPECT_THAT(Results.signatures,
877 UnorderedElementsAre(
878 Sig("foo(float x, float y) -> void", {"float x", "float y"}),
879 Sig("foo(float x, int y) -> void", {"float x", "int y"}),
880 Sig("foo(int x, float y) -> void", {"int x", "float y"}),
881 Sig("foo(int x, int y) -> void", {"int x", "int y"})));
882 // We always prefer the first signature.
883 EXPECT_EQ(0, Results.activeSignature);
884 EXPECT_EQ(0, Results.activeParameter);
885}
886
887TEST(SignatureHelpTest, DefaultArgs) {
888 auto Results = signatures(R"cpp(
889 void bar(int x, int y = 0);
890 void bar(float x = 0, int y = 42);
891 int main() { bar(^
892 )cpp");
893 EXPECT_THAT(Results.signatures,
894 UnorderedElementsAre(
895 Sig("bar(int x, int y = 0) -> void", {"int x", "int y = 0"}),
896 Sig("bar(float x = 0, int y = 42) -> void",
897 {"float x = 0", "int y = 42"})));
898 EXPECT_EQ(0, Results.activeSignature);
899 EXPECT_EQ(0, Results.activeParameter);
900}
901
902TEST(SignatureHelpTest, ActiveArg) {
903 auto Results = signatures(R"cpp(
904 int baz(int a, int b, int c);
905 int main() { baz(baz(1,2,3), ^); }
906 )cpp");
907 EXPECT_THAT(Results.signatures,
908 ElementsAre(Sig("baz(int a, int b, int c) -> int",
909 {"int a", "int b", "int c"})));
910 EXPECT_EQ(0, Results.activeSignature);
911 EXPECT_EQ(1, Results.activeParameter);
912}
913
Ilya Biryukov43c292c2018-08-30 13:14:31 +0000914TEST(SignatureHelpTest, OpeningParen) {
915 llvm::StringLiteral Tests[] = {// Recursive function call.
916 R"cpp(
917 int foo(int a, int b, int c);
918 int main() {
919 foo(foo $p^( foo(10, 10, 10), ^ )));
920 })cpp",
921 // Functional type cast.
922 R"cpp(
923 struct Foo {
924 Foo(int a, int b, int c);
925 };
926 int main() {
927 Foo $p^( 10, ^ );
928 })cpp",
929 // New expression.
930 R"cpp(
931 struct Foo {
932 Foo(int a, int b, int c);
933 };
934 int main() {
935 new Foo $p^( 10, ^ );
936 })cpp",
937 // Macro expansion.
938 R"cpp(
939 int foo(int a, int b, int c);
940 #define FOO foo(
941
942 int main() {
943 // Macro expansions.
944 $p^FOO 10, ^ );
945 })cpp",
946 // Macro arguments.
947 R"cpp(
948 int foo(int a, int b, int c);
949 int main() {
950 #define ID(X) X
951 ID(foo $p^( foo(10), ^ ))
952 })cpp"};
953
954 for (auto Test : Tests) {
955 Annotations Code(Test);
956 EXPECT_EQ(signatures(Code.code(), Code.point()).argListStart,
957 Code.point("p"))
958 << "Test source:" << Test;
959 }
960}
961
Haojian Wu061c73e2018-01-23 11:37:26 +0000962class IndexRequestCollector : public SymbolIndex {
963public:
964 bool
Sam McCalld1a7a372018-01-31 13:40:48 +0000965 fuzzyFind(const FuzzyFindRequest &Req,
Haojian Wu061c73e2018-01-23 11:37:26 +0000966 llvm::function_ref<void(const Symbol &)> Callback) const override {
967 Requests.push_back(Req);
Sam McCallab8e3932018-02-19 13:04:41 +0000968 return true;
Haojian Wu061c73e2018-01-23 11:37:26 +0000969 }
970
Eric Liu9ec459f2018-03-14 09:48:05 +0000971 void lookup(const LookupRequest &,
972 llvm::function_ref<void(const Symbol &)>) const override {}
973
Haojian Wu65ac3212018-08-06 13:14:32 +0000974 void findOccurrences(const OccurrencesRequest &Req,
975 llvm::function_ref<void(const SymbolOccurrence &)>
976 Callback) const override {}
977
Kirill Bobyrevfc890012018-08-24 09:12:54 +0000978 // This is incorrect, but IndexRequestCollector is not an actual index and it
979 // isn't used in production code.
980 size_t estimateMemoryUsage() const override { return 0; }
981
Eric Liu25d74e92018-08-24 11:23:56 +0000982 const std::vector<FuzzyFindRequest> consumeRequests() const {
983 auto Reqs = std::move(Requests);
984 Requests = {};
985 return Reqs;
986 }
Haojian Wu061c73e2018-01-23 11:37:26 +0000987
988private:
989 mutable std::vector<FuzzyFindRequest> Requests;
990};
991
992std::vector<FuzzyFindRequest> captureIndexRequests(llvm::StringRef Code) {
993 clangd::CodeCompleteOptions Opts;
994 IndexRequestCollector Requests;
995 Opts.Index = &Requests;
996 completions(Code, {}, Opts);
Eric Liu25d74e92018-08-24 11:23:56 +0000997 return Requests.consumeRequests();
Haojian Wu061c73e2018-01-23 11:37:26 +0000998}
999
1000TEST(CompletionTest, UnqualifiedIdQuery) {
1001 auto Requests = captureIndexRequests(R"cpp(
1002 namespace std {}
1003 using namespace std;
1004 namespace ns {
1005 void f() {
1006 vec^
1007 }
1008 }
1009 )cpp");
1010
1011 EXPECT_THAT(Requests,
1012 ElementsAre(Field(&FuzzyFindRequest::Scopes,
1013 UnorderedElementsAre("", "ns::", "std::"))));
1014}
1015
1016TEST(CompletionTest, ResolvedQualifiedIdQuery) {
1017 auto Requests = captureIndexRequests(R"cpp(
1018 namespace ns1 {}
1019 namespace ns2 {} // ignore
1020 namespace ns3 { namespace nns3 {} }
1021 namespace foo {
1022 using namespace ns1;
1023 using namespace ns3::nns3;
1024 }
1025 namespace ns {
1026 void f() {
1027 foo::^
1028 }
1029 }
1030 )cpp");
1031
1032 EXPECT_THAT(Requests,
1033 ElementsAre(Field(
1034 &FuzzyFindRequest::Scopes,
1035 UnorderedElementsAre("foo::", "ns1::", "ns3::nns3::"))));
1036}
1037
1038TEST(CompletionTest, UnresolvedQualifierIdQuery) {
1039 auto Requests = captureIndexRequests(R"cpp(
1040 namespace a {}
1041 using namespace a;
1042 namespace ns {
1043 void f() {
1044 bar::^
1045 }
1046 } // namespace ns
1047 )cpp");
1048
1049 EXPECT_THAT(Requests, ElementsAre(Field(&FuzzyFindRequest::Scopes,
1050 UnorderedElementsAre("bar::"))));
1051}
1052
1053TEST(CompletionTest, UnresolvedNestedQualifierIdQuery) {
1054 auto Requests = captureIndexRequests(R"cpp(
1055 namespace a {}
1056 using namespace a;
1057 namespace ns {
1058 void f() {
1059 ::a::bar::^
1060 }
1061 } // namespace ns
1062 )cpp");
1063
1064 EXPECT_THAT(Requests, ElementsAre(Field(&FuzzyFindRequest::Scopes,
1065 UnorderedElementsAre("a::bar::"))));
1066}
1067
1068TEST(CompletionTest, EmptyQualifiedQuery) {
1069 auto Requests = captureIndexRequests(R"cpp(
1070 namespace ns {
1071 void f() {
1072 ^
1073 }
1074 } // namespace ns
1075 )cpp");
1076
1077 EXPECT_THAT(Requests, ElementsAre(Field(&FuzzyFindRequest::Scopes,
1078 UnorderedElementsAre("", "ns::"))));
1079}
1080
1081TEST(CompletionTest, GlobalQualifiedQuery) {
1082 auto Requests = captureIndexRequests(R"cpp(
1083 namespace ns {
1084 void f() {
1085 ::^
1086 }
1087 } // namespace ns
1088 )cpp");
1089
1090 EXPECT_THAT(Requests, ElementsAre(Field(&FuzzyFindRequest::Scopes,
1091 UnorderedElementsAre(""))));
1092}
1093
Ilya Biryukova907ba42018-05-14 10:50:04 +00001094TEST(CompletionTest, NoIndexCompletionsInsideClasses) {
1095 auto Completions = completions(
1096 R"cpp(
1097 struct Foo {
1098 int SomeNameOfField;
1099 typedef int SomeNameOfTypedefField;
1100 };
1101
1102 Foo::^)cpp",
1103 {func("::SomeNameInTheIndex"), func("::Foo::SomeNameInTheIndex")});
1104
Sam McCalle746a2b2018-07-02 11:13:16 +00001105 EXPECT_THAT(Completions.Completions,
Ilya Biryukova907ba42018-05-14 10:50:04 +00001106 AllOf(Contains(Labeled("SomeNameOfField")),
1107 Contains(Labeled("SomeNameOfTypedefField")),
1108 Not(Contains(Labeled("SomeNameInTheIndex")))));
1109}
1110
1111TEST(CompletionTest, NoIndexCompletionsInsideDependentCode) {
1112 {
1113 auto Completions = completions(
1114 R"cpp(
1115 template <class T>
1116 void foo() {
1117 T::^
1118 }
1119 )cpp",
1120 {func("::SomeNameInTheIndex")});
1121
Sam McCalle746a2b2018-07-02 11:13:16 +00001122 EXPECT_THAT(Completions.Completions,
Ilya Biryukova907ba42018-05-14 10:50:04 +00001123 Not(Contains(Labeled("SomeNameInTheIndex"))));
1124 }
1125
1126 {
1127 auto Completions = completions(
1128 R"cpp(
1129 template <class T>
1130 void foo() {
1131 T::template Y<int>::^
1132 }
1133 )cpp",
1134 {func("::SomeNameInTheIndex")});
1135
Sam McCalle746a2b2018-07-02 11:13:16 +00001136 EXPECT_THAT(Completions.Completions,
Ilya Biryukova907ba42018-05-14 10:50:04 +00001137 Not(Contains(Labeled("SomeNameInTheIndex"))));
1138 }
1139
1140 {
1141 auto Completions = completions(
1142 R"cpp(
1143 template <class T>
1144 void foo() {
1145 T::foo::^
1146 }
1147 )cpp",
1148 {func("::SomeNameInTheIndex")});
1149
Sam McCalle746a2b2018-07-02 11:13:16 +00001150 EXPECT_THAT(Completions.Completions,
Ilya Biryukova907ba42018-05-14 10:50:04 +00001151 Not(Contains(Labeled("SomeNameInTheIndex"))));
1152 }
1153}
1154
Sam McCallc18c2802018-06-15 11:06:29 +00001155TEST(CompletionTest, OverloadBundling) {
1156 clangd::CodeCompleteOptions Opts;
1157 Opts.BundleOverloads = true;
1158
1159 std::string Context = R"cpp(
1160 struct X {
1161 // Overload with int
1162 int a(int);
1163 // Overload with bool
1164 int a(bool);
1165 int b(float);
1166 };
1167 int GFuncC(int);
1168 int GFuncD(int);
1169 )cpp";
1170
1171 // Member completions are bundled.
Sam McCalle746a2b2018-07-02 11:13:16 +00001172 EXPECT_THAT(completions(Context + "int y = X().^", {}, Opts).Completions,
Sam McCallc18c2802018-06-15 11:06:29 +00001173 UnorderedElementsAre(Labeled("a(…)"), Labeled("b(float)")));
1174
1175 // Non-member completions are bundled, including index+sema.
1176 Symbol NoArgsGFunc = func("GFuncC");
1177 EXPECT_THAT(
Sam McCalle746a2b2018-07-02 11:13:16 +00001178 completions(Context + "int y = GFunc^", {NoArgsGFunc}, Opts).Completions,
Sam McCallc18c2802018-06-15 11:06:29 +00001179 UnorderedElementsAre(Labeled("GFuncC(…)"), Labeled("GFuncD(int)")));
1180
1181 // Differences in header-to-insert suppress bundling.
1182 Symbol::Details Detail;
1183 std::string DeclFile = URI::createFile(testPath("foo")).toString();
1184 NoArgsGFunc.CanonicalDeclaration.FileURI = DeclFile;
1185 Detail.IncludeHeader = "<foo>";
1186 NoArgsGFunc.Detail = &Detail;
1187 EXPECT_THAT(
Sam McCalle746a2b2018-07-02 11:13:16 +00001188 completions(Context + "int y = GFunc^", {NoArgsGFunc}, Opts).Completions,
1189 UnorderedElementsAre(AllOf(Named("GFuncC"), InsertInclude("<foo>")),
1190 Labeled("GFuncC(int)"), Labeled("GFuncD(int)")));
Sam McCallc18c2802018-06-15 11:06:29 +00001191
1192 // Examine a bundled completion in detail.
Sam McCalle746a2b2018-07-02 11:13:16 +00001193 auto A =
1194 completions(Context + "int y = X().a^", {}, Opts).Completions.front();
1195 EXPECT_EQ(A.Name, "a");
1196 EXPECT_EQ(A.Signature, "(…)");
1197 EXPECT_EQ(A.BundleSize, 2u);
1198 EXPECT_EQ(A.Kind, CompletionItemKind::Method);
1199 EXPECT_EQ(A.ReturnType, "int"); // All overloads return int.
Sam McCallc18c2802018-06-15 11:06:29 +00001200 // For now we just return one of the doc strings arbitrarily.
Sam McCalle746a2b2018-07-02 11:13:16 +00001201 EXPECT_THAT(A.Documentation, AnyOf(HasSubstr("Overload with int"),
Sam McCallc18c2802018-06-15 11:06:29 +00001202 HasSubstr("Overload with bool")));
Kadir Cetinkaya516fcda2018-08-23 12:19:39 +00001203 EXPECT_EQ(A.SnippetSuffix, "($0)");
Sam McCallc18c2802018-06-15 11:06:29 +00001204}
1205
Ilya Biryukov30b04b12018-05-28 09:54:51 +00001206TEST(CompletionTest, DocumentationFromChangedFileCrash) {
Ilya Biryukovbe0eb8f2018-05-24 14:49:23 +00001207 MockFSProvider FS;
1208 auto FooH = testPath("foo.h");
1209 auto FooCpp = testPath("foo.cpp");
1210 FS.Files[FooH] = R"cpp(
1211 // this is my documentation comment.
1212 int func();
1213 )cpp";
1214 FS.Files[FooCpp] = "";
1215
1216 MockCompilationDatabase CDB;
1217 IgnoreDiagnostics DiagConsumer;
1218 ClangdServer Server(CDB, FS, DiagConsumer, ClangdServer::optsForTest());
1219
1220 Annotations Source(R"cpp(
1221 #include "foo.h"
1222 int func() {
1223 // This makes sure we have func from header in the AST.
1224 }
1225 int a = fun^
1226 )cpp");
1227 Server.addDocument(FooCpp, Source.code(), WantDiagnostics::Yes);
1228 // We need to wait for preamble to build.
1229 ASSERT_TRUE(Server.blockUntilIdleForTest());
1230
1231 // Change the header file. Completion will reuse the old preamble!
1232 FS.Files[FooH] = R"cpp(
1233 int func();
1234 )cpp";
1235
1236 clangd::CodeCompleteOptions Opts;
1237 Opts.IncludeComments = true;
Sam McCalle746a2b2018-07-02 11:13:16 +00001238 CodeCompleteResult Completions =
Ilya Biryukovbe0eb8f2018-05-24 14:49:23 +00001239 cantFail(runCodeComplete(Server, FooCpp, Source.point(), Opts));
1240 // We shouldn't crash. Unfortunately, current workaround is to not produce
1241 // comments for symbols from headers.
Sam McCalle746a2b2018-07-02 11:13:16 +00001242 EXPECT_THAT(Completions.Completions,
Ilya Biryukovbe0eb8f2018-05-24 14:49:23 +00001243 Contains(AllOf(Not(IsDocumented()), Named("func"))));
1244}
1245
Ilya Biryukov89fcf6b2018-06-15 08:31:17 +00001246TEST(CompletionTest, NonDocComments) {
1247 MockFSProvider FS;
1248 auto FooCpp = testPath("foo.cpp");
1249 FS.Files[FooCpp] = "";
1250
1251 MockCompilationDatabase CDB;
1252 IgnoreDiagnostics DiagConsumer;
1253 ClangdServer Server(CDB, FS, DiagConsumer, ClangdServer::optsForTest());
1254
1255 Annotations Source(R"cpp(
Ilya Biryukovda8dd8b2018-06-27 09:47:20 +00001256 // We ignore namespace comments, for rationale see CodeCompletionStrings.h.
1257 namespace comments_ns {
1258 }
1259
Ilya Biryukov89fcf6b2018-06-15 08:31:17 +00001260 // ------------------
1261 int comments_foo();
1262
1263 // A comment and a decl are separated by newlines.
1264 // Therefore, the comment shouldn't show up as doc comment.
1265
1266 int comments_bar();
1267
1268 // this comment should be in the results.
1269 int comments_baz();
1270
1271
1272 template <class T>
1273 struct Struct {
1274 int comments_qux();
1275 int comments_quux();
1276 };
1277
1278
1279 // This comment should not be there.
1280
1281 template <class T>
1282 int Struct<T>::comments_qux() {
1283 }
1284
1285 // This comment **should** be in results.
1286 template <class T>
1287 int Struct<T>::comments_quux() {
1288 int a = comments^;
1289 }
1290 )cpp");
Reid Kleckner80274b12018-06-18 18:55:10 +00001291 // FIXME: Auto-completion in a template requires disabling delayed template
1292 // parsing.
1293 CDB.ExtraClangFlags.push_back("-fno-delayed-template-parsing");
Ilya Biryukov89fcf6b2018-06-15 08:31:17 +00001294 Server.addDocument(FooCpp, Source.code(), WantDiagnostics::Yes);
Sam McCalle746a2b2018-07-02 11:13:16 +00001295 CodeCompleteResult Completions = cantFail(runCodeComplete(
Ilya Biryukov89fcf6b2018-06-15 08:31:17 +00001296 Server, FooCpp, Source.point(), clangd::CodeCompleteOptions()));
1297
1298 // We should not get any of those comments in completion.
1299 EXPECT_THAT(
Sam McCalle746a2b2018-07-02 11:13:16 +00001300 Completions.Completions,
Ilya Biryukov89fcf6b2018-06-15 08:31:17 +00001301 UnorderedElementsAre(AllOf(Not(IsDocumented()), Named("comments_foo")),
1302 AllOf(IsDocumented(), Named("comments_baz")),
1303 AllOf(IsDocumented(), Named("comments_quux")),
Ilya Biryukovda8dd8b2018-06-27 09:47:20 +00001304 AllOf(Not(IsDocumented()), Named("comments_ns")),
Ilya Biryukov89fcf6b2018-06-15 08:31:17 +00001305 // FIXME(ibiryukov): the following items should have
1306 // empty documentation, since they are separated from
1307 // a comment with an empty line. Unfortunately, I
1308 // couldn't make Sema tests pass if we ignore those.
1309 AllOf(IsDocumented(), Named("comments_bar")),
1310 AllOf(IsDocumented(), Named("comments_qux"))));
1311}
1312
Ilya Biryukov981a35d2018-05-28 12:11:37 +00001313TEST(CompletionTest, CompleteOnInvalidLine) {
1314 auto FooCpp = testPath("foo.cpp");
1315
1316 MockCompilationDatabase CDB;
1317 IgnoreDiagnostics DiagConsumer;
1318 MockFSProvider FS;
1319 FS.Files[FooCpp] = "// empty file";
1320
1321 ClangdServer Server(CDB, FS, DiagConsumer, ClangdServer::optsForTest());
1322 // Run completion outside the file range.
1323 Position Pos;
1324 Pos.line = 100;
1325 Pos.character = 0;
1326 EXPECT_THAT_EXPECTED(
1327 runCodeComplete(Server, FooCpp, Pos, clangd::CodeCompleteOptions()),
1328 Failed());
1329}
1330
Eric Liu7ad16962018-06-22 10:46:59 +00001331TEST(CompletionTest, QualifiedNames) {
1332 auto Results = completions(
1333 R"cpp(
1334 namespace ns { int local; void both(); }
1335 void f() { ::ns::^ }
1336 )cpp",
1337 {func("ns::both"), cls("ns::Index")});
1338 // We get results from both index and sema, with no duplicates.
Sam McCalle746a2b2018-07-02 11:13:16 +00001339 EXPECT_THAT(
1340 Results.Completions,
1341 UnorderedElementsAre(Scope("ns::"), Scope("ns::"), Scope("ns::")));
1342}
1343
1344TEST(CompletionTest, Render) {
1345 CodeCompletion C;
1346 C.Name = "x";
1347 C.Signature = "(bool) const";
1348 C.SnippetSuffix = "(${0:bool})";
1349 C.ReturnType = "int";
1350 C.RequiredQualifier = "Foo::";
1351 C.Scope = "ns::Foo::";
1352 C.Documentation = "This is x().";
1353 C.Header = "\"foo.h\"";
1354 C.Kind = CompletionItemKind::Method;
1355 C.Score.Total = 1.0;
Sam McCall4e5742a2018-07-06 11:50:49 +00001356 C.Origin = SymbolOrigin::AST | SymbolOrigin::Static;
Sam McCalle746a2b2018-07-02 11:13:16 +00001357
1358 CodeCompleteOptions Opts;
1359 Opts.IncludeIndicator.Insert = "^";
1360 Opts.IncludeIndicator.NoInsert = "";
1361 Opts.EnableSnippets = false;
1362
1363 auto R = C.render(Opts);
1364 EXPECT_EQ(R.label, "Foo::x(bool) const");
1365 EXPECT_EQ(R.insertText, "Foo::x");
1366 EXPECT_EQ(R.insertTextFormat, InsertTextFormat::PlainText);
1367 EXPECT_EQ(R.filterText, "x");
1368 EXPECT_EQ(R.detail, "int\n\"foo.h\"");
1369 EXPECT_EQ(R.documentation, "This is x().");
1370 EXPECT_THAT(R.additionalTextEdits, IsEmpty());
Sam McCalle746a2b2018-07-02 11:13:16 +00001371 EXPECT_EQ(R.sortText, sortText(1.0, "x"));
1372
1373 Opts.EnableSnippets = true;
1374 R = C.render(Opts);
1375 EXPECT_EQ(R.insertText, "Foo::x(${0:bool})");
1376 EXPECT_EQ(R.insertTextFormat, InsertTextFormat::Snippet);
1377
1378 C.HeaderInsertion.emplace();
1379 R = C.render(Opts);
1380 EXPECT_EQ(R.label, "^Foo::x(bool) const");
1381 EXPECT_THAT(R.additionalTextEdits, Not(IsEmpty()));
1382
Sam McCall2161ec72018-07-05 06:20:41 +00001383 Opts.ShowOrigins = true;
1384 R = C.render(Opts);
1385 EXPECT_EQ(R.label, "^[AS]Foo::x(bool) const");
1386
Sam McCalle746a2b2018-07-02 11:13:16 +00001387 C.BundleSize = 2;
1388 R = C.render(Opts);
1389 EXPECT_EQ(R.detail, "[2 overloads]\n\"foo.h\"");
Eric Liu7ad16962018-06-22 10:46:59 +00001390}
Ilya Biryukov981a35d2018-05-28 12:11:37 +00001391
Eric Liu485074f2018-07-11 13:15:31 +00001392TEST(CompletionTest, IgnoreRecoveryResults) {
1393 auto Results = completions(
1394 R"cpp(
1395 namespace ns { int NotRecovered() { return 0; } }
1396 void f() {
1397 // Sema enters recovery mode first and then normal mode.
1398 if (auto x = ns::NotRecover^)
1399 }
1400 )cpp");
1401 EXPECT_THAT(Results.Completions, UnorderedElementsAre(Named("NotRecovered")));
1402}
1403
Eric Liuf433c2d2018-07-18 15:31:14 +00001404TEST(CompletionTest, ScopeOfClassFieldInConstructorInitializer) {
1405 auto Results = completions(
1406 R"cpp(
1407 namespace ns {
1408 class X { public: X(); int x_; };
1409 X::X() : x_^(0) {}
1410 }
1411 )cpp");
1412 EXPECT_THAT(Results.Completions,
1413 UnorderedElementsAre(AllOf(Scope("ns::X::"), Named("x_"))));
1414}
1415
Eric Liu5d2a8072018-07-23 10:56:37 +00001416TEST(CompletionTest, CodeCompletionContext) {
1417 auto Results = completions(
1418 R"cpp(
1419 namespace ns {
1420 class X { public: X(); int x_; };
1421 void f() {
1422 X x;
1423 x.^;
1424 }
1425 }
1426 )cpp");
1427
1428 EXPECT_THAT(Results.Context, CodeCompletionContext::CCC_DotMemberAccess);
1429}
1430
Kadir Cetinkaya2f84d912018-08-08 08:59:29 +00001431TEST(CompletionTest, FixItForArrowToDot) {
1432 MockFSProvider FS;
1433 MockCompilationDatabase CDB;
1434 IgnoreDiagnostics DiagConsumer;
1435 ClangdServer Server(CDB, FS, DiagConsumer, ClangdServer::optsForTest());
1436
1437 CodeCompleteOptions Opts;
1438 Opts.IncludeFixIts = true;
1439 Annotations TestCode(
1440 R"cpp(
1441 class Auxilary {
1442 public:
1443 void AuxFunction();
1444 };
1445 class ClassWithPtr {
1446 public:
1447 void MemberFunction();
1448 Auxilary* operator->() const;
1449 Auxilary* Aux;
1450 };
1451 void f() {
1452 ClassWithPtr x;
1453 x[[->]]^;
1454 }
1455 )cpp");
1456 auto Results =
1457 completions(Server, TestCode.code(), TestCode.point(), {}, Opts);
1458 EXPECT_EQ(Results.Completions.size(), 3u);
1459
1460 TextEdit ReplacementEdit;
1461 ReplacementEdit.range = TestCode.range();
1462 ReplacementEdit.newText = ".";
1463 for (const auto &C : Results.Completions) {
1464 EXPECT_TRUE(C.FixIts.size() == 1u || C.Name == "AuxFunction");
Haojian Wu1793bc92018-08-10 08:34:16 +00001465 if (!C.FixIts.empty()) {
Kadir Cetinkaya2f84d912018-08-08 08:59:29 +00001466 EXPECT_THAT(C.FixIts, ElementsAre(ReplacementEdit));
Haojian Wu1793bc92018-08-10 08:34:16 +00001467 }
Kadir Cetinkaya2f84d912018-08-08 08:59:29 +00001468 }
1469}
1470
1471TEST(CompletionTest, FixItForDotToArrow) {
1472 MockFSProvider FS;
1473 MockCompilationDatabase CDB;
1474 IgnoreDiagnostics DiagConsumer;
1475 ClangdServer Server(CDB, FS, DiagConsumer, ClangdServer::optsForTest());
1476
1477 CodeCompleteOptions Opts;
1478 Opts.IncludeFixIts = true;
1479 Annotations TestCode(
1480 R"cpp(
1481 class Auxilary {
1482 public:
1483 void AuxFunction();
1484 };
1485 class ClassWithPtr {
1486 public:
1487 void MemberFunction();
1488 Auxilary* operator->() const;
1489 Auxilary* Aux;
1490 };
1491 void f() {
1492 ClassWithPtr x;
1493 x[[.]]^;
1494 }
1495 )cpp");
1496 auto Results =
1497 completions(Server, TestCode.code(), TestCode.point(), {}, Opts);
1498 EXPECT_EQ(Results.Completions.size(), 3u);
1499
1500 TextEdit ReplacementEdit;
1501 ReplacementEdit.range = TestCode.range();
1502 ReplacementEdit.newText = "->";
1503 for (const auto &C : Results.Completions) {
1504 EXPECT_TRUE(C.FixIts.empty() || C.Name == "AuxFunction");
1505 if (!C.FixIts.empty()) {
1506 EXPECT_THAT(C.FixIts, ElementsAre(ReplacementEdit));
1507 }
1508 }
1509}
1510
Kadir Cetinkayaa9c9d002018-08-13 08:23:01 +00001511TEST(CompletionTest, RenderWithFixItMerged) {
1512 TextEdit FixIt;
1513 FixIt.range.end.character = 5;
1514 FixIt.newText = "->";
1515
1516 CodeCompletion C;
1517 C.Name = "x";
1518 C.RequiredQualifier = "Foo::";
1519 C.FixIts = {FixIt};
1520 C.CompletionTokenRange.start.character = 5;
1521
1522 CodeCompleteOptions Opts;
1523 Opts.IncludeFixIts = true;
1524
1525 auto R = C.render(Opts);
1526 EXPECT_TRUE(R.textEdit);
1527 EXPECT_EQ(R.textEdit->newText, "->Foo::x");
1528 EXPECT_TRUE(R.additionalTextEdits.empty());
1529}
1530
1531TEST(CompletionTest, RenderWithFixItNonMerged) {
1532 TextEdit FixIt;
1533 FixIt.range.end.character = 4;
1534 FixIt.newText = "->";
1535
1536 CodeCompletion C;
1537 C.Name = "x";
1538 C.RequiredQualifier = "Foo::";
1539 C.FixIts = {FixIt};
1540 C.CompletionTokenRange.start.character = 5;
1541
1542 CodeCompleteOptions Opts;
1543 Opts.IncludeFixIts = true;
1544
1545 auto R = C.render(Opts);
1546 EXPECT_TRUE(R.textEdit);
1547 EXPECT_EQ(R.textEdit->newText, "Foo::x");
1548 EXPECT_THAT(R.additionalTextEdits, UnorderedElementsAre(FixIt));
1549}
1550
1551TEST(CompletionTest, CompletionTokenRange) {
1552 MockFSProvider FS;
1553 MockCompilationDatabase CDB;
1554 IgnoreDiagnostics DiagConsumer;
1555 ClangdServer Server(CDB, FS, DiagConsumer, ClangdServer::optsForTest());
1556
1557 constexpr const char *TestCodes[] = {
1558 R"cpp(
1559 class Auxilary {
1560 public:
1561 void AuxFunction();
1562 };
1563 void f() {
1564 Auxilary x;
1565 x.[[Aux]]^;
1566 }
1567 )cpp",
1568 R"cpp(
1569 class Auxilary {
1570 public:
1571 void AuxFunction();
1572 };
1573 void f() {
1574 Auxilary x;
1575 x.[[]]^;
1576 }
1577 )cpp"};
1578 for (const auto &Text : TestCodes) {
1579 Annotations TestCode(Text);
1580 auto Results = completions(Server, TestCode.code(), TestCode.point());
1581
1582 EXPECT_EQ(Results.Completions.size(), 1u);
1583 EXPECT_THAT(Results.Completions.front().CompletionTokenRange, TestCode.range());
1584 }
1585}
1586
Kadir Cetinkayae486e372018-08-13 08:40:05 +00001587TEST(SignatureHelpTest, OverloadsOrdering) {
1588 const auto Results = signatures(R"cpp(
1589 void foo(int x);
1590 void foo(int x, float y);
1591 void foo(float x, int y);
1592 void foo(float x, float y);
1593 void foo(int x, int y = 0);
1594 int main() { foo(^); }
1595 )cpp");
1596 EXPECT_THAT(
1597 Results.signatures,
1598 ElementsAre(
1599 Sig("foo(int x) -> void", {"int x"}),
1600 Sig("foo(int x, int y = 0) -> void", {"int x", "int y = 0"}),
1601 Sig("foo(float x, int y) -> void", {"float x", "int y"}),
1602 Sig("foo(int x, float y) -> void", {"int x", "float y"}),
1603 Sig("foo(float x, float y) -> void", {"float x", "float y"})));
1604 // We always prefer the first signature.
1605 EXPECT_EQ(0, Results.activeSignature);
1606 EXPECT_EQ(0, Results.activeParameter);
1607}
1608
Ilya Biryukov8fd44bb2018-08-14 09:36:32 +00001609TEST(SignatureHelpTest, InstantiatedSignatures) {
Simon Pilgrim83552ee2018-08-16 11:41:19 +00001610 StringRef Sig0 = R"cpp(
Ilya Biryukov8fd44bb2018-08-14 09:36:32 +00001611 template <class T>
1612 void foo(T, T, T);
1613
1614 int main() {
1615 foo<int>(^);
1616 }
Simon Pilgrim83552ee2018-08-16 11:41:19 +00001617 )cpp";
1618
1619 EXPECT_THAT(signatures(Sig0).signatures,
Ilya Biryukov8fd44bb2018-08-14 09:36:32 +00001620 ElementsAre(Sig("foo(T, T, T) -> void", {"T", "T", "T"})));
1621
Simon Pilgrim83552ee2018-08-16 11:41:19 +00001622 StringRef Sig1 = R"cpp(
Ilya Biryukov8fd44bb2018-08-14 09:36:32 +00001623 template <class T>
1624 void foo(T, T, T);
1625
1626 int main() {
1627 foo(10, ^);
Simon Pilgrim83552ee2018-08-16 11:41:19 +00001628 })cpp";
1629
1630 EXPECT_THAT(signatures(Sig1).signatures,
Ilya Biryukov8fd44bb2018-08-14 09:36:32 +00001631 ElementsAre(Sig("foo(T, T, T) -> void", {"T", "T", "T"})));
1632
Simon Pilgrim83552ee2018-08-16 11:41:19 +00001633 StringRef Sig2 = R"cpp(
Ilya Biryukov8fd44bb2018-08-14 09:36:32 +00001634 template <class ...T>
1635 void foo(T...);
1636
1637 int main() {
1638 foo<int>(^);
1639 }
Simon Pilgrim83552ee2018-08-16 11:41:19 +00001640 )cpp";
1641
1642 EXPECT_THAT(signatures(Sig2).signatures,
Ilya Biryukov8fd44bb2018-08-14 09:36:32 +00001643 ElementsAre(Sig("foo(T...) -> void", {"T..."})));
1644
1645 // It is debatable whether we should substitute the outer template parameter
1646 // ('T') in that case. Currently we don't substitute it in signature help, but
1647 // do substitute in code complete.
1648 // FIXME: make code complete and signature help consistent, figure out which
1649 // way is better.
Simon Pilgrim83552ee2018-08-16 11:41:19 +00001650 StringRef Sig3 = R"cpp(
Ilya Biryukov8fd44bb2018-08-14 09:36:32 +00001651 template <class T>
1652 struct X {
1653 template <class U>
1654 void foo(T, U);
1655 };
1656
1657 int main() {
1658 X<int>().foo<double>(^)
1659 }
Simon Pilgrim83552ee2018-08-16 11:41:19 +00001660 )cpp";
1661
1662 EXPECT_THAT(signatures(Sig3).signatures,
Ilya Biryukov8fd44bb2018-08-14 09:36:32 +00001663 ElementsAre(Sig("foo(T, U) -> void", {"T", "U"})));
1664}
1665
Ilya Biryukov8a0f76b2018-08-17 09:32:30 +00001666TEST(SignatureHelpTest, IndexDocumentation) {
1667 Symbol::Details DocDetails;
1668 DocDetails.Documentation = "Doc from the index";
1669
1670 Symbol Foo0 = sym("foo", index::SymbolKind::Function, "@F@\\0#");
1671 Foo0.Detail = &DocDetails;
1672 Symbol Foo1 = sym("foo", index::SymbolKind::Function, "@F@\\0#I#");
1673 Foo1.Detail = &DocDetails;
1674 Symbol Foo2 = sym("foo", index::SymbolKind::Function, "@F@\\0#I#I#");
1675
Simon Pilgrim24d34922018-08-17 10:40:05 +00001676 StringRef Sig0 = R"cpp(
Ilya Biryukov8a0f76b2018-08-17 09:32:30 +00001677 int foo();
1678 int foo(double);
1679
1680 void test() {
1681 foo(^);
1682 }
Simon Pilgrim24d34922018-08-17 10:40:05 +00001683 )cpp";
1684
1685 EXPECT_THAT(
1686 signatures(Sig0, {Foo0}).signatures,
Ilya Biryukov8a0f76b2018-08-17 09:32:30 +00001687 ElementsAre(AllOf(Sig("foo() -> int", {}), SigDoc("Doc from the index")),
1688 AllOf(Sig("foo(double) -> int", {"double"}), SigDoc(""))));
1689
Simon Pilgrim24d34922018-08-17 10:40:05 +00001690 StringRef Sig1 = R"cpp(
Ilya Biryukov8a0f76b2018-08-17 09:32:30 +00001691 int foo();
1692 // Overriden doc from sema
1693 int foo(int);
1694 // Doc from sema
1695 int foo(int, int);
1696
1697 void test() {
1698 foo(^);
1699 }
Simon Pilgrim24d34922018-08-17 10:40:05 +00001700 )cpp";
1701
1702 EXPECT_THAT(
1703 signatures(Sig1, {Foo0, Foo1, Foo2}).signatures,
Ilya Biryukov8a0f76b2018-08-17 09:32:30 +00001704 ElementsAre(AllOf(Sig("foo() -> int", {}), SigDoc("Doc from the index")),
1705 AllOf(Sig("foo(int) -> int", {"int"}),
1706 SigDoc("Overriden doc from sema")),
1707 AllOf(Sig("foo(int, int) -> int", {"int", "int"}),
1708 SigDoc("Doc from sema"))));
1709}
1710
Kadir Cetinkaya516fcda2018-08-23 12:19:39 +00001711TEST(CompletionTest, CompletionFunctionArgsDisabled) {
Kadir Cetinkaya6c9f15c2018-08-17 15:42:54 +00001712 CodeCompleteOptions Opts;
Kadir Cetinkaya6c9f15c2018-08-17 15:42:54 +00001713 Opts.EnableSnippets = true;
1714 Opts.EnableFunctionArgSnippets = false;
Kadir Cetinkaya516fcda2018-08-23 12:19:39 +00001715 const std::string Header =
1716 R"cpp(
1717 void xfoo();
1718 void xfoo(int x, int y);
1719 void xbar();
1720 void f() {
1721 )cpp";
Kadir Cetinkaya6c9f15c2018-08-17 15:42:54 +00001722 {
Kadir Cetinkaya516fcda2018-08-23 12:19:39 +00001723 auto Results = completions(Header + "\nxfo^", {}, Opts);
1724 EXPECT_THAT(
1725 Results.Completions,
1726 UnorderedElementsAre(AllOf(Named("xfoo"), SnippetSuffix("()")),
1727 AllOf(Named("xfoo"), SnippetSuffix("($0)"))));
Kadir Cetinkaya6c9f15c2018-08-17 15:42:54 +00001728 }
Kadir Cetinkaya6c9f15c2018-08-17 15:42:54 +00001729 {
Kadir Cetinkaya516fcda2018-08-23 12:19:39 +00001730 auto Results = completions(Header + "\nxba^", {}, Opts);
1731 EXPECT_THAT(Results.Completions, UnorderedElementsAre(AllOf(
1732 Named("xbar"), SnippetSuffix("()"))));
Kadir Cetinkaya6c9f15c2018-08-17 15:42:54 +00001733 }
Kadir Cetinkaya6c9f15c2018-08-17 15:42:54 +00001734 {
Kadir Cetinkaya516fcda2018-08-23 12:19:39 +00001735 Opts.BundleOverloads = true;
1736 auto Results = completions(Header + "\nxfo^", {}, Opts);
1737 EXPECT_THAT(
1738 Results.Completions,
1739 UnorderedElementsAre(AllOf(Named("xfoo"), SnippetSuffix("($0)"))));
Kadir Cetinkaya6c9f15c2018-08-17 15:42:54 +00001740 }
1741}
1742
Kadir Cetinkayaf8b85a32018-08-23 13:14:50 +00001743TEST(CompletionTest, SuggestOverrides) {
1744 constexpr const char *const Text(R"cpp(
1745 class A {
1746 public:
1747 virtual void vfunc(bool param);
1748 virtual void vfunc(bool param, int p);
1749 void func(bool param);
1750 };
1751 class B : public A {
1752 virtual void ttt(bool param) const;
1753 void vfunc(bool param, int p) override;
1754 };
1755 class C : public B {
1756 public:
1757 void vfunc(bool param) override;
1758 ^
1759 };
1760 )cpp");
1761 const auto Results = completions(Text);
1762 EXPECT_THAT(Results.Completions,
1763 AllOf(Contains(Labeled("void vfunc(bool param, int p) override")),
1764 Contains(Labeled("void ttt(bool param) const override")),
1765 Not(Contains(Labeled("void vfunc(bool param) override")))));
1766}
1767
Eric Liu25d74e92018-08-24 11:23:56 +00001768TEST(SpeculateCompletionFilter, Filters) {
1769 Annotations F(R"cpp($bof^
1770 $bol^
1771 ab$ab^
1772 x.ab$dot^
1773 x.$dotempty^
1774 x::ab$scoped^
1775 x::$scopedempty^
1776
1777 )cpp");
1778 auto speculate = [&](StringRef PointName) {
1779 auto Filter = speculateCompletionFilter(F.code(), F.point(PointName));
1780 assert(Filter);
1781 return *Filter;
1782 };
1783 EXPECT_EQ(speculate("bof"), "");
1784 EXPECT_EQ(speculate("bol"), "");
1785 EXPECT_EQ(speculate("ab"), "ab");
1786 EXPECT_EQ(speculate("dot"), "ab");
1787 EXPECT_EQ(speculate("dotempty"), "");
1788 EXPECT_EQ(speculate("scoped"), "ab");
1789 EXPECT_EQ(speculate("scopedempty"), "");
1790}
1791
1792TEST(CompletionTest, EnableSpeculativeIndexRequest) {
1793 MockFSProvider FS;
1794 MockCompilationDatabase CDB;
1795 IgnoreDiagnostics DiagConsumer;
1796 ClangdServer Server(CDB, FS, DiagConsumer, ClangdServer::optsForTest());
1797
1798 auto File = testPath("foo.cpp");
1799 Annotations Test(R"cpp(
1800 namespace ns1 { int abc; }
1801 namespace ns2 { int abc; }
1802 void f() { ns1::ab$1^; ns1::ab$2^; }
1803 void f() { ns2::ab$3^; }
1804 )cpp");
1805 runAddDocument(Server, File, Test.code());
1806 clangd::CodeCompleteOptions Opts = {};
1807
1808 IndexRequestCollector Requests;
1809 Opts.Index = &Requests;
1810 Opts.SpeculativeIndexRequest = true;
1811
1812 auto CompleteAtPoint = [&](StringRef P) {
1813 cantFail(runCodeComplete(Server, File, Test.point(P), Opts));
1814 // Sleep for a while to make sure asynchronous call (if applicable) is also
1815 // triggered before callback is invoked.
1816 std::this_thread::sleep_for(std::chrono::milliseconds(100));
1817 };
1818
1819 CompleteAtPoint("1");
1820 auto Reqs1 = Requests.consumeRequests();
1821 ASSERT_EQ(Reqs1.size(), 1u);
1822 EXPECT_THAT(Reqs1[0].Scopes, UnorderedElementsAre("ns1::"));
1823
1824 CompleteAtPoint("2");
1825 auto Reqs2 = Requests.consumeRequests();
1826 // Speculation succeeded. Used speculative index result.
1827 ASSERT_EQ(Reqs2.size(), 1u);
1828 EXPECT_EQ(Reqs2[0], Reqs1[0]);
1829
1830 CompleteAtPoint("3");
1831 // Speculation failed. Sent speculative index request and the new index
1832 // request after sema.
1833 auto Reqs3 = Requests.consumeRequests();
1834 ASSERT_EQ(Reqs3.size(), 2u);
1835}
1836
Sam McCall9aad25f2017-12-05 07:20:26 +00001837} // namespace
1838} // namespace clangd
1839} // namespace clang