blob: f98f2c426e05880ddc84fa91556af7b7d7d5c312 [file] [log] [blame]
Ilya Biryukov38d79772017-05-16 09:38:59 +00001//===--- ClangdLSPServer.cpp - LSP server ------------------------*- C++-*-===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Ilya Biryukov38d79772017-05-16 09:38:59 +00006//
Kirill Bobyrev8e35f1e2018-08-14 16:03:32 +00007//===----------------------------------------------------------------------===//
Ilya Biryukov38d79772017-05-16 09:38:59 +00008
9#include "ClangdLSPServer.h"
Ilya Biryukov71028b82018-03-12 15:28:22 +000010#include "Diagnostics.h"
Ilya Biryukovf9169d02019-05-29 10:01:00 +000011#include "FormattedString.h"
Kadir Cetinkaya256247c2019-06-26 07:45:27 +000012#include "GlobalCompilationDatabase.h"
Ilya Biryukovcce67a32019-01-29 14:17:36 +000013#include "Protocol.h"
Johan Vikstroma848dab2019-07-04 07:53:12 +000014#include "SemanticHighlighting.h"
Sam McCallb536a2a2017-12-19 12:23:48 +000015#include "SourceCode.h"
Sam McCall2c30fbc2018-10-18 12:32:04 +000016#include "Trace.h"
Eric Liu78ed91a72018-01-29 15:37:46 +000017#include "URI.h"
Sam McCall395fde72019-06-18 13:37:54 +000018#include "refactor/Tweak.h"
Ilya Biryukovcce67a32019-01-29 14:17:36 +000019#include "clang/Tooling/Core/Replacement.h"
Kadir Cetinkaya256247c2019-06-26 07:45:27 +000020#include "llvm/ADT/ArrayRef.h"
Sam McCalla69698f2019-03-27 17:47:49 +000021#include "llvm/ADT/Optional.h"
Kadir Cetinkaya689bf932018-08-24 13:09:41 +000022#include "llvm/ADT/ScopeExit.h"
Simon Marchi9569fd52018-03-16 14:30:42 +000023#include "llvm/Support/Errc.h"
Ilya Biryukovcce67a32019-01-29 14:17:36 +000024#include "llvm/Support/Error.h"
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +000025#include "llvm/Support/FormatVariadic.h"
Eric Liu5740ff52018-01-31 16:26:27 +000026#include "llvm/Support/Path.h"
Sam McCall2c30fbc2018-10-18 12:32:04 +000027#include "llvm/Support/ScopedPrinter.h"
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +000028
Sam McCallc008af62018-10-20 15:30:37 +000029namespace clang {
30namespace clangd {
Ilya Biryukovafb55542017-05-16 14:40:30 +000031namespace {
Ilya Biryukovcce67a32019-01-29 14:17:36 +000032/// Transforms a tweak into a code action that would apply it if executed.
33/// EXPECTS: T.prepare() was called and returned true.
34CodeAction toCodeAction(const ClangdServer::TweakRef &T, const URIForFile &File,
35 Range Selection) {
36 CodeAction CA;
37 CA.title = T.Title;
Sam McCall395fde72019-06-18 13:37:54 +000038 switch (T.Intent) {
39 case Tweak::Refactor:
40 CA.kind = CodeAction::REFACTOR_KIND;
41 break;
42 case Tweak::Info:
43 CA.kind = CodeAction::INFO_KIND;
44 break;
45 }
Ilya Biryukovcce67a32019-01-29 14:17:36 +000046 // This tweak may have an expensive second stage, we only run it if the user
47 // actually chooses it in the UI. We reply with a command that would run the
48 // corresponding tweak.
49 // FIXME: for some tweaks, computing the edits is cheap and we could send them
50 // directly.
51 CA.command.emplace();
52 CA.command->title = T.Title;
53 CA.command->command = Command::CLANGD_APPLY_TWEAK;
54 CA.command->tweakArgs.emplace();
55 CA.command->tweakArgs->file = File;
56 CA.command->tweakArgs->tweakID = T.ID;
57 CA.command->tweakArgs->selection = Selection;
58 return CA;
Simon Pilgrime9a136b2019-02-03 14:08:30 +000059}
Ilya Biryukovcce67a32019-01-29 14:17:36 +000060
Ilya Biryukov19d75602018-11-23 15:21:19 +000061void adjustSymbolKinds(llvm::MutableArrayRef<DocumentSymbol> Syms,
62 SymbolKindBitset Kinds) {
63 for (auto &S : Syms) {
64 S.kind = adjustKindToCapability(S.kind, Kinds);
65 adjustSymbolKinds(S.children, Kinds);
66 }
67}
68
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +000069SymbolKindBitset defaultSymbolKinds() {
70 SymbolKindBitset Defaults;
71 for (size_t I = SymbolKindMin; I <= static_cast<size_t>(SymbolKind::Array);
72 ++I)
73 Defaults.set(I);
74 return Defaults;
75}
76
Kadir Cetinkaya133d46f2018-09-27 17:13:07 +000077CompletionItemKindBitset defaultCompletionItemKinds() {
78 CompletionItemKindBitset Defaults;
79 for (size_t I = CompletionItemKindMin;
80 I <= static_cast<size_t>(CompletionItemKind::Reference); ++I)
81 Defaults.set(I);
82 return Defaults;
83}
84
Haojian Wu1ca2ee42019-07-04 12:27:21 +000085// Build a lookup table (HighlightingKind => {TextMate Scopes}), which is sent
86// to the LSP client.
87std::vector<std::vector<std::string>> buildHighlightScopeLookupTable() {
88 std::vector<std::vector<std::string>> LookupTable;
89 // HighlightingKind is using as the index.
90 for (int KindValue = 0; KindValue < (int)HighlightingKind::NumKinds;
91 ++KindValue)
92 LookupTable.push_back({toTextMateScope((HighlightingKind)(KindValue))});
93 return LookupTable;
94}
95
Ilya Biryukovafb55542017-05-16 14:40:30 +000096} // namespace
97
Sam McCall2c30fbc2018-10-18 12:32:04 +000098// MessageHandler dispatches incoming LSP messages.
99// It handles cross-cutting concerns:
100// - serializes/deserializes protocol objects to JSON
101// - logging of inbound messages
102// - cancellation handling
103// - basic call tracing
Sam McCall3d0adbe2018-10-18 14:41:50 +0000104// MessageHandler ensures that initialize() is called before any other handler.
Sam McCall2c30fbc2018-10-18 12:32:04 +0000105class ClangdLSPServer::MessageHandler : public Transport::MessageHandler {
106public:
107 MessageHandler(ClangdLSPServer &Server) : Server(Server) {}
108
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000109 bool onNotify(llvm::StringRef Method, llvm::json::Value Params) override {
Sam McCalla69698f2019-03-27 17:47:49 +0000110 WithContext HandlerContext(handlerContext());
Sam McCall2c30fbc2018-10-18 12:32:04 +0000111 log("<-- {0}", Method);
112 if (Method == "exit")
113 return false;
Sam McCall3d0adbe2018-10-18 14:41:50 +0000114 if (!Server.Server)
115 elog("Notification {0} before initialization", Method);
116 else if (Method == "$/cancelRequest")
Sam McCall2c30fbc2018-10-18 12:32:04 +0000117 onCancel(std::move(Params));
118 else if (auto Handler = Notifications.lookup(Method))
119 Handler(std::move(Params));
120 else
121 log("unhandled notification {0}", Method);
122 return true;
123 }
124
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000125 bool onCall(llvm::StringRef Method, llvm::json::Value Params,
126 llvm::json::Value ID) override {
Sam McCalla69698f2019-03-27 17:47:49 +0000127 WithContext HandlerContext(handlerContext());
Sam McCalle2f3a732018-10-24 14:26:26 +0000128 // Calls can be canceled by the client. Add cancellation context.
129 WithContext WithCancel(cancelableRequestContext(ID));
130 trace::Span Tracer(Method);
131 SPAN_ATTACH(Tracer, "Params", Params);
132 ReplyOnce Reply(ID, Method, &Server, Tracer.Args);
Sam McCall2c30fbc2018-10-18 12:32:04 +0000133 log("<-- {0}({1})", Method, ID);
Sam McCall3d0adbe2018-10-18 14:41:50 +0000134 if (!Server.Server && Method != "initialize") {
135 elog("Call {0} before initialization.", Method);
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000136 Reply(llvm::make_error<LSPError>("server not initialized",
137 ErrorCode::ServerNotInitialized));
Sam McCall3d0adbe2018-10-18 14:41:50 +0000138 } else if (auto Handler = Calls.lookup(Method))
Sam McCalle2f3a732018-10-24 14:26:26 +0000139 Handler(std::move(Params), std::move(Reply));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000140 else
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000141 Reply(llvm::make_error<LSPError>("method not found",
142 ErrorCode::MethodNotFound));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000143 return true;
144 }
145
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000146 bool onReply(llvm::json::Value ID,
147 llvm::Expected<llvm::json::Value> Result) override {
Sam McCalla69698f2019-03-27 17:47:49 +0000148 WithContext HandlerContext(handlerContext());
Haojian Wuf2516342019-08-05 12:48:09 +0000149
150 Callback<llvm::json::Value> ReplyHandler = nullptr;
151 if (auto IntID = ID.getAsInteger()) {
152 std::lock_guard<std::mutex> Mutex(CallMutex);
153 // Find a corresponding callback for the request ID;
154 for (size_t Index = 0; Index < ReplyCallbacks.size(); ++Index) {
155 if (ReplyCallbacks[Index].first == *IntID) {
156 ReplyHandler = std::move(ReplyCallbacks[Index].second);
157 ReplyCallbacks.erase(ReplyCallbacks.begin() +
158 Index); // remove the entry
159 break;
160 }
161 }
162 }
163
164 if (!ReplyHandler) {
165 // No callback being found, use a default log callback.
166 ReplyHandler = [&ID](llvm::Expected<llvm::json::Value> Result) {
167 elog("received a reply with ID {0}, but there was no such call", ID);
168 if (!Result)
169 llvm::consumeError(Result.takeError());
170 };
171 }
172
173 // Log and run the reply handler.
174 if (Result) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000175 log("<-- reply({0})", ID);
Haojian Wuf2516342019-08-05 12:48:09 +0000176 ReplyHandler(std::move(Result));
177 } else {
178 auto Err = Result.takeError();
179 log("<-- reply({0}) error: {1}", ID, Err);
180 ReplyHandler(std::move(Err));
181 }
Sam McCall2c30fbc2018-10-18 12:32:04 +0000182 return true;
183 }
184
185 // Bind an LSP method name to a call.
Sam McCalle2f3a732018-10-24 14:26:26 +0000186 template <typename Param, typename Result>
Sam McCall2c30fbc2018-10-18 12:32:04 +0000187 void bind(const char *Method,
Sam McCalle2f3a732018-10-24 14:26:26 +0000188 void (ClangdLSPServer::*Handler)(const Param &, Callback<Result>)) {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000189 Calls[Method] = [Method, Handler, this](llvm::json::Value RawParams,
Sam McCalle2f3a732018-10-24 14:26:26 +0000190 ReplyOnce Reply) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000191 Param P;
Sam McCalle2f3a732018-10-24 14:26:26 +0000192 if (fromJSON(RawParams, P)) {
193 (Server.*Handler)(P, std::move(Reply));
194 } else {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000195 elog("Failed to decode {0} request.", Method);
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000196 Reply(llvm::make_error<LSPError>("failed to decode request",
197 ErrorCode::InvalidRequest));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000198 }
Sam McCall2c30fbc2018-10-18 12:32:04 +0000199 };
200 }
201
Haojian Wuf2516342019-08-05 12:48:09 +0000202 // Bind a reply callback to a request. The callback will be invoked when
203 // clangd receives the reply from the LSP client.
204 // Return a call id of the request.
205 llvm::json::Value bindReply(Callback<llvm::json::Value> Reply) {
206 llvm::Optional<std::pair<int, Callback<llvm::json::Value>>> OldestCB;
207 int ID;
208 {
209 std::lock_guard<std::mutex> Mutex(CallMutex);
210 ID = NextCallID++;
211 ReplyCallbacks.emplace_back(ID, std::move(Reply));
212
213 // If the queue overflows, we assume that the client didn't reply the
214 // oldest request, and run the corresponding callback which replies an
215 // error to the client.
216 if (ReplyCallbacks.size() > MaxReplayCallbacks) {
217 elog("more than {0} outstanding LSP calls, forgetting about {1}",
218 MaxReplayCallbacks, ReplyCallbacks.front().first);
219 OldestCB = std::move(ReplyCallbacks.front());
220 ReplyCallbacks.pop_front();
221 }
222 }
223 if (OldestCB)
224 OldestCB->second(llvm::createStringError(
225 llvm::inconvertibleErrorCode(),
226 llvm::formatv("failed to receive a client reply for request ({0})",
227 OldestCB->first)));
228 return ID;
229 }
230
Sam McCall2c30fbc2018-10-18 12:32:04 +0000231 // Bind an LSP method name to a notification.
232 template <typename Param>
233 void bind(const char *Method,
234 void (ClangdLSPServer::*Handler)(const Param &)) {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000235 Notifications[Method] = [Method, Handler,
236 this](llvm::json::Value RawParams) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000237 Param P;
238 if (!fromJSON(RawParams, P)) {
239 elog("Failed to decode {0} request.", Method);
240 return;
241 }
242 trace::Span Tracer(Method);
243 SPAN_ATTACH(Tracer, "Params", RawParams);
244 (Server.*Handler)(P);
245 };
246 }
247
248private:
Sam McCalle2f3a732018-10-24 14:26:26 +0000249 // Function object to reply to an LSP call.
250 // Each instance must be called exactly once, otherwise:
251 // - the bug is logged, and (in debug mode) an assert will fire
252 // - if there was no reply, an error reply is sent
253 // - if there were multiple replies, only the first is sent
254 class ReplyOnce {
255 std::atomic<bool> Replied = {false};
Sam McCalld7babe42018-10-24 15:18:40 +0000256 std::chrono::steady_clock::time_point Start;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000257 llvm::json::Value ID;
Sam McCalle2f3a732018-10-24 14:26:26 +0000258 std::string Method;
259 ClangdLSPServer *Server; // Null when moved-from.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000260 llvm::json::Object *TraceArgs;
Sam McCalle2f3a732018-10-24 14:26:26 +0000261
262 public:
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000263 ReplyOnce(const llvm::json::Value &ID, llvm::StringRef Method,
264 ClangdLSPServer *Server, llvm::json::Object *TraceArgs)
Sam McCalld7babe42018-10-24 15:18:40 +0000265 : Start(std::chrono::steady_clock::now()), ID(ID), Method(Method),
266 Server(Server), TraceArgs(TraceArgs) {
Sam McCalle2f3a732018-10-24 14:26:26 +0000267 assert(Server);
268 }
269 ReplyOnce(ReplyOnce &&Other)
Sam McCalld7babe42018-10-24 15:18:40 +0000270 : Replied(Other.Replied.load()), Start(Other.Start),
271 ID(std::move(Other.ID)), Method(std::move(Other.Method)),
272 Server(Other.Server), TraceArgs(Other.TraceArgs) {
Sam McCalle2f3a732018-10-24 14:26:26 +0000273 Other.Server = nullptr;
274 }
Ilya Biryukov22fa4652019-01-03 13:28:05 +0000275 ReplyOnce &operator=(ReplyOnce &&) = delete;
Sam McCalle2f3a732018-10-24 14:26:26 +0000276 ReplyOnce(const ReplyOnce &) = delete;
Ilya Biryukov22fa4652019-01-03 13:28:05 +0000277 ReplyOnce &operator=(const ReplyOnce &) = delete;
Sam McCalle2f3a732018-10-24 14:26:26 +0000278
279 ~ReplyOnce() {
Haojian Wuf2516342019-08-05 12:48:09 +0000280 // There's one legitimate reason to never reply to a request: clangd's
281 // request handler send a call to the client (e.g. applyEdit) and the
282 // client never replied. In this case, the ReplyOnce is owned by
283 // ClangdLSPServer's reply callback table and is destroyed along with the
284 // server. We don't attempt to send a reply in this case, there's little
285 // to be gained from doing so.
286 if (Server && !Server->IsBeingDestroyed && !Replied) {
Sam McCalle2f3a732018-10-24 14:26:26 +0000287 elog("No reply to message {0}({1})", Method, ID);
288 assert(false && "must reply to all calls!");
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000289 (*this)(llvm::make_error<LSPError>("server failed to reply",
290 ErrorCode::InternalError));
Sam McCalle2f3a732018-10-24 14:26:26 +0000291 }
292 }
293
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000294 void operator()(llvm::Expected<llvm::json::Value> Reply) {
Sam McCalle2f3a732018-10-24 14:26:26 +0000295 assert(Server && "moved-from!");
296 if (Replied.exchange(true)) {
297 elog("Replied twice to message {0}({1})", Method, ID);
298 assert(false && "must reply to each call only once!");
299 return;
300 }
Sam McCalld7babe42018-10-24 15:18:40 +0000301 auto Duration = std::chrono::steady_clock::now() - Start;
302 if (Reply) {
303 log("--> reply:{0}({1}) {2:ms}", Method, ID, Duration);
304 if (TraceArgs)
Sam McCalle2f3a732018-10-24 14:26:26 +0000305 (*TraceArgs)["Reply"] = *Reply;
Sam McCalld7babe42018-10-24 15:18:40 +0000306 std::lock_guard<std::mutex> Lock(Server->TranspWriter);
307 Server->Transp.reply(std::move(ID), std::move(Reply));
308 } else {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000309 llvm::Error Err = Reply.takeError();
Sam McCalld7babe42018-10-24 15:18:40 +0000310 log("--> reply:{0}({1}) {2:ms}, error: {3}", Method, ID, Duration, Err);
311 if (TraceArgs)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000312 (*TraceArgs)["Error"] = llvm::to_string(Err);
Sam McCalld7babe42018-10-24 15:18:40 +0000313 std::lock_guard<std::mutex> Lock(Server->TranspWriter);
314 Server->Transp.reply(std::move(ID), std::move(Err));
Sam McCalle2f3a732018-10-24 14:26:26 +0000315 }
Sam McCalle2f3a732018-10-24 14:26:26 +0000316 }
317 };
318
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000319 llvm::StringMap<std::function<void(llvm::json::Value)>> Notifications;
320 llvm::StringMap<std::function<void(llvm::json::Value, ReplyOnce)>> Calls;
Haojian Wuf2516342019-08-05 12:48:09 +0000321 // The maximum number of callbacks held in clangd.
322 //
323 // We bound the maximum size to the pending map to prevent memory leakage
324 // for cases where LSP clients don't reply for the request.
325 static constexpr int MaxReplayCallbacks = 100;
326 mutable std::mutex CallMutex;
327 int NextCallID = 0; /* GUARDED_BY(CallMutex) */
328 std::deque<std::pair</*RequestID*/ int,
329 /*ReplyHandler*/ Callback<llvm::json::Value>>>
330 ReplyCallbacks; /* GUARDED_BY(CallMutex) */
Sam McCall2c30fbc2018-10-18 12:32:04 +0000331
332 // Method calls may be cancelled by ID, so keep track of their state.
333 // This needs a mutex: handlers may finish on a different thread, and that's
334 // when we clean up entries in the map.
335 mutable std::mutex RequestCancelersMutex;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000336 llvm::StringMap<std::pair<Canceler, /*Cookie*/ unsigned>> RequestCancelers;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000337 unsigned NextRequestCookie = 0; // To disambiguate reused IDs, see below.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000338 void onCancel(const llvm::json::Value &Params) {
339 const llvm::json::Value *ID = nullptr;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000340 if (auto *O = Params.getAsObject())
341 ID = O->get("id");
342 if (!ID) {
343 elog("Bad cancellation request: {0}", Params);
344 return;
345 }
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000346 auto StrID = llvm::to_string(*ID);
Sam McCall2c30fbc2018-10-18 12:32:04 +0000347 std::lock_guard<std::mutex> Lock(RequestCancelersMutex);
348 auto It = RequestCancelers.find(StrID);
349 if (It != RequestCancelers.end())
350 It->second.first(); // Invoke the canceler.
351 }
Sam McCalla69698f2019-03-27 17:47:49 +0000352
353 Context handlerContext() const {
354 return Context::current().derive(
355 kCurrentOffsetEncoding,
356 Server.NegotiatedOffsetEncoding.getValueOr(OffsetEncoding::UTF16));
357 }
358
Sam McCall2c30fbc2018-10-18 12:32:04 +0000359 // We run cancelable requests in a context that does two things:
360 // - allows cancellation using RequestCancelers[ID]
361 // - cleans up the entry in RequestCancelers when it's no longer needed
362 // If a client reuses an ID, the last wins and the first cannot be canceled.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000363 Context cancelableRequestContext(const llvm::json::Value &ID) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000364 auto Task = cancelableTask();
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000365 auto StrID = llvm::to_string(ID); // JSON-serialize ID for map key.
Sam McCall2c30fbc2018-10-18 12:32:04 +0000366 auto Cookie = NextRequestCookie++; // No lock, only called on main thread.
367 {
368 std::lock_guard<std::mutex> Lock(RequestCancelersMutex);
369 RequestCancelers[StrID] = {std::move(Task.second), Cookie};
370 }
371 // When the request ends, we can clean up the entry we just added.
372 // The cookie lets us check that it hasn't been overwritten due to ID
373 // reuse.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000374 return Task.first.derive(llvm::make_scope_exit([this, StrID, Cookie] {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000375 std::lock_guard<std::mutex> Lock(RequestCancelersMutex);
376 auto It = RequestCancelers.find(StrID);
377 if (It != RequestCancelers.end() && It->second.second == Cookie)
378 RequestCancelers.erase(It);
379 }));
380 }
381
382 ClangdLSPServer &Server;
383};
Haojian Wuf2516342019-08-05 12:48:09 +0000384constexpr int ClangdLSPServer::MessageHandler::MaxReplayCallbacks;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000385
386// call(), notify(), and reply() wrap the Transport, adding logging and locking.
Haojian Wuf2516342019-08-05 12:48:09 +0000387void ClangdLSPServer::callRaw(StringRef Method, llvm::json::Value Params,
388 Callback<llvm::json::Value> CB) {
389 auto ID = MsgHandler->bindReply(std::move(CB));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000390 log("--> {0}({1})", Method, ID);
Sam McCall2c30fbc2018-10-18 12:32:04 +0000391 std::lock_guard<std::mutex> Lock(TranspWriter);
392 Transp.call(Method, std::move(Params), ID);
393}
394
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000395void ClangdLSPServer::notify(llvm::StringRef Method, llvm::json::Value Params) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000396 log("--> {0}", Method);
397 std::lock_guard<std::mutex> Lock(TranspWriter);
398 Transp.notify(Method, std::move(Params));
399}
400
Sam McCall2c30fbc2018-10-18 12:32:04 +0000401void ClangdLSPServer::onInitialize(const InitializeParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000402 Callback<llvm::json::Value> Reply) {
Sam McCalla69698f2019-03-27 17:47:49 +0000403 // Determine character encoding first as it affects constructed ClangdServer.
404 if (Params.capabilities.offsetEncoding && !NegotiatedOffsetEncoding) {
405 NegotiatedOffsetEncoding = OffsetEncoding::UTF16; // fallback
406 for (OffsetEncoding Supported : *Params.capabilities.offsetEncoding)
407 if (Supported != OffsetEncoding::UnsupportedEncoding) {
408 NegotiatedOffsetEncoding = Supported;
409 break;
410 }
411 }
412 llvm::Optional<WithContextValue> WithOffsetEncoding;
413 if (NegotiatedOffsetEncoding)
414 WithOffsetEncoding.emplace(kCurrentOffsetEncoding,
415 *NegotiatedOffsetEncoding);
416
Johan Vikstroma848dab2019-07-04 07:53:12 +0000417 ClangdServerOpts.SemanticHighlighting =
418 Params.capabilities.SemanticHighlighting;
Sam McCall0d9b40f2018-10-19 15:42:23 +0000419 if (Params.rootUri && *Params.rootUri)
420 ClangdServerOpts.WorkspaceRoot = Params.rootUri->file();
421 else if (Params.rootPath && !Params.rootPath->empty())
422 ClangdServerOpts.WorkspaceRoot = *Params.rootPath;
Sam McCall3d0adbe2018-10-18 14:41:50 +0000423 if (Server)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000424 return Reply(llvm::make_error<LSPError>("server already initialized",
425 ErrorCode::InvalidRequest));
Sam McCallbc904612018-10-25 04:22:52 +0000426 if (const auto &Dir = Params.initializationOptions.compilationDatabasePath)
427 CompileCommandsDir = Dir;
Kadir Cetinkaya256247c2019-06-26 07:45:27 +0000428 if (UseDirBasedCDB) {
Jonas Devlieghere1c705d92019-08-14 23:52:23 +0000429 BaseCDB = std::make_unique<DirectoryBasedGlobalCompilationDatabase>(
Sam McCallc55d09a2018-11-02 13:09:36 +0000430 CompileCommandsDir);
Kadir Cetinkaya256247c2019-06-26 07:45:27 +0000431 BaseCDB = getQueryDriverDatabase(
432 llvm::makeArrayRef(ClangdServerOpts.QueryDriverGlobs),
433 std::move(BaseCDB));
434 }
Kadir Cetinkayabe6b35d2019-01-22 09:10:20 +0000435 CDB.emplace(BaseCDB.get(), Params.initializationOptions.fallbackFlags,
436 ClangdServerOpts.ResourceDir);
Sam McCallc55d09a2018-11-02 13:09:36 +0000437 Server.emplace(*CDB, FSProvider, static_cast<DiagnosticsConsumer &>(*this),
438 ClangdServerOpts);
Sam McCallbc904612018-10-25 04:22:52 +0000439 applyConfiguration(Params.initializationOptions.ConfigSettings);
Simon Marchi88016782018-08-01 11:28:49 +0000440
Sam McCallbf6a2fc2018-10-17 07:33:42 +0000441 CCOpts.EnableSnippets = Params.capabilities.CompletionSnippets;
Sam McCall8d412942019-06-18 11:57:26 +0000442 CCOpts.IncludeFixIts = Params.capabilities.CompletionFixes;
Sam McCall5f092e32019-07-08 17:27:15 +0000443 if (!CCOpts.BundleOverloads.hasValue())
444 CCOpts.BundleOverloads = Params.capabilities.HasSignatureHelp;
Sam McCallbf6a2fc2018-10-17 07:33:42 +0000445 DiagOpts.EmbedFixesInDiagnostics = Params.capabilities.DiagnosticFixes;
446 DiagOpts.SendDiagnosticCategory = Params.capabilities.DiagnosticCategory;
Sam McCallc9e4ee92019-04-18 15:17:07 +0000447 DiagOpts.EmitRelatedLocations =
448 Params.capabilities.DiagnosticRelatedInformation;
Sam McCallbf6a2fc2018-10-17 07:33:42 +0000449 if (Params.capabilities.WorkspaceSymbolKinds)
450 SupportedSymbolKinds |= *Params.capabilities.WorkspaceSymbolKinds;
451 if (Params.capabilities.CompletionItemKinds)
452 SupportedCompletionItemKinds |= *Params.capabilities.CompletionItemKinds;
453 SupportsCodeAction = Params.capabilities.CodeActionStructure;
Ilya Biryukov19d75602018-11-23 15:21:19 +0000454 SupportsHierarchicalDocumentSymbol =
455 Params.capabilities.HierarchicalDocumentSymbol;
Haojian Wub6188492018-12-20 15:39:12 +0000456 SupportFileStatus = Params.initializationOptions.FileStatus;
Ilya Biryukovf9169d02019-05-29 10:01:00 +0000457 HoverContentFormat = Params.capabilities.HoverContentFormat;
Ilya Biryukov4ef0f822019-06-04 09:36:59 +0000458 SupportsOffsetsInSignatureHelp = Params.capabilities.OffsetsInSignatureHelp;
Haojian Wuf429ab62019-07-24 07:49:23 +0000459
460 // Per LSP, renameProvider can be either boolean or RenameOptions.
461 // RenameOptions will be specified if the client states it supports prepare.
462 llvm::json::Value RenameProvider =
463 llvm::json::Object{{"prepareProvider", true}};
464 if (!Params.capabilities.RenamePrepareSupport) // Only boolean allowed per LSP
465 RenameProvider = true;
466
Sam McCalla69698f2019-03-27 17:47:49 +0000467 llvm::json::Object Result{
Sam McCall0930ab02017-11-07 15:49:35 +0000468 {{"capabilities",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000469 llvm::json::Object{
Simon Marchi98082622018-03-26 14:41:40 +0000470 {"textDocumentSync", (int)TextDocumentSyncKind::Incremental},
Sam McCall0930ab02017-11-07 15:49:35 +0000471 {"documentFormattingProvider", true},
472 {"documentRangeFormattingProvider", true},
473 {"documentOnTypeFormattingProvider",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000474 llvm::json::Object{
Sam McCall25c62572019-06-10 14:26:21 +0000475 {"firstTriggerCharacter", "\n"},
Sam McCall0930ab02017-11-07 15:49:35 +0000476 {"moreTriggerCharacter", {}},
477 }},
478 {"codeActionProvider", true},
479 {"completionProvider",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000480 llvm::json::Object{
Sam McCall0930ab02017-11-07 15:49:35 +0000481 {"resolveProvider", false},
Ilya Biryukovb0826bd2019-01-03 13:37:12 +0000482 // We do extra checks for '>' and ':' in completion to only
483 // trigger on '->' and '::'.
Sam McCall0930ab02017-11-07 15:49:35 +0000484 {"triggerCharacters", {".", ">", ":"}},
485 }},
486 {"signatureHelpProvider",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000487 llvm::json::Object{
Sam McCall0930ab02017-11-07 15:49:35 +0000488 {"triggerCharacters", {"(", ","}},
489 }},
Sam McCall866ba2c2019-02-01 11:26:13 +0000490 {"declarationProvider", true},
Sam McCall0930ab02017-11-07 15:49:35 +0000491 {"definitionProvider", true},
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000492 {"documentHighlightProvider", true},
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000493 {"hoverProvider", true},
Haojian Wuf429ab62019-07-24 07:49:23 +0000494 {"renameProvider", std::move(RenameProvider)},
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000495 {"documentSymbolProvider", true},
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000496 {"workspaceSymbolProvider", true},
Sam McCall1ad142f2018-09-05 11:53:07 +0000497 {"referencesProvider", true},
Sam McCall0930ab02017-11-07 15:49:35 +0000498 {"executeCommandProvider",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000499 llvm::json::Object{
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000500 {"commands",
501 {ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND,
502 ExecuteCommandParams::CLANGD_APPLY_TWEAK}},
Sam McCall0930ab02017-11-07 15:49:35 +0000503 }},
Kadir Cetinkaya86658022019-03-19 09:27:04 +0000504 {"typeHierarchyProvider", true},
Sam McCalla69698f2019-03-27 17:47:49 +0000505 }}}};
506 if (NegotiatedOffsetEncoding)
507 Result["offsetEncoding"] = *NegotiatedOffsetEncoding;
Johan Vikstroma848dab2019-07-04 07:53:12 +0000508 if (Params.capabilities.SemanticHighlighting)
509 Result.getObject("capabilities")
510 ->insert(
511 {"semanticHighlighting",
Haojian Wu1ca2ee42019-07-04 12:27:21 +0000512 llvm::json::Object{{"scopes", buildHighlightScopeLookupTable()}}});
Sam McCalla69698f2019-03-27 17:47:49 +0000513 Reply(std::move(Result));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000514}
515
Sam McCall2c30fbc2018-10-18 12:32:04 +0000516void ClangdLSPServer::onShutdown(const ShutdownParams &Params,
517 Callback<std::nullptr_t> Reply) {
Ilya Biryukov0d9b8a32017-10-25 08:45:41 +0000518 // Do essentially nothing, just say we're ready to exit.
519 ShutdownRequestReceived = true;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000520 Reply(nullptr);
Sam McCall8a5dded2017-10-12 13:29:58 +0000521}
Ilya Biryukovafb55542017-05-16 14:40:30 +0000522
Sam McCall422c8282018-11-26 16:00:11 +0000523// sync is a clangd extension: it blocks until all background work completes.
524// It blocks the calling thread, so no messages are processed until it returns!
525void ClangdLSPServer::onSync(const NoParams &Params,
526 Callback<std::nullptr_t> Reply) {
527 if (Server->blockUntilIdleForTest(/*TimeoutSeconds=*/60))
528 Reply(nullptr);
529 else
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000530 Reply(llvm::createStringError(llvm::inconvertibleErrorCode(),
531 "Not idle after a minute"));
Sam McCall422c8282018-11-26 16:00:11 +0000532}
533
Sam McCall2c30fbc2018-10-18 12:32:04 +0000534void ClangdLSPServer::onDocumentDidOpen(
535 const DidOpenTextDocumentParams &Params) {
Simon Marchi9569fd52018-03-16 14:30:42 +0000536 PathRef File = Params.textDocument.uri.file();
Ilya Biryukovb10ef472018-06-13 09:20:41 +0000537
Sam McCall2c30fbc2018-10-18 12:32:04 +0000538 const std::string &Contents = Params.textDocument.text;
Simon Marchi9569fd52018-03-16 14:30:42 +0000539
Simon Marchi98082622018-03-26 14:41:40 +0000540 DraftMgr.addDraft(File, Contents);
Ilya Biryukov652364b2018-09-26 05:48:29 +0000541 Server->addDocument(File, Contents, WantDiagnostics::Yes);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000542}
543
Sam McCall2c30fbc2018-10-18 12:32:04 +0000544void ClangdLSPServer::onDocumentDidChange(
545 const DidChangeTextDocumentParams &Params) {
Eric Liu51fed182018-02-22 18:40:39 +0000546 auto WantDiags = WantDiagnostics::Auto;
547 if (Params.wantDiagnostics.hasValue())
548 WantDiags = Params.wantDiagnostics.getValue() ? WantDiagnostics::Yes
549 : WantDiagnostics::No;
Simon Marchi9569fd52018-03-16 14:30:42 +0000550
551 PathRef File = Params.textDocument.uri.file();
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000552 llvm::Expected<std::string> Contents =
Simon Marchi98082622018-03-26 14:41:40 +0000553 DraftMgr.updateDraft(File, Params.contentChanges);
554 if (!Contents) {
555 // If this fails, we are most likely going to be not in sync anymore with
556 // the client. It is better to remove the draft and let further operations
557 // fail rather than giving wrong results.
558 DraftMgr.removeDraft(File);
Ilya Biryukov652364b2018-09-26 05:48:29 +0000559 Server->removeDocument(File);
Sam McCallbed58852018-07-11 10:35:11 +0000560 elog("Failed to update {0}: {1}", File, Contents.takeError());
Simon Marchi98082622018-03-26 14:41:40 +0000561 return;
562 }
Simon Marchi9569fd52018-03-16 14:30:42 +0000563
Ilya Biryukov652364b2018-09-26 05:48:29 +0000564 Server->addDocument(File, *Contents, WantDiags);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000565}
566
Sam McCall2c30fbc2018-10-18 12:32:04 +0000567void ClangdLSPServer::onFileEvent(const DidChangeWatchedFilesParams &Params) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000568 Server->onFileEvent(Params);
Marc-Andre Laperlebf114242017-10-02 18:00:37 +0000569}
570
Sam McCall2c30fbc2018-10-18 12:32:04 +0000571void ClangdLSPServer::onCommand(const ExecuteCommandParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000572 Callback<llvm::json::Value> Reply) {
Haojian Wuf2516342019-08-05 12:48:09 +0000573 auto ApplyEdit = [this](WorkspaceEdit WE,
574 Callback<ApplyWorkspaceEditResponse> Reply) {
Eric Liuc5105f92018-02-16 14:15:55 +0000575 ApplyWorkspaceEditParams Edit;
576 Edit.edit = std::move(WE);
Haojian Wuf2516342019-08-05 12:48:09 +0000577 call("workspace/applyEdit", std::move(Edit), std::move(Reply));
Eric Liuc5105f92018-02-16 14:15:55 +0000578 };
Haojian Wuf2516342019-08-05 12:48:09 +0000579 // FIXME: this lambda is tangled and confusing, refactor it.
580 auto ReplyAfterApplyingEdit =
581 [](decltype(Reply) Reply, std::string SuccessMessage,
582 llvm::Expected<ApplyWorkspaceEditResponse> Response) {
583 if (!Response)
584 return Reply(Response.takeError());
585 if (!Response->applied) {
586 std::string Reason = Response->failureReason
587 ? *Response->failureReason
588 : "unknown reason";
589 return Reply(llvm::createStringError(
590 llvm::inconvertibleErrorCode(),
591 ("edits were not applied: " + Reason).c_str()));
592 }
593 return Reply(SuccessMessage);
594 };
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000595 if (Params.command == ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND &&
596 Params.workspaceEdit) {
597 // The flow for "apply-fix" :
598 // 1. We publish a diagnostic, including fixits
599 // 2. The user clicks on the diagnostic, the editor asks us for code actions
600 // 3. We send code actions, with the fixit embedded as context
601 // 4. The user selects the fixit, the editor asks us to apply it
602 // 5. We unwrap the changes and send them back to the editor
Haojian Wuf2516342019-08-05 12:48:09 +0000603 // 6. The editor applies the changes (applyEdit), and sends us a reply
604 // 7. We unwrap the reply and send a reply to the editor.
605 ApplyEdit(*Params.workspaceEdit,
606 Bind(ReplyAfterApplyingEdit, std::move(Reply),
607 std::string("Fix applied.")));
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000608 } else if (Params.command == ExecuteCommandParams::CLANGD_APPLY_TWEAK &&
609 Params.tweakArgs) {
610 auto Code = DraftMgr.getDraft(Params.tweakArgs->file.file());
611 if (!Code)
612 return Reply(llvm::createStringError(
613 llvm::inconvertibleErrorCode(),
614 "trying to apply a code action for a non-added file"));
615
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000616 auto Action = [this, ApplyEdit, ReplyAfterApplyingEdit,
617 Reply = std::move(Reply), File = Params.tweakArgs->file,
618 Code = std::move(*Code)](
619 llvm::Expected<Tweak::Effect> R) mutable {
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000620 if (!R)
621 return Reply(R.takeError());
622
Sam McCall395fde72019-06-18 13:37:54 +0000623 if (R->ApplyEdit) {
624 WorkspaceEdit WE;
625 WE.changes.emplace();
Sam McCall08372eb2019-06-19 07:29:10 +0000626 (*WE.changes)[File.uri()] = replacementsToEdits(Code, *R->ApplyEdit);
Haojian Wuf2516342019-08-05 12:48:09 +0000627 ApplyEdit(std::move(WE), Bind(ReplyAfterApplyingEdit, std::move(Reply),
628 std::string("Tweak applied.")));
Sam McCall395fde72019-06-18 13:37:54 +0000629 }
630 if (R->ShowMessage) {
631 ShowMessageParams Msg;
632 Msg.message = *R->ShowMessage;
633 Msg.type = MessageType::Info;
634 notify("window/showMessage", Msg);
Haojian Wuf2516342019-08-05 12:48:09 +0000635 Reply("Tweak applied.");
Sam McCall395fde72019-06-18 13:37:54 +0000636 }
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000637 };
638 Server->applyTweak(Params.tweakArgs->file.file(),
639 Params.tweakArgs->selection, Params.tweakArgs->tweakID,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000640 std::move(Action));
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000641 } else {
642 // We should not get here because ExecuteCommandParams would not have
643 // parsed in the first place and this handler should not be called. But if
644 // more commands are added, this will be here has a safe guard.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000645 Reply(llvm::make_error<LSPError>(
646 llvm::formatv("Unsupported command \"{0}\".", Params.command).str(),
Sam McCall2c30fbc2018-10-18 12:32:04 +0000647 ErrorCode::InvalidParams));
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000648 }
649}
650
Sam McCall2c30fbc2018-10-18 12:32:04 +0000651void ClangdLSPServer::onWorkspaceSymbol(
652 const WorkspaceSymbolParams &Params,
653 Callback<std::vector<SymbolInformation>> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000654 Server->workspaceSymbols(
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000655 Params.query, CCOpts.Limit,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000656 [Reply = std::move(Reply),
657 this](llvm::Expected<std::vector<SymbolInformation>> Items) mutable {
658 if (!Items)
659 return Reply(Items.takeError());
660 for (auto &Sym : *Items)
661 Sym.kind = adjustKindToCapability(Sym.kind, SupportedSymbolKinds);
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000662
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000663 Reply(std::move(*Items));
664 });
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000665}
666
Haojian Wuf429ab62019-07-24 07:49:23 +0000667void ClangdLSPServer::onPrepareRename(const TextDocumentPositionParams &Params,
668 Callback<llvm::Optional<Range>> Reply) {
669 Server->prepareRename(Params.textDocument.uri.file(), Params.position,
670 std::move(Reply));
671}
672
Sam McCall2c30fbc2018-10-18 12:32:04 +0000673void ClangdLSPServer::onRename(const RenameParams &Params,
674 Callback<WorkspaceEdit> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000675 Path File = Params.textDocument.uri.file();
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000676 llvm::Optional<std::string> Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000677 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000678 return Reply(llvm::make_error<LSPError>(
679 "onRename called for non-added file", ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000680
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000681 Server->rename(File, Params.position, Params.newName, /*WantFormat=*/true,
682 [File, Code, Params, Reply = std::move(Reply)](
683 llvm::Expected<std::vector<TextEdit>> Edits) mutable {
684 if (!Edits)
685 return Reply(Edits.takeError());
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000686
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000687 WorkspaceEdit WE;
688 WE.changes = {{Params.textDocument.uri.uri(), *Edits}};
689 Reply(WE);
690 });
Haojian Wu345099c2017-11-09 11:30:04 +0000691}
692
Sam McCall2c30fbc2018-10-18 12:32:04 +0000693void ClangdLSPServer::onDocumentDidClose(
694 const DidCloseTextDocumentParams &Params) {
Simon Marchi9569fd52018-03-16 14:30:42 +0000695 PathRef File = Params.textDocument.uri.file();
696 DraftMgr.removeDraft(File);
Ilya Biryukov652364b2018-09-26 05:48:29 +0000697 Server->removeDocument(File);
Ilya Biryukov49c10712019-03-25 10:15:11 +0000698
699 {
700 std::lock_guard<std::mutex> Lock(FixItsMutex);
701 FixItsMap.erase(File);
702 }
Johan Vikstromc2653ef22019-08-01 08:08:44 +0000703 {
704 std::lock_guard<std::mutex> HLock(HighlightingsMutex);
705 FileToHighlightings.erase(File);
706 }
Ilya Biryukov49c10712019-03-25 10:15:11 +0000707 // clangd will not send updates for this file anymore, so we empty out the
708 // list of diagnostics shown on the client (e.g. in the "Problems" pane of
709 // VSCode). Note that this cannot race with actual diagnostics responses
710 // because removeDocument() guarantees no diagnostic callbacks will be
711 // executed after it returns.
712 publishDiagnostics(URIForFile::canonicalize(File, /*TUPath=*/File), {});
Ilya Biryukovafb55542017-05-16 14:40:30 +0000713}
714
Sam McCall4db732a2017-09-30 10:08:52 +0000715void ClangdLSPServer::onDocumentOnTypeFormatting(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000716 const DocumentOnTypeFormattingParams &Params,
717 Callback<std::vector<TextEdit>> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000718 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000719 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000720 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000721 return Reply(llvm::make_error<LSPError>(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000722 "onDocumentOnTypeFormatting called for non-added file",
723 ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000724
Sam McCall25c62572019-06-10 14:26:21 +0000725 Reply(Server->formatOnType(*Code, File, Params.position, Params.ch));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000726}
727
Sam McCall4db732a2017-09-30 10:08:52 +0000728void ClangdLSPServer::onDocumentRangeFormatting(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000729 const DocumentRangeFormattingParams &Params,
730 Callback<std::vector<TextEdit>> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000731 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000732 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000733 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000734 return Reply(llvm::make_error<LSPError>(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000735 "onDocumentRangeFormatting called for non-added file",
736 ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000737
Ilya Biryukov652364b2018-09-26 05:48:29 +0000738 auto ReplacementsOrError = Server->formatRange(*Code, File, Params.range);
Raoul Wols212bcf82017-12-12 20:25:06 +0000739 if (ReplacementsOrError)
Sam McCall2c30fbc2018-10-18 12:32:04 +0000740 Reply(replacementsToEdits(*Code, ReplacementsOrError.get()));
Raoul Wols212bcf82017-12-12 20:25:06 +0000741 else
Sam McCall2c30fbc2018-10-18 12:32:04 +0000742 Reply(ReplacementsOrError.takeError());
Ilya Biryukovafb55542017-05-16 14:40:30 +0000743}
744
Sam McCall2c30fbc2018-10-18 12:32:04 +0000745void ClangdLSPServer::onDocumentFormatting(
746 const DocumentFormattingParams &Params,
747 Callback<std::vector<TextEdit>> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000748 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000749 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000750 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000751 return Reply(llvm::make_error<LSPError>(
752 "onDocumentFormatting called for non-added file",
753 ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000754
Ilya Biryukov652364b2018-09-26 05:48:29 +0000755 auto ReplacementsOrError = Server->formatFile(*Code, File);
Raoul Wols212bcf82017-12-12 20:25:06 +0000756 if (ReplacementsOrError)
Sam McCall2c30fbc2018-10-18 12:32:04 +0000757 Reply(replacementsToEdits(*Code, ReplacementsOrError.get()));
Raoul Wols212bcf82017-12-12 20:25:06 +0000758 else
Sam McCall2c30fbc2018-10-18 12:32:04 +0000759 Reply(ReplacementsOrError.takeError());
Sam McCall4db732a2017-09-30 10:08:52 +0000760}
761
Ilya Biryukov19d75602018-11-23 15:21:19 +0000762/// The functions constructs a flattened view of the DocumentSymbol hierarchy.
763/// Used by the clients that do not support the hierarchical view.
764static std::vector<SymbolInformation>
765flattenSymbolHierarchy(llvm::ArrayRef<DocumentSymbol> Symbols,
766 const URIForFile &FileURI) {
767
768 std::vector<SymbolInformation> Results;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000769 std::function<void(const DocumentSymbol &, llvm::StringRef)> Process =
770 [&](const DocumentSymbol &S, llvm::Optional<llvm::StringRef> ParentName) {
Ilya Biryukov19d75602018-11-23 15:21:19 +0000771 SymbolInformation SI;
772 SI.containerName = ParentName ? "" : *ParentName;
773 SI.name = S.name;
774 SI.kind = S.kind;
775 SI.location.range = S.range;
776 SI.location.uri = FileURI;
777
778 Results.push_back(std::move(SI));
779 std::string FullName =
780 !ParentName ? S.name : (ParentName->str() + "::" + S.name);
781 for (auto &C : S.children)
782 Process(C, /*ParentName=*/FullName);
783 };
784 for (auto &S : Symbols)
785 Process(S, /*ParentName=*/"");
786 return Results;
787}
788
789void ClangdLSPServer::onDocumentSymbol(const DocumentSymbolParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000790 Callback<llvm::json::Value> Reply) {
Ilya Biryukov19d75602018-11-23 15:21:19 +0000791 URIForFile FileURI = Params.textDocument.uri;
Ilya Biryukov652364b2018-09-26 05:48:29 +0000792 Server->documentSymbols(
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000793 Params.textDocument.uri.file(),
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000794 [this, FileURI, Reply = std::move(Reply)](
795 llvm::Expected<std::vector<DocumentSymbol>> Items) mutable {
796 if (!Items)
797 return Reply(Items.takeError());
798 adjustSymbolKinds(*Items, SupportedSymbolKinds);
799 if (SupportsHierarchicalDocumentSymbol)
800 return Reply(std::move(*Items));
801 else
802 return Reply(flattenSymbolHierarchy(*Items, FileURI));
803 });
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000804}
805
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000806static llvm::Optional<Command> asCommand(const CodeAction &Action) {
Sam McCall20841d42018-10-16 16:29:41 +0000807 Command Cmd;
808 if (Action.command && Action.edit)
Sam McCallc008af62018-10-20 15:30:37 +0000809 return None; // Not representable. (We never emit these anyway).
Sam McCall20841d42018-10-16 16:29:41 +0000810 if (Action.command) {
811 Cmd = *Action.command;
812 } else if (Action.edit) {
813 Cmd.command = Command::CLANGD_APPLY_FIX_COMMAND;
814 Cmd.workspaceEdit = *Action.edit;
815 } else {
Sam McCallc008af62018-10-20 15:30:37 +0000816 return None;
Sam McCall20841d42018-10-16 16:29:41 +0000817 }
818 Cmd.title = Action.title;
819 if (Action.kind && *Action.kind == CodeAction::QUICKFIX_KIND)
820 Cmd.title = "Apply fix: " + Cmd.title;
821 return Cmd;
822}
823
Sam McCall2c30fbc2018-10-18 12:32:04 +0000824void ClangdLSPServer::onCodeAction(const CodeActionParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000825 Callback<llvm::json::Value> Reply) {
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000826 URIForFile File = Params.textDocument.uri;
827 auto Code = DraftMgr.getDraft(File.file());
Sam McCall2c30fbc2018-10-18 12:32:04 +0000828 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000829 return Reply(llvm::make_error<LSPError>(
830 "onCodeAction called for non-added file", ErrorCode::InvalidParams));
Sam McCall20841d42018-10-16 16:29:41 +0000831 // We provide a code action for Fixes on the specified diagnostics.
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000832 std::vector<CodeAction> FixIts;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000833 for (const Diagnostic &D : Params.context.diagnostics) {
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000834 for (auto &F : getFixes(File.file(), D)) {
835 FixIts.push_back(toCodeAction(F, Params.textDocument.uri));
836 FixIts.back().diagnostics = {D};
Sam McCalldd0566b2017-11-06 15:40:30 +0000837 }
Ilya Biryukovafb55542017-05-16 14:40:30 +0000838 }
Sam McCall20841d42018-10-16 16:29:41 +0000839
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000840 // Now enumerate the semantic code actions.
841 auto ConsumeActions =
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000842 [Reply = std::move(Reply), File, Code = std::move(*Code),
843 Selection = Params.range, FixIts = std::move(FixIts), this](
844 llvm::Expected<std::vector<ClangdServer::TweakRef>> Tweaks) mutable {
Ilya Biryukovc6ed7782019-01-30 14:24:17 +0000845 if (!Tweaks)
846 return Reply(Tweaks.takeError());
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000847
848 std::vector<CodeAction> Actions = std::move(FixIts);
849 Actions.reserve(Actions.size() + Tweaks->size());
850 for (const auto &T : *Tweaks)
851 Actions.push_back(toCodeAction(T, File, Selection));
852
853 if (SupportsCodeAction)
854 return Reply(llvm::json::Array(Actions));
855 std::vector<Command> Commands;
856 for (const auto &Action : Actions) {
857 if (auto Command = asCommand(Action))
858 Commands.push_back(std::move(*Command));
859 }
860 return Reply(llvm::json::Array(Commands));
861 };
862
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000863 Server->enumerateTweaks(File.file(), Params.range, std::move(ConsumeActions));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000864}
865
Ilya Biryukovb0826bd2019-01-03 13:37:12 +0000866void ClangdLSPServer::onCompletion(const CompletionParams &Params,
Sam McCall2c30fbc2018-10-18 12:32:04 +0000867 Callback<CompletionList> Reply) {
Ilya Biryukova7a11472019-06-07 16:24:38 +0000868 if (!shouldRunCompletion(Params)) {
869 // Clients sometimes auto-trigger completions in undesired places (e.g.
870 // 'a >^ '), we return empty results in those cases.
871 vlog("ignored auto-triggered completion, preceding char did not match");
872 return Reply(CompletionList());
873 }
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000874 Server->codeComplete(Params.textDocument.uri.file(), Params.position, CCOpts,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000875 [Reply = std::move(Reply),
876 this](llvm::Expected<CodeCompleteResult> List) mutable {
877 if (!List)
878 return Reply(List.takeError());
879 CompletionList LSPList;
880 LSPList.isIncomplete = List->HasMore;
881 for (const auto &R : List->Completions) {
882 CompletionItem C = R.render(CCOpts);
883 C.kind = adjustKindToCapability(
884 C.kind, SupportedCompletionItemKinds);
885 LSPList.items.push_back(std::move(C));
886 }
887 return Reply(std::move(LSPList));
888 });
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000889}
890
Sam McCall2c30fbc2018-10-18 12:32:04 +0000891void ClangdLSPServer::onSignatureHelp(const TextDocumentPositionParams &Params,
892 Callback<SignatureHelp> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000893 Server->signatureHelp(Params.textDocument.uri.file(), Params.position,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000894 [Reply = std::move(Reply), this](
895 llvm::Expected<SignatureHelp> Signature) mutable {
896 if (!Signature)
897 return Reply(Signature.takeError());
898 if (SupportsOffsetsInSignatureHelp)
899 return Reply(std::move(*Signature));
900 // Strip out the offsets from signature help for
901 // clients that only support string labels.
902 for (auto &SigInfo : Signature->signatures) {
903 for (auto &Param : SigInfo.parameters)
904 Param.labelOffsets.reset();
905 }
906 return Reply(std::move(*Signature));
907 });
Ilya Biryukov652364b2018-09-26 05:48:29 +0000908}
909
Sam McCall0dbab7f2019-02-02 05:56:00 +0000910// Go to definition has a toggle function: if def and decl are distinct, then
911// the first press gives you the def, the second gives you the matching def.
912// getToggle() returns the counterpart location that under the cursor.
913//
914// We return the toggled location alone (ignoring other symbols) to encourage
915// editors to "bounce" quickly between locations, without showing a menu.
916static Location *getToggle(const TextDocumentPositionParams &Point,
917 LocatedSymbol &Sym) {
918 // Toggle only makes sense with two distinct locations.
919 if (!Sym.Definition || *Sym.Definition == Sym.PreferredDeclaration)
920 return nullptr;
921 if (Sym.Definition->uri.file() == Point.textDocument.uri.file() &&
922 Sym.Definition->range.contains(Point.position))
923 return &Sym.PreferredDeclaration;
924 if (Sym.PreferredDeclaration.uri.file() == Point.textDocument.uri.file() &&
925 Sym.PreferredDeclaration.range.contains(Point.position))
926 return &*Sym.Definition;
927 return nullptr;
928}
929
Sam McCall2c30fbc2018-10-18 12:32:04 +0000930void ClangdLSPServer::onGoToDefinition(const TextDocumentPositionParams &Params,
931 Callback<std::vector<Location>> Reply) {
Sam McCall866ba2c2019-02-01 11:26:13 +0000932 Server->locateSymbolAt(
933 Params.textDocument.uri.file(), Params.position,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000934 [Params, Reply = std::move(Reply)](
935 llvm::Expected<std::vector<LocatedSymbol>> Symbols) mutable {
936 if (!Symbols)
937 return Reply(Symbols.takeError());
938 std::vector<Location> Defs;
939 for (auto &S : *Symbols) {
940 if (Location *Toggle = getToggle(Params, S))
941 return Reply(std::vector<Location>{std::move(*Toggle)});
942 Defs.push_back(S.Definition.getValueOr(S.PreferredDeclaration));
943 }
944 Reply(std::move(Defs));
945 });
Sam McCall866ba2c2019-02-01 11:26:13 +0000946}
947
948void ClangdLSPServer::onGoToDeclaration(
949 const TextDocumentPositionParams &Params,
950 Callback<std::vector<Location>> Reply) {
951 Server->locateSymbolAt(
952 Params.textDocument.uri.file(), Params.position,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000953 [Params, Reply = std::move(Reply)](
954 llvm::Expected<std::vector<LocatedSymbol>> Symbols) mutable {
955 if (!Symbols)
956 return Reply(Symbols.takeError());
957 std::vector<Location> Decls;
958 for (auto &S : *Symbols) {
959 if (Location *Toggle = getToggle(Params, S))
960 return Reply(std::vector<Location>{std::move(*Toggle)});
961 Decls.push_back(std::move(S.PreferredDeclaration));
962 }
963 Reply(std::move(Decls));
964 });
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000965}
966
Sam McCall111fe842019-05-07 07:55:35 +0000967void ClangdLSPServer::onSwitchSourceHeader(
968 const TextDocumentIdentifier &Params,
Sam McCallb9ec3e92019-05-07 08:30:32 +0000969 Callback<llvm::Optional<URIForFile>> Reply) {
Sam McCall111fe842019-05-07 07:55:35 +0000970 if (auto Result = Server->switchSourceHeader(Params.uri.file()))
Sam McCallb9ec3e92019-05-07 08:30:32 +0000971 Reply(URIForFile::canonicalize(*Result, Params.uri.file()));
Sam McCall111fe842019-05-07 07:55:35 +0000972 else
973 Reply(llvm::None);
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000974}
975
Sam McCall2c30fbc2018-10-18 12:32:04 +0000976void ClangdLSPServer::onDocumentHighlight(
977 const TextDocumentPositionParams &Params,
978 Callback<std::vector<DocumentHighlight>> Reply) {
979 Server->findDocumentHighlights(Params.textDocument.uri.file(),
980 Params.position, std::move(Reply));
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000981}
982
Sam McCall2c30fbc2018-10-18 12:32:04 +0000983void ClangdLSPServer::onHover(const TextDocumentPositionParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000984 Callback<llvm::Optional<Hover>> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000985 Server->findHover(Params.textDocument.uri.file(), Params.position,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000986 [Reply = std::move(Reply), this](
987 llvm::Expected<llvm::Optional<HoverInfo>> H) mutable {
988 if (!H)
989 return Reply(H.takeError());
990 if (!*H)
991 return Reply(llvm::None);
Ilya Biryukovf9169d02019-05-29 10:01:00 +0000992
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000993 Hover R;
994 R.contents.kind = HoverContentFormat;
995 R.range = (*H)->SymRange;
996 switch (HoverContentFormat) {
997 case MarkupKind::PlainText:
998 R.contents.value = (*H)->present().renderAsPlainText();
999 return Reply(std::move(R));
1000 case MarkupKind::Markdown:
1001 R.contents.value = (*H)->present().renderAsMarkdown();
1002 return Reply(std::move(R));
1003 };
1004 llvm_unreachable("unhandled MarkupKind");
1005 });
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +00001006}
1007
Kadir Cetinkaya86658022019-03-19 09:27:04 +00001008void ClangdLSPServer::onTypeHierarchy(
1009 const TypeHierarchyParams &Params,
1010 Callback<Optional<TypeHierarchyItem>> Reply) {
1011 Server->typeHierarchy(Params.textDocument.uri.file(), Params.position,
1012 Params.resolve, Params.direction, std::move(Reply));
1013}
1014
Nathan Ridge087b0442019-07-13 03:24:48 +00001015void ClangdLSPServer::onResolveTypeHierarchy(
1016 const ResolveTypeHierarchyItemParams &Params,
1017 Callback<Optional<TypeHierarchyItem>> Reply) {
1018 Server->resolveTypeHierarchy(Params.item, Params.resolve, Params.direction,
1019 std::move(Reply));
1020}
1021
Simon Marchi88016782018-08-01 11:28:49 +00001022void ClangdLSPServer::applyConfiguration(
Sam McCallbc904612018-10-25 04:22:52 +00001023 const ConfigurationSettings &Settings) {
Simon Marchiabeed662018-10-16 15:55:03 +00001024 // Per-file update to the compilation database.
Sam McCallbc904612018-10-25 04:22:52 +00001025 bool ShouldReparseOpenFiles = false;
1026 for (auto &Entry : Settings.compilationDatabaseChanges) {
1027 /// The opened files need to be reparsed only when some existing
1028 /// entries are changed.
1029 PathRef File = Entry.first;
Sam McCallc55d09a2018-11-02 13:09:36 +00001030 auto Old = CDB->getCompileCommand(File);
1031 auto New =
1032 tooling::CompileCommand(std::move(Entry.second.workingDirectory), File,
1033 std::move(Entry.second.compilationCommand),
1034 /*Output=*/"");
Sam McCall6980edb2018-11-02 14:07:51 +00001035 if (Old != New) {
Sam McCallc55d09a2018-11-02 13:09:36 +00001036 CDB->setCompileCommand(File, std::move(New));
Sam McCall6980edb2018-11-02 14:07:51 +00001037 ShouldReparseOpenFiles = true;
1038 }
Alex Lorenzf8087862018-08-01 17:39:29 +00001039 }
Sam McCallbc904612018-10-25 04:22:52 +00001040 if (ShouldReparseOpenFiles)
1041 reparseOpenedFiles();
Simon Marchi5178f922018-02-22 14:00:39 +00001042}
1043
Johan Vikstroma848dab2019-07-04 07:53:12 +00001044void ClangdLSPServer::publishSemanticHighlighting(
1045 SemanticHighlightingParams Params) {
1046 notify("textDocument/semanticHighlighting", Params);
1047}
1048
Ilya Biryukov49c10712019-03-25 10:15:11 +00001049void ClangdLSPServer::publishDiagnostics(
1050 const URIForFile &File, std::vector<clangd::Diagnostic> Diagnostics) {
1051 // Publish diagnostics.
1052 notify("textDocument/publishDiagnostics",
1053 llvm::json::Object{
1054 {"uri", File},
1055 {"diagnostics", std::move(Diagnostics)},
1056 });
1057}
1058
Simon Marchi88016782018-08-01 11:28:49 +00001059// FIXME: This function needs to be properly tested.
1060void ClangdLSPServer::onChangeConfiguration(
Sam McCall2c30fbc2018-10-18 12:32:04 +00001061 const DidChangeConfigurationParams &Params) {
Simon Marchi88016782018-08-01 11:28:49 +00001062 applyConfiguration(Params.settings);
1063}
1064
Sam McCall2c30fbc2018-10-18 12:32:04 +00001065void ClangdLSPServer::onReference(const ReferenceParams &Params,
1066 Callback<std::vector<Location>> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +00001067 Server->findReferences(Params.textDocument.uri.file(), Params.position,
Haojian Wuc34f0222019-01-14 18:11:09 +00001068 CCOpts.Limit, std::move(Reply));
Sam McCall1ad142f2018-09-05 11:53:07 +00001069}
1070
Jan Korousb4067012018-11-27 16:40:46 +00001071void ClangdLSPServer::onSymbolInfo(const TextDocumentPositionParams &Params,
1072 Callback<std::vector<SymbolDetails>> Reply) {
1073 Server->symbolInfo(Params.textDocument.uri.file(), Params.position,
1074 std::move(Reply));
1075}
1076
Sam McCalla69698f2019-03-27 17:47:49 +00001077ClangdLSPServer::ClangdLSPServer(
1078 class Transport &Transp, const FileSystemProvider &FSProvider,
1079 const clangd::CodeCompleteOptions &CCOpts,
1080 llvm::Optional<Path> CompileCommandsDir, bool UseDirBasedCDB,
1081 llvm::Optional<OffsetEncoding> ForcedOffsetEncoding,
1082 const ClangdServer::Options &Opts)
Haojian Wu1ca0c582019-01-22 09:39:05 +00001083 : Transp(Transp), MsgHandler(new MessageHandler(*this)),
1084 FSProvider(FSProvider), CCOpts(CCOpts),
Sam McCalld1c9d112018-10-23 14:19:54 +00001085 SupportedSymbolKinds(defaultSymbolKinds()),
Kadir Cetinkaya133d46f2018-09-27 17:13:07 +00001086 SupportedCompletionItemKinds(defaultCompletionItemKinds()),
Sam McCallc55d09a2018-11-02 13:09:36 +00001087 UseDirBasedCDB(UseDirBasedCDB),
Sam McCalla69698f2019-03-27 17:47:49 +00001088 CompileCommandsDir(std::move(CompileCommandsDir)), ClangdServerOpts(Opts),
1089 NegotiatedOffsetEncoding(ForcedOffsetEncoding) {
Sam McCall2c30fbc2018-10-18 12:32:04 +00001090 // clang-format off
1091 MsgHandler->bind("initialize", &ClangdLSPServer::onInitialize);
1092 MsgHandler->bind("shutdown", &ClangdLSPServer::onShutdown);
Sam McCall422c8282018-11-26 16:00:11 +00001093 MsgHandler->bind("sync", &ClangdLSPServer::onSync);
Sam McCall2c30fbc2018-10-18 12:32:04 +00001094 MsgHandler->bind("textDocument/rangeFormatting", &ClangdLSPServer::onDocumentRangeFormatting);
1095 MsgHandler->bind("textDocument/onTypeFormatting", &ClangdLSPServer::onDocumentOnTypeFormatting);
1096 MsgHandler->bind("textDocument/formatting", &ClangdLSPServer::onDocumentFormatting);
1097 MsgHandler->bind("textDocument/codeAction", &ClangdLSPServer::onCodeAction);
1098 MsgHandler->bind("textDocument/completion", &ClangdLSPServer::onCompletion);
1099 MsgHandler->bind("textDocument/signatureHelp", &ClangdLSPServer::onSignatureHelp);
1100 MsgHandler->bind("textDocument/definition", &ClangdLSPServer::onGoToDefinition);
Sam McCall866ba2c2019-02-01 11:26:13 +00001101 MsgHandler->bind("textDocument/declaration", &ClangdLSPServer::onGoToDeclaration);
Sam McCall2c30fbc2018-10-18 12:32:04 +00001102 MsgHandler->bind("textDocument/references", &ClangdLSPServer::onReference);
1103 MsgHandler->bind("textDocument/switchSourceHeader", &ClangdLSPServer::onSwitchSourceHeader);
Haojian Wuf429ab62019-07-24 07:49:23 +00001104 MsgHandler->bind("textDocument/prepareRename", &ClangdLSPServer::onPrepareRename);
Sam McCall2c30fbc2018-10-18 12:32:04 +00001105 MsgHandler->bind("textDocument/rename", &ClangdLSPServer::onRename);
1106 MsgHandler->bind("textDocument/hover", &ClangdLSPServer::onHover);
1107 MsgHandler->bind("textDocument/documentSymbol", &ClangdLSPServer::onDocumentSymbol);
1108 MsgHandler->bind("workspace/executeCommand", &ClangdLSPServer::onCommand);
1109 MsgHandler->bind("textDocument/documentHighlight", &ClangdLSPServer::onDocumentHighlight);
1110 MsgHandler->bind("workspace/symbol", &ClangdLSPServer::onWorkspaceSymbol);
1111 MsgHandler->bind("textDocument/didOpen", &ClangdLSPServer::onDocumentDidOpen);
1112 MsgHandler->bind("textDocument/didClose", &ClangdLSPServer::onDocumentDidClose);
1113 MsgHandler->bind("textDocument/didChange", &ClangdLSPServer::onDocumentDidChange);
1114 MsgHandler->bind("workspace/didChangeWatchedFiles", &ClangdLSPServer::onFileEvent);
1115 MsgHandler->bind("workspace/didChangeConfiguration", &ClangdLSPServer::onChangeConfiguration);
Jan Korousb4067012018-11-27 16:40:46 +00001116 MsgHandler->bind("textDocument/symbolInfo", &ClangdLSPServer::onSymbolInfo);
Kadir Cetinkaya86658022019-03-19 09:27:04 +00001117 MsgHandler->bind("textDocument/typeHierarchy", &ClangdLSPServer::onTypeHierarchy);
Nathan Ridge087b0442019-07-13 03:24:48 +00001118 MsgHandler->bind("typeHierarchy/resolve", &ClangdLSPServer::onResolveTypeHierarchy);
Sam McCall2c30fbc2018-10-18 12:32:04 +00001119 // clang-format on
1120}
1121
Haojian Wuf2516342019-08-05 12:48:09 +00001122ClangdLSPServer::~ClangdLSPServer() { IsBeingDestroyed = true; }
Ilya Biryukov38d79772017-05-16 09:38:59 +00001123
Sam McCalldc8f3cf2018-10-17 07:32:05 +00001124bool ClangdLSPServer::run() {
Ilya Biryukovafb55542017-05-16 14:40:30 +00001125 // Run the Language Server loop.
Sam McCalldc8f3cf2018-10-17 07:32:05 +00001126 bool CleanExit = true;
Sam McCall2c30fbc2018-10-18 12:32:04 +00001127 if (auto Err = Transp.loop(*MsgHandler)) {
Sam McCalldc8f3cf2018-10-17 07:32:05 +00001128 elog("Transport error: {0}", std::move(Err));
1129 CleanExit = false;
1130 }
Ilya Biryukovafb55542017-05-16 14:40:30 +00001131
Ilya Biryukov652364b2018-09-26 05:48:29 +00001132 // Destroy ClangdServer to ensure all worker threads finish.
1133 Server.reset();
Sam McCalldc8f3cf2018-10-17 07:32:05 +00001134 return CleanExit && ShutdownRequestReceived;
Ilya Biryukov38d79772017-05-16 09:38:59 +00001135}
1136
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001137std::vector<Fix> ClangdLSPServer::getFixes(llvm::StringRef File,
Ilya Biryukov71028b82018-03-12 15:28:22 +00001138 const clangd::Diagnostic &D) {
Ilya Biryukov38d79772017-05-16 09:38:59 +00001139 std::lock_guard<std::mutex> Lock(FixItsMutex);
1140 auto DiagToFixItsIter = FixItsMap.find(File);
1141 if (DiagToFixItsIter == FixItsMap.end())
1142 return {};
1143
1144 const auto &DiagToFixItsMap = DiagToFixItsIter->second;
1145 auto FixItsIter = DiagToFixItsMap.find(D);
1146 if (FixItsIter == DiagToFixItsMap.end())
1147 return {};
1148
1149 return FixItsIter->second;
1150}
1151
Ilya Biryukovb0826bd2019-01-03 13:37:12 +00001152bool ClangdLSPServer::shouldRunCompletion(
1153 const CompletionParams &Params) const {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001154 llvm::StringRef Trigger = Params.context.triggerCharacter;
Ilya Biryukovb0826bd2019-01-03 13:37:12 +00001155 if (Params.context.triggerKind != CompletionTriggerKind::TriggerCharacter ||
1156 (Trigger != ">" && Trigger != ":"))
1157 return true;
1158
1159 auto Code = DraftMgr.getDraft(Params.textDocument.uri.file());
1160 if (!Code)
1161 return true; // completion code will log the error for untracked doc.
1162
1163 // A completion request is sent when the user types '>' or ':', but we only
1164 // want to trigger on '->' and '::'. We check the preceeding character to make
1165 // sure it matches what we expected.
1166 // Running the lexer here would be more robust (e.g. we can detect comments
1167 // and avoid triggering completion there), but we choose to err on the side
1168 // of simplicity here.
1169 auto Offset = positionToOffset(*Code, Params.position,
1170 /*AllowColumnsBeyondLineLength=*/false);
1171 if (!Offset) {
1172 vlog("could not convert position '{0}' to offset for file '{1}'",
1173 Params.position, Params.textDocument.uri.file());
1174 return true;
1175 }
1176 if (*Offset < 2)
1177 return false;
1178
1179 if (Trigger == ">")
1180 return (*Code)[*Offset - 2] == '-'; // trigger only on '->'.
1181 if (Trigger == ":")
1182 return (*Code)[*Offset - 2] == ':'; // trigger only on '::'.
1183 assert(false && "unhandled trigger character");
1184 return true;
1185}
1186
Johan Vikstroma848dab2019-07-04 07:53:12 +00001187void ClangdLSPServer::onHighlightingsReady(
Johan Vikstromc2653ef22019-08-01 08:08:44 +00001188 PathRef File, std::vector<HighlightingToken> Highlightings, int NumLines) {
1189 std::vector<HighlightingToken> Old;
1190 std::vector<HighlightingToken> HighlightingsCopy = Highlightings;
1191 {
1192 std::lock_guard<std::mutex> Lock(HighlightingsMutex);
1193 Old = std::move(FileToHighlightings[File]);
1194 FileToHighlightings[File] = std::move(HighlightingsCopy);
1195 }
1196 // LSP allows us to send incremental edits of highlightings. Also need to diff
1197 // to remove highlightings from tokens that should no longer have them.
1198 std::vector<LineHighlightings> Diffed =
1199 diffHighlightings(Highlightings, Old, NumLines);
Johan Vikstroma848dab2019-07-04 07:53:12 +00001200 publishSemanticHighlighting(
1201 {{URIForFile::canonicalize(File, /*TUPath=*/File)},
Johan Vikstromc2653ef22019-08-01 08:08:44 +00001202 toSemanticHighlightingInformation(Diffed)});
Johan Vikstroma848dab2019-07-04 07:53:12 +00001203}
1204
Sam McCalla7bb0cc2018-03-12 23:22:35 +00001205void ClangdLSPServer::onDiagnosticsReady(PathRef File,
1206 std::vector<Diag> Diagnostics) {
Eric Liu4d814a92018-11-28 10:30:42 +00001207 auto URI = URIForFile::canonicalize(File, /*TUPath=*/File);
Sam McCall16e70702018-10-24 07:59:38 +00001208 std::vector<Diagnostic> LSPDiagnostics;
Ilya Biryukov38d79772017-05-16 09:38:59 +00001209 DiagnosticToReplacementMap LocalFixIts; // Temporary storage
Sam McCalla7bb0cc2018-03-12 23:22:35 +00001210 for (auto &Diag : Diagnostics) {
Sam McCall16e70702018-10-24 07:59:38 +00001211 toLSPDiags(Diag, URI, DiagOpts,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001212 [&](clangd::Diagnostic Diag, llvm::ArrayRef<Fix> Fixes) {
Sam McCall16e70702018-10-24 07:59:38 +00001213 auto &FixItsForDiagnostic = LocalFixIts[Diag];
1214 llvm::copy(Fixes, std::back_inserter(FixItsForDiagnostic));
1215 LSPDiagnostics.push_back(std::move(Diag));
1216 });
Ilya Biryukov38d79772017-05-16 09:38:59 +00001217 }
1218
1219 // Cache FixIts
1220 {
Ilya Biryukov38d79772017-05-16 09:38:59 +00001221 std::lock_guard<std::mutex> Lock(FixItsMutex);
1222 FixItsMap[File] = LocalFixIts;
1223 }
1224
Ilya Biryukov49c10712019-03-25 10:15:11 +00001225 // Send a notification to the LSP client.
1226 publishDiagnostics(URI, std::move(LSPDiagnostics));
Ilya Biryukov38d79772017-05-16 09:38:59 +00001227}
Simon Marchi9569fd52018-03-16 14:30:42 +00001228
Haojian Wub6188492018-12-20 15:39:12 +00001229void ClangdLSPServer::onFileUpdated(PathRef File, const TUStatus &Status) {
1230 if (!SupportFileStatus)
1231 return;
1232 // FIXME: we don't emit "BuildingFile" and `RunningAction`, as these
1233 // two statuses are running faster in practice, which leads the UI constantly
1234 // changing, and doesn't provide much value. We may want to emit status at a
1235 // reasonable time interval (e.g. 0.5s).
1236 if (Status.Action.S == TUAction::BuildingFile ||
1237 Status.Action.S == TUAction::RunningAction)
1238 return;
1239 notify("textDocument/clangd.fileStatus", Status.render(File));
1240}
1241
Simon Marchi9569fd52018-03-16 14:30:42 +00001242void ClangdLSPServer::reparseOpenedFiles() {
1243 for (const Path &FilePath : DraftMgr.getActiveFiles())
Ilya Biryukov652364b2018-09-26 05:48:29 +00001244 Server->addDocument(FilePath, *DraftMgr.getDraft(FilePath),
1245 WantDiagnostics::Auto);
Simon Marchi9569fd52018-03-16 14:30:42 +00001246}
Alex Lorenzf8087862018-08-01 17:39:29 +00001247
Sam McCallc008af62018-10-20 15:30:37 +00001248} // namespace clangd
1249} // namespace clang