blob: eafe353bb70ef134d97902281c36a48435e6ca72 [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"
Kadir Cetinkaya6b850322020-03-17 19:08:23 +010018#include "TUScheduler.h"
Sam McCall2c30fbc2018-10-18 12:32:04 +000019#include "Trace.h"
Eric Liu78ed91a72018-01-29 15:37:46 +000020#include "URI.h"
Sam McCall395fde72019-06-18 13:37:54 +000021#include "refactor/Tweak.h"
Sam McCall6f7dca92020-03-03 12:25:46 +010022#include "clang/Basic/Version.h"
Ilya Biryukovcce67a32019-01-29 14:17:36 +000023#include "clang/Tooling/Core/Replacement.h"
Kadir Cetinkaya256247c2019-06-26 07:45:27 +000024#include "llvm/ADT/ArrayRef.h"
Sam McCalla69698f2019-03-27 17:47:49 +000025#include "llvm/ADT/Optional.h"
Kadir Cetinkaya689bf932018-08-24 13:09:41 +000026#include "llvm/ADT/ScopeExit.h"
Kadir Cetinkaya5b270932019-09-09 12:28:44 +000027#include "llvm/ADT/StringRef.h"
Utkarsh Saxena55925da2019-09-24 13:38:33 +000028#include "llvm/ADT/iterator_range.h"
Simon Marchi9569fd52018-03-16 14:30:42 +000029#include "llvm/Support/Errc.h"
Ilya Biryukovcce67a32019-01-29 14:17:36 +000030#include "llvm/Support/Error.h"
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +000031#include "llvm/Support/FormatVariadic.h"
Utkarsh Saxena55925da2019-09-24 13:38:33 +000032#include "llvm/Support/JSON.h"
Eric Liu5740ff52018-01-31 16:26:27 +000033#include "llvm/Support/Path.h"
Kadir Cetinkaya5b270932019-09-09 12:28:44 +000034#include "llvm/Support/SHA1.h"
Sam McCall2c30fbc2018-10-18 12:32:04 +000035#include "llvm/Support/ScopedPrinter.h"
Kadir Cetinkaya5b270932019-09-09 12:28:44 +000036#include <cstddef>
Utkarsh Saxena55925da2019-09-24 13:38:33 +000037#include <memory>
Sam McCall7d20e802020-01-22 19:41:45 +010038#include <mutex>
Kadir Cetinkaya5b270932019-09-09 12:28:44 +000039#include <string>
Utkarsh Saxena55925da2019-09-24 13:38:33 +000040#include <vector>
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +000041
Sam McCallc008af62018-10-20 15:30:37 +000042namespace clang {
43namespace clangd {
Ilya Biryukovafb55542017-05-16 14:40:30 +000044namespace {
Sam McCall2cd33e62020-03-04 00:33:29 +010045
46// LSP defines file versions as numbers that increase.
47// ClangdServer treats them as opaque and therefore uses strings instead.
48std::string encodeVersion(int64_t LSPVersion) {
49 return llvm::to_string(LSPVersion);
50}
51llvm::Optional<int64_t> decodeVersion(llvm::StringRef Encoded) {
52 int64_t Result;
53 if (llvm::to_integer(Encoded, Result, 10))
54 return Result;
55 else if (!Encoded.empty()) // Empty can be e.g. diagnostics on close.
56 elog("unexpected non-numeric version {0}", Encoded);
57 return llvm::None;
58}
59
Ilya Biryukovcce67a32019-01-29 14:17:36 +000060/// Transforms a tweak into a code action that would apply it if executed.
61/// EXPECTS: T.prepare() was called and returned true.
62CodeAction toCodeAction(const ClangdServer::TweakRef &T, const URIForFile &File,
63 Range Selection) {
64 CodeAction CA;
65 CA.title = T.Title;
Sam McCall395fde72019-06-18 13:37:54 +000066 switch (T.Intent) {
67 case Tweak::Refactor:
Benjamin Krameradcd0262020-01-28 20:23:46 +010068 CA.kind = std::string(CodeAction::REFACTOR_KIND);
Sam McCall395fde72019-06-18 13:37:54 +000069 break;
70 case Tweak::Info:
Benjamin Krameradcd0262020-01-28 20:23:46 +010071 CA.kind = std::string(CodeAction::INFO_KIND);
Sam McCall395fde72019-06-18 13:37:54 +000072 break;
73 }
Ilya Biryukovcce67a32019-01-29 14:17:36 +000074 // This tweak may have an expensive second stage, we only run it if the user
75 // actually chooses it in the UI. We reply with a command that would run the
76 // corresponding tweak.
77 // FIXME: for some tweaks, computing the edits is cheap and we could send them
78 // directly.
79 CA.command.emplace();
80 CA.command->title = T.Title;
Benjamin Krameradcd0262020-01-28 20:23:46 +010081 CA.command->command = std::string(Command::CLANGD_APPLY_TWEAK);
Ilya Biryukovcce67a32019-01-29 14:17:36 +000082 CA.command->tweakArgs.emplace();
83 CA.command->tweakArgs->file = File;
84 CA.command->tweakArgs->tweakID = T.ID;
85 CA.command->tweakArgs->selection = Selection;
86 return CA;
Simon Pilgrime9a136b2019-02-03 14:08:30 +000087}
Ilya Biryukovcce67a32019-01-29 14:17:36 +000088
Ilya Biryukov19d75602018-11-23 15:21:19 +000089void adjustSymbolKinds(llvm::MutableArrayRef<DocumentSymbol> Syms,
90 SymbolKindBitset Kinds) {
91 for (auto &S : Syms) {
92 S.kind = adjustKindToCapability(S.kind, Kinds);
93 adjustSymbolKinds(S.children, Kinds);
94 }
95}
96
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +000097SymbolKindBitset defaultSymbolKinds() {
98 SymbolKindBitset Defaults;
99 for (size_t I = SymbolKindMin; I <= static_cast<size_t>(SymbolKind::Array);
100 ++I)
101 Defaults.set(I);
102 return Defaults;
103}
104
Kadir Cetinkaya133d46f2018-09-27 17:13:07 +0000105CompletionItemKindBitset defaultCompletionItemKinds() {
106 CompletionItemKindBitset Defaults;
107 for (size_t I = CompletionItemKindMin;
108 I <= static_cast<size_t>(CompletionItemKind::Reference); ++I)
109 Defaults.set(I);
110 return Defaults;
111}
112
Haojian Wu1ca2ee42019-07-04 12:27:21 +0000113// Build a lookup table (HighlightingKind => {TextMate Scopes}), which is sent
114// to the LSP client.
115std::vector<std::vector<std::string>> buildHighlightScopeLookupTable() {
116 std::vector<std::vector<std::string>> LookupTable;
117 // HighlightingKind is using as the index.
Ilya Biryukov63d5d162019-09-09 08:57:17 +0000118 for (int KindValue = 0; KindValue <= (int)HighlightingKind::LastKind;
Haojian Wu1ca2ee42019-07-04 12:27:21 +0000119 ++KindValue)
Benjamin Krameradcd0262020-01-28 20:23:46 +0100120 LookupTable.push_back(
121 {std::string(toTextMateScope((HighlightingKind)(KindValue)))});
Haojian Wu1ca2ee42019-07-04 12:27:21 +0000122 return LookupTable;
123}
124
Haojian Wu852bafa2019-10-23 14:40:20 +0200125// Makes sure edits in \p FE are applicable to latest file contents reported by
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000126// editor. If not generates an error message containing information about files
127// that needs to be saved.
Haojian Wu852bafa2019-10-23 14:40:20 +0200128llvm::Error validateEdits(const DraftStore &DraftMgr, const FileEdits &FE) {
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000129 size_t InvalidFileCount = 0;
130 llvm::StringRef LastInvalidFile;
Haojian Wu852bafa2019-10-23 14:40:20 +0200131 for (const auto &It : FE) {
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000132 if (auto Draft = DraftMgr.getDraft(It.first())) {
133 // If the file is open in user's editor, make sure the version we
134 // saw and current version are compatible as this is the text that
135 // will be replaced by editors.
Sam McCallcaf5a4d2020-03-03 15:57:39 +0100136 if (!It.second.canApplyTo(Draft->Contents)) {
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000137 ++InvalidFileCount;
138 LastInvalidFile = It.first();
139 }
140 }
141 }
142 if (!InvalidFileCount)
143 return llvm::Error::success();
144 if (InvalidFileCount == 1)
145 return llvm::createStringError(llvm::inconvertibleErrorCode(),
146 "File must be saved first: " +
147 LastInvalidFile);
148 return llvm::createStringError(
149 llvm::inconvertibleErrorCode(),
150 "Files must be saved first: " + LastInvalidFile + " (and " +
151 llvm::to_string(InvalidFileCount - 1) + " others)");
152}
153
Ilya Biryukovafb55542017-05-16 14:40:30 +0000154} // namespace
155
Sam McCall2c30fbc2018-10-18 12:32:04 +0000156// MessageHandler dispatches incoming LSP messages.
157// It handles cross-cutting concerns:
158// - serializes/deserializes protocol objects to JSON
159// - logging of inbound messages
160// - cancellation handling
161// - basic call tracing
Sam McCall3d0adbe2018-10-18 14:41:50 +0000162// MessageHandler ensures that initialize() is called before any other handler.
Sam McCall2c30fbc2018-10-18 12:32:04 +0000163class ClangdLSPServer::MessageHandler : public Transport::MessageHandler {
164public:
165 MessageHandler(ClangdLSPServer &Server) : Server(Server) {}
166
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000167 bool onNotify(llvm::StringRef Method, llvm::json::Value Params) override {
Sam McCalla69698f2019-03-27 17:47:49 +0000168 WithContext HandlerContext(handlerContext());
Sam McCall2c30fbc2018-10-18 12:32:04 +0000169 log("<-- {0}", Method);
170 if (Method == "exit")
171 return false;
Sam McCall3d0adbe2018-10-18 14:41:50 +0000172 if (!Server.Server)
173 elog("Notification {0} before initialization", Method);
174 else if (Method == "$/cancelRequest")
Sam McCall2c30fbc2018-10-18 12:32:04 +0000175 onCancel(std::move(Params));
176 else if (auto Handler = Notifications.lookup(Method))
177 Handler(std::move(Params));
178 else
179 log("unhandled notification {0}", Method);
180 return true;
181 }
182
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000183 bool onCall(llvm::StringRef Method, llvm::json::Value Params,
184 llvm::json::Value ID) override {
Sam McCalla69698f2019-03-27 17:47:49 +0000185 WithContext HandlerContext(handlerContext());
Sam McCalle2f3a732018-10-24 14:26:26 +0000186 // Calls can be canceled by the client. Add cancellation context.
187 WithContext WithCancel(cancelableRequestContext(ID));
188 trace::Span Tracer(Method);
189 SPAN_ATTACH(Tracer, "Params", Params);
190 ReplyOnce Reply(ID, Method, &Server, Tracer.Args);
Sam McCall2c30fbc2018-10-18 12:32:04 +0000191 log("<-- {0}({1})", Method, ID);
Sam McCall3d0adbe2018-10-18 14:41:50 +0000192 if (!Server.Server && Method != "initialize") {
193 elog("Call {0} before initialization.", Method);
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000194 Reply(llvm::make_error<LSPError>("server not initialized",
195 ErrorCode::ServerNotInitialized));
Sam McCall3d0adbe2018-10-18 14:41:50 +0000196 } else if (auto Handler = Calls.lookup(Method))
Sam McCalle2f3a732018-10-24 14:26:26 +0000197 Handler(std::move(Params), std::move(Reply));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000198 else
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000199 Reply(llvm::make_error<LSPError>("method not found",
200 ErrorCode::MethodNotFound));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000201 return true;
202 }
203
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000204 bool onReply(llvm::json::Value ID,
205 llvm::Expected<llvm::json::Value> Result) override {
Sam McCalla69698f2019-03-27 17:47:49 +0000206 WithContext HandlerContext(handlerContext());
Haojian Wuf2516342019-08-05 12:48:09 +0000207
208 Callback<llvm::json::Value> ReplyHandler = nullptr;
209 if (auto IntID = ID.getAsInteger()) {
210 std::lock_guard<std::mutex> Mutex(CallMutex);
211 // Find a corresponding callback for the request ID;
212 for (size_t Index = 0; Index < ReplyCallbacks.size(); ++Index) {
213 if (ReplyCallbacks[Index].first == *IntID) {
214 ReplyHandler = std::move(ReplyCallbacks[Index].second);
215 ReplyCallbacks.erase(ReplyCallbacks.begin() +
216 Index); // remove the entry
217 break;
218 }
219 }
220 }
221
222 if (!ReplyHandler) {
223 // No callback being found, use a default log callback.
224 ReplyHandler = [&ID](llvm::Expected<llvm::json::Value> Result) {
225 elog("received a reply with ID {0}, but there was no such call", ID);
226 if (!Result)
227 llvm::consumeError(Result.takeError());
228 };
229 }
230
231 // Log and run the reply handler.
232 if (Result) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000233 log("<-- reply({0})", ID);
Haojian Wuf2516342019-08-05 12:48:09 +0000234 ReplyHandler(std::move(Result));
235 } else {
236 auto Err = Result.takeError();
237 log("<-- reply({0}) error: {1}", ID, Err);
238 ReplyHandler(std::move(Err));
239 }
Sam McCall2c30fbc2018-10-18 12:32:04 +0000240 return true;
241 }
242
243 // Bind an LSP method name to a call.
Sam McCalle2f3a732018-10-24 14:26:26 +0000244 template <typename Param, typename Result>
Sam McCall2c30fbc2018-10-18 12:32:04 +0000245 void bind(const char *Method,
Sam McCalle2f3a732018-10-24 14:26:26 +0000246 void (ClangdLSPServer::*Handler)(const Param &, Callback<Result>)) {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000247 Calls[Method] = [Method, Handler, this](llvm::json::Value RawParams,
Sam McCalle2f3a732018-10-24 14:26:26 +0000248 ReplyOnce Reply) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000249 Param P;
Sam McCalle2f3a732018-10-24 14:26:26 +0000250 if (fromJSON(RawParams, P)) {
251 (Server.*Handler)(P, std::move(Reply));
252 } else {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000253 elog("Failed to decode {0} request.", Method);
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000254 Reply(llvm::make_error<LSPError>("failed to decode request",
255 ErrorCode::InvalidRequest));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000256 }
Sam McCall2c30fbc2018-10-18 12:32:04 +0000257 };
258 }
259
Haojian Wuf2516342019-08-05 12:48:09 +0000260 // Bind a reply callback to a request. The callback will be invoked when
261 // clangd receives the reply from the LSP client.
262 // Return a call id of the request.
263 llvm::json::Value bindReply(Callback<llvm::json::Value> Reply) {
264 llvm::Optional<std::pair<int, Callback<llvm::json::Value>>> OldestCB;
265 int ID;
266 {
267 std::lock_guard<std::mutex> Mutex(CallMutex);
268 ID = NextCallID++;
269 ReplyCallbacks.emplace_back(ID, std::move(Reply));
270
271 // If the queue overflows, we assume that the client didn't reply the
272 // oldest request, and run the corresponding callback which replies an
273 // error to the client.
274 if (ReplyCallbacks.size() > MaxReplayCallbacks) {
275 elog("more than {0} outstanding LSP calls, forgetting about {1}",
276 MaxReplayCallbacks, ReplyCallbacks.front().first);
277 OldestCB = std::move(ReplyCallbacks.front());
278 ReplyCallbacks.pop_front();
279 }
280 }
281 if (OldestCB)
282 OldestCB->second(llvm::createStringError(
283 llvm::inconvertibleErrorCode(),
284 llvm::formatv("failed to receive a client reply for request ({0})",
285 OldestCB->first)));
286 return ID;
287 }
288
Sam McCall2c30fbc2018-10-18 12:32:04 +0000289 // Bind an LSP method name to a notification.
290 template <typename Param>
291 void bind(const char *Method,
292 void (ClangdLSPServer::*Handler)(const Param &)) {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000293 Notifications[Method] = [Method, Handler,
294 this](llvm::json::Value RawParams) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000295 Param P;
296 if (!fromJSON(RawParams, P)) {
297 elog("Failed to decode {0} request.", Method);
298 return;
299 }
300 trace::Span Tracer(Method);
301 SPAN_ATTACH(Tracer, "Params", RawParams);
302 (Server.*Handler)(P);
303 };
304 }
305
306private:
Sam McCalle2f3a732018-10-24 14:26:26 +0000307 // Function object to reply to an LSP call.
308 // Each instance must be called exactly once, otherwise:
309 // - the bug is logged, and (in debug mode) an assert will fire
310 // - if there was no reply, an error reply is sent
311 // - if there were multiple replies, only the first is sent
312 class ReplyOnce {
313 std::atomic<bool> Replied = {false};
Sam McCalld7babe42018-10-24 15:18:40 +0000314 std::chrono::steady_clock::time_point Start;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000315 llvm::json::Value ID;
Sam McCalle2f3a732018-10-24 14:26:26 +0000316 std::string Method;
317 ClangdLSPServer *Server; // Null when moved-from.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000318 llvm::json::Object *TraceArgs;
Sam McCalle2f3a732018-10-24 14:26:26 +0000319
320 public:
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000321 ReplyOnce(const llvm::json::Value &ID, llvm::StringRef Method,
322 ClangdLSPServer *Server, llvm::json::Object *TraceArgs)
Sam McCalld7babe42018-10-24 15:18:40 +0000323 : Start(std::chrono::steady_clock::now()), ID(ID), Method(Method),
324 Server(Server), TraceArgs(TraceArgs) {
Sam McCalle2f3a732018-10-24 14:26:26 +0000325 assert(Server);
326 }
327 ReplyOnce(ReplyOnce &&Other)
Sam McCalld7babe42018-10-24 15:18:40 +0000328 : Replied(Other.Replied.load()), Start(Other.Start),
329 ID(std::move(Other.ID)), Method(std::move(Other.Method)),
330 Server(Other.Server), TraceArgs(Other.TraceArgs) {
Sam McCalle2f3a732018-10-24 14:26:26 +0000331 Other.Server = nullptr;
332 }
Ilya Biryukov22fa4652019-01-03 13:28:05 +0000333 ReplyOnce &operator=(ReplyOnce &&) = delete;
Sam McCalle2f3a732018-10-24 14:26:26 +0000334 ReplyOnce(const ReplyOnce &) = delete;
Ilya Biryukov22fa4652019-01-03 13:28:05 +0000335 ReplyOnce &operator=(const ReplyOnce &) = delete;
Sam McCalle2f3a732018-10-24 14:26:26 +0000336
337 ~ReplyOnce() {
Haojian Wuf2516342019-08-05 12:48:09 +0000338 // There's one legitimate reason to never reply to a request: clangd's
339 // request handler send a call to the client (e.g. applyEdit) and the
340 // client never replied. In this case, the ReplyOnce is owned by
341 // ClangdLSPServer's reply callback table and is destroyed along with the
342 // server. We don't attempt to send a reply in this case, there's little
343 // to be gained from doing so.
344 if (Server && !Server->IsBeingDestroyed && !Replied) {
Sam McCalle2f3a732018-10-24 14:26:26 +0000345 elog("No reply to message {0}({1})", Method, ID);
346 assert(false && "must reply to all calls!");
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000347 (*this)(llvm::make_error<LSPError>("server failed to reply",
348 ErrorCode::InternalError));
Sam McCalle2f3a732018-10-24 14:26:26 +0000349 }
350 }
351
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000352 void operator()(llvm::Expected<llvm::json::Value> Reply) {
Sam McCalle2f3a732018-10-24 14:26:26 +0000353 assert(Server && "moved-from!");
354 if (Replied.exchange(true)) {
355 elog("Replied twice to message {0}({1})", Method, ID);
356 assert(false && "must reply to each call only once!");
357 return;
358 }
Sam McCalld7babe42018-10-24 15:18:40 +0000359 auto Duration = std::chrono::steady_clock::now() - Start;
360 if (Reply) {
361 log("--> reply:{0}({1}) {2:ms}", Method, ID, Duration);
362 if (TraceArgs)
Sam McCalle2f3a732018-10-24 14:26:26 +0000363 (*TraceArgs)["Reply"] = *Reply;
Sam McCalld7babe42018-10-24 15:18:40 +0000364 std::lock_guard<std::mutex> Lock(Server->TranspWriter);
365 Server->Transp.reply(std::move(ID), std::move(Reply));
366 } else {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000367 llvm::Error Err = Reply.takeError();
Sam McCalld7babe42018-10-24 15:18:40 +0000368 log("--> reply:{0}({1}) {2:ms}, error: {3}", Method, ID, Duration, Err);
369 if (TraceArgs)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000370 (*TraceArgs)["Error"] = llvm::to_string(Err);
Sam McCalld7babe42018-10-24 15:18:40 +0000371 std::lock_guard<std::mutex> Lock(Server->TranspWriter);
372 Server->Transp.reply(std::move(ID), std::move(Err));
Sam McCalle2f3a732018-10-24 14:26:26 +0000373 }
Sam McCalle2f3a732018-10-24 14:26:26 +0000374 }
375 };
376
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000377 llvm::StringMap<std::function<void(llvm::json::Value)>> Notifications;
378 llvm::StringMap<std::function<void(llvm::json::Value, ReplyOnce)>> Calls;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000379
380 // Method calls may be cancelled by ID, so keep track of their state.
381 // This needs a mutex: handlers may finish on a different thread, and that's
382 // when we clean up entries in the map.
383 mutable std::mutex RequestCancelersMutex;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000384 llvm::StringMap<std::pair<Canceler, /*Cookie*/ unsigned>> RequestCancelers;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000385 unsigned NextRequestCookie = 0; // To disambiguate reused IDs, see below.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000386 void onCancel(const llvm::json::Value &Params) {
387 const llvm::json::Value *ID = nullptr;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000388 if (auto *O = Params.getAsObject())
389 ID = O->get("id");
390 if (!ID) {
391 elog("Bad cancellation request: {0}", Params);
392 return;
393 }
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000394 auto StrID = llvm::to_string(*ID);
Sam McCall2c30fbc2018-10-18 12:32:04 +0000395 std::lock_guard<std::mutex> Lock(RequestCancelersMutex);
396 auto It = RequestCancelers.find(StrID);
397 if (It != RequestCancelers.end())
398 It->second.first(); // Invoke the canceler.
399 }
Sam McCalla69698f2019-03-27 17:47:49 +0000400
401 Context handlerContext() const {
402 return Context::current().derive(
403 kCurrentOffsetEncoding,
404 Server.NegotiatedOffsetEncoding.getValueOr(OffsetEncoding::UTF16));
405 }
406
Sam McCall2c30fbc2018-10-18 12:32:04 +0000407 // We run cancelable requests in a context that does two things:
408 // - allows cancellation using RequestCancelers[ID]
409 // - cleans up the entry in RequestCancelers when it's no longer needed
410 // If a client reuses an ID, the last wins and the first cannot be canceled.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000411 Context cancelableRequestContext(const llvm::json::Value &ID) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000412 auto Task = cancelableTask();
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000413 auto StrID = llvm::to_string(ID); // JSON-serialize ID for map key.
Sam McCall2c30fbc2018-10-18 12:32:04 +0000414 auto Cookie = NextRequestCookie++; // No lock, only called on main thread.
415 {
416 std::lock_guard<std::mutex> Lock(RequestCancelersMutex);
417 RequestCancelers[StrID] = {std::move(Task.second), Cookie};
418 }
419 // When the request ends, we can clean up the entry we just added.
420 // The cookie lets us check that it hasn't been overwritten due to ID
421 // reuse.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000422 return Task.first.derive(llvm::make_scope_exit([this, StrID, Cookie] {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000423 std::lock_guard<std::mutex> Lock(RequestCancelersMutex);
424 auto It = RequestCancelers.find(StrID);
425 if (It != RequestCancelers.end() && It->second.second == Cookie)
426 RequestCancelers.erase(It);
427 }));
428 }
429
Kadir Cetinkaya9a3a87d2019-10-09 13:59:31 +0000430 // The maximum number of callbacks held in clangd.
431 //
432 // We bound the maximum size to the pending map to prevent memory leakage
433 // for cases where LSP clients don't reply for the request.
434 // This has to go after RequestCancellers and RequestCancellersMutex since it
435 // can contain a callback that has a cancelable context.
436 static constexpr int MaxReplayCallbacks = 100;
437 mutable std::mutex CallMutex;
438 int NextCallID = 0; /* GUARDED_BY(CallMutex) */
439 std::deque<std::pair</*RequestID*/ int,
440 /*ReplyHandler*/ Callback<llvm::json::Value>>>
441 ReplyCallbacks; /* GUARDED_BY(CallMutex) */
442
Sam McCall2c30fbc2018-10-18 12:32:04 +0000443 ClangdLSPServer &Server;
444};
Haojian Wuf2516342019-08-05 12:48:09 +0000445constexpr int ClangdLSPServer::MessageHandler::MaxReplayCallbacks;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000446
447// call(), notify(), and reply() wrap the Transport, adding logging and locking.
Haojian Wuf2516342019-08-05 12:48:09 +0000448void ClangdLSPServer::callRaw(StringRef Method, llvm::json::Value Params,
449 Callback<llvm::json::Value> CB) {
450 auto ID = MsgHandler->bindReply(std::move(CB));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000451 log("--> {0}({1})", Method, ID);
Sam McCall2c30fbc2018-10-18 12:32:04 +0000452 std::lock_guard<std::mutex> Lock(TranspWriter);
453 Transp.call(Method, std::move(Params), ID);
454}
455
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000456void ClangdLSPServer::notify(llvm::StringRef Method, llvm::json::Value Params) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000457 log("--> {0}", Method);
458 std::lock_guard<std::mutex> Lock(TranspWriter);
459 Transp.notify(Method, std::move(Params));
460}
461
Sam McCall71177ac2020-03-24 02:24:47 +0100462static std::vector<llvm::StringRef> semanticTokenTypes() {
463 std::vector<llvm::StringRef> Types;
464 for (unsigned I = 0; I <= static_cast<unsigned>(HighlightingKind::LastKind);
465 ++I)
466 Types.push_back(toSemanticTokenType(static_cast<HighlightingKind>(I)));
467 return Types;
468}
469
Sam McCall2c30fbc2018-10-18 12:32:04 +0000470void ClangdLSPServer::onInitialize(const InitializeParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000471 Callback<llvm::json::Value> Reply) {
Sam McCalla69698f2019-03-27 17:47:49 +0000472 // Determine character encoding first as it affects constructed ClangdServer.
473 if (Params.capabilities.offsetEncoding && !NegotiatedOffsetEncoding) {
474 NegotiatedOffsetEncoding = OffsetEncoding::UTF16; // fallback
475 for (OffsetEncoding Supported : *Params.capabilities.offsetEncoding)
476 if (Supported != OffsetEncoding::UnsupportedEncoding) {
477 NegotiatedOffsetEncoding = Supported;
478 break;
479 }
480 }
Sam McCalla69698f2019-03-27 17:47:49 +0000481
Sam McCalledf6a192020-03-24 00:31:14 +0100482 ClangdServerOpts.TheiaSemanticHighlighting =
483 Params.capabilities.TheiaSemanticHighlighting;
Sam McCallfc830102020-04-01 12:02:28 +0200484 if (Params.capabilities.TheiaSemanticHighlighting &&
485 Params.capabilities.SemanticTokens) {
486 log("Client supports legacy semanticHighlights notification and standard "
487 "semanticTokens request, choosing the latter (no notifications).");
488 ClangdServerOpts.TheiaSemanticHighlighting = false;
489 }
490
Sam McCall0d9b40f2018-10-19 15:42:23 +0000491 if (Params.rootUri && *Params.rootUri)
Benjamin Krameradcd0262020-01-28 20:23:46 +0100492 ClangdServerOpts.WorkspaceRoot = std::string(Params.rootUri->file());
Sam McCall0d9b40f2018-10-19 15:42:23 +0000493 else if (Params.rootPath && !Params.rootPath->empty())
494 ClangdServerOpts.WorkspaceRoot = *Params.rootPath;
Sam McCall3d0adbe2018-10-18 14:41:50 +0000495 if (Server)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000496 return Reply(llvm::make_error<LSPError>("server already initialized",
497 ErrorCode::InvalidRequest));
Sam McCallbc904612018-10-25 04:22:52 +0000498 if (const auto &Dir = Params.initializationOptions.compilationDatabasePath)
499 CompileCommandsDir = Dir;
Kadir Cetinkaya256247c2019-06-26 07:45:27 +0000500 if (UseDirBasedCDB) {
Jonas Devlieghere1c705d92019-08-14 23:52:23 +0000501 BaseCDB = std::make_unique<DirectoryBasedGlobalCompilationDatabase>(
Sam McCallc55d09a2018-11-02 13:09:36 +0000502 CompileCommandsDir);
Kadir Cetinkaya256247c2019-06-26 07:45:27 +0000503 BaseCDB = getQueryDriverDatabase(
504 llvm::makeArrayRef(ClangdServerOpts.QueryDriverGlobs),
505 std::move(BaseCDB));
506 }
Sam McCall99768b22019-11-29 19:37:48 +0100507 auto Mangler = CommandMangler::detect();
508 if (ClangdServerOpts.ResourceDir)
509 Mangler.ResourceDir = *ClangdServerOpts.ResourceDir;
Kadir Cetinkayabe6b35d2019-01-22 09:10:20 +0000510 CDB.emplace(BaseCDB.get(), Params.initializationOptions.fallbackFlags,
Sam McCall99768b22019-11-29 19:37:48 +0100511 tooling::ArgumentsAdjuster(Mangler));
Kadir Cetinkaya9d662472019-10-15 14:20:52 +0000512 {
513 // Switch caller's context with LSPServer's background context. Since we
514 // rather want to propagate information from LSPServer's context into the
515 // Server, CDB, etc.
516 WithContext MainContext(BackgroundContext.clone());
517 llvm::Optional<WithContextValue> WithOffsetEncoding;
518 if (NegotiatedOffsetEncoding)
519 WithOffsetEncoding.emplace(kCurrentOffsetEncoding,
520 *NegotiatedOffsetEncoding);
Sam McCall6ef1cce2020-01-24 14:08:56 +0100521 Server.emplace(*CDB, FSProvider, ClangdServerOpts,
522 static_cast<ClangdServer::Callbacks *>(this));
Kadir Cetinkaya9d662472019-10-15 14:20:52 +0000523 }
Sam McCallbc904612018-10-25 04:22:52 +0000524 applyConfiguration(Params.initializationOptions.ConfigSettings);
Simon Marchi88016782018-08-01 11:28:49 +0000525
Sam McCallbf6a2fc2018-10-17 07:33:42 +0000526 CCOpts.EnableSnippets = Params.capabilities.CompletionSnippets;
Sam McCall8d412942019-06-18 11:57:26 +0000527 CCOpts.IncludeFixIts = Params.capabilities.CompletionFixes;
Sam McCall5f092e32019-07-08 17:27:15 +0000528 if (!CCOpts.BundleOverloads.hasValue())
529 CCOpts.BundleOverloads = Params.capabilities.HasSignatureHelp;
Sam McCallbf6a2fc2018-10-17 07:33:42 +0000530 DiagOpts.EmbedFixesInDiagnostics = Params.capabilities.DiagnosticFixes;
531 DiagOpts.SendDiagnosticCategory = Params.capabilities.DiagnosticCategory;
Sam McCallc9e4ee92019-04-18 15:17:07 +0000532 DiagOpts.EmitRelatedLocations =
533 Params.capabilities.DiagnosticRelatedInformation;
Sam McCallbf6a2fc2018-10-17 07:33:42 +0000534 if (Params.capabilities.WorkspaceSymbolKinds)
535 SupportedSymbolKinds |= *Params.capabilities.WorkspaceSymbolKinds;
536 if (Params.capabilities.CompletionItemKinds)
537 SupportedCompletionItemKinds |= *Params.capabilities.CompletionItemKinds;
538 SupportsCodeAction = Params.capabilities.CodeActionStructure;
Ilya Biryukov19d75602018-11-23 15:21:19 +0000539 SupportsHierarchicalDocumentSymbol =
540 Params.capabilities.HierarchicalDocumentSymbol;
Haojian Wub6188492018-12-20 15:39:12 +0000541 SupportFileStatus = Params.initializationOptions.FileStatus;
Ilya Biryukovf9169d02019-05-29 10:01:00 +0000542 HoverContentFormat = Params.capabilities.HoverContentFormat;
Ilya Biryukov4ef0f822019-06-04 09:36:59 +0000543 SupportsOffsetsInSignatureHelp = Params.capabilities.OffsetsInSignatureHelp;
Sam McCall7d20e802020-01-22 19:41:45 +0100544 if (Params.capabilities.WorkDoneProgress)
545 BackgroundIndexProgressState = BackgroundIndexProgress::Empty;
546 BackgroundIndexSkipCreate = Params.capabilities.ImplicitProgressCreation;
Haojian Wuf429ab62019-07-24 07:49:23 +0000547
548 // Per LSP, renameProvider can be either boolean or RenameOptions.
549 // RenameOptions will be specified if the client states it supports prepare.
550 llvm::json::Value RenameProvider =
551 llvm::json::Object{{"prepareProvider", true}};
552 if (!Params.capabilities.RenamePrepareSupport) // Only boolean allowed per LSP
553 RenameProvider = true;
554
Haojian Wu08d93f12019-08-22 14:53:45 +0000555 // Per LSP, codeActionProvide can be either boolean or CodeActionOptions.
556 // CodeActionOptions is only valid if the client supports action literal
557 // via textDocument.codeAction.codeActionLiteralSupport.
558 llvm::json::Value CodeActionProvider = true;
559 if (Params.capabilities.CodeActionStructure)
560 CodeActionProvider = llvm::json::Object{
561 {"codeActionKinds",
562 {CodeAction::QUICKFIX_KIND, CodeAction::REFACTOR_KIND,
563 CodeAction::INFO_KIND}}};
564
Sam McCalla69698f2019-03-27 17:47:49 +0000565 llvm::json::Object Result{
Sam McCall6f7dca92020-03-03 12:25:46 +0100566 {{"serverInfo",
567 llvm::json::Object{{"name", "clangd"},
568 {"version", getClangToolFullVersion("clangd")}}},
569 {"capabilities",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000570 llvm::json::Object{
Simon Marchi98082622018-03-26 14:41:40 +0000571 {"textDocumentSync", (int)TextDocumentSyncKind::Incremental},
Sam McCall0930ab02017-11-07 15:49:35 +0000572 {"documentFormattingProvider", true},
573 {"documentRangeFormattingProvider", true},
574 {"documentOnTypeFormattingProvider",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000575 llvm::json::Object{
Sam McCall25c62572019-06-10 14:26:21 +0000576 {"firstTriggerCharacter", "\n"},
Sam McCall0930ab02017-11-07 15:49:35 +0000577 {"moreTriggerCharacter", {}},
578 }},
Haojian Wu08d93f12019-08-22 14:53:45 +0000579 {"codeActionProvider", std::move(CodeActionProvider)},
Sam McCall0930ab02017-11-07 15:49:35 +0000580 {"completionProvider",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000581 llvm::json::Object{
Kirill Bobyrev2a095ff2020-02-18 17:55:12 +0100582 {"allCommitCharacters", " \t()[]{}<>:;,+-/*%^&#?.=\"'|"},
Sam McCall0930ab02017-11-07 15:49:35 +0000583 {"resolveProvider", false},
Ilya Biryukovb0826bd2019-01-03 13:37:12 +0000584 // We do extra checks for '>' and ':' in completion to only
585 // trigger on '->' and '::'.
Sam McCall0930ab02017-11-07 15:49:35 +0000586 {"triggerCharacters", {".", ">", ":"}},
587 }},
Sam McCall71177ac2020-03-24 02:24:47 +0100588 {"semanticTokensProvider",
589 llvm::json::Object{
Sam McCall9e3063e2020-04-01 16:21:44 +0200590 {"documentProvider", llvm::json::Object{{"edits", true}}},
Sam McCall71177ac2020-03-24 02:24:47 +0100591 {"rangeProvider", false},
592 {"legend",
593 llvm::json::Object{{"tokenTypes", semanticTokenTypes()},
594 {"tokenModifiers", llvm::json::Array()}}},
595 }},
Sam McCall0930ab02017-11-07 15:49:35 +0000596 {"signatureHelpProvider",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000597 llvm::json::Object{
Sam McCall0930ab02017-11-07 15:49:35 +0000598 {"triggerCharacters", {"(", ","}},
599 }},
Sam McCall866ba2c2019-02-01 11:26:13 +0000600 {"declarationProvider", true},
Sam McCall0930ab02017-11-07 15:49:35 +0000601 {"definitionProvider", true},
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000602 {"documentHighlightProvider", true},
Sam McCall8d7ecc12019-12-16 19:08:51 +0100603 {"documentLinkProvider",
604 llvm::json::Object{
605 {"resolveProvider", false},
606 }},
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000607 {"hoverProvider", true},
Haojian Wuf429ab62019-07-24 07:49:23 +0000608 {"renameProvider", std::move(RenameProvider)},
Utkarsh Saxena55925da2019-09-24 13:38:33 +0000609 {"selectionRangeProvider", true},
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000610 {"documentSymbolProvider", true},
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000611 {"workspaceSymbolProvider", true},
Sam McCall1ad142f2018-09-05 11:53:07 +0000612 {"referencesProvider", true},
Sam McCall0930ab02017-11-07 15:49:35 +0000613 {"executeCommandProvider",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000614 llvm::json::Object{
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000615 {"commands",
616 {ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND,
617 ExecuteCommandParams::CLANGD_APPLY_TWEAK}},
Sam McCall0930ab02017-11-07 15:49:35 +0000618 }},
Kadir Cetinkaya86658022019-03-19 09:27:04 +0000619 {"typeHierarchyProvider", true},
Sam McCalla69698f2019-03-27 17:47:49 +0000620 }}}};
621 if (NegotiatedOffsetEncoding)
622 Result["offsetEncoding"] = *NegotiatedOffsetEncoding;
Sam McCallfc830102020-04-01 12:02:28 +0200623 if (ClangdServerOpts.TheiaSemanticHighlighting)
Johan Vikstroma848dab2019-07-04 07:53:12 +0000624 Result.getObject("capabilities")
625 ->insert(
626 {"semanticHighlighting",
Haojian Wu1ca2ee42019-07-04 12:27:21 +0000627 llvm::json::Object{{"scopes", buildHighlightScopeLookupTable()}}});
Sam McCalla69698f2019-03-27 17:47:49 +0000628 Reply(std::move(Result));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000629}
630
Sam McCall8a2d2942020-03-03 12:12:14 +0100631void ClangdLSPServer::onInitialized(const InitializedParams &Params) {}
632
Sam McCall2c30fbc2018-10-18 12:32:04 +0000633void ClangdLSPServer::onShutdown(const ShutdownParams &Params,
634 Callback<std::nullptr_t> Reply) {
Ilya Biryukov0d9b8a32017-10-25 08:45:41 +0000635 // Do essentially nothing, just say we're ready to exit.
636 ShutdownRequestReceived = true;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000637 Reply(nullptr);
Sam McCall8a5dded2017-10-12 13:29:58 +0000638}
Ilya Biryukovafb55542017-05-16 14:40:30 +0000639
Sam McCall422c8282018-11-26 16:00:11 +0000640// sync is a clangd extension: it blocks until all background work completes.
641// It blocks the calling thread, so no messages are processed until it returns!
642void ClangdLSPServer::onSync(const NoParams &Params,
643 Callback<std::nullptr_t> Reply) {
644 if (Server->blockUntilIdleForTest(/*TimeoutSeconds=*/60))
645 Reply(nullptr);
646 else
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000647 Reply(llvm::createStringError(llvm::inconvertibleErrorCode(),
648 "Not idle after a minute"));
Sam McCall422c8282018-11-26 16:00:11 +0000649}
650
Sam McCall2c30fbc2018-10-18 12:32:04 +0000651void ClangdLSPServer::onDocumentDidOpen(
652 const DidOpenTextDocumentParams &Params) {
Simon Marchi9569fd52018-03-16 14:30:42 +0000653 PathRef File = Params.textDocument.uri.file();
Ilya Biryukovb10ef472018-06-13 09:20:41 +0000654
Sam McCall2c30fbc2018-10-18 12:32:04 +0000655 const std::string &Contents = Params.textDocument.text;
Simon Marchi9569fd52018-03-16 14:30:42 +0000656
Sam McCall2cd33e62020-03-04 00:33:29 +0100657 auto Version = DraftMgr.addDraft(File, Params.textDocument.version, Contents);
658 Server->addDocument(File, Contents, encodeVersion(Version),
659 WantDiagnostics::Yes);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000660}
661
Sam McCall2c30fbc2018-10-18 12:32:04 +0000662void ClangdLSPServer::onDocumentDidChange(
663 const DidChangeTextDocumentParams &Params) {
Eric Liu51fed182018-02-22 18:40:39 +0000664 auto WantDiags = WantDiagnostics::Auto;
665 if (Params.wantDiagnostics.hasValue())
666 WantDiags = Params.wantDiagnostics.getValue() ? WantDiagnostics::Yes
667 : WantDiagnostics::No;
Simon Marchi9569fd52018-03-16 14:30:42 +0000668
669 PathRef File = Params.textDocument.uri.file();
Sam McCallcaf5a4d2020-03-03 15:57:39 +0100670 llvm::Expected<DraftStore::Draft> Draft = DraftMgr.updateDraft(
671 File, Params.textDocument.version, Params.contentChanges);
672 if (!Draft) {
Simon Marchi98082622018-03-26 14:41:40 +0000673 // If this fails, we are most likely going to be not in sync anymore with
674 // the client. It is better to remove the draft and let further operations
675 // fail rather than giving wrong results.
676 DraftMgr.removeDraft(File);
Ilya Biryukov652364b2018-09-26 05:48:29 +0000677 Server->removeDocument(File);
Sam McCallcaf5a4d2020-03-03 15:57:39 +0100678 elog("Failed to update {0}: {1}", File, Draft.takeError());
Simon Marchi98082622018-03-26 14:41:40 +0000679 return;
680 }
Simon Marchi9569fd52018-03-16 14:30:42 +0000681
Sam McCall2cd33e62020-03-04 00:33:29 +0100682 Server->addDocument(File, Draft->Contents, encodeVersion(Draft->Version),
683 WantDiags, Params.forceRebuild);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000684}
685
Sam McCall2c30fbc2018-10-18 12:32:04 +0000686void ClangdLSPServer::onFileEvent(const DidChangeWatchedFilesParams &Params) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000687 Server->onFileEvent(Params);
Marc-Andre Laperlebf114242017-10-02 18:00:37 +0000688}
689
Sam McCall2c30fbc2018-10-18 12:32:04 +0000690void ClangdLSPServer::onCommand(const ExecuteCommandParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000691 Callback<llvm::json::Value> Reply) {
Ilya Biryukov12864002019-08-16 12:46:41 +0000692 auto ApplyEdit = [this](WorkspaceEdit WE, std::string SuccessMessage,
693 decltype(Reply) Reply) {
Eric Liuc5105f92018-02-16 14:15:55 +0000694 ApplyWorkspaceEditParams Edit;
695 Edit.edit = std::move(WE);
Ilya Biryukov12864002019-08-16 12:46:41 +0000696 call<ApplyWorkspaceEditResponse>(
697 "workspace/applyEdit", std::move(Edit),
698 [Reply = std::move(Reply), SuccessMessage = std::move(SuccessMessage)](
699 llvm::Expected<ApplyWorkspaceEditResponse> Response) mutable {
700 if (!Response)
701 return Reply(Response.takeError());
702 if (!Response->applied) {
703 std::string Reason = Response->failureReason
704 ? *Response->failureReason
705 : "unknown reason";
706 return Reply(llvm::createStringError(
707 llvm::inconvertibleErrorCode(),
708 ("edits were not applied: " + Reason).c_str()));
709 }
710 return Reply(SuccessMessage);
711 });
Eric Liuc5105f92018-02-16 14:15:55 +0000712 };
Ilya Biryukov12864002019-08-16 12:46:41 +0000713
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000714 if (Params.command == ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND &&
715 Params.workspaceEdit) {
716 // The flow for "apply-fix" :
717 // 1. We publish a diagnostic, including fixits
718 // 2. The user clicks on the diagnostic, the editor asks us for code actions
719 // 3. We send code actions, with the fixit embedded as context
720 // 4. The user selects the fixit, the editor asks us to apply it
721 // 5. We unwrap the changes and send them back to the editor
Haojian Wuf2516342019-08-05 12:48:09 +0000722 // 6. The editor applies the changes (applyEdit), and sends us a reply
723 // 7. We unwrap the reply and send a reply to the editor.
Ilya Biryukov12864002019-08-16 12:46:41 +0000724 ApplyEdit(*Params.workspaceEdit, "Fix applied.", std::move(Reply));
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000725 } else if (Params.command == ExecuteCommandParams::CLANGD_APPLY_TWEAK &&
726 Params.tweakArgs) {
727 auto Code = DraftMgr.getDraft(Params.tweakArgs->file.file());
728 if (!Code)
729 return Reply(llvm::createStringError(
730 llvm::inconvertibleErrorCode(),
731 "trying to apply a code action for a non-added file"));
732
Ilya Biryukov12864002019-08-16 12:46:41 +0000733 auto Action = [this, ApplyEdit, Reply = std::move(Reply),
734 File = Params.tweakArgs->file, Code = std::move(*Code)](
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000735 llvm::Expected<Tweak::Effect> R) mutable {
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000736 if (!R)
737 return Reply(R.takeError());
738
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000739 assert(R->ShowMessage ||
740 (!R->ApplyEdits.empty() && "tweak has no effect"));
Ilya Biryukov12864002019-08-16 12:46:41 +0000741
Sam McCall395fde72019-06-18 13:37:54 +0000742 if (R->ShowMessage) {
743 ShowMessageParams Msg;
744 Msg.message = *R->ShowMessage;
745 Msg.type = MessageType::Info;
746 notify("window/showMessage", Msg);
747 }
Ilya Biryukov12864002019-08-16 12:46:41 +0000748 // When no edit is specified, make sure we Reply().
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000749 if (R->ApplyEdits.empty())
750 return Reply("Tweak applied.");
751
Haojian Wu852bafa2019-10-23 14:40:20 +0200752 if (auto Err = validateEdits(DraftMgr, R->ApplyEdits))
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000753 return Reply(std::move(Err));
754
755 WorkspaceEdit WE;
756 WE.changes.emplace();
757 for (const auto &It : R->ApplyEdits) {
Kadir Cetinkayae95e5162019-10-02 09:12:01 +0000758 (*WE.changes)[URI::createFile(It.first()).toString()] =
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000759 It.second.asTextEdits();
760 }
761 // ApplyEdit will take care of calling Reply().
762 return ApplyEdit(std::move(WE), "Tweak applied.", std::move(Reply));
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000763 };
764 Server->applyTweak(Params.tweakArgs->file.file(),
765 Params.tweakArgs->selection, Params.tweakArgs->tweakID,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000766 std::move(Action));
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000767 } else {
768 // We should not get here because ExecuteCommandParams would not have
769 // parsed in the first place and this handler should not be called. But if
770 // more commands are added, this will be here has a safe guard.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000771 Reply(llvm::make_error<LSPError>(
772 llvm::formatv("Unsupported command \"{0}\".", Params.command).str(),
Sam McCall2c30fbc2018-10-18 12:32:04 +0000773 ErrorCode::InvalidParams));
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000774 }
775}
776
Sam McCall2c30fbc2018-10-18 12:32:04 +0000777void ClangdLSPServer::onWorkspaceSymbol(
778 const WorkspaceSymbolParams &Params,
779 Callback<std::vector<SymbolInformation>> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000780 Server->workspaceSymbols(
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000781 Params.query, CCOpts.Limit,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000782 [Reply = std::move(Reply),
783 this](llvm::Expected<std::vector<SymbolInformation>> Items) mutable {
784 if (!Items)
785 return Reply(Items.takeError());
786 for (auto &Sym : *Items)
787 Sym.kind = adjustKindToCapability(Sym.kind, SupportedSymbolKinds);
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000788
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000789 Reply(std::move(*Items));
790 });
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000791}
792
Haojian Wuf429ab62019-07-24 07:49:23 +0000793void ClangdLSPServer::onPrepareRename(const TextDocumentPositionParams &Params,
794 Callback<llvm::Optional<Range>> Reply) {
795 Server->prepareRename(Params.textDocument.uri.file(), Params.position,
Haojian Wu34d0e1b2020-02-19 15:37:36 +0100796 RenameOpts, std::move(Reply));
Haojian Wuf429ab62019-07-24 07:49:23 +0000797}
798
Sam McCall2c30fbc2018-10-18 12:32:04 +0000799void ClangdLSPServer::onRename(const RenameParams &Params,
800 Callback<WorkspaceEdit> Reply) {
Benjamin Krameradcd0262020-01-28 20:23:46 +0100801 Path File = std::string(Params.textDocument.uri.file());
Sam McCallcaf5a4d2020-03-03 15:57:39 +0100802 if (!DraftMgr.getDraft(File))
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000803 return Reply(llvm::make_error<LSPError>(
804 "onRename called for non-added file", ErrorCode::InvalidParams));
Haojian Wu852bafa2019-10-23 14:40:20 +0200805 Server->rename(
Haojian Wu34d0e1b2020-02-19 15:37:36 +0100806 File, Params.position, Params.newName, RenameOpts,
Haojian Wu852bafa2019-10-23 14:40:20 +0200807 [File, Params, Reply = std::move(Reply),
808 this](llvm::Expected<FileEdits> Edits) mutable {
809 if (!Edits)
810 return Reply(Edits.takeError());
811 if (auto Err = validateEdits(DraftMgr, *Edits))
812 return Reply(std::move(Err));
813 WorkspaceEdit Result;
814 Result.changes.emplace();
815 for (const auto &Rep : *Edits) {
816 (*Result.changes)[URI::createFile(Rep.first()).toString()] =
817 Rep.second.asTextEdits();
818 }
819 Reply(Result);
820 });
Haojian Wu345099c2017-11-09 11:30:04 +0000821}
822
Sam McCall2c30fbc2018-10-18 12:32:04 +0000823void ClangdLSPServer::onDocumentDidClose(
824 const DidCloseTextDocumentParams &Params) {
Simon Marchi9569fd52018-03-16 14:30:42 +0000825 PathRef File = Params.textDocument.uri.file();
826 DraftMgr.removeDraft(File);
Ilya Biryukov652364b2018-09-26 05:48:29 +0000827 Server->removeDocument(File);
Ilya Biryukov49c10712019-03-25 10:15:11 +0000828
829 {
830 std::lock_guard<std::mutex> Lock(FixItsMutex);
831 FixItsMap.erase(File);
832 }
Johan Vikstromc2653ef22019-08-01 08:08:44 +0000833 {
834 std::lock_guard<std::mutex> HLock(HighlightingsMutex);
835 FileToHighlightings.erase(File);
836 }
Sam McCall9e3063e2020-04-01 16:21:44 +0200837 {
838 std::lock_guard<std::mutex> HLock(SemanticTokensMutex);
839 LastSemanticTokens.erase(File);
840 }
Ilya Biryukov49c10712019-03-25 10:15:11 +0000841 // clangd will not send updates for this file anymore, so we empty out the
842 // list of diagnostics shown on the client (e.g. in the "Problems" pane of
843 // VSCode). Note that this cannot race with actual diagnostics responses
844 // because removeDocument() guarantees no diagnostic callbacks will be
845 // executed after it returns.
Sam McCall6525a6b2020-03-03 12:44:40 +0100846 PublishDiagnosticsParams Notification;
847 Notification.uri = URIForFile::canonicalize(File, /*TUPath=*/File);
848 publishDiagnostics(Notification);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000849}
850
Sam McCall4db732a2017-09-30 10:08:52 +0000851void ClangdLSPServer::onDocumentOnTypeFormatting(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000852 const DocumentOnTypeFormattingParams &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 "onDocumentOnTypeFormatting called for non-added file",
859 ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000860
Sam McCallcaf5a4d2020-03-03 15:57:39 +0100861 Reply(Server->formatOnType(Code->Contents, File, Params.position, Params.ch));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000862}
863
Sam McCall4db732a2017-09-30 10:08:52 +0000864void ClangdLSPServer::onDocumentRangeFormatting(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000865 const DocumentRangeFormattingParams &Params,
866 Callback<std::vector<TextEdit>> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000867 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000868 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000869 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000870 return Reply(llvm::make_error<LSPError>(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000871 "onDocumentRangeFormatting called for non-added file",
872 ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000873
Sam McCallcaf5a4d2020-03-03 15:57:39 +0100874 auto ReplacementsOrError =
875 Server->formatRange(Code->Contents, File, Params.range);
Raoul Wols212bcf82017-12-12 20:25:06 +0000876 if (ReplacementsOrError)
Sam McCallcaf5a4d2020-03-03 15:57:39 +0100877 Reply(replacementsToEdits(Code->Contents, ReplacementsOrError.get()));
Raoul Wols212bcf82017-12-12 20:25:06 +0000878 else
Sam McCall2c30fbc2018-10-18 12:32:04 +0000879 Reply(ReplacementsOrError.takeError());
Ilya Biryukovafb55542017-05-16 14:40:30 +0000880}
881
Sam McCall2c30fbc2018-10-18 12:32:04 +0000882void ClangdLSPServer::onDocumentFormatting(
883 const DocumentFormattingParams &Params,
884 Callback<std::vector<TextEdit>> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000885 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000886 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000887 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000888 return Reply(llvm::make_error<LSPError>(
889 "onDocumentFormatting called for non-added file",
890 ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000891
Sam McCallcaf5a4d2020-03-03 15:57:39 +0100892 auto ReplacementsOrError = Server->formatFile(Code->Contents, File);
Raoul Wols212bcf82017-12-12 20:25:06 +0000893 if (ReplacementsOrError)
Sam McCallcaf5a4d2020-03-03 15:57:39 +0100894 Reply(replacementsToEdits(Code->Contents, ReplacementsOrError.get()));
Raoul Wols212bcf82017-12-12 20:25:06 +0000895 else
Sam McCall2c30fbc2018-10-18 12:32:04 +0000896 Reply(ReplacementsOrError.takeError());
Sam McCall4db732a2017-09-30 10:08:52 +0000897}
898
Ilya Biryukov19d75602018-11-23 15:21:19 +0000899/// The functions constructs a flattened view of the DocumentSymbol hierarchy.
900/// Used by the clients that do not support the hierarchical view.
901static std::vector<SymbolInformation>
902flattenSymbolHierarchy(llvm::ArrayRef<DocumentSymbol> Symbols,
903 const URIForFile &FileURI) {
904
905 std::vector<SymbolInformation> Results;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000906 std::function<void(const DocumentSymbol &, llvm::StringRef)> Process =
907 [&](const DocumentSymbol &S, llvm::Optional<llvm::StringRef> ParentName) {
Ilya Biryukov19d75602018-11-23 15:21:19 +0000908 SymbolInformation SI;
Benjamin Krameradcd0262020-01-28 20:23:46 +0100909 SI.containerName = std::string(ParentName ? "" : *ParentName);
Ilya Biryukov19d75602018-11-23 15:21:19 +0000910 SI.name = S.name;
911 SI.kind = S.kind;
912 SI.location.range = S.range;
913 SI.location.uri = FileURI;
914
915 Results.push_back(std::move(SI));
916 std::string FullName =
917 !ParentName ? S.name : (ParentName->str() + "::" + S.name);
918 for (auto &C : S.children)
919 Process(C, /*ParentName=*/FullName);
920 };
921 for (auto &S : Symbols)
922 Process(S, /*ParentName=*/"");
923 return Results;
924}
925
926void ClangdLSPServer::onDocumentSymbol(const DocumentSymbolParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000927 Callback<llvm::json::Value> Reply) {
Ilya Biryukov19d75602018-11-23 15:21:19 +0000928 URIForFile FileURI = Params.textDocument.uri;
Ilya Biryukov652364b2018-09-26 05:48:29 +0000929 Server->documentSymbols(
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000930 Params.textDocument.uri.file(),
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000931 [this, FileURI, Reply = std::move(Reply)](
932 llvm::Expected<std::vector<DocumentSymbol>> Items) mutable {
933 if (!Items)
934 return Reply(Items.takeError());
935 adjustSymbolKinds(*Items, SupportedSymbolKinds);
936 if (SupportsHierarchicalDocumentSymbol)
937 return Reply(std::move(*Items));
938 else
939 return Reply(flattenSymbolHierarchy(*Items, FileURI));
940 });
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000941}
942
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000943static llvm::Optional<Command> asCommand(const CodeAction &Action) {
Sam McCall20841d42018-10-16 16:29:41 +0000944 Command Cmd;
945 if (Action.command && Action.edit)
Sam McCallc008af62018-10-20 15:30:37 +0000946 return None; // Not representable. (We never emit these anyway).
Sam McCall20841d42018-10-16 16:29:41 +0000947 if (Action.command) {
948 Cmd = *Action.command;
949 } else if (Action.edit) {
Benjamin Krameradcd0262020-01-28 20:23:46 +0100950 Cmd.command = std::string(Command::CLANGD_APPLY_FIX_COMMAND);
Sam McCall20841d42018-10-16 16:29:41 +0000951 Cmd.workspaceEdit = *Action.edit;
952 } else {
Sam McCallc008af62018-10-20 15:30:37 +0000953 return None;
Sam McCall20841d42018-10-16 16:29:41 +0000954 }
955 Cmd.title = Action.title;
956 if (Action.kind && *Action.kind == CodeAction::QUICKFIX_KIND)
957 Cmd.title = "Apply fix: " + Cmd.title;
958 return Cmd;
959}
960
Sam McCall2c30fbc2018-10-18 12:32:04 +0000961void ClangdLSPServer::onCodeAction(const CodeActionParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000962 Callback<llvm::json::Value> Reply) {
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000963 URIForFile File = Params.textDocument.uri;
964 auto Code = DraftMgr.getDraft(File.file());
Sam McCall2c30fbc2018-10-18 12:32:04 +0000965 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000966 return Reply(llvm::make_error<LSPError>(
967 "onCodeAction called for non-added file", ErrorCode::InvalidParams));
Sam McCall20841d42018-10-16 16:29:41 +0000968 // We provide a code action for Fixes on the specified diagnostics.
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000969 std::vector<CodeAction> FixIts;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000970 for (const Diagnostic &D : Params.context.diagnostics) {
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000971 for (auto &F : getFixes(File.file(), D)) {
972 FixIts.push_back(toCodeAction(F, Params.textDocument.uri));
973 FixIts.back().diagnostics = {D};
Sam McCalldd0566b2017-11-06 15:40:30 +0000974 }
Ilya Biryukovafb55542017-05-16 14:40:30 +0000975 }
Sam McCall20841d42018-10-16 16:29:41 +0000976
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000977 // Now enumerate the semantic code actions.
978 auto ConsumeActions =
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000979 [Reply = std::move(Reply), File, Code = std::move(*Code),
980 Selection = Params.range, FixIts = std::move(FixIts), this](
981 llvm::Expected<std::vector<ClangdServer::TweakRef>> Tweaks) mutable {
Ilya Biryukovc6ed7782019-01-30 14:24:17 +0000982 if (!Tweaks)
983 return Reply(Tweaks.takeError());
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000984
985 std::vector<CodeAction> Actions = std::move(FixIts);
986 Actions.reserve(Actions.size() + Tweaks->size());
987 for (const auto &T : *Tweaks)
988 Actions.push_back(toCodeAction(T, File, Selection));
989
990 if (SupportsCodeAction)
991 return Reply(llvm::json::Array(Actions));
992 std::vector<Command> Commands;
993 for (const auto &Action : Actions) {
994 if (auto Command = asCommand(Action))
995 Commands.push_back(std::move(*Command));
996 }
997 return Reply(llvm::json::Array(Commands));
998 };
999
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001000 Server->enumerateTweaks(File.file(), Params.range, std::move(ConsumeActions));
Ilya Biryukovafb55542017-05-16 14:40:30 +00001001}
1002
Ilya Biryukovb0826bd2019-01-03 13:37:12 +00001003void ClangdLSPServer::onCompletion(const CompletionParams &Params,
Sam McCall2c30fbc2018-10-18 12:32:04 +00001004 Callback<CompletionList> Reply) {
Ilya Biryukova7a11472019-06-07 16:24:38 +00001005 if (!shouldRunCompletion(Params)) {
1006 // Clients sometimes auto-trigger completions in undesired places (e.g.
1007 // 'a >^ '), we return empty results in those cases.
1008 vlog("ignored auto-triggered completion, preceding char did not match");
1009 return Reply(CompletionList());
1010 }
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001011 Server->codeComplete(Params.textDocument.uri.file(), Params.position, CCOpts,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001012 [Reply = std::move(Reply),
1013 this](llvm::Expected<CodeCompleteResult> List) mutable {
1014 if (!List)
1015 return Reply(List.takeError());
1016 CompletionList LSPList;
1017 LSPList.isIncomplete = List->HasMore;
1018 for (const auto &R : List->Completions) {
1019 CompletionItem C = R.render(CCOpts);
1020 C.kind = adjustKindToCapability(
1021 C.kind, SupportedCompletionItemKinds);
1022 LSPList.items.push_back(std::move(C));
1023 }
1024 return Reply(std::move(LSPList));
1025 });
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +00001026}
1027
Sam McCall2c30fbc2018-10-18 12:32:04 +00001028void ClangdLSPServer::onSignatureHelp(const TextDocumentPositionParams &Params,
1029 Callback<SignatureHelp> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +00001030 Server->signatureHelp(Params.textDocument.uri.file(), Params.position,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001031 [Reply = std::move(Reply), this](
1032 llvm::Expected<SignatureHelp> Signature) mutable {
1033 if (!Signature)
1034 return Reply(Signature.takeError());
1035 if (SupportsOffsetsInSignatureHelp)
1036 return Reply(std::move(*Signature));
1037 // Strip out the offsets from signature help for
1038 // clients that only support string labels.
1039 for (auto &SigInfo : Signature->signatures) {
1040 for (auto &Param : SigInfo.parameters)
1041 Param.labelOffsets.reset();
1042 }
1043 return Reply(std::move(*Signature));
1044 });
Ilya Biryukov652364b2018-09-26 05:48:29 +00001045}
1046
Sam McCall0dbab7f2019-02-02 05:56:00 +00001047// Go to definition has a toggle function: if def and decl are distinct, then
1048// the first press gives you the def, the second gives you the matching def.
1049// getToggle() returns the counterpart location that under the cursor.
1050//
1051// We return the toggled location alone (ignoring other symbols) to encourage
1052// editors to "bounce" quickly between locations, without showing a menu.
1053static Location *getToggle(const TextDocumentPositionParams &Point,
1054 LocatedSymbol &Sym) {
1055 // Toggle only makes sense with two distinct locations.
1056 if (!Sym.Definition || *Sym.Definition == Sym.PreferredDeclaration)
1057 return nullptr;
1058 if (Sym.Definition->uri.file() == Point.textDocument.uri.file() &&
1059 Sym.Definition->range.contains(Point.position))
1060 return &Sym.PreferredDeclaration;
1061 if (Sym.PreferredDeclaration.uri.file() == Point.textDocument.uri.file() &&
1062 Sym.PreferredDeclaration.range.contains(Point.position))
1063 return &*Sym.Definition;
1064 return nullptr;
1065}
1066
Sam McCall2c30fbc2018-10-18 12:32:04 +00001067void ClangdLSPServer::onGoToDefinition(const TextDocumentPositionParams &Params,
1068 Callback<std::vector<Location>> Reply) {
Sam McCall866ba2c2019-02-01 11:26:13 +00001069 Server->locateSymbolAt(
1070 Params.textDocument.uri.file(), Params.position,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001071 [Params, Reply = std::move(Reply)](
1072 llvm::Expected<std::vector<LocatedSymbol>> Symbols) mutable {
1073 if (!Symbols)
1074 return Reply(Symbols.takeError());
1075 std::vector<Location> Defs;
1076 for (auto &S : *Symbols) {
1077 if (Location *Toggle = getToggle(Params, S))
1078 return Reply(std::vector<Location>{std::move(*Toggle)});
1079 Defs.push_back(S.Definition.getValueOr(S.PreferredDeclaration));
1080 }
1081 Reply(std::move(Defs));
1082 });
Sam McCall866ba2c2019-02-01 11:26:13 +00001083}
1084
1085void ClangdLSPServer::onGoToDeclaration(
1086 const TextDocumentPositionParams &Params,
1087 Callback<std::vector<Location>> Reply) {
1088 Server->locateSymbolAt(
1089 Params.textDocument.uri.file(), Params.position,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001090 [Params, Reply = std::move(Reply)](
1091 llvm::Expected<std::vector<LocatedSymbol>> Symbols) mutable {
1092 if (!Symbols)
1093 return Reply(Symbols.takeError());
1094 std::vector<Location> Decls;
1095 for (auto &S : *Symbols) {
1096 if (Location *Toggle = getToggle(Params, S))
1097 return Reply(std::vector<Location>{std::move(*Toggle)});
1098 Decls.push_back(std::move(S.PreferredDeclaration));
1099 }
1100 Reply(std::move(Decls));
1101 });
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +00001102}
1103
Sam McCall111fe842019-05-07 07:55:35 +00001104void ClangdLSPServer::onSwitchSourceHeader(
1105 const TextDocumentIdentifier &Params,
Sam McCallb9ec3e92019-05-07 08:30:32 +00001106 Callback<llvm::Optional<URIForFile>> Reply) {
Haojian Wud6d5edd2019-10-01 10:21:15 +00001107 Server->switchSourceHeader(
1108 Params.uri.file(),
1109 [Reply = std::move(Reply),
1110 Params](llvm::Expected<llvm::Optional<clangd::Path>> Path) mutable {
1111 if (!Path)
1112 return Reply(Path.takeError());
1113 if (*Path)
Haojian Wu77c97002019-10-07 11:37:25 +00001114 return Reply(URIForFile::canonicalize(**Path, Params.uri.file()));
Haojian Wud6d5edd2019-10-01 10:21:15 +00001115 return Reply(llvm::None);
1116 });
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +00001117}
1118
Sam McCall2c30fbc2018-10-18 12:32:04 +00001119void ClangdLSPServer::onDocumentHighlight(
1120 const TextDocumentPositionParams &Params,
1121 Callback<std::vector<DocumentHighlight>> Reply) {
1122 Server->findDocumentHighlights(Params.textDocument.uri.file(),
1123 Params.position, std::move(Reply));
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +00001124}
1125
Sam McCall2c30fbc2018-10-18 12:32:04 +00001126void ClangdLSPServer::onHover(const TextDocumentPositionParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001127 Callback<llvm::Optional<Hover>> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +00001128 Server->findHover(Params.textDocument.uri.file(), Params.position,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001129 [Reply = std::move(Reply), this](
1130 llvm::Expected<llvm::Optional<HoverInfo>> H) mutable {
1131 if (!H)
1132 return Reply(H.takeError());
1133 if (!*H)
1134 return Reply(llvm::None);
Ilya Biryukovf9169d02019-05-29 10:01:00 +00001135
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001136 Hover R;
1137 R.contents.kind = HoverContentFormat;
1138 R.range = (*H)->SymRange;
1139 switch (HoverContentFormat) {
1140 case MarkupKind::PlainText:
Kadir Cetinkaya597c6b62019-12-10 10:28:37 +01001141 R.contents.value = (*H)->present().asPlainText();
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001142 return Reply(std::move(R));
1143 case MarkupKind::Markdown:
Kadir Cetinkaya597c6b62019-12-10 10:28:37 +01001144 R.contents.value = (*H)->present().asMarkdown();
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001145 return Reply(std::move(R));
1146 };
1147 llvm_unreachable("unhandled MarkupKind");
1148 });
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +00001149}
1150
Kadir Cetinkaya86658022019-03-19 09:27:04 +00001151void ClangdLSPServer::onTypeHierarchy(
1152 const TypeHierarchyParams &Params,
1153 Callback<Optional<TypeHierarchyItem>> Reply) {
1154 Server->typeHierarchy(Params.textDocument.uri.file(), Params.position,
1155 Params.resolve, Params.direction, std::move(Reply));
1156}
1157
Nathan Ridge087b0442019-07-13 03:24:48 +00001158void ClangdLSPServer::onResolveTypeHierarchy(
1159 const ResolveTypeHierarchyItemParams &Params,
1160 Callback<Optional<TypeHierarchyItem>> Reply) {
1161 Server->resolveTypeHierarchy(Params.item, Params.resolve, Params.direction,
1162 std::move(Reply));
1163}
1164
Simon Marchi88016782018-08-01 11:28:49 +00001165void ClangdLSPServer::applyConfiguration(
Sam McCallbc904612018-10-25 04:22:52 +00001166 const ConfigurationSettings &Settings) {
Simon Marchiabeed662018-10-16 15:55:03 +00001167 // Per-file update to the compilation database.
David Goldman60249c22020-01-13 17:01:10 -05001168 llvm::StringSet<> ModifiedFiles;
Sam McCallbc904612018-10-25 04:22:52 +00001169 for (auto &Entry : Settings.compilationDatabaseChanges) {
Sam McCallbc904612018-10-25 04:22:52 +00001170 PathRef File = Entry.first;
Sam McCallc55d09a2018-11-02 13:09:36 +00001171 auto Old = CDB->getCompileCommand(File);
1172 auto New =
1173 tooling::CompileCommand(std::move(Entry.second.workingDirectory), File,
1174 std::move(Entry.second.compilationCommand),
1175 /*Output=*/"");
Sam McCall6980edb2018-11-02 14:07:51 +00001176 if (Old != New) {
Sam McCallc55d09a2018-11-02 13:09:36 +00001177 CDB->setCompileCommand(File, std::move(New));
David Goldman60249c22020-01-13 17:01:10 -05001178 ModifiedFiles.insert(File);
Sam McCall6980edb2018-11-02 14:07:51 +00001179 }
Alex Lorenzf8087862018-08-01 17:39:29 +00001180 }
David Goldman60249c22020-01-13 17:01:10 -05001181
1182 reparseOpenedFiles(ModifiedFiles);
Simon Marchi5178f922018-02-22 14:00:39 +00001183}
1184
Sam McCalledf6a192020-03-24 00:31:14 +01001185void ClangdLSPServer::publishTheiaSemanticHighlighting(
1186 const TheiaSemanticHighlightingParams &Params) {
Johan Vikstroma848dab2019-07-04 07:53:12 +00001187 notify("textDocument/semanticHighlighting", Params);
1188}
1189
Ilya Biryukov49c10712019-03-25 10:15:11 +00001190void ClangdLSPServer::publishDiagnostics(
Sam McCall6525a6b2020-03-03 12:44:40 +01001191 const PublishDiagnosticsParams &Params) {
1192 notify("textDocument/publishDiagnostics", Params);
Ilya Biryukov49c10712019-03-25 10:15:11 +00001193}
1194
Simon Marchi88016782018-08-01 11:28:49 +00001195// FIXME: This function needs to be properly tested.
1196void ClangdLSPServer::onChangeConfiguration(
Sam McCall2c30fbc2018-10-18 12:32:04 +00001197 const DidChangeConfigurationParams &Params) {
Simon Marchi88016782018-08-01 11:28:49 +00001198 applyConfiguration(Params.settings);
1199}
1200
Sam McCall2c30fbc2018-10-18 12:32:04 +00001201void ClangdLSPServer::onReference(const ReferenceParams &Params,
1202 Callback<std::vector<Location>> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +00001203 Server->findReferences(Params.textDocument.uri.file(), Params.position,
Haojian Wu5181ada2019-11-18 11:35:00 +01001204 CCOpts.Limit,
1205 [Reply = std::move(Reply)](
1206 llvm::Expected<ReferencesResult> Refs) mutable {
1207 if (!Refs)
1208 return Reply(Refs.takeError());
1209 return Reply(std::move(Refs->References));
1210 });
Sam McCall1ad142f2018-09-05 11:53:07 +00001211}
1212
Jan Korousb4067012018-11-27 16:40:46 +00001213void ClangdLSPServer::onSymbolInfo(const TextDocumentPositionParams &Params,
1214 Callback<std::vector<SymbolDetails>> Reply) {
1215 Server->symbolInfo(Params.textDocument.uri.file(), Params.position,
1216 std::move(Reply));
1217}
1218
Utkarsh Saxena55925da2019-09-24 13:38:33 +00001219void ClangdLSPServer::onSelectionRange(
1220 const SelectionRangeParams &Params,
1221 Callback<std::vector<SelectionRange>> Reply) {
Utkarsh Saxena55925da2019-09-24 13:38:33 +00001222 Server->semanticRanges(
Sam McCall8f237f92020-03-25 00:51:50 +01001223 Params.textDocument.uri.file(), Params.positions,
Utkarsh Saxena55925da2019-09-24 13:38:33 +00001224 [Reply = std::move(Reply)](
Sam McCall8f237f92020-03-25 00:51:50 +01001225 llvm::Expected<std::vector<SelectionRange>> Ranges) mutable {
1226 if (!Ranges)
Utkarsh Saxena55925da2019-09-24 13:38:33 +00001227 return Reply(Ranges.takeError());
Sam McCall8f237f92020-03-25 00:51:50 +01001228 return Reply(std::move(*Ranges));
Utkarsh Saxena55925da2019-09-24 13:38:33 +00001229 });
1230}
1231
Sam McCall8d7ecc12019-12-16 19:08:51 +01001232void ClangdLSPServer::onDocumentLink(
1233 const DocumentLinkParams &Params,
1234 Callback<std::vector<DocumentLink>> Reply) {
1235
1236 // TODO(forster): This currently resolves all targets eagerly. This is slow,
1237 // because it blocks on the preamble/AST being built. We could respond to the
1238 // request faster by using string matching or the lexer to find the includes
1239 // and resolving the targets lazily.
1240 Server->documentLinks(
1241 Params.textDocument.uri.file(),
1242 [Reply = std::move(Reply)](
1243 llvm::Expected<std::vector<DocumentLink>> Links) mutable {
1244 if (!Links) {
1245 return Reply(Links.takeError());
1246 }
1247 return Reply(std::move(Links));
1248 });
1249}
1250
Sam McCall9e3063e2020-04-01 16:21:44 +02001251// Increment a numeric string: "" -> 1 -> 2 -> ... -> 9 -> 10 -> 11 ...
1252static void increment(std::string &S) {
1253 for (char &C : llvm::reverse(S)) {
1254 if (C != '9') {
1255 ++C;
1256 return;
1257 }
1258 C = '0';
1259 }
1260 S.insert(S.begin(), '1');
1261}
1262
Sam McCall71177ac2020-03-24 02:24:47 +01001263void ClangdLSPServer::onSemanticTokens(const SemanticTokensParams &Params,
1264 Callback<SemanticTokens> CB) {
1265 Server->semanticHighlights(
1266 Params.textDocument.uri.file(),
Sam McCall9e3063e2020-04-01 16:21:44 +02001267 [this, File(Params.textDocument.uri.file().str()), CB(std::move(CB))](
1268 llvm::Expected<std::vector<HighlightingToken>> HT) mutable {
1269 if (!HT)
1270 return CB(HT.takeError());
Sam McCall71177ac2020-03-24 02:24:47 +01001271 SemanticTokens Result;
Sam McCall9e3063e2020-04-01 16:21:44 +02001272 Result.tokens = toSemanticTokens(*HT);
1273 {
1274 std::lock_guard<std::mutex> Lock(SemanticTokensMutex);
1275 auto& Last = LastSemanticTokens[File];
1276
1277 Last.tokens = Result.tokens;
1278 increment(Last.resultId);
1279 Result.resultId = Last.resultId;
1280 }
1281 CB(std::move(Result));
1282 });
1283}
1284
1285void ClangdLSPServer::onSemanticTokensEdits(
1286 const SemanticTokensEditsParams &Params,
1287 Callback<SemanticTokensOrEdits> CB) {
1288 Server->semanticHighlights(
1289 Params.textDocument.uri.file(),
1290 [this, PrevResultID(Params.previousResultId),
1291 File(Params.textDocument.uri.file().str()), CB(std::move(CB))](
1292 llvm::Expected<std::vector<HighlightingToken>> HT) mutable {
1293 if (!HT)
1294 return CB(HT.takeError());
1295 std::vector<SemanticToken> Toks = toSemanticTokens(*HT);
1296
1297 SemanticTokensOrEdits Result;
1298 {
1299 std::lock_guard<std::mutex> Lock(SemanticTokensMutex);
1300 auto& Last = LastSemanticTokens[File];
1301
1302 if (PrevResultID == Last.resultId) {
1303 Result.edits = diffTokens(Last.tokens, Toks);
1304 } else {
1305 vlog("semanticTokens/edits: wanted edits vs {0} but last result "
1306 "had ID {1}. Returning full token list.",
1307 PrevResultID, Last.resultId);
1308 Result.tokens = Toks;
1309 }
1310
1311 Last.tokens = std::move(Toks);
1312 increment(Last.resultId);
1313 Result.resultId = Last.resultId;
1314 }
1315
Sam McCall71177ac2020-03-24 02:24:47 +01001316 CB(std::move(Result));
1317 });
1318}
1319
Sam McCalla69698f2019-03-27 17:47:49 +00001320ClangdLSPServer::ClangdLSPServer(
1321 class Transport &Transp, const FileSystemProvider &FSProvider,
1322 const clangd::CodeCompleteOptions &CCOpts,
Haojian Wu34d0e1b2020-02-19 15:37:36 +01001323 const clangd::RenameOptions &RenameOpts,
Sam McCalla69698f2019-03-27 17:47:49 +00001324 llvm::Optional<Path> CompileCommandsDir, bool UseDirBasedCDB,
1325 llvm::Optional<OffsetEncoding> ForcedOffsetEncoding,
1326 const ClangdServer::Options &Opts)
Kadir Cetinkaya9d662472019-10-15 14:20:52 +00001327 : BackgroundContext(Context::current().clone()), Transp(Transp),
1328 MsgHandler(new MessageHandler(*this)), FSProvider(FSProvider),
Haojian Wu34d0e1b2020-02-19 15:37:36 +01001329 CCOpts(CCOpts), RenameOpts(RenameOpts),
1330 SupportedSymbolKinds(defaultSymbolKinds()),
Kadir Cetinkaya133d46f2018-09-27 17:13:07 +00001331 SupportedCompletionItemKinds(defaultCompletionItemKinds()),
Sam McCallc55d09a2018-11-02 13:09:36 +00001332 UseDirBasedCDB(UseDirBasedCDB),
Sam McCalla69698f2019-03-27 17:47:49 +00001333 CompileCommandsDir(std::move(CompileCommandsDir)), ClangdServerOpts(Opts),
1334 NegotiatedOffsetEncoding(ForcedOffsetEncoding) {
Sam McCall2c30fbc2018-10-18 12:32:04 +00001335 // clang-format off
1336 MsgHandler->bind("initialize", &ClangdLSPServer::onInitialize);
Sam McCall8a2d2942020-03-03 12:12:14 +01001337 MsgHandler->bind("initialized", &ClangdLSPServer::onInitialized);
Sam McCall2c30fbc2018-10-18 12:32:04 +00001338 MsgHandler->bind("shutdown", &ClangdLSPServer::onShutdown);
Sam McCall422c8282018-11-26 16:00:11 +00001339 MsgHandler->bind("sync", &ClangdLSPServer::onSync);
Sam McCall2c30fbc2018-10-18 12:32:04 +00001340 MsgHandler->bind("textDocument/rangeFormatting", &ClangdLSPServer::onDocumentRangeFormatting);
1341 MsgHandler->bind("textDocument/onTypeFormatting", &ClangdLSPServer::onDocumentOnTypeFormatting);
1342 MsgHandler->bind("textDocument/formatting", &ClangdLSPServer::onDocumentFormatting);
1343 MsgHandler->bind("textDocument/codeAction", &ClangdLSPServer::onCodeAction);
1344 MsgHandler->bind("textDocument/completion", &ClangdLSPServer::onCompletion);
1345 MsgHandler->bind("textDocument/signatureHelp", &ClangdLSPServer::onSignatureHelp);
1346 MsgHandler->bind("textDocument/definition", &ClangdLSPServer::onGoToDefinition);
Sam McCall866ba2c2019-02-01 11:26:13 +00001347 MsgHandler->bind("textDocument/declaration", &ClangdLSPServer::onGoToDeclaration);
Sam McCall2c30fbc2018-10-18 12:32:04 +00001348 MsgHandler->bind("textDocument/references", &ClangdLSPServer::onReference);
1349 MsgHandler->bind("textDocument/switchSourceHeader", &ClangdLSPServer::onSwitchSourceHeader);
Haojian Wuf429ab62019-07-24 07:49:23 +00001350 MsgHandler->bind("textDocument/prepareRename", &ClangdLSPServer::onPrepareRename);
Sam McCall2c30fbc2018-10-18 12:32:04 +00001351 MsgHandler->bind("textDocument/rename", &ClangdLSPServer::onRename);
1352 MsgHandler->bind("textDocument/hover", &ClangdLSPServer::onHover);
1353 MsgHandler->bind("textDocument/documentSymbol", &ClangdLSPServer::onDocumentSymbol);
1354 MsgHandler->bind("workspace/executeCommand", &ClangdLSPServer::onCommand);
1355 MsgHandler->bind("textDocument/documentHighlight", &ClangdLSPServer::onDocumentHighlight);
1356 MsgHandler->bind("workspace/symbol", &ClangdLSPServer::onWorkspaceSymbol);
1357 MsgHandler->bind("textDocument/didOpen", &ClangdLSPServer::onDocumentDidOpen);
1358 MsgHandler->bind("textDocument/didClose", &ClangdLSPServer::onDocumentDidClose);
1359 MsgHandler->bind("textDocument/didChange", &ClangdLSPServer::onDocumentDidChange);
1360 MsgHandler->bind("workspace/didChangeWatchedFiles", &ClangdLSPServer::onFileEvent);
1361 MsgHandler->bind("workspace/didChangeConfiguration", &ClangdLSPServer::onChangeConfiguration);
Jan Korousb4067012018-11-27 16:40:46 +00001362 MsgHandler->bind("textDocument/symbolInfo", &ClangdLSPServer::onSymbolInfo);
Kadir Cetinkaya86658022019-03-19 09:27:04 +00001363 MsgHandler->bind("textDocument/typeHierarchy", &ClangdLSPServer::onTypeHierarchy);
Nathan Ridge087b0442019-07-13 03:24:48 +00001364 MsgHandler->bind("typeHierarchy/resolve", &ClangdLSPServer::onResolveTypeHierarchy);
Utkarsh Saxena55925da2019-09-24 13:38:33 +00001365 MsgHandler->bind("textDocument/selectionRange", &ClangdLSPServer::onSelectionRange);
Sam McCall8d7ecc12019-12-16 19:08:51 +01001366 MsgHandler->bind("textDocument/documentLink", &ClangdLSPServer::onDocumentLink);
Sam McCall71177ac2020-03-24 02:24:47 +01001367 MsgHandler->bind("textDocument/semanticTokens", &ClangdLSPServer::onSemanticTokens);
Sam McCall9e3063e2020-04-01 16:21:44 +02001368 MsgHandler->bind("textDocument/semanticTokens/edits", &ClangdLSPServer::onSemanticTokensEdits);
Sam McCall2c30fbc2018-10-18 12:32:04 +00001369 // clang-format on
1370}
1371
Kadir Cetinkaya6b850322020-03-17 19:08:23 +01001372ClangdLSPServer::~ClangdLSPServer() {
1373 IsBeingDestroyed = true;
Sam McCall8bda5f22019-10-23 11:11:18 +02001374 // Explicitly destroy ClangdServer first, blocking on threads it owns.
1375 // This ensures they don't access any other members.
1376 Server.reset();
1377}
Ilya Biryukov38d79772017-05-16 09:38:59 +00001378
Sam McCalldc8f3cf2018-10-17 07:32:05 +00001379bool ClangdLSPServer::run() {
Ilya Biryukovafb55542017-05-16 14:40:30 +00001380 // Run the Language Server loop.
Sam McCalldc8f3cf2018-10-17 07:32:05 +00001381 bool CleanExit = true;
Sam McCall2c30fbc2018-10-18 12:32:04 +00001382 if (auto Err = Transp.loop(*MsgHandler)) {
Sam McCalldc8f3cf2018-10-17 07:32:05 +00001383 elog("Transport error: {0}", std::move(Err));
1384 CleanExit = false;
1385 }
Ilya Biryukovafb55542017-05-16 14:40:30 +00001386
Sam McCalldc8f3cf2018-10-17 07:32:05 +00001387 return CleanExit && ShutdownRequestReceived;
Ilya Biryukov38d79772017-05-16 09:38:59 +00001388}
1389
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001390std::vector<Fix> ClangdLSPServer::getFixes(llvm::StringRef File,
Ilya Biryukov71028b82018-03-12 15:28:22 +00001391 const clangd::Diagnostic &D) {
Ilya Biryukov38d79772017-05-16 09:38:59 +00001392 std::lock_guard<std::mutex> Lock(FixItsMutex);
1393 auto DiagToFixItsIter = FixItsMap.find(File);
1394 if (DiagToFixItsIter == FixItsMap.end())
1395 return {};
1396
1397 const auto &DiagToFixItsMap = DiagToFixItsIter->second;
1398 auto FixItsIter = DiagToFixItsMap.find(D);
1399 if (FixItsIter == DiagToFixItsMap.end())
1400 return {};
1401
1402 return FixItsIter->second;
1403}
1404
Ilya Biryukovb0826bd2019-01-03 13:37:12 +00001405bool ClangdLSPServer::shouldRunCompletion(
1406 const CompletionParams &Params) const {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001407 llvm::StringRef Trigger = Params.context.triggerCharacter;
Ilya Biryukovb0826bd2019-01-03 13:37:12 +00001408 if (Params.context.triggerKind != CompletionTriggerKind::TriggerCharacter ||
1409 (Trigger != ">" && Trigger != ":"))
1410 return true;
1411
1412 auto Code = DraftMgr.getDraft(Params.textDocument.uri.file());
1413 if (!Code)
1414 return true; // completion code will log the error for untracked doc.
1415
1416 // A completion request is sent when the user types '>' or ':', but we only
1417 // want to trigger on '->' and '::'. We check the preceeding character to make
1418 // sure it matches what we expected.
1419 // Running the lexer here would be more robust (e.g. we can detect comments
1420 // and avoid triggering completion there), but we choose to err on the side
1421 // of simplicity here.
Sam McCallcaf5a4d2020-03-03 15:57:39 +01001422 auto Offset = positionToOffset(Code->Contents, Params.position,
Ilya Biryukovb0826bd2019-01-03 13:37:12 +00001423 /*AllowColumnsBeyondLineLength=*/false);
1424 if (!Offset) {
1425 vlog("could not convert position '{0}' to offset for file '{1}'",
1426 Params.position, Params.textDocument.uri.file());
1427 return true;
1428 }
1429 if (*Offset < 2)
1430 return false;
1431
1432 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 if (Trigger == ":")
Sam McCallcaf5a4d2020-03-03 15:57:39 +01001435 return Code->Contents[*Offset - 2] == ':'; // trigger only on '::'.
Ilya Biryukovb0826bd2019-01-03 13:37:12 +00001436 assert(false && "unhandled trigger character");
1437 return true;
1438}
1439
Johan Vikstroma848dab2019-07-04 07:53:12 +00001440void ClangdLSPServer::onHighlightingsReady(
Sam McCall2cd33e62020-03-04 00:33:29 +01001441 PathRef File, llvm::StringRef Version,
1442 std::vector<HighlightingToken> Highlightings) {
Johan Vikstromc2653ef22019-08-01 08:08:44 +00001443 std::vector<HighlightingToken> Old;
1444 std::vector<HighlightingToken> HighlightingsCopy = Highlightings;
1445 {
1446 std::lock_guard<std::mutex> Lock(HighlightingsMutex);
1447 Old = std::move(FileToHighlightings[File]);
1448 FileToHighlightings[File] = std::move(HighlightingsCopy);
1449 }
1450 // LSP allows us to send incremental edits of highlightings. Also need to diff
1451 // to remove highlightings from tokens that should no longer have them.
Haojian Wu0a6000f2019-08-26 08:38:45 +00001452 std::vector<LineHighlightings> Diffed = diffHighlightings(Highlightings, Old);
Sam McCalledf6a192020-03-24 00:31:14 +01001453 TheiaSemanticHighlightingParams Notification;
Sam McCall2cd33e62020-03-04 00:33:29 +01001454 Notification.TextDocument.uri =
1455 URIForFile::canonicalize(File, /*TUPath=*/File);
1456 Notification.TextDocument.version = decodeVersion(Version);
Sam McCalledf6a192020-03-24 00:31:14 +01001457 Notification.Lines = toTheiaSemanticHighlightingInformation(Diffed);
1458 publishTheiaSemanticHighlighting(Notification);
Johan Vikstroma848dab2019-07-04 07:53:12 +00001459}
1460
Sam McCall2cd33e62020-03-04 00:33:29 +01001461void ClangdLSPServer::onDiagnosticsReady(PathRef File, llvm::StringRef Version,
Sam McCalla7bb0cc2018-03-12 23:22:35 +00001462 std::vector<Diag> Diagnostics) {
Sam McCall6525a6b2020-03-03 12:44:40 +01001463 PublishDiagnosticsParams Notification;
Sam McCall2cd33e62020-03-04 00:33:29 +01001464 Notification.version = decodeVersion(Version);
Sam McCall6525a6b2020-03-03 12:44:40 +01001465 Notification.uri = URIForFile::canonicalize(File, /*TUPath=*/File);
Ilya Biryukov38d79772017-05-16 09:38:59 +00001466 DiagnosticToReplacementMap LocalFixIts; // Temporary storage
Sam McCalla7bb0cc2018-03-12 23:22:35 +00001467 for (auto &Diag : Diagnostics) {
Sam McCall6525a6b2020-03-03 12:44:40 +01001468 toLSPDiags(Diag, Notification.uri, DiagOpts,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001469 [&](clangd::Diagnostic Diag, llvm::ArrayRef<Fix> Fixes) {
Sam McCall16e70702018-10-24 07:59:38 +00001470 auto &FixItsForDiagnostic = LocalFixIts[Diag];
1471 llvm::copy(Fixes, std::back_inserter(FixItsForDiagnostic));
Sam McCall6525a6b2020-03-03 12:44:40 +01001472 Notification.diagnostics.push_back(std::move(Diag));
Sam McCall16e70702018-10-24 07:59:38 +00001473 });
Ilya Biryukov38d79772017-05-16 09:38:59 +00001474 }
1475
1476 // Cache FixIts
1477 {
Ilya Biryukov38d79772017-05-16 09:38:59 +00001478 std::lock_guard<std::mutex> Lock(FixItsMutex);
1479 FixItsMap[File] = LocalFixIts;
1480 }
1481
Ilya Biryukov49c10712019-03-25 10:15:11 +00001482 // Send a notification to the LSP client.
Sam McCall6525a6b2020-03-03 12:44:40 +01001483 publishDiagnostics(Notification);
Ilya Biryukov38d79772017-05-16 09:38:59 +00001484}
Simon Marchi9569fd52018-03-16 14:30:42 +00001485
Sam McCall7d20e802020-01-22 19:41:45 +01001486void ClangdLSPServer::onBackgroundIndexProgress(
1487 const BackgroundQueue::Stats &Stats) {
1488 static const char ProgressToken[] = "backgroundIndexProgress";
1489 std::lock_guard<std::mutex> Lock(BackgroundIndexProgressMutex);
1490
1491 auto NotifyProgress = [this](const BackgroundQueue::Stats &Stats) {
1492 if (BackgroundIndexProgressState != BackgroundIndexProgress::Live) {
1493 WorkDoneProgressBegin Begin;
1494 Begin.percentage = true;
1495 Begin.title = "indexing";
1496 progress(ProgressToken, std::move(Begin));
1497 BackgroundIndexProgressState = BackgroundIndexProgress::Live;
1498 }
1499
1500 if (Stats.Completed < Stats.Enqueued) {
1501 assert(Stats.Enqueued > Stats.LastIdle);
1502 WorkDoneProgressReport Report;
1503 Report.percentage = 100.0 * (Stats.Completed - Stats.LastIdle) /
1504 (Stats.Enqueued - Stats.LastIdle);
1505 Report.message =
1506 llvm::formatv("{0}/{1}", Stats.Completed - Stats.LastIdle,
1507 Stats.Enqueued - Stats.LastIdle);
1508 progress(ProgressToken, std::move(Report));
1509 } else {
1510 assert(Stats.Completed == Stats.Enqueued);
1511 progress(ProgressToken, WorkDoneProgressEnd());
1512 BackgroundIndexProgressState = BackgroundIndexProgress::Empty;
1513 }
1514 };
1515
1516 switch (BackgroundIndexProgressState) {
1517 case BackgroundIndexProgress::Unsupported:
1518 return;
1519 case BackgroundIndexProgress::Creating:
1520 // Cache this update for when the progress bar is available.
1521 PendingBackgroundIndexProgress = Stats;
1522 return;
1523 case BackgroundIndexProgress::Empty: {
1524 if (BackgroundIndexSkipCreate) {
1525 NotifyProgress(Stats);
1526 break;
1527 }
1528 // Cache this update for when the progress bar is available.
1529 PendingBackgroundIndexProgress = Stats;
1530 BackgroundIndexProgressState = BackgroundIndexProgress::Creating;
1531 WorkDoneProgressCreateParams CreateRequest;
1532 CreateRequest.token = ProgressToken;
1533 call<std::nullptr_t>(
1534 "window/workDoneProgress/create", CreateRequest,
1535 [this, NotifyProgress](llvm::Expected<std::nullptr_t> E) {
1536 std::lock_guard<std::mutex> Lock(BackgroundIndexProgressMutex);
1537 if (E) {
1538 NotifyProgress(this->PendingBackgroundIndexProgress);
1539 } else {
1540 elog("Failed to create background index progress bar: {0}",
1541 E.takeError());
1542 // give up forever rather than thrashing about
1543 BackgroundIndexProgressState = BackgroundIndexProgress::Unsupported;
1544 }
1545 });
1546 break;
1547 }
1548 case BackgroundIndexProgress::Live:
1549 NotifyProgress(Stats);
1550 break;
1551 }
1552}
1553
Haojian Wub6188492018-12-20 15:39:12 +00001554void ClangdLSPServer::onFileUpdated(PathRef File, const TUStatus &Status) {
1555 if (!SupportFileStatus)
1556 return;
1557 // FIXME: we don't emit "BuildingFile" and `RunningAction`, as these
1558 // two statuses are running faster in practice, which leads the UI constantly
1559 // changing, and doesn't provide much value. We may want to emit status at a
1560 // reasonable time interval (e.g. 0.5s).
Kadir Cetinkaya6b850322020-03-17 19:08:23 +01001561 if (Status.PreambleActivity == PreambleAction::Idle &&
1562 (Status.ASTActivity.K == ASTAction::Building ||
1563 Status.ASTActivity.K == ASTAction::RunningAction))
Haojian Wub6188492018-12-20 15:39:12 +00001564 return;
1565 notify("textDocument/clangd.fileStatus", Status.render(File));
1566}
1567
David Goldman60249c22020-01-13 17:01:10 -05001568void ClangdLSPServer::reparseOpenedFiles(
1569 const llvm::StringSet<> &ModifiedFiles) {
1570 if (ModifiedFiles.empty())
1571 return;
1572 // Reparse only opened files that were modified.
Simon Marchi9569fd52018-03-16 14:30:42 +00001573 for (const Path &FilePath : DraftMgr.getActiveFiles())
David Goldman60249c22020-01-13 17:01:10 -05001574 if (ModifiedFiles.find(FilePath) != ModifiedFiles.end())
Sam McCall2cd33e62020-03-04 00:33:29 +01001575 if (auto Draft = DraftMgr.getDraft(FilePath)) // else disappeared in race?
1576 Server->addDocument(FilePath, std::move(Draft->Contents),
1577 encodeVersion(Draft->Version),
1578 WantDiagnostics::Auto);
Simon Marchi9569fd52018-03-16 14:30:42 +00001579}
Alex Lorenzf8087862018-08-01 17:39:29 +00001580
Sam McCallc008af62018-10-20 15:30:37 +00001581} // namespace clangd
1582} // namespace clang