blob: 91d35537c905ef98eaaab16ddccbcd515b65c0f4 [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 {
108 log("<-- {0}({1})", Method, ID);
Sam McCall3d0adbe2018-10-18 14:41:50 +0000109 if (!Server.Server && Method != "initialize") {
110 elog("Call {0} before initialization.", Method);
111 Server.reply(ID, make_error<LSPError>("server not initialized",
112 ErrorCode::ServerNotInitialized));
113 } else if (auto Handler = Calls.lookup(Method))
Sam McCall2c30fbc2018-10-18 12:32:04 +0000114 Handler(std::move(Params), std::move(ID));
115 else
Sam McCallc008af62018-10-20 15:30:37 +0000116 Server.reply(ID, make_error<LSPError>("method not found",
117 ErrorCode::MethodNotFound));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000118 return true;
119 }
120
121 bool onReply(json::Value ID, Expected<json::Value> Result) override {
122 // We ignore replies, just log them.
123 if (Result)
124 log("<-- reply({0})", ID);
125 else
Sam McCallc008af62018-10-20 15:30:37 +0000126 log("<-- reply({0}) error: {1}", ID, toString(Result.takeError()));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000127 return true;
128 }
129
130 // Bind an LSP method name to a call.
131 template <typename Param, typename Reply>
132 void bind(const char *Method,
133 void (ClangdLSPServer::*Handler)(const Param &, Callback<Reply>)) {
134 Calls[Method] = [Method, Handler, this](json::Value RawParams,
135 json::Value ID) {
136 Param P;
137 if (!fromJSON(RawParams, P)) {
138 elog("Failed to decode {0} request.", Method);
139 Server.reply(ID, make_error<LSPError>("failed to decode request",
140 ErrorCode::InvalidRequest));
141 return;
142 }
143 trace::Span Tracer(Method);
144 SPAN_ATTACH(Tracer, "Params", RawParams);
145 auto *Trace = Tracer.Args; // We attach reply from another thread.
146 // Calls can be canceled by the client. Add cancellation context.
147 WithContext WithCancel(cancelableRequestContext(ID));
148 // FIXME: this function should assert it's called exactly once.
Sam McCallc008af62018-10-20 15:30:37 +0000149 (Server.*Handler)(P, [this, ID, Trace](Expected<Reply> Result) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000150 if (Result) {
151 if (Trace)
152 (*Trace)["Reply"] = *Result;
153 Server.reply(ID, json::Value(std::move(*Result)));
154 } else {
155 auto Err = Result.takeError();
156 if (Trace)
Sam McCallc008af62018-10-20 15:30:37 +0000157 (*Trace)["Error"] = to_string(Err);
Sam McCall2c30fbc2018-10-18 12:32:04 +0000158 Server.reply(ID, std::move(Err));
159 }
160 });
161 };
162 }
163
164 // Bind an LSP method name to a notification.
165 template <typename Param>
166 void bind(const char *Method,
167 void (ClangdLSPServer::*Handler)(const Param &)) {
168 Notifications[Method] = [Method, Handler, this](json::Value RawParams) {
169 Param P;
170 if (!fromJSON(RawParams, P)) {
171 elog("Failed to decode {0} request.", Method);
172 return;
173 }
174 trace::Span Tracer(Method);
175 SPAN_ATTACH(Tracer, "Params", RawParams);
176 (Server.*Handler)(P);
177 };
178 }
179
180private:
Sam McCallc008af62018-10-20 15:30:37 +0000181 StringMap<std::function<void(json::Value)>> Notifications;
182 StringMap<std::function<void(json::Value, json::Value)>> Calls;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000183
184 // Method calls may be cancelled by ID, so keep track of their state.
185 // This needs a mutex: handlers may finish on a different thread, and that's
186 // when we clean up entries in the map.
187 mutable std::mutex RequestCancelersMutex;
Sam McCallc008af62018-10-20 15:30:37 +0000188 StringMap<std::pair<Canceler, /*Cookie*/ unsigned>> RequestCancelers;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000189 unsigned NextRequestCookie = 0; // To disambiguate reused IDs, see below.
Sam McCallc008af62018-10-20 15:30:37 +0000190 void onCancel(const json::Value &Params) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000191 const json::Value *ID = nullptr;
192 if (auto *O = Params.getAsObject())
193 ID = O->get("id");
194 if (!ID) {
195 elog("Bad cancellation request: {0}", Params);
196 return;
197 }
Sam McCallc008af62018-10-20 15:30:37 +0000198 auto StrID = to_string(*ID);
Sam McCall2c30fbc2018-10-18 12:32:04 +0000199 std::lock_guard<std::mutex> Lock(RequestCancelersMutex);
200 auto It = RequestCancelers.find(StrID);
201 if (It != RequestCancelers.end())
202 It->second.first(); // Invoke the canceler.
203 }
204 // We run cancelable requests in a context that does two things:
205 // - allows cancellation using RequestCancelers[ID]
206 // - cleans up the entry in RequestCancelers when it's no longer needed
207 // If a client reuses an ID, the last wins and the first cannot be canceled.
208 Context cancelableRequestContext(const json::Value &ID) {
209 auto Task = cancelableTask();
Sam McCallc008af62018-10-20 15:30:37 +0000210 auto StrID = to_string(ID); // JSON-serialize ID for map key.
Sam McCall2c30fbc2018-10-18 12:32:04 +0000211 auto Cookie = NextRequestCookie++; // No lock, only called on main thread.
212 {
213 std::lock_guard<std::mutex> Lock(RequestCancelersMutex);
214 RequestCancelers[StrID] = {std::move(Task.second), Cookie};
215 }
216 // When the request ends, we can clean up the entry we just added.
217 // The cookie lets us check that it hasn't been overwritten due to ID
218 // reuse.
219 return Task.first.derive(make_scope_exit([this, StrID, Cookie] {
220 std::lock_guard<std::mutex> Lock(RequestCancelersMutex);
221 auto It = RequestCancelers.find(StrID);
222 if (It != RequestCancelers.end() && It->second.second == Cookie)
223 RequestCancelers.erase(It);
224 }));
225 }
226
227 ClangdLSPServer &Server;
228};
229
230// call(), notify(), and reply() wrap the Transport, adding logging and locking.
231void ClangdLSPServer::call(StringRef Method, json::Value Params) {
232 auto ID = NextCallID++;
233 log("--> {0}({1})", Method, ID);
234 // We currently don't handle responses, so no need to store ID anywhere.
235 std::lock_guard<std::mutex> Lock(TranspWriter);
236 Transp.call(Method, std::move(Params), ID);
237}
238
239void ClangdLSPServer::notify(StringRef Method, json::Value Params) {
240 log("--> {0}", Method);
241 std::lock_guard<std::mutex> Lock(TranspWriter);
242 Transp.notify(Method, std::move(Params));
243}
244
Sam McCallc008af62018-10-20 15:30:37 +0000245void ClangdLSPServer::reply(json::Value ID, Expected<json::Value> Result) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000246 if (Result) {
247 log("--> reply({0})", ID);
248 std::lock_guard<std::mutex> Lock(TranspWriter);
249 Transp.reply(std::move(ID), std::move(Result));
250 } else {
251 Error Err = Result.takeError();
252 log("--> reply({0}) error: {1}", ID, Err);
253 std::lock_guard<std::mutex> Lock(TranspWriter);
254 Transp.reply(std::move(ID), std::move(Err));
255 }
256}
257
258void ClangdLSPServer::onInitialize(const InitializeParams &Params,
259 Callback<json::Value> Reply) {
Sam McCall0d9b40f2018-10-19 15:42:23 +0000260 if (Params.rootUri && *Params.rootUri)
261 ClangdServerOpts.WorkspaceRoot = Params.rootUri->file();
262 else if (Params.rootPath && !Params.rootPath->empty())
263 ClangdServerOpts.WorkspaceRoot = *Params.rootPath;
Sam McCall3d0adbe2018-10-18 14:41:50 +0000264 if (Server)
265 return Reply(make_error<LSPError>("server already initialized",
266 ErrorCode::InvalidRequest));
267 Server.emplace(CDB.getCDB(), FSProvider,
268 static_cast<DiagnosticsConsumer &>(*this), ClangdServerOpts);
Simon Marchiabeed662018-10-16 15:55:03 +0000269 if (Params.initializationOptions) {
270 const ClangdInitializationOptions &Opts = *Params.initializationOptions;
271
272 // Explicit compilation database path.
273 if (Opts.compilationDatabasePath.hasValue()) {
274 CDB.setCompileCommandsDir(Opts.compilationDatabasePath.getValue());
275 }
276
277 applyConfiguration(Opts.ParamsChange);
278 }
Simon Marchi88016782018-08-01 11:28:49 +0000279
Sam McCallbf6a2fc2018-10-17 07:33:42 +0000280 CCOpts.EnableSnippets = Params.capabilities.CompletionSnippets;
281 DiagOpts.EmbedFixesInDiagnostics = Params.capabilities.DiagnosticFixes;
282 DiagOpts.SendDiagnosticCategory = Params.capabilities.DiagnosticCategory;
283 if (Params.capabilities.WorkspaceSymbolKinds)
284 SupportedSymbolKinds |= *Params.capabilities.WorkspaceSymbolKinds;
285 if (Params.capabilities.CompletionItemKinds)
286 SupportedCompletionItemKinds |= *Params.capabilities.CompletionItemKinds;
287 SupportsCodeAction = Params.capabilities.CodeActionStructure;
Kadir Cetinkaya133d46f2018-09-27 17:13:07 +0000288
Sam McCall2c30fbc2018-10-18 12:32:04 +0000289 Reply(json::Object{
Sam McCall0930ab02017-11-07 15:49:35 +0000290 {{"capabilities",
Sam McCalld20d7982018-07-09 14:25:59 +0000291 json::Object{
Simon Marchi98082622018-03-26 14:41:40 +0000292 {"textDocumentSync", (int)TextDocumentSyncKind::Incremental},
Sam McCall0930ab02017-11-07 15:49:35 +0000293 {"documentFormattingProvider", true},
294 {"documentRangeFormattingProvider", true},
295 {"documentOnTypeFormattingProvider",
Sam McCalld20d7982018-07-09 14:25:59 +0000296 json::Object{
Sam McCall0930ab02017-11-07 15:49:35 +0000297 {"firstTriggerCharacter", "}"},
298 {"moreTriggerCharacter", {}},
299 }},
300 {"codeActionProvider", true},
301 {"completionProvider",
Sam McCalld20d7982018-07-09 14:25:59 +0000302 json::Object{
Sam McCall0930ab02017-11-07 15:49:35 +0000303 {"resolveProvider", false},
304 {"triggerCharacters", {".", ">", ":"}},
305 }},
306 {"signatureHelpProvider",
Sam McCalld20d7982018-07-09 14:25:59 +0000307 json::Object{
Sam McCall0930ab02017-11-07 15:49:35 +0000308 {"triggerCharacters", {"(", ","}},
309 }},
310 {"definitionProvider", true},
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000311 {"documentHighlightProvider", true},
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000312 {"hoverProvider", true},
Haojian Wu345099c2017-11-09 11:30:04 +0000313 {"renameProvider", true},
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000314 {"documentSymbolProvider", true},
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000315 {"workspaceSymbolProvider", true},
Sam McCall1ad142f2018-09-05 11:53:07 +0000316 {"referencesProvider", true},
Sam McCall0930ab02017-11-07 15:49:35 +0000317 {"executeCommandProvider",
Sam McCalld20d7982018-07-09 14:25:59 +0000318 json::Object{
Eric Liu2c190532018-05-15 15:23:53 +0000319 {"commands", {ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND}},
Sam McCall0930ab02017-11-07 15:49:35 +0000320 }},
321 }}}});
Ilya Biryukovafb55542017-05-16 14:40:30 +0000322}
323
Sam McCall2c30fbc2018-10-18 12:32:04 +0000324void ClangdLSPServer::onShutdown(const ShutdownParams &Params,
325 Callback<std::nullptr_t> Reply) {
Ilya Biryukov0d9b8a32017-10-25 08:45:41 +0000326 // Do essentially nothing, just say we're ready to exit.
327 ShutdownRequestReceived = true;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000328 Reply(nullptr);
Sam McCall8a5dded2017-10-12 13:29:58 +0000329}
Ilya Biryukovafb55542017-05-16 14:40:30 +0000330
Sam McCall2c30fbc2018-10-18 12:32:04 +0000331void ClangdLSPServer::onDocumentDidOpen(
332 const DidOpenTextDocumentParams &Params) {
Simon Marchi9569fd52018-03-16 14:30:42 +0000333 PathRef File = Params.textDocument.uri.file();
Alex Lorenzf8087862018-08-01 17:39:29 +0000334 if (Params.metadata && !Params.metadata->extraFlags.empty())
335 CDB.setExtraFlagsForFile(File, std::move(Params.metadata->extraFlags));
Ilya Biryukovb10ef472018-06-13 09:20:41 +0000336
Sam McCall2c30fbc2018-10-18 12:32:04 +0000337 const std::string &Contents = Params.textDocument.text;
Simon Marchi9569fd52018-03-16 14:30:42 +0000338
Simon Marchi98082622018-03-26 14:41:40 +0000339 DraftMgr.addDraft(File, Contents);
Ilya Biryukov652364b2018-09-26 05:48:29 +0000340 Server->addDocument(File, Contents, WantDiagnostics::Yes);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000341}
342
Sam McCall2c30fbc2018-10-18 12:32:04 +0000343void ClangdLSPServer::onDocumentDidChange(
344 const DidChangeTextDocumentParams &Params) {
Eric Liu51fed182018-02-22 18:40:39 +0000345 auto WantDiags = WantDiagnostics::Auto;
346 if (Params.wantDiagnostics.hasValue())
347 WantDiags = Params.wantDiagnostics.getValue() ? WantDiagnostics::Yes
348 : WantDiagnostics::No;
Simon Marchi9569fd52018-03-16 14:30:42 +0000349
350 PathRef File = Params.textDocument.uri.file();
Sam McCallc008af62018-10-20 15:30:37 +0000351 Expected<std::string> Contents =
Simon Marchi98082622018-03-26 14:41:40 +0000352 DraftMgr.updateDraft(File, Params.contentChanges);
353 if (!Contents) {
354 // If this fails, we are most likely going to be not in sync anymore with
355 // the client. It is better to remove the draft and let further operations
356 // fail rather than giving wrong results.
357 DraftMgr.removeDraft(File);
Ilya Biryukov652364b2018-09-26 05:48:29 +0000358 Server->removeDocument(File);
Ilya Biryukovb10ef472018-06-13 09:20:41 +0000359 CDB.invalidate(File);
Sam McCallbed58852018-07-11 10:35:11 +0000360 elog("Failed to update {0}: {1}", File, Contents.takeError());
Simon Marchi98082622018-03-26 14:41:40 +0000361 return;
362 }
Simon Marchi9569fd52018-03-16 14:30:42 +0000363
Ilya Biryukov652364b2018-09-26 05:48:29 +0000364 Server->addDocument(File, *Contents, WantDiags);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000365}
366
Sam McCall2c30fbc2018-10-18 12:32:04 +0000367void ClangdLSPServer::onFileEvent(const DidChangeWatchedFilesParams &Params) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000368 Server->onFileEvent(Params);
Marc-Andre Laperlebf114242017-10-02 18:00:37 +0000369}
370
Sam McCall2c30fbc2018-10-18 12:32:04 +0000371void ClangdLSPServer::onCommand(const ExecuteCommandParams &Params,
372 Callback<json::Value> Reply) {
373 auto ApplyEdit = [&](WorkspaceEdit WE) {
Eric Liuc5105f92018-02-16 14:15:55 +0000374 ApplyWorkspaceEditParams Edit;
375 Edit.edit = std::move(WE);
Eric Liuc5105f92018-02-16 14:15:55 +0000376 // Ideally, we would wait for the response and if there is no error, we
377 // would reply success/failure to the original RPC.
378 call("workspace/applyEdit", Edit);
379 };
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000380 if (Params.command == ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND &&
381 Params.workspaceEdit) {
382 // The flow for "apply-fix" :
383 // 1. We publish a diagnostic, including fixits
384 // 2. The user clicks on the diagnostic, the editor asks us for code actions
385 // 3. We send code actions, with the fixit embedded as context
386 // 4. The user selects the fixit, the editor asks us to apply it
387 // 5. We unwrap the changes and send them back to the editor
388 // 6. The editor applies the changes (applyEdit), and sends us a reply (but
389 // we ignore it)
390
Sam McCall2c30fbc2018-10-18 12:32:04 +0000391 Reply("Fix applied.");
Eric Liuc5105f92018-02-16 14:15:55 +0000392 ApplyEdit(*Params.workspaceEdit);
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000393 } else {
394 // We should not get here because ExecuteCommandParams would not have
395 // parsed in the first place and this handler should not be called. But if
396 // more commands are added, this will be here has a safe guard.
Sam McCall2c30fbc2018-10-18 12:32:04 +0000397 Reply(make_error<LSPError>(
Sam McCallc008af62018-10-20 15:30:37 +0000398 formatv("Unsupported command \"{0}\".", Params.command).str(),
Sam McCall2c30fbc2018-10-18 12:32:04 +0000399 ErrorCode::InvalidParams));
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000400 }
401}
402
Sam McCall2c30fbc2018-10-18 12:32:04 +0000403void ClangdLSPServer::onWorkspaceSymbol(
404 const WorkspaceSymbolParams &Params,
405 Callback<std::vector<SymbolInformation>> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000406 Server->workspaceSymbols(
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000407 Params.query, CCOpts.Limit,
Sam McCall2c30fbc2018-10-18 12:32:04 +0000408 Bind(
409 [this](decltype(Reply) Reply,
Sam McCallc008af62018-10-20 15:30:37 +0000410 Expected<std::vector<SymbolInformation>> Items) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000411 if (!Items)
412 return Reply(Items.takeError());
413 for (auto &Sym : *Items)
414 Sym.kind = adjustKindToCapability(Sym.kind, SupportedSymbolKinds);
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000415
Sam McCall2c30fbc2018-10-18 12:32:04 +0000416 Reply(std::move(*Items));
417 },
418 std::move(Reply)));
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000419}
420
Sam McCall2c30fbc2018-10-18 12:32:04 +0000421void ClangdLSPServer::onRename(const RenameParams &Params,
422 Callback<WorkspaceEdit> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000423 Path File = Params.textDocument.uri.file();
Sam McCallc008af62018-10-20 15:30:37 +0000424 Optional<std::string> Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000425 if (!Code)
Sam McCall2c30fbc2018-10-18 12:32:04 +0000426 return Reply(make_error<LSPError>("onRename called for non-added file",
427 ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000428
Ilya Biryukov652364b2018-09-26 05:48:29 +0000429 Server->rename(
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000430 File, Params.position, Params.newName,
Sam McCall2c30fbc2018-10-18 12:32:04 +0000431 Bind(
Sam McCallc008af62018-10-20 15:30:37 +0000432 [File, Code,
433 Params](decltype(Reply) Reply,
434 Expected<std::vector<tooling::Replacement>> Replacements) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000435 if (!Replacements)
436 return Reply(Replacements.takeError());
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000437
Sam McCall2c30fbc2018-10-18 12:32:04 +0000438 // Turn the replacements into the format specified by the Language
439 // Server Protocol. Fuse them into one big JSON array.
440 std::vector<TextEdit> Edits;
441 for (const auto &R : *Replacements)
442 Edits.push_back(replacementToEdit(*Code, R));
443 WorkspaceEdit WE;
444 WE.changes = {{Params.textDocument.uri.uri(), Edits}};
445 Reply(WE);
446 },
447 std::move(Reply)));
Haojian Wu345099c2017-11-09 11:30:04 +0000448}
449
Sam McCall2c30fbc2018-10-18 12:32:04 +0000450void ClangdLSPServer::onDocumentDidClose(
451 const DidCloseTextDocumentParams &Params) {
Simon Marchi9569fd52018-03-16 14:30:42 +0000452 PathRef File = Params.textDocument.uri.file();
453 DraftMgr.removeDraft(File);
Ilya Biryukov652364b2018-09-26 05:48:29 +0000454 Server->removeDocument(File);
Alex Lorenzf8087862018-08-01 17:39:29 +0000455 CDB.invalidate(File);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000456}
457
Sam McCall4db732a2017-09-30 10:08:52 +0000458void ClangdLSPServer::onDocumentOnTypeFormatting(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000459 const DocumentOnTypeFormattingParams &Params,
460 Callback<std::vector<TextEdit>> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000461 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000462 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000463 if (!Code)
Sam McCall2c30fbc2018-10-18 12:32:04 +0000464 return Reply(make_error<LSPError>(
465 "onDocumentOnTypeFormatting called for non-added file",
466 ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000467
Ilya Biryukov652364b2018-09-26 05:48:29 +0000468 auto ReplacementsOrError = Server->formatOnType(*Code, File, Params.position);
Raoul Wols212bcf82017-12-12 20:25:06 +0000469 if (ReplacementsOrError)
Sam McCall2c30fbc2018-10-18 12:32:04 +0000470 Reply(replacementsToEdits(*Code, ReplacementsOrError.get()));
Raoul Wols212bcf82017-12-12 20:25:06 +0000471 else
Sam McCall2c30fbc2018-10-18 12:32:04 +0000472 Reply(ReplacementsOrError.takeError());
Ilya Biryukovafb55542017-05-16 14:40:30 +0000473}
474
Sam McCall4db732a2017-09-30 10:08:52 +0000475void ClangdLSPServer::onDocumentRangeFormatting(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000476 const DocumentRangeFormattingParams &Params,
477 Callback<std::vector<TextEdit>> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000478 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000479 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000480 if (!Code)
Sam McCall2c30fbc2018-10-18 12:32:04 +0000481 return Reply(make_error<LSPError>(
482 "onDocumentRangeFormatting called for non-added file",
483 ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000484
Ilya Biryukov652364b2018-09-26 05:48:29 +0000485 auto ReplacementsOrError = Server->formatRange(*Code, File, Params.range);
Raoul Wols212bcf82017-12-12 20:25:06 +0000486 if (ReplacementsOrError)
Sam McCall2c30fbc2018-10-18 12:32:04 +0000487 Reply(replacementsToEdits(*Code, ReplacementsOrError.get()));
Raoul Wols212bcf82017-12-12 20:25:06 +0000488 else
Sam McCall2c30fbc2018-10-18 12:32:04 +0000489 Reply(ReplacementsOrError.takeError());
Ilya Biryukovafb55542017-05-16 14:40:30 +0000490}
491
Sam McCall2c30fbc2018-10-18 12:32:04 +0000492void ClangdLSPServer::onDocumentFormatting(
493 const DocumentFormattingParams &Params,
494 Callback<std::vector<TextEdit>> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000495 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000496 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000497 if (!Code)
Sam McCall2c30fbc2018-10-18 12:32:04 +0000498 return Reply(
499 make_error<LSPError>("onDocumentFormatting called for non-added file",
500 ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000501
Ilya Biryukov652364b2018-09-26 05:48:29 +0000502 auto ReplacementsOrError = Server->formatFile(*Code, File);
Raoul Wols212bcf82017-12-12 20:25:06 +0000503 if (ReplacementsOrError)
Sam McCall2c30fbc2018-10-18 12:32:04 +0000504 Reply(replacementsToEdits(*Code, ReplacementsOrError.get()));
Raoul Wols212bcf82017-12-12 20:25:06 +0000505 else
Sam McCall2c30fbc2018-10-18 12:32:04 +0000506 Reply(ReplacementsOrError.takeError());
Sam McCall4db732a2017-09-30 10:08:52 +0000507}
508
Sam McCall2c30fbc2018-10-18 12:32:04 +0000509void ClangdLSPServer::onDocumentSymbol(
510 const DocumentSymbolParams &Params,
511 Callback<std::vector<SymbolInformation>> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000512 Server->documentSymbols(
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000513 Params.textDocument.uri.file(),
Sam McCall2c30fbc2018-10-18 12:32:04 +0000514 Bind(
515 [this](decltype(Reply) Reply,
Sam McCallc008af62018-10-20 15:30:37 +0000516 Expected<std::vector<SymbolInformation>> Items) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000517 if (!Items)
518 return Reply(Items.takeError());
519 for (auto &Sym : *Items)
520 Sym.kind = adjustKindToCapability(Sym.kind, SupportedSymbolKinds);
521 Reply(std::move(*Items));
522 },
523 std::move(Reply)));
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000524}
525
Sam McCall20841d42018-10-16 16:29:41 +0000526static Optional<Command> asCommand(const CodeAction &Action) {
527 Command Cmd;
528 if (Action.command && Action.edit)
Sam McCallc008af62018-10-20 15:30:37 +0000529 return None; // Not representable. (We never emit these anyway).
Sam McCall20841d42018-10-16 16:29:41 +0000530 if (Action.command) {
531 Cmd = *Action.command;
532 } else if (Action.edit) {
533 Cmd.command = Command::CLANGD_APPLY_FIX_COMMAND;
534 Cmd.workspaceEdit = *Action.edit;
535 } else {
Sam McCallc008af62018-10-20 15:30:37 +0000536 return None;
Sam McCall20841d42018-10-16 16:29:41 +0000537 }
538 Cmd.title = Action.title;
539 if (Action.kind && *Action.kind == CodeAction::QUICKFIX_KIND)
540 Cmd.title = "Apply fix: " + Cmd.title;
541 return Cmd;
542}
543
Sam McCall2c30fbc2018-10-18 12:32:04 +0000544void ClangdLSPServer::onCodeAction(const CodeActionParams &Params,
545 Callback<json::Value> Reply) {
546 auto Code = DraftMgr.getDraft(Params.textDocument.uri.file());
547 if (!Code)
548 return Reply(make_error<LSPError>("onCodeAction called for non-added file",
549 ErrorCode::InvalidParams));
Sam McCall20841d42018-10-16 16:29:41 +0000550 // We provide a code action for Fixes on the specified diagnostics.
Sam McCall20841d42018-10-16 16:29:41 +0000551 std::vector<CodeAction> Actions;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000552 for (const Diagnostic &D : Params.context.diagnostics) {
Ilya Biryukov71028b82018-03-12 15:28:22 +0000553 for (auto &F : getFixes(Params.textDocument.uri.file(), D)) {
Sam McCall20841d42018-10-16 16:29:41 +0000554 Actions.emplace_back();
555 Actions.back().title = F.Message;
556 Actions.back().kind = CodeAction::QUICKFIX_KIND;
557 Actions.back().diagnostics = {D};
558 Actions.back().edit.emplace();
559 Actions.back().edit->changes.emplace();
560 (*Actions.back().edit->changes)[Params.textDocument.uri.uri()] = {
561 F.Edits.begin(), F.Edits.end()};
Sam McCalldd0566b2017-11-06 15:40:30 +0000562 }
Ilya Biryukovafb55542017-05-16 14:40:30 +0000563 }
Sam McCall20841d42018-10-16 16:29:41 +0000564
565 if (SupportsCodeAction)
Sam McCall2c30fbc2018-10-18 12:32:04 +0000566 Reply(json::Array(Actions));
Sam McCall20841d42018-10-16 16:29:41 +0000567 else {
568 std::vector<Command> Commands;
569 for (const auto &Action : Actions)
570 if (auto Command = asCommand(Action))
571 Commands.push_back(std::move(*Command));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000572 Reply(json::Array(Commands));
Sam McCall20841d42018-10-16 16:29:41 +0000573 }
Ilya Biryukovafb55542017-05-16 14:40:30 +0000574}
575
Sam McCall2c30fbc2018-10-18 12:32:04 +0000576void ClangdLSPServer::onCompletion(const TextDocumentPositionParams &Params,
577 Callback<CompletionList> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000578 Server->codeComplete(Params.textDocument.uri.file(), Params.position, CCOpts,
Sam McCall2c30fbc2018-10-18 12:32:04 +0000579 Bind(
580 [this](decltype(Reply) Reply,
Sam McCallc008af62018-10-20 15:30:37 +0000581 Expected<CodeCompleteResult> List) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000582 if (!List)
583 return Reply(List.takeError());
584 CompletionList LSPList;
585 LSPList.isIncomplete = List->HasMore;
586 for (const auto &R : List->Completions) {
587 CompletionItem C = R.render(CCOpts);
588 C.kind = adjustKindToCapability(
589 C.kind, SupportedCompletionItemKinds);
590 LSPList.items.push_back(std::move(C));
591 }
592 return Reply(std::move(LSPList));
593 },
594 std::move(Reply)));
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000595}
596
Sam McCall2c30fbc2018-10-18 12:32:04 +0000597void ClangdLSPServer::onSignatureHelp(const TextDocumentPositionParams &Params,
598 Callback<SignatureHelp> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000599 Server->signatureHelp(Params.textDocument.uri.file(), Params.position,
Sam McCall2c30fbc2018-10-18 12:32:04 +0000600 std::move(Reply));
Ilya Biryukov652364b2018-09-26 05:48:29 +0000601}
602
Sam McCall2c30fbc2018-10-18 12:32:04 +0000603void ClangdLSPServer::onGoToDefinition(const TextDocumentPositionParams &Params,
604 Callback<std::vector<Location>> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000605 Server->findDefinitions(Params.textDocument.uri.file(), Params.position,
Sam McCall2c30fbc2018-10-18 12:32:04 +0000606 std::move(Reply));
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000607}
608
Sam McCall2c30fbc2018-10-18 12:32:04 +0000609void ClangdLSPServer::onSwitchSourceHeader(const TextDocumentIdentifier &Params,
610 Callback<std::string> Reply) {
Sam McCallc008af62018-10-20 15:30:37 +0000611 Optional<Path> Result = Server->switchSourceHeader(Params.uri.file());
Sam McCall2c30fbc2018-10-18 12:32:04 +0000612 Reply(Result ? URI::createFile(*Result).toString() : "");
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000613}
614
Sam McCall2c30fbc2018-10-18 12:32:04 +0000615void ClangdLSPServer::onDocumentHighlight(
616 const TextDocumentPositionParams &Params,
617 Callback<std::vector<DocumentHighlight>> Reply) {
618 Server->findDocumentHighlights(Params.textDocument.uri.file(),
619 Params.position, std::move(Reply));
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000620}
621
Sam McCall2c30fbc2018-10-18 12:32:04 +0000622void ClangdLSPServer::onHover(const TextDocumentPositionParams &Params,
Sam McCallc008af62018-10-20 15:30:37 +0000623 Callback<Optional<Hover>> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000624 Server->findHover(Params.textDocument.uri.file(), Params.position,
Sam McCall2c30fbc2018-10-18 12:32:04 +0000625 std::move(Reply));
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000626}
627
Simon Marchi88016782018-08-01 11:28:49 +0000628void ClangdLSPServer::applyConfiguration(
Simon Marchiabeed662018-10-16 15:55:03 +0000629 const ClangdConfigurationParamsChange &Params) {
630 // Per-file update to the compilation database.
631 if (Params.compilationDatabaseChanges) {
632 const auto &CompileCommandUpdates = *Params.compilationDatabaseChanges;
Alex Lorenzf8087862018-08-01 17:39:29 +0000633 bool ShouldReparseOpenFiles = false;
634 for (auto &Entry : CompileCommandUpdates) {
635 /// The opened files need to be reparsed only when some existing
636 /// entries are changed.
637 PathRef File = Entry.first;
638 if (!CDB.setCompilationCommandForFile(
639 File, tooling::CompileCommand(
640 std::move(Entry.second.workingDirectory), File,
641 std::move(Entry.second.compilationCommand),
642 /*Output=*/"")))
643 ShouldReparseOpenFiles = true;
644 }
645 if (ShouldReparseOpenFiles)
646 reparseOpenedFiles();
647 }
Simon Marchi5178f922018-02-22 14:00:39 +0000648}
649
Simon Marchi88016782018-08-01 11:28:49 +0000650// FIXME: This function needs to be properly tested.
651void ClangdLSPServer::onChangeConfiguration(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000652 const DidChangeConfigurationParams &Params) {
Simon Marchi88016782018-08-01 11:28:49 +0000653 applyConfiguration(Params.settings);
654}
655
Sam McCall2c30fbc2018-10-18 12:32:04 +0000656void ClangdLSPServer::onReference(const ReferenceParams &Params,
657 Callback<std::vector<Location>> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000658 Server->findReferences(Params.textDocument.uri.file(), Params.position,
Sam McCall2c30fbc2018-10-18 12:32:04 +0000659 std::move(Reply));
Sam McCall1ad142f2018-09-05 11:53:07 +0000660}
661
Sam McCalldc8f3cf2018-10-17 07:32:05 +0000662ClangdLSPServer::ClangdLSPServer(class Transport &Transp,
Sam McCalladccab62017-11-23 16:58:22 +0000663 const clangd::CodeCompleteOptions &CCOpts,
Sam McCallc008af62018-10-20 15:30:37 +0000664 Optional<Path> CompileCommandsDir,
Alex Lorenzf8087862018-08-01 17:39:29 +0000665 bool ShouldUseInMemoryCDB,
Sam McCall7363a2f2018-03-05 17:28:54 +0000666 const ClangdServer::Options &Opts)
Sam McCall2c30fbc2018-10-18 12:32:04 +0000667 : Transp(Transp), MsgHandler(new MessageHandler(*this)),
Sam McCalldc8f3cf2018-10-17 07:32:05 +0000668 CDB(ShouldUseInMemoryCDB ? CompilationDB::makeInMemory()
669 : CompilationDB::makeDirectoryBased(
670 std::move(CompileCommandsDir))),
Ilya Biryukovb10ef472018-06-13 09:20:41 +0000671 CCOpts(CCOpts), SupportedSymbolKinds(defaultSymbolKinds()),
Kadir Cetinkaya133d46f2018-09-27 17:13:07 +0000672 SupportedCompletionItemKinds(defaultCompletionItemKinds()),
Sam McCall3d0adbe2018-10-18 14:41:50 +0000673 ClangdServerOpts(Opts) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000674 // clang-format off
675 MsgHandler->bind("initialize", &ClangdLSPServer::onInitialize);
676 MsgHandler->bind("shutdown", &ClangdLSPServer::onShutdown);
677 MsgHandler->bind("textDocument/rangeFormatting", &ClangdLSPServer::onDocumentRangeFormatting);
678 MsgHandler->bind("textDocument/onTypeFormatting", &ClangdLSPServer::onDocumentOnTypeFormatting);
679 MsgHandler->bind("textDocument/formatting", &ClangdLSPServer::onDocumentFormatting);
680 MsgHandler->bind("textDocument/codeAction", &ClangdLSPServer::onCodeAction);
681 MsgHandler->bind("textDocument/completion", &ClangdLSPServer::onCompletion);
682 MsgHandler->bind("textDocument/signatureHelp", &ClangdLSPServer::onSignatureHelp);
683 MsgHandler->bind("textDocument/definition", &ClangdLSPServer::onGoToDefinition);
684 MsgHandler->bind("textDocument/references", &ClangdLSPServer::onReference);
685 MsgHandler->bind("textDocument/switchSourceHeader", &ClangdLSPServer::onSwitchSourceHeader);
686 MsgHandler->bind("textDocument/rename", &ClangdLSPServer::onRename);
687 MsgHandler->bind("textDocument/hover", &ClangdLSPServer::onHover);
688 MsgHandler->bind("textDocument/documentSymbol", &ClangdLSPServer::onDocumentSymbol);
689 MsgHandler->bind("workspace/executeCommand", &ClangdLSPServer::onCommand);
690 MsgHandler->bind("textDocument/documentHighlight", &ClangdLSPServer::onDocumentHighlight);
691 MsgHandler->bind("workspace/symbol", &ClangdLSPServer::onWorkspaceSymbol);
692 MsgHandler->bind("textDocument/didOpen", &ClangdLSPServer::onDocumentDidOpen);
693 MsgHandler->bind("textDocument/didClose", &ClangdLSPServer::onDocumentDidClose);
694 MsgHandler->bind("textDocument/didChange", &ClangdLSPServer::onDocumentDidChange);
695 MsgHandler->bind("workspace/didChangeWatchedFiles", &ClangdLSPServer::onFileEvent);
696 MsgHandler->bind("workspace/didChangeConfiguration", &ClangdLSPServer::onChangeConfiguration);
697 // clang-format on
698}
699
700ClangdLSPServer::~ClangdLSPServer() = default;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000701
Sam McCalldc8f3cf2018-10-17 07:32:05 +0000702bool ClangdLSPServer::run() {
Ilya Biryukovafb55542017-05-16 14:40:30 +0000703 // Run the Language Server loop.
Sam McCalldc8f3cf2018-10-17 07:32:05 +0000704 bool CleanExit = true;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000705 if (auto Err = Transp.loop(*MsgHandler)) {
Sam McCalldc8f3cf2018-10-17 07:32:05 +0000706 elog("Transport error: {0}", std::move(Err));
707 CleanExit = false;
708 }
Ilya Biryukovafb55542017-05-16 14:40:30 +0000709
Ilya Biryukov652364b2018-09-26 05:48:29 +0000710 // Destroy ClangdServer to ensure all worker threads finish.
711 Server.reset();
Sam McCalldc8f3cf2018-10-17 07:32:05 +0000712 return CleanExit && ShutdownRequestReceived;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000713}
714
Ilya Biryukov71028b82018-03-12 15:28:22 +0000715std::vector<Fix> ClangdLSPServer::getFixes(StringRef File,
716 const clangd::Diagnostic &D) {
Ilya Biryukov38d79772017-05-16 09:38:59 +0000717 std::lock_guard<std::mutex> Lock(FixItsMutex);
718 auto DiagToFixItsIter = FixItsMap.find(File);
719 if (DiagToFixItsIter == FixItsMap.end())
720 return {};
721
722 const auto &DiagToFixItsMap = DiagToFixItsIter->second;
723 auto FixItsIter = DiagToFixItsMap.find(D);
724 if (FixItsIter == DiagToFixItsMap.end())
725 return {};
726
727 return FixItsIter->second;
728}
729
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000730void ClangdLSPServer::onDiagnosticsReady(PathRef File,
731 std::vector<Diag> Diagnostics) {
Sam McCalld20d7982018-07-09 14:25:59 +0000732 json::Array DiagnosticsJSON;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000733
734 DiagnosticToReplacementMap LocalFixIts; // Temporary storage
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000735 for (auto &Diag : Diagnostics) {
Sam McCallc008af62018-10-20 15:30:37 +0000736 toLSPDiags(Diag, [&](clangd::Diagnostic Diag, ArrayRef<Fix> Fixes) {
Alex Lorenz8626d362018-08-10 17:25:07 +0000737 json::Object LSPDiag({
Ilya Biryukov71028b82018-03-12 15:28:22 +0000738 {"range", Diag.range},
739 {"severity", Diag.severity},
740 {"message", Diag.message},
741 });
Alex Lorenz8626d362018-08-10 17:25:07 +0000742 // LSP extension: embed the fixes in the diagnostic.
743 if (DiagOpts.EmbedFixesInDiagnostics && !Fixes.empty()) {
744 json::Array ClangdFixes;
745 for (const auto &Fix : Fixes) {
746 WorkspaceEdit WE;
747 URIForFile URI{File};
748 WE.changes = {{URI.uri(), std::vector<TextEdit>(Fix.Edits.begin(),
749 Fix.Edits.end())}};
750 ClangdFixes.push_back(
751 json::Object{{"edit", toJSON(WE)}, {"title", Fix.Message}});
752 }
753 LSPDiag["clangd_fixes"] = std::move(ClangdFixes);
754 }
Alex Lorenz0ce8a7a2018-08-22 20:30:06 +0000755 if (DiagOpts.SendDiagnosticCategory && !Diag.category.empty())
Alex Lorenz37146432018-08-14 22:21:40 +0000756 LSPDiag["category"] = Diag.category;
Alex Lorenz8626d362018-08-10 17:25:07 +0000757 DiagnosticsJSON.push_back(std::move(LSPDiag));
Ilya Biryukov71028b82018-03-12 15:28:22 +0000758
759 auto &FixItsForDiagnostic = LocalFixIts[Diag];
Kirill Bobyrev4a5ff882018-10-07 14:49:41 +0000760 llvm::copy(Fixes, std::back_inserter(FixItsForDiagnostic));
Sam McCalldd0566b2017-11-06 15:40:30 +0000761 });
Ilya Biryukov38d79772017-05-16 09:38:59 +0000762 }
763
764 // Cache FixIts
765 {
766 // FIXME(ibiryukov): should be deleted when documents are removed
767 std::lock_guard<std::mutex> Lock(FixItsMutex);
768 FixItsMap[File] = LocalFixIts;
769 }
770
771 // Publish diagnostics.
Sam McCall2c30fbc2018-10-18 12:32:04 +0000772 notify("textDocument/publishDiagnostics",
773 json::Object{
774 {"uri", URIForFile{File}},
775 {"diagnostics", std::move(DiagnosticsJSON)},
776 });
Ilya Biryukov38d79772017-05-16 09:38:59 +0000777}
Simon Marchi9569fd52018-03-16 14:30:42 +0000778
779void ClangdLSPServer::reparseOpenedFiles() {
780 for (const Path &FilePath : DraftMgr.getActiveFiles())
Ilya Biryukov652364b2018-09-26 05:48:29 +0000781 Server->addDocument(FilePath, *DraftMgr.getDraft(FilePath),
782 WantDiagnostics::Auto);
Simon Marchi9569fd52018-03-16 14:30:42 +0000783}
Alex Lorenzf8087862018-08-01 17:39:29 +0000784
785ClangdLSPServer::CompilationDB ClangdLSPServer::CompilationDB::makeInMemory() {
Sam McCall2172ee92018-10-23 13:14:02 +0000786 return CompilationDB(llvm::make_unique<InMemoryCompilationDb>(),
Alex Lorenzf8087862018-08-01 17:39:29 +0000787 /*IsDirectoryBased=*/false);
788}
789
790ClangdLSPServer::CompilationDB
791ClangdLSPServer::CompilationDB::makeDirectoryBased(
Sam McCallc008af62018-10-20 15:30:37 +0000792 Optional<Path> CompileCommandsDir) {
Alex Lorenzf8087862018-08-01 17:39:29 +0000793 auto CDB = llvm::make_unique<DirectoryBasedGlobalCompilationDatabase>(
794 std::move(CompileCommandsDir));
Sam McCall2172ee92018-10-23 13:14:02 +0000795 return CompilationDB(std::move(CDB),
Alex Lorenzf8087862018-08-01 17:39:29 +0000796 /*IsDirectoryBased=*/true);
797}
798
799void ClangdLSPServer::CompilationDB::invalidate(PathRef File) {
800 if (!IsDirectoryBased)
801 static_cast<InMemoryCompilationDb *>(CDB.get())->invalidate(File);
Alex Lorenzf8087862018-08-01 17:39:29 +0000802}
803
804bool ClangdLSPServer::CompilationDB::setCompilationCommandForFile(
805 PathRef File, tooling::CompileCommand CompilationCommand) {
806 if (IsDirectoryBased) {
807 elog("Trying to set compile command for {0} while using directory-based "
808 "compilation database",
809 File);
810 return false;
811 }
812 return static_cast<InMemoryCompilationDb *>(CDB.get())
813 ->setCompilationCommandForFile(File, std::move(CompilationCommand));
814}
815
816void ClangdLSPServer::CompilationDB::setExtraFlagsForFile(
817 PathRef File, std::vector<std::string> ExtraFlags) {
818 if (!IsDirectoryBased) {
819 elog("Trying to set extra flags for {0} while using in-memory compilation "
820 "database",
821 File);
822 return;
823 }
824 static_cast<DirectoryBasedGlobalCompilationDatabase *>(CDB.get())
825 ->setExtraFlagsForFile(File, std::move(ExtraFlags));
Alex Lorenzf8087862018-08-01 17:39:29 +0000826}
827
828void ClangdLSPServer::CompilationDB::setCompileCommandsDir(Path P) {
829 if (!IsDirectoryBased) {
830 elog("Trying to set compile commands dir while using in-memory compilation "
831 "database");
832 return;
833 }
834 static_cast<DirectoryBasedGlobalCompilationDatabase *>(CDB.get())
835 ->setCompileCommandsDir(P);
Alex Lorenzf8087862018-08-01 17:39:29 +0000836}
Sam McCallc008af62018-10-20 15:30:37 +0000837
838} // namespace clangd
839} // namespace clang