24#include "clang/Basic/Diagnostic.h"
25#include "clang/Basic/LLVM.h"
26#include "llvm/ADT/FunctionExtras.h"
27#include "llvm/ADT/StringRef.h"
28#include "llvm/Support/Error.h"
29#include "llvm/Support/FormatVariadic.h"
30#include "llvm/Support/JSON.h"
31#include "llvm/Support/raw_ostream.h"
32#include "llvm/Testing/Support/Error.h"
33#include "llvm/Testing/Support/SupportHelpers.h"
34#include "gmock/gmock.h"
35#include "gtest/gtest.h"
37#include <condition_variable>
49using testing::ElementsAre;
52 if (
const auto *O = arg.getAsObject()) {
53 if (
const auto Msg = O->getString(
"message"))
59class LSPTest :
public ::testing::Test {
61 LSPTest() : LogSession(L) {
62 ClangdServer::Options &Base = Opts;
65 Base.BuildDynamicSymbolIndex =
true;
66 Base.FeatureModules = &FeatureModules;
70 EXPECT_FALSE(Server) <<
"Already initialized";
71 Server.emplace(Client.transport(), FS, std::move(Opts));
72 ServerThread.emplace([&] { EXPECT_TRUE(Server->run()); });
73 Client.call(
"initialize", llvm::json::Object{});
79 Client.call(
"shutdown",
nullptr);
80 Client.notify(
"exit",
nullptr);
93 ClangdLSPServer::Options Opts;
94 FeatureModuleSet FeatureModules;
97 class Logger :
public clang::clangd::Logger {
99 void log(Level L,
const char *Fmt,
100 const llvm::formatv_object_base &Message)
override {
101 raw_ostream::Colors
Color;
104 Color = raw_ostream::BLUE;
107 Color = raw_ostream::RED;
110 Color = raw_ostream::YELLOW;
113 std::lock_guard<std::mutex> Lock(LogMu);
114 (llvm::outs().changeColor(
Color) << Message <<
"\n").resetColor();
120 LoggingSession LogSession;
121 std::optional<ClangdLSPServer> Server;
122 std::optional<std::thread> ServerThread;
126TEST_F(LSPTest, GoToDefinition) {
129 return n >= 2 ? ^fib(n - 1) + fib(n - 2) : 1;
132 auto &Client = start();
133 Client.didOpen(
"foo.cpp", Code.code());
134 auto &Def = Client.call(
"textDocument/definition",
136 {
"textDocument", Client.documentID(
"foo.cpp")},
137 {
"position", Code.point()},
139 llvm::json::Value Want = llvm::json::Array{llvm::json::Object{
140 {
"uri", Client.uri(
"foo.cpp")}, {
"range", Code.range()}}};
141 EXPECT_EQ(Def.takeValue(), Want);
144TEST_F(LSPTest, Diagnostics) {
145 auto &Client = start();
146 Client.didOpen(
"foo.cpp",
"void main(int, char**);");
147 EXPECT_THAT(Client.diagnostics(
"foo.cpp"),
148 llvm::ValueIs(testing::ElementsAre(
149 diagMessage(
"'main' must return 'int' (fix available)"))));
151 Client.didChange(
"foo.cpp",
"int x = \"42\";");
152 EXPECT_THAT(Client.diagnostics(
"foo.cpp"),
153 llvm::ValueIs(testing::ElementsAre(
154 diagMessage(
"Cannot initialize a variable of type 'int' with "
155 "an lvalue of type 'const char[3]'"))));
157 Client.didClose(
"foo.cpp");
158 EXPECT_THAT(Client.diagnostics(
"foo.cpp"), llvm::ValueIs(testing::IsEmpty()));
161TEST_F(LSPTest, DiagnosticsHeaderSaved) {
162 auto &Client = start();
163 Client.didOpen(
"foo.cpp", R
"cpp(
167 EXPECT_THAT(Client.diagnostics("foo.cpp"),
168 llvm::ValueIs(testing::ElementsAre(
169 diagMessage(
"'foo.h' file not found"),
170 diagMessage(
"Use of undeclared identifier 'VAR'"))));
172 FS.Files[
"foo.h"] =
"#define VAR original";
174 "textDocument/didSave",
175 llvm::json::Object{{
"textDocument", Client.documentID(
"foo.h")}});
176 EXPECT_THAT(Client.diagnostics(
"foo.cpp"),
177 llvm::ValueIs(testing::ElementsAre(
178 diagMessage(
"Use of undeclared identifier 'original'"))));
180 FS.Files[
"foo.h"] =
"#define VAR changed";
182 "textDocument/didSave",
183 llvm::json::Object{{
"textDocument", Client.documentID(
"foo.h")}});
185 EXPECT_THAT(Client.diagnostics(
"foo.cpp"),
186 llvm::ValueIs(testing::ElementsAre(
187 diagMessage(
"Use of undeclared identifier 'changed'"))));
190TEST_F(LSPTest, RecordsLatencies) {
192 auto &Client = start();
193 llvm::StringLiteral MethodName =
"method_name";
194 EXPECT_THAT(Tracer.takeMetric(
"lsp_latency", MethodName), testing::SizeIs(0));
195 llvm::consumeError(Client.call(MethodName, {}).take().takeError());
197 EXPECT_THAT(Tracer.takeMetric(
"lsp_latency", MethodName), testing::SizeIs(1));
202TEST_F(LSPTest, ClangTidyRename) {
204 if (!CLANGD_TIDY_CHECKS)
212 constexpr auto ClangTidyProvider = [](tidy::ClangTidyOptions &ClangTidyOpts,
214 ClangTidyOpts.Checks = {
"-*,readability-identifier-naming"};
215 ClangTidyOpts.CheckOptions[
"readability-identifier-naming.FunctionCase"] =
219 std::make_unique<ClangTidyFeatureModule>(ClangTidyProvider));
220 auto &Client = start();
221 Client.didOpen(
"foo.hpp", Header.code());
222 Client.didOpen(
"foo.cpp", Source.code());
224 auto Diags = Client.diagnostics(
"foo.cpp");
225 ASSERT_TRUE(Diags && !Diags->empty());
226 auto RenameDiag = Diags->front();
230 .call(
"textDocument/codeAction",
232 {
"textDocument", Client.documentID(
"foo.cpp")},
235 {
"diagnostics", llvm::json::Array{RenameDiag}}}},
236 {
"range", Source.range()}})
240 ASSERT_EQ((*RenameCommand.getAsObject())[
"title"],
241 "Apply fix: change 'foo' to 'Foo'");
243 Client.expectServerCall(
"workspace/applyEdit");
244 Client.call(
"workspace/executeCommand", RenameCommand);
247 auto Params = Client.takeCallParams(
"workspace/applyEdit");
248 auto Uri = [&](llvm::StringRef
Path) {
249 return Client.uri(
Path).getAsString().value().str();
251 llvm::json::Object ExpectedEdit = llvm::json::Object{
252 {
"edit", llvm::json::Object{
255 {Uri(
"foo.hpp"), llvm::json::Array{llvm::json::Object{
256 {
"range", Header.range()},
260 {Uri(
"foo.cpp"), llvm::json::Array{llvm::json::Object{
261 {
"range", Source.range()},
266 EXPECT_EQ(Params, std::vector{llvm::json::Value(std::move(ExpectedEdit))});
269TEST_F(LSPTest, ClangTidyCrash_Issue109367) {
271 if (!CLANGD_TIDY_CHECKS)
273 constexpr auto ClangTidyProvider = [](tidy::ClangTidyOptions &ClangTidyOpts,
275 ClangTidyOpts.Checks = {
"-*,boost-use-ranges"};
278 std::make_unique<ClangTidyFeatureModule>(ClangTidyProvider));
281 auto &Client = start();
282 Client.didOpen(
"a.cpp",
"");
283 Client.didOpen(
"b.cpp",
"");
287TEST_F(LSPTest, IncomingCalls) {
294 auto &Client = start();
295 Client.didOpen(
"foo.cpp", Code.code());
297 .call(
"textDocument/prepareCallHierarchy",
299 {
"textDocument", Client.documentID(
"foo.cpp")},
300 {
"position", Code.point()}})
302 auto FirstItem = (*Items.getAsArray())[0];
304 .call(
"callHierarchy/incomingCalls",
305 llvm::json::Object{{
"item", FirstItem}})
307 auto FirstCall = *(*Calls.getAsArray())[0].getAsObject();
308 EXPECT_EQ(FirstCall[
"fromRanges"], llvm::json::Value{Code.range()});
309 auto From = *FirstCall[
"from"].getAsObject();
310 EXPECT_EQ(From[
"name"],
"caller1");
313TEST_F(LSPTest, CDBConfigIntegration) {
314 Opts.ConfigProvider =
318 FS.Files[
".clangd"] = R
"yaml(
322 CompilationDatabase: bar
324 FS.Files["bar/compile_flags.txt"] =
"-DFOO=BAR";
326 auto &Client = start();
328 Client.didOpen(
"foo.cpp",
"int x = FOO;");
329 EXPECT_THAT(Client.diagnostics(
"foo.cpp"),
330 llvm::ValueIs(testing::ElementsAre(
331 diagMessage(
"Use of undeclared identifier 'FOO'"))));
333 Client.didOpen(
"bar.cpp",
"int x = FOO;");
334 EXPECT_THAT(Client.diagnostics(
"bar.cpp"),
335 llvm::ValueIs(testing::ElementsAre(
336 diagMessage(
"Use of undeclared identifier 'BAR'"))));
339TEST_F(LSPTest, ModulesTest) {
341 OutgoingNotification<int>
Changed;
342 void initializeLSP(LSPBinder &Bind,
const llvm::json::Object &ClientCaps,
343 llvm::json::Object &ServerCaps)
override {
344 Bind.notification(
"add",
this, &MathModule::add);
345 Bind.method(
"get",
this, &MathModule::get);
346 Changed = Bind.outgoingNotification(
"changed");
351 void add(
const int &
X) {
355 void get(
const std::nullptr_t &, Callback<int> Reply) {
356 scheduler().runQuick(
358 [Reply(std::move(Reply)), Value(Value)]()
mutable { Reply(Value); });
361 FeatureModules.add(std::make_unique<MathModule>());
363 auto &Client = start();
364 Client.notify(
"add", 2);
365 Client.notify(
"add", 8);
366 EXPECT_EQ(10, Client.call(
"get",
nullptr).takeValue());
367 EXPECT_THAT(Client.takeNotifications(
"changed"),
368 ElementsAre(llvm::json::Value(2), llvm::json::Value(10)));
371TEST_F(LSPTest, FeatureModulesThreadingTest) {
375 bool ShouldStop =
false;
377 std::deque<Callback<int>> Queue;
378 std::condition_variable CV;
383 std::unique_lock<std::mutex> Lock(Mu);
385 CV.wait(Lock, [&] {
return ShouldStop || !Queue.empty(); });
391 Callback<int> &Task = Queue.front();
401 bool blockUntilIdle(Deadline D)
override {
402 std::unique_lock<std::mutex> Lock(Mu);
403 return clangd::wait(Lock, CV, D, [
this] {
return Queue.empty(); });
406 void stop()
override {
408 std::lock_guard<std::mutex> Lock(Mu);
415 AsyncCounter() : Thread([this] { run(); }) {}
423 std::lock_guard<std::mutex> Lock(Mu);
424 EXPECT_TRUE(ShouldStop) <<
"ClangdServer should request shutdown";
425 EXPECT_EQ(Queue.size(), 0u) <<
"ClangdServer should block until idle";
430 void initializeLSP(LSPBinder &Bind,
const llvm::json::Object &ClientCaps,
431 llvm::json::Object &ServerCaps)
override {
432 Bind.notification(
"increment",
this, &AsyncCounter::increment);
438 std::lock_guard<std::mutex> Lock(Mu);
443 void increment(
const std::nullptr_t &) {
445 std::lock_guard<std::mutex> Lock(Mu);
446 Queue.push_back(
nullptr);
452 FeatureModules.add(std::make_unique<AsyncCounter>());
453 auto &Client = start();
455 Client.notify(
"increment",
nullptr);
456 Client.notify(
"increment",
nullptr);
457 Client.notify(
"increment",
nullptr);
459 EXPECT_EQ(3, FeatureModules.get<AsyncCounter>()->getSync());
461 Client.notify(
"increment",
nullptr);
462 Client.notify(
"increment",
nullptr);
463 Client.notify(
"increment",
nullptr);
467TEST_F(LSPTest, DiagModuleTest) {
468 static constexpr llvm::StringLiteral DiagMsg =
"DiagMsg";
470 struct DiagHooks :
public ASTListener {
471 void sawDiagnostic(
const clang::Diagnostic &, clangd::Diag &D)
override {
472 D.Message = DiagMsg.str();
477 std::unique_ptr<ASTListener> astListeners()
override {
478 return std::make_unique<DiagHooks>();
481 FeatureModules.add(std::make_unique<DiagModule>());
483 auto &Client = start();
484 Client.didOpen(
"foo.cpp",
"test;");
485 EXPECT_THAT(Client.diagnostics(
"foo.cpp"),
486 llvm::ValueIs(testing::ElementsAre(diagMessage(DiagMsg))));
490TEST_F(LSPTest, CompletionOutOfRangePosition) {
491 auto &Client = start();
492 Client.didOpen(
"foo.cpp",
"int x;");
493 auto &Reply = Client.call(
494 "textDocument/completion",
496 {
"textDocument", Client.documentID(
"foo.cpp")},
497 {
"position", llvm::json::Object{{
"line", 97}, {
"character", 0}}},
501 {
"triggerCharacter",
">"},
504 auto Result = Reply.take();
505 ASSERT_TRUE(!!Result) <<
"Expected a response, not a server crash";
509TEST_F(LSPTest, ShutdownDuringRename) {
511 auto &Client = start();
512 Client.didOpen(
"foo.cpp", Code.code());
513 auto &Reply = Client.call(
"textDocument/rename",
515 {
"textDocument", Client.documentID(
"foo.cpp")},
516 {
"position", Code.point()},
520 auto Result = Reply.take();
521 ASSERT_TRUE(!!Result) <<
"Expected a response, not a server crash";
static clang::FrontendPluginRegistry::Add< clang::tidy::ClangTidyPluginAction > X("clang-tidy", "clang-tidy")
Same as llvm::Annotations, but adjusts functions to LSP-specific types for positions and ranges.
static Options optsForTest()
A FeatureModule contributes a vertical feature to clangd.
static std::unique_ptr< Provider > fromAncestorRelativeYAMLFiles(llvm::StringRef RelPath, const ThreadsafeFS &, bool Trusted=false)
A RAII Tracer that can be used by tests.
FIXME: Skip testing on windows temporarily due to the different escaping code mode.
@ Changed
The file got changed.
TEST_F(BackgroundIndexTest, NoCrashOnErrorFile)
void log(const char *Fmt, Ts &&... Vals)
std::string Path
A typedef to represent a file path.
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//