summaryrefslogtreecommitdiffstats
path: root/unittests/clangd/CodeCompleteTests.cpp
blob: 4e598d350bcc9d0313da9ab13f1e784e72c96040 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
//===-- CodeCompleteTests.cpp -----------------------------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "ClangdServer.h"
#include "Compiler.h"
#include "Context.h"
#include "Matchers.h"
#include "Protocol.h"
#include "SourceCode.h"
#include "TestFS.h"
#include "index/MemIndex.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"

namespace clang {
namespace clangd {
// Let GMock print completion items and signature help.
void PrintTo(const CompletionItem &I, std::ostream *O) {
  llvm::raw_os_ostream OS(*O);
  OS << I.label << " - " << toJSON(I);
}
void PrintTo(const std::vector<CompletionItem> &V, std::ostream *O) {
  *O << "{\n";
  for (const auto &I : V) {
    *O << "\t";
    PrintTo(I, O);
    *O << "\n";
  }
  *O << "}";
}
void PrintTo(const SignatureInformation &I, std::ostream *O) {
  llvm::raw_os_ostream OS(*O);
  OS << I.label << " - " << toJSON(I);
}
void PrintTo(const std::vector<SignatureInformation> &V, std::ostream *O) {
  *O << "{\n";
  for (const auto &I : V) {
    *O << "\t";
    PrintTo(I, O);
    *O << "\n";
  }
  *O << "}";
}

namespace {
using namespace llvm;
using ::testing::AllOf;
using ::testing::Contains;
using ::testing::ElementsAre;
using ::testing::Not;

class IgnoreDiagnostics : public DiagnosticsConsumer {
  void onDiagnosticsReady(
      PathRef File, Tagged<std::vector<DiagWithFixIts>> Diagnostics) override {}
};

struct StringWithPos {
  std::string Text;
  clangd::Position MarkerPos;
};

/// Accepts a source file with a cursor marker ^.
/// Returns the source file with the marker removed, and the marker position.
StringWithPos parseTextMarker(StringRef Text) {
  std::size_t MarkerOffset = Text.find('^');
  assert(MarkerOffset != StringRef::npos && "^ wasn't found in Text.");

  std::string WithoutMarker;
  WithoutMarker += Text.take_front(MarkerOffset);
  WithoutMarker += Text.drop_front(MarkerOffset + 1);
  assert(StringRef(WithoutMarker).find('^') == StringRef::npos &&
         "There were multiple occurences of ^ inside Text");

  auto MarkerPos = offsetToPosition(WithoutMarker, MarkerOffset);
  return {std::move(WithoutMarker), MarkerPos};
}

// GMock helpers for matching completion items.
MATCHER_P(Named, Name, "") { return arg.insertText == Name; }
MATCHER_P(Labeled, Label, "") { return arg.label == Label; }
MATCHER_P(Kind, K, "") { return arg.kind == K; }
MATCHER_P(Filter, F, "") { return arg.filterText == F; }
MATCHER_P(PlainText, Text, "") {
  return arg.insertTextFormat == clangd::InsertTextFormat::PlainText &&
         arg.insertText == Text;
}
MATCHER_P(Snippet, Text, "") {
  return arg.insertTextFormat == clangd::InsertTextFormat::Snippet &&
         arg.insertText == Text;
}
// Shorthand for Contains(Named(Name)).
Matcher<const std::vector<CompletionItem> &> Has(std::string Name) {
  return Contains(Named(std::move(Name)));
}
Matcher<const std::vector<CompletionItem> &> Has(std::string Name,
                                                 CompletionItemKind K) {
  return Contains(AllOf(Named(std::move(Name)), Kind(K)));
}
MATCHER(IsDocumented, "") { return !arg.documentation.empty(); }

CompletionList completions(StringRef Text,
                           clangd::CodeCompleteOptions Opts = {}) {
  MockFSProvider FS;
  MockCompilationDatabase CDB;
  IgnoreDiagnostics DiagConsumer;
  ClangdServer Server(CDB, DiagConsumer, FS, getDefaultAsyncThreadsCount(),
                      /*StorePreamblesInMemory=*/true);
  auto File = getVirtualTestFilePath("foo.cpp");
  auto Test = parseTextMarker(Text);
  Server.addDocument(Context::empty(), File, Test.Text);
  return Server.codeComplete(Context::empty(), File, Test.MarkerPos, Opts)
      .get()
      .second.Value;
}

TEST(CompletionTest, Limit) {
  clangd::CodeCompleteOptions Opts;
  Opts.Limit = 2;
  auto Results = completions(R"cpp(
struct ClassWithMembers {
  int AAA();
  int BBB();
  int CCC();
}
int main() { ClassWithMembers().^ }
      )cpp",
                             Opts);

  EXPECT_TRUE(Results.isIncomplete);
  EXPECT_THAT(Results.items, ElementsAre(Named("AAA"), Named("BBB")));
}

TEST(CompletionTest, Filter) {
  std::string Body = R"cpp(
    int Abracadabra;
    int Alakazam;
    struct S {
      int FooBar;
      int FooBaz;
      int Qux;
    };
  )cpp";
  EXPECT_THAT(completions(Body + "int main() { S().Foba^ }").items,
              AllOf(Has("FooBar"), Has("FooBaz"), Not(Has("Qux"))));

  EXPECT_THAT(completions(Body + "int main() { S().FR^ }").items,
              AllOf(Has("FooBar"), Not(Has("FooBaz")), Not(Has("Qux"))));

  EXPECT_THAT(completions(Body + "int main() { S().opr^ }").items,
              Has("operator="));

  EXPECT_THAT(completions(Body + "int main() { aaa^ }").items,
              AllOf(Has("Abracadabra"), Has("Alakazam")));

  EXPECT_THAT(completions(Body + "int main() { _a^ }").items,
              AllOf(Has("static_cast"), Not(Has("Abracadabra"))));
}

void TestAfterDotCompletion(clangd::CodeCompleteOptions Opts) {
  auto Results = completions(
      R"cpp(
      #define MACRO X

      int global_var;

      int global_func();

      struct GlobalClass {};

      struct ClassWithMembers {
        /// Doc for method.
        int method();

        int field;
      private:
        int private_field;
      };

      int test() {
        struct LocalClass {};

        /// Doc for local_var.
        int local_var;

        ClassWithMembers().^
      }
      )cpp",
      Opts);

  // Class members. The only items that must be present in after-dot
  // completion.
  EXPECT_THAT(
      Results.items,
      AllOf(Has(Opts.EnableSnippets ? "method()" : "method"), Has("field")));
  EXPECT_IFF(Opts.IncludeIneligibleResults, Results.items,
             Has("private_field"));
  // Global items.
  EXPECT_THAT(Results.items, Not(AnyOf(Has("global_var"), Has("global_func"),
                                       Has("global_func()"), Has("GlobalClass"),
                                       Has("MACRO"), Has("LocalClass"))));
  // There should be no code patterns (aka snippets) in after-dot
  // completion. At least there aren't any we're aware of.
  EXPECT_THAT(Results.items, Not(Contains(Kind(CompletionItemKind::Snippet))));
  // Check documentation.
  EXPECT_IFF(Opts.IncludeBriefComments, Results.items,
             Contains(IsDocumented()));
}

void TestGlobalScopeCompletion(clangd::CodeCompleteOptions Opts) {
  auto Results = completions(
      R"cpp(
      #define MACRO X

      int global_var;
      int global_func();

      struct GlobalClass {};

      struct ClassWithMembers {
        /// Doc for method.
        int method();
      };

      int test() {
        struct LocalClass {};

        /// Doc for local_var.
        int local_var;

        ^
      }
      )cpp",
      Opts);

  // Class members. Should never be present in global completions.
  EXPECT_THAT(Results.items,
              Not(AnyOf(Has("method"), Has("method()"), Has("field"))));
  // Global items.
  EXPECT_IFF(Opts.IncludeGlobals, Results.items,
             AllOf(Has("global_var"),
                   Has(Opts.EnableSnippets ? "global_func()" : "global_func"),
                   Has("GlobalClass")));
  // A macro.
  EXPECT_IFF(Opts.IncludeMacros, Results.items, Has("MACRO"));
  // Local items. Must be present always.
  EXPECT_THAT(Results.items,
              AllOf(Has("local_var"), Has("LocalClass"),
                    Contains(Kind(CompletionItemKind::Snippet))));
  // Check documentation.
  EXPECT_IFF(Opts.IncludeBriefComments, Results.items,
             Contains(IsDocumented()));
}

TEST(CompletionTest, CompletionOptions) {
  clangd::CodeCompleteOptions Opts;
  for (bool IncludeMacros : {true, false}) {
    Opts.IncludeMacros = IncludeMacros;
    for (bool IncludeGlobals : {true, false}) {
      Opts.IncludeGlobals = IncludeGlobals;
      for (bool IncludeBriefComments : {true, false}) {
        Opts.IncludeBriefComments = IncludeBriefComments;
        for (bool EnableSnippets : {true, false}) {
          Opts.EnableSnippets = EnableSnippets;
          for (bool IncludeCodePatterns : {true, false}) {
            Opts.IncludeCodePatterns = IncludeCodePatterns;
            for (bool IncludeIneligibleResults : {true, false}) {
              Opts.IncludeIneligibleResults = IncludeIneligibleResults;
              TestAfterDotCompletion(Opts);
              TestGlobalScopeCompletion(Opts);
            }
          }
        }
      }
    }
  }
}

// Check code completion works when the file contents are overridden.
TEST(CompletionTest, CheckContentsOverride) {
  MockFSProvider FS;
  IgnoreDiagnostics DiagConsumer;
  MockCompilationDatabase CDB;
  ClangdServer Server(CDB, DiagConsumer, FS, getDefaultAsyncThreadsCount(),
                      /*StorePreamblesInMemory=*/true);
  auto File = getVirtualTestFilePath("foo.cpp");
  Server.addDocument(Context::empty(), File, "ignored text!");

  auto Example = parseTextMarker("int cbc; int b = ^;");
  auto Results =
      Server
          .codeComplete(Context::empty(), File, Example.MarkerPos,
                        clangd::CodeCompleteOptions(), StringRef(Example.Text))
          .get()
          .second.Value;
  EXPECT_THAT(Results.items, Contains(Named("cbc")));
}

TEST(CompletionTest, Priorities) {
  auto Internal = completions(R"cpp(
      class Foo {
        public: void pub();
        protected: void prot();
        private: void priv();
      };
      void Foo::pub() { this->^ }
  )cpp");
  EXPECT_THAT(Internal.items,
              HasSubsequence(Named("priv"), Named("prot"), Named("pub")));

  auto External = completions(R"cpp(
      class Foo {
        public: void pub();
        protected: void prot();
        private: void priv();
      };
      void test() {
        Foo F;
        F.^
      }
  )cpp");
  EXPECT_THAT(External.items,
              AllOf(Has("pub"), Not(Has("prot")), Not(Has("priv"))));
}

TEST(CompletionTest, Qualifiers) {
  auto Results = completions(R"cpp(
      class Foo {
        public: int foo() const;
        int bar() const;
      };
      class Bar : public Foo {
        int foo() const;
      };
      void test() { Bar().^ }
  )cpp");
  EXPECT_THAT(Results.items, HasSubsequence(Labeled("bar() const"),
                                            Labeled("Foo::foo() const")));
  EXPECT_THAT(Results.items, Not(Contains(Labeled("foo() const")))); // private
}

TEST(CompletionTest, Snippets) {
  clangd::CodeCompleteOptions Opts;
  Opts.EnableSnippets = true;
  auto Results = completions(
      R"cpp(
      struct fake {
        int a;
        int f(int i, const float f) const;
      };
      int main() {
        fake f;
        f.^
      }
      )cpp",
      Opts);
  EXPECT_THAT(Results.items,
              HasSubsequence(PlainText("a"),
                             Snippet("f(${1:int i}, ${2:const float f})")));
}

TEST(CompletionTest, Kinds) {
  auto Results = completions(R"cpp(
      #define MACRO X
      int variable;
      struct Struct {};
      int function();
      int X = ^
  )cpp");
  EXPECT_THAT(Results.items, Has("function", CompletionItemKind::Function));
  EXPECT_THAT(Results.items, Has("variable", CompletionItemKind::Variable));
  EXPECT_THAT(Results.items, Has("int", CompletionItemKind::Keyword));
  EXPECT_THAT(Results.items, Has("Struct", CompletionItemKind::Class));
  EXPECT_THAT(Results.items, Has("MACRO", CompletionItemKind::Text));

  clangd::CodeCompleteOptions Opts;
  Opts.EnableSnippets = true; // Needed for code patterns.

  Results = completions("nam^");
  EXPECT_THAT(Results.items, Has("namespace", CompletionItemKind::Snippet));
}

SignatureHelp signatures(StringRef Text) {
  MockFSProvider FS;
  MockCompilationDatabase CDB;
  IgnoreDiagnostics DiagConsumer;
  ClangdServer Server(CDB, DiagConsumer, FS, getDefaultAsyncThreadsCount(),
                      /*StorePreamblesInMemory=*/true);
  auto File = getVirtualTestFilePath("foo.cpp");
  auto Test = parseTextMarker(Text);
  Server.addDocument(Context::empty(), File, Test.Text);
  auto R = Server.signatureHelp(Context::empty(), File, Test.MarkerPos);
  assert(R);
  return R.get().Value;
}

MATCHER_P(ParamsAre, P, "") {
  if (P.size() != arg.parameters.size())
    return false;
  for (unsigned I = 0; I < P.size(); ++I)
    if (P[I] != arg.parameters[I].label)
      return false;
  return true;
}

Matcher<SignatureInformation> Sig(std::string Label,
                                  std::vector<std::string> Params) {
  return AllOf(Labeled(Label), ParamsAre(Params));
}

TEST(SignatureHelpTest, Overloads) {
  auto Results = signatures(R"cpp(
    void foo(int x, int y);
    void foo(int x, float y);
    void foo(float x, int y);
    void foo(float x, float y);
    void bar(int x, int y = 0);
    int main() { foo(^); }
  )cpp");
  EXPECT_THAT(Results.signatures,
              UnorderedElementsAre(
                  Sig("foo(float x, float y) -> void", {"float x", "float y"}),
                  Sig("foo(float x, int y) -> void", {"float x", "int y"}),
                  Sig("foo(int x, float y) -> void", {"int x", "float y"}),
                  Sig("foo(int x, int y) -> void", {"int x", "int y"})));
  // We always prefer the first signature.
  EXPECT_EQ(0, Results.activeSignature);
  EXPECT_EQ(0, Results.activeParameter);
}

TEST(SignatureHelpTest, DefaultArgs) {
  auto Results = signatures(R"cpp(
    void bar(int x, int y = 0);
    void bar(float x = 0, int y = 42);
    int main() { bar(^
  )cpp");
  EXPECT_THAT(Results.signatures,
              UnorderedElementsAre(
                  Sig("bar(int x, int y = 0) -> void", {"int x", "int y = 0"}),
                  Sig("bar(float x = 0, int y = 42) -> void",
                      {"float x = 0", "int y = 42"})));
  EXPECT_EQ(0, Results.activeSignature);
  EXPECT_EQ(0, Results.activeParameter);
}

TEST(SignatureHelpTest, ActiveArg) {
  auto Results = signatures(R"cpp(
    int baz(int a, int b, int c);
    int main() { baz(baz(1,2,3), ^); }
  )cpp");
  EXPECT_THAT(Results.signatures,
              ElementsAre(Sig("baz(int a, int b, int c) -> int",
                              {"int a", "int b", "int c"})));
  EXPECT_EQ(0, Results.activeSignature);
  EXPECT_EQ(1, Results.activeParameter);
}

std::unique_ptr<SymbolIndex> simpleIndexFromSymbols(
    std::vector<std::pair<std::string, index::SymbolKind>> Symbols) {
  auto I = llvm::make_unique<MemIndex>();
  struct Snapshot {
    SymbolSlab Slab;
    std::vector<const Symbol *> Pointers;
  };
  auto Snap = std::make_shared<Snapshot>();
  for (const auto &Pair : Symbols) {
    Symbol Sym;
    Sym.ID = SymbolID(Pair.first);
    llvm::StringRef QName = Pair.first;
    size_t Pos = QName.rfind("::");
    if (Pos == llvm::StringRef::npos) {
      Sym.Name = QName;
      Sym.Scope = "";
    } else {
      Sym.Name = QName.substr(Pos + 2);
      Sym.Scope = QName.substr(0, Pos);
    }
    Sym.SymInfo.Kind = Pair.second;
    Snap->Slab.insert(std::move(Sym));
  }
  for (auto &Iter : Snap->Slab)
    Snap->Pointers.push_back(&Iter.second);
  auto S = std::shared_ptr<std::vector<const Symbol *>>(std::move(Snap),
                                                        &Snap->Pointers);
  I->build(std::move(S));
  return I;
}

TEST(CompletionTest, NoIndex) {
  clangd::CodeCompleteOptions Opts;
  Opts.Index = nullptr;

  auto Results = completions(R"cpp(
      namespace ns { class No {}; }
      void f() { ns::^ }
  )cpp",
                             Opts);
  EXPECT_THAT(Results.items, Has("No"));
}

TEST(CompletionTest, SimpleIndexBased) {
  clangd::CodeCompleteOptions Opts;
  auto I = simpleIndexFromSymbols({{"ns::XYZ", index::SymbolKind::Class},
                                   {"nx::XYZ", index::SymbolKind::Class},
                                   {"ns::foo", index::SymbolKind::Function}});
  Opts.Index = I.get();

  auto Results = completions(R"cpp(
      namespace ns { class No {}; }
      void f() { ns::^ }
  )cpp",
                             Opts);
  EXPECT_THAT(Results.items, Has("XYZ", CompletionItemKind::Class));
  EXPECT_THAT(Results.items, Has("foo", CompletionItemKind::Function));
  EXPECT_THAT(Results.items, Not(Has("No")));
}

TEST(CompletionTest, IndexBasedWithFilter) {
  clangd::CodeCompleteOptions Opts;
  auto I = simpleIndexFromSymbols({{"ns::XYZ", index::SymbolKind::Class},
                                   {"ns::foo", index::SymbolKind::Function}});
  Opts.Index = I.get();

  auto Results = completions(R"cpp(
      void f() { ns::x^ }
  )cpp",
                             Opts);
  EXPECT_THAT(Results.items, Contains(AllOf(Named("XYZ"), Filter("x"))));
  EXPECT_THAT(Results.items, Not(Has("foo")));
}

TEST(CompletionTest, GlobalQualified) {
  clangd::CodeCompleteOptions Opts;
  auto I = simpleIndexFromSymbols({{"XYZ", index::SymbolKind::Class}});
  Opts.Index = I.get();

  auto Results = completions(R"cpp(
      void f() { ::^ }
  )cpp",
                             Opts);
  EXPECT_THAT(Results.items, Has("XYZ", CompletionItemKind::Class));
}

TEST(CompletionTest, FullyQualifiedScope) {
  clangd::CodeCompleteOptions Opts;
  auto I = simpleIndexFromSymbols({{"ns::XYZ", index::SymbolKind::Class}});
  Opts.Index = I.get();

  auto Results = completions(R"cpp(
      void f() { ::ns::^ }
  )cpp",
                             Opts);
  EXPECT_THAT(Results.items, Has("XYZ", CompletionItemKind::Class));
}

} // namespace
} // namespace clangd
} // namespace clang