blob: 748269d5aef4b531095088a2e5c0e6c6ba6cbbb5 [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"
Kadir Cetinkaya9d662472019-10-15 14:20:52 +000010#include "Context.h"
Ilya Biryukov71028b82018-03-12 15:28:22 +000011#include "Diagnostics.h"
Kadir Cetinkaya5b270932019-09-09 12:28:44 +000012#include "DraftStore.h"
Ilya Biryukovf9169d02019-05-29 10:01:00 +000013#include "FormattedString.h"
Kadir Cetinkaya256247c2019-06-26 07:45:27 +000014#include "GlobalCompilationDatabase.h"
Ilya Biryukovcce67a32019-01-29 14:17:36 +000015#include "Protocol.h"
Johan Vikstroma848dab2019-07-04 07:53:12 +000016#include "SemanticHighlighting.h"
Sam McCallb536a2a2017-12-19 12:23:48 +000017#include "SourceCode.h"
Sam McCall2c30fbc2018-10-18 12:32:04 +000018#include "Trace.h"
Eric Liu78ed91a72018-01-29 15:37:46 +000019#include "URI.h"
Sam McCall395fde72019-06-18 13:37:54 +000020#include "refactor/Tweak.h"
Sam McCall6f7dca92020-03-03 12:25:46 +010021#include "clang/Basic/Version.h"
Ilya Biryukovcce67a32019-01-29 14:17:36 +000022#include "clang/Tooling/Core/Replacement.h"
Kadir Cetinkaya256247c2019-06-26 07:45:27 +000023#include "llvm/ADT/ArrayRef.h"
Sam McCalla69698f2019-03-27 17:47:49 +000024#include "llvm/ADT/Optional.h"
Kadir Cetinkaya689bf932018-08-24 13:09:41 +000025#include "llvm/ADT/ScopeExit.h"
Kadir Cetinkaya5b270932019-09-09 12:28:44 +000026#include "llvm/ADT/StringRef.h"
Utkarsh Saxena55925da2019-09-24 13:38:33 +000027#include "llvm/ADT/iterator_range.h"
Simon Marchi9569fd52018-03-16 14:30:42 +000028#include "llvm/Support/Errc.h"
Ilya Biryukovcce67a32019-01-29 14:17:36 +000029#include "llvm/Support/Error.h"
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +000030#include "llvm/Support/FormatVariadic.h"
Utkarsh Saxena55925da2019-09-24 13:38:33 +000031#include "llvm/Support/JSON.h"
Eric Liu5740ff52018-01-31 16:26:27 +000032#include "llvm/Support/Path.h"
Kadir Cetinkaya5b270932019-09-09 12:28:44 +000033#include "llvm/Support/SHA1.h"
Sam McCall2c30fbc2018-10-18 12:32:04 +000034#include "llvm/Support/ScopedPrinter.h"
Kadir Cetinkaya5b270932019-09-09 12:28:44 +000035#include <cstddef>
Utkarsh Saxena55925da2019-09-24 13:38:33 +000036#include <memory>
Sam McCall7d20e802020-01-22 19:41:45 +010037#include <mutex>
Kadir Cetinkaya5b270932019-09-09 12:28:44 +000038#include <string>
Utkarsh Saxena55925da2019-09-24 13:38:33 +000039#include <vector>
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +000040
Sam McCallc008af62018-10-20 15:30:37 +000041namespace clang {
42namespace clangd {
Ilya Biryukovafb55542017-05-16 14:40:30 +000043namespace {
Sam McCall2cd33e62020-03-04 00:33:29 +010044
45// LSP defines file versions as numbers that increase.
46// ClangdServer treats them as opaque and therefore uses strings instead.
47std::string encodeVersion(int64_t LSPVersion) {
48 return llvm::to_string(LSPVersion);
49}
50llvm::Optional<int64_t> decodeVersion(llvm::StringRef Encoded) {
51 int64_t Result;
52 if (llvm::to_integer(Encoded, Result, 10))
53 return Result;
54 else if (!Encoded.empty()) // Empty can be e.g. diagnostics on close.
55 elog("unexpected non-numeric version {0}", Encoded);
56 return llvm::None;
57}
58
Ilya Biryukovcce67a32019-01-29 14:17:36 +000059/// Transforms a tweak into a code action that would apply it if executed.
60/// EXPECTS: T.prepare() was called and returned true.
61CodeAction toCodeAction(const ClangdServer::TweakRef &T, const URIForFile &File,
62 Range Selection) {
63 CodeAction CA;
64 CA.title = T.Title;
Sam McCall395fde72019-06-18 13:37:54 +000065 switch (T.Intent) {
66 case Tweak::Refactor:
Benjamin Krameradcd0262020-01-28 20:23:46 +010067 CA.kind = std::string(CodeAction::REFACTOR_KIND);
Sam McCall395fde72019-06-18 13:37:54 +000068 break;
69 case Tweak::Info:
Benjamin Krameradcd0262020-01-28 20:23:46 +010070 CA.kind = std::string(CodeAction::INFO_KIND);
Sam McCall395fde72019-06-18 13:37:54 +000071 break;
72 }
Ilya Biryukovcce67a32019-01-29 14:17:36 +000073 // This tweak may have an expensive second stage, we only run it if the user
74 // actually chooses it in the UI. We reply with a command that would run the
75 // corresponding tweak.
76 // FIXME: for some tweaks, computing the edits is cheap and we could send them
77 // directly.
78 CA.command.emplace();
79 CA.command->title = T.Title;
Benjamin Krameradcd0262020-01-28 20:23:46 +010080 CA.command->command = std::string(Command::CLANGD_APPLY_TWEAK);
Ilya Biryukovcce67a32019-01-29 14:17:36 +000081 CA.command->tweakArgs.emplace();
82 CA.command->tweakArgs->file = File;
83 CA.command->tweakArgs->tweakID = T.ID;
84 CA.command->tweakArgs->selection = Selection;
85 return CA;
Simon Pilgrime9a136b2019-02-03 14:08:30 +000086}
Ilya Biryukovcce67a32019-01-29 14:17:36 +000087
Ilya Biryukov19d75602018-11-23 15:21:19 +000088void adjustSymbolKinds(llvm::MutableArrayRef<DocumentSymbol> Syms,
89 SymbolKindBitset Kinds) {
90 for (auto &S : Syms) {
91 S.kind = adjustKindToCapability(S.kind, Kinds);
92 adjustSymbolKinds(S.children, Kinds);
93 }
94}
95
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +000096SymbolKindBitset defaultSymbolKinds() {
97 SymbolKindBitset Defaults;
98 for (size_t I = SymbolKindMin; I <= static_cast<size_t>(SymbolKind::Array);
99 ++I)
100 Defaults.set(I);
101 return Defaults;
102}
103
Kadir Cetinkaya133d46f2018-09-27 17:13:07 +0000104CompletionItemKindBitset defaultCompletionItemKinds() {
105 CompletionItemKindBitset Defaults;
106 for (size_t I = CompletionItemKindMin;
107 I <= static_cast<size_t>(CompletionItemKind::Reference); ++I)
108 Defaults.set(I);
109 return Defaults;
110}
111
Haojian Wu1ca2ee42019-07-04 12:27:21 +0000112// Build a lookup table (HighlightingKind => {TextMate Scopes}), which is sent
113// to the LSP client.
114std::vector<std::vector<std::string>> buildHighlightScopeLookupTable() {
115 std::vector<std::vector<std::string>> LookupTable;
116 // HighlightingKind is using as the index.
Ilya Biryukov63d5d162019-09-09 08:57:17 +0000117 for (int KindValue = 0; KindValue <= (int)HighlightingKind::LastKind;
Haojian Wu1ca2ee42019-07-04 12:27:21 +0000118 ++KindValue)
Benjamin Krameradcd0262020-01-28 20:23:46 +0100119 LookupTable.push_back(
120 {std::string(toTextMateScope((HighlightingKind)(KindValue)))});
Haojian Wu1ca2ee42019-07-04 12:27:21 +0000121 return LookupTable;
122}
123
Haojian Wu852bafa2019-10-23 14:40:20 +0200124// Makes sure edits in \p FE are applicable to latest file contents reported by
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000125// editor. If not generates an error message containing information about files
126// that needs to be saved.
Haojian Wu852bafa2019-10-23 14:40:20 +0200127llvm::Error validateEdits(const DraftStore &DraftMgr, const FileEdits &FE) {
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000128 size_t InvalidFileCount = 0;
129 llvm::StringRef LastInvalidFile;
Haojian Wu852bafa2019-10-23 14:40:20 +0200130 for (const auto &It : FE) {
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000131 if (auto Draft = DraftMgr.getDraft(It.first())) {
132 // If the file is open in user's editor, make sure the version we
133 // saw and current version are compatible as this is the text that
134 // will be replaced by editors.
Sam McCallcaf5a4d2020-03-03 15:57:39 +0100135 if (!It.second.canApplyTo(Draft->Contents)) {
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000136 ++InvalidFileCount;
137 LastInvalidFile = It.first();
138 }
139 }
140 }
141 if (!InvalidFileCount)
142 return llvm::Error::success();
143 if (InvalidFileCount == 1)
144 return llvm::createStringError(llvm::inconvertibleErrorCode(),
145 "File must be saved first: " +
146 LastInvalidFile);
147 return llvm::createStringError(
148 llvm::inconvertibleErrorCode(),
149 "Files must be saved first: " + LastInvalidFile + " (and " +
150 llvm::to_string(InvalidFileCount - 1) + " others)");
151}
152
Utkarsh Saxena55925da2019-09-24 13:38:33 +0000153// Converts a list of Ranges to a LinkedList of SelectionRange.
154SelectionRange render(const std::vector<Range> &Ranges) {
155 if (Ranges.empty())
156 return {};
157 SelectionRange Result;
158 Result.range = Ranges[0];
159 auto *Next = &Result.parent;
160 for (const auto &R : llvm::make_range(Ranges.begin() + 1, Ranges.end())) {
161 *Next = std::make_unique<SelectionRange>();
162 Next->get()->range = R;
163 Next = &Next->get()->parent;
164 }
165 return Result;
166}
167
Ilya Biryukovafb55542017-05-16 14:40:30 +0000168} // namespace
169
Sam McCall2c30fbc2018-10-18 12:32:04 +0000170// MessageHandler dispatches incoming LSP messages.
171// It handles cross-cutting concerns:
172// - serializes/deserializes protocol objects to JSON
173// - logging of inbound messages
174// - cancellation handling
175// - basic call tracing
Sam McCall3d0adbe2018-10-18 14:41:50 +0000176// MessageHandler ensures that initialize() is called before any other handler.
Sam McCall2c30fbc2018-10-18 12:32:04 +0000177class ClangdLSPServer::MessageHandler : public Transport::MessageHandler {
178public:
179 MessageHandler(ClangdLSPServer &Server) : Server(Server) {}
180
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000181 bool onNotify(llvm::StringRef Method, llvm::json::Value Params) override {
Sam McCalla69698f2019-03-27 17:47:49 +0000182 WithContext HandlerContext(handlerContext());
Sam McCall2c30fbc2018-10-18 12:32:04 +0000183 log("<-- {0}", Method);
184 if (Method == "exit")
185 return false;
Sam McCall3d0adbe2018-10-18 14:41:50 +0000186 if (!Server.Server)
187 elog("Notification {0} before initialization", Method);
188 else if (Method == "$/cancelRequest")
Sam McCall2c30fbc2018-10-18 12:32:04 +0000189 onCancel(std::move(Params));
190 else if (auto Handler = Notifications.lookup(Method))
191 Handler(std::move(Params));
192 else
193 log("unhandled notification {0}", Method);
194 return true;
195 }
196
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000197 bool onCall(llvm::StringRef Method, llvm::json::Value Params,
198 llvm::json::Value ID) override {
Sam McCalla69698f2019-03-27 17:47:49 +0000199 WithContext HandlerContext(handlerContext());
Sam McCalle2f3a732018-10-24 14:26:26 +0000200 // Calls can be canceled by the client. Add cancellation context.
201 WithContext WithCancel(cancelableRequestContext(ID));
202 trace::Span Tracer(Method);
203 SPAN_ATTACH(Tracer, "Params", Params);
204 ReplyOnce Reply(ID, Method, &Server, Tracer.Args);
Sam McCall2c30fbc2018-10-18 12:32:04 +0000205 log("<-- {0}({1})", Method, ID);
Sam McCall3d0adbe2018-10-18 14:41:50 +0000206 if (!Server.Server && Method != "initialize") {
207 elog("Call {0} before initialization.", Method);
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000208 Reply(llvm::make_error<LSPError>("server not initialized",
209 ErrorCode::ServerNotInitialized));
Sam McCall3d0adbe2018-10-18 14:41:50 +0000210 } else if (auto Handler = Calls.lookup(Method))
Sam McCalle2f3a732018-10-24 14:26:26 +0000211 Handler(std::move(Params), std::move(Reply));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000212 else
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000213 Reply(llvm::make_error<LSPError>("method not found",
214 ErrorCode::MethodNotFound));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000215 return true;
216 }
217
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000218 bool onReply(llvm::json::Value ID,
219 llvm::Expected<llvm::json::Value> Result) override {
Sam McCalla69698f2019-03-27 17:47:49 +0000220 WithContext HandlerContext(handlerContext());
Haojian Wuf2516342019-08-05 12:48:09 +0000221
222 Callback<llvm::json::Value> ReplyHandler = nullptr;
223 if (auto IntID = ID.getAsInteger()) {
224 std::lock_guard<std::mutex> Mutex(CallMutex);
225 // Find a corresponding callback for the request ID;
226 for (size_t Index = 0; Index < ReplyCallbacks.size(); ++Index) {
227 if (ReplyCallbacks[Index].first == *IntID) {
228 ReplyHandler = std::move(ReplyCallbacks[Index].second);
229 ReplyCallbacks.erase(ReplyCallbacks.begin() +
230 Index); // remove the entry
231 break;
232 }
233 }
234 }
235
236 if (!ReplyHandler) {
237 // No callback being found, use a default log callback.
238 ReplyHandler = [&ID](llvm::Expected<llvm::json::Value> Result) {
239 elog("received a reply with ID {0}, but there was no such call", ID);
240 if (!Result)
241 llvm::consumeError(Result.takeError());
242 };
243 }
244
245 // Log and run the reply handler.
246 if (Result) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000247 log("<-- reply({0})", ID);
Haojian Wuf2516342019-08-05 12:48:09 +0000248 ReplyHandler(std::move(Result));
249 } else {
250 auto Err = Result.takeError();
251 log("<-- reply({0}) error: {1}", ID, Err);
252 ReplyHandler(std::move(Err));
253 }
Sam McCall2c30fbc2018-10-18 12:32:04 +0000254 return true;
255 }
256
257 // Bind an LSP method name to a call.
Sam McCalle2f3a732018-10-24 14:26:26 +0000258 template <typename Param, typename Result>
Sam McCall2c30fbc2018-10-18 12:32:04 +0000259 void bind(const char *Method,
Sam McCalle2f3a732018-10-24 14:26:26 +0000260 void (ClangdLSPServer::*Handler)(const Param &, Callback<Result>)) {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000261 Calls[Method] = [Method, Handler, this](llvm::json::Value RawParams,
Sam McCalle2f3a732018-10-24 14:26:26 +0000262 ReplyOnce Reply) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000263 Param P;
Sam McCalle2f3a732018-10-24 14:26:26 +0000264 if (fromJSON(RawParams, P)) {
265 (Server.*Handler)(P, std::move(Reply));
266 } else {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000267 elog("Failed to decode {0} request.", Method);
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000268 Reply(llvm::make_error<LSPError>("failed to decode request",
269 ErrorCode::InvalidRequest));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000270 }
Sam McCall2c30fbc2018-10-18 12:32:04 +0000271 };
272 }
273
Haojian Wuf2516342019-08-05 12:48:09 +0000274 // Bind a reply callback to a request. The callback will be invoked when
275 // clangd receives the reply from the LSP client.
276 // Return a call id of the request.
277 llvm::json::Value bindReply(Callback<llvm::json::Value> Reply) {
278 llvm::Optional<std::pair<int, Callback<llvm::json::Value>>> OldestCB;
279 int ID;
280 {
281 std::lock_guard<std::mutex> Mutex(CallMutex);
282 ID = NextCallID++;
283 ReplyCallbacks.emplace_back(ID, std::move(Reply));
284
285 // If the queue overflows, we assume that the client didn't reply the
286 // oldest request, and run the corresponding callback which replies an
287 // error to the client.
288 if (ReplyCallbacks.size() > MaxReplayCallbacks) {
289 elog("more than {0} outstanding LSP calls, forgetting about {1}",
290 MaxReplayCallbacks, ReplyCallbacks.front().first);
291 OldestCB = std::move(ReplyCallbacks.front());
292 ReplyCallbacks.pop_front();
293 }
294 }
295 if (OldestCB)
296 OldestCB->second(llvm::createStringError(
297 llvm::inconvertibleErrorCode(),
298 llvm::formatv("failed to receive a client reply for request ({0})",
299 OldestCB->first)));
300 return ID;
301 }
302
Sam McCall2c30fbc2018-10-18 12:32:04 +0000303 // Bind an LSP method name to a notification.
304 template <typename Param>
305 void bind(const char *Method,
306 void (ClangdLSPServer::*Handler)(const Param &)) {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000307 Notifications[Method] = [Method, Handler,
308 this](llvm::json::Value RawParams) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000309 Param P;
310 if (!fromJSON(RawParams, P)) {
311 elog("Failed to decode {0} request.", Method);
312 return;
313 }
314 trace::Span Tracer(Method);
315 SPAN_ATTACH(Tracer, "Params", RawParams);
316 (Server.*Handler)(P);
317 };
318 }
319
320private:
Sam McCalle2f3a732018-10-24 14:26:26 +0000321 // Function object to reply to an LSP call.
322 // Each instance must be called exactly once, otherwise:
323 // - the bug is logged, and (in debug mode) an assert will fire
324 // - if there was no reply, an error reply is sent
325 // - if there were multiple replies, only the first is sent
326 class ReplyOnce {
327 std::atomic<bool> Replied = {false};
Sam McCalld7babe42018-10-24 15:18:40 +0000328 std::chrono::steady_clock::time_point Start;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000329 llvm::json::Value ID;
Sam McCalle2f3a732018-10-24 14:26:26 +0000330 std::string Method;
331 ClangdLSPServer *Server; // Null when moved-from.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000332 llvm::json::Object *TraceArgs;
Sam McCalle2f3a732018-10-24 14:26:26 +0000333
334 public:
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000335 ReplyOnce(const llvm::json::Value &ID, llvm::StringRef Method,
336 ClangdLSPServer *Server, llvm::json::Object *TraceArgs)
Sam McCalld7babe42018-10-24 15:18:40 +0000337 : Start(std::chrono::steady_clock::now()), ID(ID), Method(Method),
338 Server(Server), TraceArgs(TraceArgs) {
Sam McCalle2f3a732018-10-24 14:26:26 +0000339 assert(Server);
340 }
341 ReplyOnce(ReplyOnce &&Other)
Sam McCalld7babe42018-10-24 15:18:40 +0000342 : Replied(Other.Replied.load()), Start(Other.Start),
343 ID(std::move(Other.ID)), Method(std::move(Other.Method)),
344 Server(Other.Server), TraceArgs(Other.TraceArgs) {
Sam McCalle2f3a732018-10-24 14:26:26 +0000345 Other.Server = nullptr;
346 }
Ilya Biryukov22fa4652019-01-03 13:28:05 +0000347 ReplyOnce &operator=(ReplyOnce &&) = delete;
Sam McCalle2f3a732018-10-24 14:26:26 +0000348 ReplyOnce(const ReplyOnce &) = delete;
Ilya Biryukov22fa4652019-01-03 13:28:05 +0000349 ReplyOnce &operator=(const ReplyOnce &) = delete;
Sam McCalle2f3a732018-10-24 14:26:26 +0000350
351 ~ReplyOnce() {
Haojian Wuf2516342019-08-05 12:48:09 +0000352 // There's one legitimate reason to never reply to a request: clangd's
353 // request handler send a call to the client (e.g. applyEdit) and the
354 // client never replied. In this case, the ReplyOnce is owned by
355 // ClangdLSPServer's reply callback table and is destroyed along with the
356 // server. We don't attempt to send a reply in this case, there's little
357 // to be gained from doing so.
358 if (Server && !Server->IsBeingDestroyed && !Replied) {
Sam McCalle2f3a732018-10-24 14:26:26 +0000359 elog("No reply to message {0}({1})", Method, ID);
360 assert(false && "must reply to all calls!");
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000361 (*this)(llvm::make_error<LSPError>("server failed to reply",
362 ErrorCode::InternalError));
Sam McCalle2f3a732018-10-24 14:26:26 +0000363 }
364 }
365
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000366 void operator()(llvm::Expected<llvm::json::Value> Reply) {
Sam McCalle2f3a732018-10-24 14:26:26 +0000367 assert(Server && "moved-from!");
368 if (Replied.exchange(true)) {
369 elog("Replied twice to message {0}({1})", Method, ID);
370 assert(false && "must reply to each call only once!");
371 return;
372 }
Sam McCalld7babe42018-10-24 15:18:40 +0000373 auto Duration = std::chrono::steady_clock::now() - Start;
374 if (Reply) {
375 log("--> reply:{0}({1}) {2:ms}", Method, ID, Duration);
376 if (TraceArgs)
Sam McCalle2f3a732018-10-24 14:26:26 +0000377 (*TraceArgs)["Reply"] = *Reply;
Sam McCalld7babe42018-10-24 15:18:40 +0000378 std::lock_guard<std::mutex> Lock(Server->TranspWriter);
379 Server->Transp.reply(std::move(ID), std::move(Reply));
380 } else {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000381 llvm::Error Err = Reply.takeError();
Sam McCalld7babe42018-10-24 15:18:40 +0000382 log("--> reply:{0}({1}) {2:ms}, error: {3}", Method, ID, Duration, Err);
383 if (TraceArgs)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000384 (*TraceArgs)["Error"] = llvm::to_string(Err);
Sam McCalld7babe42018-10-24 15:18:40 +0000385 std::lock_guard<std::mutex> Lock(Server->TranspWriter);
386 Server->Transp.reply(std::move(ID), std::move(Err));
Sam McCalle2f3a732018-10-24 14:26:26 +0000387 }
Sam McCalle2f3a732018-10-24 14:26:26 +0000388 }
389 };
390
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000391 llvm::StringMap<std::function<void(llvm::json::Value)>> Notifications;
392 llvm::StringMap<std::function<void(llvm::json::Value, ReplyOnce)>> Calls;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000393
394 // Method calls may be cancelled by ID, so keep track of their state.
395 // This needs a mutex: handlers may finish on a different thread, and that's
396 // when we clean up entries in the map.
397 mutable std::mutex RequestCancelersMutex;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000398 llvm::StringMap<std::pair<Canceler, /*Cookie*/ unsigned>> RequestCancelers;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000399 unsigned NextRequestCookie = 0; // To disambiguate reused IDs, see below.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000400 void onCancel(const llvm::json::Value &Params) {
401 const llvm::json::Value *ID = nullptr;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000402 if (auto *O = Params.getAsObject())
403 ID = O->get("id");
404 if (!ID) {
405 elog("Bad cancellation request: {0}", Params);
406 return;
407 }
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000408 auto StrID = llvm::to_string(*ID);
Sam McCall2c30fbc2018-10-18 12:32:04 +0000409 std::lock_guard<std::mutex> Lock(RequestCancelersMutex);
410 auto It = RequestCancelers.find(StrID);
411 if (It != RequestCancelers.end())
412 It->second.first(); // Invoke the canceler.
413 }
Sam McCalla69698f2019-03-27 17:47:49 +0000414
415 Context handlerContext() const {
416 return Context::current().derive(
417 kCurrentOffsetEncoding,
418 Server.NegotiatedOffsetEncoding.getValueOr(OffsetEncoding::UTF16));
419 }
420
Sam McCall2c30fbc2018-10-18 12:32:04 +0000421 // We run cancelable requests in a context that does two things:
422 // - allows cancellation using RequestCancelers[ID]
423 // - cleans up the entry in RequestCancelers when it's no longer needed
424 // If a client reuses an ID, the last wins and the first cannot be canceled.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000425 Context cancelableRequestContext(const llvm::json::Value &ID) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000426 auto Task = cancelableTask();
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000427 auto StrID = llvm::to_string(ID); // JSON-serialize ID for map key.
Sam McCall2c30fbc2018-10-18 12:32:04 +0000428 auto Cookie = NextRequestCookie++; // No lock, only called on main thread.
429 {
430 std::lock_guard<std::mutex> Lock(RequestCancelersMutex);
431 RequestCancelers[StrID] = {std::move(Task.second), Cookie};
432 }
433 // When the request ends, we can clean up the entry we just added.
434 // The cookie lets us check that it hasn't been overwritten due to ID
435 // reuse.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000436 return Task.first.derive(llvm::make_scope_exit([this, StrID, Cookie] {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000437 std::lock_guard<std::mutex> Lock(RequestCancelersMutex);
438 auto It = RequestCancelers.find(StrID);
439 if (It != RequestCancelers.end() && It->second.second == Cookie)
440 RequestCancelers.erase(It);
441 }));
442 }
443
Kadir Cetinkaya9a3a87d2019-10-09 13:59:31 +0000444 // The maximum number of callbacks held in clangd.
445 //
446 // We bound the maximum size to the pending map to prevent memory leakage
447 // for cases where LSP clients don't reply for the request.
448 // This has to go after RequestCancellers and RequestCancellersMutex since it
449 // can contain a callback that has a cancelable context.
450 static constexpr int MaxReplayCallbacks = 100;
451 mutable std::mutex CallMutex;
452 int NextCallID = 0; /* GUARDED_BY(CallMutex) */
453 std::deque<std::pair</*RequestID*/ int,
454 /*ReplyHandler*/ Callback<llvm::json::Value>>>
455 ReplyCallbacks; /* GUARDED_BY(CallMutex) */
456
Sam McCall2c30fbc2018-10-18 12:32:04 +0000457 ClangdLSPServer &Server;
458};
Haojian Wuf2516342019-08-05 12:48:09 +0000459constexpr int ClangdLSPServer::MessageHandler::MaxReplayCallbacks;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000460
461// call(), notify(), and reply() wrap the Transport, adding logging and locking.
Haojian Wuf2516342019-08-05 12:48:09 +0000462void ClangdLSPServer::callRaw(StringRef Method, llvm::json::Value Params,
463 Callback<llvm::json::Value> CB) {
464 auto ID = MsgHandler->bindReply(std::move(CB));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000465 log("--> {0}({1})", Method, ID);
Sam McCall2c30fbc2018-10-18 12:32:04 +0000466 std::lock_guard<std::mutex> Lock(TranspWriter);
467 Transp.call(Method, std::move(Params), ID);
468}
469
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000470void ClangdLSPServer::notify(llvm::StringRef Method, llvm::json::Value Params) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000471 log("--> {0}", Method);
472 std::lock_guard<std::mutex> Lock(TranspWriter);
473 Transp.notify(Method, std::move(Params));
474}
475
Sam McCall2c30fbc2018-10-18 12:32:04 +0000476void ClangdLSPServer::onInitialize(const InitializeParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000477 Callback<llvm::json::Value> Reply) {
Sam McCalla69698f2019-03-27 17:47:49 +0000478 // Determine character encoding first as it affects constructed ClangdServer.
479 if (Params.capabilities.offsetEncoding && !NegotiatedOffsetEncoding) {
480 NegotiatedOffsetEncoding = OffsetEncoding::UTF16; // fallback
481 for (OffsetEncoding Supported : *Params.capabilities.offsetEncoding)
482 if (Supported != OffsetEncoding::UnsupportedEncoding) {
483 NegotiatedOffsetEncoding = Supported;
484 break;
485 }
486 }
Sam McCalla69698f2019-03-27 17:47:49 +0000487
Johan Vikstroma848dab2019-07-04 07:53:12 +0000488 ClangdServerOpts.SemanticHighlighting =
489 Params.capabilities.SemanticHighlighting;
Sam McCall0d9b40f2018-10-19 15:42:23 +0000490 if (Params.rootUri && *Params.rootUri)
Benjamin Krameradcd0262020-01-28 20:23:46 +0100491 ClangdServerOpts.WorkspaceRoot = std::string(Params.rootUri->file());
Sam McCall0d9b40f2018-10-19 15:42:23 +0000492 else if (Params.rootPath && !Params.rootPath->empty())
493 ClangdServerOpts.WorkspaceRoot = *Params.rootPath;
Sam McCall3d0adbe2018-10-18 14:41:50 +0000494 if (Server)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000495 return Reply(llvm::make_error<LSPError>("server already initialized",
496 ErrorCode::InvalidRequest));
Sam McCallbc904612018-10-25 04:22:52 +0000497 if (const auto &Dir = Params.initializationOptions.compilationDatabasePath)
498 CompileCommandsDir = Dir;
Kadir Cetinkaya256247c2019-06-26 07:45:27 +0000499 if (UseDirBasedCDB) {
Jonas Devlieghere1c705d92019-08-14 23:52:23 +0000500 BaseCDB = std::make_unique<DirectoryBasedGlobalCompilationDatabase>(
Sam McCallc55d09a2018-11-02 13:09:36 +0000501 CompileCommandsDir);
Kadir Cetinkaya256247c2019-06-26 07:45:27 +0000502 BaseCDB = getQueryDriverDatabase(
503 llvm::makeArrayRef(ClangdServerOpts.QueryDriverGlobs),
504 std::move(BaseCDB));
505 }
Sam McCall99768b22019-11-29 19:37:48 +0100506 auto Mangler = CommandMangler::detect();
507 if (ClangdServerOpts.ResourceDir)
508 Mangler.ResourceDir = *ClangdServerOpts.ResourceDir;
Kadir Cetinkayabe6b35d2019-01-22 09:10:20 +0000509 CDB.emplace(BaseCDB.get(), Params.initializationOptions.fallbackFlags,
Sam McCall99768b22019-11-29 19:37:48 +0100510 tooling::ArgumentsAdjuster(Mangler));
Kadir Cetinkaya9d662472019-10-15 14:20:52 +0000511 {
512 // Switch caller's context with LSPServer's background context. Since we
513 // rather want to propagate information from LSPServer's context into the
514 // Server, CDB, etc.
515 WithContext MainContext(BackgroundContext.clone());
516 llvm::Optional<WithContextValue> WithOffsetEncoding;
517 if (NegotiatedOffsetEncoding)
518 WithOffsetEncoding.emplace(kCurrentOffsetEncoding,
519 *NegotiatedOffsetEncoding);
Sam McCall6ef1cce2020-01-24 14:08:56 +0100520 Server.emplace(*CDB, FSProvider, ClangdServerOpts,
521 static_cast<ClangdServer::Callbacks *>(this));
Kadir Cetinkaya9d662472019-10-15 14:20:52 +0000522 }
Sam McCallbc904612018-10-25 04:22:52 +0000523 applyConfiguration(Params.initializationOptions.ConfigSettings);
Simon Marchi88016782018-08-01 11:28:49 +0000524
Sam McCallbf6a2fc2018-10-17 07:33:42 +0000525 CCOpts.EnableSnippets = Params.capabilities.CompletionSnippets;
Sam McCall8d412942019-06-18 11:57:26 +0000526 CCOpts.IncludeFixIts = Params.capabilities.CompletionFixes;
Sam McCall5f092e32019-07-08 17:27:15 +0000527 if (!CCOpts.BundleOverloads.hasValue())
528 CCOpts.BundleOverloads = Params.capabilities.HasSignatureHelp;
Sam McCallbf6a2fc2018-10-17 07:33:42 +0000529 DiagOpts.EmbedFixesInDiagnostics = Params.capabilities.DiagnosticFixes;
530 DiagOpts.SendDiagnosticCategory = Params.capabilities.DiagnosticCategory;
Sam McCallc9e4ee92019-04-18 15:17:07 +0000531 DiagOpts.EmitRelatedLocations =
532 Params.capabilities.DiagnosticRelatedInformation;
Sam McCallbf6a2fc2018-10-17 07:33:42 +0000533 if (Params.capabilities.WorkspaceSymbolKinds)
534 SupportedSymbolKinds |= *Params.capabilities.WorkspaceSymbolKinds;
535 if (Params.capabilities.CompletionItemKinds)
536 SupportedCompletionItemKinds |= *Params.capabilities.CompletionItemKinds;
537 SupportsCodeAction = Params.capabilities.CodeActionStructure;
Ilya Biryukov19d75602018-11-23 15:21:19 +0000538 SupportsHierarchicalDocumentSymbol =
539 Params.capabilities.HierarchicalDocumentSymbol;
Haojian Wub6188492018-12-20 15:39:12 +0000540 SupportFileStatus = Params.initializationOptions.FileStatus;
Ilya Biryukovf9169d02019-05-29 10:01:00 +0000541 HoverContentFormat = Params.capabilities.HoverContentFormat;
Ilya Biryukov4ef0f822019-06-04 09:36:59 +0000542 SupportsOffsetsInSignatureHelp = Params.capabilities.OffsetsInSignatureHelp;
Sam McCall7d20e802020-01-22 19:41:45 +0100543 if (Params.capabilities.WorkDoneProgress)
544 BackgroundIndexProgressState = BackgroundIndexProgress::Empty;
545 BackgroundIndexSkipCreate = Params.capabilities.ImplicitProgressCreation;
Haojian Wuf429ab62019-07-24 07:49:23 +0000546
547 // Per LSP, renameProvider can be either boolean or RenameOptions.
548 // RenameOptions will be specified if the client states it supports prepare.
549 llvm::json::Value RenameProvider =
550 llvm::json::Object{{"prepareProvider", true}};
551 if (!Params.capabilities.RenamePrepareSupport) // Only boolean allowed per LSP
552 RenameProvider = true;
553
Haojian Wu08d93f12019-08-22 14:53:45 +0000554 // Per LSP, codeActionProvide can be either boolean or CodeActionOptions.
555 // CodeActionOptions is only valid if the client supports action literal
556 // via textDocument.codeAction.codeActionLiteralSupport.
557 llvm::json::Value CodeActionProvider = true;
558 if (Params.capabilities.CodeActionStructure)
559 CodeActionProvider = llvm::json::Object{
560 {"codeActionKinds",
561 {CodeAction::QUICKFIX_KIND, CodeAction::REFACTOR_KIND,
562 CodeAction::INFO_KIND}}};
563
Sam McCalla69698f2019-03-27 17:47:49 +0000564 llvm::json::Object Result{
Sam McCall6f7dca92020-03-03 12:25:46 +0100565 {{"serverInfo",
566 llvm::json::Object{{"name", "clangd"},
567 {"version", getClangToolFullVersion("clangd")}}},
568 {"capabilities",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000569 llvm::json::Object{
Simon Marchi98082622018-03-26 14:41:40 +0000570 {"textDocumentSync", (int)TextDocumentSyncKind::Incremental},
Sam McCall0930ab02017-11-07 15:49:35 +0000571 {"documentFormattingProvider", true},
572 {"documentRangeFormattingProvider", true},
573 {"documentOnTypeFormattingProvider",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000574 llvm::json::Object{
Sam McCall25c62572019-06-10 14:26:21 +0000575 {"firstTriggerCharacter", "\n"},
Sam McCall0930ab02017-11-07 15:49:35 +0000576 {"moreTriggerCharacter", {}},
577 }},
Haojian Wu08d93f12019-08-22 14:53:45 +0000578 {"codeActionProvider", std::move(CodeActionProvider)},
Sam McCall0930ab02017-11-07 15:49:35 +0000579 {"completionProvider",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000580 llvm::json::Object{
Kirill Bobyrev2a095ff2020-02-18 17:55:12 +0100581 {"allCommitCharacters", " \t()[]{}<>:;,+-/*%^&#?.=\"'|"},
Sam McCall0930ab02017-11-07 15:49:35 +0000582 {"resolveProvider", false},
Ilya Biryukovb0826bd2019-01-03 13:37:12 +0000583 // We do extra checks for '>' and ':' in completion to only
584 // trigger on '->' and '::'.
Sam McCall0930ab02017-11-07 15:49:35 +0000585 {"triggerCharacters", {".", ">", ":"}},
586 }},
587 {"signatureHelpProvider",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000588 llvm::json::Object{
Sam McCall0930ab02017-11-07 15:49:35 +0000589 {"triggerCharacters", {"(", ","}},
590 }},
Sam McCall866ba2c2019-02-01 11:26:13 +0000591 {"declarationProvider", true},
Sam McCall0930ab02017-11-07 15:49:35 +0000592 {"definitionProvider", true},
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000593 {"documentHighlightProvider", true},
Sam McCall8d7ecc12019-12-16 19:08:51 +0100594 {"documentLinkProvider",
595 llvm::json::Object{
596 {"resolveProvider", false},
597 }},
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000598 {"hoverProvider", true},
Haojian Wuf429ab62019-07-24 07:49:23 +0000599 {"renameProvider", std::move(RenameProvider)},
Utkarsh Saxena55925da2019-09-24 13:38:33 +0000600 {"selectionRangeProvider", true},
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000601 {"documentSymbolProvider", true},
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000602 {"workspaceSymbolProvider", true},
Sam McCall1ad142f2018-09-05 11:53:07 +0000603 {"referencesProvider", true},
Sam McCall0930ab02017-11-07 15:49:35 +0000604 {"executeCommandProvider",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000605 llvm::json::Object{
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000606 {"commands",
607 {ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND,
608 ExecuteCommandParams::CLANGD_APPLY_TWEAK}},
Sam McCall0930ab02017-11-07 15:49:35 +0000609 }},
Kadir Cetinkaya86658022019-03-19 09:27:04 +0000610 {"typeHierarchyProvider", true},
Sam McCalla69698f2019-03-27 17:47:49 +0000611 }}}};
612 if (NegotiatedOffsetEncoding)
613 Result["offsetEncoding"] = *NegotiatedOffsetEncoding;
Johan Vikstroma848dab2019-07-04 07:53:12 +0000614 if (Params.capabilities.SemanticHighlighting)
615 Result.getObject("capabilities")
616 ->insert(
617 {"semanticHighlighting",
Haojian Wu1ca2ee42019-07-04 12:27:21 +0000618 llvm::json::Object{{"scopes", buildHighlightScopeLookupTable()}}});
Sam McCalla69698f2019-03-27 17:47:49 +0000619 Reply(std::move(Result));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000620}
621
Sam McCall8a2d2942020-03-03 12:12:14 +0100622void ClangdLSPServer::onInitialized(const InitializedParams &Params) {}
623
Sam McCall2c30fbc2018-10-18 12:32:04 +0000624void ClangdLSPServer::onShutdown(const ShutdownParams &Params,
625 Callback<std::nullptr_t> Reply) {
Ilya Biryukov0d9b8a32017-10-25 08:45:41 +0000626 // Do essentially nothing, just say we're ready to exit.
627 ShutdownRequestReceived = true;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000628 Reply(nullptr);
Sam McCall8a5dded2017-10-12 13:29:58 +0000629}
Ilya Biryukovafb55542017-05-16 14:40:30 +0000630
Sam McCall422c8282018-11-26 16:00:11 +0000631// sync is a clangd extension: it blocks until all background work completes.
632// It blocks the calling thread, so no messages are processed until it returns!
633void ClangdLSPServer::onSync(const NoParams &Params,
634 Callback<std::nullptr_t> Reply) {
635 if (Server->blockUntilIdleForTest(/*TimeoutSeconds=*/60))
636 Reply(nullptr);
637 else
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000638 Reply(llvm::createStringError(llvm::inconvertibleErrorCode(),
639 "Not idle after a minute"));
Sam McCall422c8282018-11-26 16:00:11 +0000640}
641
Sam McCall2c30fbc2018-10-18 12:32:04 +0000642void ClangdLSPServer::onDocumentDidOpen(
643 const DidOpenTextDocumentParams &Params) {
Simon Marchi9569fd52018-03-16 14:30:42 +0000644 PathRef File = Params.textDocument.uri.file();
Ilya Biryukovb10ef472018-06-13 09:20:41 +0000645
Sam McCall2c30fbc2018-10-18 12:32:04 +0000646 const std::string &Contents = Params.textDocument.text;
Simon Marchi9569fd52018-03-16 14:30:42 +0000647
Sam McCall2cd33e62020-03-04 00:33:29 +0100648 auto Version = DraftMgr.addDraft(File, Params.textDocument.version, Contents);
649 Server->addDocument(File, Contents, encodeVersion(Version),
650 WantDiagnostics::Yes);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000651}
652
Sam McCall2c30fbc2018-10-18 12:32:04 +0000653void ClangdLSPServer::onDocumentDidChange(
654 const DidChangeTextDocumentParams &Params) {
Eric Liu51fed182018-02-22 18:40:39 +0000655 auto WantDiags = WantDiagnostics::Auto;
656 if (Params.wantDiagnostics.hasValue())
657 WantDiags = Params.wantDiagnostics.getValue() ? WantDiagnostics::Yes
658 : WantDiagnostics::No;
Simon Marchi9569fd52018-03-16 14:30:42 +0000659
660 PathRef File = Params.textDocument.uri.file();
Sam McCallcaf5a4d2020-03-03 15:57:39 +0100661 llvm::Expected<DraftStore::Draft> Draft = DraftMgr.updateDraft(
662 File, Params.textDocument.version, Params.contentChanges);
663 if (!Draft) {
Simon Marchi98082622018-03-26 14:41:40 +0000664 // If this fails, we are most likely going to be not in sync anymore with
665 // the client. It is better to remove the draft and let further operations
666 // fail rather than giving wrong results.
667 DraftMgr.removeDraft(File);
Ilya Biryukov652364b2018-09-26 05:48:29 +0000668 Server->removeDocument(File);
Sam McCallcaf5a4d2020-03-03 15:57:39 +0100669 elog("Failed to update {0}: {1}", File, Draft.takeError());
Simon Marchi98082622018-03-26 14:41:40 +0000670 return;
671 }
Simon Marchi9569fd52018-03-16 14:30:42 +0000672
Sam McCall2cd33e62020-03-04 00:33:29 +0100673 Server->addDocument(File, Draft->Contents, encodeVersion(Draft->Version),
674 WantDiags, Params.forceRebuild);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000675}
676
Sam McCall2c30fbc2018-10-18 12:32:04 +0000677void ClangdLSPServer::onFileEvent(const DidChangeWatchedFilesParams &Params) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000678 Server->onFileEvent(Params);
Marc-Andre Laperlebf114242017-10-02 18:00:37 +0000679}
680
Sam McCall2c30fbc2018-10-18 12:32:04 +0000681void ClangdLSPServer::onCommand(const ExecuteCommandParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000682 Callback<llvm::json::Value> Reply) {
Ilya Biryukov12864002019-08-16 12:46:41 +0000683 auto ApplyEdit = [this](WorkspaceEdit WE, std::string SuccessMessage,
684 decltype(Reply) Reply) {
Eric Liuc5105f92018-02-16 14:15:55 +0000685 ApplyWorkspaceEditParams Edit;
686 Edit.edit = std::move(WE);
Ilya Biryukov12864002019-08-16 12:46:41 +0000687 call<ApplyWorkspaceEditResponse>(
688 "workspace/applyEdit", std::move(Edit),
689 [Reply = std::move(Reply), SuccessMessage = std::move(SuccessMessage)](
690 llvm::Expected<ApplyWorkspaceEditResponse> Response) mutable {
691 if (!Response)
692 return Reply(Response.takeError());
693 if (!Response->applied) {
694 std::string Reason = Response->failureReason
695 ? *Response->failureReason
696 : "unknown reason";
697 return Reply(llvm::createStringError(
698 llvm::inconvertibleErrorCode(),
699 ("edits were not applied: " + Reason).c_str()));
700 }
701 return Reply(SuccessMessage);
702 });
Eric Liuc5105f92018-02-16 14:15:55 +0000703 };
Ilya Biryukov12864002019-08-16 12:46:41 +0000704
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000705 if (Params.command == ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND &&
706 Params.workspaceEdit) {
707 // The flow for "apply-fix" :
708 // 1. We publish a diagnostic, including fixits
709 // 2. The user clicks on the diagnostic, the editor asks us for code actions
710 // 3. We send code actions, with the fixit embedded as context
711 // 4. The user selects the fixit, the editor asks us to apply it
712 // 5. We unwrap the changes and send them back to the editor
Haojian Wuf2516342019-08-05 12:48:09 +0000713 // 6. The editor applies the changes (applyEdit), and sends us a reply
714 // 7. We unwrap the reply and send a reply to the editor.
Ilya Biryukov12864002019-08-16 12:46:41 +0000715 ApplyEdit(*Params.workspaceEdit, "Fix applied.", std::move(Reply));
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000716 } else if (Params.command == ExecuteCommandParams::CLANGD_APPLY_TWEAK &&
717 Params.tweakArgs) {
718 auto Code = DraftMgr.getDraft(Params.tweakArgs->file.file());
719 if (!Code)
720 return Reply(llvm::createStringError(
721 llvm::inconvertibleErrorCode(),
722 "trying to apply a code action for a non-added file"));
723
Ilya Biryukov12864002019-08-16 12:46:41 +0000724 auto Action = [this, ApplyEdit, Reply = std::move(Reply),
725 File = Params.tweakArgs->file, Code = std::move(*Code)](
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000726 llvm::Expected<Tweak::Effect> R) mutable {
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000727 if (!R)
728 return Reply(R.takeError());
729
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000730 assert(R->ShowMessage ||
731 (!R->ApplyEdits.empty() && "tweak has no effect"));
Ilya Biryukov12864002019-08-16 12:46:41 +0000732
Sam McCall395fde72019-06-18 13:37:54 +0000733 if (R->ShowMessage) {
734 ShowMessageParams Msg;
735 Msg.message = *R->ShowMessage;
736 Msg.type = MessageType::Info;
737 notify("window/showMessage", Msg);
738 }
Ilya Biryukov12864002019-08-16 12:46:41 +0000739 // When no edit is specified, make sure we Reply().
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000740 if (R->ApplyEdits.empty())
741 return Reply("Tweak applied.");
742
Haojian Wu852bafa2019-10-23 14:40:20 +0200743 if (auto Err = validateEdits(DraftMgr, R->ApplyEdits))
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000744 return Reply(std::move(Err));
745
746 WorkspaceEdit WE;
747 WE.changes.emplace();
748 for (const auto &It : R->ApplyEdits) {
Kadir Cetinkayae95e5162019-10-02 09:12:01 +0000749 (*WE.changes)[URI::createFile(It.first()).toString()] =
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000750 It.second.asTextEdits();
751 }
752 // ApplyEdit will take care of calling Reply().
753 return ApplyEdit(std::move(WE), "Tweak applied.", std::move(Reply));
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000754 };
755 Server->applyTweak(Params.tweakArgs->file.file(),
756 Params.tweakArgs->selection, Params.tweakArgs->tweakID,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000757 std::move(Action));
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000758 } else {
759 // We should not get here because ExecuteCommandParams would not have
760 // parsed in the first place and this handler should not be called. But if
761 // more commands are added, this will be here has a safe guard.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000762 Reply(llvm::make_error<LSPError>(
763 llvm::formatv("Unsupported command \"{0}\".", Params.command).str(),
Sam McCall2c30fbc2018-10-18 12:32:04 +0000764 ErrorCode::InvalidParams));
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000765 }
766}
767
Sam McCall2c30fbc2018-10-18 12:32:04 +0000768void ClangdLSPServer::onWorkspaceSymbol(
769 const WorkspaceSymbolParams &Params,
770 Callback<std::vector<SymbolInformation>> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000771 Server->workspaceSymbols(
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000772 Params.query, CCOpts.Limit,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000773 [Reply = std::move(Reply),
774 this](llvm::Expected<std::vector<SymbolInformation>> Items) mutable {
775 if (!Items)
776 return Reply(Items.takeError());
777 for (auto &Sym : *Items)
778 Sym.kind = adjustKindToCapability(Sym.kind, SupportedSymbolKinds);
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000779
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000780 Reply(std::move(*Items));
781 });
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000782}
783
Haojian Wuf429ab62019-07-24 07:49:23 +0000784void ClangdLSPServer::onPrepareRename(const TextDocumentPositionParams &Params,
785 Callback<llvm::Optional<Range>> Reply) {
786 Server->prepareRename(Params.textDocument.uri.file(), Params.position,
Haojian Wu34d0e1b2020-02-19 15:37:36 +0100787 RenameOpts, std::move(Reply));
Haojian Wuf429ab62019-07-24 07:49:23 +0000788}
789
Sam McCall2c30fbc2018-10-18 12:32:04 +0000790void ClangdLSPServer::onRename(const RenameParams &Params,
791 Callback<WorkspaceEdit> Reply) {
Benjamin Krameradcd0262020-01-28 20:23:46 +0100792 Path File = std::string(Params.textDocument.uri.file());
Sam McCallcaf5a4d2020-03-03 15:57:39 +0100793 if (!DraftMgr.getDraft(File))
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000794 return Reply(llvm::make_error<LSPError>(
795 "onRename called for non-added file", ErrorCode::InvalidParams));
Haojian Wu852bafa2019-10-23 14:40:20 +0200796 Server->rename(
Haojian Wu34d0e1b2020-02-19 15:37:36 +0100797 File, Params.position, Params.newName, RenameOpts,
Haojian Wu852bafa2019-10-23 14:40:20 +0200798 [File, Params, Reply = std::move(Reply),
799 this](llvm::Expected<FileEdits> Edits) mutable {
800 if (!Edits)
801 return Reply(Edits.takeError());
802 if (auto Err = validateEdits(DraftMgr, *Edits))
803 return Reply(std::move(Err));
804 WorkspaceEdit Result;
805 Result.changes.emplace();
806 for (const auto &Rep : *Edits) {
807 (*Result.changes)[URI::createFile(Rep.first()).toString()] =
808 Rep.second.asTextEdits();
809 }
810 Reply(Result);
811 });
Haojian Wu345099c2017-11-09 11:30:04 +0000812}
813
Sam McCall2c30fbc2018-10-18 12:32:04 +0000814void ClangdLSPServer::onDocumentDidClose(
815 const DidCloseTextDocumentParams &Params) {
Simon Marchi9569fd52018-03-16 14:30:42 +0000816 PathRef File = Params.textDocument.uri.file();
817 DraftMgr.removeDraft(File);
Ilya Biryukov652364b2018-09-26 05:48:29 +0000818 Server->removeDocument(File);
Ilya Biryukov49c10712019-03-25 10:15:11 +0000819
820 {
821 std::lock_guard<std::mutex> Lock(FixItsMutex);
822 FixItsMap.erase(File);
823 }
Johan Vikstromc2653ef22019-08-01 08:08:44 +0000824 {
825 std::lock_guard<std::mutex> HLock(HighlightingsMutex);
826 FileToHighlightings.erase(File);
827 }
Ilya Biryukov49c10712019-03-25 10:15:11 +0000828 // clangd will not send updates for this file anymore, so we empty out the
829 // list of diagnostics shown on the client (e.g. in the "Problems" pane of
830 // VSCode). Note that this cannot race with actual diagnostics responses
831 // because removeDocument() guarantees no diagnostic callbacks will be
832 // executed after it returns.
Sam McCall6525a6b2020-03-03 12:44:40 +0100833 PublishDiagnosticsParams Notification;
834 Notification.uri = URIForFile::canonicalize(File, /*TUPath=*/File);
835 publishDiagnostics(Notification);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000836}
837
Sam McCall4db732a2017-09-30 10:08:52 +0000838void ClangdLSPServer::onDocumentOnTypeFormatting(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000839 const DocumentOnTypeFormattingParams &Params,
840 Callback<std::vector<TextEdit>> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000841 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000842 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000843 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000844 return Reply(llvm::make_error<LSPError>(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000845 "onDocumentOnTypeFormatting called for non-added file",
846 ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000847
Sam McCallcaf5a4d2020-03-03 15:57:39 +0100848 Reply(Server->formatOnType(Code->Contents, File, Params.position, Params.ch));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000849}
850
Sam McCall4db732a2017-09-30 10:08:52 +0000851void ClangdLSPServer::onDocumentRangeFormatting(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000852 const DocumentRangeFormattingParams &Params,
853 Callback<std::vector<TextEdit>> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000854 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000855 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000856 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000857 return Reply(llvm::make_error<LSPError>(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000858 "onDocumentRangeFormatting called for non-added file",
859 ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000860
Sam McCallcaf5a4d2020-03-03 15:57:39 +0100861 auto ReplacementsOrError =
862 Server->formatRange(Code->Contents, File, Params.range);
Raoul Wols212bcf82017-12-12 20:25:06 +0000863 if (ReplacementsOrError)
Sam McCallcaf5a4d2020-03-03 15:57:39 +0100864 Reply(replacementsToEdits(Code->Contents, ReplacementsOrError.get()));
Raoul Wols212bcf82017-12-12 20:25:06 +0000865 else
Sam McCall2c30fbc2018-10-18 12:32:04 +0000866 Reply(ReplacementsOrError.takeError());
Ilya Biryukovafb55542017-05-16 14:40:30 +0000867}
868
Sam McCall2c30fbc2018-10-18 12:32:04 +0000869void ClangdLSPServer::onDocumentFormatting(
870 const DocumentFormattingParams &Params,
871 Callback<std::vector<TextEdit>> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000872 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000873 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000874 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000875 return Reply(llvm::make_error<LSPError>(
876 "onDocumentFormatting called for non-added file",
877 ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000878
Sam McCallcaf5a4d2020-03-03 15:57:39 +0100879 auto ReplacementsOrError = Server->formatFile(Code->Contents, File);
Raoul Wols212bcf82017-12-12 20:25:06 +0000880 if (ReplacementsOrError)
Sam McCallcaf5a4d2020-03-03 15:57:39 +0100881 Reply(replacementsToEdits(Code->Contents, ReplacementsOrError.get()));
Raoul Wols212bcf82017-12-12 20:25:06 +0000882 else
Sam McCall2c30fbc2018-10-18 12:32:04 +0000883 Reply(ReplacementsOrError.takeError());
Sam McCall4db732a2017-09-30 10:08:52 +0000884}
885
Ilya Biryukov19d75602018-11-23 15:21:19 +0000886/// The functions constructs a flattened view of the DocumentSymbol hierarchy.
887/// Used by the clients that do not support the hierarchical view.
888static std::vector<SymbolInformation>
889flattenSymbolHierarchy(llvm::ArrayRef<DocumentSymbol> Symbols,
890 const URIForFile &FileURI) {
891
892 std::vector<SymbolInformation> Results;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000893 std::function<void(const DocumentSymbol &, llvm::StringRef)> Process =
894 [&](const DocumentSymbol &S, llvm::Optional<llvm::StringRef> ParentName) {
Ilya Biryukov19d75602018-11-23 15:21:19 +0000895 SymbolInformation SI;
Benjamin Krameradcd0262020-01-28 20:23:46 +0100896 SI.containerName = std::string(ParentName ? "" : *ParentName);
Ilya Biryukov19d75602018-11-23 15:21:19 +0000897 SI.name = S.name;
898 SI.kind = S.kind;
899 SI.location.range = S.range;
900 SI.location.uri = FileURI;
901
902 Results.push_back(std::move(SI));
903 std::string FullName =
904 !ParentName ? S.name : (ParentName->str() + "::" + S.name);
905 for (auto &C : S.children)
906 Process(C, /*ParentName=*/FullName);
907 };
908 for (auto &S : Symbols)
909 Process(S, /*ParentName=*/"");
910 return Results;
911}
912
913void ClangdLSPServer::onDocumentSymbol(const DocumentSymbolParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000914 Callback<llvm::json::Value> Reply) {
Ilya Biryukov19d75602018-11-23 15:21:19 +0000915 URIForFile FileURI = Params.textDocument.uri;
Ilya Biryukov652364b2018-09-26 05:48:29 +0000916 Server->documentSymbols(
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000917 Params.textDocument.uri.file(),
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000918 [this, FileURI, Reply = std::move(Reply)](
919 llvm::Expected<std::vector<DocumentSymbol>> Items) mutable {
920 if (!Items)
921 return Reply(Items.takeError());
922 adjustSymbolKinds(*Items, SupportedSymbolKinds);
923 if (SupportsHierarchicalDocumentSymbol)
924 return Reply(std::move(*Items));
925 else
926 return Reply(flattenSymbolHierarchy(*Items, FileURI));
927 });
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000928}
929
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000930static llvm::Optional<Command> asCommand(const CodeAction &Action) {
Sam McCall20841d42018-10-16 16:29:41 +0000931 Command Cmd;
932 if (Action.command && Action.edit)
Sam McCallc008af62018-10-20 15:30:37 +0000933 return None; // Not representable. (We never emit these anyway).
Sam McCall20841d42018-10-16 16:29:41 +0000934 if (Action.command) {
935 Cmd = *Action.command;
936 } else if (Action.edit) {
Benjamin Krameradcd0262020-01-28 20:23:46 +0100937 Cmd.command = std::string(Command::CLANGD_APPLY_FIX_COMMAND);
Sam McCall20841d42018-10-16 16:29:41 +0000938 Cmd.workspaceEdit = *Action.edit;
939 } else {
Sam McCallc008af62018-10-20 15:30:37 +0000940 return None;
Sam McCall20841d42018-10-16 16:29:41 +0000941 }
942 Cmd.title = Action.title;
943 if (Action.kind && *Action.kind == CodeAction::QUICKFIX_KIND)
944 Cmd.title = "Apply fix: " + Cmd.title;
945 return Cmd;
946}
947
Sam McCall2c30fbc2018-10-18 12:32:04 +0000948void ClangdLSPServer::onCodeAction(const CodeActionParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000949 Callback<llvm::json::Value> Reply) {
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000950 URIForFile File = Params.textDocument.uri;
951 auto Code = DraftMgr.getDraft(File.file());
Sam McCall2c30fbc2018-10-18 12:32:04 +0000952 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000953 return Reply(llvm::make_error<LSPError>(
954 "onCodeAction called for non-added file", ErrorCode::InvalidParams));
Sam McCall20841d42018-10-16 16:29:41 +0000955 // We provide a code action for Fixes on the specified diagnostics.
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000956 std::vector<CodeAction> FixIts;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000957 for (const Diagnostic &D : Params.context.diagnostics) {
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000958 for (auto &F : getFixes(File.file(), D)) {
959 FixIts.push_back(toCodeAction(F, Params.textDocument.uri));
960 FixIts.back().diagnostics = {D};
Sam McCalldd0566b2017-11-06 15:40:30 +0000961 }
Ilya Biryukovafb55542017-05-16 14:40:30 +0000962 }
Sam McCall20841d42018-10-16 16:29:41 +0000963
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000964 // Now enumerate the semantic code actions.
965 auto ConsumeActions =
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000966 [Reply = std::move(Reply), File, Code = std::move(*Code),
967 Selection = Params.range, FixIts = std::move(FixIts), this](
968 llvm::Expected<std::vector<ClangdServer::TweakRef>> Tweaks) mutable {
Ilya Biryukovc6ed7782019-01-30 14:24:17 +0000969 if (!Tweaks)
970 return Reply(Tweaks.takeError());
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000971
972 std::vector<CodeAction> Actions = std::move(FixIts);
973 Actions.reserve(Actions.size() + Tweaks->size());
974 for (const auto &T : *Tweaks)
975 Actions.push_back(toCodeAction(T, File, Selection));
976
977 if (SupportsCodeAction)
978 return Reply(llvm::json::Array(Actions));
979 std::vector<Command> Commands;
980 for (const auto &Action : Actions) {
981 if (auto Command = asCommand(Action))
982 Commands.push_back(std::move(*Command));
983 }
984 return Reply(llvm::json::Array(Commands));
985 };
986
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000987 Server->enumerateTweaks(File.file(), Params.range, std::move(ConsumeActions));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000988}
989
Ilya Biryukovb0826bd2019-01-03 13:37:12 +0000990void ClangdLSPServer::onCompletion(const CompletionParams &Params,
Sam McCall2c30fbc2018-10-18 12:32:04 +0000991 Callback<CompletionList> Reply) {
Ilya Biryukova7a11472019-06-07 16:24:38 +0000992 if (!shouldRunCompletion(Params)) {
993 // Clients sometimes auto-trigger completions in undesired places (e.g.
994 // 'a >^ '), we return empty results in those cases.
995 vlog("ignored auto-triggered completion, preceding char did not match");
996 return Reply(CompletionList());
997 }
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000998 Server->codeComplete(Params.textDocument.uri.file(), Params.position, CCOpts,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000999 [Reply = std::move(Reply),
1000 this](llvm::Expected<CodeCompleteResult> List) mutable {
1001 if (!List)
1002 return Reply(List.takeError());
1003 CompletionList LSPList;
1004 LSPList.isIncomplete = List->HasMore;
1005 for (const auto &R : List->Completions) {
1006 CompletionItem C = R.render(CCOpts);
1007 C.kind = adjustKindToCapability(
1008 C.kind, SupportedCompletionItemKinds);
1009 LSPList.items.push_back(std::move(C));
1010 }
1011 return Reply(std::move(LSPList));
1012 });
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +00001013}
1014
Sam McCall2c30fbc2018-10-18 12:32:04 +00001015void ClangdLSPServer::onSignatureHelp(const TextDocumentPositionParams &Params,
1016 Callback<SignatureHelp> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +00001017 Server->signatureHelp(Params.textDocument.uri.file(), Params.position,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001018 [Reply = std::move(Reply), this](
1019 llvm::Expected<SignatureHelp> Signature) mutable {
1020 if (!Signature)
1021 return Reply(Signature.takeError());
1022 if (SupportsOffsetsInSignatureHelp)
1023 return Reply(std::move(*Signature));
1024 // Strip out the offsets from signature help for
1025 // clients that only support string labels.
1026 for (auto &SigInfo : Signature->signatures) {
1027 for (auto &Param : SigInfo.parameters)
1028 Param.labelOffsets.reset();
1029 }
1030 return Reply(std::move(*Signature));
1031 });
Ilya Biryukov652364b2018-09-26 05:48:29 +00001032}
1033
Sam McCall0dbab7f2019-02-02 05:56:00 +00001034// Go to definition has a toggle function: if def and decl are distinct, then
1035// the first press gives you the def, the second gives you the matching def.
1036// getToggle() returns the counterpart location that under the cursor.
1037//
1038// We return the toggled location alone (ignoring other symbols) to encourage
1039// editors to "bounce" quickly between locations, without showing a menu.
1040static Location *getToggle(const TextDocumentPositionParams &Point,
1041 LocatedSymbol &Sym) {
1042 // Toggle only makes sense with two distinct locations.
1043 if (!Sym.Definition || *Sym.Definition == Sym.PreferredDeclaration)
1044 return nullptr;
1045 if (Sym.Definition->uri.file() == Point.textDocument.uri.file() &&
1046 Sym.Definition->range.contains(Point.position))
1047 return &Sym.PreferredDeclaration;
1048 if (Sym.PreferredDeclaration.uri.file() == Point.textDocument.uri.file() &&
1049 Sym.PreferredDeclaration.range.contains(Point.position))
1050 return &*Sym.Definition;
1051 return nullptr;
1052}
1053
Sam McCall2c30fbc2018-10-18 12:32:04 +00001054void ClangdLSPServer::onGoToDefinition(const TextDocumentPositionParams &Params,
1055 Callback<std::vector<Location>> Reply) {
Sam McCall866ba2c2019-02-01 11:26:13 +00001056 Server->locateSymbolAt(
1057 Params.textDocument.uri.file(), Params.position,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001058 [Params, Reply = std::move(Reply)](
1059 llvm::Expected<std::vector<LocatedSymbol>> Symbols) mutable {
1060 if (!Symbols)
1061 return Reply(Symbols.takeError());
1062 std::vector<Location> Defs;
1063 for (auto &S : *Symbols) {
1064 if (Location *Toggle = getToggle(Params, S))
1065 return Reply(std::vector<Location>{std::move(*Toggle)});
1066 Defs.push_back(S.Definition.getValueOr(S.PreferredDeclaration));
1067 }
1068 Reply(std::move(Defs));
1069 });
Sam McCall866ba2c2019-02-01 11:26:13 +00001070}
1071
1072void ClangdLSPServer::onGoToDeclaration(
1073 const TextDocumentPositionParams &Params,
1074 Callback<std::vector<Location>> Reply) {
1075 Server->locateSymbolAt(
1076 Params.textDocument.uri.file(), Params.position,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001077 [Params, Reply = std::move(Reply)](
1078 llvm::Expected<std::vector<LocatedSymbol>> Symbols) mutable {
1079 if (!Symbols)
1080 return Reply(Symbols.takeError());
1081 std::vector<Location> Decls;
1082 for (auto &S : *Symbols) {
1083 if (Location *Toggle = getToggle(Params, S))
1084 return Reply(std::vector<Location>{std::move(*Toggle)});
1085 Decls.push_back(std::move(S.PreferredDeclaration));
1086 }
1087 Reply(std::move(Decls));
1088 });
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +00001089}
1090
Sam McCall111fe842019-05-07 07:55:35 +00001091void ClangdLSPServer::onSwitchSourceHeader(
1092 const TextDocumentIdentifier &Params,
Sam McCallb9ec3e92019-05-07 08:30:32 +00001093 Callback<llvm::Optional<URIForFile>> Reply) {
Haojian Wud6d5edd2019-10-01 10:21:15 +00001094 Server->switchSourceHeader(
1095 Params.uri.file(),
1096 [Reply = std::move(Reply),
1097 Params](llvm::Expected<llvm::Optional<clangd::Path>> Path) mutable {
1098 if (!Path)
1099 return Reply(Path.takeError());
1100 if (*Path)
Haojian Wu77c97002019-10-07 11:37:25 +00001101 return Reply(URIForFile::canonicalize(**Path, Params.uri.file()));
Haojian Wud6d5edd2019-10-01 10:21:15 +00001102 return Reply(llvm::None);
1103 });
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +00001104}
1105
Sam McCall2c30fbc2018-10-18 12:32:04 +00001106void ClangdLSPServer::onDocumentHighlight(
1107 const TextDocumentPositionParams &Params,
1108 Callback<std::vector<DocumentHighlight>> Reply) {
1109 Server->findDocumentHighlights(Params.textDocument.uri.file(),
1110 Params.position, std::move(Reply));
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +00001111}
1112
Sam McCall2c30fbc2018-10-18 12:32:04 +00001113void ClangdLSPServer::onHover(const TextDocumentPositionParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001114 Callback<llvm::Optional<Hover>> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +00001115 Server->findHover(Params.textDocument.uri.file(), Params.position,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001116 [Reply = std::move(Reply), this](
1117 llvm::Expected<llvm::Optional<HoverInfo>> H) mutable {
1118 if (!H)
1119 return Reply(H.takeError());
1120 if (!*H)
1121 return Reply(llvm::None);
Ilya Biryukovf9169d02019-05-29 10:01:00 +00001122
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001123 Hover R;
1124 R.contents.kind = HoverContentFormat;
1125 R.range = (*H)->SymRange;
1126 switch (HoverContentFormat) {
1127 case MarkupKind::PlainText:
Kadir Cetinkaya597c6b62019-12-10 10:28:37 +01001128 R.contents.value = (*H)->present().asPlainText();
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001129 return Reply(std::move(R));
1130 case MarkupKind::Markdown:
Kadir Cetinkaya597c6b62019-12-10 10:28:37 +01001131 R.contents.value = (*H)->present().asMarkdown();
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001132 return Reply(std::move(R));
1133 };
1134 llvm_unreachable("unhandled MarkupKind");
1135 });
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +00001136}
1137
Kadir Cetinkaya86658022019-03-19 09:27:04 +00001138void ClangdLSPServer::onTypeHierarchy(
1139 const TypeHierarchyParams &Params,
1140 Callback<Optional<TypeHierarchyItem>> Reply) {
1141 Server->typeHierarchy(Params.textDocument.uri.file(), Params.position,
1142 Params.resolve, Params.direction, std::move(Reply));
1143}
1144
Nathan Ridge087b0442019-07-13 03:24:48 +00001145void ClangdLSPServer::onResolveTypeHierarchy(
1146 const ResolveTypeHierarchyItemParams &Params,
1147 Callback<Optional<TypeHierarchyItem>> Reply) {
1148 Server->resolveTypeHierarchy(Params.item, Params.resolve, Params.direction,
1149 std::move(Reply));
1150}
1151
Simon Marchi88016782018-08-01 11:28:49 +00001152void ClangdLSPServer::applyConfiguration(
Sam McCallbc904612018-10-25 04:22:52 +00001153 const ConfigurationSettings &Settings) {
Simon Marchiabeed662018-10-16 15:55:03 +00001154 // Per-file update to the compilation database.
David Goldman60249c22020-01-13 17:01:10 -05001155 llvm::StringSet<> ModifiedFiles;
Sam McCallbc904612018-10-25 04:22:52 +00001156 for (auto &Entry : Settings.compilationDatabaseChanges) {
Sam McCallbc904612018-10-25 04:22:52 +00001157 PathRef File = Entry.first;
Sam McCallc55d09a2018-11-02 13:09:36 +00001158 auto Old = CDB->getCompileCommand(File);
1159 auto New =
1160 tooling::CompileCommand(std::move(Entry.second.workingDirectory), File,
1161 std::move(Entry.second.compilationCommand),
1162 /*Output=*/"");
Sam McCall6980edb2018-11-02 14:07:51 +00001163 if (Old != New) {
Sam McCallc55d09a2018-11-02 13:09:36 +00001164 CDB->setCompileCommand(File, std::move(New));
David Goldman60249c22020-01-13 17:01:10 -05001165 ModifiedFiles.insert(File);
Sam McCall6980edb2018-11-02 14:07:51 +00001166 }
Alex Lorenzf8087862018-08-01 17:39:29 +00001167 }
David Goldman60249c22020-01-13 17:01:10 -05001168
1169 reparseOpenedFiles(ModifiedFiles);
Simon Marchi5178f922018-02-22 14:00:39 +00001170}
1171
Johan Vikstroma848dab2019-07-04 07:53:12 +00001172void ClangdLSPServer::publishSemanticHighlighting(
Sam McCall6525a6b2020-03-03 12:44:40 +01001173 const SemanticHighlightingParams &Params) {
Johan Vikstroma848dab2019-07-04 07:53:12 +00001174 notify("textDocument/semanticHighlighting", Params);
1175}
1176
Ilya Biryukov49c10712019-03-25 10:15:11 +00001177void ClangdLSPServer::publishDiagnostics(
Sam McCall6525a6b2020-03-03 12:44:40 +01001178 const PublishDiagnosticsParams &Params) {
1179 notify("textDocument/publishDiagnostics", Params);
Ilya Biryukov49c10712019-03-25 10:15:11 +00001180}
1181
Simon Marchi88016782018-08-01 11:28:49 +00001182// FIXME: This function needs to be properly tested.
1183void ClangdLSPServer::onChangeConfiguration(
Sam McCall2c30fbc2018-10-18 12:32:04 +00001184 const DidChangeConfigurationParams &Params) {
Simon Marchi88016782018-08-01 11:28:49 +00001185 applyConfiguration(Params.settings);
1186}
1187
Sam McCall2c30fbc2018-10-18 12:32:04 +00001188void ClangdLSPServer::onReference(const ReferenceParams &Params,
1189 Callback<std::vector<Location>> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +00001190 Server->findReferences(Params.textDocument.uri.file(), Params.position,
Haojian Wu5181ada2019-11-18 11:35:00 +01001191 CCOpts.Limit,
1192 [Reply = std::move(Reply)](
1193 llvm::Expected<ReferencesResult> Refs) mutable {
1194 if (!Refs)
1195 return Reply(Refs.takeError());
1196 return Reply(std::move(Refs->References));
1197 });
Sam McCall1ad142f2018-09-05 11:53:07 +00001198}
1199
Jan Korousb4067012018-11-27 16:40:46 +00001200void ClangdLSPServer::onSymbolInfo(const TextDocumentPositionParams &Params,
1201 Callback<std::vector<SymbolDetails>> Reply) {
1202 Server->symbolInfo(Params.textDocument.uri.file(), Params.position,
1203 std::move(Reply));
1204}
1205
Utkarsh Saxena55925da2019-09-24 13:38:33 +00001206void ClangdLSPServer::onSelectionRange(
1207 const SelectionRangeParams &Params,
1208 Callback<std::vector<SelectionRange>> Reply) {
1209 if (Params.positions.size() != 1) {
1210 elog("{0} positions provided to SelectionRange. Supports exactly one "
1211 "position.",
1212 Params.positions.size());
1213 return Reply(llvm::make_error<LSPError>(
1214 "SelectionRange supports exactly one position",
1215 ErrorCode::InvalidRequest));
1216 }
1217 Server->semanticRanges(
1218 Params.textDocument.uri.file(), Params.positions[0],
1219 [Reply = std::move(Reply)](
1220 llvm::Expected<std::vector<Range>> Ranges) mutable {
1221 if (!Ranges) {
1222 return Reply(Ranges.takeError());
1223 }
1224 std::vector<SelectionRange> Result;
1225 Result.emplace_back(render(std::move(*Ranges)));
1226 return Reply(std::move(Result));
1227 });
1228}
1229
Sam McCall8d7ecc12019-12-16 19:08:51 +01001230void ClangdLSPServer::onDocumentLink(
1231 const DocumentLinkParams &Params,
1232 Callback<std::vector<DocumentLink>> Reply) {
1233
1234 // TODO(forster): This currently resolves all targets eagerly. This is slow,
1235 // because it blocks on the preamble/AST being built. We could respond to the
1236 // request faster by using string matching or the lexer to find the includes
1237 // and resolving the targets lazily.
1238 Server->documentLinks(
1239 Params.textDocument.uri.file(),
1240 [Reply = std::move(Reply)](
1241 llvm::Expected<std::vector<DocumentLink>> Links) mutable {
1242 if (!Links) {
1243 return Reply(Links.takeError());
1244 }
1245 return Reply(std::move(Links));
1246 });
1247}
1248
Sam McCalla69698f2019-03-27 17:47:49 +00001249ClangdLSPServer::ClangdLSPServer(
1250 class Transport &Transp, const FileSystemProvider &FSProvider,
1251 const clangd::CodeCompleteOptions &CCOpts,
Haojian Wu34d0e1b2020-02-19 15:37:36 +01001252 const clangd::RenameOptions &RenameOpts,
Sam McCalla69698f2019-03-27 17:47:49 +00001253 llvm::Optional<Path> CompileCommandsDir, bool UseDirBasedCDB,
1254 llvm::Optional<OffsetEncoding> ForcedOffsetEncoding,
1255 const ClangdServer::Options &Opts)
Kadir Cetinkaya9d662472019-10-15 14:20:52 +00001256 : BackgroundContext(Context::current().clone()), Transp(Transp),
1257 MsgHandler(new MessageHandler(*this)), FSProvider(FSProvider),
Haojian Wu34d0e1b2020-02-19 15:37:36 +01001258 CCOpts(CCOpts), RenameOpts(RenameOpts),
1259 SupportedSymbolKinds(defaultSymbolKinds()),
Kadir Cetinkaya133d46f2018-09-27 17:13:07 +00001260 SupportedCompletionItemKinds(defaultCompletionItemKinds()),
Sam McCallc55d09a2018-11-02 13:09:36 +00001261 UseDirBasedCDB(UseDirBasedCDB),
Sam McCalla69698f2019-03-27 17:47:49 +00001262 CompileCommandsDir(std::move(CompileCommandsDir)), ClangdServerOpts(Opts),
1263 NegotiatedOffsetEncoding(ForcedOffsetEncoding) {
Sam McCall2c30fbc2018-10-18 12:32:04 +00001264 // clang-format off
1265 MsgHandler->bind("initialize", &ClangdLSPServer::onInitialize);
Sam McCall8a2d2942020-03-03 12:12:14 +01001266 MsgHandler->bind("initialized", &ClangdLSPServer::onInitialized);
Sam McCall2c30fbc2018-10-18 12:32:04 +00001267 MsgHandler->bind("shutdown", &ClangdLSPServer::onShutdown);
Sam McCall422c8282018-11-26 16:00:11 +00001268 MsgHandler->bind("sync", &ClangdLSPServer::onSync);
Sam McCall2c30fbc2018-10-18 12:32:04 +00001269 MsgHandler->bind("textDocument/rangeFormatting", &ClangdLSPServer::onDocumentRangeFormatting);
1270 MsgHandler->bind("textDocument/onTypeFormatting", &ClangdLSPServer::onDocumentOnTypeFormatting);
1271 MsgHandler->bind("textDocument/formatting", &ClangdLSPServer::onDocumentFormatting);
1272 MsgHandler->bind("textDocument/codeAction", &ClangdLSPServer::onCodeAction);
1273 MsgHandler->bind("textDocument/completion", &ClangdLSPServer::onCompletion);
1274 MsgHandler->bind("textDocument/signatureHelp", &ClangdLSPServer::onSignatureHelp);
1275 MsgHandler->bind("textDocument/definition", &ClangdLSPServer::onGoToDefinition);
Sam McCall866ba2c2019-02-01 11:26:13 +00001276 MsgHandler->bind("textDocument/declaration", &ClangdLSPServer::onGoToDeclaration);
Sam McCall2c30fbc2018-10-18 12:32:04 +00001277 MsgHandler->bind("textDocument/references", &ClangdLSPServer::onReference);
1278 MsgHandler->bind("textDocument/switchSourceHeader", &ClangdLSPServer::onSwitchSourceHeader);
Haojian Wuf429ab62019-07-24 07:49:23 +00001279 MsgHandler->bind("textDocument/prepareRename", &ClangdLSPServer::onPrepareRename);
Sam McCall2c30fbc2018-10-18 12:32:04 +00001280 MsgHandler->bind("textDocument/rename", &ClangdLSPServer::onRename);
1281 MsgHandler->bind("textDocument/hover", &ClangdLSPServer::onHover);
1282 MsgHandler->bind("textDocument/documentSymbol", &ClangdLSPServer::onDocumentSymbol);
1283 MsgHandler->bind("workspace/executeCommand", &ClangdLSPServer::onCommand);
1284 MsgHandler->bind("textDocument/documentHighlight", &ClangdLSPServer::onDocumentHighlight);
1285 MsgHandler->bind("workspace/symbol", &ClangdLSPServer::onWorkspaceSymbol);
1286 MsgHandler->bind("textDocument/didOpen", &ClangdLSPServer::onDocumentDidOpen);
1287 MsgHandler->bind("textDocument/didClose", &ClangdLSPServer::onDocumentDidClose);
1288 MsgHandler->bind("textDocument/didChange", &ClangdLSPServer::onDocumentDidChange);
1289 MsgHandler->bind("workspace/didChangeWatchedFiles", &ClangdLSPServer::onFileEvent);
1290 MsgHandler->bind("workspace/didChangeConfiguration", &ClangdLSPServer::onChangeConfiguration);
Jan Korousb4067012018-11-27 16:40:46 +00001291 MsgHandler->bind("textDocument/symbolInfo", &ClangdLSPServer::onSymbolInfo);
Kadir Cetinkaya86658022019-03-19 09:27:04 +00001292 MsgHandler->bind("textDocument/typeHierarchy", &ClangdLSPServer::onTypeHierarchy);
Nathan Ridge087b0442019-07-13 03:24:48 +00001293 MsgHandler->bind("typeHierarchy/resolve", &ClangdLSPServer::onResolveTypeHierarchy);
Utkarsh Saxena55925da2019-09-24 13:38:33 +00001294 MsgHandler->bind("textDocument/selectionRange", &ClangdLSPServer::onSelectionRange);
Sam McCall8d7ecc12019-12-16 19:08:51 +01001295 MsgHandler->bind("textDocument/documentLink", &ClangdLSPServer::onDocumentLink);
Sam McCall2c30fbc2018-10-18 12:32:04 +00001296 // clang-format on
1297}
1298
Sam McCall8bda5f22019-10-23 11:11:18 +02001299ClangdLSPServer::~ClangdLSPServer() { IsBeingDestroyed = true;
1300 // Explicitly destroy ClangdServer first, blocking on threads it owns.
1301 // This ensures they don't access any other members.
1302 Server.reset();
1303}
Ilya Biryukov38d79772017-05-16 09:38:59 +00001304
Sam McCalldc8f3cf2018-10-17 07:32:05 +00001305bool ClangdLSPServer::run() {
Ilya Biryukovafb55542017-05-16 14:40:30 +00001306 // Run the Language Server loop.
Sam McCalldc8f3cf2018-10-17 07:32:05 +00001307 bool CleanExit = true;
Sam McCall2c30fbc2018-10-18 12:32:04 +00001308 if (auto Err = Transp.loop(*MsgHandler)) {
Sam McCalldc8f3cf2018-10-17 07:32:05 +00001309 elog("Transport error: {0}", std::move(Err));
1310 CleanExit = false;
1311 }
Ilya Biryukovafb55542017-05-16 14:40:30 +00001312
Sam McCalldc8f3cf2018-10-17 07:32:05 +00001313 return CleanExit && ShutdownRequestReceived;
Ilya Biryukov38d79772017-05-16 09:38:59 +00001314}
1315
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001316std::vector<Fix> ClangdLSPServer::getFixes(llvm::StringRef File,
Ilya Biryukov71028b82018-03-12 15:28:22 +00001317 const clangd::Diagnostic &D) {
Ilya Biryukov38d79772017-05-16 09:38:59 +00001318 std::lock_guard<std::mutex> Lock(FixItsMutex);
1319 auto DiagToFixItsIter = FixItsMap.find(File);
1320 if (DiagToFixItsIter == FixItsMap.end())
1321 return {};
1322
1323 const auto &DiagToFixItsMap = DiagToFixItsIter->second;
1324 auto FixItsIter = DiagToFixItsMap.find(D);
1325 if (FixItsIter == DiagToFixItsMap.end())
1326 return {};
1327
1328 return FixItsIter->second;
1329}
1330
Ilya Biryukovb0826bd2019-01-03 13:37:12 +00001331bool ClangdLSPServer::shouldRunCompletion(
1332 const CompletionParams &Params) const {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001333 llvm::StringRef Trigger = Params.context.triggerCharacter;
Ilya Biryukovb0826bd2019-01-03 13:37:12 +00001334 if (Params.context.triggerKind != CompletionTriggerKind::TriggerCharacter ||
1335 (Trigger != ">" && Trigger != ":"))
1336 return true;
1337
1338 auto Code = DraftMgr.getDraft(Params.textDocument.uri.file());
1339 if (!Code)
1340 return true; // completion code will log the error for untracked doc.
1341
1342 // A completion request is sent when the user types '>' or ':', but we only
1343 // want to trigger on '->' and '::'. We check the preceeding character to make
1344 // sure it matches what we expected.
1345 // Running the lexer here would be more robust (e.g. we can detect comments
1346 // and avoid triggering completion there), but we choose to err on the side
1347 // of simplicity here.
Sam McCallcaf5a4d2020-03-03 15:57:39 +01001348 auto Offset = positionToOffset(Code->Contents, Params.position,
Ilya Biryukovb0826bd2019-01-03 13:37:12 +00001349 /*AllowColumnsBeyondLineLength=*/false);
1350 if (!Offset) {
1351 vlog("could not convert position '{0}' to offset for file '{1}'",
1352 Params.position, Params.textDocument.uri.file());
1353 return true;
1354 }
1355 if (*Offset < 2)
1356 return false;
1357
1358 if (Trigger == ">")
Sam McCallcaf5a4d2020-03-03 15:57:39 +01001359 return Code->Contents[*Offset - 2] == '-'; // trigger only on '->'.
Ilya Biryukovb0826bd2019-01-03 13:37:12 +00001360 if (Trigger == ":")
Sam McCallcaf5a4d2020-03-03 15:57:39 +01001361 return Code->Contents[*Offset - 2] == ':'; // trigger only on '::'.
Ilya Biryukovb0826bd2019-01-03 13:37:12 +00001362 assert(false && "unhandled trigger character");
1363 return true;
1364}
1365
Johan Vikstroma848dab2019-07-04 07:53:12 +00001366void ClangdLSPServer::onHighlightingsReady(
Sam McCall2cd33e62020-03-04 00:33:29 +01001367 PathRef File, llvm::StringRef Version,
1368 std::vector<HighlightingToken> Highlightings) {
Johan Vikstromc2653ef22019-08-01 08:08:44 +00001369 std::vector<HighlightingToken> Old;
1370 std::vector<HighlightingToken> HighlightingsCopy = Highlightings;
1371 {
1372 std::lock_guard<std::mutex> Lock(HighlightingsMutex);
1373 Old = std::move(FileToHighlightings[File]);
1374 FileToHighlightings[File] = std::move(HighlightingsCopy);
1375 }
1376 // LSP allows us to send incremental edits of highlightings. Also need to diff
1377 // to remove highlightings from tokens that should no longer have them.
Haojian Wu0a6000f2019-08-26 08:38:45 +00001378 std::vector<LineHighlightings> Diffed = diffHighlightings(Highlightings, Old);
Sam McCall2cd33e62020-03-04 00:33:29 +01001379 SemanticHighlightingParams Notification;
1380 Notification.TextDocument.uri =
1381 URIForFile::canonicalize(File, /*TUPath=*/File);
1382 Notification.TextDocument.version = decodeVersion(Version);
1383 Notification.Lines = toSemanticHighlightingInformation(Diffed);
1384 publishSemanticHighlighting(Notification);
Johan Vikstroma848dab2019-07-04 07:53:12 +00001385}
1386
Sam McCall2cd33e62020-03-04 00:33:29 +01001387void ClangdLSPServer::onDiagnosticsReady(PathRef File, llvm::StringRef Version,
Sam McCalla7bb0cc2018-03-12 23:22:35 +00001388 std::vector<Diag> Diagnostics) {
Sam McCall6525a6b2020-03-03 12:44:40 +01001389 PublishDiagnosticsParams Notification;
Sam McCall2cd33e62020-03-04 00:33:29 +01001390 Notification.version = decodeVersion(Version);
Sam McCall6525a6b2020-03-03 12:44:40 +01001391 Notification.uri = URIForFile::canonicalize(File, /*TUPath=*/File);
Ilya Biryukov38d79772017-05-16 09:38:59 +00001392 DiagnosticToReplacementMap LocalFixIts; // Temporary storage
Sam McCalla7bb0cc2018-03-12 23:22:35 +00001393 for (auto &Diag : Diagnostics) {
Sam McCall6525a6b2020-03-03 12:44:40 +01001394 toLSPDiags(Diag, Notification.uri, DiagOpts,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001395 [&](clangd::Diagnostic Diag, llvm::ArrayRef<Fix> Fixes) {
Sam McCall16e70702018-10-24 07:59:38 +00001396 auto &FixItsForDiagnostic = LocalFixIts[Diag];
1397 llvm::copy(Fixes, std::back_inserter(FixItsForDiagnostic));
Sam McCall6525a6b2020-03-03 12:44:40 +01001398 Notification.diagnostics.push_back(std::move(Diag));
Sam McCall16e70702018-10-24 07:59:38 +00001399 });
Ilya Biryukov38d79772017-05-16 09:38:59 +00001400 }
1401
1402 // Cache FixIts
1403 {
Ilya Biryukov38d79772017-05-16 09:38:59 +00001404 std::lock_guard<std::mutex> Lock(FixItsMutex);
1405 FixItsMap[File] = LocalFixIts;
1406 }
1407
Ilya Biryukov49c10712019-03-25 10:15:11 +00001408 // Send a notification to the LSP client.
Sam McCall6525a6b2020-03-03 12:44:40 +01001409 publishDiagnostics(Notification);
Ilya Biryukov38d79772017-05-16 09:38:59 +00001410}
Simon Marchi9569fd52018-03-16 14:30:42 +00001411
Sam McCall7d20e802020-01-22 19:41:45 +01001412void ClangdLSPServer::onBackgroundIndexProgress(
1413 const BackgroundQueue::Stats &Stats) {
1414 static const char ProgressToken[] = "backgroundIndexProgress";
1415 std::lock_guard<std::mutex> Lock(BackgroundIndexProgressMutex);
1416
1417 auto NotifyProgress = [this](const BackgroundQueue::Stats &Stats) {
1418 if (BackgroundIndexProgressState != BackgroundIndexProgress::Live) {
1419 WorkDoneProgressBegin Begin;
1420 Begin.percentage = true;
1421 Begin.title = "indexing";
1422 progress(ProgressToken, std::move(Begin));
1423 BackgroundIndexProgressState = BackgroundIndexProgress::Live;
1424 }
1425
1426 if (Stats.Completed < Stats.Enqueued) {
1427 assert(Stats.Enqueued > Stats.LastIdle);
1428 WorkDoneProgressReport Report;
1429 Report.percentage = 100.0 * (Stats.Completed - Stats.LastIdle) /
1430 (Stats.Enqueued - Stats.LastIdle);
1431 Report.message =
1432 llvm::formatv("{0}/{1}", Stats.Completed - Stats.LastIdle,
1433 Stats.Enqueued - Stats.LastIdle);
1434 progress(ProgressToken, std::move(Report));
1435 } else {
1436 assert(Stats.Completed == Stats.Enqueued);
1437 progress(ProgressToken, WorkDoneProgressEnd());
1438 BackgroundIndexProgressState = BackgroundIndexProgress::Empty;
1439 }
1440 };
1441
1442 switch (BackgroundIndexProgressState) {
1443 case BackgroundIndexProgress::Unsupported:
1444 return;
1445 case BackgroundIndexProgress::Creating:
1446 // Cache this update for when the progress bar is available.
1447 PendingBackgroundIndexProgress = Stats;
1448 return;
1449 case BackgroundIndexProgress::Empty: {
1450 if (BackgroundIndexSkipCreate) {
1451 NotifyProgress(Stats);
1452 break;
1453 }
1454 // Cache this update for when the progress bar is available.
1455 PendingBackgroundIndexProgress = Stats;
1456 BackgroundIndexProgressState = BackgroundIndexProgress::Creating;
1457 WorkDoneProgressCreateParams CreateRequest;
1458 CreateRequest.token = ProgressToken;
1459 call<std::nullptr_t>(
1460 "window/workDoneProgress/create", CreateRequest,
1461 [this, NotifyProgress](llvm::Expected<std::nullptr_t> E) {
1462 std::lock_guard<std::mutex> Lock(BackgroundIndexProgressMutex);
1463 if (E) {
1464 NotifyProgress(this->PendingBackgroundIndexProgress);
1465 } else {
1466 elog("Failed to create background index progress bar: {0}",
1467 E.takeError());
1468 // give up forever rather than thrashing about
1469 BackgroundIndexProgressState = BackgroundIndexProgress::Unsupported;
1470 }
1471 });
1472 break;
1473 }
1474 case BackgroundIndexProgress::Live:
1475 NotifyProgress(Stats);
1476 break;
1477 }
1478}
1479
Haojian Wub6188492018-12-20 15:39:12 +00001480void ClangdLSPServer::onFileUpdated(PathRef File, const TUStatus &Status) {
1481 if (!SupportFileStatus)
1482 return;
1483 // FIXME: we don't emit "BuildingFile" and `RunningAction`, as these
1484 // two statuses are running faster in practice, which leads the UI constantly
1485 // changing, and doesn't provide much value. We may want to emit status at a
1486 // reasonable time interval (e.g. 0.5s).
1487 if (Status.Action.S == TUAction::BuildingFile ||
1488 Status.Action.S == TUAction::RunningAction)
1489 return;
1490 notify("textDocument/clangd.fileStatus", Status.render(File));
1491}
1492
David Goldman60249c22020-01-13 17:01:10 -05001493void ClangdLSPServer::reparseOpenedFiles(
1494 const llvm::StringSet<> &ModifiedFiles) {
1495 if (ModifiedFiles.empty())
1496 return;
1497 // Reparse only opened files that were modified.
Simon Marchi9569fd52018-03-16 14:30:42 +00001498 for (const Path &FilePath : DraftMgr.getActiveFiles())
David Goldman60249c22020-01-13 17:01:10 -05001499 if (ModifiedFiles.find(FilePath) != ModifiedFiles.end())
Sam McCall2cd33e62020-03-04 00:33:29 +01001500 if (auto Draft = DraftMgr.getDraft(FilePath)) // else disappeared in race?
1501 Server->addDocument(FilePath, std::move(Draft->Contents),
1502 encodeVersion(Draft->Version),
1503 WantDiagnostics::Auto);
Simon Marchi9569fd52018-03-16 14:30:42 +00001504}
Alex Lorenzf8087862018-08-01 17:39:29 +00001505
Sam McCallc008af62018-10-20 15:30:37 +00001506} // namespace clangd
1507} // namespace clang