aboutsummaryrefslogtreecommitdiff
path: root/clang-tools-extra/clangd/unittests/StdLibTests.cpp
blob: 15e4b088b93391945a8eab65d3d4a307f2888182 (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
//===-- StdLibTests.cpp -----------------------------------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//

#include "Annotations.h"
#include "ClangdServer.h"
#include "CodeComplete.h"
#include "Compiler.h"
#include "Config.h"
#include "SyncAPI.h"
#include "TestFS.h"
#include "index/Index.h"
#include "index/StdLib.h"
#include "clang/Basic/LangOptions.h"
#include "clang/Basic/SourceManager.h"
#include "llvm/Testing/Support/Error.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include <memory>

using namespace testing;

namespace clang {
namespace clangd {
namespace {

// Check the generated header sources contains usual standard library headers.
TEST(StdLibTests, getStdlibUmbrellaHeader) {
  LangOptions LO;
  LO.CPlusPlus = true;

  auto CXX = getStdlibUmbrellaHeader(LO).str();
  EXPECT_THAT(CXX, HasSubstr("#include <string>"));
  EXPECT_THAT(CXX, HasSubstr("#include <cstdio>"));
  EXPECT_THAT(CXX, Not(HasSubstr("#include <ios646.h>")));

  LO.CPlusPlus = false;
  auto C = getStdlibUmbrellaHeader(LO).str();
  EXPECT_THAT(C, Not(HasSubstr("#include <string>")));
  EXPECT_THAT(C, Not(HasSubstr("#include <cstdio>")));
  EXPECT_THAT(C, HasSubstr("#include <stdio.h>"));
}

MATCHER_P(Named, Name, "") { return arg.Name == Name; }

// Build an index, and check if it contains the right symbols.
TEST(StdLibTests, indexStandardLibrary) {
  MockFS FS;
  FS.Files["std/foo.h"] = R"cpp(
  #include <platform_stuff.h>
  #if __cplusplus >= 201703L
    int foo17();
  #elif __cplusplus >= 201402L
    int foo14();
  #else
    bool foo98();
  #endif
  )cpp";
  FS.Files["nonstd/platform_stuff.h"] = "int magic = 42;";

  ParseInputs OriginalInputs;
  OriginalInputs.TFS = &FS;
  OriginalInputs.CompileCommand.Filename = testPath("main.cc");
  OriginalInputs.CompileCommand.CommandLine = {"clang++", testPath("main.cc"),
                                               "-isystemstd/",
                                               "-isystemnonstd/", "-std=c++14"};
  OriginalInputs.CompileCommand.Directory = testRoot();
  IgnoreDiagnostics Diags;
  auto CI = buildCompilerInvocation(OriginalInputs, Diags);
  ASSERT_TRUE(CI);

  StdLibLocation Loc;
  Loc.Paths.push_back(testPath("std/"));

  auto Symbols =
      indexStandardLibrary("#include <foo.h>", std::move(CI), Loc, FS);
  EXPECT_THAT(Symbols, ElementsAre(Named("foo14")));
}

TEST(StdLibTests, StdLibSet) {
  StdLibSet Set;
  MockFS FS;
  FS.Files["std/_"] = "";
  FS.Files["libc/_"] = "";

  HeaderSearchOptions HSOpts;
  auto Add = [&](const LangOptions &LO,
                 std::vector<llvm::StringRef> SearchPath) {
    SourceManagerForFile SM("scratch", "");
    SM.get().getFileManager().setVirtualFileSystem(FS.view(std::nullopt));
    HeaderSearch HS(HSOpts, SM.get(), SM.get().getDiagnostics(), LO,
                    /*Target=*/nullptr);
    for (auto P : SearchPath)
      HS.AddSearchPath(
          DirectoryLookup(
              cantFail(SM.get().getFileManager().getDirectoryRef(testPath(P))),
              SrcMgr::C_System, /*isFramework=*/false),
          true);
    return Set.add(LO, HS);
  };

  Config Cfg;
  Cfg.Index.StandardLibrary = false;
  WithContextValue Disabled(Config::Key, std::move(Cfg));

  LangOptions LO;
  LO.CPlusPlus = true;
  EXPECT_FALSE(Add(LO, {"std"})) << "Disabled in config";

  Cfg = Config();
  Cfg.Index.StandardLibrary = true;
  WithContextValue Enabled(Config::Key, std::move(Cfg));

  EXPECT_FALSE(Add(LO, {"std"})) << "No <vector> found";
  FS.Files["std/vector"] = "class vector;";
  EXPECT_TRUE(Add(LO, {"std"})) << "Indexing as C++98";
  EXPECT_FALSE(Add(LO, {"std"})) << "Don't reindex";
  LO.CPlusPlus11 = true;
  EXPECT_TRUE(Add(LO, {"std"})) << "Indexing as C++11";
  LO.CPlusPlus = false;
  EXPECT_FALSE(Add(LO, {"libc"})) << "No <stdio.h>";
  FS.Files["libc/stdio.h"] = true;
  EXPECT_TRUE(Add(LO, {"libc"})) << "Indexing as C";
}

MATCHER_P(StdlibSymbol, Name, "") {
  return arg.Name == Name && arg.Includes.size() == 1 &&
         llvm::StringRef(arg.Includes.front().Header).starts_with("<");
}

TEST(StdLibTests, EndToEnd) {
  Config Cfg;
  Cfg.Index.StandardLibrary = true;
  WithContextValue Enabled(Config::Key, std::move(Cfg));

  MockFS FS;
  FS.Files["stdlib/vector"] =
      "namespace std { template <class> class vector; }";
  FS.Files["stdlib/list"] =
      " namespace std { template <typename T> class list; }";
  MockCompilationDatabase CDB;
  CDB.ExtraClangFlags.push_back("-isystem" + testPath("stdlib"));
  ClangdServer::Options Opts = ClangdServer::optsForTest();
  Opts.BuildDynamicSymbolIndex = true; // also used for stdlib index
  ClangdServer Server(CDB, FS, Opts);

  Annotations A("std::^");

  Server.addDocument(testPath("foo.cc"), A.code());
  ASSERT_TRUE(Server.blockUntilIdleForTest());
  clangd::CodeCompleteOptions CCOpts;
  auto Completions =
      cantFail(runCodeComplete(Server, testPath("foo.cc"), A.point(), CCOpts));
  EXPECT_THAT(
      Completions.Completions,
      UnorderedElementsAre(StdlibSymbol("list"), StdlibSymbol("vector")));
}

TEST(StdLibTests, StdLibDocComments) {
  Config Cfg;
  Cfg.Index.StandardLibrary = true;
  WithContextValue Enabled(Config::Key, std::move(Cfg));

  MockFS FS;
  FS.Files["stdlib/vector"] = R"cpp(
    namespace std {
      struct vector {
        /**doc comment*/
        struct inner {};
      };
    }
  )cpp";
  MockCompilationDatabase CDB;
  CDB.ExtraClangFlags.push_back("-isystem" + testPath("stdlib"));
  ClangdServer::Options Opts = ClangdServer::optsForTest();
  Opts.BuildDynamicSymbolIndex = true; // also used for stdlib index
  ClangdServer Server(CDB, FS, Opts);

  // Open an empty file. <vector> will not be part of the preamble index,
  // but it will be part of the stdlib index.
  Server.addDocument(testPath("foo.cc"), "");

  // Wait for the stdlib index to be built.
  ASSERT_TRUE(Server.blockUntilIdleForTest());

  // Check that the index contains the doc comment.
  SymbolSlab Result;
  EXPECT_THAT_ERROR(runCustomAction(Server, testPath("foo.cc"),
                                    [&](InputsAndAST Inputs) {
                                      FuzzyFindRequest Req;
                                      Req.Query = "inner";
                                      Req.Scopes = {"std::vector::"};
                                      SymbolSlab::Builder Builder;
                                      Inputs.Inputs.Index->fuzzyFind(
                                          Req, [&](const Symbol &Sym) {
                                            Builder.insert(Sym);
                                          });
                                      Result = std::move(Builder).build();
                                    }),
                    llvm::Succeeded());
  ASSERT_EQ(Result.size(), 1u);
  EXPECT_EQ(Result.begin()->Documentation, "doc comment");
}

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