blob: 248dab8ca27fa4376972a7d6b5eb2a43d60a249c [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 Liu83f63e42018-09-03 10:18:21 +000058MATCHER_P(HasInclude, IncludeHeader, "") {
59 return !arg.Includes.empty() && arg.Includes[0].Header == IncludeHeader;
Eric Liu63f419a2018-05-15 15:29:32 +000060}
Eric Liu83f63e42018-09-03 10:18:21 +000061MATCHER_P(InsertInclude, IncludeHeader, "") {
62 return !arg.Includes.empty() && arg.Includes[0].Header == IncludeHeader &&
63 bool(arg.Includes[0].Insertion);
64}
65MATCHER(InsertInclude, "") {
66 return !arg.Includes.empty() && bool(arg.Includes[0].Insertion);
67}
Sam McCalle746a2b2018-07-02 11:13:16 +000068MATCHER_P(SnippetSuffix, Text, "") { return arg.SnippetSuffix == Text; }
Sam McCall2161ec72018-07-05 06:20:41 +000069MATCHER_P(Origin, OriginSet, "") { return arg.Origin == OriginSet; }
Eric Liu63f419a2018-05-15 15:29:32 +000070
Sam McCallf6ae3232017-12-05 20:11:29 +000071// Shorthand for Contains(Named(Name)).
Sam McCalle746a2b2018-07-02 11:13:16 +000072Matcher<const std::vector<CodeCompletion> &> Has(std::string Name) {
Sam McCallf6ae3232017-12-05 20:11:29 +000073 return Contains(Named(std::move(Name)));
74}
Sam McCalle746a2b2018-07-02 11:13:16 +000075Matcher<const std::vector<CodeCompletion> &> Has(std::string Name,
Sam McCall44fdcec22017-12-08 15:00:59 +000076 CompletionItemKind K) {
77 return Contains(AllOf(Named(std::move(Name)), Kind(K)));
Sam McCallf6ae3232017-12-05 20:11:29 +000078}
Sam McCalle746a2b2018-07-02 11:13:16 +000079MATCHER(IsDocumented, "") { return !arg.Documentation.empty(); }
Eric Liu6df66002018-09-06 18:52:26 +000080MATCHER(Deprecated, "") { return arg.Deprecated; }
Sam McCall9aad25f2017-12-05 07:20:26 +000081
Sam McCalla15c2d62018-01-18 09:27:56 +000082std::unique_ptr<SymbolIndex> memIndex(std::vector<Symbol> Symbols) {
83 SymbolSlab::Builder Slab;
84 for (const auto &Sym : Symbols)
85 Slab.insert(Sym);
Sam McCallb0138312018-09-04 14:39:56 +000086 return MemIndex::build(std::move(Slab).build(), RefSlab());
Sam McCalla15c2d62018-01-18 09:27:56 +000087}
88
Kadir Cetinkaya2f84d912018-08-08 08:59:29 +000089CodeCompleteResult completions(ClangdServer &Server, StringRef TestCode,
90 Position point,
91 std::vector<Symbol> IndexSymbols = {},
92 clangd::CodeCompleteOptions Opts = {}) {
93 std::unique_ptr<SymbolIndex> OverrideIndex;
94 if (!IndexSymbols.empty()) {
95 assert(!Opts.Index && "both Index and IndexSymbols given!");
96 OverrideIndex = memIndex(std::move(IndexSymbols));
97 Opts.Index = OverrideIndex.get();
98 }
99
100 auto File = testPath("foo.cpp");
101 runAddDocument(Server, File, TestCode);
102 auto CompletionList = cantFail(runCodeComplete(Server, File, point, Opts));
103 return CompletionList;
104}
105
Sam McCalle746a2b2018-07-02 11:13:16 +0000106CodeCompleteResult completions(ClangdServer &Server, StringRef Text,
107 std::vector<Symbol> IndexSymbols = {},
108 clangd::CodeCompleteOptions Opts = {}) {
Sam McCalla15c2d62018-01-18 09:27:56 +0000109 std::unique_ptr<SymbolIndex> OverrideIndex;
110 if (!IndexSymbols.empty()) {
111 assert(!Opts.Index && "both Index and IndexSymbols given!");
112 OverrideIndex = memIndex(std::move(IndexSymbols));
113 Opts.Index = OverrideIndex.get();
114 }
115
Sam McCallc1568062018-02-16 09:41:43 +0000116 auto File = testPath("foo.cpp");
Sam McCall328cbdb2017-12-20 16:06:05 +0000117 Annotations Test(Text);
Sam McCall7363a2f2018-03-05 17:28:54 +0000118 runAddDocument(Server, File, Test.code());
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000119 auto CompletionList =
120 cantFail(runCodeComplete(Server, File, Test.point(), Opts));
Ilya Biryukov5a5e1ca2017-12-29 14:59:22 +0000121 return CompletionList;
Sam McCall9aad25f2017-12-05 07:20:26 +0000122}
123
Eric Liu63f419a2018-05-15 15:29:32 +0000124// Builds a server and runs code completion.
125// If IndexSymbols is non-empty, an index will be built and passed to opts.
Sam McCalle746a2b2018-07-02 11:13:16 +0000126CodeCompleteResult completions(StringRef Text,
127 std::vector<Symbol> IndexSymbols = {},
128 clangd::CodeCompleteOptions Opts = {}) {
Eric Liu63f419a2018-05-15 15:29:32 +0000129 MockFSProvider FS;
130 MockCompilationDatabase CDB;
131 IgnoreDiagnostics DiagConsumer;
132 ClangdServer Server(CDB, FS, DiagConsumer, ClangdServer::optsForTest());
133 return completions(Server, Text, std::move(IndexSymbols), std::move(Opts));
134}
135
Sam McCall545a20d2018-01-19 14:34:02 +0000136std::string replace(StringRef Haystack, StringRef Needle, StringRef Repl) {
137 std::string Result;
138 raw_string_ostream OS(Result);
139 std::pair<StringRef, StringRef> Split;
140 for (Split = Haystack.split(Needle); !Split.second.empty();
141 Split = Split.first.split(Needle))
142 OS << Split.first << Repl;
143 Result += Split.first;
144 OS.flush();
145 return Result;
146}
147
Sam McCalla15c2d62018-01-18 09:27:56 +0000148// Helpers to produce fake index symbols for memIndex() or completions().
Sam McCall545a20d2018-01-19 14:34:02 +0000149// USRFormat is a regex replacement string for the unqualified part of the USR.
150Symbol sym(StringRef QName, index::SymbolKind Kind, StringRef USRFormat) {
Sam McCalla15c2d62018-01-18 09:27:56 +0000151 Symbol Sym;
Sam McCall545a20d2018-01-19 14:34:02 +0000152 std::string USR = "c:"; // We synthesize a few simple cases of USRs by hand!
Sam McCalla15c2d62018-01-18 09:27:56 +0000153 size_t Pos = QName.rfind("::");
154 if (Pos == llvm::StringRef::npos) {
155 Sym.Name = QName;
156 Sym.Scope = "";
157 } else {
158 Sym.Name = QName.substr(Pos + 2);
Sam McCall8b2faee2018-01-19 22:18:21 +0000159 Sym.Scope = QName.substr(0, Pos + 2);
160 USR += "@N@" + replace(QName.substr(0, Pos), "::", "@N@"); // ns:: -> @N@ns
Sam McCalla15c2d62018-01-18 09:27:56 +0000161 }
Sam McCall545a20d2018-01-19 14:34:02 +0000162 USR += Regex("^.*$").sub(USRFormat, Sym.Name); // e.g. func -> @F@func#
163 Sym.ID = SymbolID(USR);
Sam McCalla15c2d62018-01-18 09:27:56 +0000164 Sym.SymInfo.Kind = Kind;
Eric Liu6df66002018-09-06 18:52:26 +0000165 Sym.Flags |= Symbol::IndexedForCodeCompletion;
Sam McCall2161ec72018-07-05 06:20:41 +0000166 Sym.Origin = SymbolOrigin::Static;
Sam McCalla15c2d62018-01-18 09:27:56 +0000167 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) {
Eric Liu9b3cba72018-05-30 09:03:39 +0000173 return sym(Name, index::SymbolKind::Class, "@S@\\0");
Sam McCall545a20d2018-01-19 14:34:02 +0000174}
175Symbol var(StringRef Name) {
176 return sym(Name, index::SymbolKind::Variable, "@\\0");
177}
Sam McCalldc8abc42018-05-03 14:53:02 +0000178Symbol ns(StringRef Name) {
179 return sym(Name, index::SymbolKind::Namespace, "@N@\\0");
180}
181Symbol withReferences(int N, Symbol S) {
182 S.References = N;
183 return S;
184}
Sam McCalla15c2d62018-01-18 09:27:56 +0000185
Sam McCallf6ae3232017-12-05 20:11:29 +0000186TEST(CompletionTest, Limit) {
187 clangd::CodeCompleteOptions Opts;
188 Opts.Limit = 2;
189 auto Results = completions(R"cpp(
Sam McCall9aad25f2017-12-05 07:20:26 +0000190struct ClassWithMembers {
191 int AAA();
192 int BBB();
193 int CCC();
194}
Sam McCallf6ae3232017-12-05 20:11:29 +0000195int main() { ClassWithMembers().^ }
Sam McCall9aad25f2017-12-05 07:20:26 +0000196 )cpp",
Sam McCalla15c2d62018-01-18 09:27:56 +0000197 /*IndexSymbols=*/{}, Opts);
Sam McCall9aad25f2017-12-05 07:20:26 +0000198
Sam McCalle746a2b2018-07-02 11:13:16 +0000199 EXPECT_TRUE(Results.HasMore);
200 EXPECT_THAT(Results.Completions, ElementsAre(Named("AAA"), Named("BBB")));
Sam McCall9aad25f2017-12-05 07:20:26 +0000201}
202
Sam McCallf6ae3232017-12-05 20:11:29 +0000203TEST(CompletionTest, Filter) {
204 std::string Body = R"cpp(
Sam McCall8b2dcc12018-06-14 13:50:30 +0000205 #define MotorCar
206 int Car;
Sam McCall9aad25f2017-12-05 07:20:26 +0000207 struct S {
208 int FooBar;
209 int FooBaz;
210 int Qux;
211 };
212 )cpp";
Sam McCall8b2dcc12018-06-14 13:50:30 +0000213
214 // Only items matching the fuzzy query are returned.
Sam McCalle746a2b2018-07-02 11:13:16 +0000215 EXPECT_THAT(completions(Body + "int main() { S().Foba^ }").Completions,
Sam McCall8b2dcc12018-06-14 13:50:30 +0000216 AllOf(Has("FooBar"), Has("FooBaz"), Not(Has("Qux"))));
Sam McCall9aad25f2017-12-05 07:20:26 +0000217
Sam McCall8b2dcc12018-06-14 13:50:30 +0000218 // Macros require prefix match.
Sam McCalle746a2b2018-07-02 11:13:16 +0000219 EXPECT_THAT(completions(Body + "int main() { C^ }").Completions,
Sam McCall8b2dcc12018-06-14 13:50:30 +0000220 AllOf(Has("Car"), Not(Has("MotorCar"))));
Sam McCall9aad25f2017-12-05 07:20:26 +0000221}
222
Sam McCallf6ae3232017-12-05 20:11:29 +0000223void TestAfterDotCompletion(clangd::CodeCompleteOptions Opts) {
Sam McCall44fdcec22017-12-08 15:00:59 +0000224 auto Results = completions(
225 R"cpp(
226 #define MACRO X
Sam McCall9aad25f2017-12-05 07:20:26 +0000227
Sam McCall44fdcec22017-12-08 15:00:59 +0000228 int global_var;
Sam McCall9aad25f2017-12-05 07:20:26 +0000229
Sam McCall44fdcec22017-12-08 15:00:59 +0000230 int global_func();
Sam McCall9aad25f2017-12-05 07:20:26 +0000231
Sam McCall44fdcec22017-12-08 15:00:59 +0000232 struct GlobalClass {};
Sam McCall9aad25f2017-12-05 07:20:26 +0000233
Sam McCall44fdcec22017-12-08 15:00:59 +0000234 struct ClassWithMembers {
235 /// Doc for method.
236 int method();
Sam McCall9aad25f2017-12-05 07:20:26 +0000237
Sam McCall44fdcec22017-12-08 15:00:59 +0000238 int field;
239 private:
240 int private_field;
241 };
Sam McCall9aad25f2017-12-05 07:20:26 +0000242
Sam McCall44fdcec22017-12-08 15:00:59 +0000243 int test() {
244 struct LocalClass {};
Sam McCall9aad25f2017-12-05 07:20:26 +0000245
Sam McCall44fdcec22017-12-08 15:00:59 +0000246 /// Doc for local_var.
247 int local_var;
Sam McCall9aad25f2017-12-05 07:20:26 +0000248
Sam McCall44fdcec22017-12-08 15:00:59 +0000249 ClassWithMembers().^
250 }
251 )cpp",
Sam McCall545a20d2018-01-19 14:34:02 +0000252 {cls("IndexClass"), var("index_var"), func("index_func")}, Opts);
Sam McCall9aad25f2017-12-05 07:20:26 +0000253
Sam McCallf6ae3232017-12-05 20:11:29 +0000254 // Class members. The only items that must be present in after-dot
255 // completion.
Sam McCalle746a2b2018-07-02 11:13:16 +0000256 EXPECT_THAT(Results.Completions,
257 AllOf(Has("method"), Has("field"), Not(Has("ClassWithMembers")),
Sam McCall4caa8512018-06-07 12:49:17 +0000258 Not(Has("operator=")), Not(Has("~ClassWithMembers"))));
Sam McCalle746a2b2018-07-02 11:13:16 +0000259 EXPECT_IFF(Opts.IncludeIneligibleResults, Results.Completions,
Sam McCall44fdcec22017-12-08 15:00:59 +0000260 Has("private_field"));
Sam McCallf6ae3232017-12-05 20:11:29 +0000261 // Global items.
Sam McCall545a20d2018-01-19 14:34:02 +0000262 EXPECT_THAT(
Sam McCalle746a2b2018-07-02 11:13:16 +0000263 Results.Completions,
Sam McCall545a20d2018-01-19 14:34:02 +0000264 Not(AnyOf(Has("global_var"), Has("index_var"), Has("global_func"),
265 Has("global_func()"), Has("index_func"), Has("GlobalClass"),
266 Has("IndexClass"), Has("MACRO"), Has("LocalClass"))));
Sam McCallf6ae3232017-12-05 20:11:29 +0000267 // There should be no code patterns (aka snippets) in after-dot
268 // completion. At least there aren't any we're aware of.
Sam McCalle746a2b2018-07-02 11:13:16 +0000269 EXPECT_THAT(Results.Completions,
270 Not(Contains(Kind(CompletionItemKind::Snippet))));
Sam McCallf6ae3232017-12-05 20:11:29 +0000271 // Check documentation.
Sam McCalle746a2b2018-07-02 11:13:16 +0000272 EXPECT_IFF(Opts.IncludeComments, Results.Completions,
273 Contains(IsDocumented()));
Sam McCallf6ae3232017-12-05 20:11:29 +0000274}
Sam McCall9aad25f2017-12-05 07:20:26 +0000275
Sam McCallf6ae3232017-12-05 20:11:29 +0000276void TestGlobalScopeCompletion(clangd::CodeCompleteOptions Opts) {
Sam McCall44fdcec22017-12-08 15:00:59 +0000277 auto Results = completions(
278 R"cpp(
279 #define MACRO X
Sam McCall9aad25f2017-12-05 07:20:26 +0000280
Sam McCall44fdcec22017-12-08 15:00:59 +0000281 int global_var;
282 int global_func();
Sam McCall9aad25f2017-12-05 07:20:26 +0000283
Sam McCall44fdcec22017-12-08 15:00:59 +0000284 struct GlobalClass {};
Sam McCall9aad25f2017-12-05 07:20:26 +0000285
Sam McCall44fdcec22017-12-08 15:00:59 +0000286 struct ClassWithMembers {
287 /// Doc for method.
288 int method();
289 };
Sam McCall9aad25f2017-12-05 07:20:26 +0000290
Sam McCall44fdcec22017-12-08 15:00:59 +0000291 int test() {
292 struct LocalClass {};
Sam McCall9aad25f2017-12-05 07:20:26 +0000293
Sam McCall44fdcec22017-12-08 15:00:59 +0000294 /// Doc for local_var.
295 int local_var;
Sam McCall9aad25f2017-12-05 07:20:26 +0000296
Sam McCall44fdcec22017-12-08 15:00:59 +0000297 ^
298 }
299 )cpp",
Sam McCall545a20d2018-01-19 14:34:02 +0000300 {cls("IndexClass"), var("index_var"), func("index_func")}, Opts);
Sam McCallf6ae3232017-12-05 20:11:29 +0000301
302 // Class members. Should never be present in global completions.
Sam McCalle746a2b2018-07-02 11:13:16 +0000303 EXPECT_THAT(Results.Completions,
Sam McCallf6ae3232017-12-05 20:11:29 +0000304 Not(AnyOf(Has("method"), Has("method()"), Has("field"))));
305 // Global items.
Sam McCalle746a2b2018-07-02 11:13:16 +0000306 EXPECT_THAT(Results.Completions,
307 AllOf(Has("global_var"), Has("index_var"), Has("global_func"),
Sam McCall545a20d2018-01-19 14:34:02 +0000308 Has("index_func" /* our fake symbol doesn't include () */),
309 Has("GlobalClass"), Has("IndexClass")));
Sam McCallf6ae3232017-12-05 20:11:29 +0000310 // A macro.
Sam McCalle746a2b2018-07-02 11:13:16 +0000311 EXPECT_IFF(Opts.IncludeMacros, Results.Completions, Has("MACRO"));
Sam McCallf6ae3232017-12-05 20:11:29 +0000312 // Local items. Must be present always.
Sam McCalle746a2b2018-07-02 11:13:16 +0000313 EXPECT_THAT(Results.Completions,
Ilya Biryukov9b5ffc22017-12-12 12:56:46 +0000314 AllOf(Has("local_var"), Has("LocalClass"),
315 Contains(Kind(CompletionItemKind::Snippet))));
Sam McCallf6ae3232017-12-05 20:11:29 +0000316 // Check documentation.
Sam McCalle746a2b2018-07-02 11:13:16 +0000317 EXPECT_IFF(Opts.IncludeComments, Results.Completions,
318 Contains(IsDocumented()));
Sam McCallf6ae3232017-12-05 20:11:29 +0000319}
320
321TEST(CompletionTest, CompletionOptions) {
Sam McCall2c3849a2018-01-16 12:21:24 +0000322 auto Test = [&](const clangd::CodeCompleteOptions &Opts) {
323 TestAfterDotCompletion(Opts);
324 TestGlobalScopeCompletion(Opts);
325 };
326 // We used to test every combination of options, but that got too slow (2^N).
327 auto Flags = {
Ilya Biryukov71028b82018-03-12 15:28:22 +0000328 &clangd::CodeCompleteOptions::IncludeMacros,
Ilya Biryukov43714502018-05-16 12:32:44 +0000329 &clangd::CodeCompleteOptions::IncludeComments,
Ilya Biryukov71028b82018-03-12 15:28:22 +0000330 &clangd::CodeCompleteOptions::IncludeCodePatterns,
331 &clangd::CodeCompleteOptions::IncludeIneligibleResults,
Sam McCall2c3849a2018-01-16 12:21:24 +0000332 };
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 McCall44fdcec22017-12-08 15:00:59 +0000343TEST(CompletionTest, Priorities) {
344 auto Internal = completions(R"cpp(
345 class Foo {
346 public: void pub();
347 protected: void prot();
348 private: void priv();
349 };
350 void Foo::pub() { this->^ }
351 )cpp");
Sam McCalle746a2b2018-07-02 11:13:16 +0000352 EXPECT_THAT(Internal.Completions,
Sam McCall44fdcec22017-12-08 15:00:59 +0000353 HasSubsequence(Named("priv"), Named("prot"), Named("pub")));
354
355 auto External = completions(R"cpp(
356 class Foo {
357 public: void pub();
358 protected: void prot();
359 private: void priv();
360 };
361 void test() {
362 Foo F;
363 F.^
364 }
365 )cpp");
Sam McCalle746a2b2018-07-02 11:13:16 +0000366 EXPECT_THAT(External.Completions,
Sam McCall44fdcec22017-12-08 15:00:59 +0000367 AllOf(Has("pub"), Not(Has("prot")), Not(Has("priv"))));
368}
369
370TEST(CompletionTest, Qualifiers) {
371 auto Results = completions(R"cpp(
372 class Foo {
373 public: int foo() const;
374 int bar() const;
375 };
376 class Bar : public Foo {
377 int foo() const;
378 };
379 void test() { Bar().^ }
380 )cpp");
Sam McCalle746a2b2018-07-02 11:13:16 +0000381 EXPECT_THAT(Results.Completions,
382 HasSubsequence(AllOf(Qualifier(""), Named("bar")),
383 AllOf(Qualifier("Foo::"), Named("foo"))));
384 EXPECT_THAT(Results.Completions,
385 Not(Contains(AllOf(Qualifier(""), Named("foo"))))); // private
Sam McCall44fdcec22017-12-08 15:00:59 +0000386}
387
Sam McCall4caa8512018-06-07 12:49:17 +0000388TEST(CompletionTest, InjectedTypename) {
389 // These are suppressed when accessed as a member...
Sam McCalle746a2b2018-07-02 11:13:16 +0000390 EXPECT_THAT(completions("struct X{}; void foo(){ X().^ }").Completions,
Sam McCall4caa8512018-06-07 12:49:17 +0000391 Not(Has("X")));
Sam McCalle746a2b2018-07-02 11:13:16 +0000392 EXPECT_THAT(completions("struct X{ void foo(){ this->^ } };").Completions,
Sam McCall4caa8512018-06-07 12:49:17 +0000393 Not(Has("X")));
394 // ...but accessible in other, more useful cases.
Sam McCalle746a2b2018-07-02 11:13:16 +0000395 EXPECT_THAT(completions("struct X{ void foo(){ ^ } };").Completions,
396 Has("X"));
397 EXPECT_THAT(
398 completions("struct Y{}; struct X:Y{ void foo(){ ^ } };").Completions,
399 Has("Y"));
Sam McCall4caa8512018-06-07 12:49:17 +0000400 EXPECT_THAT(
401 completions(
402 "template<class> struct Y{}; struct X:Y<int>{ void foo(){ ^ } };")
Sam McCalle746a2b2018-07-02 11:13:16 +0000403 .Completions,
Sam McCall4caa8512018-06-07 12:49:17 +0000404 Has("Y"));
405 // This case is marginal (`using X::X` is useful), we allow it for now.
Sam McCalle746a2b2018-07-02 11:13:16 +0000406 EXPECT_THAT(completions("struct X{}; void foo(){ X::^ }").Completions,
407 Has("X"));
Sam McCall4caa8512018-06-07 12:49:17 +0000408}
409
Sam McCall44fdcec22017-12-08 15:00:59 +0000410TEST(CompletionTest, Snippets) {
411 clangd::CodeCompleteOptions Opts;
Sam McCall44fdcec22017-12-08 15:00:59 +0000412 auto Results = completions(
413 R"cpp(
414 struct fake {
415 int a;
416 int f(int i, const float f) const;
417 };
418 int main() {
419 fake f;
420 f.^
421 }
422 )cpp",
Sam McCalla15c2d62018-01-18 09:27:56 +0000423 /*IndexSymbols=*/{}, Opts);
Sam McCalle746a2b2018-07-02 11:13:16 +0000424 EXPECT_THAT(
425 Results.Completions,
426 HasSubsequence(Named("a"),
427 SnippetSuffix("(${1:int i}, ${2:const float f})")));
Sam McCall44fdcec22017-12-08 15:00:59 +0000428}
429
430TEST(CompletionTest, Kinds) {
Sam McCall545a20d2018-01-19 14:34:02 +0000431 auto Results = completions(
432 R"cpp(
433 #define MACRO X
434 int variable;
435 struct Struct {};
436 int function();
437 int X = ^
438 )cpp",
439 {func("indexFunction"), var("indexVariable"), cls("indexClass")});
Sam McCalle746a2b2018-07-02 11:13:16 +0000440 EXPECT_THAT(Results.Completions,
Sam McCall545a20d2018-01-19 14:34:02 +0000441 AllOf(Has("function", CompletionItemKind::Function),
442 Has("variable", CompletionItemKind::Variable),
443 Has("int", CompletionItemKind::Keyword),
444 Has("Struct", CompletionItemKind::Class),
445 Has("MACRO", CompletionItemKind::Text),
446 Has("indexFunction", CompletionItemKind::Function),
447 Has("indexVariable", CompletionItemKind::Variable),
448 Has("indexClass", CompletionItemKind::Class)));
Sam McCall44fdcec22017-12-08 15:00:59 +0000449
Sam McCall44fdcec22017-12-08 15:00:59 +0000450 Results = completions("nam^");
Sam McCalle746a2b2018-07-02 11:13:16 +0000451 EXPECT_THAT(Results.Completions,
452 Has("namespace", CompletionItemKind::Snippet));
Sam McCall44fdcec22017-12-08 15:00:59 +0000453}
454
Sam McCall84652cc2018-01-12 16:16:09 +0000455TEST(CompletionTest, NoDuplicates) {
Sam McCall545a20d2018-01-19 14:34:02 +0000456 auto Results = completions(
457 R"cpp(
458 class Adapter {
Sam McCall545a20d2018-01-19 14:34:02 +0000459 };
Sam McCall84652cc2018-01-12 16:16:09 +0000460
Eric Liu9b3cba72018-05-30 09:03:39 +0000461 void f() {
Sam McCall545a20d2018-01-19 14:34:02 +0000462 Adapter^
463 }
464 )cpp",
465 {cls("Adapter")});
Sam McCall84652cc2018-01-12 16:16:09 +0000466
467 // Make sure there are no duplicate entries of 'Adapter'.
Sam McCalle746a2b2018-07-02 11:13:16 +0000468 EXPECT_THAT(Results.Completions, ElementsAre(Named("Adapter")));
Sam McCall84652cc2018-01-12 16:16:09 +0000469}
470
Sam McCall545a20d2018-01-19 14:34:02 +0000471TEST(CompletionTest, ScopedNoIndex) {
472 auto Results = completions(
473 R"cpp(
Sam McCall8b2dcc12018-06-14 13:50:30 +0000474 namespace fake { int BigBang, Babble, Box; };
475 int main() { fake::ba^ }
Sam McCall545a20d2018-01-19 14:34:02 +0000476 ")cpp");
Sam McCall8b2dcc12018-06-14 13:50:30 +0000477 // Babble is a better match than BigBang. Box doesn't match at all.
Sam McCalle746a2b2018-07-02 11:13:16 +0000478 EXPECT_THAT(Results.Completions,
479 ElementsAre(Named("Babble"), Named("BigBang")));
Sam McCall84652cc2018-01-12 16:16:09 +0000480}
481
Sam McCall545a20d2018-01-19 14:34:02 +0000482TEST(CompletionTest, Scoped) {
Sam McCalla15c2d62018-01-18 09:27:56 +0000483 auto Results = completions(
484 R"cpp(
Sam McCall8b2dcc12018-06-14 13:50:30 +0000485 namespace fake { int Babble, Box; };
486 int main() { fake::ba^ }
Sam McCall545a20d2018-01-19 14:34:02 +0000487 ")cpp",
488 {var("fake::BigBang")});
Sam McCalle746a2b2018-07-02 11:13:16 +0000489 EXPECT_THAT(Results.Completions,
490 ElementsAre(Named("Babble"), Named("BigBang")));
Sam McCalla15c2d62018-01-18 09:27:56 +0000491}
492
Sam McCall545a20d2018-01-19 14:34:02 +0000493TEST(CompletionTest, ScopedWithFilter) {
Sam McCalla15c2d62018-01-18 09:27:56 +0000494 auto Results = completions(
495 R"cpp(
496 void f() { ns::x^ }
497 )cpp",
498 {cls("ns::XYZ"), func("ns::foo")});
Sam McCalle746a2b2018-07-02 11:13:16 +0000499 EXPECT_THAT(Results.Completions, UnorderedElementsAre(Named("XYZ")));
Sam McCalla15c2d62018-01-18 09:27:56 +0000500}
501
Sam McCalldc8abc42018-05-03 14:53:02 +0000502TEST(CompletionTest, ReferencesAffectRanking) {
Eric Liu84bd5db2018-07-25 11:26:35 +0000503 auto Results = completions("int main() { abs^ }", {ns("absl"), func("absb")});
504 EXPECT_THAT(Results.Completions, HasSubsequence(Named("absb"), Named("absl")));
Sam McCalldc8abc42018-05-03 14:53:02 +0000505 Results = completions("int main() { abs^ }",
Eric Liu84bd5db2018-07-25 11:26:35 +0000506 {withReferences(10000, ns("absl")), func("absb")});
507 EXPECT_THAT(Results.Completions,
508 HasSubsequence(Named("absl"), Named("absb")));
Sam McCalldc8abc42018-05-03 14:53:02 +0000509}
510
Sam McCall545a20d2018-01-19 14:34:02 +0000511TEST(CompletionTest, GlobalQualified) {
Sam McCalla15c2d62018-01-18 09:27:56 +0000512 auto Results = completions(
513 R"cpp(
514 void f() { ::^ }
515 )cpp",
516 {cls("XYZ")});
Sam McCalle746a2b2018-07-02 11:13:16 +0000517 EXPECT_THAT(Results.Completions,
518 AllOf(Has("XYZ", CompletionItemKind::Class),
519 Has("f", CompletionItemKind::Function)));
Sam McCalla15c2d62018-01-18 09:27:56 +0000520}
521
Sam McCall545a20d2018-01-19 14:34:02 +0000522TEST(CompletionTest, FullyQualified) {
Sam McCalla15c2d62018-01-18 09:27:56 +0000523 auto Results = completions(
524 R"cpp(
Sam McCall545a20d2018-01-19 14:34:02 +0000525 namespace ns { void bar(); }
Sam McCalla15c2d62018-01-18 09:27:56 +0000526 void f() { ::ns::^ }
527 )cpp",
528 {cls("ns::XYZ")});
Sam McCalle746a2b2018-07-02 11:13:16 +0000529 EXPECT_THAT(Results.Completions,
530 AllOf(Has("XYZ", CompletionItemKind::Class),
531 Has("bar", CompletionItemKind::Function)));
Sam McCall545a20d2018-01-19 14:34:02 +0000532}
533
534TEST(CompletionTest, SemaIndexMerge) {
535 auto Results = completions(
536 R"cpp(
537 namespace ns { int local; void both(); }
538 void f() { ::ns::^ }
539 )cpp",
540 {func("ns::both"), cls("ns::Index")});
541 // We get results from both index and sema, with no duplicates.
Sam McCall2161ec72018-07-05 06:20:41 +0000542 EXPECT_THAT(Results.Completions,
543 UnorderedElementsAre(
544 AllOf(Named("local"), Origin(SymbolOrigin::AST)),
545 AllOf(Named("Index"), Origin(SymbolOrigin::Static)),
546 AllOf(Named("both"),
547 Origin(SymbolOrigin::AST | SymbolOrigin::Static))));
Sam McCalla15c2d62018-01-18 09:27:56 +0000548}
549
Haojian Wu48b48652018-01-25 09:20:09 +0000550TEST(CompletionTest, SemaIndexMergeWithLimit) {
551 clangd::CodeCompleteOptions Opts;
552 Opts.Limit = 1;
553 auto Results = completions(
554 R"cpp(
555 namespace ns { int local; void both(); }
556 void f() { ::ns::^ }
557 )cpp",
558 {func("ns::both"), cls("ns::Index")}, Opts);
Sam McCalle746a2b2018-07-02 11:13:16 +0000559 EXPECT_EQ(Results.Completions.size(), Opts.Limit);
560 EXPECT_TRUE(Results.HasMore);
Haojian Wu48b48652018-01-25 09:20:09 +0000561}
562
Eric Liu63f419a2018-05-15 15:29:32 +0000563TEST(CompletionTest, IncludeInsertionPreprocessorIntegrationTests) {
564 MockFSProvider FS;
565 MockCompilationDatabase CDB;
566 std::string Subdir = testPath("sub");
567 std::string SearchDirArg = (llvm::Twine("-I") + Subdir).str();
568 CDB.ExtraClangFlags = {SearchDirArg.c_str()};
569 std::string BarHeader = testPath("sub/bar.h");
570 FS.Files[BarHeader] = "";
571
572 IgnoreDiagnostics DiagConsumer;
573 ClangdServer Server(CDB, FS, DiagConsumer, ClangdServer::optsForTest());
Eric Liu63f419a2018-05-15 15:29:32 +0000574 auto BarURI = URI::createFile(BarHeader).toString();
575 Symbol Sym = cls("ns::X");
576 Sym.CanonicalDeclaration.FileURI = BarURI;
Eric Liu83f63e42018-09-03 10:18:21 +0000577 Sym.IncludeHeaders.emplace_back(BarURI, 1);
Eric Liu63f419a2018-05-15 15:29:32 +0000578 // Shoten include path based on search dirctory and insert.
579 auto Results = completions(Server,
580 R"cpp(
581 int main() { ns::^ }
582 )cpp",
583 {Sym});
Sam McCalle746a2b2018-07-02 11:13:16 +0000584 EXPECT_THAT(Results.Completions,
585 ElementsAre(AllOf(Named("X"), InsertInclude("\"bar.h\""))));
Eric Liu63f419a2018-05-15 15:29:32 +0000586 // Duplicate based on inclusions in preamble.
587 Results = completions(Server,
588 R"cpp(
589 #include "sub/bar.h" // not shortest, so should only match resolved.
590 int main() { ns::^ }
591 )cpp",
592 {Sym});
Sam McCalle746a2b2018-07-02 11:13:16 +0000593 EXPECT_THAT(Results.Completions, ElementsAre(AllOf(Named("X"), Labeled("X"),
594 Not(InsertInclude()))));
Eric Liu63f419a2018-05-15 15:29:32 +0000595}
596
Eric Liu9b3cba72018-05-30 09:03:39 +0000597TEST(CompletionTest, NoIncludeInsertionWhenDeclFoundInFile) {
598 MockFSProvider FS;
599 MockCompilationDatabase CDB;
600
601 IgnoreDiagnostics DiagConsumer;
602 ClangdServer Server(CDB, FS, DiagConsumer, ClangdServer::optsForTest());
Eric Liu9b3cba72018-05-30 09:03:39 +0000603 Symbol SymX = cls("ns::X");
604 Symbol SymY = cls("ns::Y");
605 std::string BarHeader = testPath("bar.h");
606 auto BarURI = URI::createFile(BarHeader).toString();
607 SymX.CanonicalDeclaration.FileURI = BarURI;
608 SymY.CanonicalDeclaration.FileURI = BarURI;
Eric Liu83f63e42018-09-03 10:18:21 +0000609 SymX.IncludeHeaders.emplace_back("<bar>", 1);
610 SymY.IncludeHeaders.emplace_back("<bar>", 1);
Eric Liu9b3cba72018-05-30 09:03:39 +0000611 // Shoten include path based on search dirctory and insert.
612 auto Results = completions(Server,
613 R"cpp(
614 namespace ns {
615 class X;
616 class Y {}
617 }
618 int main() { ns::^ }
619 )cpp",
620 {SymX, SymY});
Sam McCalle746a2b2018-07-02 11:13:16 +0000621 EXPECT_THAT(Results.Completions,
622 ElementsAre(AllOf(Named("X"), Not(InsertInclude())),
623 AllOf(Named("Y"), Not(InsertInclude()))));
Eric Liu9b3cba72018-05-30 09:03:39 +0000624}
625
Sam McCalla15c2d62018-01-18 09:27:56 +0000626TEST(CompletionTest, IndexSuppressesPreambleCompletions) {
627 MockFSProvider FS;
628 MockCompilationDatabase CDB;
629 IgnoreDiagnostics DiagConsumer;
Sam McCall7363a2f2018-03-05 17:28:54 +0000630 ClangdServer Server(CDB, FS, DiagConsumer, ClangdServer::optsForTest());
Sam McCalla15c2d62018-01-18 09:27:56 +0000631
Sam McCallc1568062018-02-16 09:41:43 +0000632 FS.Files[testPath("bar.h")] =
Sam McCalld5ea3e32018-01-24 17:53:32 +0000633 R"cpp(namespace ns { struct preamble { int member; }; })cpp";
Sam McCallc1568062018-02-16 09:41:43 +0000634 auto File = testPath("foo.cpp");
Sam McCalla15c2d62018-01-18 09:27:56 +0000635 Annotations Test(R"cpp(
636 #include "bar.h"
637 namespace ns { int local; }
Sam McCalld5ea3e32018-01-24 17:53:32 +0000638 void f() { ns::^; }
639 void f() { ns::preamble().$2^; }
Sam McCalla15c2d62018-01-18 09:27:56 +0000640 )cpp");
Sam McCall7363a2f2018-03-05 17:28:54 +0000641 runAddDocument(Server, File, Test.code());
Sam McCalla15c2d62018-01-18 09:27:56 +0000642 clangd::CodeCompleteOptions Opts = {};
643
Sam McCalla15c2d62018-01-18 09:27:56 +0000644 auto I = memIndex({var("ns::index")});
645 Opts.Index = I.get();
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000646 auto WithIndex = cantFail(runCodeComplete(Server, File, Test.point(), Opts));
Sam McCalle746a2b2018-07-02 11:13:16 +0000647 EXPECT_THAT(WithIndex.Completions,
Sam McCalla15c2d62018-01-18 09:27:56 +0000648 UnorderedElementsAre(Named("local"), Named("index")));
Sam McCalld5ea3e32018-01-24 17:53:32 +0000649 auto ClassFromPreamble =
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000650 cantFail(runCodeComplete(Server, File, Test.point("2"), Opts));
Sam McCalle746a2b2018-07-02 11:13:16 +0000651 EXPECT_THAT(ClassFromPreamble.Completions, Contains(Named("member")));
Sam McCall0bb24cd2018-02-13 08:59:23 +0000652
653 Opts.Index = nullptr;
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000654 auto WithoutIndex =
655 cantFail(runCodeComplete(Server, File, Test.point(), Opts));
Sam McCalle746a2b2018-07-02 11:13:16 +0000656 EXPECT_THAT(WithoutIndex.Completions,
Sam McCall0bb24cd2018-02-13 08:59:23 +0000657 UnorderedElementsAre(Named("local"), Named("preamble")));
Sam McCalla15c2d62018-01-18 09:27:56 +0000658}
659
660TEST(CompletionTest, DynamicIndexMultiFile) {
661 MockFSProvider FS;
662 MockCompilationDatabase CDB;
663 IgnoreDiagnostics DiagConsumer;
Sam McCall7363a2f2018-03-05 17:28:54 +0000664 auto Opts = ClangdServer::optsForTest();
665 Opts.BuildDynamicSymbolIndex = true;
666 ClangdServer Server(CDB, FS, DiagConsumer, Opts);
Sam McCalla15c2d62018-01-18 09:27:56 +0000667
Eric Liu709bde82018-02-19 18:48:44 +0000668 FS.Files[testPath("foo.h")] = R"cpp(
Sam McCalla15c2d62018-01-18 09:27:56 +0000669 namespace ns { class XYZ {}; void foo(int x) {} }
Eric Liu709bde82018-02-19 18:48:44 +0000670 )cpp";
Sam McCall7363a2f2018-03-05 17:28:54 +0000671 runAddDocument(Server, testPath("foo.cpp"), R"cpp(
Eric Liu709bde82018-02-19 18:48:44 +0000672 #include "foo.h"
Sam McCall0bb24cd2018-02-13 08:59:23 +0000673 )cpp");
Sam McCalla15c2d62018-01-18 09:27:56 +0000674
Sam McCallc1568062018-02-16 09:41:43 +0000675 auto File = testPath("bar.cpp");
Sam McCalla15c2d62018-01-18 09:27:56 +0000676 Annotations Test(R"cpp(
677 namespace ns {
678 class XXX {};
679 /// Doooc
680 void fooooo() {}
681 }
682 void f() { ns::^ }
683 )cpp");
Sam McCall7363a2f2018-03-05 17:28:54 +0000684 runAddDocument(Server, File, Test.code());
Sam McCalla15c2d62018-01-18 09:27:56 +0000685
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000686 auto Results = cantFail(runCodeComplete(Server, File, Test.point(), {}));
Sam McCalla15c2d62018-01-18 09:27:56 +0000687 // "XYZ" and "foo" are not included in the file being completed but are still
688 // visible through the index.
Sam McCalle746a2b2018-07-02 11:13:16 +0000689 EXPECT_THAT(Results.Completions, Has("XYZ", CompletionItemKind::Class));
690 EXPECT_THAT(Results.Completions, Has("foo", CompletionItemKind::Function));
691 EXPECT_THAT(Results.Completions, Has("XXX", CompletionItemKind::Class));
692 EXPECT_THAT(Results.Completions,
693 Contains((Named("fooooo"), Kind(CompletionItemKind::Function),
694 Doc("Doooc"), ReturnType("void"))));
Sam McCalla15c2d62018-01-18 09:27:56 +0000695}
696
Ilya Biryukovc22d3442018-05-16 12:32:49 +0000697TEST(CompletionTest, Documentation) {
698 auto Results = completions(
699 R"cpp(
700 // Non-doxygen comment.
701 int foo();
702 /// Doxygen comment.
703 /// \param int a
704 int bar(int a);
705 /* Multi-line
706 block comment
707 */
708 int baz();
709
710 int x = ^
711 )cpp");
Sam McCalle746a2b2018-07-02 11:13:16 +0000712 EXPECT_THAT(Results.Completions,
Ilya Biryukovc22d3442018-05-16 12:32:49 +0000713 Contains(AllOf(Named("foo"), Doc("Non-doxygen comment."))));
714 EXPECT_THAT(
Sam McCalle746a2b2018-07-02 11:13:16 +0000715 Results.Completions,
Ilya Biryukovc22d3442018-05-16 12:32:49 +0000716 Contains(AllOf(Named("bar"), Doc("Doxygen comment.\n\\param int a"))));
Sam McCalle746a2b2018-07-02 11:13:16 +0000717 EXPECT_THAT(Results.Completions,
Ilya Biryukovc22d3442018-05-16 12:32:49 +0000718 Contains(AllOf(Named("baz"), Doc("Multi-line\nblock comment"))));
719}
720
Marc-Andre Laperle945b5a32018-06-05 14:01:40 +0000721TEST(CompletionTest, GlobalCompletionFiltering) {
722
723 Symbol Class = cls("XYZ");
Eric Liu6df66002018-09-06 18:52:26 +0000724 Class.Flags = static_cast<Symbol::SymbolFlag>(
725 Class.Flags & ~(Symbol::IndexedForCodeCompletion));
Marc-Andre Laperle945b5a32018-06-05 14:01:40 +0000726 Symbol Func = func("XYZ::foooo");
Eric Liu6df66002018-09-06 18:52:26 +0000727 Func.Flags = static_cast<Symbol::SymbolFlag>(
728 Func.Flags & ~(Symbol::IndexedForCodeCompletion));
Marc-Andre Laperle945b5a32018-06-05 14:01:40 +0000729
730 auto Results = completions(R"(// void f() {
731 XYZ::foooo^
732 })",
733 {Class, Func});
Sam McCalle746a2b2018-07-02 11:13:16 +0000734 EXPECT_THAT(Results.Completions, IsEmpty());
Marc-Andre Laperle945b5a32018-06-05 14:01:40 +0000735}
736
Haojian Wu58d208d2018-01-25 09:44:06 +0000737TEST(CodeCompleteTest, DisableTypoCorrection) {
738 auto Results = completions(R"cpp(
739 namespace clang { int v; }
740 void f() { clangd::^
741 )cpp");
Sam McCalle746a2b2018-07-02 11:13:16 +0000742 EXPECT_TRUE(Results.Completions.empty());
Haojian Wu58d208d2018-01-25 09:44:06 +0000743}
744
Ilya Biryukov53d6d932018-03-06 16:45:21 +0000745TEST(CodeCompleteTest, NoColonColonAtTheEnd) {
746 auto Results = completions(R"cpp(
747 namespace clang { }
748 void f() {
749 clan^
750 }
751 )cpp");
752
Sam McCalle746a2b2018-07-02 11:13:16 +0000753 EXPECT_THAT(Results.Completions, Contains(Labeled("clang")));
754 EXPECT_THAT(Results.Completions, Not(Contains(Labeled("clang::"))));
Ilya Biryukov53d6d932018-03-06 16:45:21 +0000755}
756
Ilya Biryukov94da7bd2018-03-16 15:23:44 +0000757TEST(CompletionTest, BacktrackCrashes) {
758 // Sema calls code completion callbacks twice in these cases.
759 auto Results = completions(R"cpp(
760 namespace ns {
761 struct FooBarBaz {};
762 } // namespace ns
763
764 int foo(ns::FooBar^
765 )cpp");
766
Sam McCalle746a2b2018-07-02 11:13:16 +0000767 EXPECT_THAT(Results.Completions, ElementsAre(Labeled("FooBarBaz")));
Ilya Biryukov94da7bd2018-03-16 15:23:44 +0000768
769 // Check we don't crash in that case too.
770 completions(R"cpp(
771 struct FooBarBaz {};
772 void test() {
773 if (FooBarBaz * x^) {}
774 }
775)cpp");
776}
777
Eric Liu42abe412018-05-24 11:20:19 +0000778TEST(CompletionTest, CompleteInMacroWithStringification) {
779 auto Results = completions(R"cpp(
780void f(const char *, int x);
781#define F(x) f(#x, x)
782
783namespace ns {
784int X;
785int Y;
786} // namespace ns
787
788int f(int input_num) {
789 F(ns::^)
790}
791)cpp");
792
Sam McCalle746a2b2018-07-02 11:13:16 +0000793 EXPECT_THAT(Results.Completions,
Eric Liu42abe412018-05-24 11:20:19 +0000794 UnorderedElementsAre(Named("X"), Named("Y")));
795}
796
797TEST(CompletionTest, CompleteInMacroAndNamespaceWithStringification) {
798 auto Results = completions(R"cpp(
799void f(const char *, int x);
800#define F(x) f(#x, x)
801
802namespace ns {
803int X;
804
805int f(int input_num) {
806 F(^)
807}
808} // namespace ns
809)cpp");
810
Sam McCalle746a2b2018-07-02 11:13:16 +0000811 EXPECT_THAT(Results.Completions, Contains(Named("X")));
Eric Liu42abe412018-05-24 11:20:19 +0000812}
813
Eric Liu485074f2018-07-11 13:15:31 +0000814TEST(CompletionTest, IgnoreCompleteInExcludedPPBranchWithRecoveryContext) {
Ilya Biryukov94da7bd2018-03-16 15:23:44 +0000815 auto Results = completions(R"cpp(
816 int bar(int param_in_bar) {
817 }
818
819 int foo(int param_in_foo) {
820#if 0
Eric Liu485074f2018-07-11 13:15:31 +0000821 // In recorvery mode, "param_in_foo" will also be suggested among many other
822 // unrelated symbols; however, this is really a special case where this works.
823 // If the #if block is outside of the function, "param_in_foo" is still
824 // suggested, but "bar" and "foo" are missing. So the recovery mode doesn't
825 // really provide useful results in excluded branches.
Ilya Biryukov94da7bd2018-03-16 15:23:44 +0000826 par^
827#endif
828 }
829)cpp");
830
Eric Liu485074f2018-07-11 13:15:31 +0000831 EXPECT_TRUE(Results.Completions.empty());
Ilya Biryukov94da7bd2018-03-16 15:23:44 +0000832}
Ilya Biryukov43c292c2018-08-30 13:14:31 +0000833SignatureHelp signatures(StringRef Text, Position Point,
Ilya Biryukov8a0f76b2018-08-17 09:32:30 +0000834 std::vector<Symbol> IndexSymbols = {}) {
835 std::unique_ptr<SymbolIndex> Index;
836 if (!IndexSymbols.empty())
837 Index = memIndex(IndexSymbols);
838
Sam McCall800d4372017-12-19 10:29:27 +0000839 MockFSProvider FS;
840 MockCompilationDatabase CDB;
841 IgnoreDiagnostics DiagConsumer;
Ilya Biryukov8a0f76b2018-08-17 09:32:30 +0000842 ClangdServer::Options Opts = ClangdServer::optsForTest();
843 Opts.StaticIndex = Index.get();
844
845 ClangdServer Server(CDB, FS, DiagConsumer, Opts);
Sam McCallc1568062018-02-16 09:41:43 +0000846 auto File = testPath("foo.cpp");
Ilya Biryukov43c292c2018-08-30 13:14:31 +0000847 runAddDocument(Server, File, Text);
848 return cantFail(runSignatureHelp(Server, File, Point));
849}
850
851SignatureHelp signatures(StringRef Text,
852 std::vector<Symbol> IndexSymbols = {}) {
Sam McCall328cbdb2017-12-20 16:06:05 +0000853 Annotations Test(Text);
Ilya Biryukov43c292c2018-08-30 13:14:31 +0000854 return signatures(Test.code(), Test.point(), std::move(IndexSymbols));
Sam McCall800d4372017-12-19 10:29:27 +0000855}
856
857MATCHER_P(ParamsAre, P, "") {
858 if (P.size() != arg.parameters.size())
859 return false;
860 for (unsigned I = 0; I < P.size(); ++I)
861 if (P[I] != arg.parameters[I].label)
862 return false;
863 return true;
864}
Ilya Biryukov8a0f76b2018-08-17 09:32:30 +0000865MATCHER_P(SigDoc, Doc, "") { return arg.documentation == Doc; }
Sam McCall800d4372017-12-19 10:29:27 +0000866
867Matcher<SignatureInformation> Sig(std::string Label,
868 std::vector<std::string> Params) {
Eric Liu8f3678d2018-06-15 13:34:18 +0000869 return AllOf(SigHelpLabeled(Label), ParamsAre(Params));
Sam McCall800d4372017-12-19 10:29:27 +0000870}
871
872TEST(SignatureHelpTest, Overloads) {
873 auto Results = signatures(R"cpp(
874 void foo(int x, int y);
875 void foo(int x, float y);
876 void foo(float x, int y);
877 void foo(float x, float y);
878 void bar(int x, int y = 0);
879 int main() { foo(^); }
880 )cpp");
881 EXPECT_THAT(Results.signatures,
882 UnorderedElementsAre(
883 Sig("foo(float x, float y) -> void", {"float x", "float y"}),
884 Sig("foo(float x, int y) -> void", {"float x", "int y"}),
885 Sig("foo(int x, float y) -> void", {"int x", "float y"}),
886 Sig("foo(int x, int y) -> void", {"int x", "int y"})));
887 // We always prefer the first signature.
888 EXPECT_EQ(0, Results.activeSignature);
889 EXPECT_EQ(0, Results.activeParameter);
890}
891
892TEST(SignatureHelpTest, DefaultArgs) {
893 auto Results = signatures(R"cpp(
894 void bar(int x, int y = 0);
895 void bar(float x = 0, int y = 42);
896 int main() { bar(^
897 )cpp");
898 EXPECT_THAT(Results.signatures,
899 UnorderedElementsAre(
900 Sig("bar(int x, int y = 0) -> void", {"int x", "int y = 0"}),
901 Sig("bar(float x = 0, int y = 42) -> void",
902 {"float x = 0", "int y = 42"})));
903 EXPECT_EQ(0, Results.activeSignature);
904 EXPECT_EQ(0, Results.activeParameter);
905}
906
907TEST(SignatureHelpTest, ActiveArg) {
908 auto Results = signatures(R"cpp(
909 int baz(int a, int b, int c);
910 int main() { baz(baz(1,2,3), ^); }
911 )cpp");
912 EXPECT_THAT(Results.signatures,
913 ElementsAre(Sig("baz(int a, int b, int c) -> int",
914 {"int a", "int b", "int c"})));
915 EXPECT_EQ(0, Results.activeSignature);
916 EXPECT_EQ(1, Results.activeParameter);
917}
918
Ilya Biryukov43c292c2018-08-30 13:14:31 +0000919TEST(SignatureHelpTest, OpeningParen) {
920 llvm::StringLiteral Tests[] = {// Recursive function call.
921 R"cpp(
922 int foo(int a, int b, int c);
923 int main() {
924 foo(foo $p^( foo(10, 10, 10), ^ )));
925 })cpp",
926 // Functional type cast.
927 R"cpp(
928 struct Foo {
929 Foo(int a, int b, int c);
930 };
931 int main() {
932 Foo $p^( 10, ^ );
933 })cpp",
934 // New expression.
935 R"cpp(
936 struct Foo {
937 Foo(int a, int b, int c);
938 };
939 int main() {
940 new Foo $p^( 10, ^ );
941 })cpp",
942 // Macro expansion.
943 R"cpp(
944 int foo(int a, int b, int c);
945 #define FOO foo(
946
947 int main() {
948 // Macro expansions.
949 $p^FOO 10, ^ );
950 })cpp",
951 // Macro arguments.
952 R"cpp(
953 int foo(int a, int b, int c);
954 int main() {
955 #define ID(X) X
956 ID(foo $p^( foo(10), ^ ))
957 })cpp"};
958
959 for (auto Test : Tests) {
960 Annotations Code(Test);
961 EXPECT_EQ(signatures(Code.code(), Code.point()).argListStart,
962 Code.point("p"))
963 << "Test source:" << Test;
964 }
965}
966
Haojian Wu061c73e2018-01-23 11:37:26 +0000967class IndexRequestCollector : public SymbolIndex {
968public:
969 bool
Sam McCalld1a7a372018-01-31 13:40:48 +0000970 fuzzyFind(const FuzzyFindRequest &Req,
Haojian Wu061c73e2018-01-23 11:37:26 +0000971 llvm::function_ref<void(const Symbol &)> Callback) const override {
Ilya Biryukov5c4d6e62018-09-06 11:04:56 +0000972 std::lock_guard<std::mutex> Lock(Mut);
Haojian Wu061c73e2018-01-23 11:37:26 +0000973 Requests.push_back(Req);
Sam McCallab8e3932018-02-19 13:04:41 +0000974 return true;
Haojian Wu061c73e2018-01-23 11:37:26 +0000975 }
976
Eric Liu9ec459f2018-03-14 09:48:05 +0000977 void lookup(const LookupRequest &,
978 llvm::function_ref<void(const Symbol &)>) const override {}
979
Sam McCallb0138312018-09-04 14:39:56 +0000980 void refs(const RefsRequest &,
981 llvm::function_ref<void(const Ref &)>) const override {}
Haojian Wu65ac3212018-08-06 13:14:32 +0000982
Kirill Bobyrevfc890012018-08-24 09:12:54 +0000983 // This is incorrect, but IndexRequestCollector is not an actual index and it
984 // isn't used in production code.
985 size_t estimateMemoryUsage() const override { return 0; }
986
Eric Liu25d74e92018-08-24 11:23:56 +0000987 const std::vector<FuzzyFindRequest> consumeRequests() const {
Ilya Biryukov5c4d6e62018-09-06 11:04:56 +0000988 std::lock_guard<std::mutex> Lock(Mut);
Eric Liu25d74e92018-08-24 11:23:56 +0000989 auto Reqs = std::move(Requests);
990 Requests = {};
991 return Reqs;
992 }
Haojian Wu061c73e2018-01-23 11:37:26 +0000993
994private:
Ilya Biryukov5c4d6e62018-09-06 11:04:56 +0000995 // We need a mutex to handle async fuzzy find requests.
996 mutable std::mutex Mut;
Haojian Wu061c73e2018-01-23 11:37:26 +0000997 mutable std::vector<FuzzyFindRequest> Requests;
998};
999
1000std::vector<FuzzyFindRequest> captureIndexRequests(llvm::StringRef Code) {
1001 clangd::CodeCompleteOptions Opts;
1002 IndexRequestCollector Requests;
1003 Opts.Index = &Requests;
1004 completions(Code, {}, Opts);
Eric Liu25d74e92018-08-24 11:23:56 +00001005 return Requests.consumeRequests();
Haojian Wu061c73e2018-01-23 11:37:26 +00001006}
1007
1008TEST(CompletionTest, UnqualifiedIdQuery) {
1009 auto Requests = captureIndexRequests(R"cpp(
1010 namespace std {}
1011 using namespace std;
1012 namespace ns {
1013 void f() {
1014 vec^
1015 }
1016 }
1017 )cpp");
1018
1019 EXPECT_THAT(Requests,
1020 ElementsAre(Field(&FuzzyFindRequest::Scopes,
1021 UnorderedElementsAre("", "ns::", "std::"))));
1022}
1023
1024TEST(CompletionTest, ResolvedQualifiedIdQuery) {
1025 auto Requests = captureIndexRequests(R"cpp(
1026 namespace ns1 {}
1027 namespace ns2 {} // ignore
1028 namespace ns3 { namespace nns3 {} }
1029 namespace foo {
1030 using namespace ns1;
1031 using namespace ns3::nns3;
1032 }
1033 namespace ns {
1034 void f() {
1035 foo::^
1036 }
1037 }
1038 )cpp");
1039
1040 EXPECT_THAT(Requests,
1041 ElementsAre(Field(
1042 &FuzzyFindRequest::Scopes,
1043 UnorderedElementsAre("foo::", "ns1::", "ns3::nns3::"))));
1044}
1045
1046TEST(CompletionTest, UnresolvedQualifierIdQuery) {
1047 auto Requests = captureIndexRequests(R"cpp(
1048 namespace a {}
1049 using namespace a;
1050 namespace ns {
1051 void f() {
1052 bar::^
1053 }
1054 } // namespace ns
1055 )cpp");
1056
1057 EXPECT_THAT(Requests, ElementsAre(Field(&FuzzyFindRequest::Scopes,
1058 UnorderedElementsAre("bar::"))));
1059}
1060
1061TEST(CompletionTest, UnresolvedNestedQualifierIdQuery) {
1062 auto Requests = captureIndexRequests(R"cpp(
1063 namespace a {}
1064 using namespace a;
1065 namespace ns {
1066 void f() {
1067 ::a::bar::^
1068 }
1069 } // namespace ns
1070 )cpp");
1071
1072 EXPECT_THAT(Requests, ElementsAre(Field(&FuzzyFindRequest::Scopes,
1073 UnorderedElementsAre("a::bar::"))));
1074}
1075
1076TEST(CompletionTest, EmptyQualifiedQuery) {
1077 auto Requests = captureIndexRequests(R"cpp(
1078 namespace ns {
1079 void f() {
1080 ^
1081 }
1082 } // namespace ns
1083 )cpp");
1084
1085 EXPECT_THAT(Requests, ElementsAre(Field(&FuzzyFindRequest::Scopes,
1086 UnorderedElementsAre("", "ns::"))));
1087}
1088
1089TEST(CompletionTest, GlobalQualifiedQuery) {
1090 auto Requests = captureIndexRequests(R"cpp(
1091 namespace ns {
1092 void f() {
1093 ::^
1094 }
1095 } // namespace ns
1096 )cpp");
1097
1098 EXPECT_THAT(Requests, ElementsAre(Field(&FuzzyFindRequest::Scopes,
1099 UnorderedElementsAre(""))));
1100}
1101
Ilya Biryukova907ba42018-05-14 10:50:04 +00001102TEST(CompletionTest, NoIndexCompletionsInsideClasses) {
1103 auto Completions = completions(
1104 R"cpp(
1105 struct Foo {
1106 int SomeNameOfField;
1107 typedef int SomeNameOfTypedefField;
1108 };
1109
1110 Foo::^)cpp",
1111 {func("::SomeNameInTheIndex"), func("::Foo::SomeNameInTheIndex")});
1112
Sam McCalle746a2b2018-07-02 11:13:16 +00001113 EXPECT_THAT(Completions.Completions,
Ilya Biryukova907ba42018-05-14 10:50:04 +00001114 AllOf(Contains(Labeled("SomeNameOfField")),
1115 Contains(Labeled("SomeNameOfTypedefField")),
1116 Not(Contains(Labeled("SomeNameInTheIndex")))));
1117}
1118
1119TEST(CompletionTest, NoIndexCompletionsInsideDependentCode) {
1120 {
1121 auto Completions = completions(
1122 R"cpp(
1123 template <class T>
1124 void foo() {
1125 T::^
1126 }
1127 )cpp",
1128 {func("::SomeNameInTheIndex")});
1129
Sam McCalle746a2b2018-07-02 11:13:16 +00001130 EXPECT_THAT(Completions.Completions,
Ilya Biryukova907ba42018-05-14 10:50:04 +00001131 Not(Contains(Labeled("SomeNameInTheIndex"))));
1132 }
1133
1134 {
1135 auto Completions = completions(
1136 R"cpp(
1137 template <class T>
1138 void foo() {
1139 T::template Y<int>::^
1140 }
1141 )cpp",
1142 {func("::SomeNameInTheIndex")});
1143
Sam McCalle746a2b2018-07-02 11:13:16 +00001144 EXPECT_THAT(Completions.Completions,
Ilya Biryukova907ba42018-05-14 10:50:04 +00001145 Not(Contains(Labeled("SomeNameInTheIndex"))));
1146 }
1147
1148 {
1149 auto Completions = completions(
1150 R"cpp(
1151 template <class T>
1152 void foo() {
1153 T::foo::^
1154 }
1155 )cpp",
1156 {func("::SomeNameInTheIndex")});
1157
Sam McCalle746a2b2018-07-02 11:13:16 +00001158 EXPECT_THAT(Completions.Completions,
Ilya Biryukova907ba42018-05-14 10:50:04 +00001159 Not(Contains(Labeled("SomeNameInTheIndex"))));
1160 }
1161}
1162
Sam McCallc18c2802018-06-15 11:06:29 +00001163TEST(CompletionTest, OverloadBundling) {
1164 clangd::CodeCompleteOptions Opts;
1165 Opts.BundleOverloads = true;
1166
1167 std::string Context = R"cpp(
1168 struct X {
1169 // Overload with int
1170 int a(int);
1171 // Overload with bool
1172 int a(bool);
1173 int b(float);
1174 };
1175 int GFuncC(int);
1176 int GFuncD(int);
1177 )cpp";
1178
1179 // Member completions are bundled.
Sam McCalle746a2b2018-07-02 11:13:16 +00001180 EXPECT_THAT(completions(Context + "int y = X().^", {}, Opts).Completions,
Sam McCallc18c2802018-06-15 11:06:29 +00001181 UnorderedElementsAre(Labeled("a(…)"), Labeled("b(float)")));
1182
1183 // Non-member completions are bundled, including index+sema.
1184 Symbol NoArgsGFunc = func("GFuncC");
1185 EXPECT_THAT(
Sam McCalle746a2b2018-07-02 11:13:16 +00001186 completions(Context + "int y = GFunc^", {NoArgsGFunc}, Opts).Completions,
Sam McCallc18c2802018-06-15 11:06:29 +00001187 UnorderedElementsAre(Labeled("GFuncC(…)"), Labeled("GFuncD(int)")));
1188
1189 // Differences in header-to-insert suppress bundling.
Sam McCallc18c2802018-06-15 11:06:29 +00001190 std::string DeclFile = URI::createFile(testPath("foo")).toString();
1191 NoArgsGFunc.CanonicalDeclaration.FileURI = DeclFile;
Eric Liu83f63e42018-09-03 10:18:21 +00001192 NoArgsGFunc.IncludeHeaders.emplace_back("<foo>", 1);
Sam McCallc18c2802018-06-15 11:06:29 +00001193 EXPECT_THAT(
Sam McCalle746a2b2018-07-02 11:13:16 +00001194 completions(Context + "int y = GFunc^", {NoArgsGFunc}, Opts).Completions,
1195 UnorderedElementsAre(AllOf(Named("GFuncC"), InsertInclude("<foo>")),
1196 Labeled("GFuncC(int)"), Labeled("GFuncD(int)")));
Sam McCallc18c2802018-06-15 11:06:29 +00001197
1198 // Examine a bundled completion in detail.
Sam McCalle746a2b2018-07-02 11:13:16 +00001199 auto A =
1200 completions(Context + "int y = X().a^", {}, Opts).Completions.front();
1201 EXPECT_EQ(A.Name, "a");
1202 EXPECT_EQ(A.Signature, "(…)");
1203 EXPECT_EQ(A.BundleSize, 2u);
1204 EXPECT_EQ(A.Kind, CompletionItemKind::Method);
1205 EXPECT_EQ(A.ReturnType, "int"); // All overloads return int.
Sam McCallc18c2802018-06-15 11:06:29 +00001206 // For now we just return one of the doc strings arbitrarily.
Sam McCalle746a2b2018-07-02 11:13:16 +00001207 EXPECT_THAT(A.Documentation, AnyOf(HasSubstr("Overload with int"),
Sam McCallc18c2802018-06-15 11:06:29 +00001208 HasSubstr("Overload with bool")));
Kadir Cetinkaya516fcda2018-08-23 12:19:39 +00001209 EXPECT_EQ(A.SnippetSuffix, "($0)");
Sam McCallc18c2802018-06-15 11:06:29 +00001210}
1211
Ilya Biryukov30b04b12018-05-28 09:54:51 +00001212TEST(CompletionTest, DocumentationFromChangedFileCrash) {
Ilya Biryukovbe0eb8f2018-05-24 14:49:23 +00001213 MockFSProvider FS;
1214 auto FooH = testPath("foo.h");
1215 auto FooCpp = testPath("foo.cpp");
1216 FS.Files[FooH] = R"cpp(
1217 // this is my documentation comment.
1218 int func();
1219 )cpp";
1220 FS.Files[FooCpp] = "";
1221
1222 MockCompilationDatabase CDB;
1223 IgnoreDiagnostics DiagConsumer;
1224 ClangdServer Server(CDB, FS, DiagConsumer, ClangdServer::optsForTest());
1225
1226 Annotations Source(R"cpp(
1227 #include "foo.h"
1228 int func() {
1229 // This makes sure we have func from header in the AST.
1230 }
1231 int a = fun^
1232 )cpp");
1233 Server.addDocument(FooCpp, Source.code(), WantDiagnostics::Yes);
1234 // We need to wait for preamble to build.
1235 ASSERT_TRUE(Server.blockUntilIdleForTest());
1236
1237 // Change the header file. Completion will reuse the old preamble!
1238 FS.Files[FooH] = R"cpp(
1239 int func();
1240 )cpp";
1241
1242 clangd::CodeCompleteOptions Opts;
1243 Opts.IncludeComments = true;
Sam McCalle746a2b2018-07-02 11:13:16 +00001244 CodeCompleteResult Completions =
Ilya Biryukovbe0eb8f2018-05-24 14:49:23 +00001245 cantFail(runCodeComplete(Server, FooCpp, Source.point(), Opts));
1246 // We shouldn't crash. Unfortunately, current workaround is to not produce
1247 // comments for symbols from headers.
Sam McCalle746a2b2018-07-02 11:13:16 +00001248 EXPECT_THAT(Completions.Completions,
Ilya Biryukovbe0eb8f2018-05-24 14:49:23 +00001249 Contains(AllOf(Not(IsDocumented()), Named("func"))));
1250}
1251
Ilya Biryukov89fcf6b2018-06-15 08:31:17 +00001252TEST(CompletionTest, NonDocComments) {
1253 MockFSProvider FS;
1254 auto FooCpp = testPath("foo.cpp");
1255 FS.Files[FooCpp] = "";
1256
1257 MockCompilationDatabase CDB;
1258 IgnoreDiagnostics DiagConsumer;
1259 ClangdServer Server(CDB, FS, DiagConsumer, ClangdServer::optsForTest());
1260
1261 Annotations Source(R"cpp(
Ilya Biryukovda8dd8b2018-06-27 09:47:20 +00001262 // We ignore namespace comments, for rationale see CodeCompletionStrings.h.
1263 namespace comments_ns {
1264 }
1265
Ilya Biryukov89fcf6b2018-06-15 08:31:17 +00001266 // ------------------
1267 int comments_foo();
1268
1269 // A comment and a decl are separated by newlines.
1270 // Therefore, the comment shouldn't show up as doc comment.
1271
1272 int comments_bar();
1273
1274 // this comment should be in the results.
1275 int comments_baz();
1276
1277
1278 template <class T>
1279 struct Struct {
1280 int comments_qux();
1281 int comments_quux();
1282 };
1283
1284
1285 // This comment should not be there.
1286
1287 template <class T>
1288 int Struct<T>::comments_qux() {
1289 }
1290
1291 // This comment **should** be in results.
1292 template <class T>
1293 int Struct<T>::comments_quux() {
1294 int a = comments^;
1295 }
1296 )cpp");
Reid Kleckner80274b12018-06-18 18:55:10 +00001297 // FIXME: Auto-completion in a template requires disabling delayed template
1298 // parsing.
1299 CDB.ExtraClangFlags.push_back("-fno-delayed-template-parsing");
Ilya Biryukov89fcf6b2018-06-15 08:31:17 +00001300 Server.addDocument(FooCpp, Source.code(), WantDiagnostics::Yes);
Sam McCalle746a2b2018-07-02 11:13:16 +00001301 CodeCompleteResult Completions = cantFail(runCodeComplete(
Ilya Biryukov89fcf6b2018-06-15 08:31:17 +00001302 Server, FooCpp, Source.point(), clangd::CodeCompleteOptions()));
1303
1304 // We should not get any of those comments in completion.
1305 EXPECT_THAT(
Sam McCalle746a2b2018-07-02 11:13:16 +00001306 Completions.Completions,
Ilya Biryukov89fcf6b2018-06-15 08:31:17 +00001307 UnorderedElementsAre(AllOf(Not(IsDocumented()), Named("comments_foo")),
1308 AllOf(IsDocumented(), Named("comments_baz")),
1309 AllOf(IsDocumented(), Named("comments_quux")),
Ilya Biryukovda8dd8b2018-06-27 09:47:20 +00001310 AllOf(Not(IsDocumented()), Named("comments_ns")),
Ilya Biryukov89fcf6b2018-06-15 08:31:17 +00001311 // FIXME(ibiryukov): the following items should have
1312 // empty documentation, since they are separated from
1313 // a comment with an empty line. Unfortunately, I
1314 // couldn't make Sema tests pass if we ignore those.
1315 AllOf(IsDocumented(), Named("comments_bar")),
1316 AllOf(IsDocumented(), Named("comments_qux"))));
1317}
1318
Ilya Biryukov981a35d2018-05-28 12:11:37 +00001319TEST(CompletionTest, CompleteOnInvalidLine) {
1320 auto FooCpp = testPath("foo.cpp");
1321
1322 MockCompilationDatabase CDB;
1323 IgnoreDiagnostics DiagConsumer;
1324 MockFSProvider FS;
1325 FS.Files[FooCpp] = "// empty file";
1326
1327 ClangdServer Server(CDB, FS, DiagConsumer, ClangdServer::optsForTest());
1328 // Run completion outside the file range.
1329 Position Pos;
1330 Pos.line = 100;
1331 Pos.character = 0;
1332 EXPECT_THAT_EXPECTED(
1333 runCodeComplete(Server, FooCpp, Pos, clangd::CodeCompleteOptions()),
1334 Failed());
1335}
1336
Eric Liu7ad16962018-06-22 10:46:59 +00001337TEST(CompletionTest, QualifiedNames) {
1338 auto Results = completions(
1339 R"cpp(
1340 namespace ns { int local; void both(); }
1341 void f() { ::ns::^ }
1342 )cpp",
1343 {func("ns::both"), cls("ns::Index")});
1344 // We get results from both index and sema, with no duplicates.
Sam McCalle746a2b2018-07-02 11:13:16 +00001345 EXPECT_THAT(
1346 Results.Completions,
1347 UnorderedElementsAre(Scope("ns::"), Scope("ns::"), Scope("ns::")));
1348}
1349
1350TEST(CompletionTest, Render) {
1351 CodeCompletion C;
1352 C.Name = "x";
1353 C.Signature = "(bool) const";
1354 C.SnippetSuffix = "(${0:bool})";
1355 C.ReturnType = "int";
1356 C.RequiredQualifier = "Foo::";
1357 C.Scope = "ns::Foo::";
1358 C.Documentation = "This is x().";
Eric Liu83f63e42018-09-03 10:18:21 +00001359 C.Includes.emplace_back();
1360 auto &Include = C.Includes.back();
1361 Include.Header = "\"foo.h\"";
Sam McCalle746a2b2018-07-02 11:13:16 +00001362 C.Kind = CompletionItemKind::Method;
1363 C.Score.Total = 1.0;
Sam McCall4e5742a2018-07-06 11:50:49 +00001364 C.Origin = SymbolOrigin::AST | SymbolOrigin::Static;
Sam McCalle746a2b2018-07-02 11:13:16 +00001365
1366 CodeCompleteOptions Opts;
1367 Opts.IncludeIndicator.Insert = "^";
1368 Opts.IncludeIndicator.NoInsert = "";
1369 Opts.EnableSnippets = false;
1370
1371 auto R = C.render(Opts);
1372 EXPECT_EQ(R.label, "Foo::x(bool) const");
1373 EXPECT_EQ(R.insertText, "Foo::x");
1374 EXPECT_EQ(R.insertTextFormat, InsertTextFormat::PlainText);
1375 EXPECT_EQ(R.filterText, "x");
1376 EXPECT_EQ(R.detail, "int\n\"foo.h\"");
1377 EXPECT_EQ(R.documentation, "This is x().");
1378 EXPECT_THAT(R.additionalTextEdits, IsEmpty());
Sam McCalle746a2b2018-07-02 11:13:16 +00001379 EXPECT_EQ(R.sortText, sortText(1.0, "x"));
Eric Liu6df66002018-09-06 18:52:26 +00001380 EXPECT_FALSE(R.deprecated);
Sam McCalle746a2b2018-07-02 11:13:16 +00001381
1382 Opts.EnableSnippets = true;
1383 R = C.render(Opts);
1384 EXPECT_EQ(R.insertText, "Foo::x(${0:bool})");
1385 EXPECT_EQ(R.insertTextFormat, InsertTextFormat::Snippet);
1386
Eric Liu83f63e42018-09-03 10:18:21 +00001387 Include.Insertion.emplace();
Sam McCalle746a2b2018-07-02 11:13:16 +00001388 R = C.render(Opts);
1389 EXPECT_EQ(R.label, "^Foo::x(bool) const");
1390 EXPECT_THAT(R.additionalTextEdits, Not(IsEmpty()));
1391
Sam McCall2161ec72018-07-05 06:20:41 +00001392 Opts.ShowOrigins = true;
1393 R = C.render(Opts);
1394 EXPECT_EQ(R.label, "^[AS]Foo::x(bool) const");
1395
Sam McCalle746a2b2018-07-02 11:13:16 +00001396 C.BundleSize = 2;
1397 R = C.render(Opts);
1398 EXPECT_EQ(R.detail, "[2 overloads]\n\"foo.h\"");
Eric Liu6df66002018-09-06 18:52:26 +00001399
1400 C.Deprecated = true;
1401 R = C.render(Opts);
1402 EXPECT_TRUE(R.deprecated);
Eric Liu7ad16962018-06-22 10:46:59 +00001403}
Ilya Biryukov981a35d2018-05-28 12:11:37 +00001404
Eric Liu485074f2018-07-11 13:15:31 +00001405TEST(CompletionTest, IgnoreRecoveryResults) {
1406 auto Results = completions(
1407 R"cpp(
1408 namespace ns { int NotRecovered() { return 0; } }
1409 void f() {
1410 // Sema enters recovery mode first and then normal mode.
1411 if (auto x = ns::NotRecover^)
1412 }
1413 )cpp");
1414 EXPECT_THAT(Results.Completions, UnorderedElementsAre(Named("NotRecovered")));
1415}
1416
Eric Liuf433c2d2018-07-18 15:31:14 +00001417TEST(CompletionTest, ScopeOfClassFieldInConstructorInitializer) {
1418 auto Results = completions(
1419 R"cpp(
1420 namespace ns {
1421 class X { public: X(); int x_; };
1422 X::X() : x_^(0) {}
1423 }
1424 )cpp");
1425 EXPECT_THAT(Results.Completions,
1426 UnorderedElementsAre(AllOf(Scope("ns::X::"), Named("x_"))));
1427}
1428
Eric Liu5d2a8072018-07-23 10:56:37 +00001429TEST(CompletionTest, CodeCompletionContext) {
1430 auto Results = completions(
1431 R"cpp(
1432 namespace ns {
1433 class X { public: X(); int x_; };
1434 void f() {
1435 X x;
1436 x.^;
1437 }
1438 }
1439 )cpp");
1440
1441 EXPECT_THAT(Results.Context, CodeCompletionContext::CCC_DotMemberAccess);
1442}
1443
Kadir Cetinkaya2f84d912018-08-08 08:59:29 +00001444TEST(CompletionTest, FixItForArrowToDot) {
1445 MockFSProvider FS;
1446 MockCompilationDatabase CDB;
1447 IgnoreDiagnostics DiagConsumer;
1448 ClangdServer Server(CDB, FS, DiagConsumer, ClangdServer::optsForTest());
1449
1450 CodeCompleteOptions Opts;
1451 Opts.IncludeFixIts = true;
1452 Annotations TestCode(
1453 R"cpp(
1454 class Auxilary {
1455 public:
1456 void AuxFunction();
1457 };
1458 class ClassWithPtr {
1459 public:
1460 void MemberFunction();
1461 Auxilary* operator->() const;
1462 Auxilary* Aux;
1463 };
1464 void f() {
1465 ClassWithPtr x;
1466 x[[->]]^;
1467 }
1468 )cpp");
1469 auto Results =
1470 completions(Server, TestCode.code(), TestCode.point(), {}, Opts);
1471 EXPECT_EQ(Results.Completions.size(), 3u);
1472
1473 TextEdit ReplacementEdit;
1474 ReplacementEdit.range = TestCode.range();
1475 ReplacementEdit.newText = ".";
1476 for (const auto &C : Results.Completions) {
1477 EXPECT_TRUE(C.FixIts.size() == 1u || C.Name == "AuxFunction");
Haojian Wu1793bc92018-08-10 08:34:16 +00001478 if (!C.FixIts.empty()) {
Kadir Cetinkaya2f84d912018-08-08 08:59:29 +00001479 EXPECT_THAT(C.FixIts, ElementsAre(ReplacementEdit));
Haojian Wu1793bc92018-08-10 08:34:16 +00001480 }
Kadir Cetinkaya2f84d912018-08-08 08:59:29 +00001481 }
1482}
1483
1484TEST(CompletionTest, FixItForDotToArrow) {
1485 MockFSProvider FS;
1486 MockCompilationDatabase CDB;
1487 IgnoreDiagnostics DiagConsumer;
1488 ClangdServer Server(CDB, FS, DiagConsumer, ClangdServer::optsForTest());
1489
1490 CodeCompleteOptions Opts;
1491 Opts.IncludeFixIts = true;
1492 Annotations TestCode(
1493 R"cpp(
1494 class Auxilary {
1495 public:
1496 void AuxFunction();
1497 };
1498 class ClassWithPtr {
1499 public:
1500 void MemberFunction();
1501 Auxilary* operator->() const;
1502 Auxilary* Aux;
1503 };
1504 void f() {
1505 ClassWithPtr x;
1506 x[[.]]^;
1507 }
1508 )cpp");
1509 auto Results =
1510 completions(Server, TestCode.code(), TestCode.point(), {}, Opts);
1511 EXPECT_EQ(Results.Completions.size(), 3u);
1512
1513 TextEdit ReplacementEdit;
1514 ReplacementEdit.range = TestCode.range();
1515 ReplacementEdit.newText = "->";
1516 for (const auto &C : Results.Completions) {
1517 EXPECT_TRUE(C.FixIts.empty() || C.Name == "AuxFunction");
1518 if (!C.FixIts.empty()) {
1519 EXPECT_THAT(C.FixIts, ElementsAre(ReplacementEdit));
1520 }
1521 }
1522}
1523
Kadir Cetinkayaa9c9d002018-08-13 08:23:01 +00001524TEST(CompletionTest, RenderWithFixItMerged) {
1525 TextEdit FixIt;
1526 FixIt.range.end.character = 5;
1527 FixIt.newText = "->";
1528
1529 CodeCompletion C;
1530 C.Name = "x";
1531 C.RequiredQualifier = "Foo::";
1532 C.FixIts = {FixIt};
1533 C.CompletionTokenRange.start.character = 5;
1534
1535 CodeCompleteOptions Opts;
1536 Opts.IncludeFixIts = true;
1537
1538 auto R = C.render(Opts);
1539 EXPECT_TRUE(R.textEdit);
1540 EXPECT_EQ(R.textEdit->newText, "->Foo::x");
1541 EXPECT_TRUE(R.additionalTextEdits.empty());
1542}
1543
1544TEST(CompletionTest, RenderWithFixItNonMerged) {
1545 TextEdit FixIt;
1546 FixIt.range.end.character = 4;
1547 FixIt.newText = "->";
1548
1549 CodeCompletion C;
1550 C.Name = "x";
1551 C.RequiredQualifier = "Foo::";
1552 C.FixIts = {FixIt};
1553 C.CompletionTokenRange.start.character = 5;
1554
1555 CodeCompleteOptions Opts;
1556 Opts.IncludeFixIts = true;
1557
1558 auto R = C.render(Opts);
1559 EXPECT_TRUE(R.textEdit);
1560 EXPECT_EQ(R.textEdit->newText, "Foo::x");
1561 EXPECT_THAT(R.additionalTextEdits, UnorderedElementsAre(FixIt));
1562}
1563
1564TEST(CompletionTest, CompletionTokenRange) {
1565 MockFSProvider FS;
1566 MockCompilationDatabase CDB;
1567 IgnoreDiagnostics DiagConsumer;
1568 ClangdServer Server(CDB, FS, DiagConsumer, ClangdServer::optsForTest());
1569
1570 constexpr const char *TestCodes[] = {
1571 R"cpp(
1572 class Auxilary {
1573 public:
1574 void AuxFunction();
1575 };
1576 void f() {
1577 Auxilary x;
1578 x.[[Aux]]^;
1579 }
1580 )cpp",
1581 R"cpp(
1582 class Auxilary {
1583 public:
1584 void AuxFunction();
1585 };
1586 void f() {
1587 Auxilary x;
1588 x.[[]]^;
1589 }
1590 )cpp"};
1591 for (const auto &Text : TestCodes) {
1592 Annotations TestCode(Text);
1593 auto Results = completions(Server, TestCode.code(), TestCode.point());
1594
1595 EXPECT_EQ(Results.Completions.size(), 1u);
1596 EXPECT_THAT(Results.Completions.front().CompletionTokenRange, TestCode.range());
1597 }
1598}
1599
Kadir Cetinkayae486e372018-08-13 08:40:05 +00001600TEST(SignatureHelpTest, OverloadsOrdering) {
1601 const auto Results = signatures(R"cpp(
1602 void foo(int x);
1603 void foo(int x, float y);
1604 void foo(float x, int y);
1605 void foo(float x, float y);
1606 void foo(int x, int y = 0);
1607 int main() { foo(^); }
1608 )cpp");
1609 EXPECT_THAT(
1610 Results.signatures,
1611 ElementsAre(
1612 Sig("foo(int x) -> void", {"int x"}),
1613 Sig("foo(int x, int y = 0) -> void", {"int x", "int y = 0"}),
1614 Sig("foo(float x, int y) -> void", {"float x", "int y"}),
1615 Sig("foo(int x, float y) -> void", {"int x", "float y"}),
1616 Sig("foo(float x, float y) -> void", {"float x", "float y"})));
1617 // We always prefer the first signature.
1618 EXPECT_EQ(0, Results.activeSignature);
1619 EXPECT_EQ(0, Results.activeParameter);
1620}
1621
Ilya Biryukov8fd44bb2018-08-14 09:36:32 +00001622TEST(SignatureHelpTest, InstantiatedSignatures) {
Simon Pilgrim83552ee2018-08-16 11:41:19 +00001623 StringRef Sig0 = R"cpp(
Ilya Biryukov8fd44bb2018-08-14 09:36:32 +00001624 template <class T>
1625 void foo(T, T, T);
1626
1627 int main() {
1628 foo<int>(^);
1629 }
Simon Pilgrim83552ee2018-08-16 11:41:19 +00001630 )cpp";
1631
1632 EXPECT_THAT(signatures(Sig0).signatures,
Ilya Biryukov8fd44bb2018-08-14 09:36:32 +00001633 ElementsAre(Sig("foo(T, T, T) -> void", {"T", "T", "T"})));
1634
Simon Pilgrim83552ee2018-08-16 11:41:19 +00001635 StringRef Sig1 = R"cpp(
Ilya Biryukov8fd44bb2018-08-14 09:36:32 +00001636 template <class T>
1637 void foo(T, T, T);
1638
1639 int main() {
1640 foo(10, ^);
Simon Pilgrim83552ee2018-08-16 11:41:19 +00001641 })cpp";
1642
1643 EXPECT_THAT(signatures(Sig1).signatures,
Ilya Biryukov8fd44bb2018-08-14 09:36:32 +00001644 ElementsAre(Sig("foo(T, T, T) -> void", {"T", "T", "T"})));
1645
Simon Pilgrim83552ee2018-08-16 11:41:19 +00001646 StringRef Sig2 = R"cpp(
Ilya Biryukov8fd44bb2018-08-14 09:36:32 +00001647 template <class ...T>
1648 void foo(T...);
1649
1650 int main() {
1651 foo<int>(^);
1652 }
Simon Pilgrim83552ee2018-08-16 11:41:19 +00001653 )cpp";
1654
1655 EXPECT_THAT(signatures(Sig2).signatures,
Ilya Biryukov8fd44bb2018-08-14 09:36:32 +00001656 ElementsAre(Sig("foo(T...) -> void", {"T..."})));
1657
1658 // It is debatable whether we should substitute the outer template parameter
1659 // ('T') in that case. Currently we don't substitute it in signature help, but
1660 // do substitute in code complete.
1661 // FIXME: make code complete and signature help consistent, figure out which
1662 // way is better.
Simon Pilgrim83552ee2018-08-16 11:41:19 +00001663 StringRef Sig3 = R"cpp(
Ilya Biryukov8fd44bb2018-08-14 09:36:32 +00001664 template <class T>
1665 struct X {
1666 template <class U>
1667 void foo(T, U);
1668 };
1669
1670 int main() {
1671 X<int>().foo<double>(^)
1672 }
Simon Pilgrim83552ee2018-08-16 11:41:19 +00001673 )cpp";
1674
1675 EXPECT_THAT(signatures(Sig3).signatures,
Ilya Biryukov8fd44bb2018-08-14 09:36:32 +00001676 ElementsAre(Sig("foo(T, U) -> void", {"T", "U"})));
1677}
1678
Ilya Biryukov8a0f76b2018-08-17 09:32:30 +00001679TEST(SignatureHelpTest, IndexDocumentation) {
Ilya Biryukov8a0f76b2018-08-17 09:32:30 +00001680 Symbol Foo0 = sym("foo", index::SymbolKind::Function, "@F@\\0#");
Sam McCall2e5700f2018-08-31 13:55:01 +00001681 Foo0.Documentation = "Doc from the index";
Ilya Biryukov8a0f76b2018-08-17 09:32:30 +00001682 Symbol Foo1 = sym("foo", index::SymbolKind::Function, "@F@\\0#I#");
Sam McCall2e5700f2018-08-31 13:55:01 +00001683 Foo1.Documentation = "Doc from the index";
Ilya Biryukov8a0f76b2018-08-17 09:32:30 +00001684 Symbol Foo2 = sym("foo", index::SymbolKind::Function, "@F@\\0#I#I#");
1685
Simon Pilgrim24d34922018-08-17 10:40:05 +00001686 StringRef Sig0 = R"cpp(
Ilya Biryukov8a0f76b2018-08-17 09:32:30 +00001687 int foo();
1688 int foo(double);
1689
1690 void test() {
1691 foo(^);
1692 }
Simon Pilgrim24d34922018-08-17 10:40:05 +00001693 )cpp";
1694
1695 EXPECT_THAT(
1696 signatures(Sig0, {Foo0}).signatures,
Ilya Biryukov8a0f76b2018-08-17 09:32:30 +00001697 ElementsAre(AllOf(Sig("foo() -> int", {}), SigDoc("Doc from the index")),
1698 AllOf(Sig("foo(double) -> int", {"double"}), SigDoc(""))));
1699
Simon Pilgrim24d34922018-08-17 10:40:05 +00001700 StringRef Sig1 = R"cpp(
Ilya Biryukov8a0f76b2018-08-17 09:32:30 +00001701 int foo();
1702 // Overriden doc from sema
1703 int foo(int);
1704 // Doc from sema
1705 int foo(int, int);
1706
1707 void test() {
1708 foo(^);
1709 }
Simon Pilgrim24d34922018-08-17 10:40:05 +00001710 )cpp";
1711
1712 EXPECT_THAT(
1713 signatures(Sig1, {Foo0, Foo1, Foo2}).signatures,
Ilya Biryukov8a0f76b2018-08-17 09:32:30 +00001714 ElementsAre(AllOf(Sig("foo() -> int", {}), SigDoc("Doc from the index")),
1715 AllOf(Sig("foo(int) -> int", {"int"}),
1716 SigDoc("Overriden doc from sema")),
1717 AllOf(Sig("foo(int, int) -> int", {"int", "int"}),
1718 SigDoc("Doc from sema"))));
1719}
1720
Kadir Cetinkaya516fcda2018-08-23 12:19:39 +00001721TEST(CompletionTest, CompletionFunctionArgsDisabled) {
Kadir Cetinkaya6c9f15c2018-08-17 15:42:54 +00001722 CodeCompleteOptions Opts;
Kadir Cetinkaya6c9f15c2018-08-17 15:42:54 +00001723 Opts.EnableSnippets = true;
1724 Opts.EnableFunctionArgSnippets = false;
Kadir Cetinkaya516fcda2018-08-23 12:19:39 +00001725 const std::string Header =
1726 R"cpp(
1727 void xfoo();
1728 void xfoo(int x, int y);
1729 void xbar();
1730 void f() {
1731 )cpp";
Kadir Cetinkaya6c9f15c2018-08-17 15:42:54 +00001732 {
Kadir Cetinkaya516fcda2018-08-23 12:19:39 +00001733 auto Results = completions(Header + "\nxfo^", {}, Opts);
1734 EXPECT_THAT(
1735 Results.Completions,
1736 UnorderedElementsAre(AllOf(Named("xfoo"), SnippetSuffix("()")),
1737 AllOf(Named("xfoo"), SnippetSuffix("($0)"))));
Kadir Cetinkaya6c9f15c2018-08-17 15:42:54 +00001738 }
Kadir Cetinkaya6c9f15c2018-08-17 15:42:54 +00001739 {
Kadir Cetinkaya516fcda2018-08-23 12:19:39 +00001740 auto Results = completions(Header + "\nxba^", {}, Opts);
1741 EXPECT_THAT(Results.Completions, UnorderedElementsAre(AllOf(
1742 Named("xbar"), SnippetSuffix("()"))));
Kadir Cetinkaya6c9f15c2018-08-17 15:42:54 +00001743 }
Kadir Cetinkaya6c9f15c2018-08-17 15:42:54 +00001744 {
Kadir Cetinkaya516fcda2018-08-23 12:19:39 +00001745 Opts.BundleOverloads = true;
1746 auto Results = completions(Header + "\nxfo^", {}, Opts);
1747 EXPECT_THAT(
1748 Results.Completions,
1749 UnorderedElementsAre(AllOf(Named("xfoo"), SnippetSuffix("($0)"))));
Kadir Cetinkaya6c9f15c2018-08-17 15:42:54 +00001750 }
1751}
1752
Kadir Cetinkayaf8b85a32018-08-23 13:14:50 +00001753TEST(CompletionTest, SuggestOverrides) {
1754 constexpr const char *const Text(R"cpp(
1755 class A {
1756 public:
1757 virtual void vfunc(bool param);
1758 virtual void vfunc(bool param, int p);
1759 void func(bool param);
1760 };
1761 class B : public A {
1762 virtual void ttt(bool param) const;
1763 void vfunc(bool param, int p) override;
1764 };
1765 class C : public B {
1766 public:
1767 void vfunc(bool param) override;
1768 ^
1769 };
1770 )cpp");
1771 const auto Results = completions(Text);
1772 EXPECT_THAT(Results.Completions,
1773 AllOf(Contains(Labeled("void vfunc(bool param, int p) override")),
1774 Contains(Labeled("void ttt(bool param) const override")),
1775 Not(Contains(Labeled("void vfunc(bool param) override")))));
1776}
1777
Ilya Biryukov5a79d1e2018-09-03 15:25:27 +00001778TEST(CompletionTest, OverridesNonIdentName) {
1779 // Check the completions call does not crash.
1780 completions(R"cpp(
1781 struct Base {
1782 virtual ~Base() = 0;
1783 virtual operator int() = 0;
1784 virtual Base& operator+(Base&) = 0;
1785 };
1786
1787 struct Derived : Base {
1788 ^
1789 };
1790 )cpp");
1791}
1792
Eric Liu25d74e92018-08-24 11:23:56 +00001793TEST(SpeculateCompletionFilter, Filters) {
1794 Annotations F(R"cpp($bof^
1795 $bol^
1796 ab$ab^
1797 x.ab$dot^
1798 x.$dotempty^
1799 x::ab$scoped^
1800 x::$scopedempty^
1801
1802 )cpp");
1803 auto speculate = [&](StringRef PointName) {
1804 auto Filter = speculateCompletionFilter(F.code(), F.point(PointName));
1805 assert(Filter);
1806 return *Filter;
1807 };
1808 EXPECT_EQ(speculate("bof"), "");
1809 EXPECT_EQ(speculate("bol"), "");
1810 EXPECT_EQ(speculate("ab"), "ab");
1811 EXPECT_EQ(speculate("dot"), "ab");
1812 EXPECT_EQ(speculate("dotempty"), "");
1813 EXPECT_EQ(speculate("scoped"), "ab");
1814 EXPECT_EQ(speculate("scopedempty"), "");
1815}
1816
1817TEST(CompletionTest, EnableSpeculativeIndexRequest) {
1818 MockFSProvider FS;
1819 MockCompilationDatabase CDB;
1820 IgnoreDiagnostics DiagConsumer;
1821 ClangdServer Server(CDB, FS, DiagConsumer, ClangdServer::optsForTest());
1822
1823 auto File = testPath("foo.cpp");
1824 Annotations Test(R"cpp(
1825 namespace ns1 { int abc; }
1826 namespace ns2 { int abc; }
1827 void f() { ns1::ab$1^; ns1::ab$2^; }
1828 void f() { ns2::ab$3^; }
1829 )cpp");
1830 runAddDocument(Server, File, Test.code());
1831 clangd::CodeCompleteOptions Opts = {};
1832
1833 IndexRequestCollector Requests;
1834 Opts.Index = &Requests;
1835 Opts.SpeculativeIndexRequest = true;
1836
1837 auto CompleteAtPoint = [&](StringRef P) {
1838 cantFail(runCodeComplete(Server, File, Test.point(P), Opts));
1839 // Sleep for a while to make sure asynchronous call (if applicable) is also
1840 // triggered before callback is invoked.
1841 std::this_thread::sleep_for(std::chrono::milliseconds(100));
1842 };
1843
1844 CompleteAtPoint("1");
1845 auto Reqs1 = Requests.consumeRequests();
1846 ASSERT_EQ(Reqs1.size(), 1u);
1847 EXPECT_THAT(Reqs1[0].Scopes, UnorderedElementsAre("ns1::"));
1848
1849 CompleteAtPoint("2");
1850 auto Reqs2 = Requests.consumeRequests();
1851 // Speculation succeeded. Used speculative index result.
1852 ASSERT_EQ(Reqs2.size(), 1u);
1853 EXPECT_EQ(Reqs2[0], Reqs1[0]);
1854
1855 CompleteAtPoint("3");
1856 // Speculation failed. Sent speculative index request and the new index
1857 // request after sema.
1858 auto Reqs3 = Requests.consumeRequests();
1859 ASSERT_EQ(Reqs3.size(), 2u);
1860}
1861
Eric Liu83f63e42018-09-03 10:18:21 +00001862TEST(CompletionTest, InsertTheMostPopularHeader) {
1863 std::string DeclFile = URI::createFile(testPath("foo")).toString();
1864 Symbol sym = func("Func");
1865 sym.CanonicalDeclaration.FileURI = DeclFile;
1866 sym.IncludeHeaders.emplace_back("\"foo.h\"", 2);
1867 sym.IncludeHeaders.emplace_back("\"bar.h\"", 1000);
1868
1869 auto Results = completions("Fun^", {sym}).Completions;
1870 assert(!Results.empty());
1871 EXPECT_THAT(Results[0], AllOf(Named("Func"), InsertInclude("\"bar.h\"")));
1872 EXPECT_EQ(Results[0].Includes.size(), 2u);
1873}
1874
1875TEST(CompletionTest, NoInsertIncludeIfOnePresent) {
1876 MockFSProvider FS;
1877 MockCompilationDatabase CDB;
1878
1879 std::string FooHeader = testPath("foo.h");
1880 FS.Files[FooHeader] = "";
1881
1882 IgnoreDiagnostics DiagConsumer;
1883 ClangdServer Server(CDB, FS, DiagConsumer, ClangdServer::optsForTest());
1884
1885 std::string DeclFile = URI::createFile(testPath("foo")).toString();
1886 Symbol sym = func("Func");
1887 sym.CanonicalDeclaration.FileURI = DeclFile;
1888 sym.IncludeHeaders.emplace_back("\"foo.h\"", 2);
1889 sym.IncludeHeaders.emplace_back("\"bar.h\"", 1000);
1890
1891 EXPECT_THAT(
1892 completions(Server, "#include \"foo.h\"\nFun^", {sym}).Completions,
1893 UnorderedElementsAre(
1894 AllOf(Named("Func"), HasInclude("\"foo.h\""), Not(InsertInclude()))));
1895}
1896
Eric Liud25f1212018-09-06 09:59:37 +00001897TEST(CompletionTest, MergeMacrosFromIndexAndSema) {
1898 Symbol Sym;
1899 Sym.Name = "Clangd_Macro_Test";
1900 Sym.ID = SymbolID("c:foo.cpp@8@macro@Clangd_Macro_Test");
1901 Sym.SymInfo.Kind = index::SymbolKind::Macro;
Eric Liu6df66002018-09-06 18:52:26 +00001902 Sym.Flags |= Symbol::IndexedForCodeCompletion;
Eric Liud25f1212018-09-06 09:59:37 +00001903 EXPECT_THAT(completions("#define Clangd_Macro_Test\nClangd_Macro_T^", {Sym})
1904 .Completions,
1905 UnorderedElementsAre(Named("Clangd_Macro_Test")));
1906}
1907
Eric Liu6df66002018-09-06 18:52:26 +00001908TEST(CompletionTest, DeprecatedResults) {
1909 std::string Body = R"cpp(
1910 void TestClangd();
1911 void TestClangc() __attribute__((deprecated("", "")));
1912 )cpp";
1913
1914 EXPECT_THAT(
1915 completions(Body + "int main() { TestClang^ }").Completions,
1916 UnorderedElementsAre(AllOf(Named("TestClangd"), Not(Deprecated())),
1917 AllOf(Named("TestClangc"), Deprecated())));
1918}
1919
Kadir Cetinkaya0b77d032018-09-10 14:22:42 +00001920TEST(SignatureHelpTest, InsideArgument) {
1921 {
1922 const auto Results = signatures(R"cpp(
1923 void foo(int x);
1924 void foo(int x, int y);
1925 int main() { foo(1+^); }
1926 )cpp");
1927 EXPECT_THAT(
1928 Results.signatures,
1929 ElementsAre(Sig("foo(int x) -> void", {"int x"}),
1930 Sig("foo(int x, int y) -> void", {"int x", "int y"})));
1931 EXPECT_EQ(0, Results.activeParameter);
1932 }
1933 {
1934 const auto Results = signatures(R"cpp(
1935 void foo(int x);
1936 void foo(int x, int y);
1937 int main() { foo(1^); }
1938 )cpp");
1939 EXPECT_THAT(
1940 Results.signatures,
1941 ElementsAre(Sig("foo(int x) -> void", {"int x"}),
1942 Sig("foo(int x, int y) -> void", {"int x", "int y"})));
1943 EXPECT_EQ(0, Results.activeParameter);
1944 }
1945 {
1946 const auto Results = signatures(R"cpp(
1947 void foo(int x);
1948 void foo(int x, int y);
1949 int main() { foo(1^0); }
1950 )cpp");
1951 EXPECT_THAT(
1952 Results.signatures,
1953 ElementsAre(Sig("foo(int x) -> void", {"int x"}),
1954 Sig("foo(int x, int y) -> void", {"int x", "int y"})));
1955 EXPECT_EQ(0, Results.activeParameter);
1956 }
1957 {
1958 const auto Results = signatures(R"cpp(
1959 void foo(int x);
1960 void foo(int x, int y);
1961 int bar(int x, int y);
1962 int main() { bar(foo(2, 3^)); }
1963 )cpp");
1964 EXPECT_THAT(Results.signatures, ElementsAre(Sig("foo(int x, int y) -> void",
1965 {"int x", "int y"})));
1966 EXPECT_EQ(1, Results.activeParameter);
1967 }
1968}
1969
Kadir Cetinkaya873cae52018-09-11 15:12:10 +00001970TEST(SignatureHelpTest, ConstructorInitializeFields) {
1971 {
1972 const auto Results = signatures(R"cpp(
1973 struct A {
1974 A(int);
1975 };
1976 struct B {
1977 B() : a_elem(^) {}
1978 A a_elem;
1979 };
1980 )cpp");
1981 EXPECT_THAT(Results.signatures, UnorderedElementsAre(
1982 Sig("A(int)", {"int"}),
1983 Sig("A(A &&)", {"A &&"}),
1984 Sig("A(const A &)", {"const A &"})
1985 ));
1986 }
1987 {
1988 const auto Results = signatures(R"cpp(
1989 struct A {
1990 A(int);
1991 };
1992 struct C {
1993 C(int);
1994 C(A);
1995 };
1996 struct B {
1997 B() : c_elem(A(1^)) {}
1998 C c_elem;
1999 };
2000 )cpp");
2001 EXPECT_THAT(Results.signatures, UnorderedElementsAre(
2002 Sig("A(int)", {"int"}),
2003 Sig("A(A &&)", {"A &&"}),
2004 Sig("A(const A &)", {"const A &"})
2005 ));
2006 }
2007}
2008
Sam McCall9aad25f2017-12-05 07:20:26 +00002009} // namespace
2010} // namespace clangd
2011} // namespace clang