blob: 19476d7fa05223701ea69c1385574ca4d816695a [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
Ilya Biryukovafb55542017-05-16 14:40:30 +0000153} // namespace
154
Sam McCall2c30fbc2018-10-18 12:32:04 +0000155// MessageHandler dispatches incoming LSP messages.
156// It handles cross-cutting concerns:
157// - serializes/deserializes protocol objects to JSON
158// - logging of inbound messages
159// - cancellation handling
160// - basic call tracing
Sam McCall3d0adbe2018-10-18 14:41:50 +0000161// MessageHandler ensures that initialize() is called before any other handler.
Sam McCall2c30fbc2018-10-18 12:32:04 +0000162class ClangdLSPServer::MessageHandler : public Transport::MessageHandler {
163public:
164 MessageHandler(ClangdLSPServer &Server) : Server(Server) {}
165
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000166 bool onNotify(llvm::StringRef Method, llvm::json::Value Params) override {
Sam McCalla69698f2019-03-27 17:47:49 +0000167 WithContext HandlerContext(handlerContext());
Sam McCall2c30fbc2018-10-18 12:32:04 +0000168 log("<-- {0}", Method);
169 if (Method == "exit")
170 return false;
Sam McCall3d0adbe2018-10-18 14:41:50 +0000171 if (!Server.Server)
172 elog("Notification {0} before initialization", Method);
173 else if (Method == "$/cancelRequest")
Sam McCall2c30fbc2018-10-18 12:32:04 +0000174 onCancel(std::move(Params));
175 else if (auto Handler = Notifications.lookup(Method))
176 Handler(std::move(Params));
177 else
178 log("unhandled notification {0}", Method);
179 return true;
180 }
181
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000182 bool onCall(llvm::StringRef Method, llvm::json::Value Params,
183 llvm::json::Value ID) override {
Sam McCalla69698f2019-03-27 17:47:49 +0000184 WithContext HandlerContext(handlerContext());
Sam McCalle2f3a732018-10-24 14:26:26 +0000185 // Calls can be canceled by the client. Add cancellation context.
186 WithContext WithCancel(cancelableRequestContext(ID));
187 trace::Span Tracer(Method);
188 SPAN_ATTACH(Tracer, "Params", Params);
189 ReplyOnce Reply(ID, Method, &Server, Tracer.Args);
Sam McCall2c30fbc2018-10-18 12:32:04 +0000190 log("<-- {0}({1})", Method, ID);
Sam McCall3d0adbe2018-10-18 14:41:50 +0000191 if (!Server.Server && Method != "initialize") {
192 elog("Call {0} before initialization.", Method);
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000193 Reply(llvm::make_error<LSPError>("server not initialized",
194 ErrorCode::ServerNotInitialized));
Sam McCall3d0adbe2018-10-18 14:41:50 +0000195 } else if (auto Handler = Calls.lookup(Method))
Sam McCalle2f3a732018-10-24 14:26:26 +0000196 Handler(std::move(Params), std::move(Reply));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000197 else
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000198 Reply(llvm::make_error<LSPError>("method not found",
199 ErrorCode::MethodNotFound));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000200 return true;
201 }
202
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000203 bool onReply(llvm::json::Value ID,
204 llvm::Expected<llvm::json::Value> Result) override {
Sam McCalla69698f2019-03-27 17:47:49 +0000205 WithContext HandlerContext(handlerContext());
Haojian Wuf2516342019-08-05 12:48:09 +0000206
207 Callback<llvm::json::Value> ReplyHandler = nullptr;
208 if (auto IntID = ID.getAsInteger()) {
209 std::lock_guard<std::mutex> Mutex(CallMutex);
210 // Find a corresponding callback for the request ID;
211 for (size_t Index = 0; Index < ReplyCallbacks.size(); ++Index) {
212 if (ReplyCallbacks[Index].first == *IntID) {
213 ReplyHandler = std::move(ReplyCallbacks[Index].second);
214 ReplyCallbacks.erase(ReplyCallbacks.begin() +
215 Index); // remove the entry
216 break;
217 }
218 }
219 }
220
221 if (!ReplyHandler) {
222 // No callback being found, use a default log callback.
223 ReplyHandler = [&ID](llvm::Expected<llvm::json::Value> Result) {
224 elog("received a reply with ID {0}, but there was no such call", ID);
225 if (!Result)
226 llvm::consumeError(Result.takeError());
227 };
228 }
229
230 // Log and run the reply handler.
231 if (Result) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000232 log("<-- reply({0})", ID);
Haojian Wuf2516342019-08-05 12:48:09 +0000233 ReplyHandler(std::move(Result));
234 } else {
235 auto Err = Result.takeError();
236 log("<-- reply({0}) error: {1}", ID, Err);
237 ReplyHandler(std::move(Err));
238 }
Sam McCall2c30fbc2018-10-18 12:32:04 +0000239 return true;
240 }
241
242 // Bind an LSP method name to a call.
Sam McCalle2f3a732018-10-24 14:26:26 +0000243 template <typename Param, typename Result>
Sam McCall2c30fbc2018-10-18 12:32:04 +0000244 void bind(const char *Method,
Sam McCalle2f3a732018-10-24 14:26:26 +0000245 void (ClangdLSPServer::*Handler)(const Param &, Callback<Result>)) {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000246 Calls[Method] = [Method, Handler, this](llvm::json::Value RawParams,
Sam McCalle2f3a732018-10-24 14:26:26 +0000247 ReplyOnce Reply) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000248 Param P;
Sam McCalle2f3a732018-10-24 14:26:26 +0000249 if (fromJSON(RawParams, P)) {
250 (Server.*Handler)(P, std::move(Reply));
251 } else {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000252 elog("Failed to decode {0} request.", Method);
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000253 Reply(llvm::make_error<LSPError>("failed to decode request",
254 ErrorCode::InvalidRequest));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000255 }
Sam McCall2c30fbc2018-10-18 12:32:04 +0000256 };
257 }
258
Haojian Wuf2516342019-08-05 12:48:09 +0000259 // Bind a reply callback to a request. The callback will be invoked when
260 // clangd receives the reply from the LSP client.
261 // Return a call id of the request.
262 llvm::json::Value bindReply(Callback<llvm::json::Value> Reply) {
263 llvm::Optional<std::pair<int, Callback<llvm::json::Value>>> OldestCB;
264 int ID;
265 {
266 std::lock_guard<std::mutex> Mutex(CallMutex);
267 ID = NextCallID++;
268 ReplyCallbacks.emplace_back(ID, std::move(Reply));
269
270 // If the queue overflows, we assume that the client didn't reply the
271 // oldest request, and run the corresponding callback which replies an
272 // error to the client.
273 if (ReplyCallbacks.size() > MaxReplayCallbacks) {
274 elog("more than {0} outstanding LSP calls, forgetting about {1}",
275 MaxReplayCallbacks, ReplyCallbacks.front().first);
276 OldestCB = std::move(ReplyCallbacks.front());
277 ReplyCallbacks.pop_front();
278 }
279 }
280 if (OldestCB)
281 OldestCB->second(llvm::createStringError(
282 llvm::inconvertibleErrorCode(),
283 llvm::formatv("failed to receive a client reply for request ({0})",
284 OldestCB->first)));
285 return ID;
286 }
287
Sam McCall2c30fbc2018-10-18 12:32:04 +0000288 // Bind an LSP method name to a notification.
289 template <typename Param>
290 void bind(const char *Method,
291 void (ClangdLSPServer::*Handler)(const Param &)) {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000292 Notifications[Method] = [Method, Handler,
293 this](llvm::json::Value RawParams) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000294 Param P;
295 if (!fromJSON(RawParams, P)) {
296 elog("Failed to decode {0} request.", Method);
297 return;
298 }
299 trace::Span Tracer(Method);
300 SPAN_ATTACH(Tracer, "Params", RawParams);
301 (Server.*Handler)(P);
302 };
303 }
304
305private:
Sam McCalle2f3a732018-10-24 14:26:26 +0000306 // Function object to reply to an LSP call.
307 // Each instance must be called exactly once, otherwise:
308 // - the bug is logged, and (in debug mode) an assert will fire
309 // - if there was no reply, an error reply is sent
310 // - if there were multiple replies, only the first is sent
311 class ReplyOnce {
312 std::atomic<bool> Replied = {false};
Sam McCalld7babe42018-10-24 15:18:40 +0000313 std::chrono::steady_clock::time_point Start;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000314 llvm::json::Value ID;
Sam McCalle2f3a732018-10-24 14:26:26 +0000315 std::string Method;
316 ClangdLSPServer *Server; // Null when moved-from.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000317 llvm::json::Object *TraceArgs;
Sam McCalle2f3a732018-10-24 14:26:26 +0000318
319 public:
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000320 ReplyOnce(const llvm::json::Value &ID, llvm::StringRef Method,
321 ClangdLSPServer *Server, llvm::json::Object *TraceArgs)
Sam McCalld7babe42018-10-24 15:18:40 +0000322 : Start(std::chrono::steady_clock::now()), ID(ID), Method(Method),
323 Server(Server), TraceArgs(TraceArgs) {
Sam McCalle2f3a732018-10-24 14:26:26 +0000324 assert(Server);
325 }
326 ReplyOnce(ReplyOnce &&Other)
Sam McCalld7babe42018-10-24 15:18:40 +0000327 : Replied(Other.Replied.load()), Start(Other.Start),
328 ID(std::move(Other.ID)), Method(std::move(Other.Method)),
329 Server(Other.Server), TraceArgs(Other.TraceArgs) {
Sam McCalle2f3a732018-10-24 14:26:26 +0000330 Other.Server = nullptr;
331 }
Ilya Biryukov22fa4652019-01-03 13:28:05 +0000332 ReplyOnce &operator=(ReplyOnce &&) = delete;
Sam McCalle2f3a732018-10-24 14:26:26 +0000333 ReplyOnce(const ReplyOnce &) = delete;
Ilya Biryukov22fa4652019-01-03 13:28:05 +0000334 ReplyOnce &operator=(const ReplyOnce &) = delete;
Sam McCalle2f3a732018-10-24 14:26:26 +0000335
336 ~ReplyOnce() {
Haojian Wuf2516342019-08-05 12:48:09 +0000337 // There's one legitimate reason to never reply to a request: clangd's
338 // request handler send a call to the client (e.g. applyEdit) and the
339 // client never replied. In this case, the ReplyOnce is owned by
340 // ClangdLSPServer's reply callback table and is destroyed along with the
341 // server. We don't attempt to send a reply in this case, there's little
342 // to be gained from doing so.
343 if (Server && !Server->IsBeingDestroyed && !Replied) {
Sam McCalle2f3a732018-10-24 14:26:26 +0000344 elog("No reply to message {0}({1})", Method, ID);
345 assert(false && "must reply to all calls!");
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000346 (*this)(llvm::make_error<LSPError>("server failed to reply",
347 ErrorCode::InternalError));
Sam McCalle2f3a732018-10-24 14:26:26 +0000348 }
349 }
350
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000351 void operator()(llvm::Expected<llvm::json::Value> Reply) {
Sam McCalle2f3a732018-10-24 14:26:26 +0000352 assert(Server && "moved-from!");
353 if (Replied.exchange(true)) {
354 elog("Replied twice to message {0}({1})", Method, ID);
355 assert(false && "must reply to each call only once!");
356 return;
357 }
Sam McCalld7babe42018-10-24 15:18:40 +0000358 auto Duration = std::chrono::steady_clock::now() - Start;
359 if (Reply) {
360 log("--> reply:{0}({1}) {2:ms}", Method, ID, Duration);
361 if (TraceArgs)
Sam McCalle2f3a732018-10-24 14:26:26 +0000362 (*TraceArgs)["Reply"] = *Reply;
Sam McCalld7babe42018-10-24 15:18:40 +0000363 std::lock_guard<std::mutex> Lock(Server->TranspWriter);
364 Server->Transp.reply(std::move(ID), std::move(Reply));
365 } else {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000366 llvm::Error Err = Reply.takeError();
Sam McCalld7babe42018-10-24 15:18:40 +0000367 log("--> reply:{0}({1}) {2:ms}, error: {3}", Method, ID, Duration, Err);
368 if (TraceArgs)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000369 (*TraceArgs)["Error"] = llvm::to_string(Err);
Sam McCalld7babe42018-10-24 15:18:40 +0000370 std::lock_guard<std::mutex> Lock(Server->TranspWriter);
371 Server->Transp.reply(std::move(ID), std::move(Err));
Sam McCalle2f3a732018-10-24 14:26:26 +0000372 }
Sam McCalle2f3a732018-10-24 14:26:26 +0000373 }
374 };
375
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000376 llvm::StringMap<std::function<void(llvm::json::Value)>> Notifications;
377 llvm::StringMap<std::function<void(llvm::json::Value, ReplyOnce)>> Calls;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000378
379 // Method calls may be cancelled by ID, so keep track of their state.
380 // This needs a mutex: handlers may finish on a different thread, and that's
381 // when we clean up entries in the map.
382 mutable std::mutex RequestCancelersMutex;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000383 llvm::StringMap<std::pair<Canceler, /*Cookie*/ unsigned>> RequestCancelers;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000384 unsigned NextRequestCookie = 0; // To disambiguate reused IDs, see below.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000385 void onCancel(const llvm::json::Value &Params) {
386 const llvm::json::Value *ID = nullptr;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000387 if (auto *O = Params.getAsObject())
388 ID = O->get("id");
389 if (!ID) {
390 elog("Bad cancellation request: {0}", Params);
391 return;
392 }
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000393 auto StrID = llvm::to_string(*ID);
Sam McCall2c30fbc2018-10-18 12:32:04 +0000394 std::lock_guard<std::mutex> Lock(RequestCancelersMutex);
395 auto It = RequestCancelers.find(StrID);
396 if (It != RequestCancelers.end())
397 It->second.first(); // Invoke the canceler.
398 }
Sam McCalla69698f2019-03-27 17:47:49 +0000399
400 Context handlerContext() const {
401 return Context::current().derive(
402 kCurrentOffsetEncoding,
403 Server.NegotiatedOffsetEncoding.getValueOr(OffsetEncoding::UTF16));
404 }
405
Sam McCall2c30fbc2018-10-18 12:32:04 +0000406 // We run cancelable requests in a context that does two things:
407 // - allows cancellation using RequestCancelers[ID]
408 // - cleans up the entry in RequestCancelers when it's no longer needed
409 // If a client reuses an ID, the last wins and the first cannot be canceled.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000410 Context cancelableRequestContext(const llvm::json::Value &ID) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000411 auto Task = cancelableTask();
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000412 auto StrID = llvm::to_string(ID); // JSON-serialize ID for map key.
Sam McCall2c30fbc2018-10-18 12:32:04 +0000413 auto Cookie = NextRequestCookie++; // No lock, only called on main thread.
414 {
415 std::lock_guard<std::mutex> Lock(RequestCancelersMutex);
416 RequestCancelers[StrID] = {std::move(Task.second), Cookie};
417 }
418 // When the request ends, we can clean up the entry we just added.
419 // The cookie lets us check that it hasn't been overwritten due to ID
420 // reuse.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000421 return Task.first.derive(llvm::make_scope_exit([this, StrID, Cookie] {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000422 std::lock_guard<std::mutex> Lock(RequestCancelersMutex);
423 auto It = RequestCancelers.find(StrID);
424 if (It != RequestCancelers.end() && It->second.second == Cookie)
425 RequestCancelers.erase(It);
426 }));
427 }
428
Kadir Cetinkaya9a3a87d2019-10-09 13:59:31 +0000429 // The maximum number of callbacks held in clangd.
430 //
431 // We bound the maximum size to the pending map to prevent memory leakage
432 // for cases where LSP clients don't reply for the request.
433 // This has to go after RequestCancellers and RequestCancellersMutex since it
434 // can contain a callback that has a cancelable context.
435 static constexpr int MaxReplayCallbacks = 100;
436 mutable std::mutex CallMutex;
437 int NextCallID = 0; /* GUARDED_BY(CallMutex) */
438 std::deque<std::pair</*RequestID*/ int,
439 /*ReplyHandler*/ Callback<llvm::json::Value>>>
440 ReplyCallbacks; /* GUARDED_BY(CallMutex) */
441
Sam McCall2c30fbc2018-10-18 12:32:04 +0000442 ClangdLSPServer &Server;
443};
Haojian Wuf2516342019-08-05 12:48:09 +0000444constexpr int ClangdLSPServer::MessageHandler::MaxReplayCallbacks;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000445
446// call(), notify(), and reply() wrap the Transport, adding logging and locking.
Haojian Wuf2516342019-08-05 12:48:09 +0000447void ClangdLSPServer::callRaw(StringRef Method, llvm::json::Value Params,
448 Callback<llvm::json::Value> CB) {
449 auto ID = MsgHandler->bindReply(std::move(CB));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000450 log("--> {0}({1})", Method, ID);
Sam McCall2c30fbc2018-10-18 12:32:04 +0000451 std::lock_guard<std::mutex> Lock(TranspWriter);
452 Transp.call(Method, std::move(Params), ID);
453}
454
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000455void ClangdLSPServer::notify(llvm::StringRef Method, llvm::json::Value Params) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000456 log("--> {0}", Method);
457 std::lock_guard<std::mutex> Lock(TranspWriter);
458 Transp.notify(Method, std::move(Params));
459}
460
Sam McCall71177ac2020-03-24 02:24:47 +0100461static std::vector<llvm::StringRef> semanticTokenTypes() {
462 std::vector<llvm::StringRef> Types;
463 for (unsigned I = 0; I <= static_cast<unsigned>(HighlightingKind::LastKind);
464 ++I)
465 Types.push_back(toSemanticTokenType(static_cast<HighlightingKind>(I)));
466 return Types;
467}
468
Sam McCall2c30fbc2018-10-18 12:32:04 +0000469void ClangdLSPServer::onInitialize(const InitializeParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000470 Callback<llvm::json::Value> Reply) {
Sam McCalla69698f2019-03-27 17:47:49 +0000471 // Determine character encoding first as it affects constructed ClangdServer.
472 if (Params.capabilities.offsetEncoding && !NegotiatedOffsetEncoding) {
473 NegotiatedOffsetEncoding = OffsetEncoding::UTF16; // fallback
474 for (OffsetEncoding Supported : *Params.capabilities.offsetEncoding)
475 if (Supported != OffsetEncoding::UnsupportedEncoding) {
476 NegotiatedOffsetEncoding = Supported;
477 break;
478 }
479 }
Sam McCalla69698f2019-03-27 17:47:49 +0000480
Sam McCalledf6a192020-03-24 00:31:14 +0100481 ClangdServerOpts.TheiaSemanticHighlighting =
482 Params.capabilities.TheiaSemanticHighlighting;
Sam McCallfc830102020-04-01 12:02:28 +0200483 if (Params.capabilities.TheiaSemanticHighlighting &&
484 Params.capabilities.SemanticTokens) {
485 log("Client supports legacy semanticHighlights notification and standard "
486 "semanticTokens request, choosing the latter (no notifications).");
487 ClangdServerOpts.TheiaSemanticHighlighting = false;
488 }
489
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 }},
Sam McCall71177ac2020-03-24 02:24:47 +0100587 {"semanticTokensProvider",
588 llvm::json::Object{
Sam McCall9e3063e2020-04-01 16:21:44 +0200589 {"documentProvider", llvm::json::Object{{"edits", true}}},
Sam McCall71177ac2020-03-24 02:24:47 +0100590 {"rangeProvider", false},
591 {"legend",
592 llvm::json::Object{{"tokenTypes", semanticTokenTypes()},
593 {"tokenModifiers", llvm::json::Array()}}},
594 }},
Sam McCall0930ab02017-11-07 15:49:35 +0000595 {"signatureHelpProvider",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000596 llvm::json::Object{
Sam McCall0930ab02017-11-07 15:49:35 +0000597 {"triggerCharacters", {"(", ","}},
598 }},
Sam McCall866ba2c2019-02-01 11:26:13 +0000599 {"declarationProvider", true},
Sam McCall0930ab02017-11-07 15:49:35 +0000600 {"definitionProvider", true},
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000601 {"documentHighlightProvider", true},
Sam McCall8d7ecc12019-12-16 19:08:51 +0100602 {"documentLinkProvider",
603 llvm::json::Object{
604 {"resolveProvider", false},
605 }},
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000606 {"hoverProvider", true},
Haojian Wuf429ab62019-07-24 07:49:23 +0000607 {"renameProvider", std::move(RenameProvider)},
Utkarsh Saxena55925da2019-09-24 13:38:33 +0000608 {"selectionRangeProvider", true},
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000609 {"documentSymbolProvider", true},
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000610 {"workspaceSymbolProvider", true},
Sam McCall1ad142f2018-09-05 11:53:07 +0000611 {"referencesProvider", true},
Sam McCall0930ab02017-11-07 15:49:35 +0000612 {"executeCommandProvider",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000613 llvm::json::Object{
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000614 {"commands",
615 {ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND,
616 ExecuteCommandParams::CLANGD_APPLY_TWEAK}},
Sam McCall0930ab02017-11-07 15:49:35 +0000617 }},
Kadir Cetinkaya86658022019-03-19 09:27:04 +0000618 {"typeHierarchyProvider", true},
Sam McCalla69698f2019-03-27 17:47:49 +0000619 }}}};
620 if (NegotiatedOffsetEncoding)
621 Result["offsetEncoding"] = *NegotiatedOffsetEncoding;
Sam McCallfc830102020-04-01 12:02:28 +0200622 if (ClangdServerOpts.TheiaSemanticHighlighting)
Johan Vikstroma848dab2019-07-04 07:53:12 +0000623 Result.getObject("capabilities")
624 ->insert(
625 {"semanticHighlighting",
Haojian Wu1ca2ee42019-07-04 12:27:21 +0000626 llvm::json::Object{{"scopes", buildHighlightScopeLookupTable()}}});
Sam McCalla69698f2019-03-27 17:47:49 +0000627 Reply(std::move(Result));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000628}
629
Sam McCall8a2d2942020-03-03 12:12:14 +0100630void ClangdLSPServer::onInitialized(const InitializedParams &Params) {}
631
Sam McCall2c30fbc2018-10-18 12:32:04 +0000632void ClangdLSPServer::onShutdown(const ShutdownParams &Params,
633 Callback<std::nullptr_t> Reply) {
Ilya Biryukov0d9b8a32017-10-25 08:45:41 +0000634 // Do essentially nothing, just say we're ready to exit.
635 ShutdownRequestReceived = true;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000636 Reply(nullptr);
Sam McCall8a5dded2017-10-12 13:29:58 +0000637}
Ilya Biryukovafb55542017-05-16 14:40:30 +0000638
Sam McCall422c8282018-11-26 16:00:11 +0000639// sync is a clangd extension: it blocks until all background work completes.
640// It blocks the calling thread, so no messages are processed until it returns!
641void ClangdLSPServer::onSync(const NoParams &Params,
642 Callback<std::nullptr_t> Reply) {
643 if (Server->blockUntilIdleForTest(/*TimeoutSeconds=*/60))
644 Reply(nullptr);
645 else
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000646 Reply(llvm::createStringError(llvm::inconvertibleErrorCode(),
647 "Not idle after a minute"));
Sam McCall422c8282018-11-26 16:00:11 +0000648}
649
Sam McCall2c30fbc2018-10-18 12:32:04 +0000650void ClangdLSPServer::onDocumentDidOpen(
651 const DidOpenTextDocumentParams &Params) {
Simon Marchi9569fd52018-03-16 14:30:42 +0000652 PathRef File = Params.textDocument.uri.file();
Ilya Biryukovb10ef472018-06-13 09:20:41 +0000653
Sam McCall2c30fbc2018-10-18 12:32:04 +0000654 const std::string &Contents = Params.textDocument.text;
Simon Marchi9569fd52018-03-16 14:30:42 +0000655
Sam McCall2cd33e62020-03-04 00:33:29 +0100656 auto Version = DraftMgr.addDraft(File, Params.textDocument.version, Contents);
657 Server->addDocument(File, Contents, encodeVersion(Version),
658 WantDiagnostics::Yes);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000659}
660
Sam McCall2c30fbc2018-10-18 12:32:04 +0000661void ClangdLSPServer::onDocumentDidChange(
662 const DidChangeTextDocumentParams &Params) {
Eric Liu51fed182018-02-22 18:40:39 +0000663 auto WantDiags = WantDiagnostics::Auto;
664 if (Params.wantDiagnostics.hasValue())
665 WantDiags = Params.wantDiagnostics.getValue() ? WantDiagnostics::Yes
666 : WantDiagnostics::No;
Simon Marchi9569fd52018-03-16 14:30:42 +0000667
668 PathRef File = Params.textDocument.uri.file();
Sam McCallcaf5a4d2020-03-03 15:57:39 +0100669 llvm::Expected<DraftStore::Draft> Draft = DraftMgr.updateDraft(
670 File, Params.textDocument.version, Params.contentChanges);
671 if (!Draft) {
Simon Marchi98082622018-03-26 14:41:40 +0000672 // If this fails, we are most likely going to be not in sync anymore with
673 // the client. It is better to remove the draft and let further operations
674 // fail rather than giving wrong results.
675 DraftMgr.removeDraft(File);
Ilya Biryukov652364b2018-09-26 05:48:29 +0000676 Server->removeDocument(File);
Sam McCallcaf5a4d2020-03-03 15:57:39 +0100677 elog("Failed to update {0}: {1}", File, Draft.takeError());
Simon Marchi98082622018-03-26 14:41:40 +0000678 return;
679 }
Simon Marchi9569fd52018-03-16 14:30:42 +0000680
Sam McCall2cd33e62020-03-04 00:33:29 +0100681 Server->addDocument(File, Draft->Contents, encodeVersion(Draft->Version),
682 WantDiags, Params.forceRebuild);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000683}
684
Sam McCall2c30fbc2018-10-18 12:32:04 +0000685void ClangdLSPServer::onFileEvent(const DidChangeWatchedFilesParams &Params) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000686 Server->onFileEvent(Params);
Marc-Andre Laperlebf114242017-10-02 18:00:37 +0000687}
688
Sam McCall2c30fbc2018-10-18 12:32:04 +0000689void ClangdLSPServer::onCommand(const ExecuteCommandParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000690 Callback<llvm::json::Value> Reply) {
Ilya Biryukov12864002019-08-16 12:46:41 +0000691 auto ApplyEdit = [this](WorkspaceEdit WE, std::string SuccessMessage,
692 decltype(Reply) Reply) {
Eric Liuc5105f92018-02-16 14:15:55 +0000693 ApplyWorkspaceEditParams Edit;
694 Edit.edit = std::move(WE);
Ilya Biryukov12864002019-08-16 12:46:41 +0000695 call<ApplyWorkspaceEditResponse>(
696 "workspace/applyEdit", std::move(Edit),
697 [Reply = std::move(Reply), SuccessMessage = std::move(SuccessMessage)](
698 llvm::Expected<ApplyWorkspaceEditResponse> Response) mutable {
699 if (!Response)
700 return Reply(Response.takeError());
701 if (!Response->applied) {
702 std::string Reason = Response->failureReason
703 ? *Response->failureReason
704 : "unknown reason";
705 return Reply(llvm::createStringError(
706 llvm::inconvertibleErrorCode(),
707 ("edits were not applied: " + Reason).c_str()));
708 }
709 return Reply(SuccessMessage);
710 });
Eric Liuc5105f92018-02-16 14:15:55 +0000711 };
Ilya Biryukov12864002019-08-16 12:46:41 +0000712
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000713 if (Params.command == ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND &&
714 Params.workspaceEdit) {
715 // The flow for "apply-fix" :
716 // 1. We publish a diagnostic, including fixits
717 // 2. The user clicks on the diagnostic, the editor asks us for code actions
718 // 3. We send code actions, with the fixit embedded as context
719 // 4. The user selects the fixit, the editor asks us to apply it
720 // 5. We unwrap the changes and send them back to the editor
Haojian Wuf2516342019-08-05 12:48:09 +0000721 // 6. The editor applies the changes (applyEdit), and sends us a reply
722 // 7. We unwrap the reply and send a reply to the editor.
Ilya Biryukov12864002019-08-16 12:46:41 +0000723 ApplyEdit(*Params.workspaceEdit, "Fix applied.", std::move(Reply));
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000724 } else if (Params.command == ExecuteCommandParams::CLANGD_APPLY_TWEAK &&
725 Params.tweakArgs) {
726 auto Code = DraftMgr.getDraft(Params.tweakArgs->file.file());
727 if (!Code)
728 return Reply(llvm::createStringError(
729 llvm::inconvertibleErrorCode(),
730 "trying to apply a code action for a non-added file"));
731
Ilya Biryukov12864002019-08-16 12:46:41 +0000732 auto Action = [this, ApplyEdit, Reply = std::move(Reply),
733 File = Params.tweakArgs->file, Code = std::move(*Code)](
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000734 llvm::Expected<Tweak::Effect> R) mutable {
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000735 if (!R)
736 return Reply(R.takeError());
737
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000738 assert(R->ShowMessage ||
739 (!R->ApplyEdits.empty() && "tweak has no effect"));
Ilya Biryukov12864002019-08-16 12:46:41 +0000740
Sam McCall395fde72019-06-18 13:37:54 +0000741 if (R->ShowMessage) {
742 ShowMessageParams Msg;
743 Msg.message = *R->ShowMessage;
744 Msg.type = MessageType::Info;
745 notify("window/showMessage", Msg);
746 }
Ilya Biryukov12864002019-08-16 12:46:41 +0000747 // When no edit is specified, make sure we Reply().
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000748 if (R->ApplyEdits.empty())
749 return Reply("Tweak applied.");
750
Haojian Wu852bafa2019-10-23 14:40:20 +0200751 if (auto Err = validateEdits(DraftMgr, R->ApplyEdits))
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000752 return Reply(std::move(Err));
753
754 WorkspaceEdit WE;
755 WE.changes.emplace();
756 for (const auto &It : R->ApplyEdits) {
Kadir Cetinkayae95e5162019-10-02 09:12:01 +0000757 (*WE.changes)[URI::createFile(It.first()).toString()] =
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000758 It.second.asTextEdits();
759 }
760 // ApplyEdit will take care of calling Reply().
761 return ApplyEdit(std::move(WE), "Tweak applied.", std::move(Reply));
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000762 };
763 Server->applyTweak(Params.tweakArgs->file.file(),
764 Params.tweakArgs->selection, Params.tweakArgs->tweakID,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000765 std::move(Action));
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000766 } else {
767 // We should not get here because ExecuteCommandParams would not have
768 // parsed in the first place and this handler should not be called. But if
769 // more commands are added, this will be here has a safe guard.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000770 Reply(llvm::make_error<LSPError>(
771 llvm::formatv("Unsupported command \"{0}\".", Params.command).str(),
Sam McCall2c30fbc2018-10-18 12:32:04 +0000772 ErrorCode::InvalidParams));
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000773 }
774}
775
Sam McCall2c30fbc2018-10-18 12:32:04 +0000776void ClangdLSPServer::onWorkspaceSymbol(
777 const WorkspaceSymbolParams &Params,
778 Callback<std::vector<SymbolInformation>> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000779 Server->workspaceSymbols(
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000780 Params.query, CCOpts.Limit,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000781 [Reply = std::move(Reply),
782 this](llvm::Expected<std::vector<SymbolInformation>> Items) mutable {
783 if (!Items)
784 return Reply(Items.takeError());
785 for (auto &Sym : *Items)
786 Sym.kind = adjustKindToCapability(Sym.kind, SupportedSymbolKinds);
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000787
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000788 Reply(std::move(*Items));
789 });
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000790}
791
Haojian Wuf429ab62019-07-24 07:49:23 +0000792void ClangdLSPServer::onPrepareRename(const TextDocumentPositionParams &Params,
793 Callback<llvm::Optional<Range>> Reply) {
794 Server->prepareRename(Params.textDocument.uri.file(), Params.position,
Haojian Wu34d0e1b2020-02-19 15:37:36 +0100795 RenameOpts, std::move(Reply));
Haojian Wuf429ab62019-07-24 07:49:23 +0000796}
797
Sam McCall2c30fbc2018-10-18 12:32:04 +0000798void ClangdLSPServer::onRename(const RenameParams &Params,
799 Callback<WorkspaceEdit> Reply) {
Benjamin Krameradcd0262020-01-28 20:23:46 +0100800 Path File = std::string(Params.textDocument.uri.file());
Sam McCallcaf5a4d2020-03-03 15:57:39 +0100801 if (!DraftMgr.getDraft(File))
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000802 return Reply(llvm::make_error<LSPError>(
803 "onRename called for non-added file", ErrorCode::InvalidParams));
Haojian Wu852bafa2019-10-23 14:40:20 +0200804 Server->rename(
Haojian Wu34d0e1b2020-02-19 15:37:36 +0100805 File, Params.position, Params.newName, RenameOpts,
Haojian Wu852bafa2019-10-23 14:40:20 +0200806 [File, Params, Reply = std::move(Reply),
807 this](llvm::Expected<FileEdits> Edits) mutable {
808 if (!Edits)
809 return Reply(Edits.takeError());
810 if (auto Err = validateEdits(DraftMgr, *Edits))
811 return Reply(std::move(Err));
812 WorkspaceEdit Result;
813 Result.changes.emplace();
814 for (const auto &Rep : *Edits) {
815 (*Result.changes)[URI::createFile(Rep.first()).toString()] =
816 Rep.second.asTextEdits();
817 }
818 Reply(Result);
819 });
Haojian Wu345099c2017-11-09 11:30:04 +0000820}
821
Sam McCall2c30fbc2018-10-18 12:32:04 +0000822void ClangdLSPServer::onDocumentDidClose(
823 const DidCloseTextDocumentParams &Params) {
Simon Marchi9569fd52018-03-16 14:30:42 +0000824 PathRef File = Params.textDocument.uri.file();
825 DraftMgr.removeDraft(File);
Ilya Biryukov652364b2018-09-26 05:48:29 +0000826 Server->removeDocument(File);
Ilya Biryukov49c10712019-03-25 10:15:11 +0000827
828 {
829 std::lock_guard<std::mutex> Lock(FixItsMutex);
830 FixItsMap.erase(File);
831 }
Johan Vikstromc2653ef22019-08-01 08:08:44 +0000832 {
833 std::lock_guard<std::mutex> HLock(HighlightingsMutex);
834 FileToHighlightings.erase(File);
835 }
Sam McCall9e3063e2020-04-01 16:21:44 +0200836 {
837 std::lock_guard<std::mutex> HLock(SemanticTokensMutex);
838 LastSemanticTokens.erase(File);
839 }
Ilya Biryukov49c10712019-03-25 10:15:11 +0000840 // clangd will not send updates for this file anymore, so we empty out the
841 // list of diagnostics shown on the client (e.g. in the "Problems" pane of
842 // VSCode). Note that this cannot race with actual diagnostics responses
843 // because removeDocument() guarantees no diagnostic callbacks will be
844 // executed after it returns.
Sam McCall6525a6b2020-03-03 12:44:40 +0100845 PublishDiagnosticsParams Notification;
846 Notification.uri = URIForFile::canonicalize(File, /*TUPath=*/File);
847 publishDiagnostics(Notification);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000848}
849
Sam McCall4db732a2017-09-30 10:08:52 +0000850void ClangdLSPServer::onDocumentOnTypeFormatting(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000851 const DocumentOnTypeFormattingParams &Params,
852 Callback<std::vector<TextEdit>> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000853 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000854 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000855 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000856 return Reply(llvm::make_error<LSPError>(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000857 "onDocumentOnTypeFormatting called for non-added file",
858 ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000859
Sam McCallcaf5a4d2020-03-03 15:57:39 +0100860 Reply(Server->formatOnType(Code->Contents, File, Params.position, Params.ch));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000861}
862
Sam McCall4db732a2017-09-30 10:08:52 +0000863void ClangdLSPServer::onDocumentRangeFormatting(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000864 const DocumentRangeFormattingParams &Params,
865 Callback<std::vector<TextEdit>> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000866 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000867 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000868 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000869 return Reply(llvm::make_error<LSPError>(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000870 "onDocumentRangeFormatting called for non-added file",
871 ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000872
Sam McCallcaf5a4d2020-03-03 15:57:39 +0100873 auto ReplacementsOrError =
874 Server->formatRange(Code->Contents, File, Params.range);
Raoul Wols212bcf82017-12-12 20:25:06 +0000875 if (ReplacementsOrError)
Sam McCallcaf5a4d2020-03-03 15:57:39 +0100876 Reply(replacementsToEdits(Code->Contents, ReplacementsOrError.get()));
Raoul Wols212bcf82017-12-12 20:25:06 +0000877 else
Sam McCall2c30fbc2018-10-18 12:32:04 +0000878 Reply(ReplacementsOrError.takeError());
Ilya Biryukovafb55542017-05-16 14:40:30 +0000879}
880
Sam McCall2c30fbc2018-10-18 12:32:04 +0000881void ClangdLSPServer::onDocumentFormatting(
882 const DocumentFormattingParams &Params,
883 Callback<std::vector<TextEdit>> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000884 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000885 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000886 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000887 return Reply(llvm::make_error<LSPError>(
888 "onDocumentFormatting called for non-added file",
889 ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000890
Sam McCallcaf5a4d2020-03-03 15:57:39 +0100891 auto ReplacementsOrError = Server->formatFile(Code->Contents, File);
Raoul Wols212bcf82017-12-12 20:25:06 +0000892 if (ReplacementsOrError)
Sam McCallcaf5a4d2020-03-03 15:57:39 +0100893 Reply(replacementsToEdits(Code->Contents, ReplacementsOrError.get()));
Raoul Wols212bcf82017-12-12 20:25:06 +0000894 else
Sam McCall2c30fbc2018-10-18 12:32:04 +0000895 Reply(ReplacementsOrError.takeError());
Sam McCall4db732a2017-09-30 10:08:52 +0000896}
897
Ilya Biryukov19d75602018-11-23 15:21:19 +0000898/// The functions constructs a flattened view of the DocumentSymbol hierarchy.
899/// Used by the clients that do not support the hierarchical view.
900static std::vector<SymbolInformation>
901flattenSymbolHierarchy(llvm::ArrayRef<DocumentSymbol> Symbols,
902 const URIForFile &FileURI) {
903
904 std::vector<SymbolInformation> Results;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000905 std::function<void(const DocumentSymbol &, llvm::StringRef)> Process =
906 [&](const DocumentSymbol &S, llvm::Optional<llvm::StringRef> ParentName) {
Ilya Biryukov19d75602018-11-23 15:21:19 +0000907 SymbolInformation SI;
Benjamin Krameradcd0262020-01-28 20:23:46 +0100908 SI.containerName = std::string(ParentName ? "" : *ParentName);
Ilya Biryukov19d75602018-11-23 15:21:19 +0000909 SI.name = S.name;
910 SI.kind = S.kind;
911 SI.location.range = S.range;
912 SI.location.uri = FileURI;
913
914 Results.push_back(std::move(SI));
915 std::string FullName =
916 !ParentName ? S.name : (ParentName->str() + "::" + S.name);
917 for (auto &C : S.children)
918 Process(C, /*ParentName=*/FullName);
919 };
920 for (auto &S : Symbols)
921 Process(S, /*ParentName=*/"");
922 return Results;
923}
924
925void ClangdLSPServer::onDocumentSymbol(const DocumentSymbolParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000926 Callback<llvm::json::Value> Reply) {
Ilya Biryukov19d75602018-11-23 15:21:19 +0000927 URIForFile FileURI = Params.textDocument.uri;
Ilya Biryukov652364b2018-09-26 05:48:29 +0000928 Server->documentSymbols(
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000929 Params.textDocument.uri.file(),
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000930 [this, FileURI, Reply = std::move(Reply)](
931 llvm::Expected<std::vector<DocumentSymbol>> Items) mutable {
932 if (!Items)
933 return Reply(Items.takeError());
934 adjustSymbolKinds(*Items, SupportedSymbolKinds);
935 if (SupportsHierarchicalDocumentSymbol)
936 return Reply(std::move(*Items));
937 else
938 return Reply(flattenSymbolHierarchy(*Items, FileURI));
939 });
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000940}
941
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000942static llvm::Optional<Command> asCommand(const CodeAction &Action) {
Sam McCall20841d42018-10-16 16:29:41 +0000943 Command Cmd;
944 if (Action.command && Action.edit)
Sam McCallc008af62018-10-20 15:30:37 +0000945 return None; // Not representable. (We never emit these anyway).
Sam McCall20841d42018-10-16 16:29:41 +0000946 if (Action.command) {
947 Cmd = *Action.command;
948 } else if (Action.edit) {
Benjamin Krameradcd0262020-01-28 20:23:46 +0100949 Cmd.command = std::string(Command::CLANGD_APPLY_FIX_COMMAND);
Sam McCall20841d42018-10-16 16:29:41 +0000950 Cmd.workspaceEdit = *Action.edit;
951 } else {
Sam McCallc008af62018-10-20 15:30:37 +0000952 return None;
Sam McCall20841d42018-10-16 16:29:41 +0000953 }
954 Cmd.title = Action.title;
955 if (Action.kind && *Action.kind == CodeAction::QUICKFIX_KIND)
956 Cmd.title = "Apply fix: " + Cmd.title;
957 return Cmd;
958}
959
Sam McCall2c30fbc2018-10-18 12:32:04 +0000960void ClangdLSPServer::onCodeAction(const CodeActionParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000961 Callback<llvm::json::Value> Reply) {
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000962 URIForFile File = Params.textDocument.uri;
963 auto Code = DraftMgr.getDraft(File.file());
Sam McCall2c30fbc2018-10-18 12:32:04 +0000964 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000965 return Reply(llvm::make_error<LSPError>(
966 "onCodeAction called for non-added file", ErrorCode::InvalidParams));
Sam McCall20841d42018-10-16 16:29:41 +0000967 // We provide a code action for Fixes on the specified diagnostics.
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000968 std::vector<CodeAction> FixIts;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000969 for (const Diagnostic &D : Params.context.diagnostics) {
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000970 for (auto &F : getFixes(File.file(), D)) {
971 FixIts.push_back(toCodeAction(F, Params.textDocument.uri));
972 FixIts.back().diagnostics = {D};
Sam McCalldd0566b2017-11-06 15:40:30 +0000973 }
Ilya Biryukovafb55542017-05-16 14:40:30 +0000974 }
Sam McCall20841d42018-10-16 16:29:41 +0000975
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000976 // Now enumerate the semantic code actions.
977 auto ConsumeActions =
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000978 [Reply = std::move(Reply), File, Code = std::move(*Code),
979 Selection = Params.range, FixIts = std::move(FixIts), this](
980 llvm::Expected<std::vector<ClangdServer::TweakRef>> Tweaks) mutable {
Ilya Biryukovc6ed7782019-01-30 14:24:17 +0000981 if (!Tweaks)
982 return Reply(Tweaks.takeError());
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000983
984 std::vector<CodeAction> Actions = std::move(FixIts);
985 Actions.reserve(Actions.size() + Tweaks->size());
986 for (const auto &T : *Tweaks)
987 Actions.push_back(toCodeAction(T, File, Selection));
988
989 if (SupportsCodeAction)
990 return Reply(llvm::json::Array(Actions));
991 std::vector<Command> Commands;
992 for (const auto &Action : Actions) {
993 if (auto Command = asCommand(Action))
994 Commands.push_back(std::move(*Command));
995 }
996 return Reply(llvm::json::Array(Commands));
997 };
998
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000999 Server->enumerateTweaks(File.file(), Params.range, std::move(ConsumeActions));
Ilya Biryukovafb55542017-05-16 14:40:30 +00001000}
1001
Ilya Biryukovb0826bd2019-01-03 13:37:12 +00001002void ClangdLSPServer::onCompletion(const CompletionParams &Params,
Sam McCall2c30fbc2018-10-18 12:32:04 +00001003 Callback<CompletionList> Reply) {
Ilya Biryukova7a11472019-06-07 16:24:38 +00001004 if (!shouldRunCompletion(Params)) {
1005 // Clients sometimes auto-trigger completions in undesired places (e.g.
1006 // 'a >^ '), we return empty results in those cases.
1007 vlog("ignored auto-triggered completion, preceding char did not match");
1008 return Reply(CompletionList());
1009 }
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001010 Server->codeComplete(Params.textDocument.uri.file(), Params.position, CCOpts,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001011 [Reply = std::move(Reply),
1012 this](llvm::Expected<CodeCompleteResult> List) mutable {
1013 if (!List)
1014 return Reply(List.takeError());
1015 CompletionList LSPList;
1016 LSPList.isIncomplete = List->HasMore;
1017 for (const auto &R : List->Completions) {
1018 CompletionItem C = R.render(CCOpts);
1019 C.kind = adjustKindToCapability(
1020 C.kind, SupportedCompletionItemKinds);
1021 LSPList.items.push_back(std::move(C));
1022 }
1023 return Reply(std::move(LSPList));
1024 });
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +00001025}
1026
Sam McCall2c30fbc2018-10-18 12:32:04 +00001027void ClangdLSPServer::onSignatureHelp(const TextDocumentPositionParams &Params,
1028 Callback<SignatureHelp> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +00001029 Server->signatureHelp(Params.textDocument.uri.file(), Params.position,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001030 [Reply = std::move(Reply), this](
1031 llvm::Expected<SignatureHelp> Signature) mutable {
1032 if (!Signature)
1033 return Reply(Signature.takeError());
1034 if (SupportsOffsetsInSignatureHelp)
1035 return Reply(std::move(*Signature));
1036 // Strip out the offsets from signature help for
1037 // clients that only support string labels.
1038 for (auto &SigInfo : Signature->signatures) {
1039 for (auto &Param : SigInfo.parameters)
1040 Param.labelOffsets.reset();
1041 }
1042 return Reply(std::move(*Signature));
1043 });
Ilya Biryukov652364b2018-09-26 05:48:29 +00001044}
1045
Sam McCall0dbab7f2019-02-02 05:56:00 +00001046// Go to definition has a toggle function: if def and decl are distinct, then
1047// the first press gives you the def, the second gives you the matching def.
1048// getToggle() returns the counterpart location that under the cursor.
1049//
1050// We return the toggled location alone (ignoring other symbols) to encourage
1051// editors to "bounce" quickly between locations, without showing a menu.
1052static Location *getToggle(const TextDocumentPositionParams &Point,
1053 LocatedSymbol &Sym) {
1054 // Toggle only makes sense with two distinct locations.
1055 if (!Sym.Definition || *Sym.Definition == Sym.PreferredDeclaration)
1056 return nullptr;
1057 if (Sym.Definition->uri.file() == Point.textDocument.uri.file() &&
1058 Sym.Definition->range.contains(Point.position))
1059 return &Sym.PreferredDeclaration;
1060 if (Sym.PreferredDeclaration.uri.file() == Point.textDocument.uri.file() &&
1061 Sym.PreferredDeclaration.range.contains(Point.position))
1062 return &*Sym.Definition;
1063 return nullptr;
1064}
1065
Sam McCall2c30fbc2018-10-18 12:32:04 +00001066void ClangdLSPServer::onGoToDefinition(const TextDocumentPositionParams &Params,
1067 Callback<std::vector<Location>> Reply) {
Sam McCall866ba2c2019-02-01 11:26:13 +00001068 Server->locateSymbolAt(
1069 Params.textDocument.uri.file(), Params.position,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001070 [Params, Reply = std::move(Reply)](
1071 llvm::Expected<std::vector<LocatedSymbol>> Symbols) mutable {
1072 if (!Symbols)
1073 return Reply(Symbols.takeError());
1074 std::vector<Location> Defs;
1075 for (auto &S : *Symbols) {
1076 if (Location *Toggle = getToggle(Params, S))
1077 return Reply(std::vector<Location>{std::move(*Toggle)});
1078 Defs.push_back(S.Definition.getValueOr(S.PreferredDeclaration));
1079 }
1080 Reply(std::move(Defs));
1081 });
Sam McCall866ba2c2019-02-01 11:26:13 +00001082}
1083
1084void ClangdLSPServer::onGoToDeclaration(
1085 const TextDocumentPositionParams &Params,
1086 Callback<std::vector<Location>> Reply) {
1087 Server->locateSymbolAt(
1088 Params.textDocument.uri.file(), Params.position,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001089 [Params, Reply = std::move(Reply)](
1090 llvm::Expected<std::vector<LocatedSymbol>> Symbols) mutable {
1091 if (!Symbols)
1092 return Reply(Symbols.takeError());
1093 std::vector<Location> Decls;
1094 for (auto &S : *Symbols) {
1095 if (Location *Toggle = getToggle(Params, S))
1096 return Reply(std::vector<Location>{std::move(*Toggle)});
1097 Decls.push_back(std::move(S.PreferredDeclaration));
1098 }
1099 Reply(std::move(Decls));
1100 });
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +00001101}
1102
Sam McCall111fe842019-05-07 07:55:35 +00001103void ClangdLSPServer::onSwitchSourceHeader(
1104 const TextDocumentIdentifier &Params,
Sam McCallb9ec3e92019-05-07 08:30:32 +00001105 Callback<llvm::Optional<URIForFile>> Reply) {
Haojian Wud6d5edd2019-10-01 10:21:15 +00001106 Server->switchSourceHeader(
1107 Params.uri.file(),
1108 [Reply = std::move(Reply),
1109 Params](llvm::Expected<llvm::Optional<clangd::Path>> Path) mutable {
1110 if (!Path)
1111 return Reply(Path.takeError());
1112 if (*Path)
Haojian Wu77c97002019-10-07 11:37:25 +00001113 return Reply(URIForFile::canonicalize(**Path, Params.uri.file()));
Haojian Wud6d5edd2019-10-01 10:21:15 +00001114 return Reply(llvm::None);
1115 });
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +00001116}
1117
Sam McCall2c30fbc2018-10-18 12:32:04 +00001118void ClangdLSPServer::onDocumentHighlight(
1119 const TextDocumentPositionParams &Params,
1120 Callback<std::vector<DocumentHighlight>> Reply) {
1121 Server->findDocumentHighlights(Params.textDocument.uri.file(),
1122 Params.position, std::move(Reply));
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +00001123}
1124
Sam McCall2c30fbc2018-10-18 12:32:04 +00001125void ClangdLSPServer::onHover(const TextDocumentPositionParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001126 Callback<llvm::Optional<Hover>> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +00001127 Server->findHover(Params.textDocument.uri.file(), Params.position,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001128 [Reply = std::move(Reply), this](
1129 llvm::Expected<llvm::Optional<HoverInfo>> H) mutable {
1130 if (!H)
1131 return Reply(H.takeError());
1132 if (!*H)
1133 return Reply(llvm::None);
Ilya Biryukovf9169d02019-05-29 10:01:00 +00001134
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001135 Hover R;
1136 R.contents.kind = HoverContentFormat;
1137 R.range = (*H)->SymRange;
1138 switch (HoverContentFormat) {
1139 case MarkupKind::PlainText:
Kadir Cetinkaya597c6b62019-12-10 10:28:37 +01001140 R.contents.value = (*H)->present().asPlainText();
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001141 return Reply(std::move(R));
1142 case MarkupKind::Markdown:
Kadir Cetinkaya597c6b62019-12-10 10:28:37 +01001143 R.contents.value = (*H)->present().asMarkdown();
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001144 return Reply(std::move(R));
1145 };
1146 llvm_unreachable("unhandled MarkupKind");
1147 });
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +00001148}
1149
Kadir Cetinkaya86658022019-03-19 09:27:04 +00001150void ClangdLSPServer::onTypeHierarchy(
1151 const TypeHierarchyParams &Params,
1152 Callback<Optional<TypeHierarchyItem>> Reply) {
1153 Server->typeHierarchy(Params.textDocument.uri.file(), Params.position,
1154 Params.resolve, Params.direction, std::move(Reply));
1155}
1156
Nathan Ridge087b0442019-07-13 03:24:48 +00001157void ClangdLSPServer::onResolveTypeHierarchy(
1158 const ResolveTypeHierarchyItemParams &Params,
1159 Callback<Optional<TypeHierarchyItem>> Reply) {
1160 Server->resolveTypeHierarchy(Params.item, Params.resolve, Params.direction,
1161 std::move(Reply));
1162}
1163
Simon Marchi88016782018-08-01 11:28:49 +00001164void ClangdLSPServer::applyConfiguration(
Sam McCallbc904612018-10-25 04:22:52 +00001165 const ConfigurationSettings &Settings) {
Simon Marchiabeed662018-10-16 15:55:03 +00001166 // Per-file update to the compilation database.
David Goldman60249c22020-01-13 17:01:10 -05001167 llvm::StringSet<> ModifiedFiles;
Sam McCallbc904612018-10-25 04:22:52 +00001168 for (auto &Entry : Settings.compilationDatabaseChanges) {
Sam McCallbc904612018-10-25 04:22:52 +00001169 PathRef File = Entry.first;
Sam McCallc55d09a2018-11-02 13:09:36 +00001170 auto Old = CDB->getCompileCommand(File);
1171 auto New =
1172 tooling::CompileCommand(std::move(Entry.second.workingDirectory), File,
1173 std::move(Entry.second.compilationCommand),
1174 /*Output=*/"");
Sam McCall6980edb2018-11-02 14:07:51 +00001175 if (Old != New) {
Sam McCallc55d09a2018-11-02 13:09:36 +00001176 CDB->setCompileCommand(File, std::move(New));
David Goldman60249c22020-01-13 17:01:10 -05001177 ModifiedFiles.insert(File);
Sam McCall6980edb2018-11-02 14:07:51 +00001178 }
Alex Lorenzf8087862018-08-01 17:39:29 +00001179 }
David Goldman60249c22020-01-13 17:01:10 -05001180
1181 reparseOpenedFiles(ModifiedFiles);
Simon Marchi5178f922018-02-22 14:00:39 +00001182}
1183
Sam McCalledf6a192020-03-24 00:31:14 +01001184void ClangdLSPServer::publishTheiaSemanticHighlighting(
1185 const TheiaSemanticHighlightingParams &Params) {
Johan Vikstroma848dab2019-07-04 07:53:12 +00001186 notify("textDocument/semanticHighlighting", Params);
1187}
1188
Ilya Biryukov49c10712019-03-25 10:15:11 +00001189void ClangdLSPServer::publishDiagnostics(
Sam McCall6525a6b2020-03-03 12:44:40 +01001190 const PublishDiagnosticsParams &Params) {
1191 notify("textDocument/publishDiagnostics", Params);
Ilya Biryukov49c10712019-03-25 10:15:11 +00001192}
1193
Simon Marchi88016782018-08-01 11:28:49 +00001194// FIXME: This function needs to be properly tested.
1195void ClangdLSPServer::onChangeConfiguration(
Sam McCall2c30fbc2018-10-18 12:32:04 +00001196 const DidChangeConfigurationParams &Params) {
Simon Marchi88016782018-08-01 11:28:49 +00001197 applyConfiguration(Params.settings);
1198}
1199
Sam McCall2c30fbc2018-10-18 12:32:04 +00001200void ClangdLSPServer::onReference(const ReferenceParams &Params,
1201 Callback<std::vector<Location>> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +00001202 Server->findReferences(Params.textDocument.uri.file(), Params.position,
Haojian Wu5181ada2019-11-18 11:35:00 +01001203 CCOpts.Limit,
1204 [Reply = std::move(Reply)](
1205 llvm::Expected<ReferencesResult> Refs) mutable {
1206 if (!Refs)
1207 return Reply(Refs.takeError());
1208 return Reply(std::move(Refs->References));
1209 });
Sam McCall1ad142f2018-09-05 11:53:07 +00001210}
1211
Jan Korousb4067012018-11-27 16:40:46 +00001212void ClangdLSPServer::onSymbolInfo(const TextDocumentPositionParams &Params,
1213 Callback<std::vector<SymbolDetails>> Reply) {
1214 Server->symbolInfo(Params.textDocument.uri.file(), Params.position,
1215 std::move(Reply));
1216}
1217
Utkarsh Saxena55925da2019-09-24 13:38:33 +00001218void ClangdLSPServer::onSelectionRange(
1219 const SelectionRangeParams &Params,
1220 Callback<std::vector<SelectionRange>> Reply) {
Utkarsh Saxena55925da2019-09-24 13:38:33 +00001221 Server->semanticRanges(
Sam McCall8f237f92020-03-25 00:51:50 +01001222 Params.textDocument.uri.file(), Params.positions,
Utkarsh Saxena55925da2019-09-24 13:38:33 +00001223 [Reply = std::move(Reply)](
Sam McCall8f237f92020-03-25 00:51:50 +01001224 llvm::Expected<std::vector<SelectionRange>> Ranges) mutable {
1225 if (!Ranges)
Utkarsh Saxena55925da2019-09-24 13:38:33 +00001226 return Reply(Ranges.takeError());
Sam McCall8f237f92020-03-25 00:51:50 +01001227 return Reply(std::move(*Ranges));
Utkarsh Saxena55925da2019-09-24 13:38:33 +00001228 });
1229}
1230
Sam McCall8d7ecc12019-12-16 19:08:51 +01001231void ClangdLSPServer::onDocumentLink(
1232 const DocumentLinkParams &Params,
1233 Callback<std::vector<DocumentLink>> Reply) {
1234
1235 // TODO(forster): This currently resolves all targets eagerly. This is slow,
1236 // because it blocks on the preamble/AST being built. We could respond to the
1237 // request faster by using string matching or the lexer to find the includes
1238 // and resolving the targets lazily.
1239 Server->documentLinks(
1240 Params.textDocument.uri.file(),
1241 [Reply = std::move(Reply)](
1242 llvm::Expected<std::vector<DocumentLink>> Links) mutable {
1243 if (!Links) {
1244 return Reply(Links.takeError());
1245 }
1246 return Reply(std::move(Links));
1247 });
1248}
1249
Sam McCall9e3063e2020-04-01 16:21:44 +02001250// Increment a numeric string: "" -> 1 -> 2 -> ... -> 9 -> 10 -> 11 ...
1251static void increment(std::string &S) {
1252 for (char &C : llvm::reverse(S)) {
1253 if (C != '9') {
1254 ++C;
1255 return;
1256 }
1257 C = '0';
1258 }
1259 S.insert(S.begin(), '1');
1260}
1261
Sam McCall71177ac2020-03-24 02:24:47 +01001262void ClangdLSPServer::onSemanticTokens(const SemanticTokensParams &Params,
1263 Callback<SemanticTokens> CB) {
1264 Server->semanticHighlights(
1265 Params.textDocument.uri.file(),
Sam McCall9e3063e2020-04-01 16:21:44 +02001266 [this, File(Params.textDocument.uri.file().str()), CB(std::move(CB))](
1267 llvm::Expected<std::vector<HighlightingToken>> HT) mutable {
1268 if (!HT)
1269 return CB(HT.takeError());
Sam McCall71177ac2020-03-24 02:24:47 +01001270 SemanticTokens Result;
Sam McCall9e3063e2020-04-01 16:21:44 +02001271 Result.tokens = toSemanticTokens(*HT);
1272 {
1273 std::lock_guard<std::mutex> Lock(SemanticTokensMutex);
1274 auto& Last = LastSemanticTokens[File];
1275
1276 Last.tokens = Result.tokens;
1277 increment(Last.resultId);
1278 Result.resultId = Last.resultId;
1279 }
1280 CB(std::move(Result));
1281 });
1282}
1283
1284void ClangdLSPServer::onSemanticTokensEdits(
1285 const SemanticTokensEditsParams &Params,
1286 Callback<SemanticTokensOrEdits> CB) {
1287 Server->semanticHighlights(
1288 Params.textDocument.uri.file(),
1289 [this, PrevResultID(Params.previousResultId),
1290 File(Params.textDocument.uri.file().str()), CB(std::move(CB))](
1291 llvm::Expected<std::vector<HighlightingToken>> HT) mutable {
1292 if (!HT)
1293 return CB(HT.takeError());
1294 std::vector<SemanticToken> Toks = toSemanticTokens(*HT);
1295
1296 SemanticTokensOrEdits Result;
1297 {
1298 std::lock_guard<std::mutex> Lock(SemanticTokensMutex);
1299 auto& Last = LastSemanticTokens[File];
1300
1301 if (PrevResultID == Last.resultId) {
1302 Result.edits = diffTokens(Last.tokens, Toks);
1303 } else {
1304 vlog("semanticTokens/edits: wanted edits vs {0} but last result "
1305 "had ID {1}. Returning full token list.",
1306 PrevResultID, Last.resultId);
1307 Result.tokens = Toks;
1308 }
1309
1310 Last.tokens = std::move(Toks);
1311 increment(Last.resultId);
1312 Result.resultId = Last.resultId;
1313 }
1314
Sam McCall71177ac2020-03-24 02:24:47 +01001315 CB(std::move(Result));
1316 });
1317}
1318
Sam McCalla69698f2019-03-27 17:47:49 +00001319ClangdLSPServer::ClangdLSPServer(
1320 class Transport &Transp, const FileSystemProvider &FSProvider,
1321 const clangd::CodeCompleteOptions &CCOpts,
Haojian Wu34d0e1b2020-02-19 15:37:36 +01001322 const clangd::RenameOptions &RenameOpts,
Sam McCalla69698f2019-03-27 17:47:49 +00001323 llvm::Optional<Path> CompileCommandsDir, bool UseDirBasedCDB,
1324 llvm::Optional<OffsetEncoding> ForcedOffsetEncoding,
1325 const ClangdServer::Options &Opts)
Kadir Cetinkaya9d662472019-10-15 14:20:52 +00001326 : BackgroundContext(Context::current().clone()), Transp(Transp),
1327 MsgHandler(new MessageHandler(*this)), FSProvider(FSProvider),
Haojian Wu34d0e1b2020-02-19 15:37:36 +01001328 CCOpts(CCOpts), RenameOpts(RenameOpts),
1329 SupportedSymbolKinds(defaultSymbolKinds()),
Kadir Cetinkaya133d46f2018-09-27 17:13:07 +00001330 SupportedCompletionItemKinds(defaultCompletionItemKinds()),
Sam McCallc55d09a2018-11-02 13:09:36 +00001331 UseDirBasedCDB(UseDirBasedCDB),
Sam McCalla69698f2019-03-27 17:47:49 +00001332 CompileCommandsDir(std::move(CompileCommandsDir)), ClangdServerOpts(Opts),
1333 NegotiatedOffsetEncoding(ForcedOffsetEncoding) {
Sam McCall2c30fbc2018-10-18 12:32:04 +00001334 // clang-format off
1335 MsgHandler->bind("initialize", &ClangdLSPServer::onInitialize);
Sam McCall8a2d2942020-03-03 12:12:14 +01001336 MsgHandler->bind("initialized", &ClangdLSPServer::onInitialized);
Sam McCall2c30fbc2018-10-18 12:32:04 +00001337 MsgHandler->bind("shutdown", &ClangdLSPServer::onShutdown);
Sam McCall422c8282018-11-26 16:00:11 +00001338 MsgHandler->bind("sync", &ClangdLSPServer::onSync);
Sam McCall2c30fbc2018-10-18 12:32:04 +00001339 MsgHandler->bind("textDocument/rangeFormatting", &ClangdLSPServer::onDocumentRangeFormatting);
1340 MsgHandler->bind("textDocument/onTypeFormatting", &ClangdLSPServer::onDocumentOnTypeFormatting);
1341 MsgHandler->bind("textDocument/formatting", &ClangdLSPServer::onDocumentFormatting);
1342 MsgHandler->bind("textDocument/codeAction", &ClangdLSPServer::onCodeAction);
1343 MsgHandler->bind("textDocument/completion", &ClangdLSPServer::onCompletion);
1344 MsgHandler->bind("textDocument/signatureHelp", &ClangdLSPServer::onSignatureHelp);
1345 MsgHandler->bind("textDocument/definition", &ClangdLSPServer::onGoToDefinition);
Sam McCall866ba2c2019-02-01 11:26:13 +00001346 MsgHandler->bind("textDocument/declaration", &ClangdLSPServer::onGoToDeclaration);
Sam McCall2c30fbc2018-10-18 12:32:04 +00001347 MsgHandler->bind("textDocument/references", &ClangdLSPServer::onReference);
1348 MsgHandler->bind("textDocument/switchSourceHeader", &ClangdLSPServer::onSwitchSourceHeader);
Haojian Wuf429ab62019-07-24 07:49:23 +00001349 MsgHandler->bind("textDocument/prepareRename", &ClangdLSPServer::onPrepareRename);
Sam McCall2c30fbc2018-10-18 12:32:04 +00001350 MsgHandler->bind("textDocument/rename", &ClangdLSPServer::onRename);
1351 MsgHandler->bind("textDocument/hover", &ClangdLSPServer::onHover);
1352 MsgHandler->bind("textDocument/documentSymbol", &ClangdLSPServer::onDocumentSymbol);
1353 MsgHandler->bind("workspace/executeCommand", &ClangdLSPServer::onCommand);
1354 MsgHandler->bind("textDocument/documentHighlight", &ClangdLSPServer::onDocumentHighlight);
1355 MsgHandler->bind("workspace/symbol", &ClangdLSPServer::onWorkspaceSymbol);
1356 MsgHandler->bind("textDocument/didOpen", &ClangdLSPServer::onDocumentDidOpen);
1357 MsgHandler->bind("textDocument/didClose", &ClangdLSPServer::onDocumentDidClose);
1358 MsgHandler->bind("textDocument/didChange", &ClangdLSPServer::onDocumentDidChange);
1359 MsgHandler->bind("workspace/didChangeWatchedFiles", &ClangdLSPServer::onFileEvent);
1360 MsgHandler->bind("workspace/didChangeConfiguration", &ClangdLSPServer::onChangeConfiguration);
Jan Korousb4067012018-11-27 16:40:46 +00001361 MsgHandler->bind("textDocument/symbolInfo", &ClangdLSPServer::onSymbolInfo);
Kadir Cetinkaya86658022019-03-19 09:27:04 +00001362 MsgHandler->bind("textDocument/typeHierarchy", &ClangdLSPServer::onTypeHierarchy);
Nathan Ridge087b0442019-07-13 03:24:48 +00001363 MsgHandler->bind("typeHierarchy/resolve", &ClangdLSPServer::onResolveTypeHierarchy);
Utkarsh Saxena55925da2019-09-24 13:38:33 +00001364 MsgHandler->bind("textDocument/selectionRange", &ClangdLSPServer::onSelectionRange);
Sam McCall8d7ecc12019-12-16 19:08:51 +01001365 MsgHandler->bind("textDocument/documentLink", &ClangdLSPServer::onDocumentLink);
Sam McCall71177ac2020-03-24 02:24:47 +01001366 MsgHandler->bind("textDocument/semanticTokens", &ClangdLSPServer::onSemanticTokens);
Sam McCall9e3063e2020-04-01 16:21:44 +02001367 MsgHandler->bind("textDocument/semanticTokens/edits", &ClangdLSPServer::onSemanticTokensEdits);
Sam McCall2c30fbc2018-10-18 12:32:04 +00001368 // clang-format on
1369}
1370
Sam McCall8bda5f22019-10-23 11:11:18 +02001371ClangdLSPServer::~ClangdLSPServer() { IsBeingDestroyed = true;
1372 // Explicitly destroy ClangdServer first, blocking on threads it owns.
1373 // This ensures they don't access any other members.
1374 Server.reset();
1375}
Ilya Biryukov38d79772017-05-16 09:38:59 +00001376
Sam McCalldc8f3cf2018-10-17 07:32:05 +00001377bool ClangdLSPServer::run() {
Ilya Biryukovafb55542017-05-16 14:40:30 +00001378 // Run the Language Server loop.
Sam McCalldc8f3cf2018-10-17 07:32:05 +00001379 bool CleanExit = true;
Sam McCall2c30fbc2018-10-18 12:32:04 +00001380 if (auto Err = Transp.loop(*MsgHandler)) {
Sam McCalldc8f3cf2018-10-17 07:32:05 +00001381 elog("Transport error: {0}", std::move(Err));
1382 CleanExit = false;
1383 }
Ilya Biryukovafb55542017-05-16 14:40:30 +00001384
Sam McCalldc8f3cf2018-10-17 07:32:05 +00001385 return CleanExit && ShutdownRequestReceived;
Ilya Biryukov38d79772017-05-16 09:38:59 +00001386}
1387
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001388std::vector<Fix> ClangdLSPServer::getFixes(llvm::StringRef File,
Ilya Biryukov71028b82018-03-12 15:28:22 +00001389 const clangd::Diagnostic &D) {
Ilya Biryukov38d79772017-05-16 09:38:59 +00001390 std::lock_guard<std::mutex> Lock(FixItsMutex);
1391 auto DiagToFixItsIter = FixItsMap.find(File);
1392 if (DiagToFixItsIter == FixItsMap.end())
1393 return {};
1394
1395 const auto &DiagToFixItsMap = DiagToFixItsIter->second;
1396 auto FixItsIter = DiagToFixItsMap.find(D);
1397 if (FixItsIter == DiagToFixItsMap.end())
1398 return {};
1399
1400 return FixItsIter->second;
1401}
1402
Ilya Biryukovb0826bd2019-01-03 13:37:12 +00001403bool ClangdLSPServer::shouldRunCompletion(
1404 const CompletionParams &Params) const {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001405 llvm::StringRef Trigger = Params.context.triggerCharacter;
Ilya Biryukovb0826bd2019-01-03 13:37:12 +00001406 if (Params.context.triggerKind != CompletionTriggerKind::TriggerCharacter ||
1407 (Trigger != ">" && Trigger != ":"))
1408 return true;
1409
1410 auto Code = DraftMgr.getDraft(Params.textDocument.uri.file());
1411 if (!Code)
1412 return true; // completion code will log the error for untracked doc.
1413
1414 // A completion request is sent when the user types '>' or ':', but we only
1415 // want to trigger on '->' and '::'. We check the preceeding character to make
1416 // sure it matches what we expected.
1417 // Running the lexer here would be more robust (e.g. we can detect comments
1418 // and avoid triggering completion there), but we choose to err on the side
1419 // of simplicity here.
Sam McCallcaf5a4d2020-03-03 15:57:39 +01001420 auto Offset = positionToOffset(Code->Contents, Params.position,
Ilya Biryukovb0826bd2019-01-03 13:37:12 +00001421 /*AllowColumnsBeyondLineLength=*/false);
1422 if (!Offset) {
1423 vlog("could not convert position '{0}' to offset for file '{1}'",
1424 Params.position, Params.textDocument.uri.file());
1425 return true;
1426 }
1427 if (*Offset < 2)
1428 return false;
1429
1430 if (Trigger == ">")
Sam McCallcaf5a4d2020-03-03 15:57:39 +01001431 return Code->Contents[*Offset - 2] == '-'; // trigger only on '->'.
Ilya Biryukovb0826bd2019-01-03 13:37:12 +00001432 if (Trigger == ":")
Sam McCallcaf5a4d2020-03-03 15:57:39 +01001433 return Code->Contents[*Offset - 2] == ':'; // trigger only on '::'.
Ilya Biryukovb0826bd2019-01-03 13:37:12 +00001434 assert(false && "unhandled trigger character");
1435 return true;
1436}
1437
Johan Vikstroma848dab2019-07-04 07:53:12 +00001438void ClangdLSPServer::onHighlightingsReady(
Sam McCall2cd33e62020-03-04 00:33:29 +01001439 PathRef File, llvm::StringRef Version,
1440 std::vector<HighlightingToken> Highlightings) {
Johan Vikstromc2653ef22019-08-01 08:08:44 +00001441 std::vector<HighlightingToken> Old;
1442 std::vector<HighlightingToken> HighlightingsCopy = Highlightings;
1443 {
1444 std::lock_guard<std::mutex> Lock(HighlightingsMutex);
1445 Old = std::move(FileToHighlightings[File]);
1446 FileToHighlightings[File] = std::move(HighlightingsCopy);
1447 }
1448 // LSP allows us to send incremental edits of highlightings. Also need to diff
1449 // to remove highlightings from tokens that should no longer have them.
Haojian Wu0a6000f2019-08-26 08:38:45 +00001450 std::vector<LineHighlightings> Diffed = diffHighlightings(Highlightings, Old);
Sam McCalledf6a192020-03-24 00:31:14 +01001451 TheiaSemanticHighlightingParams Notification;
Sam McCall2cd33e62020-03-04 00:33:29 +01001452 Notification.TextDocument.uri =
1453 URIForFile::canonicalize(File, /*TUPath=*/File);
1454 Notification.TextDocument.version = decodeVersion(Version);
Sam McCalledf6a192020-03-24 00:31:14 +01001455 Notification.Lines = toTheiaSemanticHighlightingInformation(Diffed);
1456 publishTheiaSemanticHighlighting(Notification);
Johan Vikstroma848dab2019-07-04 07:53:12 +00001457}
1458
Sam McCall2cd33e62020-03-04 00:33:29 +01001459void ClangdLSPServer::onDiagnosticsReady(PathRef File, llvm::StringRef Version,
Sam McCalla7bb0cc2018-03-12 23:22:35 +00001460 std::vector<Diag> Diagnostics) {
Sam McCall6525a6b2020-03-03 12:44:40 +01001461 PublishDiagnosticsParams Notification;
Sam McCall2cd33e62020-03-04 00:33:29 +01001462 Notification.version = decodeVersion(Version);
Sam McCall6525a6b2020-03-03 12:44:40 +01001463 Notification.uri = URIForFile::canonicalize(File, /*TUPath=*/File);
Ilya Biryukov38d79772017-05-16 09:38:59 +00001464 DiagnosticToReplacementMap LocalFixIts; // Temporary storage
Sam McCalla7bb0cc2018-03-12 23:22:35 +00001465 for (auto &Diag : Diagnostics) {
Sam McCall6525a6b2020-03-03 12:44:40 +01001466 toLSPDiags(Diag, Notification.uri, DiagOpts,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001467 [&](clangd::Diagnostic Diag, llvm::ArrayRef<Fix> Fixes) {
Sam McCall16e70702018-10-24 07:59:38 +00001468 auto &FixItsForDiagnostic = LocalFixIts[Diag];
1469 llvm::copy(Fixes, std::back_inserter(FixItsForDiagnostic));
Sam McCall6525a6b2020-03-03 12:44:40 +01001470 Notification.diagnostics.push_back(std::move(Diag));
Sam McCall16e70702018-10-24 07:59:38 +00001471 });
Ilya Biryukov38d79772017-05-16 09:38:59 +00001472 }
1473
1474 // Cache FixIts
1475 {
Ilya Biryukov38d79772017-05-16 09:38:59 +00001476 std::lock_guard<std::mutex> Lock(FixItsMutex);
1477 FixItsMap[File] = LocalFixIts;
1478 }
1479
Ilya Biryukov49c10712019-03-25 10:15:11 +00001480 // Send a notification to the LSP client.
Sam McCall6525a6b2020-03-03 12:44:40 +01001481 publishDiagnostics(Notification);
Ilya Biryukov38d79772017-05-16 09:38:59 +00001482}
Simon Marchi9569fd52018-03-16 14:30:42 +00001483
Sam McCall7d20e802020-01-22 19:41:45 +01001484void ClangdLSPServer::onBackgroundIndexProgress(
1485 const BackgroundQueue::Stats &Stats) {
1486 static const char ProgressToken[] = "backgroundIndexProgress";
1487 std::lock_guard<std::mutex> Lock(BackgroundIndexProgressMutex);
1488
1489 auto NotifyProgress = [this](const BackgroundQueue::Stats &Stats) {
1490 if (BackgroundIndexProgressState != BackgroundIndexProgress::Live) {
1491 WorkDoneProgressBegin Begin;
1492 Begin.percentage = true;
1493 Begin.title = "indexing";
1494 progress(ProgressToken, std::move(Begin));
1495 BackgroundIndexProgressState = BackgroundIndexProgress::Live;
1496 }
1497
1498 if (Stats.Completed < Stats.Enqueued) {
1499 assert(Stats.Enqueued > Stats.LastIdle);
1500 WorkDoneProgressReport Report;
1501 Report.percentage = 100.0 * (Stats.Completed - Stats.LastIdle) /
1502 (Stats.Enqueued - Stats.LastIdle);
1503 Report.message =
1504 llvm::formatv("{0}/{1}", Stats.Completed - Stats.LastIdle,
1505 Stats.Enqueued - Stats.LastIdle);
1506 progress(ProgressToken, std::move(Report));
1507 } else {
1508 assert(Stats.Completed == Stats.Enqueued);
1509 progress(ProgressToken, WorkDoneProgressEnd());
1510 BackgroundIndexProgressState = BackgroundIndexProgress::Empty;
1511 }
1512 };
1513
1514 switch (BackgroundIndexProgressState) {
1515 case BackgroundIndexProgress::Unsupported:
1516 return;
1517 case BackgroundIndexProgress::Creating:
1518 // Cache this update for when the progress bar is available.
1519 PendingBackgroundIndexProgress = Stats;
1520 return;
1521 case BackgroundIndexProgress::Empty: {
1522 if (BackgroundIndexSkipCreate) {
1523 NotifyProgress(Stats);
1524 break;
1525 }
1526 // Cache this update for when the progress bar is available.
1527 PendingBackgroundIndexProgress = Stats;
1528 BackgroundIndexProgressState = BackgroundIndexProgress::Creating;
1529 WorkDoneProgressCreateParams CreateRequest;
1530 CreateRequest.token = ProgressToken;
1531 call<std::nullptr_t>(
1532 "window/workDoneProgress/create", CreateRequest,
1533 [this, NotifyProgress](llvm::Expected<std::nullptr_t> E) {
1534 std::lock_guard<std::mutex> Lock(BackgroundIndexProgressMutex);
1535 if (E) {
1536 NotifyProgress(this->PendingBackgroundIndexProgress);
1537 } else {
1538 elog("Failed to create background index progress bar: {0}",
1539 E.takeError());
1540 // give up forever rather than thrashing about
1541 BackgroundIndexProgressState = BackgroundIndexProgress::Unsupported;
1542 }
1543 });
1544 break;
1545 }
1546 case BackgroundIndexProgress::Live:
1547 NotifyProgress(Stats);
1548 break;
1549 }
1550}
1551
Haojian Wub6188492018-12-20 15:39:12 +00001552void ClangdLSPServer::onFileUpdated(PathRef File, const TUStatus &Status) {
1553 if (!SupportFileStatus)
1554 return;
1555 // FIXME: we don't emit "BuildingFile" and `RunningAction`, as these
1556 // two statuses are running faster in practice, which leads the UI constantly
1557 // changing, and doesn't provide much value. We may want to emit status at a
1558 // reasonable time interval (e.g. 0.5s).
1559 if (Status.Action.S == TUAction::BuildingFile ||
1560 Status.Action.S == TUAction::RunningAction)
1561 return;
1562 notify("textDocument/clangd.fileStatus", Status.render(File));
1563}
1564
David Goldman60249c22020-01-13 17:01:10 -05001565void ClangdLSPServer::reparseOpenedFiles(
1566 const llvm::StringSet<> &ModifiedFiles) {
1567 if (ModifiedFiles.empty())
1568 return;
1569 // Reparse only opened files that were modified.
Simon Marchi9569fd52018-03-16 14:30:42 +00001570 for (const Path &FilePath : DraftMgr.getActiveFiles())
David Goldman60249c22020-01-13 17:01:10 -05001571 if (ModifiedFiles.find(FilePath) != ModifiedFiles.end())
Sam McCall2cd33e62020-03-04 00:33:29 +01001572 if (auto Draft = DraftMgr.getDraft(FilePath)) // else disappeared in race?
1573 Server->addDocument(FilePath, std::move(Draft->Contents),
1574 encodeVersion(Draft->Version),
1575 WantDiagnostics::Auto);
Simon Marchi9569fd52018-03-16 14:30:42 +00001576}
Alex Lorenzf8087862018-08-01 17:39:29 +00001577
Sam McCallc008af62018-10-20 15:30:37 +00001578} // namespace clangd
1579} // namespace clang