blob: 2d4a9cf50763c01b3e96564be6b9dd1eed38a8f0 [file] [log] [blame]
Ilya Biryukov38d79772017-05-16 09:38:59 +00001//===--- ClangdLSPServer.cpp - LSP server ------------------------*- 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//
Kirill Bobyrev8e35f1e2018-08-14 16:03:32 +00008//===----------------------------------------------------------------------===//
Ilya Biryukov38d79772017-05-16 09:38:59 +00009
10#include "ClangdLSPServer.h"
Ilya Biryukov71028b82018-03-12 15:28:22 +000011#include "Diagnostics.h"
Sam McCallb536a2a2017-12-19 12:23:48 +000012#include "SourceCode.h"
Sam McCall2c30fbc2018-10-18 12:32:04 +000013#include "Trace.h"
Eric Liu78ed91a72018-01-29 15:37:46 +000014#include "URI.h"
Kadir Cetinkaya689bf932018-08-24 13:09:41 +000015#include "llvm/ADT/ScopeExit.h"
Simon Marchi9569fd52018-03-16 14:30:42 +000016#include "llvm/Support/Errc.h"
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +000017#include "llvm/Support/FormatVariadic.h"
Eric Liu5740ff52018-01-31 16:26:27 +000018#include "llvm/Support/Path.h"
Sam McCall2c30fbc2018-10-18 12:32:04 +000019#include "llvm/Support/ScopedPrinter.h"
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +000020
Sam McCalld20d7982018-07-09 14:25:59 +000021using namespace llvm;
Sam McCallc008af62018-10-20 15:30:37 +000022namespace clang {
23namespace clangd {
Ilya Biryukovafb55542017-05-16 14:40:30 +000024namespace {
25
Eric Liu5740ff52018-01-31 16:26:27 +000026/// \brief Supports a test URI scheme with relaxed constraints for lit tests.
27/// The path in a test URI will be combined with a platform-specific fake
28/// directory to form an absolute path. For example, test:///a.cpp is resolved
29/// C:\clangd-test\a.cpp on Windows and /clangd-test/a.cpp on Unix.
30class TestScheme : public URIScheme {
31public:
Sam McCallc008af62018-10-20 15:30:37 +000032 Expected<std::string> getAbsolutePath(StringRef /*Authority*/, StringRef Body,
33 StringRef /*HintPath*/) const override {
Eric Liu5740ff52018-01-31 16:26:27 +000034 using namespace llvm::sys;
35 // Still require "/" in body to mimic file scheme, as we want lengths of an
36 // equivalent URI in both schemes to be the same.
37 if (!Body.startswith("/"))
Sam McCallc008af62018-10-20 15:30:37 +000038 return make_error<StringError>(
Eric Liu5740ff52018-01-31 16:26:27 +000039 "Expect URI body to be an absolute path starting with '/': " + Body,
Sam McCallc008af62018-10-20 15:30:37 +000040 inconvertibleErrorCode());
Eric Liu5740ff52018-01-31 16:26:27 +000041 Body = Body.ltrim('/');
Nico Weber0da22902018-04-10 13:14:03 +000042#ifdef _WIN32
Eric Liu5740ff52018-01-31 16:26:27 +000043 constexpr char TestDir[] = "C:\\clangd-test";
44#else
45 constexpr char TestDir[] = "/clangd-test";
46#endif
Sam McCallc008af62018-10-20 15:30:37 +000047 SmallVector<char, 16> Path(Body.begin(), Body.end());
Eric Liu5740ff52018-01-31 16:26:27 +000048 path::native(Path);
49 auto Err = fs::make_absolute(TestDir, Path);
Eric Liucda25262018-02-01 12:44:52 +000050 if (Err)
51 llvm_unreachable("Failed to make absolute path in test scheme.");
Eric Liu5740ff52018-01-31 16:26:27 +000052 return std::string(Path.begin(), Path.end());
53 }
54
Sam McCallc008af62018-10-20 15:30:37 +000055 Expected<URI> uriFromAbsolutePath(StringRef AbsolutePath) const override {
Eric Liu5740ff52018-01-31 16:26:27 +000056 llvm_unreachable("Clangd must never create a test URI.");
57 }
58};
59
60static URISchemeRegistry::Add<TestScheme>
61 X("test", "Test scheme for clangd lit tests.");
62
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +000063SymbolKindBitset defaultSymbolKinds() {
64 SymbolKindBitset Defaults;
65 for (size_t I = SymbolKindMin; I <= static_cast<size_t>(SymbolKind::Array);
66 ++I)
67 Defaults.set(I);
68 return Defaults;
69}
70
Kadir Cetinkaya133d46f2018-09-27 17:13:07 +000071CompletionItemKindBitset defaultCompletionItemKinds() {
72 CompletionItemKindBitset Defaults;
73 for (size_t I = CompletionItemKindMin;
74 I <= static_cast<size_t>(CompletionItemKind::Reference); ++I)
75 Defaults.set(I);
76 return Defaults;
77}
78
Ilya Biryukovafb55542017-05-16 14:40:30 +000079} // namespace
80
Sam McCall2c30fbc2018-10-18 12:32:04 +000081// MessageHandler dispatches incoming LSP messages.
82// It handles cross-cutting concerns:
83// - serializes/deserializes protocol objects to JSON
84// - logging of inbound messages
85// - cancellation handling
86// - basic call tracing
Sam McCall3d0adbe2018-10-18 14:41:50 +000087// MessageHandler ensures that initialize() is called before any other handler.
Sam McCall2c30fbc2018-10-18 12:32:04 +000088class ClangdLSPServer::MessageHandler : public Transport::MessageHandler {
89public:
90 MessageHandler(ClangdLSPServer &Server) : Server(Server) {}
91
92 bool onNotify(StringRef Method, json::Value Params) override {
93 log("<-- {0}", Method);
94 if (Method == "exit")
95 return false;
Sam McCall3d0adbe2018-10-18 14:41:50 +000096 if (!Server.Server)
97 elog("Notification {0} before initialization", Method);
98 else if (Method == "$/cancelRequest")
Sam McCall2c30fbc2018-10-18 12:32:04 +000099 onCancel(std::move(Params));
100 else if (auto Handler = Notifications.lookup(Method))
101 Handler(std::move(Params));
102 else
103 log("unhandled notification {0}", Method);
104 return true;
105 }
106
107 bool onCall(StringRef Method, json::Value Params, json::Value ID) override {
Sam McCalle2f3a732018-10-24 14:26:26 +0000108 // Calls can be canceled by the client. Add cancellation context.
109 WithContext WithCancel(cancelableRequestContext(ID));
110 trace::Span Tracer(Method);
111 SPAN_ATTACH(Tracer, "Params", Params);
112 ReplyOnce Reply(ID, Method, &Server, Tracer.Args);
Sam McCall2c30fbc2018-10-18 12:32:04 +0000113 log("<-- {0}({1})", Method, ID);
Sam McCall3d0adbe2018-10-18 14:41:50 +0000114 if (!Server.Server && Method != "initialize") {
115 elog("Call {0} before initialization.", Method);
Sam McCalle2f3a732018-10-24 14:26:26 +0000116 Reply(make_error<LSPError>("server not initialized",
117 ErrorCode::ServerNotInitialized));
Sam McCall3d0adbe2018-10-18 14:41:50 +0000118 } else if (auto Handler = Calls.lookup(Method))
Sam McCalle2f3a732018-10-24 14:26:26 +0000119 Handler(std::move(Params), std::move(Reply));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000120 else
Sam McCalle2f3a732018-10-24 14:26:26 +0000121 Reply(
122 make_error<LSPError>("method not found", ErrorCode::MethodNotFound));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000123 return true;
124 }
125
126 bool onReply(json::Value ID, Expected<json::Value> Result) override {
127 // We ignore replies, just log them.
128 if (Result)
129 log("<-- reply({0})", ID);
130 else
Sam McCallc008af62018-10-20 15:30:37 +0000131 log("<-- reply({0}) error: {1}", ID, toString(Result.takeError()));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000132 return true;
133 }
134
135 // Bind an LSP method name to a call.
Sam McCalle2f3a732018-10-24 14:26:26 +0000136 template <typename Param, typename Result>
Sam McCall2c30fbc2018-10-18 12:32:04 +0000137 void bind(const char *Method,
Sam McCalle2f3a732018-10-24 14:26:26 +0000138 void (ClangdLSPServer::*Handler)(const Param &, Callback<Result>)) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000139 Calls[Method] = [Method, Handler, this](json::Value RawParams,
Sam McCalle2f3a732018-10-24 14:26:26 +0000140 ReplyOnce Reply) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000141 Param P;
Sam McCalle2f3a732018-10-24 14:26:26 +0000142 if (fromJSON(RawParams, P)) {
143 (Server.*Handler)(P, std::move(Reply));
144 } else {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000145 elog("Failed to decode {0} request.", Method);
Sam McCalle2f3a732018-10-24 14:26:26 +0000146 Reply(make_error<LSPError>("failed to decode request",
147 ErrorCode::InvalidRequest));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000148 }
Sam McCall2c30fbc2018-10-18 12:32:04 +0000149 };
150 }
151
152 // Bind an LSP method name to a notification.
153 template <typename Param>
154 void bind(const char *Method,
155 void (ClangdLSPServer::*Handler)(const Param &)) {
156 Notifications[Method] = [Method, Handler, this](json::Value RawParams) {
157 Param P;
158 if (!fromJSON(RawParams, P)) {
159 elog("Failed to decode {0} request.", Method);
160 return;
161 }
162 trace::Span Tracer(Method);
163 SPAN_ATTACH(Tracer, "Params", RawParams);
164 (Server.*Handler)(P);
165 };
166 }
167
168private:
Sam McCalle2f3a732018-10-24 14:26:26 +0000169 // Function object to reply to an LSP call.
170 // Each instance must be called exactly once, otherwise:
171 // - the bug is logged, and (in debug mode) an assert will fire
172 // - if there was no reply, an error reply is sent
173 // - if there were multiple replies, only the first is sent
174 class ReplyOnce {
175 std::atomic<bool> Replied = {false};
Sam McCalld7babe42018-10-24 15:18:40 +0000176 std::chrono::steady_clock::time_point Start;
Sam McCalle2f3a732018-10-24 14:26:26 +0000177 json::Value ID;
178 std::string Method;
179 ClangdLSPServer *Server; // Null when moved-from.
180 json::Object *TraceArgs;
181
182 public:
183 ReplyOnce(const json::Value &ID, StringRef Method, ClangdLSPServer *Server,
184 json::Object *TraceArgs)
Sam McCalld7babe42018-10-24 15:18:40 +0000185 : Start(std::chrono::steady_clock::now()), ID(ID), Method(Method),
186 Server(Server), TraceArgs(TraceArgs) {
Sam McCalle2f3a732018-10-24 14:26:26 +0000187 assert(Server);
188 }
189 ReplyOnce(ReplyOnce &&Other)
Sam McCalld7babe42018-10-24 15:18:40 +0000190 : Replied(Other.Replied.load()), Start(Other.Start),
191 ID(std::move(Other.ID)), Method(std::move(Other.Method)),
192 Server(Other.Server), TraceArgs(Other.TraceArgs) {
Sam McCalle2f3a732018-10-24 14:26:26 +0000193 Other.Server = nullptr;
194 }
195 ReplyOnce& operator=(ReplyOnce&&) = delete;
196 ReplyOnce(const ReplyOnce &) = delete;
197 ReplyOnce& operator=(const ReplyOnce&) = delete;
198
199 ~ReplyOnce() {
200 if (Server && !Replied) {
201 elog("No reply to message {0}({1})", Method, ID);
202 assert(false && "must reply to all calls!");
203 (*this)(make_error<LSPError>("server failed to reply",
204 ErrorCode::InternalError));
205 }
206 }
207
208 void operator()(Expected<json::Value> Reply) {
209 assert(Server && "moved-from!");
210 if (Replied.exchange(true)) {
211 elog("Replied twice to message {0}({1})", Method, ID);
212 assert(false && "must reply to each call only once!");
213 return;
214 }
Sam McCalld7babe42018-10-24 15:18:40 +0000215 auto Duration = std::chrono::steady_clock::now() - Start;
216 if (Reply) {
217 log("--> reply:{0}({1}) {2:ms}", Method, ID, Duration);
218 if (TraceArgs)
Sam McCalle2f3a732018-10-24 14:26:26 +0000219 (*TraceArgs)["Reply"] = *Reply;
Sam McCalld7babe42018-10-24 15:18:40 +0000220 std::lock_guard<std::mutex> Lock(Server->TranspWriter);
221 Server->Transp.reply(std::move(ID), std::move(Reply));
222 } else {
223 Error Err = Reply.takeError();
224 log("--> reply:{0}({1}) {2:ms}, error: {3}", Method, ID, Duration, Err);
225 if (TraceArgs)
Sam McCalle2f3a732018-10-24 14:26:26 +0000226 (*TraceArgs)["Error"] = to_string(Err);
Sam McCalld7babe42018-10-24 15:18:40 +0000227 std::lock_guard<std::mutex> Lock(Server->TranspWriter);
228 Server->Transp.reply(std::move(ID), std::move(Err));
Sam McCalle2f3a732018-10-24 14:26:26 +0000229 }
Sam McCalle2f3a732018-10-24 14:26:26 +0000230 }
231 };
232
Sam McCallc008af62018-10-20 15:30:37 +0000233 StringMap<std::function<void(json::Value)>> Notifications;
Sam McCalle2f3a732018-10-24 14:26:26 +0000234 StringMap<std::function<void(json::Value, ReplyOnce)>> Calls;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000235
236 // Method calls may be cancelled by ID, so keep track of their state.
237 // This needs a mutex: handlers may finish on a different thread, and that's
238 // when we clean up entries in the map.
239 mutable std::mutex RequestCancelersMutex;
Sam McCallc008af62018-10-20 15:30:37 +0000240 StringMap<std::pair<Canceler, /*Cookie*/ unsigned>> RequestCancelers;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000241 unsigned NextRequestCookie = 0; // To disambiguate reused IDs, see below.
Sam McCallc008af62018-10-20 15:30:37 +0000242 void onCancel(const json::Value &Params) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000243 const json::Value *ID = nullptr;
244 if (auto *O = Params.getAsObject())
245 ID = O->get("id");
246 if (!ID) {
247 elog("Bad cancellation request: {0}", Params);
248 return;
249 }
Sam McCallc008af62018-10-20 15:30:37 +0000250 auto StrID = to_string(*ID);
Sam McCall2c30fbc2018-10-18 12:32:04 +0000251 std::lock_guard<std::mutex> Lock(RequestCancelersMutex);
252 auto It = RequestCancelers.find(StrID);
253 if (It != RequestCancelers.end())
254 It->second.first(); // Invoke the canceler.
255 }
256 // We run cancelable requests in a context that does two things:
257 // - allows cancellation using RequestCancelers[ID]
258 // - cleans up the entry in RequestCancelers when it's no longer needed
259 // If a client reuses an ID, the last wins and the first cannot be canceled.
260 Context cancelableRequestContext(const json::Value &ID) {
261 auto Task = cancelableTask();
Sam McCallc008af62018-10-20 15:30:37 +0000262 auto StrID = to_string(ID); // JSON-serialize ID for map key.
Sam McCall2c30fbc2018-10-18 12:32:04 +0000263 auto Cookie = NextRequestCookie++; // No lock, only called on main thread.
264 {
265 std::lock_guard<std::mutex> Lock(RequestCancelersMutex);
266 RequestCancelers[StrID] = {std::move(Task.second), Cookie};
267 }
268 // When the request ends, we can clean up the entry we just added.
269 // The cookie lets us check that it hasn't been overwritten due to ID
270 // reuse.
271 return Task.first.derive(make_scope_exit([this, StrID, Cookie] {
272 std::lock_guard<std::mutex> Lock(RequestCancelersMutex);
273 auto It = RequestCancelers.find(StrID);
274 if (It != RequestCancelers.end() && It->second.second == Cookie)
275 RequestCancelers.erase(It);
276 }));
277 }
278
279 ClangdLSPServer &Server;
280};
281
282// call(), notify(), and reply() wrap the Transport, adding logging and locking.
283void ClangdLSPServer::call(StringRef Method, json::Value Params) {
284 auto ID = NextCallID++;
285 log("--> {0}({1})", Method, ID);
286 // We currently don't handle responses, so no need to store ID anywhere.
287 std::lock_guard<std::mutex> Lock(TranspWriter);
288 Transp.call(Method, std::move(Params), ID);
289}
290
291void ClangdLSPServer::notify(StringRef Method, json::Value Params) {
292 log("--> {0}", Method);
293 std::lock_guard<std::mutex> Lock(TranspWriter);
294 Transp.notify(Method, std::move(Params));
295}
296
Sam McCall2c30fbc2018-10-18 12:32:04 +0000297void ClangdLSPServer::onInitialize(const InitializeParams &Params,
298 Callback<json::Value> Reply) {
Sam McCall0d9b40f2018-10-19 15:42:23 +0000299 if (Params.rootUri && *Params.rootUri)
300 ClangdServerOpts.WorkspaceRoot = Params.rootUri->file();
301 else if (Params.rootPath && !Params.rootPath->empty())
302 ClangdServerOpts.WorkspaceRoot = *Params.rootPath;
Sam McCall3d0adbe2018-10-18 14:41:50 +0000303 if (Server)
304 return Reply(make_error<LSPError>("server already initialized",
305 ErrorCode::InvalidRequest));
Sam McCallbc904612018-10-25 04:22:52 +0000306 if (const auto &Dir = Params.initializationOptions.compilationDatabasePath)
307 CompileCommandsDir = Dir;
Sam McCallc55d09a2018-11-02 13:09:36 +0000308 if (UseDirBasedCDB)
309 BaseCDB = llvm::make_unique<DirectoryBasedGlobalCompilationDatabase>(
310 CompileCommandsDir);
311 CDB.emplace(BaseCDB.get());
312 Server.emplace(*CDB, FSProvider, static_cast<DiagnosticsConsumer &>(*this),
313 ClangdServerOpts);
Sam McCallbc904612018-10-25 04:22:52 +0000314 applyConfiguration(Params.initializationOptions.ConfigSettings);
Simon Marchi88016782018-08-01 11:28:49 +0000315
Sam McCallbf6a2fc2018-10-17 07:33:42 +0000316 CCOpts.EnableSnippets = Params.capabilities.CompletionSnippets;
317 DiagOpts.EmbedFixesInDiagnostics = Params.capabilities.DiagnosticFixes;
318 DiagOpts.SendDiagnosticCategory = Params.capabilities.DiagnosticCategory;
319 if (Params.capabilities.WorkspaceSymbolKinds)
320 SupportedSymbolKinds |= *Params.capabilities.WorkspaceSymbolKinds;
321 if (Params.capabilities.CompletionItemKinds)
322 SupportedCompletionItemKinds |= *Params.capabilities.CompletionItemKinds;
323 SupportsCodeAction = Params.capabilities.CodeActionStructure;
Kadir Cetinkaya133d46f2018-09-27 17:13:07 +0000324
Sam McCall2c30fbc2018-10-18 12:32:04 +0000325 Reply(json::Object{
Sam McCall0930ab02017-11-07 15:49:35 +0000326 {{"capabilities",
Sam McCalld20d7982018-07-09 14:25:59 +0000327 json::Object{
Simon Marchi98082622018-03-26 14:41:40 +0000328 {"textDocumentSync", (int)TextDocumentSyncKind::Incremental},
Sam McCall0930ab02017-11-07 15:49:35 +0000329 {"documentFormattingProvider", true},
330 {"documentRangeFormattingProvider", true},
331 {"documentOnTypeFormattingProvider",
Sam McCalld20d7982018-07-09 14:25:59 +0000332 json::Object{
Sam McCall0930ab02017-11-07 15:49:35 +0000333 {"firstTriggerCharacter", "}"},
334 {"moreTriggerCharacter", {}},
335 }},
336 {"codeActionProvider", true},
337 {"completionProvider",
Sam McCalld20d7982018-07-09 14:25:59 +0000338 json::Object{
Sam McCall0930ab02017-11-07 15:49:35 +0000339 {"resolveProvider", false},
340 {"triggerCharacters", {".", ">", ":"}},
341 }},
342 {"signatureHelpProvider",
Sam McCalld20d7982018-07-09 14:25:59 +0000343 json::Object{
Sam McCall0930ab02017-11-07 15:49:35 +0000344 {"triggerCharacters", {"(", ","}},
345 }},
346 {"definitionProvider", true},
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000347 {"documentHighlightProvider", true},
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000348 {"hoverProvider", true},
Haojian Wu345099c2017-11-09 11:30:04 +0000349 {"renameProvider", true},
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000350 {"documentSymbolProvider", true},
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000351 {"workspaceSymbolProvider", true},
Sam McCall1ad142f2018-09-05 11:53:07 +0000352 {"referencesProvider", true},
Sam McCall0930ab02017-11-07 15:49:35 +0000353 {"executeCommandProvider",
Sam McCalld20d7982018-07-09 14:25:59 +0000354 json::Object{
Eric Liu2c190532018-05-15 15:23:53 +0000355 {"commands", {ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND}},
Sam McCall0930ab02017-11-07 15:49:35 +0000356 }},
357 }}}});
Ilya Biryukovafb55542017-05-16 14:40:30 +0000358}
359
Sam McCall2c30fbc2018-10-18 12:32:04 +0000360void ClangdLSPServer::onShutdown(const ShutdownParams &Params,
361 Callback<std::nullptr_t> Reply) {
Ilya Biryukov0d9b8a32017-10-25 08:45:41 +0000362 // Do essentially nothing, just say we're ready to exit.
363 ShutdownRequestReceived = true;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000364 Reply(nullptr);
Sam McCall8a5dded2017-10-12 13:29:58 +0000365}
Ilya Biryukovafb55542017-05-16 14:40:30 +0000366
Sam McCall2c30fbc2018-10-18 12:32:04 +0000367void ClangdLSPServer::onDocumentDidOpen(
368 const DidOpenTextDocumentParams &Params) {
Simon Marchi9569fd52018-03-16 14:30:42 +0000369 PathRef File = Params.textDocument.uri.file();
Ilya Biryukovb10ef472018-06-13 09:20:41 +0000370
Sam McCall2c30fbc2018-10-18 12:32:04 +0000371 const std::string &Contents = Params.textDocument.text;
Simon Marchi9569fd52018-03-16 14:30:42 +0000372
Simon Marchi98082622018-03-26 14:41:40 +0000373 DraftMgr.addDraft(File, Contents);
Ilya Biryukov652364b2018-09-26 05:48:29 +0000374 Server->addDocument(File, Contents, WantDiagnostics::Yes);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000375}
376
Sam McCall2c30fbc2018-10-18 12:32:04 +0000377void ClangdLSPServer::onDocumentDidChange(
378 const DidChangeTextDocumentParams &Params) {
Eric Liu51fed182018-02-22 18:40:39 +0000379 auto WantDiags = WantDiagnostics::Auto;
380 if (Params.wantDiagnostics.hasValue())
381 WantDiags = Params.wantDiagnostics.getValue() ? WantDiagnostics::Yes
382 : WantDiagnostics::No;
Simon Marchi9569fd52018-03-16 14:30:42 +0000383
384 PathRef File = Params.textDocument.uri.file();
Sam McCallc008af62018-10-20 15:30:37 +0000385 Expected<std::string> Contents =
Simon Marchi98082622018-03-26 14:41:40 +0000386 DraftMgr.updateDraft(File, Params.contentChanges);
387 if (!Contents) {
388 // If this fails, we are most likely going to be not in sync anymore with
389 // the client. It is better to remove the draft and let further operations
390 // fail rather than giving wrong results.
391 DraftMgr.removeDraft(File);
Ilya Biryukov652364b2018-09-26 05:48:29 +0000392 Server->removeDocument(File);
Sam McCallbed58852018-07-11 10:35:11 +0000393 elog("Failed to update {0}: {1}", File, Contents.takeError());
Simon Marchi98082622018-03-26 14:41:40 +0000394 return;
395 }
Simon Marchi9569fd52018-03-16 14:30:42 +0000396
Ilya Biryukov652364b2018-09-26 05:48:29 +0000397 Server->addDocument(File, *Contents, WantDiags);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000398}
399
Sam McCall2c30fbc2018-10-18 12:32:04 +0000400void ClangdLSPServer::onFileEvent(const DidChangeWatchedFilesParams &Params) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000401 Server->onFileEvent(Params);
Marc-Andre Laperlebf114242017-10-02 18:00:37 +0000402}
403
Sam McCall2c30fbc2018-10-18 12:32:04 +0000404void ClangdLSPServer::onCommand(const ExecuteCommandParams &Params,
405 Callback<json::Value> Reply) {
406 auto ApplyEdit = [&](WorkspaceEdit WE) {
Eric Liuc5105f92018-02-16 14:15:55 +0000407 ApplyWorkspaceEditParams Edit;
408 Edit.edit = std::move(WE);
Eric Liuc5105f92018-02-16 14:15:55 +0000409 // Ideally, we would wait for the response and if there is no error, we
410 // would reply success/failure to the original RPC.
411 call("workspace/applyEdit", Edit);
412 };
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000413 if (Params.command == ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND &&
414 Params.workspaceEdit) {
415 // The flow for "apply-fix" :
416 // 1. We publish a diagnostic, including fixits
417 // 2. The user clicks on the diagnostic, the editor asks us for code actions
418 // 3. We send code actions, with the fixit embedded as context
419 // 4. The user selects the fixit, the editor asks us to apply it
420 // 5. We unwrap the changes and send them back to the editor
421 // 6. The editor applies the changes (applyEdit), and sends us a reply (but
422 // we ignore it)
423
Sam McCall2c30fbc2018-10-18 12:32:04 +0000424 Reply("Fix applied.");
Eric Liuc5105f92018-02-16 14:15:55 +0000425 ApplyEdit(*Params.workspaceEdit);
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000426 } else {
427 // We should not get here because ExecuteCommandParams would not have
428 // parsed in the first place and this handler should not be called. But if
429 // more commands are added, this will be here has a safe guard.
Sam McCall2c30fbc2018-10-18 12:32:04 +0000430 Reply(make_error<LSPError>(
Sam McCallc008af62018-10-20 15:30:37 +0000431 formatv("Unsupported command \"{0}\".", Params.command).str(),
Sam McCall2c30fbc2018-10-18 12:32:04 +0000432 ErrorCode::InvalidParams));
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000433 }
434}
435
Sam McCall2c30fbc2018-10-18 12:32:04 +0000436void ClangdLSPServer::onWorkspaceSymbol(
437 const WorkspaceSymbolParams &Params,
438 Callback<std::vector<SymbolInformation>> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000439 Server->workspaceSymbols(
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000440 Params.query, CCOpts.Limit,
Sam McCall2c30fbc2018-10-18 12:32:04 +0000441 Bind(
442 [this](decltype(Reply) Reply,
Sam McCallc008af62018-10-20 15:30:37 +0000443 Expected<std::vector<SymbolInformation>> Items) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000444 if (!Items)
445 return Reply(Items.takeError());
446 for (auto &Sym : *Items)
447 Sym.kind = adjustKindToCapability(Sym.kind, SupportedSymbolKinds);
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000448
Sam McCall2c30fbc2018-10-18 12:32:04 +0000449 Reply(std::move(*Items));
450 },
451 std::move(Reply)));
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000452}
453
Sam McCall2c30fbc2018-10-18 12:32:04 +0000454void ClangdLSPServer::onRename(const RenameParams &Params,
455 Callback<WorkspaceEdit> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000456 Path File = Params.textDocument.uri.file();
Sam McCallc008af62018-10-20 15:30:37 +0000457 Optional<std::string> Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000458 if (!Code)
Sam McCall2c30fbc2018-10-18 12:32:04 +0000459 return Reply(make_error<LSPError>("onRename called for non-added file",
460 ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000461
Ilya Biryukov652364b2018-09-26 05:48:29 +0000462 Server->rename(
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000463 File, Params.position, Params.newName,
Sam McCall2c30fbc2018-10-18 12:32:04 +0000464 Bind(
Sam McCallc008af62018-10-20 15:30:37 +0000465 [File, Code,
466 Params](decltype(Reply) Reply,
467 Expected<std::vector<tooling::Replacement>> Replacements) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000468 if (!Replacements)
469 return Reply(Replacements.takeError());
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000470
Sam McCall2c30fbc2018-10-18 12:32:04 +0000471 // Turn the replacements into the format specified by the Language
472 // Server Protocol. Fuse them into one big JSON array.
473 std::vector<TextEdit> Edits;
474 for (const auto &R : *Replacements)
475 Edits.push_back(replacementToEdit(*Code, R));
476 WorkspaceEdit WE;
477 WE.changes = {{Params.textDocument.uri.uri(), Edits}};
478 Reply(WE);
479 },
480 std::move(Reply)));
Haojian Wu345099c2017-11-09 11:30:04 +0000481}
482
Sam McCall2c30fbc2018-10-18 12:32:04 +0000483void ClangdLSPServer::onDocumentDidClose(
484 const DidCloseTextDocumentParams &Params) {
Simon Marchi9569fd52018-03-16 14:30:42 +0000485 PathRef File = Params.textDocument.uri.file();
486 DraftMgr.removeDraft(File);
Ilya Biryukov652364b2018-09-26 05:48:29 +0000487 Server->removeDocument(File);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000488}
489
Sam McCall4db732a2017-09-30 10:08:52 +0000490void ClangdLSPServer::onDocumentOnTypeFormatting(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000491 const DocumentOnTypeFormattingParams &Params,
492 Callback<std::vector<TextEdit>> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000493 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000494 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000495 if (!Code)
Sam McCall2c30fbc2018-10-18 12:32:04 +0000496 return Reply(make_error<LSPError>(
497 "onDocumentOnTypeFormatting called for non-added file",
498 ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000499
Ilya Biryukov652364b2018-09-26 05:48:29 +0000500 auto ReplacementsOrError = Server->formatOnType(*Code, File, Params.position);
Raoul Wols212bcf82017-12-12 20:25:06 +0000501 if (ReplacementsOrError)
Sam McCall2c30fbc2018-10-18 12:32:04 +0000502 Reply(replacementsToEdits(*Code, ReplacementsOrError.get()));
Raoul Wols212bcf82017-12-12 20:25:06 +0000503 else
Sam McCall2c30fbc2018-10-18 12:32:04 +0000504 Reply(ReplacementsOrError.takeError());
Ilya Biryukovafb55542017-05-16 14:40:30 +0000505}
506
Sam McCall4db732a2017-09-30 10:08:52 +0000507void ClangdLSPServer::onDocumentRangeFormatting(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000508 const DocumentRangeFormattingParams &Params,
509 Callback<std::vector<TextEdit>> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000510 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000511 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000512 if (!Code)
Sam McCall2c30fbc2018-10-18 12:32:04 +0000513 return Reply(make_error<LSPError>(
514 "onDocumentRangeFormatting called for non-added file",
515 ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000516
Ilya Biryukov652364b2018-09-26 05:48:29 +0000517 auto ReplacementsOrError = Server->formatRange(*Code, File, Params.range);
Raoul Wols212bcf82017-12-12 20:25:06 +0000518 if (ReplacementsOrError)
Sam McCall2c30fbc2018-10-18 12:32:04 +0000519 Reply(replacementsToEdits(*Code, ReplacementsOrError.get()));
Raoul Wols212bcf82017-12-12 20:25:06 +0000520 else
Sam McCall2c30fbc2018-10-18 12:32:04 +0000521 Reply(ReplacementsOrError.takeError());
Ilya Biryukovafb55542017-05-16 14:40:30 +0000522}
523
Sam McCall2c30fbc2018-10-18 12:32:04 +0000524void ClangdLSPServer::onDocumentFormatting(
525 const DocumentFormattingParams &Params,
526 Callback<std::vector<TextEdit>> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000527 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000528 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000529 if (!Code)
Sam McCall2c30fbc2018-10-18 12:32:04 +0000530 return Reply(
531 make_error<LSPError>("onDocumentFormatting called for non-added file",
532 ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000533
Ilya Biryukov652364b2018-09-26 05:48:29 +0000534 auto ReplacementsOrError = Server->formatFile(*Code, File);
Raoul Wols212bcf82017-12-12 20:25:06 +0000535 if (ReplacementsOrError)
Sam McCall2c30fbc2018-10-18 12:32:04 +0000536 Reply(replacementsToEdits(*Code, ReplacementsOrError.get()));
Raoul Wols212bcf82017-12-12 20:25:06 +0000537 else
Sam McCall2c30fbc2018-10-18 12:32:04 +0000538 Reply(ReplacementsOrError.takeError());
Sam McCall4db732a2017-09-30 10:08:52 +0000539}
540
Sam McCall2c30fbc2018-10-18 12:32:04 +0000541void ClangdLSPServer::onDocumentSymbol(
542 const DocumentSymbolParams &Params,
543 Callback<std::vector<SymbolInformation>> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000544 Server->documentSymbols(
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000545 Params.textDocument.uri.file(),
Sam McCall2c30fbc2018-10-18 12:32:04 +0000546 Bind(
547 [this](decltype(Reply) Reply,
Sam McCallc008af62018-10-20 15:30:37 +0000548 Expected<std::vector<SymbolInformation>> Items) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000549 if (!Items)
550 return Reply(Items.takeError());
551 for (auto &Sym : *Items)
552 Sym.kind = adjustKindToCapability(Sym.kind, SupportedSymbolKinds);
553 Reply(std::move(*Items));
554 },
555 std::move(Reply)));
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000556}
557
Sam McCall20841d42018-10-16 16:29:41 +0000558static Optional<Command> asCommand(const CodeAction &Action) {
559 Command Cmd;
560 if (Action.command && Action.edit)
Sam McCallc008af62018-10-20 15:30:37 +0000561 return None; // Not representable. (We never emit these anyway).
Sam McCall20841d42018-10-16 16:29:41 +0000562 if (Action.command) {
563 Cmd = *Action.command;
564 } else if (Action.edit) {
565 Cmd.command = Command::CLANGD_APPLY_FIX_COMMAND;
566 Cmd.workspaceEdit = *Action.edit;
567 } else {
Sam McCallc008af62018-10-20 15:30:37 +0000568 return None;
Sam McCall20841d42018-10-16 16:29:41 +0000569 }
570 Cmd.title = Action.title;
571 if (Action.kind && *Action.kind == CodeAction::QUICKFIX_KIND)
572 Cmd.title = "Apply fix: " + Cmd.title;
573 return Cmd;
574}
575
Sam McCall2c30fbc2018-10-18 12:32:04 +0000576void ClangdLSPServer::onCodeAction(const CodeActionParams &Params,
577 Callback<json::Value> Reply) {
578 auto Code = DraftMgr.getDraft(Params.textDocument.uri.file());
579 if (!Code)
580 return Reply(make_error<LSPError>("onCodeAction called for non-added file",
581 ErrorCode::InvalidParams));
Sam McCall20841d42018-10-16 16:29:41 +0000582 // We provide a code action for Fixes on the specified diagnostics.
Sam McCall20841d42018-10-16 16:29:41 +0000583 std::vector<CodeAction> Actions;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000584 for (const Diagnostic &D : Params.context.diagnostics) {
Ilya Biryukov71028b82018-03-12 15:28:22 +0000585 for (auto &F : getFixes(Params.textDocument.uri.file(), D)) {
Sam McCall16e70702018-10-24 07:59:38 +0000586 Actions.push_back(toCodeAction(F, Params.textDocument.uri));
Sam McCall20841d42018-10-16 16:29:41 +0000587 Actions.back().diagnostics = {D};
Sam McCalldd0566b2017-11-06 15:40:30 +0000588 }
Ilya Biryukovafb55542017-05-16 14:40:30 +0000589 }
Sam McCall20841d42018-10-16 16:29:41 +0000590
591 if (SupportsCodeAction)
Sam McCall2c30fbc2018-10-18 12:32:04 +0000592 Reply(json::Array(Actions));
Sam McCall20841d42018-10-16 16:29:41 +0000593 else {
594 std::vector<Command> Commands;
595 for (const auto &Action : Actions)
596 if (auto Command = asCommand(Action))
597 Commands.push_back(std::move(*Command));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000598 Reply(json::Array(Commands));
Sam McCall20841d42018-10-16 16:29:41 +0000599 }
Ilya Biryukovafb55542017-05-16 14:40:30 +0000600}
601
Sam McCall2c30fbc2018-10-18 12:32:04 +0000602void ClangdLSPServer::onCompletion(const TextDocumentPositionParams &Params,
603 Callback<CompletionList> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000604 Server->codeComplete(Params.textDocument.uri.file(), Params.position, CCOpts,
Sam McCall2c30fbc2018-10-18 12:32:04 +0000605 Bind(
606 [this](decltype(Reply) Reply,
Sam McCallc008af62018-10-20 15:30:37 +0000607 Expected<CodeCompleteResult> List) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000608 if (!List)
609 return Reply(List.takeError());
610 CompletionList LSPList;
611 LSPList.isIncomplete = List->HasMore;
612 for (const auto &R : List->Completions) {
613 CompletionItem C = R.render(CCOpts);
614 C.kind = adjustKindToCapability(
615 C.kind, SupportedCompletionItemKinds);
616 LSPList.items.push_back(std::move(C));
617 }
618 return Reply(std::move(LSPList));
619 },
620 std::move(Reply)));
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000621}
622
Sam McCall2c30fbc2018-10-18 12:32:04 +0000623void ClangdLSPServer::onSignatureHelp(const TextDocumentPositionParams &Params,
624 Callback<SignatureHelp> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000625 Server->signatureHelp(Params.textDocument.uri.file(), Params.position,
Sam McCall2c30fbc2018-10-18 12:32:04 +0000626 std::move(Reply));
Ilya Biryukov652364b2018-09-26 05:48:29 +0000627}
628
Sam McCall2c30fbc2018-10-18 12:32:04 +0000629void ClangdLSPServer::onGoToDefinition(const TextDocumentPositionParams &Params,
630 Callback<std::vector<Location>> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000631 Server->findDefinitions(Params.textDocument.uri.file(), Params.position,
Sam McCall2c30fbc2018-10-18 12:32:04 +0000632 std::move(Reply));
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000633}
634
Sam McCall2c30fbc2018-10-18 12:32:04 +0000635void ClangdLSPServer::onSwitchSourceHeader(const TextDocumentIdentifier &Params,
636 Callback<std::string> Reply) {
Sam McCallc008af62018-10-20 15:30:37 +0000637 Optional<Path> Result = Server->switchSourceHeader(Params.uri.file());
Sam McCall2c30fbc2018-10-18 12:32:04 +0000638 Reply(Result ? URI::createFile(*Result).toString() : "");
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000639}
640
Sam McCall2c30fbc2018-10-18 12:32:04 +0000641void ClangdLSPServer::onDocumentHighlight(
642 const TextDocumentPositionParams &Params,
643 Callback<std::vector<DocumentHighlight>> Reply) {
644 Server->findDocumentHighlights(Params.textDocument.uri.file(),
645 Params.position, std::move(Reply));
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000646}
647
Sam McCall2c30fbc2018-10-18 12:32:04 +0000648void ClangdLSPServer::onHover(const TextDocumentPositionParams &Params,
Sam McCallc008af62018-10-20 15:30:37 +0000649 Callback<Optional<Hover>> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000650 Server->findHover(Params.textDocument.uri.file(), Params.position,
Sam McCall2c30fbc2018-10-18 12:32:04 +0000651 std::move(Reply));
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000652}
653
Simon Marchi88016782018-08-01 11:28:49 +0000654void ClangdLSPServer::applyConfiguration(
Sam McCallbc904612018-10-25 04:22:52 +0000655 const ConfigurationSettings &Settings) {
Simon Marchiabeed662018-10-16 15:55:03 +0000656 // Per-file update to the compilation database.
Sam McCallbc904612018-10-25 04:22:52 +0000657 bool ShouldReparseOpenFiles = false;
658 for (auto &Entry : Settings.compilationDatabaseChanges) {
659 /// The opened files need to be reparsed only when some existing
660 /// entries are changed.
661 PathRef File = Entry.first;
Sam McCallc55d09a2018-11-02 13:09:36 +0000662 auto Old = CDB->getCompileCommand(File);
663 auto New =
664 tooling::CompileCommand(std::move(Entry.second.workingDirectory), File,
665 std::move(Entry.second.compilationCommand),
666 /*Output=*/"");
667 if (Old != New)
668 CDB->setCompileCommand(File, std::move(New));
669 ShouldReparseOpenFiles = true;
Alex Lorenzf8087862018-08-01 17:39:29 +0000670 }
Sam McCallbc904612018-10-25 04:22:52 +0000671 if (ShouldReparseOpenFiles)
672 reparseOpenedFiles();
Simon Marchi5178f922018-02-22 14:00:39 +0000673}
674
Simon Marchi88016782018-08-01 11:28:49 +0000675// FIXME: This function needs to be properly tested.
676void ClangdLSPServer::onChangeConfiguration(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000677 const DidChangeConfigurationParams &Params) {
Simon Marchi88016782018-08-01 11:28:49 +0000678 applyConfiguration(Params.settings);
679}
680
Sam McCall2c30fbc2018-10-18 12:32:04 +0000681void ClangdLSPServer::onReference(const ReferenceParams &Params,
682 Callback<std::vector<Location>> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000683 Server->findReferences(Params.textDocument.uri.file(), Params.position,
Sam McCall2c30fbc2018-10-18 12:32:04 +0000684 std::move(Reply));
Sam McCall1ad142f2018-09-05 11:53:07 +0000685}
686
Sam McCalldc8f3cf2018-10-17 07:32:05 +0000687ClangdLSPServer::ClangdLSPServer(class Transport &Transp,
Sam McCalladccab62017-11-23 16:58:22 +0000688 const clangd::CodeCompleteOptions &CCOpts,
Sam McCallc008af62018-10-20 15:30:37 +0000689 Optional<Path> CompileCommandsDir,
Sam McCallc55d09a2018-11-02 13:09:36 +0000690 bool UseDirBasedCDB,
Sam McCall7363a2f2018-03-05 17:28:54 +0000691 const ClangdServer::Options &Opts)
Sam McCalld1c9d112018-10-23 14:19:54 +0000692 : Transp(Transp), MsgHandler(new MessageHandler(*this)), CCOpts(CCOpts),
693 SupportedSymbolKinds(defaultSymbolKinds()),
Kadir Cetinkaya133d46f2018-09-27 17:13:07 +0000694 SupportedCompletionItemKinds(defaultCompletionItemKinds()),
Sam McCallc55d09a2018-11-02 13:09:36 +0000695 UseDirBasedCDB(UseDirBasedCDB),
Sam McCall4b86bb02018-10-25 02:22:53 +0000696 CompileCommandsDir(std::move(CompileCommandsDir)),
697 ClangdServerOpts(Opts) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000698 // clang-format off
699 MsgHandler->bind("initialize", &ClangdLSPServer::onInitialize);
700 MsgHandler->bind("shutdown", &ClangdLSPServer::onShutdown);
701 MsgHandler->bind("textDocument/rangeFormatting", &ClangdLSPServer::onDocumentRangeFormatting);
702 MsgHandler->bind("textDocument/onTypeFormatting", &ClangdLSPServer::onDocumentOnTypeFormatting);
703 MsgHandler->bind("textDocument/formatting", &ClangdLSPServer::onDocumentFormatting);
704 MsgHandler->bind("textDocument/codeAction", &ClangdLSPServer::onCodeAction);
705 MsgHandler->bind("textDocument/completion", &ClangdLSPServer::onCompletion);
706 MsgHandler->bind("textDocument/signatureHelp", &ClangdLSPServer::onSignatureHelp);
707 MsgHandler->bind("textDocument/definition", &ClangdLSPServer::onGoToDefinition);
708 MsgHandler->bind("textDocument/references", &ClangdLSPServer::onReference);
709 MsgHandler->bind("textDocument/switchSourceHeader", &ClangdLSPServer::onSwitchSourceHeader);
710 MsgHandler->bind("textDocument/rename", &ClangdLSPServer::onRename);
711 MsgHandler->bind("textDocument/hover", &ClangdLSPServer::onHover);
712 MsgHandler->bind("textDocument/documentSymbol", &ClangdLSPServer::onDocumentSymbol);
713 MsgHandler->bind("workspace/executeCommand", &ClangdLSPServer::onCommand);
714 MsgHandler->bind("textDocument/documentHighlight", &ClangdLSPServer::onDocumentHighlight);
715 MsgHandler->bind("workspace/symbol", &ClangdLSPServer::onWorkspaceSymbol);
716 MsgHandler->bind("textDocument/didOpen", &ClangdLSPServer::onDocumentDidOpen);
717 MsgHandler->bind("textDocument/didClose", &ClangdLSPServer::onDocumentDidClose);
718 MsgHandler->bind("textDocument/didChange", &ClangdLSPServer::onDocumentDidChange);
719 MsgHandler->bind("workspace/didChangeWatchedFiles", &ClangdLSPServer::onFileEvent);
720 MsgHandler->bind("workspace/didChangeConfiguration", &ClangdLSPServer::onChangeConfiguration);
721 // clang-format on
722}
723
724ClangdLSPServer::~ClangdLSPServer() = default;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000725
Sam McCalldc8f3cf2018-10-17 07:32:05 +0000726bool ClangdLSPServer::run() {
Ilya Biryukovafb55542017-05-16 14:40:30 +0000727 // Run the Language Server loop.
Sam McCalldc8f3cf2018-10-17 07:32:05 +0000728 bool CleanExit = true;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000729 if (auto Err = Transp.loop(*MsgHandler)) {
Sam McCalldc8f3cf2018-10-17 07:32:05 +0000730 elog("Transport error: {0}", std::move(Err));
731 CleanExit = false;
732 }
Ilya Biryukovafb55542017-05-16 14:40:30 +0000733
Ilya Biryukov652364b2018-09-26 05:48:29 +0000734 // Destroy ClangdServer to ensure all worker threads finish.
735 Server.reset();
Sam McCalldc8f3cf2018-10-17 07:32:05 +0000736 return CleanExit && ShutdownRequestReceived;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000737}
738
Ilya Biryukov71028b82018-03-12 15:28:22 +0000739std::vector<Fix> ClangdLSPServer::getFixes(StringRef File,
740 const clangd::Diagnostic &D) {
Ilya Biryukov38d79772017-05-16 09:38:59 +0000741 std::lock_guard<std::mutex> Lock(FixItsMutex);
742 auto DiagToFixItsIter = FixItsMap.find(File);
743 if (DiagToFixItsIter == FixItsMap.end())
744 return {};
745
746 const auto &DiagToFixItsMap = DiagToFixItsIter->second;
747 auto FixItsIter = DiagToFixItsMap.find(D);
748 if (FixItsIter == DiagToFixItsMap.end())
749 return {};
750
751 return FixItsIter->second;
752}
753
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000754void ClangdLSPServer::onDiagnosticsReady(PathRef File,
755 std::vector<Diag> Diagnostics) {
Sam McCall16e70702018-10-24 07:59:38 +0000756 URIForFile URI(File);
757 std::vector<Diagnostic> LSPDiagnostics;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000758 DiagnosticToReplacementMap LocalFixIts; // Temporary storage
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000759 for (auto &Diag : Diagnostics) {
Sam McCall16e70702018-10-24 07:59:38 +0000760 toLSPDiags(Diag, URI, DiagOpts,
761 [&](clangd::Diagnostic Diag, ArrayRef<Fix> Fixes) {
762 auto &FixItsForDiagnostic = LocalFixIts[Diag];
763 llvm::copy(Fixes, std::back_inserter(FixItsForDiagnostic));
764 LSPDiagnostics.push_back(std::move(Diag));
765 });
Ilya Biryukov38d79772017-05-16 09:38:59 +0000766 }
767
768 // Cache FixIts
769 {
770 // FIXME(ibiryukov): should be deleted when documents are removed
771 std::lock_guard<std::mutex> Lock(FixItsMutex);
772 FixItsMap[File] = LocalFixIts;
773 }
774
775 // Publish diagnostics.
Sam McCall2c30fbc2018-10-18 12:32:04 +0000776 notify("textDocument/publishDiagnostics",
777 json::Object{
Sam McCall16e70702018-10-24 07:59:38 +0000778 {"uri", URI},
779 {"diagnostics", std::move(LSPDiagnostics)},
Sam McCall2c30fbc2018-10-18 12:32:04 +0000780 });
Ilya Biryukov38d79772017-05-16 09:38:59 +0000781}
Simon Marchi9569fd52018-03-16 14:30:42 +0000782
783void ClangdLSPServer::reparseOpenedFiles() {
784 for (const Path &FilePath : DraftMgr.getActiveFiles())
Ilya Biryukov652364b2018-09-26 05:48:29 +0000785 Server->addDocument(FilePath, *DraftMgr.getDraft(FilePath),
786 WantDiagnostics::Auto);
Simon Marchi9569fd52018-03-16 14:30:42 +0000787}
Alex Lorenzf8087862018-08-01 17:39:29 +0000788
Sam McCallc008af62018-10-20 15:30:37 +0000789} // namespace clangd
790} // namespace clang