blob: 379fcfb81e680286224d04a907c838be026f66a8 [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};
176 json::Value ID;
177 std::string Method;
178 ClangdLSPServer *Server; // Null when moved-from.
179 json::Object *TraceArgs;
180
181 public:
182 ReplyOnce(const json::Value &ID, StringRef Method, ClangdLSPServer *Server,
183 json::Object *TraceArgs)
184 : ID(ID), Method(Method), Server(Server), TraceArgs(TraceArgs) {
185 assert(Server);
186 }
187 ReplyOnce(ReplyOnce &&Other)
188 : Replied(Other.Replied.load()), ID(std::move(Other.ID)),
189 Method(std::move(Other.Method)), Server(Other.Server),
190 TraceArgs(Other.TraceArgs) {
191 Other.Server = nullptr;
192 }
193 ReplyOnce& operator=(ReplyOnce&&) = delete;
194 ReplyOnce(const ReplyOnce &) = delete;
195 ReplyOnce& operator=(const ReplyOnce&) = delete;
196
197 ~ReplyOnce() {
198 if (Server && !Replied) {
199 elog("No reply to message {0}({1})", Method, ID);
200 assert(false && "must reply to all calls!");
201 (*this)(make_error<LSPError>("server failed to reply",
202 ErrorCode::InternalError));
203 }
204 }
205
206 void operator()(Expected<json::Value> Reply) {
207 assert(Server && "moved-from!");
208 if (Replied.exchange(true)) {
209 elog("Replied twice to message {0}({1})", Method, ID);
210 assert(false && "must reply to each call only once!");
211 return;
212 }
213 if (TraceArgs) {
214 if (Reply)
215 (*TraceArgs)["Reply"] = *Reply;
216 else {
217 auto Err = Reply.takeError();
218 (*TraceArgs)["Error"] = to_string(Err);
219 Reply = std::move(Err);
220 }
221 }
222 Server->reply(ID, std::move(Reply));
223 }
224 };
225
Sam McCallc008af62018-10-20 15:30:37 +0000226 StringMap<std::function<void(json::Value)>> Notifications;
Sam McCalle2f3a732018-10-24 14:26:26 +0000227 StringMap<std::function<void(json::Value, ReplyOnce)>> Calls;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000228
229 // Method calls may be cancelled by ID, so keep track of their state.
230 // This needs a mutex: handlers may finish on a different thread, and that's
231 // when we clean up entries in the map.
232 mutable std::mutex RequestCancelersMutex;
Sam McCallc008af62018-10-20 15:30:37 +0000233 StringMap<std::pair<Canceler, /*Cookie*/ unsigned>> RequestCancelers;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000234 unsigned NextRequestCookie = 0; // To disambiguate reused IDs, see below.
Sam McCallc008af62018-10-20 15:30:37 +0000235 void onCancel(const json::Value &Params) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000236 const json::Value *ID = nullptr;
237 if (auto *O = Params.getAsObject())
238 ID = O->get("id");
239 if (!ID) {
240 elog("Bad cancellation request: {0}", Params);
241 return;
242 }
Sam McCallc008af62018-10-20 15:30:37 +0000243 auto StrID = to_string(*ID);
Sam McCall2c30fbc2018-10-18 12:32:04 +0000244 std::lock_guard<std::mutex> Lock(RequestCancelersMutex);
245 auto It = RequestCancelers.find(StrID);
246 if (It != RequestCancelers.end())
247 It->second.first(); // Invoke the canceler.
248 }
249 // We run cancelable requests in a context that does two things:
250 // - allows cancellation using RequestCancelers[ID]
251 // - cleans up the entry in RequestCancelers when it's no longer needed
252 // If a client reuses an ID, the last wins and the first cannot be canceled.
253 Context cancelableRequestContext(const json::Value &ID) {
254 auto Task = cancelableTask();
Sam McCallc008af62018-10-20 15:30:37 +0000255 auto StrID = to_string(ID); // JSON-serialize ID for map key.
Sam McCall2c30fbc2018-10-18 12:32:04 +0000256 auto Cookie = NextRequestCookie++; // No lock, only called on main thread.
257 {
258 std::lock_guard<std::mutex> Lock(RequestCancelersMutex);
259 RequestCancelers[StrID] = {std::move(Task.second), Cookie};
260 }
261 // When the request ends, we can clean up the entry we just added.
262 // The cookie lets us check that it hasn't been overwritten due to ID
263 // reuse.
264 return Task.first.derive(make_scope_exit([this, StrID, Cookie] {
265 std::lock_guard<std::mutex> Lock(RequestCancelersMutex);
266 auto It = RequestCancelers.find(StrID);
267 if (It != RequestCancelers.end() && It->second.second == Cookie)
268 RequestCancelers.erase(It);
269 }));
270 }
271
272 ClangdLSPServer &Server;
273};
274
275// call(), notify(), and reply() wrap the Transport, adding logging and locking.
276void ClangdLSPServer::call(StringRef Method, json::Value Params) {
277 auto ID = NextCallID++;
278 log("--> {0}({1})", Method, ID);
279 // We currently don't handle responses, so no need to store ID anywhere.
280 std::lock_guard<std::mutex> Lock(TranspWriter);
281 Transp.call(Method, std::move(Params), ID);
282}
283
284void ClangdLSPServer::notify(StringRef Method, json::Value Params) {
285 log("--> {0}", Method);
286 std::lock_guard<std::mutex> Lock(TranspWriter);
287 Transp.notify(Method, std::move(Params));
288}
289
Sam McCallc008af62018-10-20 15:30:37 +0000290void ClangdLSPServer::reply(json::Value ID, Expected<json::Value> Result) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000291 if (Result) {
292 log("--> reply({0})", ID);
293 std::lock_guard<std::mutex> Lock(TranspWriter);
294 Transp.reply(std::move(ID), std::move(Result));
295 } else {
296 Error Err = Result.takeError();
297 log("--> reply({0}) error: {1}", ID, Err);
298 std::lock_guard<std::mutex> Lock(TranspWriter);
299 Transp.reply(std::move(ID), std::move(Err));
300 }
301}
302
303void ClangdLSPServer::onInitialize(const InitializeParams &Params,
304 Callback<json::Value> Reply) {
Sam McCall0d9b40f2018-10-19 15:42:23 +0000305 if (Params.rootUri && *Params.rootUri)
306 ClangdServerOpts.WorkspaceRoot = Params.rootUri->file();
307 else if (Params.rootPath && !Params.rootPath->empty())
308 ClangdServerOpts.WorkspaceRoot = *Params.rootPath;
Sam McCall3d0adbe2018-10-18 14:41:50 +0000309 if (Server)
310 return Reply(make_error<LSPError>("server already initialized",
311 ErrorCode::InvalidRequest));
Sam McCalld1c9d112018-10-23 14:19:54 +0000312 Optional<Path> CompileCommandsDir;
313 if (Params.initializationOptions)
314 CompileCommandsDir = Params.initializationOptions->compilationDatabasePath;
315 CDB.emplace(UseInMemoryCDB
316 ? CompilationDB::makeInMemory()
317 : CompilationDB::makeDirectoryBased(CompileCommandsDir));
318 Server.emplace(CDB->getCDB(), FSProvider,
Sam McCall3d0adbe2018-10-18 14:41:50 +0000319 static_cast<DiagnosticsConsumer &>(*this), ClangdServerOpts);
Sam McCalld1c9d112018-10-23 14:19:54 +0000320 if (Params.initializationOptions)
321 applyConfiguration(Params.initializationOptions->ParamsChange);
Simon Marchi88016782018-08-01 11:28:49 +0000322
Sam McCallbf6a2fc2018-10-17 07:33:42 +0000323 CCOpts.EnableSnippets = Params.capabilities.CompletionSnippets;
324 DiagOpts.EmbedFixesInDiagnostics = Params.capabilities.DiagnosticFixes;
325 DiagOpts.SendDiagnosticCategory = Params.capabilities.DiagnosticCategory;
326 if (Params.capabilities.WorkspaceSymbolKinds)
327 SupportedSymbolKinds |= *Params.capabilities.WorkspaceSymbolKinds;
328 if (Params.capabilities.CompletionItemKinds)
329 SupportedCompletionItemKinds |= *Params.capabilities.CompletionItemKinds;
330 SupportsCodeAction = Params.capabilities.CodeActionStructure;
Kadir Cetinkaya133d46f2018-09-27 17:13:07 +0000331
Sam McCall2c30fbc2018-10-18 12:32:04 +0000332 Reply(json::Object{
Sam McCall0930ab02017-11-07 15:49:35 +0000333 {{"capabilities",
Sam McCalld20d7982018-07-09 14:25:59 +0000334 json::Object{
Simon Marchi98082622018-03-26 14:41:40 +0000335 {"textDocumentSync", (int)TextDocumentSyncKind::Incremental},
Sam McCall0930ab02017-11-07 15:49:35 +0000336 {"documentFormattingProvider", true},
337 {"documentRangeFormattingProvider", true},
338 {"documentOnTypeFormattingProvider",
Sam McCalld20d7982018-07-09 14:25:59 +0000339 json::Object{
Sam McCall0930ab02017-11-07 15:49:35 +0000340 {"firstTriggerCharacter", "}"},
341 {"moreTriggerCharacter", {}},
342 }},
343 {"codeActionProvider", true},
344 {"completionProvider",
Sam McCalld20d7982018-07-09 14:25:59 +0000345 json::Object{
Sam McCall0930ab02017-11-07 15:49:35 +0000346 {"resolveProvider", false},
347 {"triggerCharacters", {".", ">", ":"}},
348 }},
349 {"signatureHelpProvider",
Sam McCalld20d7982018-07-09 14:25:59 +0000350 json::Object{
Sam McCall0930ab02017-11-07 15:49:35 +0000351 {"triggerCharacters", {"(", ","}},
352 }},
353 {"definitionProvider", true},
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000354 {"documentHighlightProvider", true},
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000355 {"hoverProvider", true},
Haojian Wu345099c2017-11-09 11:30:04 +0000356 {"renameProvider", true},
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000357 {"documentSymbolProvider", true},
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000358 {"workspaceSymbolProvider", true},
Sam McCall1ad142f2018-09-05 11:53:07 +0000359 {"referencesProvider", true},
Sam McCall0930ab02017-11-07 15:49:35 +0000360 {"executeCommandProvider",
Sam McCalld20d7982018-07-09 14:25:59 +0000361 json::Object{
Eric Liu2c190532018-05-15 15:23:53 +0000362 {"commands", {ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND}},
Sam McCall0930ab02017-11-07 15:49:35 +0000363 }},
364 }}}});
Ilya Biryukovafb55542017-05-16 14:40:30 +0000365}
366
Sam McCall2c30fbc2018-10-18 12:32:04 +0000367void ClangdLSPServer::onShutdown(const ShutdownParams &Params,
368 Callback<std::nullptr_t> Reply) {
Ilya Biryukov0d9b8a32017-10-25 08:45:41 +0000369 // Do essentially nothing, just say we're ready to exit.
370 ShutdownRequestReceived = true;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000371 Reply(nullptr);
Sam McCall8a5dded2017-10-12 13:29:58 +0000372}
Ilya Biryukovafb55542017-05-16 14:40:30 +0000373
Sam McCall2c30fbc2018-10-18 12:32:04 +0000374void ClangdLSPServer::onDocumentDidOpen(
375 const DidOpenTextDocumentParams &Params) {
Simon Marchi9569fd52018-03-16 14:30:42 +0000376 PathRef File = Params.textDocument.uri.file();
Alex Lorenzf8087862018-08-01 17:39:29 +0000377 if (Params.metadata && !Params.metadata->extraFlags.empty())
Sam McCalld1c9d112018-10-23 14:19:54 +0000378 CDB->setExtraFlagsForFile(File, std::move(Params.metadata->extraFlags));
Ilya Biryukovb10ef472018-06-13 09:20:41 +0000379
Sam McCall2c30fbc2018-10-18 12:32:04 +0000380 const std::string &Contents = Params.textDocument.text;
Simon Marchi9569fd52018-03-16 14:30:42 +0000381
Simon Marchi98082622018-03-26 14:41:40 +0000382 DraftMgr.addDraft(File, Contents);
Ilya Biryukov652364b2018-09-26 05:48:29 +0000383 Server->addDocument(File, Contents, WantDiagnostics::Yes);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000384}
385
Sam McCall2c30fbc2018-10-18 12:32:04 +0000386void ClangdLSPServer::onDocumentDidChange(
387 const DidChangeTextDocumentParams &Params) {
Eric Liu51fed182018-02-22 18:40:39 +0000388 auto WantDiags = WantDiagnostics::Auto;
389 if (Params.wantDiagnostics.hasValue())
390 WantDiags = Params.wantDiagnostics.getValue() ? WantDiagnostics::Yes
391 : WantDiagnostics::No;
Simon Marchi9569fd52018-03-16 14:30:42 +0000392
393 PathRef File = Params.textDocument.uri.file();
Sam McCallc008af62018-10-20 15:30:37 +0000394 Expected<std::string> Contents =
Simon Marchi98082622018-03-26 14:41:40 +0000395 DraftMgr.updateDraft(File, Params.contentChanges);
396 if (!Contents) {
397 // If this fails, we are most likely going to be not in sync anymore with
398 // the client. It is better to remove the draft and let further operations
399 // fail rather than giving wrong results.
400 DraftMgr.removeDraft(File);
Ilya Biryukov652364b2018-09-26 05:48:29 +0000401 Server->removeDocument(File);
Sam McCalld1c9d112018-10-23 14:19:54 +0000402 CDB->invalidate(File);
Sam McCallbed58852018-07-11 10:35:11 +0000403 elog("Failed to update {0}: {1}", File, Contents.takeError());
Simon Marchi98082622018-03-26 14:41:40 +0000404 return;
405 }
Simon Marchi9569fd52018-03-16 14:30:42 +0000406
Ilya Biryukov652364b2018-09-26 05:48:29 +0000407 Server->addDocument(File, *Contents, WantDiags);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000408}
409
Sam McCall2c30fbc2018-10-18 12:32:04 +0000410void ClangdLSPServer::onFileEvent(const DidChangeWatchedFilesParams &Params) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000411 Server->onFileEvent(Params);
Marc-Andre Laperlebf114242017-10-02 18:00:37 +0000412}
413
Sam McCall2c30fbc2018-10-18 12:32:04 +0000414void ClangdLSPServer::onCommand(const ExecuteCommandParams &Params,
415 Callback<json::Value> Reply) {
416 auto ApplyEdit = [&](WorkspaceEdit WE) {
Eric Liuc5105f92018-02-16 14:15:55 +0000417 ApplyWorkspaceEditParams Edit;
418 Edit.edit = std::move(WE);
Eric Liuc5105f92018-02-16 14:15:55 +0000419 // Ideally, we would wait for the response and if there is no error, we
420 // would reply success/failure to the original RPC.
421 call("workspace/applyEdit", Edit);
422 };
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000423 if (Params.command == ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND &&
424 Params.workspaceEdit) {
425 // The flow for "apply-fix" :
426 // 1. We publish a diagnostic, including fixits
427 // 2. The user clicks on the diagnostic, the editor asks us for code actions
428 // 3. We send code actions, with the fixit embedded as context
429 // 4. The user selects the fixit, the editor asks us to apply it
430 // 5. We unwrap the changes and send them back to the editor
431 // 6. The editor applies the changes (applyEdit), and sends us a reply (but
432 // we ignore it)
433
Sam McCall2c30fbc2018-10-18 12:32:04 +0000434 Reply("Fix applied.");
Eric Liuc5105f92018-02-16 14:15:55 +0000435 ApplyEdit(*Params.workspaceEdit);
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000436 } else {
437 // We should not get here because ExecuteCommandParams would not have
438 // parsed in the first place and this handler should not be called. But if
439 // more commands are added, this will be here has a safe guard.
Sam McCall2c30fbc2018-10-18 12:32:04 +0000440 Reply(make_error<LSPError>(
Sam McCallc008af62018-10-20 15:30:37 +0000441 formatv("Unsupported command \"{0}\".", Params.command).str(),
Sam McCall2c30fbc2018-10-18 12:32:04 +0000442 ErrorCode::InvalidParams));
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000443 }
444}
445
Sam McCall2c30fbc2018-10-18 12:32:04 +0000446void ClangdLSPServer::onWorkspaceSymbol(
447 const WorkspaceSymbolParams &Params,
448 Callback<std::vector<SymbolInformation>> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000449 Server->workspaceSymbols(
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000450 Params.query, CCOpts.Limit,
Sam McCall2c30fbc2018-10-18 12:32:04 +0000451 Bind(
452 [this](decltype(Reply) Reply,
Sam McCallc008af62018-10-20 15:30:37 +0000453 Expected<std::vector<SymbolInformation>> Items) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000454 if (!Items)
455 return Reply(Items.takeError());
456 for (auto &Sym : *Items)
457 Sym.kind = adjustKindToCapability(Sym.kind, SupportedSymbolKinds);
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000458
Sam McCall2c30fbc2018-10-18 12:32:04 +0000459 Reply(std::move(*Items));
460 },
461 std::move(Reply)));
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000462}
463
Sam McCall2c30fbc2018-10-18 12:32:04 +0000464void ClangdLSPServer::onRename(const RenameParams &Params,
465 Callback<WorkspaceEdit> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000466 Path File = Params.textDocument.uri.file();
Sam McCallc008af62018-10-20 15:30:37 +0000467 Optional<std::string> Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000468 if (!Code)
Sam McCall2c30fbc2018-10-18 12:32:04 +0000469 return Reply(make_error<LSPError>("onRename called for non-added file",
470 ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000471
Ilya Biryukov652364b2018-09-26 05:48:29 +0000472 Server->rename(
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000473 File, Params.position, Params.newName,
Sam McCall2c30fbc2018-10-18 12:32:04 +0000474 Bind(
Sam McCallc008af62018-10-20 15:30:37 +0000475 [File, Code,
476 Params](decltype(Reply) Reply,
477 Expected<std::vector<tooling::Replacement>> Replacements) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000478 if (!Replacements)
479 return Reply(Replacements.takeError());
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000480
Sam McCall2c30fbc2018-10-18 12:32:04 +0000481 // Turn the replacements into the format specified by the Language
482 // Server Protocol. Fuse them into one big JSON array.
483 std::vector<TextEdit> Edits;
484 for (const auto &R : *Replacements)
485 Edits.push_back(replacementToEdit(*Code, R));
486 WorkspaceEdit WE;
487 WE.changes = {{Params.textDocument.uri.uri(), Edits}};
488 Reply(WE);
489 },
490 std::move(Reply)));
Haojian Wu345099c2017-11-09 11:30:04 +0000491}
492
Sam McCall2c30fbc2018-10-18 12:32:04 +0000493void ClangdLSPServer::onDocumentDidClose(
494 const DidCloseTextDocumentParams &Params) {
Simon Marchi9569fd52018-03-16 14:30:42 +0000495 PathRef File = Params.textDocument.uri.file();
496 DraftMgr.removeDraft(File);
Ilya Biryukov652364b2018-09-26 05:48:29 +0000497 Server->removeDocument(File);
Sam McCalld1c9d112018-10-23 14:19:54 +0000498 CDB->invalidate(File);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000499}
500
Sam McCall4db732a2017-09-30 10:08:52 +0000501void ClangdLSPServer::onDocumentOnTypeFormatting(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000502 const DocumentOnTypeFormattingParams &Params,
503 Callback<std::vector<TextEdit>> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000504 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000505 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000506 if (!Code)
Sam McCall2c30fbc2018-10-18 12:32:04 +0000507 return Reply(make_error<LSPError>(
508 "onDocumentOnTypeFormatting called for non-added file",
509 ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000510
Ilya Biryukov652364b2018-09-26 05:48:29 +0000511 auto ReplacementsOrError = Server->formatOnType(*Code, File, Params.position);
Raoul Wols212bcf82017-12-12 20:25:06 +0000512 if (ReplacementsOrError)
Sam McCall2c30fbc2018-10-18 12:32:04 +0000513 Reply(replacementsToEdits(*Code, ReplacementsOrError.get()));
Raoul Wols212bcf82017-12-12 20:25:06 +0000514 else
Sam McCall2c30fbc2018-10-18 12:32:04 +0000515 Reply(ReplacementsOrError.takeError());
Ilya Biryukovafb55542017-05-16 14:40:30 +0000516}
517
Sam McCall4db732a2017-09-30 10:08:52 +0000518void ClangdLSPServer::onDocumentRangeFormatting(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000519 const DocumentRangeFormattingParams &Params,
520 Callback<std::vector<TextEdit>> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000521 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000522 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000523 if (!Code)
Sam McCall2c30fbc2018-10-18 12:32:04 +0000524 return Reply(make_error<LSPError>(
525 "onDocumentRangeFormatting called for non-added file",
526 ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000527
Ilya Biryukov652364b2018-09-26 05:48:29 +0000528 auto ReplacementsOrError = Server->formatRange(*Code, File, Params.range);
Raoul Wols212bcf82017-12-12 20:25:06 +0000529 if (ReplacementsOrError)
Sam McCall2c30fbc2018-10-18 12:32:04 +0000530 Reply(replacementsToEdits(*Code, ReplacementsOrError.get()));
Raoul Wols212bcf82017-12-12 20:25:06 +0000531 else
Sam McCall2c30fbc2018-10-18 12:32:04 +0000532 Reply(ReplacementsOrError.takeError());
Ilya Biryukovafb55542017-05-16 14:40:30 +0000533}
534
Sam McCall2c30fbc2018-10-18 12:32:04 +0000535void ClangdLSPServer::onDocumentFormatting(
536 const DocumentFormattingParams &Params,
537 Callback<std::vector<TextEdit>> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000538 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000539 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000540 if (!Code)
Sam McCall2c30fbc2018-10-18 12:32:04 +0000541 return Reply(
542 make_error<LSPError>("onDocumentFormatting called for non-added file",
543 ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000544
Ilya Biryukov652364b2018-09-26 05:48:29 +0000545 auto ReplacementsOrError = Server->formatFile(*Code, File);
Raoul Wols212bcf82017-12-12 20:25:06 +0000546 if (ReplacementsOrError)
Sam McCall2c30fbc2018-10-18 12:32:04 +0000547 Reply(replacementsToEdits(*Code, ReplacementsOrError.get()));
Raoul Wols212bcf82017-12-12 20:25:06 +0000548 else
Sam McCall2c30fbc2018-10-18 12:32:04 +0000549 Reply(ReplacementsOrError.takeError());
Sam McCall4db732a2017-09-30 10:08:52 +0000550}
551
Sam McCall2c30fbc2018-10-18 12:32:04 +0000552void ClangdLSPServer::onDocumentSymbol(
553 const DocumentSymbolParams &Params,
554 Callback<std::vector<SymbolInformation>> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000555 Server->documentSymbols(
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000556 Params.textDocument.uri.file(),
Sam McCall2c30fbc2018-10-18 12:32:04 +0000557 Bind(
558 [this](decltype(Reply) Reply,
Sam McCallc008af62018-10-20 15:30:37 +0000559 Expected<std::vector<SymbolInformation>> Items) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000560 if (!Items)
561 return Reply(Items.takeError());
562 for (auto &Sym : *Items)
563 Sym.kind = adjustKindToCapability(Sym.kind, SupportedSymbolKinds);
564 Reply(std::move(*Items));
565 },
566 std::move(Reply)));
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000567}
568
Sam McCall20841d42018-10-16 16:29:41 +0000569static Optional<Command> asCommand(const CodeAction &Action) {
570 Command Cmd;
571 if (Action.command && Action.edit)
Sam McCallc008af62018-10-20 15:30:37 +0000572 return None; // Not representable. (We never emit these anyway).
Sam McCall20841d42018-10-16 16:29:41 +0000573 if (Action.command) {
574 Cmd = *Action.command;
575 } else if (Action.edit) {
576 Cmd.command = Command::CLANGD_APPLY_FIX_COMMAND;
577 Cmd.workspaceEdit = *Action.edit;
578 } else {
Sam McCallc008af62018-10-20 15:30:37 +0000579 return None;
Sam McCall20841d42018-10-16 16:29:41 +0000580 }
581 Cmd.title = Action.title;
582 if (Action.kind && *Action.kind == CodeAction::QUICKFIX_KIND)
583 Cmd.title = "Apply fix: " + Cmd.title;
584 return Cmd;
585}
586
Sam McCall2c30fbc2018-10-18 12:32:04 +0000587void ClangdLSPServer::onCodeAction(const CodeActionParams &Params,
588 Callback<json::Value> Reply) {
589 auto Code = DraftMgr.getDraft(Params.textDocument.uri.file());
590 if (!Code)
591 return Reply(make_error<LSPError>("onCodeAction called for non-added file",
592 ErrorCode::InvalidParams));
Sam McCall20841d42018-10-16 16:29:41 +0000593 // We provide a code action for Fixes on the specified diagnostics.
Sam McCall20841d42018-10-16 16:29:41 +0000594 std::vector<CodeAction> Actions;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000595 for (const Diagnostic &D : Params.context.diagnostics) {
Ilya Biryukov71028b82018-03-12 15:28:22 +0000596 for (auto &F : getFixes(Params.textDocument.uri.file(), D)) {
Sam McCall16e70702018-10-24 07:59:38 +0000597 Actions.push_back(toCodeAction(F, Params.textDocument.uri));
Sam McCall20841d42018-10-16 16:29:41 +0000598 Actions.back().diagnostics = {D};
Sam McCalldd0566b2017-11-06 15:40:30 +0000599 }
Ilya Biryukovafb55542017-05-16 14:40:30 +0000600 }
Sam McCall20841d42018-10-16 16:29:41 +0000601
602 if (SupportsCodeAction)
Sam McCall2c30fbc2018-10-18 12:32:04 +0000603 Reply(json::Array(Actions));
Sam McCall20841d42018-10-16 16:29:41 +0000604 else {
605 std::vector<Command> Commands;
606 for (const auto &Action : Actions)
607 if (auto Command = asCommand(Action))
608 Commands.push_back(std::move(*Command));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000609 Reply(json::Array(Commands));
Sam McCall20841d42018-10-16 16:29:41 +0000610 }
Ilya Biryukovafb55542017-05-16 14:40:30 +0000611}
612
Sam McCall2c30fbc2018-10-18 12:32:04 +0000613void ClangdLSPServer::onCompletion(const TextDocumentPositionParams &Params,
614 Callback<CompletionList> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000615 Server->codeComplete(Params.textDocument.uri.file(), Params.position, CCOpts,
Sam McCall2c30fbc2018-10-18 12:32:04 +0000616 Bind(
617 [this](decltype(Reply) Reply,
Sam McCallc008af62018-10-20 15:30:37 +0000618 Expected<CodeCompleteResult> List) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000619 if (!List)
620 return Reply(List.takeError());
621 CompletionList LSPList;
622 LSPList.isIncomplete = List->HasMore;
623 for (const auto &R : List->Completions) {
624 CompletionItem C = R.render(CCOpts);
625 C.kind = adjustKindToCapability(
626 C.kind, SupportedCompletionItemKinds);
627 LSPList.items.push_back(std::move(C));
628 }
629 return Reply(std::move(LSPList));
630 },
631 std::move(Reply)));
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000632}
633
Sam McCall2c30fbc2018-10-18 12:32:04 +0000634void ClangdLSPServer::onSignatureHelp(const TextDocumentPositionParams &Params,
635 Callback<SignatureHelp> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000636 Server->signatureHelp(Params.textDocument.uri.file(), Params.position,
Sam McCall2c30fbc2018-10-18 12:32:04 +0000637 std::move(Reply));
Ilya Biryukov652364b2018-09-26 05:48:29 +0000638}
639
Sam McCall2c30fbc2018-10-18 12:32:04 +0000640void ClangdLSPServer::onGoToDefinition(const TextDocumentPositionParams &Params,
641 Callback<std::vector<Location>> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000642 Server->findDefinitions(Params.textDocument.uri.file(), Params.position,
Sam McCall2c30fbc2018-10-18 12:32:04 +0000643 std::move(Reply));
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000644}
645
Sam McCall2c30fbc2018-10-18 12:32:04 +0000646void ClangdLSPServer::onSwitchSourceHeader(const TextDocumentIdentifier &Params,
647 Callback<std::string> Reply) {
Sam McCallc008af62018-10-20 15:30:37 +0000648 Optional<Path> Result = Server->switchSourceHeader(Params.uri.file());
Sam McCall2c30fbc2018-10-18 12:32:04 +0000649 Reply(Result ? URI::createFile(*Result).toString() : "");
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000650}
651
Sam McCall2c30fbc2018-10-18 12:32:04 +0000652void ClangdLSPServer::onDocumentHighlight(
653 const TextDocumentPositionParams &Params,
654 Callback<std::vector<DocumentHighlight>> Reply) {
655 Server->findDocumentHighlights(Params.textDocument.uri.file(),
656 Params.position, std::move(Reply));
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000657}
658
Sam McCall2c30fbc2018-10-18 12:32:04 +0000659void ClangdLSPServer::onHover(const TextDocumentPositionParams &Params,
Sam McCallc008af62018-10-20 15:30:37 +0000660 Callback<Optional<Hover>> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000661 Server->findHover(Params.textDocument.uri.file(), Params.position,
Sam McCall2c30fbc2018-10-18 12:32:04 +0000662 std::move(Reply));
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000663}
664
Simon Marchi88016782018-08-01 11:28:49 +0000665void ClangdLSPServer::applyConfiguration(
Simon Marchiabeed662018-10-16 15:55:03 +0000666 const ClangdConfigurationParamsChange &Params) {
667 // Per-file update to the compilation database.
668 if (Params.compilationDatabaseChanges) {
669 const auto &CompileCommandUpdates = *Params.compilationDatabaseChanges;
Alex Lorenzf8087862018-08-01 17:39:29 +0000670 bool ShouldReparseOpenFiles = false;
671 for (auto &Entry : CompileCommandUpdates) {
672 /// The opened files need to be reparsed only when some existing
673 /// entries are changed.
674 PathRef File = Entry.first;
Sam McCalld1c9d112018-10-23 14:19:54 +0000675 if (!CDB->setCompilationCommandForFile(
Alex Lorenzf8087862018-08-01 17:39:29 +0000676 File, tooling::CompileCommand(
677 std::move(Entry.second.workingDirectory), File,
678 std::move(Entry.second.compilationCommand),
679 /*Output=*/"")))
680 ShouldReparseOpenFiles = true;
681 }
682 if (ShouldReparseOpenFiles)
683 reparseOpenedFiles();
684 }
Simon Marchi5178f922018-02-22 14:00:39 +0000685}
686
Simon Marchi88016782018-08-01 11:28:49 +0000687// FIXME: This function needs to be properly tested.
688void ClangdLSPServer::onChangeConfiguration(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000689 const DidChangeConfigurationParams &Params) {
Simon Marchi88016782018-08-01 11:28:49 +0000690 applyConfiguration(Params.settings);
691}
692
Sam McCall2c30fbc2018-10-18 12:32:04 +0000693void ClangdLSPServer::onReference(const ReferenceParams &Params,
694 Callback<std::vector<Location>> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000695 Server->findReferences(Params.textDocument.uri.file(), Params.position,
Sam McCall2c30fbc2018-10-18 12:32:04 +0000696 std::move(Reply));
Sam McCall1ad142f2018-09-05 11:53:07 +0000697}
698
Sam McCalldc8f3cf2018-10-17 07:32:05 +0000699ClangdLSPServer::ClangdLSPServer(class Transport &Transp,
Sam McCalladccab62017-11-23 16:58:22 +0000700 const clangd::CodeCompleteOptions &CCOpts,
Sam McCallc008af62018-10-20 15:30:37 +0000701 Optional<Path> CompileCommandsDir,
Alex Lorenzf8087862018-08-01 17:39:29 +0000702 bool ShouldUseInMemoryCDB,
Sam McCall7363a2f2018-03-05 17:28:54 +0000703 const ClangdServer::Options &Opts)
Sam McCalld1c9d112018-10-23 14:19:54 +0000704 : Transp(Transp), MsgHandler(new MessageHandler(*this)), CCOpts(CCOpts),
705 SupportedSymbolKinds(defaultSymbolKinds()),
Kadir Cetinkaya133d46f2018-09-27 17:13:07 +0000706 SupportedCompletionItemKinds(defaultCompletionItemKinds()),
Sam McCalld1c9d112018-10-23 14:19:54 +0000707 UseInMemoryCDB(ShouldUseInMemoryCDB), ClangdServerOpts(Opts) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000708 // clang-format off
709 MsgHandler->bind("initialize", &ClangdLSPServer::onInitialize);
710 MsgHandler->bind("shutdown", &ClangdLSPServer::onShutdown);
711 MsgHandler->bind("textDocument/rangeFormatting", &ClangdLSPServer::onDocumentRangeFormatting);
712 MsgHandler->bind("textDocument/onTypeFormatting", &ClangdLSPServer::onDocumentOnTypeFormatting);
713 MsgHandler->bind("textDocument/formatting", &ClangdLSPServer::onDocumentFormatting);
714 MsgHandler->bind("textDocument/codeAction", &ClangdLSPServer::onCodeAction);
715 MsgHandler->bind("textDocument/completion", &ClangdLSPServer::onCompletion);
716 MsgHandler->bind("textDocument/signatureHelp", &ClangdLSPServer::onSignatureHelp);
717 MsgHandler->bind("textDocument/definition", &ClangdLSPServer::onGoToDefinition);
718 MsgHandler->bind("textDocument/references", &ClangdLSPServer::onReference);
719 MsgHandler->bind("textDocument/switchSourceHeader", &ClangdLSPServer::onSwitchSourceHeader);
720 MsgHandler->bind("textDocument/rename", &ClangdLSPServer::onRename);
721 MsgHandler->bind("textDocument/hover", &ClangdLSPServer::onHover);
722 MsgHandler->bind("textDocument/documentSymbol", &ClangdLSPServer::onDocumentSymbol);
723 MsgHandler->bind("workspace/executeCommand", &ClangdLSPServer::onCommand);
724 MsgHandler->bind("textDocument/documentHighlight", &ClangdLSPServer::onDocumentHighlight);
725 MsgHandler->bind("workspace/symbol", &ClangdLSPServer::onWorkspaceSymbol);
726 MsgHandler->bind("textDocument/didOpen", &ClangdLSPServer::onDocumentDidOpen);
727 MsgHandler->bind("textDocument/didClose", &ClangdLSPServer::onDocumentDidClose);
728 MsgHandler->bind("textDocument/didChange", &ClangdLSPServer::onDocumentDidChange);
729 MsgHandler->bind("workspace/didChangeWatchedFiles", &ClangdLSPServer::onFileEvent);
730 MsgHandler->bind("workspace/didChangeConfiguration", &ClangdLSPServer::onChangeConfiguration);
731 // clang-format on
732}
733
734ClangdLSPServer::~ClangdLSPServer() = default;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000735
Sam McCalldc8f3cf2018-10-17 07:32:05 +0000736bool ClangdLSPServer::run() {
Ilya Biryukovafb55542017-05-16 14:40:30 +0000737 // Run the Language Server loop.
Sam McCalldc8f3cf2018-10-17 07:32:05 +0000738 bool CleanExit = true;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000739 if (auto Err = Transp.loop(*MsgHandler)) {
Sam McCalldc8f3cf2018-10-17 07:32:05 +0000740 elog("Transport error: {0}", std::move(Err));
741 CleanExit = false;
742 }
Ilya Biryukovafb55542017-05-16 14:40:30 +0000743
Ilya Biryukov652364b2018-09-26 05:48:29 +0000744 // Destroy ClangdServer to ensure all worker threads finish.
745 Server.reset();
Sam McCalldc8f3cf2018-10-17 07:32:05 +0000746 return CleanExit && ShutdownRequestReceived;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000747}
748
Ilya Biryukov71028b82018-03-12 15:28:22 +0000749std::vector<Fix> ClangdLSPServer::getFixes(StringRef File,
750 const clangd::Diagnostic &D) {
Ilya Biryukov38d79772017-05-16 09:38:59 +0000751 std::lock_guard<std::mutex> Lock(FixItsMutex);
752 auto DiagToFixItsIter = FixItsMap.find(File);
753 if (DiagToFixItsIter == FixItsMap.end())
754 return {};
755
756 const auto &DiagToFixItsMap = DiagToFixItsIter->second;
757 auto FixItsIter = DiagToFixItsMap.find(D);
758 if (FixItsIter == DiagToFixItsMap.end())
759 return {};
760
761 return FixItsIter->second;
762}
763
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000764void ClangdLSPServer::onDiagnosticsReady(PathRef File,
765 std::vector<Diag> Diagnostics) {
Sam McCall16e70702018-10-24 07:59:38 +0000766 URIForFile URI(File);
767 std::vector<Diagnostic> LSPDiagnostics;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000768 DiagnosticToReplacementMap LocalFixIts; // Temporary storage
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000769 for (auto &Diag : Diagnostics) {
Sam McCall16e70702018-10-24 07:59:38 +0000770 toLSPDiags(Diag, URI, DiagOpts,
771 [&](clangd::Diagnostic Diag, ArrayRef<Fix> Fixes) {
772 auto &FixItsForDiagnostic = LocalFixIts[Diag];
773 llvm::copy(Fixes, std::back_inserter(FixItsForDiagnostic));
774 LSPDiagnostics.push_back(std::move(Diag));
775 });
Ilya Biryukov38d79772017-05-16 09:38:59 +0000776 }
777
778 // Cache FixIts
779 {
780 // FIXME(ibiryukov): should be deleted when documents are removed
781 std::lock_guard<std::mutex> Lock(FixItsMutex);
782 FixItsMap[File] = LocalFixIts;
783 }
784
785 // Publish diagnostics.
Sam McCall2c30fbc2018-10-18 12:32:04 +0000786 notify("textDocument/publishDiagnostics",
787 json::Object{
Sam McCall16e70702018-10-24 07:59:38 +0000788 {"uri", URI},
789 {"diagnostics", std::move(LSPDiagnostics)},
Sam McCall2c30fbc2018-10-18 12:32:04 +0000790 });
Ilya Biryukov38d79772017-05-16 09:38:59 +0000791}
Simon Marchi9569fd52018-03-16 14:30:42 +0000792
793void ClangdLSPServer::reparseOpenedFiles() {
794 for (const Path &FilePath : DraftMgr.getActiveFiles())
Ilya Biryukov652364b2018-09-26 05:48:29 +0000795 Server->addDocument(FilePath, *DraftMgr.getDraft(FilePath),
796 WantDiagnostics::Auto);
Simon Marchi9569fd52018-03-16 14:30:42 +0000797}
Alex Lorenzf8087862018-08-01 17:39:29 +0000798
799ClangdLSPServer::CompilationDB ClangdLSPServer::CompilationDB::makeInMemory() {
Sam McCall2172ee92018-10-23 13:14:02 +0000800 return CompilationDB(llvm::make_unique<InMemoryCompilationDb>(),
Alex Lorenzf8087862018-08-01 17:39:29 +0000801 /*IsDirectoryBased=*/false);
802}
803
804ClangdLSPServer::CompilationDB
805ClangdLSPServer::CompilationDB::makeDirectoryBased(
Sam McCallc008af62018-10-20 15:30:37 +0000806 Optional<Path> CompileCommandsDir) {
Alex Lorenzf8087862018-08-01 17:39:29 +0000807 auto CDB = llvm::make_unique<DirectoryBasedGlobalCompilationDatabase>(
808 std::move(CompileCommandsDir));
Sam McCall2172ee92018-10-23 13:14:02 +0000809 return CompilationDB(std::move(CDB),
Alex Lorenzf8087862018-08-01 17:39:29 +0000810 /*IsDirectoryBased=*/true);
811}
812
813void ClangdLSPServer::CompilationDB::invalidate(PathRef File) {
814 if (!IsDirectoryBased)
815 static_cast<InMemoryCompilationDb *>(CDB.get())->invalidate(File);
Alex Lorenzf8087862018-08-01 17:39:29 +0000816}
817
818bool ClangdLSPServer::CompilationDB::setCompilationCommandForFile(
819 PathRef File, tooling::CompileCommand CompilationCommand) {
820 if (IsDirectoryBased) {
821 elog("Trying to set compile command for {0} while using directory-based "
822 "compilation database",
823 File);
824 return false;
825 }
826 return static_cast<InMemoryCompilationDb *>(CDB.get())
827 ->setCompilationCommandForFile(File, std::move(CompilationCommand));
828}
829
830void ClangdLSPServer::CompilationDB::setExtraFlagsForFile(
831 PathRef File, std::vector<std::string> ExtraFlags) {
832 if (!IsDirectoryBased) {
833 elog("Trying to set extra flags for {0} while using in-memory compilation "
834 "database",
835 File);
836 return;
837 }
838 static_cast<DirectoryBasedGlobalCompilationDatabase *>(CDB.get())
839 ->setExtraFlagsForFile(File, std::move(ExtraFlags));
Alex Lorenzf8087862018-08-01 17:39:29 +0000840}
841
Sam McCallc008af62018-10-20 15:30:37 +0000842} // namespace clangd
843} // namespace clang