blob: 928bd250d21eeac9139881f2ec0fb53e80bf9117 [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
Haojian Wu08d93f12019-08-22 14:53:45 +0000467 // Per LSP, codeActionProvide can be either boolean or CodeActionOptions.
468 // CodeActionOptions is only valid if the client supports action literal
469 // via textDocument.codeAction.codeActionLiteralSupport.
470 llvm::json::Value CodeActionProvider = true;
471 if (Params.capabilities.CodeActionStructure)
472 CodeActionProvider = llvm::json::Object{
473 {"codeActionKinds",
474 {CodeAction::QUICKFIX_KIND, CodeAction::REFACTOR_KIND,
475 CodeAction::INFO_KIND}}};
476
Sam McCalla69698f2019-03-27 17:47:49 +0000477 llvm::json::Object Result{
Sam McCall0930ab02017-11-07 15:49:35 +0000478 {{"capabilities",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000479 llvm::json::Object{
Simon Marchi98082622018-03-26 14:41:40 +0000480 {"textDocumentSync", (int)TextDocumentSyncKind::Incremental},
Sam McCall0930ab02017-11-07 15:49:35 +0000481 {"documentFormattingProvider", true},
482 {"documentRangeFormattingProvider", true},
483 {"documentOnTypeFormattingProvider",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000484 llvm::json::Object{
Sam McCall25c62572019-06-10 14:26:21 +0000485 {"firstTriggerCharacter", "\n"},
Sam McCall0930ab02017-11-07 15:49:35 +0000486 {"moreTriggerCharacter", {}},
487 }},
Haojian Wu08d93f12019-08-22 14:53:45 +0000488 {"codeActionProvider", std::move(CodeActionProvider)},
Sam McCall0930ab02017-11-07 15:49:35 +0000489 {"completionProvider",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000490 llvm::json::Object{
Sam McCall0930ab02017-11-07 15:49:35 +0000491 {"resolveProvider", false},
Ilya Biryukovb0826bd2019-01-03 13:37:12 +0000492 // We do extra checks for '>' and ':' in completion to only
493 // trigger on '->' and '::'.
Sam McCall0930ab02017-11-07 15:49:35 +0000494 {"triggerCharacters", {".", ">", ":"}},
495 }},
496 {"signatureHelpProvider",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000497 llvm::json::Object{
Sam McCall0930ab02017-11-07 15:49:35 +0000498 {"triggerCharacters", {"(", ","}},
499 }},
Sam McCall866ba2c2019-02-01 11:26:13 +0000500 {"declarationProvider", true},
Sam McCall0930ab02017-11-07 15:49:35 +0000501 {"definitionProvider", true},
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000502 {"documentHighlightProvider", true},
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000503 {"hoverProvider", true},
Haojian Wuf429ab62019-07-24 07:49:23 +0000504 {"renameProvider", std::move(RenameProvider)},
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000505 {"documentSymbolProvider", true},
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000506 {"workspaceSymbolProvider", true},
Sam McCall1ad142f2018-09-05 11:53:07 +0000507 {"referencesProvider", true},
Sam McCall0930ab02017-11-07 15:49:35 +0000508 {"executeCommandProvider",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000509 llvm::json::Object{
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000510 {"commands",
511 {ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND,
512 ExecuteCommandParams::CLANGD_APPLY_TWEAK}},
Sam McCall0930ab02017-11-07 15:49:35 +0000513 }},
Kadir Cetinkaya86658022019-03-19 09:27:04 +0000514 {"typeHierarchyProvider", true},
Sam McCalla69698f2019-03-27 17:47:49 +0000515 }}}};
516 if (NegotiatedOffsetEncoding)
517 Result["offsetEncoding"] = *NegotiatedOffsetEncoding;
Johan Vikstroma848dab2019-07-04 07:53:12 +0000518 if (Params.capabilities.SemanticHighlighting)
519 Result.getObject("capabilities")
520 ->insert(
521 {"semanticHighlighting",
Haojian Wu1ca2ee42019-07-04 12:27:21 +0000522 llvm::json::Object{{"scopes", buildHighlightScopeLookupTable()}}});
Sam McCalla69698f2019-03-27 17:47:49 +0000523 Reply(std::move(Result));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000524}
525
Sam McCall2c30fbc2018-10-18 12:32:04 +0000526void ClangdLSPServer::onShutdown(const ShutdownParams &Params,
527 Callback<std::nullptr_t> Reply) {
Ilya Biryukov0d9b8a32017-10-25 08:45:41 +0000528 // Do essentially nothing, just say we're ready to exit.
529 ShutdownRequestReceived = true;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000530 Reply(nullptr);
Sam McCall8a5dded2017-10-12 13:29:58 +0000531}
Ilya Biryukovafb55542017-05-16 14:40:30 +0000532
Sam McCall422c8282018-11-26 16:00:11 +0000533// sync is a clangd extension: it blocks until all background work completes.
534// It blocks the calling thread, so no messages are processed until it returns!
535void ClangdLSPServer::onSync(const NoParams &Params,
536 Callback<std::nullptr_t> Reply) {
537 if (Server->blockUntilIdleForTest(/*TimeoutSeconds=*/60))
538 Reply(nullptr);
539 else
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000540 Reply(llvm::createStringError(llvm::inconvertibleErrorCode(),
541 "Not idle after a minute"));
Sam McCall422c8282018-11-26 16:00:11 +0000542}
543
Sam McCall2c30fbc2018-10-18 12:32:04 +0000544void ClangdLSPServer::onDocumentDidOpen(
545 const DidOpenTextDocumentParams &Params) {
Simon Marchi9569fd52018-03-16 14:30:42 +0000546 PathRef File = Params.textDocument.uri.file();
Ilya Biryukovb10ef472018-06-13 09:20:41 +0000547
Sam McCall2c30fbc2018-10-18 12:32:04 +0000548 const std::string &Contents = Params.textDocument.text;
Simon Marchi9569fd52018-03-16 14:30:42 +0000549
Simon Marchi98082622018-03-26 14:41:40 +0000550 DraftMgr.addDraft(File, Contents);
Ilya Biryukov652364b2018-09-26 05:48:29 +0000551 Server->addDocument(File, Contents, WantDiagnostics::Yes);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000552}
553
Sam McCall2c30fbc2018-10-18 12:32:04 +0000554void ClangdLSPServer::onDocumentDidChange(
555 const DidChangeTextDocumentParams &Params) {
Eric Liu51fed182018-02-22 18:40:39 +0000556 auto WantDiags = WantDiagnostics::Auto;
557 if (Params.wantDiagnostics.hasValue())
558 WantDiags = Params.wantDiagnostics.getValue() ? WantDiagnostics::Yes
559 : WantDiagnostics::No;
Simon Marchi9569fd52018-03-16 14:30:42 +0000560
561 PathRef File = Params.textDocument.uri.file();
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000562 llvm::Expected<std::string> Contents =
Simon Marchi98082622018-03-26 14:41:40 +0000563 DraftMgr.updateDraft(File, Params.contentChanges);
564 if (!Contents) {
565 // If this fails, we are most likely going to be not in sync anymore with
566 // the client. It is better to remove the draft and let further operations
567 // fail rather than giving wrong results.
568 DraftMgr.removeDraft(File);
Ilya Biryukov652364b2018-09-26 05:48:29 +0000569 Server->removeDocument(File);
Sam McCallbed58852018-07-11 10:35:11 +0000570 elog("Failed to update {0}: {1}", File, Contents.takeError());
Simon Marchi98082622018-03-26 14:41:40 +0000571 return;
572 }
Simon Marchi9569fd52018-03-16 14:30:42 +0000573
Ilya Biryukov652364b2018-09-26 05:48:29 +0000574 Server->addDocument(File, *Contents, WantDiags);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000575}
576
Sam McCall2c30fbc2018-10-18 12:32:04 +0000577void ClangdLSPServer::onFileEvent(const DidChangeWatchedFilesParams &Params) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000578 Server->onFileEvent(Params);
Marc-Andre Laperlebf114242017-10-02 18:00:37 +0000579}
580
Sam McCall2c30fbc2018-10-18 12:32:04 +0000581void ClangdLSPServer::onCommand(const ExecuteCommandParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000582 Callback<llvm::json::Value> Reply) {
Ilya Biryukov12864002019-08-16 12:46:41 +0000583 auto ApplyEdit = [this](WorkspaceEdit WE, std::string SuccessMessage,
584 decltype(Reply) Reply) {
Eric Liuc5105f92018-02-16 14:15:55 +0000585 ApplyWorkspaceEditParams Edit;
586 Edit.edit = std::move(WE);
Ilya Biryukov12864002019-08-16 12:46:41 +0000587 call<ApplyWorkspaceEditResponse>(
588 "workspace/applyEdit", std::move(Edit),
589 [Reply = std::move(Reply), SuccessMessage = std::move(SuccessMessage)](
590 llvm::Expected<ApplyWorkspaceEditResponse> Response) mutable {
591 if (!Response)
592 return Reply(Response.takeError());
593 if (!Response->applied) {
594 std::string Reason = Response->failureReason
595 ? *Response->failureReason
596 : "unknown reason";
597 return Reply(llvm::createStringError(
598 llvm::inconvertibleErrorCode(),
599 ("edits were not applied: " + Reason).c_str()));
600 }
601 return Reply(SuccessMessage);
602 });
Eric Liuc5105f92018-02-16 14:15:55 +0000603 };
Ilya Biryukov12864002019-08-16 12:46:41 +0000604
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000605 if (Params.command == ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND &&
606 Params.workspaceEdit) {
607 // The flow for "apply-fix" :
608 // 1. We publish a diagnostic, including fixits
609 // 2. The user clicks on the diagnostic, the editor asks us for code actions
610 // 3. We send code actions, with the fixit embedded as context
611 // 4. The user selects the fixit, the editor asks us to apply it
612 // 5. We unwrap the changes and send them back to the editor
Haojian Wuf2516342019-08-05 12:48:09 +0000613 // 6. The editor applies the changes (applyEdit), and sends us a reply
614 // 7. We unwrap the reply and send a reply to the editor.
Ilya Biryukov12864002019-08-16 12:46:41 +0000615 ApplyEdit(*Params.workspaceEdit, "Fix applied.", std::move(Reply));
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000616 } else if (Params.command == ExecuteCommandParams::CLANGD_APPLY_TWEAK &&
617 Params.tweakArgs) {
618 auto Code = DraftMgr.getDraft(Params.tweakArgs->file.file());
619 if (!Code)
620 return Reply(llvm::createStringError(
621 llvm::inconvertibleErrorCode(),
622 "trying to apply a code action for a non-added file"));
623
Ilya Biryukov12864002019-08-16 12:46:41 +0000624 auto Action = [this, ApplyEdit, Reply = std::move(Reply),
625 File = Params.tweakArgs->file, Code = std::move(*Code)](
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000626 llvm::Expected<Tweak::Effect> R) mutable {
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000627 if (!R)
628 return Reply(R.takeError());
629
Haojian Wu427762f2019-08-16 13:20:51 +0000630 assert(R->ShowMessage || (R->ApplyEdit && "tweak has no effect"));
Ilya Biryukov12864002019-08-16 12:46:41 +0000631
Sam McCall395fde72019-06-18 13:37:54 +0000632 if (R->ShowMessage) {
633 ShowMessageParams Msg;
634 Msg.message = *R->ShowMessage;
635 Msg.type = MessageType::Info;
636 notify("window/showMessage", Msg);
637 }
Ilya Biryukov12864002019-08-16 12:46:41 +0000638 if (R->ApplyEdit) {
639 WorkspaceEdit WE;
640 WE.changes.emplace();
641 (*WE.changes)[File.uri()] = replacementsToEdits(Code, *R->ApplyEdit);
642 // ApplyEdit will take care of calling Reply().
643 return ApplyEdit(std::move(WE), "Tweak applied.", std::move(Reply));
644 }
645 // When no edit is specified, make sure we Reply().
646 return Reply("Tweak applied.");
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000647 };
648 Server->applyTweak(Params.tweakArgs->file.file(),
649 Params.tweakArgs->selection, Params.tweakArgs->tweakID,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000650 std::move(Action));
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000651 } else {
652 // We should not get here because ExecuteCommandParams would not have
653 // parsed in the first place and this handler should not be called. But if
654 // more commands are added, this will be here has a safe guard.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000655 Reply(llvm::make_error<LSPError>(
656 llvm::formatv("Unsupported command \"{0}\".", Params.command).str(),
Sam McCall2c30fbc2018-10-18 12:32:04 +0000657 ErrorCode::InvalidParams));
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000658 }
659}
660
Sam McCall2c30fbc2018-10-18 12:32:04 +0000661void ClangdLSPServer::onWorkspaceSymbol(
662 const WorkspaceSymbolParams &Params,
663 Callback<std::vector<SymbolInformation>> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000664 Server->workspaceSymbols(
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000665 Params.query, CCOpts.Limit,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000666 [Reply = std::move(Reply),
667 this](llvm::Expected<std::vector<SymbolInformation>> Items) mutable {
668 if (!Items)
669 return Reply(Items.takeError());
670 for (auto &Sym : *Items)
671 Sym.kind = adjustKindToCapability(Sym.kind, SupportedSymbolKinds);
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000672
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000673 Reply(std::move(*Items));
674 });
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000675}
676
Haojian Wuf429ab62019-07-24 07:49:23 +0000677void ClangdLSPServer::onPrepareRename(const TextDocumentPositionParams &Params,
678 Callback<llvm::Optional<Range>> Reply) {
679 Server->prepareRename(Params.textDocument.uri.file(), Params.position,
680 std::move(Reply));
681}
682
Sam McCall2c30fbc2018-10-18 12:32:04 +0000683void ClangdLSPServer::onRename(const RenameParams &Params,
684 Callback<WorkspaceEdit> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000685 Path File = Params.textDocument.uri.file();
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000686 llvm::Optional<std::string> Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000687 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000688 return Reply(llvm::make_error<LSPError>(
689 "onRename called for non-added file", ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000690
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000691 Server->rename(File, Params.position, Params.newName, /*WantFormat=*/true,
692 [File, Code, Params, Reply = std::move(Reply)](
693 llvm::Expected<std::vector<TextEdit>> Edits) mutable {
694 if (!Edits)
695 return Reply(Edits.takeError());
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000696
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000697 WorkspaceEdit WE;
698 WE.changes = {{Params.textDocument.uri.uri(), *Edits}};
699 Reply(WE);
700 });
Haojian Wu345099c2017-11-09 11:30:04 +0000701}
702
Sam McCall2c30fbc2018-10-18 12:32:04 +0000703void ClangdLSPServer::onDocumentDidClose(
704 const DidCloseTextDocumentParams &Params) {
Simon Marchi9569fd52018-03-16 14:30:42 +0000705 PathRef File = Params.textDocument.uri.file();
706 DraftMgr.removeDraft(File);
Ilya Biryukov652364b2018-09-26 05:48:29 +0000707 Server->removeDocument(File);
Ilya Biryukov49c10712019-03-25 10:15:11 +0000708
709 {
710 std::lock_guard<std::mutex> Lock(FixItsMutex);
711 FixItsMap.erase(File);
712 }
Johan Vikstromc2653ef22019-08-01 08:08:44 +0000713 {
714 std::lock_guard<std::mutex> HLock(HighlightingsMutex);
715 FileToHighlightings.erase(File);
716 }
Ilya Biryukov49c10712019-03-25 10:15:11 +0000717 // clangd will not send updates for this file anymore, so we empty out the
718 // list of diagnostics shown on the client (e.g. in the "Problems" pane of
719 // VSCode). Note that this cannot race with actual diagnostics responses
720 // because removeDocument() guarantees no diagnostic callbacks will be
721 // executed after it returns.
722 publishDiagnostics(URIForFile::canonicalize(File, /*TUPath=*/File), {});
Ilya Biryukovafb55542017-05-16 14:40:30 +0000723}
724
Sam McCall4db732a2017-09-30 10:08:52 +0000725void ClangdLSPServer::onDocumentOnTypeFormatting(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000726 const DocumentOnTypeFormattingParams &Params,
727 Callback<std::vector<TextEdit>> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000728 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000729 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000730 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000731 return Reply(llvm::make_error<LSPError>(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000732 "onDocumentOnTypeFormatting called for non-added file",
733 ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000734
Sam McCall25c62572019-06-10 14:26:21 +0000735 Reply(Server->formatOnType(*Code, File, Params.position, Params.ch));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000736}
737
Sam McCall4db732a2017-09-30 10:08:52 +0000738void ClangdLSPServer::onDocumentRangeFormatting(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000739 const DocumentRangeFormattingParams &Params,
740 Callback<std::vector<TextEdit>> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000741 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000742 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000743 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000744 return Reply(llvm::make_error<LSPError>(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000745 "onDocumentRangeFormatting called for non-added file",
746 ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000747
Ilya Biryukov652364b2018-09-26 05:48:29 +0000748 auto ReplacementsOrError = Server->formatRange(*Code, File, Params.range);
Raoul Wols212bcf82017-12-12 20:25:06 +0000749 if (ReplacementsOrError)
Sam McCall2c30fbc2018-10-18 12:32:04 +0000750 Reply(replacementsToEdits(*Code, ReplacementsOrError.get()));
Raoul Wols212bcf82017-12-12 20:25:06 +0000751 else
Sam McCall2c30fbc2018-10-18 12:32:04 +0000752 Reply(ReplacementsOrError.takeError());
Ilya Biryukovafb55542017-05-16 14:40:30 +0000753}
754
Sam McCall2c30fbc2018-10-18 12:32:04 +0000755void ClangdLSPServer::onDocumentFormatting(
756 const DocumentFormattingParams &Params,
757 Callback<std::vector<TextEdit>> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000758 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000759 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000760 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000761 return Reply(llvm::make_error<LSPError>(
762 "onDocumentFormatting called for non-added file",
763 ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000764
Ilya Biryukov652364b2018-09-26 05:48:29 +0000765 auto ReplacementsOrError = Server->formatFile(*Code, File);
Raoul Wols212bcf82017-12-12 20:25:06 +0000766 if (ReplacementsOrError)
Sam McCall2c30fbc2018-10-18 12:32:04 +0000767 Reply(replacementsToEdits(*Code, ReplacementsOrError.get()));
Raoul Wols212bcf82017-12-12 20:25:06 +0000768 else
Sam McCall2c30fbc2018-10-18 12:32:04 +0000769 Reply(ReplacementsOrError.takeError());
Sam McCall4db732a2017-09-30 10:08:52 +0000770}
771
Ilya Biryukov19d75602018-11-23 15:21:19 +0000772/// The functions constructs a flattened view of the DocumentSymbol hierarchy.
773/// Used by the clients that do not support the hierarchical view.
774static std::vector<SymbolInformation>
775flattenSymbolHierarchy(llvm::ArrayRef<DocumentSymbol> Symbols,
776 const URIForFile &FileURI) {
777
778 std::vector<SymbolInformation> Results;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000779 std::function<void(const DocumentSymbol &, llvm::StringRef)> Process =
780 [&](const DocumentSymbol &S, llvm::Optional<llvm::StringRef> ParentName) {
Ilya Biryukov19d75602018-11-23 15:21:19 +0000781 SymbolInformation SI;
782 SI.containerName = ParentName ? "" : *ParentName;
783 SI.name = S.name;
784 SI.kind = S.kind;
785 SI.location.range = S.range;
786 SI.location.uri = FileURI;
787
788 Results.push_back(std::move(SI));
789 std::string FullName =
790 !ParentName ? S.name : (ParentName->str() + "::" + S.name);
791 for (auto &C : S.children)
792 Process(C, /*ParentName=*/FullName);
793 };
794 for (auto &S : Symbols)
795 Process(S, /*ParentName=*/"");
796 return Results;
797}
798
799void ClangdLSPServer::onDocumentSymbol(const DocumentSymbolParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000800 Callback<llvm::json::Value> Reply) {
Ilya Biryukov19d75602018-11-23 15:21:19 +0000801 URIForFile FileURI = Params.textDocument.uri;
Ilya Biryukov652364b2018-09-26 05:48:29 +0000802 Server->documentSymbols(
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000803 Params.textDocument.uri.file(),
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000804 [this, FileURI, Reply = std::move(Reply)](
805 llvm::Expected<std::vector<DocumentSymbol>> Items) mutable {
806 if (!Items)
807 return Reply(Items.takeError());
808 adjustSymbolKinds(*Items, SupportedSymbolKinds);
809 if (SupportsHierarchicalDocumentSymbol)
810 return Reply(std::move(*Items));
811 else
812 return Reply(flattenSymbolHierarchy(*Items, FileURI));
813 });
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000814}
815
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000816static llvm::Optional<Command> asCommand(const CodeAction &Action) {
Sam McCall20841d42018-10-16 16:29:41 +0000817 Command Cmd;
818 if (Action.command && Action.edit)
Sam McCallc008af62018-10-20 15:30:37 +0000819 return None; // Not representable. (We never emit these anyway).
Sam McCall20841d42018-10-16 16:29:41 +0000820 if (Action.command) {
821 Cmd = *Action.command;
822 } else if (Action.edit) {
823 Cmd.command = Command::CLANGD_APPLY_FIX_COMMAND;
824 Cmd.workspaceEdit = *Action.edit;
825 } else {
Sam McCallc008af62018-10-20 15:30:37 +0000826 return None;
Sam McCall20841d42018-10-16 16:29:41 +0000827 }
828 Cmd.title = Action.title;
829 if (Action.kind && *Action.kind == CodeAction::QUICKFIX_KIND)
830 Cmd.title = "Apply fix: " + Cmd.title;
831 return Cmd;
832}
833
Sam McCall2c30fbc2018-10-18 12:32:04 +0000834void ClangdLSPServer::onCodeAction(const CodeActionParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000835 Callback<llvm::json::Value> Reply) {
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000836 URIForFile File = Params.textDocument.uri;
837 auto Code = DraftMgr.getDraft(File.file());
Sam McCall2c30fbc2018-10-18 12:32:04 +0000838 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000839 return Reply(llvm::make_error<LSPError>(
840 "onCodeAction called for non-added file", ErrorCode::InvalidParams));
Sam McCall20841d42018-10-16 16:29:41 +0000841 // We provide a code action for Fixes on the specified diagnostics.
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000842 std::vector<CodeAction> FixIts;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000843 for (const Diagnostic &D : Params.context.diagnostics) {
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000844 for (auto &F : getFixes(File.file(), D)) {
845 FixIts.push_back(toCodeAction(F, Params.textDocument.uri));
846 FixIts.back().diagnostics = {D};
Sam McCalldd0566b2017-11-06 15:40:30 +0000847 }
Ilya Biryukovafb55542017-05-16 14:40:30 +0000848 }
Sam McCall20841d42018-10-16 16:29:41 +0000849
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000850 // Now enumerate the semantic code actions.
851 auto ConsumeActions =
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000852 [Reply = std::move(Reply), File, Code = std::move(*Code),
853 Selection = Params.range, FixIts = std::move(FixIts), this](
854 llvm::Expected<std::vector<ClangdServer::TweakRef>> Tweaks) mutable {
Ilya Biryukovc6ed7782019-01-30 14:24:17 +0000855 if (!Tweaks)
856 return Reply(Tweaks.takeError());
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000857
858 std::vector<CodeAction> Actions = std::move(FixIts);
859 Actions.reserve(Actions.size() + Tweaks->size());
860 for (const auto &T : *Tweaks)
861 Actions.push_back(toCodeAction(T, File, Selection));
862
863 if (SupportsCodeAction)
864 return Reply(llvm::json::Array(Actions));
865 std::vector<Command> Commands;
866 for (const auto &Action : Actions) {
867 if (auto Command = asCommand(Action))
868 Commands.push_back(std::move(*Command));
869 }
870 return Reply(llvm::json::Array(Commands));
871 };
872
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000873 Server->enumerateTweaks(File.file(), Params.range, std::move(ConsumeActions));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000874}
875
Ilya Biryukovb0826bd2019-01-03 13:37:12 +0000876void ClangdLSPServer::onCompletion(const CompletionParams &Params,
Sam McCall2c30fbc2018-10-18 12:32:04 +0000877 Callback<CompletionList> Reply) {
Ilya Biryukova7a11472019-06-07 16:24:38 +0000878 if (!shouldRunCompletion(Params)) {
879 // Clients sometimes auto-trigger completions in undesired places (e.g.
880 // 'a >^ '), we return empty results in those cases.
881 vlog("ignored auto-triggered completion, preceding char did not match");
882 return Reply(CompletionList());
883 }
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000884 Server->codeComplete(Params.textDocument.uri.file(), Params.position, CCOpts,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000885 [Reply = std::move(Reply),
886 this](llvm::Expected<CodeCompleteResult> List) mutable {
887 if (!List)
888 return Reply(List.takeError());
889 CompletionList LSPList;
890 LSPList.isIncomplete = List->HasMore;
891 for (const auto &R : List->Completions) {
892 CompletionItem C = R.render(CCOpts);
893 C.kind = adjustKindToCapability(
894 C.kind, SupportedCompletionItemKinds);
895 LSPList.items.push_back(std::move(C));
896 }
897 return Reply(std::move(LSPList));
898 });
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000899}
900
Sam McCall2c30fbc2018-10-18 12:32:04 +0000901void ClangdLSPServer::onSignatureHelp(const TextDocumentPositionParams &Params,
902 Callback<SignatureHelp> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000903 Server->signatureHelp(Params.textDocument.uri.file(), Params.position,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000904 [Reply = std::move(Reply), this](
905 llvm::Expected<SignatureHelp> Signature) mutable {
906 if (!Signature)
907 return Reply(Signature.takeError());
908 if (SupportsOffsetsInSignatureHelp)
909 return Reply(std::move(*Signature));
910 // Strip out the offsets from signature help for
911 // clients that only support string labels.
912 for (auto &SigInfo : Signature->signatures) {
913 for (auto &Param : SigInfo.parameters)
914 Param.labelOffsets.reset();
915 }
916 return Reply(std::move(*Signature));
917 });
Ilya Biryukov652364b2018-09-26 05:48:29 +0000918}
919
Sam McCall0dbab7f2019-02-02 05:56:00 +0000920// Go to definition has a toggle function: if def and decl are distinct, then
921// the first press gives you the def, the second gives you the matching def.
922// getToggle() returns the counterpart location that under the cursor.
923//
924// We return the toggled location alone (ignoring other symbols) to encourage
925// editors to "bounce" quickly between locations, without showing a menu.
926static Location *getToggle(const TextDocumentPositionParams &Point,
927 LocatedSymbol &Sym) {
928 // Toggle only makes sense with two distinct locations.
929 if (!Sym.Definition || *Sym.Definition == Sym.PreferredDeclaration)
930 return nullptr;
931 if (Sym.Definition->uri.file() == Point.textDocument.uri.file() &&
932 Sym.Definition->range.contains(Point.position))
933 return &Sym.PreferredDeclaration;
934 if (Sym.PreferredDeclaration.uri.file() == Point.textDocument.uri.file() &&
935 Sym.PreferredDeclaration.range.contains(Point.position))
936 return &*Sym.Definition;
937 return nullptr;
938}
939
Sam McCall2c30fbc2018-10-18 12:32:04 +0000940void ClangdLSPServer::onGoToDefinition(const TextDocumentPositionParams &Params,
941 Callback<std::vector<Location>> Reply) {
Sam McCall866ba2c2019-02-01 11:26:13 +0000942 Server->locateSymbolAt(
943 Params.textDocument.uri.file(), Params.position,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000944 [Params, Reply = std::move(Reply)](
945 llvm::Expected<std::vector<LocatedSymbol>> Symbols) mutable {
946 if (!Symbols)
947 return Reply(Symbols.takeError());
948 std::vector<Location> Defs;
949 for (auto &S : *Symbols) {
950 if (Location *Toggle = getToggle(Params, S))
951 return Reply(std::vector<Location>{std::move(*Toggle)});
952 Defs.push_back(S.Definition.getValueOr(S.PreferredDeclaration));
953 }
954 Reply(std::move(Defs));
955 });
Sam McCall866ba2c2019-02-01 11:26:13 +0000956}
957
958void ClangdLSPServer::onGoToDeclaration(
959 const TextDocumentPositionParams &Params,
960 Callback<std::vector<Location>> Reply) {
961 Server->locateSymbolAt(
962 Params.textDocument.uri.file(), Params.position,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000963 [Params, Reply = std::move(Reply)](
964 llvm::Expected<std::vector<LocatedSymbol>> Symbols) mutable {
965 if (!Symbols)
966 return Reply(Symbols.takeError());
967 std::vector<Location> Decls;
968 for (auto &S : *Symbols) {
969 if (Location *Toggle = getToggle(Params, S))
970 return Reply(std::vector<Location>{std::move(*Toggle)});
971 Decls.push_back(std::move(S.PreferredDeclaration));
972 }
973 Reply(std::move(Decls));
974 });
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000975}
976
Sam McCall111fe842019-05-07 07:55:35 +0000977void ClangdLSPServer::onSwitchSourceHeader(
978 const TextDocumentIdentifier &Params,
Sam McCallb9ec3e92019-05-07 08:30:32 +0000979 Callback<llvm::Optional<URIForFile>> Reply) {
Sam McCall111fe842019-05-07 07:55:35 +0000980 if (auto Result = Server->switchSourceHeader(Params.uri.file()))
Sam McCallb9ec3e92019-05-07 08:30:32 +0000981 Reply(URIForFile::canonicalize(*Result, Params.uri.file()));
Sam McCall111fe842019-05-07 07:55:35 +0000982 else
983 Reply(llvm::None);
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000984}
985
Sam McCall2c30fbc2018-10-18 12:32:04 +0000986void ClangdLSPServer::onDocumentHighlight(
987 const TextDocumentPositionParams &Params,
988 Callback<std::vector<DocumentHighlight>> Reply) {
989 Server->findDocumentHighlights(Params.textDocument.uri.file(),
990 Params.position, std::move(Reply));
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000991}
992
Sam McCall2c30fbc2018-10-18 12:32:04 +0000993void ClangdLSPServer::onHover(const TextDocumentPositionParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000994 Callback<llvm::Optional<Hover>> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000995 Server->findHover(Params.textDocument.uri.file(), Params.position,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000996 [Reply = std::move(Reply), this](
997 llvm::Expected<llvm::Optional<HoverInfo>> H) mutable {
998 if (!H)
999 return Reply(H.takeError());
1000 if (!*H)
1001 return Reply(llvm::None);
Ilya Biryukovf9169d02019-05-29 10:01:00 +00001002
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001003 Hover R;
1004 R.contents.kind = HoverContentFormat;
1005 R.range = (*H)->SymRange;
1006 switch (HoverContentFormat) {
1007 case MarkupKind::PlainText:
1008 R.contents.value = (*H)->present().renderAsPlainText();
1009 return Reply(std::move(R));
1010 case MarkupKind::Markdown:
1011 R.contents.value = (*H)->present().renderAsMarkdown();
1012 return Reply(std::move(R));
1013 };
1014 llvm_unreachable("unhandled MarkupKind");
1015 });
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +00001016}
1017
Kadir Cetinkaya86658022019-03-19 09:27:04 +00001018void ClangdLSPServer::onTypeHierarchy(
1019 const TypeHierarchyParams &Params,
1020 Callback<Optional<TypeHierarchyItem>> Reply) {
1021 Server->typeHierarchy(Params.textDocument.uri.file(), Params.position,
1022 Params.resolve, Params.direction, std::move(Reply));
1023}
1024
Nathan Ridge087b0442019-07-13 03:24:48 +00001025void ClangdLSPServer::onResolveTypeHierarchy(
1026 const ResolveTypeHierarchyItemParams &Params,
1027 Callback<Optional<TypeHierarchyItem>> Reply) {
1028 Server->resolveTypeHierarchy(Params.item, Params.resolve, Params.direction,
1029 std::move(Reply));
1030}
1031
Simon Marchi88016782018-08-01 11:28:49 +00001032void ClangdLSPServer::applyConfiguration(
Sam McCallbc904612018-10-25 04:22:52 +00001033 const ConfigurationSettings &Settings) {
Simon Marchiabeed662018-10-16 15:55:03 +00001034 // Per-file update to the compilation database.
Sam McCallbc904612018-10-25 04:22:52 +00001035 bool ShouldReparseOpenFiles = false;
1036 for (auto &Entry : Settings.compilationDatabaseChanges) {
1037 /// The opened files need to be reparsed only when some existing
1038 /// entries are changed.
1039 PathRef File = Entry.first;
Sam McCallc55d09a2018-11-02 13:09:36 +00001040 auto Old = CDB->getCompileCommand(File);
1041 auto New =
1042 tooling::CompileCommand(std::move(Entry.second.workingDirectory), File,
1043 std::move(Entry.second.compilationCommand),
1044 /*Output=*/"");
Sam McCall6980edb2018-11-02 14:07:51 +00001045 if (Old != New) {
Sam McCallc55d09a2018-11-02 13:09:36 +00001046 CDB->setCompileCommand(File, std::move(New));
Sam McCall6980edb2018-11-02 14:07:51 +00001047 ShouldReparseOpenFiles = true;
1048 }
Alex Lorenzf8087862018-08-01 17:39:29 +00001049 }
Sam McCallbc904612018-10-25 04:22:52 +00001050 if (ShouldReparseOpenFiles)
1051 reparseOpenedFiles();
Simon Marchi5178f922018-02-22 14:00:39 +00001052}
1053
Johan Vikstroma848dab2019-07-04 07:53:12 +00001054void ClangdLSPServer::publishSemanticHighlighting(
1055 SemanticHighlightingParams Params) {
1056 notify("textDocument/semanticHighlighting", Params);
1057}
1058
Ilya Biryukov49c10712019-03-25 10:15:11 +00001059void ClangdLSPServer::publishDiagnostics(
1060 const URIForFile &File, std::vector<clangd::Diagnostic> Diagnostics) {
1061 // Publish diagnostics.
1062 notify("textDocument/publishDiagnostics",
1063 llvm::json::Object{
1064 {"uri", File},
1065 {"diagnostics", std::move(Diagnostics)},
1066 });
1067}
1068
Simon Marchi88016782018-08-01 11:28:49 +00001069// FIXME: This function needs to be properly tested.
1070void ClangdLSPServer::onChangeConfiguration(
Sam McCall2c30fbc2018-10-18 12:32:04 +00001071 const DidChangeConfigurationParams &Params) {
Simon Marchi88016782018-08-01 11:28:49 +00001072 applyConfiguration(Params.settings);
1073}
1074
Sam McCall2c30fbc2018-10-18 12:32:04 +00001075void ClangdLSPServer::onReference(const ReferenceParams &Params,
1076 Callback<std::vector<Location>> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +00001077 Server->findReferences(Params.textDocument.uri.file(), Params.position,
Haojian Wuc34f0222019-01-14 18:11:09 +00001078 CCOpts.Limit, std::move(Reply));
Sam McCall1ad142f2018-09-05 11:53:07 +00001079}
1080
Jan Korousb4067012018-11-27 16:40:46 +00001081void ClangdLSPServer::onSymbolInfo(const TextDocumentPositionParams &Params,
1082 Callback<std::vector<SymbolDetails>> Reply) {
1083 Server->symbolInfo(Params.textDocument.uri.file(), Params.position,
1084 std::move(Reply));
1085}
1086
Sam McCalla69698f2019-03-27 17:47:49 +00001087ClangdLSPServer::ClangdLSPServer(
1088 class Transport &Transp, const FileSystemProvider &FSProvider,
1089 const clangd::CodeCompleteOptions &CCOpts,
1090 llvm::Optional<Path> CompileCommandsDir, bool UseDirBasedCDB,
1091 llvm::Optional<OffsetEncoding> ForcedOffsetEncoding,
1092 const ClangdServer::Options &Opts)
Haojian Wu1ca0c582019-01-22 09:39:05 +00001093 : Transp(Transp), MsgHandler(new MessageHandler(*this)),
1094 FSProvider(FSProvider), CCOpts(CCOpts),
Sam McCalld1c9d112018-10-23 14:19:54 +00001095 SupportedSymbolKinds(defaultSymbolKinds()),
Kadir Cetinkaya133d46f2018-09-27 17:13:07 +00001096 SupportedCompletionItemKinds(defaultCompletionItemKinds()),
Sam McCallc55d09a2018-11-02 13:09:36 +00001097 UseDirBasedCDB(UseDirBasedCDB),
Sam McCalla69698f2019-03-27 17:47:49 +00001098 CompileCommandsDir(std::move(CompileCommandsDir)), ClangdServerOpts(Opts),
1099 NegotiatedOffsetEncoding(ForcedOffsetEncoding) {
Sam McCall2c30fbc2018-10-18 12:32:04 +00001100 // clang-format off
1101 MsgHandler->bind("initialize", &ClangdLSPServer::onInitialize);
1102 MsgHandler->bind("shutdown", &ClangdLSPServer::onShutdown);
Sam McCall422c8282018-11-26 16:00:11 +00001103 MsgHandler->bind("sync", &ClangdLSPServer::onSync);
Sam McCall2c30fbc2018-10-18 12:32:04 +00001104 MsgHandler->bind("textDocument/rangeFormatting", &ClangdLSPServer::onDocumentRangeFormatting);
1105 MsgHandler->bind("textDocument/onTypeFormatting", &ClangdLSPServer::onDocumentOnTypeFormatting);
1106 MsgHandler->bind("textDocument/formatting", &ClangdLSPServer::onDocumentFormatting);
1107 MsgHandler->bind("textDocument/codeAction", &ClangdLSPServer::onCodeAction);
1108 MsgHandler->bind("textDocument/completion", &ClangdLSPServer::onCompletion);
1109 MsgHandler->bind("textDocument/signatureHelp", &ClangdLSPServer::onSignatureHelp);
1110 MsgHandler->bind("textDocument/definition", &ClangdLSPServer::onGoToDefinition);
Sam McCall866ba2c2019-02-01 11:26:13 +00001111 MsgHandler->bind("textDocument/declaration", &ClangdLSPServer::onGoToDeclaration);
Sam McCall2c30fbc2018-10-18 12:32:04 +00001112 MsgHandler->bind("textDocument/references", &ClangdLSPServer::onReference);
1113 MsgHandler->bind("textDocument/switchSourceHeader", &ClangdLSPServer::onSwitchSourceHeader);
Haojian Wuf429ab62019-07-24 07:49:23 +00001114 MsgHandler->bind("textDocument/prepareRename", &ClangdLSPServer::onPrepareRename);
Sam McCall2c30fbc2018-10-18 12:32:04 +00001115 MsgHandler->bind("textDocument/rename", &ClangdLSPServer::onRename);
1116 MsgHandler->bind("textDocument/hover", &ClangdLSPServer::onHover);
1117 MsgHandler->bind("textDocument/documentSymbol", &ClangdLSPServer::onDocumentSymbol);
1118 MsgHandler->bind("workspace/executeCommand", &ClangdLSPServer::onCommand);
1119 MsgHandler->bind("textDocument/documentHighlight", &ClangdLSPServer::onDocumentHighlight);
1120 MsgHandler->bind("workspace/symbol", &ClangdLSPServer::onWorkspaceSymbol);
1121 MsgHandler->bind("textDocument/didOpen", &ClangdLSPServer::onDocumentDidOpen);
1122 MsgHandler->bind("textDocument/didClose", &ClangdLSPServer::onDocumentDidClose);
1123 MsgHandler->bind("textDocument/didChange", &ClangdLSPServer::onDocumentDidChange);
1124 MsgHandler->bind("workspace/didChangeWatchedFiles", &ClangdLSPServer::onFileEvent);
1125 MsgHandler->bind("workspace/didChangeConfiguration", &ClangdLSPServer::onChangeConfiguration);
Jan Korousb4067012018-11-27 16:40:46 +00001126 MsgHandler->bind("textDocument/symbolInfo", &ClangdLSPServer::onSymbolInfo);
Kadir Cetinkaya86658022019-03-19 09:27:04 +00001127 MsgHandler->bind("textDocument/typeHierarchy", &ClangdLSPServer::onTypeHierarchy);
Nathan Ridge087b0442019-07-13 03:24:48 +00001128 MsgHandler->bind("typeHierarchy/resolve", &ClangdLSPServer::onResolveTypeHierarchy);
Sam McCall2c30fbc2018-10-18 12:32:04 +00001129 // clang-format on
1130}
1131
Haojian Wuf2516342019-08-05 12:48:09 +00001132ClangdLSPServer::~ClangdLSPServer() { IsBeingDestroyed = true; }
Ilya Biryukov38d79772017-05-16 09:38:59 +00001133
Sam McCalldc8f3cf2018-10-17 07:32:05 +00001134bool ClangdLSPServer::run() {
Ilya Biryukovafb55542017-05-16 14:40:30 +00001135 // Run the Language Server loop.
Sam McCalldc8f3cf2018-10-17 07:32:05 +00001136 bool CleanExit = true;
Sam McCall2c30fbc2018-10-18 12:32:04 +00001137 if (auto Err = Transp.loop(*MsgHandler)) {
Sam McCalldc8f3cf2018-10-17 07:32:05 +00001138 elog("Transport error: {0}", std::move(Err));
1139 CleanExit = false;
1140 }
Ilya Biryukovafb55542017-05-16 14:40:30 +00001141
Ilya Biryukov652364b2018-09-26 05:48:29 +00001142 // Destroy ClangdServer to ensure all worker threads finish.
1143 Server.reset();
Sam McCalldc8f3cf2018-10-17 07:32:05 +00001144 return CleanExit && ShutdownRequestReceived;
Ilya Biryukov38d79772017-05-16 09:38:59 +00001145}
1146
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001147std::vector<Fix> ClangdLSPServer::getFixes(llvm::StringRef File,
Ilya Biryukov71028b82018-03-12 15:28:22 +00001148 const clangd::Diagnostic &D) {
Ilya Biryukov38d79772017-05-16 09:38:59 +00001149 std::lock_guard<std::mutex> Lock(FixItsMutex);
1150 auto DiagToFixItsIter = FixItsMap.find(File);
1151 if (DiagToFixItsIter == FixItsMap.end())
1152 return {};
1153
1154 const auto &DiagToFixItsMap = DiagToFixItsIter->second;
1155 auto FixItsIter = DiagToFixItsMap.find(D);
1156 if (FixItsIter == DiagToFixItsMap.end())
1157 return {};
1158
1159 return FixItsIter->second;
1160}
1161
Ilya Biryukovb0826bd2019-01-03 13:37:12 +00001162bool ClangdLSPServer::shouldRunCompletion(
1163 const CompletionParams &Params) const {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001164 llvm::StringRef Trigger = Params.context.triggerCharacter;
Ilya Biryukovb0826bd2019-01-03 13:37:12 +00001165 if (Params.context.triggerKind != CompletionTriggerKind::TriggerCharacter ||
1166 (Trigger != ">" && Trigger != ":"))
1167 return true;
1168
1169 auto Code = DraftMgr.getDraft(Params.textDocument.uri.file());
1170 if (!Code)
1171 return true; // completion code will log the error for untracked doc.
1172
1173 // A completion request is sent when the user types '>' or ':', but we only
1174 // want to trigger on '->' and '::'. We check the preceeding character to make
1175 // sure it matches what we expected.
1176 // Running the lexer here would be more robust (e.g. we can detect comments
1177 // and avoid triggering completion there), but we choose to err on the side
1178 // of simplicity here.
1179 auto Offset = positionToOffset(*Code, Params.position,
1180 /*AllowColumnsBeyondLineLength=*/false);
1181 if (!Offset) {
1182 vlog("could not convert position '{0}' to offset for file '{1}'",
1183 Params.position, Params.textDocument.uri.file());
1184 return true;
1185 }
1186 if (*Offset < 2)
1187 return false;
1188
1189 if (Trigger == ">")
1190 return (*Code)[*Offset - 2] == '-'; // trigger only on '->'.
1191 if (Trigger == ":")
1192 return (*Code)[*Offset - 2] == ':'; // trigger only on '::'.
1193 assert(false && "unhandled trigger character");
1194 return true;
1195}
1196
Johan Vikstroma848dab2019-07-04 07:53:12 +00001197void ClangdLSPServer::onHighlightingsReady(
Johan Vikstromc2653ef22019-08-01 08:08:44 +00001198 PathRef File, std::vector<HighlightingToken> Highlightings, int NumLines) {
1199 std::vector<HighlightingToken> Old;
1200 std::vector<HighlightingToken> HighlightingsCopy = Highlightings;
1201 {
1202 std::lock_guard<std::mutex> Lock(HighlightingsMutex);
1203 Old = std::move(FileToHighlightings[File]);
1204 FileToHighlightings[File] = std::move(HighlightingsCopy);
1205 }
1206 // LSP allows us to send incremental edits of highlightings. Also need to diff
1207 // to remove highlightings from tokens that should no longer have them.
1208 std::vector<LineHighlightings> Diffed =
1209 diffHighlightings(Highlightings, Old, NumLines);
Johan Vikstroma848dab2019-07-04 07:53:12 +00001210 publishSemanticHighlighting(
1211 {{URIForFile::canonicalize(File, /*TUPath=*/File)},
Johan Vikstromc2653ef22019-08-01 08:08:44 +00001212 toSemanticHighlightingInformation(Diffed)});
Johan Vikstroma848dab2019-07-04 07:53:12 +00001213}
1214
Sam McCalla7bb0cc2018-03-12 23:22:35 +00001215void ClangdLSPServer::onDiagnosticsReady(PathRef File,
1216 std::vector<Diag> Diagnostics) {
Eric Liu4d814a92018-11-28 10:30:42 +00001217 auto URI = URIForFile::canonicalize(File, /*TUPath=*/File);
Sam McCall16e70702018-10-24 07:59:38 +00001218 std::vector<Diagnostic> LSPDiagnostics;
Ilya Biryukov38d79772017-05-16 09:38:59 +00001219 DiagnosticToReplacementMap LocalFixIts; // Temporary storage
Sam McCalla7bb0cc2018-03-12 23:22:35 +00001220 for (auto &Diag : Diagnostics) {
Sam McCall16e70702018-10-24 07:59:38 +00001221 toLSPDiags(Diag, URI, DiagOpts,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001222 [&](clangd::Diagnostic Diag, llvm::ArrayRef<Fix> Fixes) {
Sam McCall16e70702018-10-24 07:59:38 +00001223 auto &FixItsForDiagnostic = LocalFixIts[Diag];
1224 llvm::copy(Fixes, std::back_inserter(FixItsForDiagnostic));
1225 LSPDiagnostics.push_back(std::move(Diag));
1226 });
Ilya Biryukov38d79772017-05-16 09:38:59 +00001227 }
1228
1229 // Cache FixIts
1230 {
Ilya Biryukov38d79772017-05-16 09:38:59 +00001231 std::lock_guard<std::mutex> Lock(FixItsMutex);
1232 FixItsMap[File] = LocalFixIts;
1233 }
1234
Ilya Biryukov49c10712019-03-25 10:15:11 +00001235 // Send a notification to the LSP client.
1236 publishDiagnostics(URI, std::move(LSPDiagnostics));
Ilya Biryukov38d79772017-05-16 09:38:59 +00001237}
Simon Marchi9569fd52018-03-16 14:30:42 +00001238
Haojian Wub6188492018-12-20 15:39:12 +00001239void ClangdLSPServer::onFileUpdated(PathRef File, const TUStatus &Status) {
1240 if (!SupportFileStatus)
1241 return;
1242 // FIXME: we don't emit "BuildingFile" and `RunningAction`, as these
1243 // two statuses are running faster in practice, which leads the UI constantly
1244 // changing, and doesn't provide much value. We may want to emit status at a
1245 // reasonable time interval (e.g. 0.5s).
1246 if (Status.Action.S == TUAction::BuildingFile ||
1247 Status.Action.S == TUAction::RunningAction)
1248 return;
1249 notify("textDocument/clangd.fileStatus", Status.render(File));
1250}
1251
Simon Marchi9569fd52018-03-16 14:30:42 +00001252void ClangdLSPServer::reparseOpenedFiles() {
1253 for (const Path &FilePath : DraftMgr.getActiveFiles())
Ilya Biryukov652364b2018-09-26 05:48:29 +00001254 Server->addDocument(FilePath, *DraftMgr.getDraft(FilePath),
1255 WantDiagnostics::Auto);
Simon Marchi9569fd52018-03-16 14:30:42 +00001256}
Alex Lorenzf8087862018-08-01 17:39:29 +00001257
Sam McCallc008af62018-10-20 15:30:37 +00001258} // namespace clangd
1259} // namespace clang