blob: e6d077b11885e9402bfbe9763dcbaf64df009c65 [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 {
Ilya Biryukovcce67a32019-01-29 14:17:36 +000044/// Transforms a tweak into a code action that would apply it if executed.
45/// EXPECTS: T.prepare() was called and returned true.
46CodeAction toCodeAction(const ClangdServer::TweakRef &T, const URIForFile &File,
47 Range Selection) {
48 CodeAction CA;
49 CA.title = T.Title;
Sam McCall395fde72019-06-18 13:37:54 +000050 switch (T.Intent) {
51 case Tweak::Refactor:
Benjamin Krameradcd0262020-01-28 20:23:46 +010052 CA.kind = std::string(CodeAction::REFACTOR_KIND);
Sam McCall395fde72019-06-18 13:37:54 +000053 break;
54 case Tweak::Info:
Benjamin Krameradcd0262020-01-28 20:23:46 +010055 CA.kind = std::string(CodeAction::INFO_KIND);
Sam McCall395fde72019-06-18 13:37:54 +000056 break;
57 }
Ilya Biryukovcce67a32019-01-29 14:17:36 +000058 // This tweak may have an expensive second stage, we only run it if the user
59 // actually chooses it in the UI. We reply with a command that would run the
60 // corresponding tweak.
61 // FIXME: for some tweaks, computing the edits is cheap and we could send them
62 // directly.
63 CA.command.emplace();
64 CA.command->title = T.Title;
Benjamin Krameradcd0262020-01-28 20:23:46 +010065 CA.command->command = std::string(Command::CLANGD_APPLY_TWEAK);
Ilya Biryukovcce67a32019-01-29 14:17:36 +000066 CA.command->tweakArgs.emplace();
67 CA.command->tweakArgs->file = File;
68 CA.command->tweakArgs->tweakID = T.ID;
69 CA.command->tweakArgs->selection = Selection;
70 return CA;
Simon Pilgrime9a136b2019-02-03 14:08:30 +000071}
Ilya Biryukovcce67a32019-01-29 14:17:36 +000072
Ilya Biryukov19d75602018-11-23 15:21:19 +000073void adjustSymbolKinds(llvm::MutableArrayRef<DocumentSymbol> Syms,
74 SymbolKindBitset Kinds) {
75 for (auto &S : Syms) {
76 S.kind = adjustKindToCapability(S.kind, Kinds);
77 adjustSymbolKinds(S.children, Kinds);
78 }
79}
80
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +000081SymbolKindBitset defaultSymbolKinds() {
82 SymbolKindBitset Defaults;
83 for (size_t I = SymbolKindMin; I <= static_cast<size_t>(SymbolKind::Array);
84 ++I)
85 Defaults.set(I);
86 return Defaults;
87}
88
Kadir Cetinkaya133d46f2018-09-27 17:13:07 +000089CompletionItemKindBitset defaultCompletionItemKinds() {
90 CompletionItemKindBitset Defaults;
91 for (size_t I = CompletionItemKindMin;
92 I <= static_cast<size_t>(CompletionItemKind::Reference); ++I)
93 Defaults.set(I);
94 return Defaults;
95}
96
Haojian Wu1ca2ee42019-07-04 12:27:21 +000097// Build a lookup table (HighlightingKind => {TextMate Scopes}), which is sent
98// to the LSP client.
99std::vector<std::vector<std::string>> buildHighlightScopeLookupTable() {
100 std::vector<std::vector<std::string>> LookupTable;
101 // HighlightingKind is using as the index.
Ilya Biryukov63d5d162019-09-09 08:57:17 +0000102 for (int KindValue = 0; KindValue <= (int)HighlightingKind::LastKind;
Haojian Wu1ca2ee42019-07-04 12:27:21 +0000103 ++KindValue)
Benjamin Krameradcd0262020-01-28 20:23:46 +0100104 LookupTable.push_back(
105 {std::string(toTextMateScope((HighlightingKind)(KindValue)))});
Haojian Wu1ca2ee42019-07-04 12:27:21 +0000106 return LookupTable;
107}
108
Haojian Wu852bafa2019-10-23 14:40:20 +0200109// Makes sure edits in \p FE are applicable to latest file contents reported by
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000110// editor. If not generates an error message containing information about files
111// that needs to be saved.
Haojian Wu852bafa2019-10-23 14:40:20 +0200112llvm::Error validateEdits(const DraftStore &DraftMgr, const FileEdits &FE) {
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000113 size_t InvalidFileCount = 0;
114 llvm::StringRef LastInvalidFile;
Haojian Wu852bafa2019-10-23 14:40:20 +0200115 for (const auto &It : FE) {
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000116 if (auto Draft = DraftMgr.getDraft(It.first())) {
117 // If the file is open in user's editor, make sure the version we
118 // saw and current version are compatible as this is the text that
119 // will be replaced by editors.
120 if (!It.second.canApplyTo(*Draft)) {
121 ++InvalidFileCount;
122 LastInvalidFile = It.first();
123 }
124 }
125 }
126 if (!InvalidFileCount)
127 return llvm::Error::success();
128 if (InvalidFileCount == 1)
129 return llvm::createStringError(llvm::inconvertibleErrorCode(),
130 "File must be saved first: " +
131 LastInvalidFile);
132 return llvm::createStringError(
133 llvm::inconvertibleErrorCode(),
134 "Files must be saved first: " + LastInvalidFile + " (and " +
135 llvm::to_string(InvalidFileCount - 1) + " others)");
136}
137
Utkarsh Saxena55925da2019-09-24 13:38:33 +0000138// Converts a list of Ranges to a LinkedList of SelectionRange.
139SelectionRange render(const std::vector<Range> &Ranges) {
140 if (Ranges.empty())
141 return {};
142 SelectionRange Result;
143 Result.range = Ranges[0];
144 auto *Next = &Result.parent;
145 for (const auto &R : llvm::make_range(Ranges.begin() + 1, Ranges.end())) {
146 *Next = std::make_unique<SelectionRange>();
147 Next->get()->range = R;
148 Next = &Next->get()->parent;
149 }
150 return Result;
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 McCall2c30fbc2018-10-18 12:32:04 +0000461void ClangdLSPServer::onInitialize(const InitializeParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000462 Callback<llvm::json::Value> Reply) {
Sam McCalla69698f2019-03-27 17:47:49 +0000463 // Determine character encoding first as it affects constructed ClangdServer.
464 if (Params.capabilities.offsetEncoding && !NegotiatedOffsetEncoding) {
465 NegotiatedOffsetEncoding = OffsetEncoding::UTF16; // fallback
466 for (OffsetEncoding Supported : *Params.capabilities.offsetEncoding)
467 if (Supported != OffsetEncoding::UnsupportedEncoding) {
468 NegotiatedOffsetEncoding = Supported;
469 break;
470 }
471 }
Sam McCalla69698f2019-03-27 17:47:49 +0000472
Johan Vikstroma848dab2019-07-04 07:53:12 +0000473 ClangdServerOpts.SemanticHighlighting =
474 Params.capabilities.SemanticHighlighting;
Sam McCall0d9b40f2018-10-19 15:42:23 +0000475 if (Params.rootUri && *Params.rootUri)
Benjamin Krameradcd0262020-01-28 20:23:46 +0100476 ClangdServerOpts.WorkspaceRoot = std::string(Params.rootUri->file());
Sam McCall0d9b40f2018-10-19 15:42:23 +0000477 else if (Params.rootPath && !Params.rootPath->empty())
478 ClangdServerOpts.WorkspaceRoot = *Params.rootPath;
Sam McCall3d0adbe2018-10-18 14:41:50 +0000479 if (Server)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000480 return Reply(llvm::make_error<LSPError>("server already initialized",
481 ErrorCode::InvalidRequest));
Sam McCallbc904612018-10-25 04:22:52 +0000482 if (const auto &Dir = Params.initializationOptions.compilationDatabasePath)
483 CompileCommandsDir = Dir;
Kadir Cetinkaya256247c2019-06-26 07:45:27 +0000484 if (UseDirBasedCDB) {
Jonas Devlieghere1c705d92019-08-14 23:52:23 +0000485 BaseCDB = std::make_unique<DirectoryBasedGlobalCompilationDatabase>(
Sam McCallc55d09a2018-11-02 13:09:36 +0000486 CompileCommandsDir);
Kadir Cetinkaya256247c2019-06-26 07:45:27 +0000487 BaseCDB = getQueryDriverDatabase(
488 llvm::makeArrayRef(ClangdServerOpts.QueryDriverGlobs),
489 std::move(BaseCDB));
490 }
Sam McCall99768b22019-11-29 19:37:48 +0100491 auto Mangler = CommandMangler::detect();
492 if (ClangdServerOpts.ResourceDir)
493 Mangler.ResourceDir = *ClangdServerOpts.ResourceDir;
Kadir Cetinkayabe6b35d2019-01-22 09:10:20 +0000494 CDB.emplace(BaseCDB.get(), Params.initializationOptions.fallbackFlags,
Sam McCall99768b22019-11-29 19:37:48 +0100495 tooling::ArgumentsAdjuster(Mangler));
Kadir Cetinkaya9d662472019-10-15 14:20:52 +0000496 {
497 // Switch caller's context with LSPServer's background context. Since we
498 // rather want to propagate information from LSPServer's context into the
499 // Server, CDB, etc.
500 WithContext MainContext(BackgroundContext.clone());
501 llvm::Optional<WithContextValue> WithOffsetEncoding;
502 if (NegotiatedOffsetEncoding)
503 WithOffsetEncoding.emplace(kCurrentOffsetEncoding,
504 *NegotiatedOffsetEncoding);
Sam McCall6ef1cce2020-01-24 14:08:56 +0100505 Server.emplace(*CDB, FSProvider, ClangdServerOpts,
506 static_cast<ClangdServer::Callbacks *>(this));
Kadir Cetinkaya9d662472019-10-15 14:20:52 +0000507 }
Sam McCallbc904612018-10-25 04:22:52 +0000508 applyConfiguration(Params.initializationOptions.ConfigSettings);
Simon Marchi88016782018-08-01 11:28:49 +0000509
Sam McCallbf6a2fc2018-10-17 07:33:42 +0000510 CCOpts.EnableSnippets = Params.capabilities.CompletionSnippets;
Sam McCall8d412942019-06-18 11:57:26 +0000511 CCOpts.IncludeFixIts = Params.capabilities.CompletionFixes;
Sam McCall5f092e32019-07-08 17:27:15 +0000512 if (!CCOpts.BundleOverloads.hasValue())
513 CCOpts.BundleOverloads = Params.capabilities.HasSignatureHelp;
Sam McCallbf6a2fc2018-10-17 07:33:42 +0000514 DiagOpts.EmbedFixesInDiagnostics = Params.capabilities.DiagnosticFixes;
515 DiagOpts.SendDiagnosticCategory = Params.capabilities.DiagnosticCategory;
Sam McCallc9e4ee92019-04-18 15:17:07 +0000516 DiagOpts.EmitRelatedLocations =
517 Params.capabilities.DiagnosticRelatedInformation;
Sam McCallbf6a2fc2018-10-17 07:33:42 +0000518 if (Params.capabilities.WorkspaceSymbolKinds)
519 SupportedSymbolKinds |= *Params.capabilities.WorkspaceSymbolKinds;
520 if (Params.capabilities.CompletionItemKinds)
521 SupportedCompletionItemKinds |= *Params.capabilities.CompletionItemKinds;
522 SupportsCodeAction = Params.capabilities.CodeActionStructure;
Ilya Biryukov19d75602018-11-23 15:21:19 +0000523 SupportsHierarchicalDocumentSymbol =
524 Params.capabilities.HierarchicalDocumentSymbol;
Haojian Wub6188492018-12-20 15:39:12 +0000525 SupportFileStatus = Params.initializationOptions.FileStatus;
Ilya Biryukovf9169d02019-05-29 10:01:00 +0000526 HoverContentFormat = Params.capabilities.HoverContentFormat;
Ilya Biryukov4ef0f822019-06-04 09:36:59 +0000527 SupportsOffsetsInSignatureHelp = Params.capabilities.OffsetsInSignatureHelp;
Sam McCall7d20e802020-01-22 19:41:45 +0100528 if (Params.capabilities.WorkDoneProgress)
529 BackgroundIndexProgressState = BackgroundIndexProgress::Empty;
530 BackgroundIndexSkipCreate = Params.capabilities.ImplicitProgressCreation;
Haojian Wuf429ab62019-07-24 07:49:23 +0000531
532 // Per LSP, renameProvider can be either boolean or RenameOptions.
533 // RenameOptions will be specified if the client states it supports prepare.
534 llvm::json::Value RenameProvider =
535 llvm::json::Object{{"prepareProvider", true}};
536 if (!Params.capabilities.RenamePrepareSupport) // Only boolean allowed per LSP
537 RenameProvider = true;
538
Haojian Wu08d93f12019-08-22 14:53:45 +0000539 // Per LSP, codeActionProvide can be either boolean or CodeActionOptions.
540 // CodeActionOptions is only valid if the client supports action literal
541 // via textDocument.codeAction.codeActionLiteralSupport.
542 llvm::json::Value CodeActionProvider = true;
543 if (Params.capabilities.CodeActionStructure)
544 CodeActionProvider = llvm::json::Object{
545 {"codeActionKinds",
546 {CodeAction::QUICKFIX_KIND, CodeAction::REFACTOR_KIND,
547 CodeAction::INFO_KIND}}};
548
Sam McCalla69698f2019-03-27 17:47:49 +0000549 llvm::json::Object Result{
Sam McCall6f7dca92020-03-03 12:25:46 +0100550 {{"serverInfo",
551 llvm::json::Object{{"name", "clangd"},
552 {"version", getClangToolFullVersion("clangd")}}},
553 {"capabilities",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000554 llvm::json::Object{
Simon Marchi98082622018-03-26 14:41:40 +0000555 {"textDocumentSync", (int)TextDocumentSyncKind::Incremental},
Sam McCall0930ab02017-11-07 15:49:35 +0000556 {"documentFormattingProvider", true},
557 {"documentRangeFormattingProvider", true},
558 {"documentOnTypeFormattingProvider",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000559 llvm::json::Object{
Sam McCall25c62572019-06-10 14:26:21 +0000560 {"firstTriggerCharacter", "\n"},
Sam McCall0930ab02017-11-07 15:49:35 +0000561 {"moreTriggerCharacter", {}},
562 }},
Haojian Wu08d93f12019-08-22 14:53:45 +0000563 {"codeActionProvider", std::move(CodeActionProvider)},
Sam McCall0930ab02017-11-07 15:49:35 +0000564 {"completionProvider",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000565 llvm::json::Object{
Kirill Bobyrev2a095ff2020-02-18 17:55:12 +0100566 {"allCommitCharacters", " \t()[]{}<>:;,+-/*%^&#?.=\"'|"},
Sam McCall0930ab02017-11-07 15:49:35 +0000567 {"resolveProvider", false},
Ilya Biryukovb0826bd2019-01-03 13:37:12 +0000568 // We do extra checks for '>' and ':' in completion to only
569 // trigger on '->' and '::'.
Sam McCall0930ab02017-11-07 15:49:35 +0000570 {"triggerCharacters", {".", ">", ":"}},
571 }},
572 {"signatureHelpProvider",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000573 llvm::json::Object{
Sam McCall0930ab02017-11-07 15:49:35 +0000574 {"triggerCharacters", {"(", ","}},
575 }},
Sam McCall866ba2c2019-02-01 11:26:13 +0000576 {"declarationProvider", true},
Sam McCall0930ab02017-11-07 15:49:35 +0000577 {"definitionProvider", true},
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000578 {"documentHighlightProvider", true},
Sam McCall8d7ecc12019-12-16 19:08:51 +0100579 {"documentLinkProvider",
580 llvm::json::Object{
581 {"resolveProvider", false},
582 }},
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000583 {"hoverProvider", true},
Haojian Wuf429ab62019-07-24 07:49:23 +0000584 {"renameProvider", std::move(RenameProvider)},
Utkarsh Saxena55925da2019-09-24 13:38:33 +0000585 {"selectionRangeProvider", true},
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000586 {"documentSymbolProvider", true},
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000587 {"workspaceSymbolProvider", true},
Sam McCall1ad142f2018-09-05 11:53:07 +0000588 {"referencesProvider", true},
Sam McCall0930ab02017-11-07 15:49:35 +0000589 {"executeCommandProvider",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000590 llvm::json::Object{
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000591 {"commands",
592 {ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND,
593 ExecuteCommandParams::CLANGD_APPLY_TWEAK}},
Sam McCall0930ab02017-11-07 15:49:35 +0000594 }},
Kadir Cetinkaya86658022019-03-19 09:27:04 +0000595 {"typeHierarchyProvider", true},
Sam McCalla69698f2019-03-27 17:47:49 +0000596 }}}};
597 if (NegotiatedOffsetEncoding)
598 Result["offsetEncoding"] = *NegotiatedOffsetEncoding;
Johan Vikstroma848dab2019-07-04 07:53:12 +0000599 if (Params.capabilities.SemanticHighlighting)
600 Result.getObject("capabilities")
601 ->insert(
602 {"semanticHighlighting",
Haojian Wu1ca2ee42019-07-04 12:27:21 +0000603 llvm::json::Object{{"scopes", buildHighlightScopeLookupTable()}}});
Sam McCalla69698f2019-03-27 17:47:49 +0000604 Reply(std::move(Result));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000605}
606
Sam McCall8a2d2942020-03-03 12:12:14 +0100607void ClangdLSPServer::onInitialized(const InitializedParams &Params) {}
608
Sam McCall2c30fbc2018-10-18 12:32:04 +0000609void ClangdLSPServer::onShutdown(const ShutdownParams &Params,
610 Callback<std::nullptr_t> Reply) {
Ilya Biryukov0d9b8a32017-10-25 08:45:41 +0000611 // Do essentially nothing, just say we're ready to exit.
612 ShutdownRequestReceived = true;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000613 Reply(nullptr);
Sam McCall8a5dded2017-10-12 13:29:58 +0000614}
Ilya Biryukovafb55542017-05-16 14:40:30 +0000615
Sam McCall422c8282018-11-26 16:00:11 +0000616// sync is a clangd extension: it blocks until all background work completes.
617// It blocks the calling thread, so no messages are processed until it returns!
618void ClangdLSPServer::onSync(const NoParams &Params,
619 Callback<std::nullptr_t> Reply) {
620 if (Server->blockUntilIdleForTest(/*TimeoutSeconds=*/60))
621 Reply(nullptr);
622 else
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000623 Reply(llvm::createStringError(llvm::inconvertibleErrorCode(),
624 "Not idle after a minute"));
Sam McCall422c8282018-11-26 16:00:11 +0000625}
626
Sam McCall2c30fbc2018-10-18 12:32:04 +0000627void ClangdLSPServer::onDocumentDidOpen(
628 const DidOpenTextDocumentParams &Params) {
Simon Marchi9569fd52018-03-16 14:30:42 +0000629 PathRef File = Params.textDocument.uri.file();
Ilya Biryukovb10ef472018-06-13 09:20:41 +0000630
Sam McCall2c30fbc2018-10-18 12:32:04 +0000631 const std::string &Contents = Params.textDocument.text;
Simon Marchi9569fd52018-03-16 14:30:42 +0000632
Simon Marchi98082622018-03-26 14:41:40 +0000633 DraftMgr.addDraft(File, Contents);
Ilya Biryukov652364b2018-09-26 05:48:29 +0000634 Server->addDocument(File, Contents, WantDiagnostics::Yes);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000635}
636
Sam McCall2c30fbc2018-10-18 12:32:04 +0000637void ClangdLSPServer::onDocumentDidChange(
638 const DidChangeTextDocumentParams &Params) {
Eric Liu51fed182018-02-22 18:40:39 +0000639 auto WantDiags = WantDiagnostics::Auto;
640 if (Params.wantDiagnostics.hasValue())
641 WantDiags = Params.wantDiagnostics.getValue() ? WantDiagnostics::Yes
642 : WantDiagnostics::No;
Simon Marchi9569fd52018-03-16 14:30:42 +0000643
644 PathRef File = Params.textDocument.uri.file();
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000645 llvm::Expected<std::string> Contents =
Simon Marchi98082622018-03-26 14:41:40 +0000646 DraftMgr.updateDraft(File, Params.contentChanges);
647 if (!Contents) {
648 // If this fails, we are most likely going to be not in sync anymore with
649 // the client. It is better to remove the draft and let further operations
650 // fail rather than giving wrong results.
651 DraftMgr.removeDraft(File);
Ilya Biryukov652364b2018-09-26 05:48:29 +0000652 Server->removeDocument(File);
Sam McCallbed58852018-07-11 10:35:11 +0000653 elog("Failed to update {0}: {1}", File, Contents.takeError());
Simon Marchi98082622018-03-26 14:41:40 +0000654 return;
655 }
Simon Marchi9569fd52018-03-16 14:30:42 +0000656
David Goldman6ff02282020-02-03 15:14:49 -0500657 Server->addDocument(File, *Contents, WantDiags, Params.forceRebuild);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000658}
659
Sam McCall2c30fbc2018-10-18 12:32:04 +0000660void ClangdLSPServer::onFileEvent(const DidChangeWatchedFilesParams &Params) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000661 Server->onFileEvent(Params);
Marc-Andre Laperlebf114242017-10-02 18:00:37 +0000662}
663
Sam McCall2c30fbc2018-10-18 12:32:04 +0000664void ClangdLSPServer::onCommand(const ExecuteCommandParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000665 Callback<llvm::json::Value> Reply) {
Ilya Biryukov12864002019-08-16 12:46:41 +0000666 auto ApplyEdit = [this](WorkspaceEdit WE, std::string SuccessMessage,
667 decltype(Reply) Reply) {
Eric Liuc5105f92018-02-16 14:15:55 +0000668 ApplyWorkspaceEditParams Edit;
669 Edit.edit = std::move(WE);
Ilya Biryukov12864002019-08-16 12:46:41 +0000670 call<ApplyWorkspaceEditResponse>(
671 "workspace/applyEdit", std::move(Edit),
672 [Reply = std::move(Reply), SuccessMessage = std::move(SuccessMessage)](
673 llvm::Expected<ApplyWorkspaceEditResponse> Response) mutable {
674 if (!Response)
675 return Reply(Response.takeError());
676 if (!Response->applied) {
677 std::string Reason = Response->failureReason
678 ? *Response->failureReason
679 : "unknown reason";
680 return Reply(llvm::createStringError(
681 llvm::inconvertibleErrorCode(),
682 ("edits were not applied: " + Reason).c_str()));
683 }
684 return Reply(SuccessMessage);
685 });
Eric Liuc5105f92018-02-16 14:15:55 +0000686 };
Ilya Biryukov12864002019-08-16 12:46:41 +0000687
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000688 if (Params.command == ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND &&
689 Params.workspaceEdit) {
690 // The flow for "apply-fix" :
691 // 1. We publish a diagnostic, including fixits
692 // 2. The user clicks on the diagnostic, the editor asks us for code actions
693 // 3. We send code actions, with the fixit embedded as context
694 // 4. The user selects the fixit, the editor asks us to apply it
695 // 5. We unwrap the changes and send them back to the editor
Haojian Wuf2516342019-08-05 12:48:09 +0000696 // 6. The editor applies the changes (applyEdit), and sends us a reply
697 // 7. We unwrap the reply and send a reply to the editor.
Ilya Biryukov12864002019-08-16 12:46:41 +0000698 ApplyEdit(*Params.workspaceEdit, "Fix applied.", std::move(Reply));
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000699 } else if (Params.command == ExecuteCommandParams::CLANGD_APPLY_TWEAK &&
700 Params.tweakArgs) {
701 auto Code = DraftMgr.getDraft(Params.tweakArgs->file.file());
702 if (!Code)
703 return Reply(llvm::createStringError(
704 llvm::inconvertibleErrorCode(),
705 "trying to apply a code action for a non-added file"));
706
Ilya Biryukov12864002019-08-16 12:46:41 +0000707 auto Action = [this, ApplyEdit, Reply = std::move(Reply),
708 File = Params.tweakArgs->file, Code = std::move(*Code)](
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000709 llvm::Expected<Tweak::Effect> R) mutable {
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000710 if (!R)
711 return Reply(R.takeError());
712
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000713 assert(R->ShowMessage ||
714 (!R->ApplyEdits.empty() && "tweak has no effect"));
Ilya Biryukov12864002019-08-16 12:46:41 +0000715
Sam McCall395fde72019-06-18 13:37:54 +0000716 if (R->ShowMessage) {
717 ShowMessageParams Msg;
718 Msg.message = *R->ShowMessage;
719 Msg.type = MessageType::Info;
720 notify("window/showMessage", Msg);
721 }
Ilya Biryukov12864002019-08-16 12:46:41 +0000722 // When no edit is specified, make sure we Reply().
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000723 if (R->ApplyEdits.empty())
724 return Reply("Tweak applied.");
725
Haojian Wu852bafa2019-10-23 14:40:20 +0200726 if (auto Err = validateEdits(DraftMgr, R->ApplyEdits))
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000727 return Reply(std::move(Err));
728
729 WorkspaceEdit WE;
730 WE.changes.emplace();
731 for (const auto &It : R->ApplyEdits) {
Kadir Cetinkayae95e5162019-10-02 09:12:01 +0000732 (*WE.changes)[URI::createFile(It.first()).toString()] =
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000733 It.second.asTextEdits();
734 }
735 // ApplyEdit will take care of calling Reply().
736 return ApplyEdit(std::move(WE), "Tweak applied.", std::move(Reply));
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000737 };
738 Server->applyTweak(Params.tweakArgs->file.file(),
739 Params.tweakArgs->selection, Params.tweakArgs->tweakID,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000740 std::move(Action));
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000741 } else {
742 // We should not get here because ExecuteCommandParams would not have
743 // parsed in the first place and this handler should not be called. But if
744 // more commands are added, this will be here has a safe guard.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000745 Reply(llvm::make_error<LSPError>(
746 llvm::formatv("Unsupported command \"{0}\".", Params.command).str(),
Sam McCall2c30fbc2018-10-18 12:32:04 +0000747 ErrorCode::InvalidParams));
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000748 }
749}
750
Sam McCall2c30fbc2018-10-18 12:32:04 +0000751void ClangdLSPServer::onWorkspaceSymbol(
752 const WorkspaceSymbolParams &Params,
753 Callback<std::vector<SymbolInformation>> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000754 Server->workspaceSymbols(
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000755 Params.query, CCOpts.Limit,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000756 [Reply = std::move(Reply),
757 this](llvm::Expected<std::vector<SymbolInformation>> Items) mutable {
758 if (!Items)
759 return Reply(Items.takeError());
760 for (auto &Sym : *Items)
761 Sym.kind = adjustKindToCapability(Sym.kind, SupportedSymbolKinds);
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000762
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000763 Reply(std::move(*Items));
764 });
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000765}
766
Haojian Wuf429ab62019-07-24 07:49:23 +0000767void ClangdLSPServer::onPrepareRename(const TextDocumentPositionParams &Params,
768 Callback<llvm::Optional<Range>> Reply) {
769 Server->prepareRename(Params.textDocument.uri.file(), Params.position,
Haojian Wu34d0e1b2020-02-19 15:37:36 +0100770 RenameOpts, std::move(Reply));
Haojian Wuf429ab62019-07-24 07:49:23 +0000771}
772
Sam McCall2c30fbc2018-10-18 12:32:04 +0000773void ClangdLSPServer::onRename(const RenameParams &Params,
774 Callback<WorkspaceEdit> Reply) {
Benjamin Krameradcd0262020-01-28 20:23:46 +0100775 Path File = std::string(Params.textDocument.uri.file());
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000776 llvm::Optional<std::string> Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000777 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000778 return Reply(llvm::make_error<LSPError>(
779 "onRename called for non-added file", ErrorCode::InvalidParams));
Haojian Wu852bafa2019-10-23 14:40:20 +0200780 Server->rename(
Haojian Wu34d0e1b2020-02-19 15:37:36 +0100781 File, Params.position, Params.newName, RenameOpts,
Haojian Wu852bafa2019-10-23 14:40:20 +0200782 [File, Params, Reply = std::move(Reply),
783 this](llvm::Expected<FileEdits> Edits) mutable {
784 if (!Edits)
785 return Reply(Edits.takeError());
786 if (auto Err = validateEdits(DraftMgr, *Edits))
787 return Reply(std::move(Err));
788 WorkspaceEdit Result;
789 Result.changes.emplace();
790 for (const auto &Rep : *Edits) {
791 (*Result.changes)[URI::createFile(Rep.first()).toString()] =
792 Rep.second.asTextEdits();
793 }
794 Reply(Result);
795 });
Haojian Wu345099c2017-11-09 11:30:04 +0000796}
797
Sam McCall2c30fbc2018-10-18 12:32:04 +0000798void ClangdLSPServer::onDocumentDidClose(
799 const DidCloseTextDocumentParams &Params) {
Simon Marchi9569fd52018-03-16 14:30:42 +0000800 PathRef File = Params.textDocument.uri.file();
801 DraftMgr.removeDraft(File);
Ilya Biryukov652364b2018-09-26 05:48:29 +0000802 Server->removeDocument(File);
Ilya Biryukov49c10712019-03-25 10:15:11 +0000803
804 {
805 std::lock_guard<std::mutex> Lock(FixItsMutex);
806 FixItsMap.erase(File);
807 }
Johan Vikstromc2653ef22019-08-01 08:08:44 +0000808 {
809 std::lock_guard<std::mutex> HLock(HighlightingsMutex);
810 FileToHighlightings.erase(File);
811 }
Ilya Biryukov49c10712019-03-25 10:15:11 +0000812 // clangd will not send updates for this file anymore, so we empty out the
813 // list of diagnostics shown on the client (e.g. in the "Problems" pane of
814 // VSCode). Note that this cannot race with actual diagnostics responses
815 // because removeDocument() guarantees no diagnostic callbacks will be
816 // executed after it returns.
817 publishDiagnostics(URIForFile::canonicalize(File, /*TUPath=*/File), {});
Ilya Biryukovafb55542017-05-16 14:40:30 +0000818}
819
Sam McCall4db732a2017-09-30 10:08:52 +0000820void ClangdLSPServer::onDocumentOnTypeFormatting(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000821 const DocumentOnTypeFormattingParams &Params,
822 Callback<std::vector<TextEdit>> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000823 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000824 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000825 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000826 return Reply(llvm::make_error<LSPError>(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000827 "onDocumentOnTypeFormatting called for non-added file",
828 ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000829
Sam McCall25c62572019-06-10 14:26:21 +0000830 Reply(Server->formatOnType(*Code, File, Params.position, Params.ch));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000831}
832
Sam McCall4db732a2017-09-30 10:08:52 +0000833void ClangdLSPServer::onDocumentRangeFormatting(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000834 const DocumentRangeFormattingParams &Params,
835 Callback<std::vector<TextEdit>> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000836 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000837 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000838 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000839 return Reply(llvm::make_error<LSPError>(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000840 "onDocumentRangeFormatting called for non-added file",
841 ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000842
Ilya Biryukov652364b2018-09-26 05:48:29 +0000843 auto ReplacementsOrError = Server->formatRange(*Code, File, Params.range);
Raoul Wols212bcf82017-12-12 20:25:06 +0000844 if (ReplacementsOrError)
Sam McCall2c30fbc2018-10-18 12:32:04 +0000845 Reply(replacementsToEdits(*Code, ReplacementsOrError.get()));
Raoul Wols212bcf82017-12-12 20:25:06 +0000846 else
Sam McCall2c30fbc2018-10-18 12:32:04 +0000847 Reply(ReplacementsOrError.takeError());
Ilya Biryukovafb55542017-05-16 14:40:30 +0000848}
849
Sam McCall2c30fbc2018-10-18 12:32:04 +0000850void ClangdLSPServer::onDocumentFormatting(
851 const DocumentFormattingParams &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>(
857 "onDocumentFormatting called for non-added file",
858 ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000859
Ilya Biryukov652364b2018-09-26 05:48:29 +0000860 auto ReplacementsOrError = Server->formatFile(*Code, File);
Raoul Wols212bcf82017-12-12 20:25:06 +0000861 if (ReplacementsOrError)
Sam McCall2c30fbc2018-10-18 12:32:04 +0000862 Reply(replacementsToEdits(*Code, ReplacementsOrError.get()));
Raoul Wols212bcf82017-12-12 20:25:06 +0000863 else
Sam McCall2c30fbc2018-10-18 12:32:04 +0000864 Reply(ReplacementsOrError.takeError());
Sam McCall4db732a2017-09-30 10:08:52 +0000865}
866
Ilya Biryukov19d75602018-11-23 15:21:19 +0000867/// The functions constructs a flattened view of the DocumentSymbol hierarchy.
868/// Used by the clients that do not support the hierarchical view.
869static std::vector<SymbolInformation>
870flattenSymbolHierarchy(llvm::ArrayRef<DocumentSymbol> Symbols,
871 const URIForFile &FileURI) {
872
873 std::vector<SymbolInformation> Results;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000874 std::function<void(const DocumentSymbol &, llvm::StringRef)> Process =
875 [&](const DocumentSymbol &S, llvm::Optional<llvm::StringRef> ParentName) {
Ilya Biryukov19d75602018-11-23 15:21:19 +0000876 SymbolInformation SI;
Benjamin Krameradcd0262020-01-28 20:23:46 +0100877 SI.containerName = std::string(ParentName ? "" : *ParentName);
Ilya Biryukov19d75602018-11-23 15:21:19 +0000878 SI.name = S.name;
879 SI.kind = S.kind;
880 SI.location.range = S.range;
881 SI.location.uri = FileURI;
882
883 Results.push_back(std::move(SI));
884 std::string FullName =
885 !ParentName ? S.name : (ParentName->str() + "::" + S.name);
886 for (auto &C : S.children)
887 Process(C, /*ParentName=*/FullName);
888 };
889 for (auto &S : Symbols)
890 Process(S, /*ParentName=*/"");
891 return Results;
892}
893
894void ClangdLSPServer::onDocumentSymbol(const DocumentSymbolParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000895 Callback<llvm::json::Value> Reply) {
Ilya Biryukov19d75602018-11-23 15:21:19 +0000896 URIForFile FileURI = Params.textDocument.uri;
Ilya Biryukov652364b2018-09-26 05:48:29 +0000897 Server->documentSymbols(
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000898 Params.textDocument.uri.file(),
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000899 [this, FileURI, Reply = std::move(Reply)](
900 llvm::Expected<std::vector<DocumentSymbol>> Items) mutable {
901 if (!Items)
902 return Reply(Items.takeError());
903 adjustSymbolKinds(*Items, SupportedSymbolKinds);
904 if (SupportsHierarchicalDocumentSymbol)
905 return Reply(std::move(*Items));
906 else
907 return Reply(flattenSymbolHierarchy(*Items, FileURI));
908 });
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000909}
910
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000911static llvm::Optional<Command> asCommand(const CodeAction &Action) {
Sam McCall20841d42018-10-16 16:29:41 +0000912 Command Cmd;
913 if (Action.command && Action.edit)
Sam McCallc008af62018-10-20 15:30:37 +0000914 return None; // Not representable. (We never emit these anyway).
Sam McCall20841d42018-10-16 16:29:41 +0000915 if (Action.command) {
916 Cmd = *Action.command;
917 } else if (Action.edit) {
Benjamin Krameradcd0262020-01-28 20:23:46 +0100918 Cmd.command = std::string(Command::CLANGD_APPLY_FIX_COMMAND);
Sam McCall20841d42018-10-16 16:29:41 +0000919 Cmd.workspaceEdit = *Action.edit;
920 } else {
Sam McCallc008af62018-10-20 15:30:37 +0000921 return None;
Sam McCall20841d42018-10-16 16:29:41 +0000922 }
923 Cmd.title = Action.title;
924 if (Action.kind && *Action.kind == CodeAction::QUICKFIX_KIND)
925 Cmd.title = "Apply fix: " + Cmd.title;
926 return Cmd;
927}
928
Sam McCall2c30fbc2018-10-18 12:32:04 +0000929void ClangdLSPServer::onCodeAction(const CodeActionParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000930 Callback<llvm::json::Value> Reply) {
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000931 URIForFile File = Params.textDocument.uri;
932 auto Code = DraftMgr.getDraft(File.file());
Sam McCall2c30fbc2018-10-18 12:32:04 +0000933 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000934 return Reply(llvm::make_error<LSPError>(
935 "onCodeAction called for non-added file", ErrorCode::InvalidParams));
Sam McCall20841d42018-10-16 16:29:41 +0000936 // We provide a code action for Fixes on the specified diagnostics.
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000937 std::vector<CodeAction> FixIts;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000938 for (const Diagnostic &D : Params.context.diagnostics) {
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000939 for (auto &F : getFixes(File.file(), D)) {
940 FixIts.push_back(toCodeAction(F, Params.textDocument.uri));
941 FixIts.back().diagnostics = {D};
Sam McCalldd0566b2017-11-06 15:40:30 +0000942 }
Ilya Biryukovafb55542017-05-16 14:40:30 +0000943 }
Sam McCall20841d42018-10-16 16:29:41 +0000944
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000945 // Now enumerate the semantic code actions.
946 auto ConsumeActions =
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000947 [Reply = std::move(Reply), File, Code = std::move(*Code),
948 Selection = Params.range, FixIts = std::move(FixIts), this](
949 llvm::Expected<std::vector<ClangdServer::TweakRef>> Tweaks) mutable {
Ilya Biryukovc6ed7782019-01-30 14:24:17 +0000950 if (!Tweaks)
951 return Reply(Tweaks.takeError());
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000952
953 std::vector<CodeAction> Actions = std::move(FixIts);
954 Actions.reserve(Actions.size() + Tweaks->size());
955 for (const auto &T : *Tweaks)
956 Actions.push_back(toCodeAction(T, File, Selection));
957
958 if (SupportsCodeAction)
959 return Reply(llvm::json::Array(Actions));
960 std::vector<Command> Commands;
961 for (const auto &Action : Actions) {
962 if (auto Command = asCommand(Action))
963 Commands.push_back(std::move(*Command));
964 }
965 return Reply(llvm::json::Array(Commands));
966 };
967
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000968 Server->enumerateTweaks(File.file(), Params.range, std::move(ConsumeActions));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000969}
970
Ilya Biryukovb0826bd2019-01-03 13:37:12 +0000971void ClangdLSPServer::onCompletion(const CompletionParams &Params,
Sam McCall2c30fbc2018-10-18 12:32:04 +0000972 Callback<CompletionList> Reply) {
Ilya Biryukova7a11472019-06-07 16:24:38 +0000973 if (!shouldRunCompletion(Params)) {
974 // Clients sometimes auto-trigger completions in undesired places (e.g.
975 // 'a >^ '), we return empty results in those cases.
976 vlog("ignored auto-triggered completion, preceding char did not match");
977 return Reply(CompletionList());
978 }
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000979 Server->codeComplete(Params.textDocument.uri.file(), Params.position, CCOpts,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000980 [Reply = std::move(Reply),
981 this](llvm::Expected<CodeCompleteResult> List) mutable {
982 if (!List)
983 return Reply(List.takeError());
984 CompletionList LSPList;
985 LSPList.isIncomplete = List->HasMore;
986 for (const auto &R : List->Completions) {
987 CompletionItem C = R.render(CCOpts);
988 C.kind = adjustKindToCapability(
989 C.kind, SupportedCompletionItemKinds);
990 LSPList.items.push_back(std::move(C));
991 }
992 return Reply(std::move(LSPList));
993 });
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000994}
995
Sam McCall2c30fbc2018-10-18 12:32:04 +0000996void ClangdLSPServer::onSignatureHelp(const TextDocumentPositionParams &Params,
997 Callback<SignatureHelp> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000998 Server->signatureHelp(Params.textDocument.uri.file(), Params.position,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000999 [Reply = std::move(Reply), this](
1000 llvm::Expected<SignatureHelp> Signature) mutable {
1001 if (!Signature)
1002 return Reply(Signature.takeError());
1003 if (SupportsOffsetsInSignatureHelp)
1004 return Reply(std::move(*Signature));
1005 // Strip out the offsets from signature help for
1006 // clients that only support string labels.
1007 for (auto &SigInfo : Signature->signatures) {
1008 for (auto &Param : SigInfo.parameters)
1009 Param.labelOffsets.reset();
1010 }
1011 return Reply(std::move(*Signature));
1012 });
Ilya Biryukov652364b2018-09-26 05:48:29 +00001013}
1014
Sam McCall0dbab7f2019-02-02 05:56:00 +00001015// Go to definition has a toggle function: if def and decl are distinct, then
1016// the first press gives you the def, the second gives you the matching def.
1017// getToggle() returns the counterpart location that under the cursor.
1018//
1019// We return the toggled location alone (ignoring other symbols) to encourage
1020// editors to "bounce" quickly between locations, without showing a menu.
1021static Location *getToggle(const TextDocumentPositionParams &Point,
1022 LocatedSymbol &Sym) {
1023 // Toggle only makes sense with two distinct locations.
1024 if (!Sym.Definition || *Sym.Definition == Sym.PreferredDeclaration)
1025 return nullptr;
1026 if (Sym.Definition->uri.file() == Point.textDocument.uri.file() &&
1027 Sym.Definition->range.contains(Point.position))
1028 return &Sym.PreferredDeclaration;
1029 if (Sym.PreferredDeclaration.uri.file() == Point.textDocument.uri.file() &&
1030 Sym.PreferredDeclaration.range.contains(Point.position))
1031 return &*Sym.Definition;
1032 return nullptr;
1033}
1034
Sam McCall2c30fbc2018-10-18 12:32:04 +00001035void ClangdLSPServer::onGoToDefinition(const TextDocumentPositionParams &Params,
1036 Callback<std::vector<Location>> Reply) {
Sam McCall866ba2c2019-02-01 11:26:13 +00001037 Server->locateSymbolAt(
1038 Params.textDocument.uri.file(), Params.position,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001039 [Params, Reply = std::move(Reply)](
1040 llvm::Expected<std::vector<LocatedSymbol>> Symbols) mutable {
1041 if (!Symbols)
1042 return Reply(Symbols.takeError());
1043 std::vector<Location> Defs;
1044 for (auto &S : *Symbols) {
1045 if (Location *Toggle = getToggle(Params, S))
1046 return Reply(std::vector<Location>{std::move(*Toggle)});
1047 Defs.push_back(S.Definition.getValueOr(S.PreferredDeclaration));
1048 }
1049 Reply(std::move(Defs));
1050 });
Sam McCall866ba2c2019-02-01 11:26:13 +00001051}
1052
1053void ClangdLSPServer::onGoToDeclaration(
1054 const TextDocumentPositionParams &Params,
1055 Callback<std::vector<Location>> Reply) {
1056 Server->locateSymbolAt(
1057 Params.textDocument.uri.file(), Params.position,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001058 [Params, Reply = std::move(Reply)](
1059 llvm::Expected<std::vector<LocatedSymbol>> Symbols) mutable {
1060 if (!Symbols)
1061 return Reply(Symbols.takeError());
1062 std::vector<Location> Decls;
1063 for (auto &S : *Symbols) {
1064 if (Location *Toggle = getToggle(Params, S))
1065 return Reply(std::vector<Location>{std::move(*Toggle)});
1066 Decls.push_back(std::move(S.PreferredDeclaration));
1067 }
1068 Reply(std::move(Decls));
1069 });
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +00001070}
1071
Sam McCall111fe842019-05-07 07:55:35 +00001072void ClangdLSPServer::onSwitchSourceHeader(
1073 const TextDocumentIdentifier &Params,
Sam McCallb9ec3e92019-05-07 08:30:32 +00001074 Callback<llvm::Optional<URIForFile>> Reply) {
Haojian Wud6d5edd2019-10-01 10:21:15 +00001075 Server->switchSourceHeader(
1076 Params.uri.file(),
1077 [Reply = std::move(Reply),
1078 Params](llvm::Expected<llvm::Optional<clangd::Path>> Path) mutable {
1079 if (!Path)
1080 return Reply(Path.takeError());
1081 if (*Path)
Haojian Wu77c97002019-10-07 11:37:25 +00001082 return Reply(URIForFile::canonicalize(**Path, Params.uri.file()));
Haojian Wud6d5edd2019-10-01 10:21:15 +00001083 return Reply(llvm::None);
1084 });
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +00001085}
1086
Sam McCall2c30fbc2018-10-18 12:32:04 +00001087void ClangdLSPServer::onDocumentHighlight(
1088 const TextDocumentPositionParams &Params,
1089 Callback<std::vector<DocumentHighlight>> Reply) {
1090 Server->findDocumentHighlights(Params.textDocument.uri.file(),
1091 Params.position, std::move(Reply));
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +00001092}
1093
Sam McCall2c30fbc2018-10-18 12:32:04 +00001094void ClangdLSPServer::onHover(const TextDocumentPositionParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001095 Callback<llvm::Optional<Hover>> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +00001096 Server->findHover(Params.textDocument.uri.file(), Params.position,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001097 [Reply = std::move(Reply), this](
1098 llvm::Expected<llvm::Optional<HoverInfo>> H) mutable {
1099 if (!H)
1100 return Reply(H.takeError());
1101 if (!*H)
1102 return Reply(llvm::None);
Ilya Biryukovf9169d02019-05-29 10:01:00 +00001103
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001104 Hover R;
1105 R.contents.kind = HoverContentFormat;
1106 R.range = (*H)->SymRange;
1107 switch (HoverContentFormat) {
1108 case MarkupKind::PlainText:
Kadir Cetinkaya597c6b62019-12-10 10:28:37 +01001109 R.contents.value = (*H)->present().asPlainText();
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001110 return Reply(std::move(R));
1111 case MarkupKind::Markdown:
Kadir Cetinkaya597c6b62019-12-10 10:28:37 +01001112 R.contents.value = (*H)->present().asMarkdown();
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001113 return Reply(std::move(R));
1114 };
1115 llvm_unreachable("unhandled MarkupKind");
1116 });
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +00001117}
1118
Kadir Cetinkaya86658022019-03-19 09:27:04 +00001119void ClangdLSPServer::onTypeHierarchy(
1120 const TypeHierarchyParams &Params,
1121 Callback<Optional<TypeHierarchyItem>> Reply) {
1122 Server->typeHierarchy(Params.textDocument.uri.file(), Params.position,
1123 Params.resolve, Params.direction, std::move(Reply));
1124}
1125
Nathan Ridge087b0442019-07-13 03:24:48 +00001126void ClangdLSPServer::onResolveTypeHierarchy(
1127 const ResolveTypeHierarchyItemParams &Params,
1128 Callback<Optional<TypeHierarchyItem>> Reply) {
1129 Server->resolveTypeHierarchy(Params.item, Params.resolve, Params.direction,
1130 std::move(Reply));
1131}
1132
Simon Marchi88016782018-08-01 11:28:49 +00001133void ClangdLSPServer::applyConfiguration(
Sam McCallbc904612018-10-25 04:22:52 +00001134 const ConfigurationSettings &Settings) {
Simon Marchiabeed662018-10-16 15:55:03 +00001135 // Per-file update to the compilation database.
David Goldman60249c22020-01-13 17:01:10 -05001136 llvm::StringSet<> ModifiedFiles;
Sam McCallbc904612018-10-25 04:22:52 +00001137 for (auto &Entry : Settings.compilationDatabaseChanges) {
Sam McCallbc904612018-10-25 04:22:52 +00001138 PathRef File = Entry.first;
Sam McCallc55d09a2018-11-02 13:09:36 +00001139 auto Old = CDB->getCompileCommand(File);
1140 auto New =
1141 tooling::CompileCommand(std::move(Entry.second.workingDirectory), File,
1142 std::move(Entry.second.compilationCommand),
1143 /*Output=*/"");
Sam McCall6980edb2018-11-02 14:07:51 +00001144 if (Old != New) {
Sam McCallc55d09a2018-11-02 13:09:36 +00001145 CDB->setCompileCommand(File, std::move(New));
David Goldman60249c22020-01-13 17:01:10 -05001146 ModifiedFiles.insert(File);
Sam McCall6980edb2018-11-02 14:07:51 +00001147 }
Alex Lorenzf8087862018-08-01 17:39:29 +00001148 }
David Goldman60249c22020-01-13 17:01:10 -05001149
1150 reparseOpenedFiles(ModifiedFiles);
Simon Marchi5178f922018-02-22 14:00:39 +00001151}
1152
Johan Vikstroma848dab2019-07-04 07:53:12 +00001153void ClangdLSPServer::publishSemanticHighlighting(
1154 SemanticHighlightingParams Params) {
1155 notify("textDocument/semanticHighlighting", Params);
1156}
1157
Ilya Biryukov49c10712019-03-25 10:15:11 +00001158void ClangdLSPServer::publishDiagnostics(
1159 const URIForFile &File, std::vector<clangd::Diagnostic> Diagnostics) {
1160 // Publish diagnostics.
1161 notify("textDocument/publishDiagnostics",
1162 llvm::json::Object{
1163 {"uri", File},
1164 {"diagnostics", std::move(Diagnostics)},
1165 });
1166}
1167
Simon Marchi88016782018-08-01 11:28:49 +00001168// FIXME: This function needs to be properly tested.
1169void ClangdLSPServer::onChangeConfiguration(
Sam McCall2c30fbc2018-10-18 12:32:04 +00001170 const DidChangeConfigurationParams &Params) {
Simon Marchi88016782018-08-01 11:28:49 +00001171 applyConfiguration(Params.settings);
1172}
1173
Sam McCall2c30fbc2018-10-18 12:32:04 +00001174void ClangdLSPServer::onReference(const ReferenceParams &Params,
1175 Callback<std::vector<Location>> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +00001176 Server->findReferences(Params.textDocument.uri.file(), Params.position,
Haojian Wu5181ada2019-11-18 11:35:00 +01001177 CCOpts.Limit,
1178 [Reply = std::move(Reply)](
1179 llvm::Expected<ReferencesResult> Refs) mutable {
1180 if (!Refs)
1181 return Reply(Refs.takeError());
1182 return Reply(std::move(Refs->References));
1183 });
Sam McCall1ad142f2018-09-05 11:53:07 +00001184}
1185
Jan Korousb4067012018-11-27 16:40:46 +00001186void ClangdLSPServer::onSymbolInfo(const TextDocumentPositionParams &Params,
1187 Callback<std::vector<SymbolDetails>> Reply) {
1188 Server->symbolInfo(Params.textDocument.uri.file(), Params.position,
1189 std::move(Reply));
1190}
1191
Utkarsh Saxena55925da2019-09-24 13:38:33 +00001192void ClangdLSPServer::onSelectionRange(
1193 const SelectionRangeParams &Params,
1194 Callback<std::vector<SelectionRange>> Reply) {
1195 if (Params.positions.size() != 1) {
1196 elog("{0} positions provided to SelectionRange. Supports exactly one "
1197 "position.",
1198 Params.positions.size());
1199 return Reply(llvm::make_error<LSPError>(
1200 "SelectionRange supports exactly one position",
1201 ErrorCode::InvalidRequest));
1202 }
1203 Server->semanticRanges(
1204 Params.textDocument.uri.file(), Params.positions[0],
1205 [Reply = std::move(Reply)](
1206 llvm::Expected<std::vector<Range>> Ranges) mutable {
1207 if (!Ranges) {
1208 return Reply(Ranges.takeError());
1209 }
1210 std::vector<SelectionRange> Result;
1211 Result.emplace_back(render(std::move(*Ranges)));
1212 return Reply(std::move(Result));
1213 });
1214}
1215
Sam McCall8d7ecc12019-12-16 19:08:51 +01001216void ClangdLSPServer::onDocumentLink(
1217 const DocumentLinkParams &Params,
1218 Callback<std::vector<DocumentLink>> Reply) {
1219
1220 // TODO(forster): This currently resolves all targets eagerly. This is slow,
1221 // because it blocks on the preamble/AST being built. We could respond to the
1222 // request faster by using string matching or the lexer to find the includes
1223 // and resolving the targets lazily.
1224 Server->documentLinks(
1225 Params.textDocument.uri.file(),
1226 [Reply = std::move(Reply)](
1227 llvm::Expected<std::vector<DocumentLink>> Links) mutable {
1228 if (!Links) {
1229 return Reply(Links.takeError());
1230 }
1231 return Reply(std::move(Links));
1232 });
1233}
1234
Sam McCalla69698f2019-03-27 17:47:49 +00001235ClangdLSPServer::ClangdLSPServer(
1236 class Transport &Transp, const FileSystemProvider &FSProvider,
1237 const clangd::CodeCompleteOptions &CCOpts,
Haojian Wu34d0e1b2020-02-19 15:37:36 +01001238 const clangd::RenameOptions &RenameOpts,
Sam McCalla69698f2019-03-27 17:47:49 +00001239 llvm::Optional<Path> CompileCommandsDir, bool UseDirBasedCDB,
1240 llvm::Optional<OffsetEncoding> ForcedOffsetEncoding,
1241 const ClangdServer::Options &Opts)
Kadir Cetinkaya9d662472019-10-15 14:20:52 +00001242 : BackgroundContext(Context::current().clone()), Transp(Transp),
1243 MsgHandler(new MessageHandler(*this)), FSProvider(FSProvider),
Haojian Wu34d0e1b2020-02-19 15:37:36 +01001244 CCOpts(CCOpts), RenameOpts(RenameOpts),
1245 SupportedSymbolKinds(defaultSymbolKinds()),
Kadir Cetinkaya133d46f2018-09-27 17:13:07 +00001246 SupportedCompletionItemKinds(defaultCompletionItemKinds()),
Sam McCallc55d09a2018-11-02 13:09:36 +00001247 UseDirBasedCDB(UseDirBasedCDB),
Sam McCalla69698f2019-03-27 17:47:49 +00001248 CompileCommandsDir(std::move(CompileCommandsDir)), ClangdServerOpts(Opts),
1249 NegotiatedOffsetEncoding(ForcedOffsetEncoding) {
Sam McCall2c30fbc2018-10-18 12:32:04 +00001250 // clang-format off
1251 MsgHandler->bind("initialize", &ClangdLSPServer::onInitialize);
Sam McCall8a2d2942020-03-03 12:12:14 +01001252 MsgHandler->bind("initialized", &ClangdLSPServer::onInitialized);
Sam McCall2c30fbc2018-10-18 12:32:04 +00001253 MsgHandler->bind("shutdown", &ClangdLSPServer::onShutdown);
Sam McCall422c8282018-11-26 16:00:11 +00001254 MsgHandler->bind("sync", &ClangdLSPServer::onSync);
Sam McCall2c30fbc2018-10-18 12:32:04 +00001255 MsgHandler->bind("textDocument/rangeFormatting", &ClangdLSPServer::onDocumentRangeFormatting);
1256 MsgHandler->bind("textDocument/onTypeFormatting", &ClangdLSPServer::onDocumentOnTypeFormatting);
1257 MsgHandler->bind("textDocument/formatting", &ClangdLSPServer::onDocumentFormatting);
1258 MsgHandler->bind("textDocument/codeAction", &ClangdLSPServer::onCodeAction);
1259 MsgHandler->bind("textDocument/completion", &ClangdLSPServer::onCompletion);
1260 MsgHandler->bind("textDocument/signatureHelp", &ClangdLSPServer::onSignatureHelp);
1261 MsgHandler->bind("textDocument/definition", &ClangdLSPServer::onGoToDefinition);
Sam McCall866ba2c2019-02-01 11:26:13 +00001262 MsgHandler->bind("textDocument/declaration", &ClangdLSPServer::onGoToDeclaration);
Sam McCall2c30fbc2018-10-18 12:32:04 +00001263 MsgHandler->bind("textDocument/references", &ClangdLSPServer::onReference);
1264 MsgHandler->bind("textDocument/switchSourceHeader", &ClangdLSPServer::onSwitchSourceHeader);
Haojian Wuf429ab62019-07-24 07:49:23 +00001265 MsgHandler->bind("textDocument/prepareRename", &ClangdLSPServer::onPrepareRename);
Sam McCall2c30fbc2018-10-18 12:32:04 +00001266 MsgHandler->bind("textDocument/rename", &ClangdLSPServer::onRename);
1267 MsgHandler->bind("textDocument/hover", &ClangdLSPServer::onHover);
1268 MsgHandler->bind("textDocument/documentSymbol", &ClangdLSPServer::onDocumentSymbol);
1269 MsgHandler->bind("workspace/executeCommand", &ClangdLSPServer::onCommand);
1270 MsgHandler->bind("textDocument/documentHighlight", &ClangdLSPServer::onDocumentHighlight);
1271 MsgHandler->bind("workspace/symbol", &ClangdLSPServer::onWorkspaceSymbol);
1272 MsgHandler->bind("textDocument/didOpen", &ClangdLSPServer::onDocumentDidOpen);
1273 MsgHandler->bind("textDocument/didClose", &ClangdLSPServer::onDocumentDidClose);
1274 MsgHandler->bind("textDocument/didChange", &ClangdLSPServer::onDocumentDidChange);
1275 MsgHandler->bind("workspace/didChangeWatchedFiles", &ClangdLSPServer::onFileEvent);
1276 MsgHandler->bind("workspace/didChangeConfiguration", &ClangdLSPServer::onChangeConfiguration);
Jan Korousb4067012018-11-27 16:40:46 +00001277 MsgHandler->bind("textDocument/symbolInfo", &ClangdLSPServer::onSymbolInfo);
Kadir Cetinkaya86658022019-03-19 09:27:04 +00001278 MsgHandler->bind("textDocument/typeHierarchy", &ClangdLSPServer::onTypeHierarchy);
Nathan Ridge087b0442019-07-13 03:24:48 +00001279 MsgHandler->bind("typeHierarchy/resolve", &ClangdLSPServer::onResolveTypeHierarchy);
Utkarsh Saxena55925da2019-09-24 13:38:33 +00001280 MsgHandler->bind("textDocument/selectionRange", &ClangdLSPServer::onSelectionRange);
Sam McCall8d7ecc12019-12-16 19:08:51 +01001281 MsgHandler->bind("textDocument/documentLink", &ClangdLSPServer::onDocumentLink);
Sam McCall2c30fbc2018-10-18 12:32:04 +00001282 // clang-format on
1283}
1284
Sam McCall8bda5f22019-10-23 11:11:18 +02001285ClangdLSPServer::~ClangdLSPServer() { IsBeingDestroyed = true;
1286 // Explicitly destroy ClangdServer first, blocking on threads it owns.
1287 // This ensures they don't access any other members.
1288 Server.reset();
1289}
Ilya Biryukov38d79772017-05-16 09:38:59 +00001290
Sam McCalldc8f3cf2018-10-17 07:32:05 +00001291bool ClangdLSPServer::run() {
Ilya Biryukovafb55542017-05-16 14:40:30 +00001292 // Run the Language Server loop.
Sam McCalldc8f3cf2018-10-17 07:32:05 +00001293 bool CleanExit = true;
Sam McCall2c30fbc2018-10-18 12:32:04 +00001294 if (auto Err = Transp.loop(*MsgHandler)) {
Sam McCalldc8f3cf2018-10-17 07:32:05 +00001295 elog("Transport error: {0}", std::move(Err));
1296 CleanExit = false;
1297 }
Ilya Biryukovafb55542017-05-16 14:40:30 +00001298
Sam McCalldc8f3cf2018-10-17 07:32:05 +00001299 return CleanExit && ShutdownRequestReceived;
Ilya Biryukov38d79772017-05-16 09:38:59 +00001300}
1301
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001302std::vector<Fix> ClangdLSPServer::getFixes(llvm::StringRef File,
Ilya Biryukov71028b82018-03-12 15:28:22 +00001303 const clangd::Diagnostic &D) {
Ilya Biryukov38d79772017-05-16 09:38:59 +00001304 std::lock_guard<std::mutex> Lock(FixItsMutex);
1305 auto DiagToFixItsIter = FixItsMap.find(File);
1306 if (DiagToFixItsIter == FixItsMap.end())
1307 return {};
1308
1309 const auto &DiagToFixItsMap = DiagToFixItsIter->second;
1310 auto FixItsIter = DiagToFixItsMap.find(D);
1311 if (FixItsIter == DiagToFixItsMap.end())
1312 return {};
1313
1314 return FixItsIter->second;
1315}
1316
Ilya Biryukovb0826bd2019-01-03 13:37:12 +00001317bool ClangdLSPServer::shouldRunCompletion(
1318 const CompletionParams &Params) const {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001319 llvm::StringRef Trigger = Params.context.triggerCharacter;
Ilya Biryukovb0826bd2019-01-03 13:37:12 +00001320 if (Params.context.triggerKind != CompletionTriggerKind::TriggerCharacter ||
1321 (Trigger != ">" && Trigger != ":"))
1322 return true;
1323
1324 auto Code = DraftMgr.getDraft(Params.textDocument.uri.file());
1325 if (!Code)
1326 return true; // completion code will log the error for untracked doc.
1327
1328 // A completion request is sent when the user types '>' or ':', but we only
1329 // want to trigger on '->' and '::'. We check the preceeding character to make
1330 // sure it matches what we expected.
1331 // Running the lexer here would be more robust (e.g. we can detect comments
1332 // and avoid triggering completion there), but we choose to err on the side
1333 // of simplicity here.
1334 auto Offset = positionToOffset(*Code, Params.position,
1335 /*AllowColumnsBeyondLineLength=*/false);
1336 if (!Offset) {
1337 vlog("could not convert position '{0}' to offset for file '{1}'",
1338 Params.position, Params.textDocument.uri.file());
1339 return true;
1340 }
1341 if (*Offset < 2)
1342 return false;
1343
1344 if (Trigger == ">")
1345 return (*Code)[*Offset - 2] == '-'; // trigger only on '->'.
1346 if (Trigger == ":")
1347 return (*Code)[*Offset - 2] == ':'; // trigger only on '::'.
1348 assert(false && "unhandled trigger character");
1349 return true;
1350}
1351
Johan Vikstroma848dab2019-07-04 07:53:12 +00001352void ClangdLSPServer::onHighlightingsReady(
Haojian Wu0a6000f2019-08-26 08:38:45 +00001353 PathRef File, std::vector<HighlightingToken> Highlightings) {
Johan Vikstromc2653ef22019-08-01 08:08:44 +00001354 std::vector<HighlightingToken> Old;
1355 std::vector<HighlightingToken> HighlightingsCopy = Highlightings;
1356 {
1357 std::lock_guard<std::mutex> Lock(HighlightingsMutex);
1358 Old = std::move(FileToHighlightings[File]);
1359 FileToHighlightings[File] = std::move(HighlightingsCopy);
1360 }
1361 // LSP allows us to send incremental edits of highlightings. Also need to diff
1362 // to remove highlightings from tokens that should no longer have them.
Haojian Wu0a6000f2019-08-26 08:38:45 +00001363 std::vector<LineHighlightings> Diffed = diffHighlightings(Highlightings, Old);
Johan Vikstroma848dab2019-07-04 07:53:12 +00001364 publishSemanticHighlighting(
1365 {{URIForFile::canonicalize(File, /*TUPath=*/File)},
Johan Vikstromc2653ef22019-08-01 08:08:44 +00001366 toSemanticHighlightingInformation(Diffed)});
Johan Vikstroma848dab2019-07-04 07:53:12 +00001367}
1368
Sam McCalla7bb0cc2018-03-12 23:22:35 +00001369void ClangdLSPServer::onDiagnosticsReady(PathRef File,
1370 std::vector<Diag> Diagnostics) {
Eric Liu4d814a92018-11-28 10:30:42 +00001371 auto URI = URIForFile::canonicalize(File, /*TUPath=*/File);
Sam McCall16e70702018-10-24 07:59:38 +00001372 std::vector<Diagnostic> LSPDiagnostics;
Ilya Biryukov38d79772017-05-16 09:38:59 +00001373 DiagnosticToReplacementMap LocalFixIts; // Temporary storage
Sam McCalla7bb0cc2018-03-12 23:22:35 +00001374 for (auto &Diag : Diagnostics) {
Sam McCall16e70702018-10-24 07:59:38 +00001375 toLSPDiags(Diag, URI, DiagOpts,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001376 [&](clangd::Diagnostic Diag, llvm::ArrayRef<Fix> Fixes) {
Sam McCall16e70702018-10-24 07:59:38 +00001377 auto &FixItsForDiagnostic = LocalFixIts[Diag];
1378 llvm::copy(Fixes, std::back_inserter(FixItsForDiagnostic));
1379 LSPDiagnostics.push_back(std::move(Diag));
1380 });
Ilya Biryukov38d79772017-05-16 09:38:59 +00001381 }
1382
1383 // Cache FixIts
1384 {
Ilya Biryukov38d79772017-05-16 09:38:59 +00001385 std::lock_guard<std::mutex> Lock(FixItsMutex);
1386 FixItsMap[File] = LocalFixIts;
1387 }
1388
Ilya Biryukov49c10712019-03-25 10:15:11 +00001389 // Send a notification to the LSP client.
1390 publishDiagnostics(URI, std::move(LSPDiagnostics));
Ilya Biryukov38d79772017-05-16 09:38:59 +00001391}
Simon Marchi9569fd52018-03-16 14:30:42 +00001392
Sam McCall7d20e802020-01-22 19:41:45 +01001393void ClangdLSPServer::onBackgroundIndexProgress(
1394 const BackgroundQueue::Stats &Stats) {
1395 static const char ProgressToken[] = "backgroundIndexProgress";
1396 std::lock_guard<std::mutex> Lock(BackgroundIndexProgressMutex);
1397
1398 auto NotifyProgress = [this](const BackgroundQueue::Stats &Stats) {
1399 if (BackgroundIndexProgressState != BackgroundIndexProgress::Live) {
1400 WorkDoneProgressBegin Begin;
1401 Begin.percentage = true;
1402 Begin.title = "indexing";
1403 progress(ProgressToken, std::move(Begin));
1404 BackgroundIndexProgressState = BackgroundIndexProgress::Live;
1405 }
1406
1407 if (Stats.Completed < Stats.Enqueued) {
1408 assert(Stats.Enqueued > Stats.LastIdle);
1409 WorkDoneProgressReport Report;
1410 Report.percentage = 100.0 * (Stats.Completed - Stats.LastIdle) /
1411 (Stats.Enqueued - Stats.LastIdle);
1412 Report.message =
1413 llvm::formatv("{0}/{1}", Stats.Completed - Stats.LastIdle,
1414 Stats.Enqueued - Stats.LastIdle);
1415 progress(ProgressToken, std::move(Report));
1416 } else {
1417 assert(Stats.Completed == Stats.Enqueued);
1418 progress(ProgressToken, WorkDoneProgressEnd());
1419 BackgroundIndexProgressState = BackgroundIndexProgress::Empty;
1420 }
1421 };
1422
1423 switch (BackgroundIndexProgressState) {
1424 case BackgroundIndexProgress::Unsupported:
1425 return;
1426 case BackgroundIndexProgress::Creating:
1427 // Cache this update for when the progress bar is available.
1428 PendingBackgroundIndexProgress = Stats;
1429 return;
1430 case BackgroundIndexProgress::Empty: {
1431 if (BackgroundIndexSkipCreate) {
1432 NotifyProgress(Stats);
1433 break;
1434 }
1435 // Cache this update for when the progress bar is available.
1436 PendingBackgroundIndexProgress = Stats;
1437 BackgroundIndexProgressState = BackgroundIndexProgress::Creating;
1438 WorkDoneProgressCreateParams CreateRequest;
1439 CreateRequest.token = ProgressToken;
1440 call<std::nullptr_t>(
1441 "window/workDoneProgress/create", CreateRequest,
1442 [this, NotifyProgress](llvm::Expected<std::nullptr_t> E) {
1443 std::lock_guard<std::mutex> Lock(BackgroundIndexProgressMutex);
1444 if (E) {
1445 NotifyProgress(this->PendingBackgroundIndexProgress);
1446 } else {
1447 elog("Failed to create background index progress bar: {0}",
1448 E.takeError());
1449 // give up forever rather than thrashing about
1450 BackgroundIndexProgressState = BackgroundIndexProgress::Unsupported;
1451 }
1452 });
1453 break;
1454 }
1455 case BackgroundIndexProgress::Live:
1456 NotifyProgress(Stats);
1457 break;
1458 }
1459}
1460
Haojian Wub6188492018-12-20 15:39:12 +00001461void ClangdLSPServer::onFileUpdated(PathRef File, const TUStatus &Status) {
1462 if (!SupportFileStatus)
1463 return;
1464 // FIXME: we don't emit "BuildingFile" and `RunningAction`, as these
1465 // two statuses are running faster in practice, which leads the UI constantly
1466 // changing, and doesn't provide much value. We may want to emit status at a
1467 // reasonable time interval (e.g. 0.5s).
1468 if (Status.Action.S == TUAction::BuildingFile ||
1469 Status.Action.S == TUAction::RunningAction)
1470 return;
1471 notify("textDocument/clangd.fileStatus", Status.render(File));
1472}
1473
David Goldman60249c22020-01-13 17:01:10 -05001474void ClangdLSPServer::reparseOpenedFiles(
1475 const llvm::StringSet<> &ModifiedFiles) {
1476 if (ModifiedFiles.empty())
1477 return;
1478 // Reparse only opened files that were modified.
Simon Marchi9569fd52018-03-16 14:30:42 +00001479 for (const Path &FilePath : DraftMgr.getActiveFiles())
David Goldman60249c22020-01-13 17:01:10 -05001480 if (ModifiedFiles.find(FilePath) != ModifiedFiles.end())
1481 Server->addDocument(FilePath, *DraftMgr.getDraft(FilePath),
1482 WantDiagnostics::Auto);
Simon Marchi9569fd52018-03-16 14:30:42 +00001483}
Alex Lorenzf8087862018-08-01 17:39:29 +00001484
Sam McCallc008af62018-10-20 15:30:37 +00001485} // namespace clangd
1486} // namespace clang