blob: 55e63c71b23eb72deb5947ff0749e4a25c64dcd6 [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"
Ilya Biryukovcce67a32019-01-29 14:17:36 +000021#include "clang/Tooling/Core/Replacement.h"
Kadir Cetinkaya256247c2019-06-26 07:45:27 +000022#include "llvm/ADT/ArrayRef.h"
Sam McCalla69698f2019-03-27 17:47:49 +000023#include "llvm/ADT/Optional.h"
Kadir Cetinkaya689bf932018-08-24 13:09:41 +000024#include "llvm/ADT/ScopeExit.h"
Kadir Cetinkaya5b270932019-09-09 12:28:44 +000025#include "llvm/ADT/StringRef.h"
Utkarsh Saxena55925da2019-09-24 13:38:33 +000026#include "llvm/ADT/iterator_range.h"
Simon Marchi9569fd52018-03-16 14:30:42 +000027#include "llvm/Support/Errc.h"
Ilya Biryukovcce67a32019-01-29 14:17:36 +000028#include "llvm/Support/Error.h"
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +000029#include "llvm/Support/FormatVariadic.h"
Utkarsh Saxena55925da2019-09-24 13:38:33 +000030#include "llvm/Support/JSON.h"
Eric Liu5740ff52018-01-31 16:26:27 +000031#include "llvm/Support/Path.h"
Kadir Cetinkaya5b270932019-09-09 12:28:44 +000032#include "llvm/Support/SHA1.h"
Sam McCall2c30fbc2018-10-18 12:32:04 +000033#include "llvm/Support/ScopedPrinter.h"
Kadir Cetinkaya5b270932019-09-09 12:28:44 +000034#include <cstddef>
Utkarsh Saxena55925da2019-09-24 13:38:33 +000035#include <memory>
Sam McCall7d20e802020-01-22 19:41:45 +010036#include <mutex>
Kadir Cetinkaya5b270932019-09-09 12:28:44 +000037#include <string>
Utkarsh Saxena55925da2019-09-24 13:38:33 +000038#include <vector>
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +000039
Sam McCallc008af62018-10-20 15:30:37 +000040namespace clang {
41namespace clangd {
Ilya Biryukovafb55542017-05-16 14:40:30 +000042namespace {
Ilya Biryukovcce67a32019-01-29 14:17:36 +000043/// Transforms a tweak into a code action that would apply it if executed.
44/// EXPECTS: T.prepare() was called and returned true.
45CodeAction toCodeAction(const ClangdServer::TweakRef &T, const URIForFile &File,
46 Range Selection) {
47 CodeAction CA;
48 CA.title = T.Title;
Sam McCall395fde72019-06-18 13:37:54 +000049 switch (T.Intent) {
50 case Tweak::Refactor:
Benjamin Krameradcd0262020-01-28 20:23:46 +010051 CA.kind = std::string(CodeAction::REFACTOR_KIND);
Sam McCall395fde72019-06-18 13:37:54 +000052 break;
53 case Tweak::Info:
Benjamin Krameradcd0262020-01-28 20:23:46 +010054 CA.kind = std::string(CodeAction::INFO_KIND);
Sam McCall395fde72019-06-18 13:37:54 +000055 break;
56 }
Ilya Biryukovcce67a32019-01-29 14:17:36 +000057 // This tweak may have an expensive second stage, we only run it if the user
58 // actually chooses it in the UI. We reply with a command that would run the
59 // corresponding tweak.
60 // FIXME: for some tweaks, computing the edits is cheap and we could send them
61 // directly.
62 CA.command.emplace();
63 CA.command->title = T.Title;
Benjamin Krameradcd0262020-01-28 20:23:46 +010064 CA.command->command = std::string(Command::CLANGD_APPLY_TWEAK);
Ilya Biryukovcce67a32019-01-29 14:17:36 +000065 CA.command->tweakArgs.emplace();
66 CA.command->tweakArgs->file = File;
67 CA.command->tweakArgs->tweakID = T.ID;
68 CA.command->tweakArgs->selection = Selection;
69 return CA;
Simon Pilgrime9a136b2019-02-03 14:08:30 +000070}
Ilya Biryukovcce67a32019-01-29 14:17:36 +000071
Ilya Biryukov19d75602018-11-23 15:21:19 +000072void adjustSymbolKinds(llvm::MutableArrayRef<DocumentSymbol> Syms,
73 SymbolKindBitset Kinds) {
74 for (auto &S : Syms) {
75 S.kind = adjustKindToCapability(S.kind, Kinds);
76 adjustSymbolKinds(S.children, Kinds);
77 }
78}
79
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +000080SymbolKindBitset defaultSymbolKinds() {
81 SymbolKindBitset Defaults;
82 for (size_t I = SymbolKindMin; I <= static_cast<size_t>(SymbolKind::Array);
83 ++I)
84 Defaults.set(I);
85 return Defaults;
86}
87
Kadir Cetinkaya133d46f2018-09-27 17:13:07 +000088CompletionItemKindBitset defaultCompletionItemKinds() {
89 CompletionItemKindBitset Defaults;
90 for (size_t I = CompletionItemKindMin;
91 I <= static_cast<size_t>(CompletionItemKind::Reference); ++I)
92 Defaults.set(I);
93 return Defaults;
94}
95
Haojian Wu1ca2ee42019-07-04 12:27:21 +000096// Build a lookup table (HighlightingKind => {TextMate Scopes}), which is sent
97// to the LSP client.
98std::vector<std::vector<std::string>> buildHighlightScopeLookupTable() {
99 std::vector<std::vector<std::string>> LookupTable;
100 // HighlightingKind is using as the index.
Ilya Biryukov63d5d162019-09-09 08:57:17 +0000101 for (int KindValue = 0; KindValue <= (int)HighlightingKind::LastKind;
Haojian Wu1ca2ee42019-07-04 12:27:21 +0000102 ++KindValue)
Benjamin Krameradcd0262020-01-28 20:23:46 +0100103 LookupTable.push_back(
104 {std::string(toTextMateScope((HighlightingKind)(KindValue)))});
Haojian Wu1ca2ee42019-07-04 12:27:21 +0000105 return LookupTable;
106}
107
Haojian Wu852bafa2019-10-23 14:40:20 +0200108// Makes sure edits in \p FE are applicable to latest file contents reported by
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000109// editor. If not generates an error message containing information about files
110// that needs to be saved.
Haojian Wu852bafa2019-10-23 14:40:20 +0200111llvm::Error validateEdits(const DraftStore &DraftMgr, const FileEdits &FE) {
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000112 size_t InvalidFileCount = 0;
113 llvm::StringRef LastInvalidFile;
Haojian Wu852bafa2019-10-23 14:40:20 +0200114 for (const auto &It : FE) {
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000115 if (auto Draft = DraftMgr.getDraft(It.first())) {
116 // If the file is open in user's editor, make sure the version we
117 // saw and current version are compatible as this is the text that
118 // will be replaced by editors.
119 if (!It.second.canApplyTo(*Draft)) {
120 ++InvalidFileCount;
121 LastInvalidFile = It.first();
122 }
123 }
124 }
125 if (!InvalidFileCount)
126 return llvm::Error::success();
127 if (InvalidFileCount == 1)
128 return llvm::createStringError(llvm::inconvertibleErrorCode(),
129 "File must be saved first: " +
130 LastInvalidFile);
131 return llvm::createStringError(
132 llvm::inconvertibleErrorCode(),
133 "Files must be saved first: " + LastInvalidFile + " (and " +
134 llvm::to_string(InvalidFileCount - 1) + " others)");
135}
136
Utkarsh Saxena55925da2019-09-24 13:38:33 +0000137// Converts a list of Ranges to a LinkedList of SelectionRange.
138SelectionRange render(const std::vector<Range> &Ranges) {
139 if (Ranges.empty())
140 return {};
141 SelectionRange Result;
142 Result.range = Ranges[0];
143 auto *Next = &Result.parent;
144 for (const auto &R : llvm::make_range(Ranges.begin() + 1, Ranges.end())) {
145 *Next = std::make_unique<SelectionRange>();
146 Next->get()->range = R;
147 Next = &Next->get()->parent;
148 }
149 return Result;
150}
151
Ilya Biryukovafb55542017-05-16 14:40:30 +0000152} // namespace
153
Sam McCall2c30fbc2018-10-18 12:32:04 +0000154// MessageHandler dispatches incoming LSP messages.
155// It handles cross-cutting concerns:
156// - serializes/deserializes protocol objects to JSON
157// - logging of inbound messages
158// - cancellation handling
159// - basic call tracing
Sam McCall3d0adbe2018-10-18 14:41:50 +0000160// MessageHandler ensures that initialize() is called before any other handler.
Sam McCall2c30fbc2018-10-18 12:32:04 +0000161class ClangdLSPServer::MessageHandler : public Transport::MessageHandler {
162public:
163 MessageHandler(ClangdLSPServer &Server) : Server(Server) {}
164
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000165 bool onNotify(llvm::StringRef Method, llvm::json::Value Params) override {
Sam McCalla69698f2019-03-27 17:47:49 +0000166 WithContext HandlerContext(handlerContext());
Sam McCall2c30fbc2018-10-18 12:32:04 +0000167 log("<-- {0}", Method);
168 if (Method == "exit")
169 return false;
Sam McCall3d0adbe2018-10-18 14:41:50 +0000170 if (!Server.Server)
171 elog("Notification {0} before initialization", Method);
172 else if (Method == "$/cancelRequest")
Sam McCall2c30fbc2018-10-18 12:32:04 +0000173 onCancel(std::move(Params));
174 else if (auto Handler = Notifications.lookup(Method))
175 Handler(std::move(Params));
176 else
177 log("unhandled notification {0}", Method);
178 return true;
179 }
180
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000181 bool onCall(llvm::StringRef Method, llvm::json::Value Params,
182 llvm::json::Value ID) override {
Sam McCalla69698f2019-03-27 17:47:49 +0000183 WithContext HandlerContext(handlerContext());
Sam McCalle2f3a732018-10-24 14:26:26 +0000184 // Calls can be canceled by the client. Add cancellation context.
185 WithContext WithCancel(cancelableRequestContext(ID));
186 trace::Span Tracer(Method);
187 SPAN_ATTACH(Tracer, "Params", Params);
188 ReplyOnce Reply(ID, Method, &Server, Tracer.Args);
Sam McCall2c30fbc2018-10-18 12:32:04 +0000189 log("<-- {0}({1})", Method, ID);
Sam McCall3d0adbe2018-10-18 14:41:50 +0000190 if (!Server.Server && Method != "initialize") {
191 elog("Call {0} before initialization.", Method);
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000192 Reply(llvm::make_error<LSPError>("server not initialized",
193 ErrorCode::ServerNotInitialized));
Sam McCall3d0adbe2018-10-18 14:41:50 +0000194 } else if (auto Handler = Calls.lookup(Method))
Sam McCalle2f3a732018-10-24 14:26:26 +0000195 Handler(std::move(Params), std::move(Reply));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000196 else
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000197 Reply(llvm::make_error<LSPError>("method not found",
198 ErrorCode::MethodNotFound));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000199 return true;
200 }
201
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000202 bool onReply(llvm::json::Value ID,
203 llvm::Expected<llvm::json::Value> Result) override {
Sam McCalla69698f2019-03-27 17:47:49 +0000204 WithContext HandlerContext(handlerContext());
Haojian Wuf2516342019-08-05 12:48:09 +0000205
206 Callback<llvm::json::Value> ReplyHandler = nullptr;
207 if (auto IntID = ID.getAsInteger()) {
208 std::lock_guard<std::mutex> Mutex(CallMutex);
209 // Find a corresponding callback for the request ID;
210 for (size_t Index = 0; Index < ReplyCallbacks.size(); ++Index) {
211 if (ReplyCallbacks[Index].first == *IntID) {
212 ReplyHandler = std::move(ReplyCallbacks[Index].second);
213 ReplyCallbacks.erase(ReplyCallbacks.begin() +
214 Index); // remove the entry
215 break;
216 }
217 }
218 }
219
220 if (!ReplyHandler) {
221 // No callback being found, use a default log callback.
222 ReplyHandler = [&ID](llvm::Expected<llvm::json::Value> Result) {
223 elog("received a reply with ID {0}, but there was no such call", ID);
224 if (!Result)
225 llvm::consumeError(Result.takeError());
226 };
227 }
228
229 // Log and run the reply handler.
230 if (Result) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000231 log("<-- reply({0})", ID);
Haojian Wuf2516342019-08-05 12:48:09 +0000232 ReplyHandler(std::move(Result));
233 } else {
234 auto Err = Result.takeError();
235 log("<-- reply({0}) error: {1}", ID, Err);
236 ReplyHandler(std::move(Err));
237 }
Sam McCall2c30fbc2018-10-18 12:32:04 +0000238 return true;
239 }
240
241 // Bind an LSP method name to a call.
Sam McCalle2f3a732018-10-24 14:26:26 +0000242 template <typename Param, typename Result>
Sam McCall2c30fbc2018-10-18 12:32:04 +0000243 void bind(const char *Method,
Sam McCalle2f3a732018-10-24 14:26:26 +0000244 void (ClangdLSPServer::*Handler)(const Param &, Callback<Result>)) {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000245 Calls[Method] = [Method, Handler, this](llvm::json::Value RawParams,
Sam McCalle2f3a732018-10-24 14:26:26 +0000246 ReplyOnce Reply) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000247 Param P;
Sam McCalle2f3a732018-10-24 14:26:26 +0000248 if (fromJSON(RawParams, P)) {
249 (Server.*Handler)(P, std::move(Reply));
250 } else {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000251 elog("Failed to decode {0} request.", Method);
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000252 Reply(llvm::make_error<LSPError>("failed to decode request",
253 ErrorCode::InvalidRequest));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000254 }
Sam McCall2c30fbc2018-10-18 12:32:04 +0000255 };
256 }
257
Haojian Wuf2516342019-08-05 12:48:09 +0000258 // Bind a reply callback to a request. The callback will be invoked when
259 // clangd receives the reply from the LSP client.
260 // Return a call id of the request.
261 llvm::json::Value bindReply(Callback<llvm::json::Value> Reply) {
262 llvm::Optional<std::pair<int, Callback<llvm::json::Value>>> OldestCB;
263 int ID;
264 {
265 std::lock_guard<std::mutex> Mutex(CallMutex);
266 ID = NextCallID++;
267 ReplyCallbacks.emplace_back(ID, std::move(Reply));
268
269 // If the queue overflows, we assume that the client didn't reply the
270 // oldest request, and run the corresponding callback which replies an
271 // error to the client.
272 if (ReplyCallbacks.size() > MaxReplayCallbacks) {
273 elog("more than {0} outstanding LSP calls, forgetting about {1}",
274 MaxReplayCallbacks, ReplyCallbacks.front().first);
275 OldestCB = std::move(ReplyCallbacks.front());
276 ReplyCallbacks.pop_front();
277 }
278 }
279 if (OldestCB)
280 OldestCB->second(llvm::createStringError(
281 llvm::inconvertibleErrorCode(),
282 llvm::formatv("failed to receive a client reply for request ({0})",
283 OldestCB->first)));
284 return ID;
285 }
286
Sam McCall2c30fbc2018-10-18 12:32:04 +0000287 // Bind an LSP method name to a notification.
288 template <typename Param>
289 void bind(const char *Method,
290 void (ClangdLSPServer::*Handler)(const Param &)) {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000291 Notifications[Method] = [Method, Handler,
292 this](llvm::json::Value RawParams) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000293 Param P;
294 if (!fromJSON(RawParams, P)) {
295 elog("Failed to decode {0} request.", Method);
296 return;
297 }
298 trace::Span Tracer(Method);
299 SPAN_ATTACH(Tracer, "Params", RawParams);
300 (Server.*Handler)(P);
301 };
302 }
303
304private:
Sam McCalle2f3a732018-10-24 14:26:26 +0000305 // Function object to reply to an LSP call.
306 // Each instance must be called exactly once, otherwise:
307 // - the bug is logged, and (in debug mode) an assert will fire
308 // - if there was no reply, an error reply is sent
309 // - if there were multiple replies, only the first is sent
310 class ReplyOnce {
311 std::atomic<bool> Replied = {false};
Sam McCalld7babe42018-10-24 15:18:40 +0000312 std::chrono::steady_clock::time_point Start;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000313 llvm::json::Value ID;
Sam McCalle2f3a732018-10-24 14:26:26 +0000314 std::string Method;
315 ClangdLSPServer *Server; // Null when moved-from.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000316 llvm::json::Object *TraceArgs;
Sam McCalle2f3a732018-10-24 14:26:26 +0000317
318 public:
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000319 ReplyOnce(const llvm::json::Value &ID, llvm::StringRef Method,
320 ClangdLSPServer *Server, llvm::json::Object *TraceArgs)
Sam McCalld7babe42018-10-24 15:18:40 +0000321 : Start(std::chrono::steady_clock::now()), ID(ID), Method(Method),
322 Server(Server), TraceArgs(TraceArgs) {
Sam McCalle2f3a732018-10-24 14:26:26 +0000323 assert(Server);
324 }
325 ReplyOnce(ReplyOnce &&Other)
Sam McCalld7babe42018-10-24 15:18:40 +0000326 : Replied(Other.Replied.load()), Start(Other.Start),
327 ID(std::move(Other.ID)), Method(std::move(Other.Method)),
328 Server(Other.Server), TraceArgs(Other.TraceArgs) {
Sam McCalle2f3a732018-10-24 14:26:26 +0000329 Other.Server = nullptr;
330 }
Ilya Biryukov22fa4652019-01-03 13:28:05 +0000331 ReplyOnce &operator=(ReplyOnce &&) = delete;
Sam McCalle2f3a732018-10-24 14:26:26 +0000332 ReplyOnce(const ReplyOnce &) = delete;
Ilya Biryukov22fa4652019-01-03 13:28:05 +0000333 ReplyOnce &operator=(const ReplyOnce &) = delete;
Sam McCalle2f3a732018-10-24 14:26:26 +0000334
335 ~ReplyOnce() {
Haojian Wuf2516342019-08-05 12:48:09 +0000336 // There's one legitimate reason to never reply to a request: clangd's
337 // request handler send a call to the client (e.g. applyEdit) and the
338 // client never replied. In this case, the ReplyOnce is owned by
339 // ClangdLSPServer's reply callback table and is destroyed along with the
340 // server. We don't attempt to send a reply in this case, there's little
341 // to be gained from doing so.
342 if (Server && !Server->IsBeingDestroyed && !Replied) {
Sam McCalle2f3a732018-10-24 14:26:26 +0000343 elog("No reply to message {0}({1})", Method, ID);
344 assert(false && "must reply to all calls!");
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000345 (*this)(llvm::make_error<LSPError>("server failed to reply",
346 ErrorCode::InternalError));
Sam McCalle2f3a732018-10-24 14:26:26 +0000347 }
348 }
349
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000350 void operator()(llvm::Expected<llvm::json::Value> Reply) {
Sam McCalle2f3a732018-10-24 14:26:26 +0000351 assert(Server && "moved-from!");
352 if (Replied.exchange(true)) {
353 elog("Replied twice to message {0}({1})", Method, ID);
354 assert(false && "must reply to each call only once!");
355 return;
356 }
Sam McCalld7babe42018-10-24 15:18:40 +0000357 auto Duration = std::chrono::steady_clock::now() - Start;
358 if (Reply) {
359 log("--> reply:{0}({1}) {2:ms}", Method, ID, Duration);
360 if (TraceArgs)
Sam McCalle2f3a732018-10-24 14:26:26 +0000361 (*TraceArgs)["Reply"] = *Reply;
Sam McCalld7babe42018-10-24 15:18:40 +0000362 std::lock_guard<std::mutex> Lock(Server->TranspWriter);
363 Server->Transp.reply(std::move(ID), std::move(Reply));
364 } else {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000365 llvm::Error Err = Reply.takeError();
Sam McCalld7babe42018-10-24 15:18:40 +0000366 log("--> reply:{0}({1}) {2:ms}, error: {3}", Method, ID, Duration, Err);
367 if (TraceArgs)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000368 (*TraceArgs)["Error"] = llvm::to_string(Err);
Sam McCalld7babe42018-10-24 15:18:40 +0000369 std::lock_guard<std::mutex> Lock(Server->TranspWriter);
370 Server->Transp.reply(std::move(ID), std::move(Err));
Sam McCalle2f3a732018-10-24 14:26:26 +0000371 }
Sam McCalle2f3a732018-10-24 14:26:26 +0000372 }
373 };
374
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000375 llvm::StringMap<std::function<void(llvm::json::Value)>> Notifications;
376 llvm::StringMap<std::function<void(llvm::json::Value, ReplyOnce)>> Calls;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000377
378 // Method calls may be cancelled by ID, so keep track of their state.
379 // This needs a mutex: handlers may finish on a different thread, and that's
380 // when we clean up entries in the map.
381 mutable std::mutex RequestCancelersMutex;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000382 llvm::StringMap<std::pair<Canceler, /*Cookie*/ unsigned>> RequestCancelers;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000383 unsigned NextRequestCookie = 0; // To disambiguate reused IDs, see below.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000384 void onCancel(const llvm::json::Value &Params) {
385 const llvm::json::Value *ID = nullptr;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000386 if (auto *O = Params.getAsObject())
387 ID = O->get("id");
388 if (!ID) {
389 elog("Bad cancellation request: {0}", Params);
390 return;
391 }
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000392 auto StrID = llvm::to_string(*ID);
Sam McCall2c30fbc2018-10-18 12:32:04 +0000393 std::lock_guard<std::mutex> Lock(RequestCancelersMutex);
394 auto It = RequestCancelers.find(StrID);
395 if (It != RequestCancelers.end())
396 It->second.first(); // Invoke the canceler.
397 }
Sam McCalla69698f2019-03-27 17:47:49 +0000398
399 Context handlerContext() const {
400 return Context::current().derive(
401 kCurrentOffsetEncoding,
402 Server.NegotiatedOffsetEncoding.getValueOr(OffsetEncoding::UTF16));
403 }
404
Sam McCall2c30fbc2018-10-18 12:32:04 +0000405 // We run cancelable requests in a context that does two things:
406 // - allows cancellation using RequestCancelers[ID]
407 // - cleans up the entry in RequestCancelers when it's no longer needed
408 // If a client reuses an ID, the last wins and the first cannot be canceled.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000409 Context cancelableRequestContext(const llvm::json::Value &ID) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000410 auto Task = cancelableTask();
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000411 auto StrID = llvm::to_string(ID); // JSON-serialize ID for map key.
Sam McCall2c30fbc2018-10-18 12:32:04 +0000412 auto Cookie = NextRequestCookie++; // No lock, only called on main thread.
413 {
414 std::lock_guard<std::mutex> Lock(RequestCancelersMutex);
415 RequestCancelers[StrID] = {std::move(Task.second), Cookie};
416 }
417 // When the request ends, we can clean up the entry we just added.
418 // The cookie lets us check that it hasn't been overwritten due to ID
419 // reuse.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000420 return Task.first.derive(llvm::make_scope_exit([this, StrID, Cookie] {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000421 std::lock_guard<std::mutex> Lock(RequestCancelersMutex);
422 auto It = RequestCancelers.find(StrID);
423 if (It != RequestCancelers.end() && It->second.second == Cookie)
424 RequestCancelers.erase(It);
425 }));
426 }
427
Kadir Cetinkaya9a3a87d2019-10-09 13:59:31 +0000428 // The maximum number of callbacks held in clangd.
429 //
430 // We bound the maximum size to the pending map to prevent memory leakage
431 // for cases where LSP clients don't reply for the request.
432 // This has to go after RequestCancellers and RequestCancellersMutex since it
433 // can contain a callback that has a cancelable context.
434 static constexpr int MaxReplayCallbacks = 100;
435 mutable std::mutex CallMutex;
436 int NextCallID = 0; /* GUARDED_BY(CallMutex) */
437 std::deque<std::pair</*RequestID*/ int,
438 /*ReplyHandler*/ Callback<llvm::json::Value>>>
439 ReplyCallbacks; /* GUARDED_BY(CallMutex) */
440
Sam McCall2c30fbc2018-10-18 12:32:04 +0000441 ClangdLSPServer &Server;
442};
Haojian Wuf2516342019-08-05 12:48:09 +0000443constexpr int ClangdLSPServer::MessageHandler::MaxReplayCallbacks;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000444
445// call(), notify(), and reply() wrap the Transport, adding logging and locking.
Haojian Wuf2516342019-08-05 12:48:09 +0000446void ClangdLSPServer::callRaw(StringRef Method, llvm::json::Value Params,
447 Callback<llvm::json::Value> CB) {
448 auto ID = MsgHandler->bindReply(std::move(CB));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000449 log("--> {0}({1})", Method, ID);
Sam McCall2c30fbc2018-10-18 12:32:04 +0000450 std::lock_guard<std::mutex> Lock(TranspWriter);
451 Transp.call(Method, std::move(Params), ID);
452}
453
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000454void ClangdLSPServer::notify(llvm::StringRef Method, llvm::json::Value Params) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000455 log("--> {0}", Method);
456 std::lock_guard<std::mutex> Lock(TranspWriter);
457 Transp.notify(Method, std::move(Params));
458}
459
Sam McCall2c30fbc2018-10-18 12:32:04 +0000460void ClangdLSPServer::onInitialize(const InitializeParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000461 Callback<llvm::json::Value> Reply) {
Sam McCalla69698f2019-03-27 17:47:49 +0000462 // Determine character encoding first as it affects constructed ClangdServer.
463 if (Params.capabilities.offsetEncoding && !NegotiatedOffsetEncoding) {
464 NegotiatedOffsetEncoding = OffsetEncoding::UTF16; // fallback
465 for (OffsetEncoding Supported : *Params.capabilities.offsetEncoding)
466 if (Supported != OffsetEncoding::UnsupportedEncoding) {
467 NegotiatedOffsetEncoding = Supported;
468 break;
469 }
470 }
Sam McCalla69698f2019-03-27 17:47:49 +0000471
Johan Vikstroma848dab2019-07-04 07:53:12 +0000472 ClangdServerOpts.SemanticHighlighting =
473 Params.capabilities.SemanticHighlighting;
Sam McCall0d9b40f2018-10-19 15:42:23 +0000474 if (Params.rootUri && *Params.rootUri)
Benjamin Krameradcd0262020-01-28 20:23:46 +0100475 ClangdServerOpts.WorkspaceRoot = std::string(Params.rootUri->file());
Sam McCall0d9b40f2018-10-19 15:42:23 +0000476 else if (Params.rootPath && !Params.rootPath->empty())
477 ClangdServerOpts.WorkspaceRoot = *Params.rootPath;
Sam McCall3d0adbe2018-10-18 14:41:50 +0000478 if (Server)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000479 return Reply(llvm::make_error<LSPError>("server already initialized",
480 ErrorCode::InvalidRequest));
Sam McCallbc904612018-10-25 04:22:52 +0000481 if (const auto &Dir = Params.initializationOptions.compilationDatabasePath)
482 CompileCommandsDir = Dir;
Kadir Cetinkaya256247c2019-06-26 07:45:27 +0000483 if (UseDirBasedCDB) {
Jonas Devlieghere1c705d92019-08-14 23:52:23 +0000484 BaseCDB = std::make_unique<DirectoryBasedGlobalCompilationDatabase>(
Sam McCallc55d09a2018-11-02 13:09:36 +0000485 CompileCommandsDir);
Kadir Cetinkaya256247c2019-06-26 07:45:27 +0000486 BaseCDB = getQueryDriverDatabase(
487 llvm::makeArrayRef(ClangdServerOpts.QueryDriverGlobs),
488 std::move(BaseCDB));
489 }
Sam McCall99768b22019-11-29 19:37:48 +0100490 auto Mangler = CommandMangler::detect();
491 if (ClangdServerOpts.ResourceDir)
492 Mangler.ResourceDir = *ClangdServerOpts.ResourceDir;
Kadir Cetinkayabe6b35d2019-01-22 09:10:20 +0000493 CDB.emplace(BaseCDB.get(), Params.initializationOptions.fallbackFlags,
Sam McCall99768b22019-11-29 19:37:48 +0100494 tooling::ArgumentsAdjuster(Mangler));
Kadir Cetinkaya9d662472019-10-15 14:20:52 +0000495 {
496 // Switch caller's context with LSPServer's background context. Since we
497 // rather want to propagate information from LSPServer's context into the
498 // Server, CDB, etc.
499 WithContext MainContext(BackgroundContext.clone());
500 llvm::Optional<WithContextValue> WithOffsetEncoding;
501 if (NegotiatedOffsetEncoding)
502 WithOffsetEncoding.emplace(kCurrentOffsetEncoding,
503 *NegotiatedOffsetEncoding);
Sam McCall6ef1cce2020-01-24 14:08:56 +0100504 Server.emplace(*CDB, FSProvider, ClangdServerOpts,
505 static_cast<ClangdServer::Callbacks *>(this));
Kadir Cetinkaya9d662472019-10-15 14:20:52 +0000506 }
Sam McCallbc904612018-10-25 04:22:52 +0000507 applyConfiguration(Params.initializationOptions.ConfigSettings);
Simon Marchi88016782018-08-01 11:28:49 +0000508
Sam McCallbf6a2fc2018-10-17 07:33:42 +0000509 CCOpts.EnableSnippets = Params.capabilities.CompletionSnippets;
Sam McCall8d412942019-06-18 11:57:26 +0000510 CCOpts.IncludeFixIts = Params.capabilities.CompletionFixes;
Sam McCall5f092e32019-07-08 17:27:15 +0000511 if (!CCOpts.BundleOverloads.hasValue())
512 CCOpts.BundleOverloads = Params.capabilities.HasSignatureHelp;
Sam McCallbf6a2fc2018-10-17 07:33:42 +0000513 DiagOpts.EmbedFixesInDiagnostics = Params.capabilities.DiagnosticFixes;
514 DiagOpts.SendDiagnosticCategory = Params.capabilities.DiagnosticCategory;
Sam McCallc9e4ee92019-04-18 15:17:07 +0000515 DiagOpts.EmitRelatedLocations =
516 Params.capabilities.DiagnosticRelatedInformation;
Sam McCallbf6a2fc2018-10-17 07:33:42 +0000517 if (Params.capabilities.WorkspaceSymbolKinds)
518 SupportedSymbolKinds |= *Params.capabilities.WorkspaceSymbolKinds;
519 if (Params.capabilities.CompletionItemKinds)
520 SupportedCompletionItemKinds |= *Params.capabilities.CompletionItemKinds;
521 SupportsCodeAction = Params.capabilities.CodeActionStructure;
Ilya Biryukov19d75602018-11-23 15:21:19 +0000522 SupportsHierarchicalDocumentSymbol =
523 Params.capabilities.HierarchicalDocumentSymbol;
Haojian Wub6188492018-12-20 15:39:12 +0000524 SupportFileStatus = Params.initializationOptions.FileStatus;
Ilya Biryukovf9169d02019-05-29 10:01:00 +0000525 HoverContentFormat = Params.capabilities.HoverContentFormat;
Ilya Biryukov4ef0f822019-06-04 09:36:59 +0000526 SupportsOffsetsInSignatureHelp = Params.capabilities.OffsetsInSignatureHelp;
Sam McCall7d20e802020-01-22 19:41:45 +0100527 if (Params.capabilities.WorkDoneProgress)
528 BackgroundIndexProgressState = BackgroundIndexProgress::Empty;
529 BackgroundIndexSkipCreate = Params.capabilities.ImplicitProgressCreation;
Haojian Wuf429ab62019-07-24 07:49:23 +0000530
531 // Per LSP, renameProvider can be either boolean or RenameOptions.
532 // RenameOptions will be specified if the client states it supports prepare.
533 llvm::json::Value RenameProvider =
534 llvm::json::Object{{"prepareProvider", true}};
535 if (!Params.capabilities.RenamePrepareSupport) // Only boolean allowed per LSP
536 RenameProvider = true;
537
Haojian Wu08d93f12019-08-22 14:53:45 +0000538 // Per LSP, codeActionProvide can be either boolean or CodeActionOptions.
539 // CodeActionOptions is only valid if the client supports action literal
540 // via textDocument.codeAction.codeActionLiteralSupport.
541 llvm::json::Value CodeActionProvider = true;
542 if (Params.capabilities.CodeActionStructure)
543 CodeActionProvider = llvm::json::Object{
544 {"codeActionKinds",
545 {CodeAction::QUICKFIX_KIND, CodeAction::REFACTOR_KIND,
546 CodeAction::INFO_KIND}}};
547
Sam McCalla69698f2019-03-27 17:47:49 +0000548 llvm::json::Object Result{
Sam McCall0930ab02017-11-07 15:49:35 +0000549 {{"capabilities",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000550 llvm::json::Object{
Simon Marchi98082622018-03-26 14:41:40 +0000551 {"textDocumentSync", (int)TextDocumentSyncKind::Incremental},
Sam McCall0930ab02017-11-07 15:49:35 +0000552 {"documentFormattingProvider", true},
553 {"documentRangeFormattingProvider", true},
554 {"documentOnTypeFormattingProvider",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000555 llvm::json::Object{
Sam McCall25c62572019-06-10 14:26:21 +0000556 {"firstTriggerCharacter", "\n"},
Sam McCall0930ab02017-11-07 15:49:35 +0000557 {"moreTriggerCharacter", {}},
558 }},
Haojian Wu08d93f12019-08-22 14:53:45 +0000559 {"codeActionProvider", std::move(CodeActionProvider)},
Sam McCall0930ab02017-11-07 15:49:35 +0000560 {"completionProvider",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000561 llvm::json::Object{
Kirill Bobyrev2a095ff2020-02-18 17:55:12 +0100562 {"allCommitCharacters", " \t()[]{}<>:;,+-/*%^&#?.=\"'|"},
Sam McCall0930ab02017-11-07 15:49:35 +0000563 {"resolveProvider", false},
Ilya Biryukovb0826bd2019-01-03 13:37:12 +0000564 // We do extra checks for '>' and ':' in completion to only
565 // trigger on '->' and '::'.
Sam McCall0930ab02017-11-07 15:49:35 +0000566 {"triggerCharacters", {".", ">", ":"}},
567 }},
568 {"signatureHelpProvider",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000569 llvm::json::Object{
Sam McCall0930ab02017-11-07 15:49:35 +0000570 {"triggerCharacters", {"(", ","}},
571 }},
Sam McCall866ba2c2019-02-01 11:26:13 +0000572 {"declarationProvider", true},
Sam McCall0930ab02017-11-07 15:49:35 +0000573 {"definitionProvider", true},
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000574 {"documentHighlightProvider", true},
Sam McCall8d7ecc12019-12-16 19:08:51 +0100575 {"documentLinkProvider",
576 llvm::json::Object{
577 {"resolveProvider", false},
578 }},
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000579 {"hoverProvider", true},
Haojian Wuf429ab62019-07-24 07:49:23 +0000580 {"renameProvider", std::move(RenameProvider)},
Utkarsh Saxena55925da2019-09-24 13:38:33 +0000581 {"selectionRangeProvider", true},
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000582 {"documentSymbolProvider", true},
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000583 {"workspaceSymbolProvider", true},
Sam McCall1ad142f2018-09-05 11:53:07 +0000584 {"referencesProvider", true},
Sam McCall0930ab02017-11-07 15:49:35 +0000585 {"executeCommandProvider",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000586 llvm::json::Object{
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000587 {"commands",
588 {ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND,
589 ExecuteCommandParams::CLANGD_APPLY_TWEAK}},
Sam McCall0930ab02017-11-07 15:49:35 +0000590 }},
Kadir Cetinkaya86658022019-03-19 09:27:04 +0000591 {"typeHierarchyProvider", true},
Sam McCalla69698f2019-03-27 17:47:49 +0000592 }}}};
593 if (NegotiatedOffsetEncoding)
594 Result["offsetEncoding"] = *NegotiatedOffsetEncoding;
Johan Vikstroma848dab2019-07-04 07:53:12 +0000595 if (Params.capabilities.SemanticHighlighting)
596 Result.getObject("capabilities")
597 ->insert(
598 {"semanticHighlighting",
Haojian Wu1ca2ee42019-07-04 12:27:21 +0000599 llvm::json::Object{{"scopes", buildHighlightScopeLookupTable()}}});
Sam McCalla69698f2019-03-27 17:47:49 +0000600 Reply(std::move(Result));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000601}
602
Sam McCall2c30fbc2018-10-18 12:32:04 +0000603void ClangdLSPServer::onShutdown(const ShutdownParams &Params,
604 Callback<std::nullptr_t> Reply) {
Ilya Biryukov0d9b8a32017-10-25 08:45:41 +0000605 // Do essentially nothing, just say we're ready to exit.
606 ShutdownRequestReceived = true;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000607 Reply(nullptr);
Sam McCall8a5dded2017-10-12 13:29:58 +0000608}
Ilya Biryukovafb55542017-05-16 14:40:30 +0000609
Sam McCall422c8282018-11-26 16:00:11 +0000610// sync is a clangd extension: it blocks until all background work completes.
611// It blocks the calling thread, so no messages are processed until it returns!
612void ClangdLSPServer::onSync(const NoParams &Params,
613 Callback<std::nullptr_t> Reply) {
614 if (Server->blockUntilIdleForTest(/*TimeoutSeconds=*/60))
615 Reply(nullptr);
616 else
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000617 Reply(llvm::createStringError(llvm::inconvertibleErrorCode(),
618 "Not idle after a minute"));
Sam McCall422c8282018-11-26 16:00:11 +0000619}
620
Sam McCall2c30fbc2018-10-18 12:32:04 +0000621void ClangdLSPServer::onDocumentDidOpen(
622 const DidOpenTextDocumentParams &Params) {
Simon Marchi9569fd52018-03-16 14:30:42 +0000623 PathRef File = Params.textDocument.uri.file();
Ilya Biryukovb10ef472018-06-13 09:20:41 +0000624
Sam McCall2c30fbc2018-10-18 12:32:04 +0000625 const std::string &Contents = Params.textDocument.text;
Simon Marchi9569fd52018-03-16 14:30:42 +0000626
Simon Marchi98082622018-03-26 14:41:40 +0000627 DraftMgr.addDraft(File, Contents);
Ilya Biryukov652364b2018-09-26 05:48:29 +0000628 Server->addDocument(File, Contents, WantDiagnostics::Yes);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000629}
630
Sam McCall2c30fbc2018-10-18 12:32:04 +0000631void ClangdLSPServer::onDocumentDidChange(
632 const DidChangeTextDocumentParams &Params) {
Eric Liu51fed182018-02-22 18:40:39 +0000633 auto WantDiags = WantDiagnostics::Auto;
634 if (Params.wantDiagnostics.hasValue())
635 WantDiags = Params.wantDiagnostics.getValue() ? WantDiagnostics::Yes
636 : WantDiagnostics::No;
Simon Marchi9569fd52018-03-16 14:30:42 +0000637
638 PathRef File = Params.textDocument.uri.file();
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000639 llvm::Expected<std::string> Contents =
Simon Marchi98082622018-03-26 14:41:40 +0000640 DraftMgr.updateDraft(File, Params.contentChanges);
641 if (!Contents) {
642 // If this fails, we are most likely going to be not in sync anymore with
643 // the client. It is better to remove the draft and let further operations
644 // fail rather than giving wrong results.
645 DraftMgr.removeDraft(File);
Ilya Biryukov652364b2018-09-26 05:48:29 +0000646 Server->removeDocument(File);
Sam McCallbed58852018-07-11 10:35:11 +0000647 elog("Failed to update {0}: {1}", File, Contents.takeError());
Simon Marchi98082622018-03-26 14:41:40 +0000648 return;
649 }
Simon Marchi9569fd52018-03-16 14:30:42 +0000650
David Goldman6ff02282020-02-03 15:14:49 -0500651 Server->addDocument(File, *Contents, WantDiags, Params.forceRebuild);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000652}
653
Sam McCall2c30fbc2018-10-18 12:32:04 +0000654void ClangdLSPServer::onFileEvent(const DidChangeWatchedFilesParams &Params) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000655 Server->onFileEvent(Params);
Marc-Andre Laperlebf114242017-10-02 18:00:37 +0000656}
657
Sam McCall2c30fbc2018-10-18 12:32:04 +0000658void ClangdLSPServer::onCommand(const ExecuteCommandParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000659 Callback<llvm::json::Value> Reply) {
Ilya Biryukov12864002019-08-16 12:46:41 +0000660 auto ApplyEdit = [this](WorkspaceEdit WE, std::string SuccessMessage,
661 decltype(Reply) Reply) {
Eric Liuc5105f92018-02-16 14:15:55 +0000662 ApplyWorkspaceEditParams Edit;
663 Edit.edit = std::move(WE);
Ilya Biryukov12864002019-08-16 12:46:41 +0000664 call<ApplyWorkspaceEditResponse>(
665 "workspace/applyEdit", std::move(Edit),
666 [Reply = std::move(Reply), SuccessMessage = std::move(SuccessMessage)](
667 llvm::Expected<ApplyWorkspaceEditResponse> Response) mutable {
668 if (!Response)
669 return Reply(Response.takeError());
670 if (!Response->applied) {
671 std::string Reason = Response->failureReason
672 ? *Response->failureReason
673 : "unknown reason";
674 return Reply(llvm::createStringError(
675 llvm::inconvertibleErrorCode(),
676 ("edits were not applied: " + Reason).c_str()));
677 }
678 return Reply(SuccessMessage);
679 });
Eric Liuc5105f92018-02-16 14:15:55 +0000680 };
Ilya Biryukov12864002019-08-16 12:46:41 +0000681
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000682 if (Params.command == ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND &&
683 Params.workspaceEdit) {
684 // The flow for "apply-fix" :
685 // 1. We publish a diagnostic, including fixits
686 // 2. The user clicks on the diagnostic, the editor asks us for code actions
687 // 3. We send code actions, with the fixit embedded as context
688 // 4. The user selects the fixit, the editor asks us to apply it
689 // 5. We unwrap the changes and send them back to the editor
Haojian Wuf2516342019-08-05 12:48:09 +0000690 // 6. The editor applies the changes (applyEdit), and sends us a reply
691 // 7. We unwrap the reply and send a reply to the editor.
Ilya Biryukov12864002019-08-16 12:46:41 +0000692 ApplyEdit(*Params.workspaceEdit, "Fix applied.", std::move(Reply));
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000693 } else if (Params.command == ExecuteCommandParams::CLANGD_APPLY_TWEAK &&
694 Params.tweakArgs) {
695 auto Code = DraftMgr.getDraft(Params.tweakArgs->file.file());
696 if (!Code)
697 return Reply(llvm::createStringError(
698 llvm::inconvertibleErrorCode(),
699 "trying to apply a code action for a non-added file"));
700
Ilya Biryukov12864002019-08-16 12:46:41 +0000701 auto Action = [this, ApplyEdit, Reply = std::move(Reply),
702 File = Params.tweakArgs->file, Code = std::move(*Code)](
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000703 llvm::Expected<Tweak::Effect> R) mutable {
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000704 if (!R)
705 return Reply(R.takeError());
706
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000707 assert(R->ShowMessage ||
708 (!R->ApplyEdits.empty() && "tweak has no effect"));
Ilya Biryukov12864002019-08-16 12:46:41 +0000709
Sam McCall395fde72019-06-18 13:37:54 +0000710 if (R->ShowMessage) {
711 ShowMessageParams Msg;
712 Msg.message = *R->ShowMessage;
713 Msg.type = MessageType::Info;
714 notify("window/showMessage", Msg);
715 }
Ilya Biryukov12864002019-08-16 12:46:41 +0000716 // When no edit is specified, make sure we Reply().
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000717 if (R->ApplyEdits.empty())
718 return Reply("Tweak applied.");
719
Haojian Wu852bafa2019-10-23 14:40:20 +0200720 if (auto Err = validateEdits(DraftMgr, R->ApplyEdits))
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000721 return Reply(std::move(Err));
722
723 WorkspaceEdit WE;
724 WE.changes.emplace();
725 for (const auto &It : R->ApplyEdits) {
Kadir Cetinkayae95e5162019-10-02 09:12:01 +0000726 (*WE.changes)[URI::createFile(It.first()).toString()] =
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000727 It.second.asTextEdits();
728 }
729 // ApplyEdit will take care of calling Reply().
730 return ApplyEdit(std::move(WE), "Tweak applied.", std::move(Reply));
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000731 };
732 Server->applyTweak(Params.tweakArgs->file.file(),
733 Params.tweakArgs->selection, Params.tweakArgs->tweakID,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000734 std::move(Action));
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000735 } else {
736 // We should not get here because ExecuteCommandParams would not have
737 // parsed in the first place and this handler should not be called. But if
738 // more commands are added, this will be here has a safe guard.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000739 Reply(llvm::make_error<LSPError>(
740 llvm::formatv("Unsupported command \"{0}\".", Params.command).str(),
Sam McCall2c30fbc2018-10-18 12:32:04 +0000741 ErrorCode::InvalidParams));
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000742 }
743}
744
Sam McCall2c30fbc2018-10-18 12:32:04 +0000745void ClangdLSPServer::onWorkspaceSymbol(
746 const WorkspaceSymbolParams &Params,
747 Callback<std::vector<SymbolInformation>> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000748 Server->workspaceSymbols(
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000749 Params.query, CCOpts.Limit,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000750 [Reply = std::move(Reply),
751 this](llvm::Expected<std::vector<SymbolInformation>> Items) mutable {
752 if (!Items)
753 return Reply(Items.takeError());
754 for (auto &Sym : *Items)
755 Sym.kind = adjustKindToCapability(Sym.kind, SupportedSymbolKinds);
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000756
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000757 Reply(std::move(*Items));
758 });
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000759}
760
Haojian Wuf429ab62019-07-24 07:49:23 +0000761void ClangdLSPServer::onPrepareRename(const TextDocumentPositionParams &Params,
762 Callback<llvm::Optional<Range>> Reply) {
763 Server->prepareRename(Params.textDocument.uri.file(), Params.position,
Haojian Wu34d0e1b2020-02-19 15:37:36 +0100764 RenameOpts, std::move(Reply));
Haojian Wuf429ab62019-07-24 07:49:23 +0000765}
766
Sam McCall2c30fbc2018-10-18 12:32:04 +0000767void ClangdLSPServer::onRename(const RenameParams &Params,
768 Callback<WorkspaceEdit> Reply) {
Benjamin Krameradcd0262020-01-28 20:23:46 +0100769 Path File = std::string(Params.textDocument.uri.file());
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000770 llvm::Optional<std::string> Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000771 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000772 return Reply(llvm::make_error<LSPError>(
773 "onRename called for non-added file", ErrorCode::InvalidParams));
Haojian Wu852bafa2019-10-23 14:40:20 +0200774 Server->rename(
Haojian Wu34d0e1b2020-02-19 15:37:36 +0100775 File, Params.position, Params.newName, RenameOpts,
Haojian Wu852bafa2019-10-23 14:40:20 +0200776 [File, Params, Reply = std::move(Reply),
777 this](llvm::Expected<FileEdits> Edits) mutable {
778 if (!Edits)
779 return Reply(Edits.takeError());
780 if (auto Err = validateEdits(DraftMgr, *Edits))
781 return Reply(std::move(Err));
782 WorkspaceEdit Result;
783 Result.changes.emplace();
784 for (const auto &Rep : *Edits) {
785 (*Result.changes)[URI::createFile(Rep.first()).toString()] =
786 Rep.second.asTextEdits();
787 }
788 Reply(Result);
789 });
Haojian Wu345099c2017-11-09 11:30:04 +0000790}
791
Sam McCall2c30fbc2018-10-18 12:32:04 +0000792void ClangdLSPServer::onDocumentDidClose(
793 const DidCloseTextDocumentParams &Params) {
Simon Marchi9569fd52018-03-16 14:30:42 +0000794 PathRef File = Params.textDocument.uri.file();
795 DraftMgr.removeDraft(File);
Ilya Biryukov652364b2018-09-26 05:48:29 +0000796 Server->removeDocument(File);
Ilya Biryukov49c10712019-03-25 10:15:11 +0000797
798 {
799 std::lock_guard<std::mutex> Lock(FixItsMutex);
800 FixItsMap.erase(File);
801 }
Johan Vikstromc2653ef22019-08-01 08:08:44 +0000802 {
803 std::lock_guard<std::mutex> HLock(HighlightingsMutex);
804 FileToHighlightings.erase(File);
805 }
Ilya Biryukov49c10712019-03-25 10:15:11 +0000806 // clangd will not send updates for this file anymore, so we empty out the
807 // list of diagnostics shown on the client (e.g. in the "Problems" pane of
808 // VSCode). Note that this cannot race with actual diagnostics responses
809 // because removeDocument() guarantees no diagnostic callbacks will be
810 // executed after it returns.
811 publishDiagnostics(URIForFile::canonicalize(File, /*TUPath=*/File), {});
Ilya Biryukovafb55542017-05-16 14:40:30 +0000812}
813
Sam McCall4db732a2017-09-30 10:08:52 +0000814void ClangdLSPServer::onDocumentOnTypeFormatting(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000815 const DocumentOnTypeFormattingParams &Params,
816 Callback<std::vector<TextEdit>> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000817 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000818 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000819 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000820 return Reply(llvm::make_error<LSPError>(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000821 "onDocumentOnTypeFormatting called for non-added file",
822 ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000823
Sam McCall25c62572019-06-10 14:26:21 +0000824 Reply(Server->formatOnType(*Code, File, Params.position, Params.ch));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000825}
826
Sam McCall4db732a2017-09-30 10:08:52 +0000827void ClangdLSPServer::onDocumentRangeFormatting(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000828 const DocumentRangeFormattingParams &Params,
829 Callback<std::vector<TextEdit>> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000830 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000831 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000832 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000833 return Reply(llvm::make_error<LSPError>(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000834 "onDocumentRangeFormatting called for non-added file",
835 ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000836
Ilya Biryukov652364b2018-09-26 05:48:29 +0000837 auto ReplacementsOrError = Server->formatRange(*Code, File, Params.range);
Raoul Wols212bcf82017-12-12 20:25:06 +0000838 if (ReplacementsOrError)
Sam McCall2c30fbc2018-10-18 12:32:04 +0000839 Reply(replacementsToEdits(*Code, ReplacementsOrError.get()));
Raoul Wols212bcf82017-12-12 20:25:06 +0000840 else
Sam McCall2c30fbc2018-10-18 12:32:04 +0000841 Reply(ReplacementsOrError.takeError());
Ilya Biryukovafb55542017-05-16 14:40:30 +0000842}
843
Sam McCall2c30fbc2018-10-18 12:32:04 +0000844void ClangdLSPServer::onDocumentFormatting(
845 const DocumentFormattingParams &Params,
846 Callback<std::vector<TextEdit>> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000847 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000848 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000849 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000850 return Reply(llvm::make_error<LSPError>(
851 "onDocumentFormatting called for non-added file",
852 ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000853
Ilya Biryukov652364b2018-09-26 05:48:29 +0000854 auto ReplacementsOrError = Server->formatFile(*Code, File);
Raoul Wols212bcf82017-12-12 20:25:06 +0000855 if (ReplacementsOrError)
Sam McCall2c30fbc2018-10-18 12:32:04 +0000856 Reply(replacementsToEdits(*Code, ReplacementsOrError.get()));
Raoul Wols212bcf82017-12-12 20:25:06 +0000857 else
Sam McCall2c30fbc2018-10-18 12:32:04 +0000858 Reply(ReplacementsOrError.takeError());
Sam McCall4db732a2017-09-30 10:08:52 +0000859}
860
Ilya Biryukov19d75602018-11-23 15:21:19 +0000861/// The functions constructs a flattened view of the DocumentSymbol hierarchy.
862/// Used by the clients that do not support the hierarchical view.
863static std::vector<SymbolInformation>
864flattenSymbolHierarchy(llvm::ArrayRef<DocumentSymbol> Symbols,
865 const URIForFile &FileURI) {
866
867 std::vector<SymbolInformation> Results;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000868 std::function<void(const DocumentSymbol &, llvm::StringRef)> Process =
869 [&](const DocumentSymbol &S, llvm::Optional<llvm::StringRef> ParentName) {
Ilya Biryukov19d75602018-11-23 15:21:19 +0000870 SymbolInformation SI;
Benjamin Krameradcd0262020-01-28 20:23:46 +0100871 SI.containerName = std::string(ParentName ? "" : *ParentName);
Ilya Biryukov19d75602018-11-23 15:21:19 +0000872 SI.name = S.name;
873 SI.kind = S.kind;
874 SI.location.range = S.range;
875 SI.location.uri = FileURI;
876
877 Results.push_back(std::move(SI));
878 std::string FullName =
879 !ParentName ? S.name : (ParentName->str() + "::" + S.name);
880 for (auto &C : S.children)
881 Process(C, /*ParentName=*/FullName);
882 };
883 for (auto &S : Symbols)
884 Process(S, /*ParentName=*/"");
885 return Results;
886}
887
888void ClangdLSPServer::onDocumentSymbol(const DocumentSymbolParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000889 Callback<llvm::json::Value> Reply) {
Ilya Biryukov19d75602018-11-23 15:21:19 +0000890 URIForFile FileURI = Params.textDocument.uri;
Ilya Biryukov652364b2018-09-26 05:48:29 +0000891 Server->documentSymbols(
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000892 Params.textDocument.uri.file(),
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000893 [this, FileURI, Reply = std::move(Reply)](
894 llvm::Expected<std::vector<DocumentSymbol>> Items) mutable {
895 if (!Items)
896 return Reply(Items.takeError());
897 adjustSymbolKinds(*Items, SupportedSymbolKinds);
898 if (SupportsHierarchicalDocumentSymbol)
899 return Reply(std::move(*Items));
900 else
901 return Reply(flattenSymbolHierarchy(*Items, FileURI));
902 });
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000903}
904
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000905static llvm::Optional<Command> asCommand(const CodeAction &Action) {
Sam McCall20841d42018-10-16 16:29:41 +0000906 Command Cmd;
907 if (Action.command && Action.edit)
Sam McCallc008af62018-10-20 15:30:37 +0000908 return None; // Not representable. (We never emit these anyway).
Sam McCall20841d42018-10-16 16:29:41 +0000909 if (Action.command) {
910 Cmd = *Action.command;
911 } else if (Action.edit) {
Benjamin Krameradcd0262020-01-28 20:23:46 +0100912 Cmd.command = std::string(Command::CLANGD_APPLY_FIX_COMMAND);
Sam McCall20841d42018-10-16 16:29:41 +0000913 Cmd.workspaceEdit = *Action.edit;
914 } else {
Sam McCallc008af62018-10-20 15:30:37 +0000915 return None;
Sam McCall20841d42018-10-16 16:29:41 +0000916 }
917 Cmd.title = Action.title;
918 if (Action.kind && *Action.kind == CodeAction::QUICKFIX_KIND)
919 Cmd.title = "Apply fix: " + Cmd.title;
920 return Cmd;
921}
922
Sam McCall2c30fbc2018-10-18 12:32:04 +0000923void ClangdLSPServer::onCodeAction(const CodeActionParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000924 Callback<llvm::json::Value> Reply) {
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000925 URIForFile File = Params.textDocument.uri;
926 auto Code = DraftMgr.getDraft(File.file());
Sam McCall2c30fbc2018-10-18 12:32:04 +0000927 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000928 return Reply(llvm::make_error<LSPError>(
929 "onCodeAction called for non-added file", ErrorCode::InvalidParams));
Sam McCall20841d42018-10-16 16:29:41 +0000930 // We provide a code action for Fixes on the specified diagnostics.
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000931 std::vector<CodeAction> FixIts;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000932 for (const Diagnostic &D : Params.context.diagnostics) {
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000933 for (auto &F : getFixes(File.file(), D)) {
934 FixIts.push_back(toCodeAction(F, Params.textDocument.uri));
935 FixIts.back().diagnostics = {D};
Sam McCalldd0566b2017-11-06 15:40:30 +0000936 }
Ilya Biryukovafb55542017-05-16 14:40:30 +0000937 }
Sam McCall20841d42018-10-16 16:29:41 +0000938
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000939 // Now enumerate the semantic code actions.
940 auto ConsumeActions =
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000941 [Reply = std::move(Reply), File, Code = std::move(*Code),
942 Selection = Params.range, FixIts = std::move(FixIts), this](
943 llvm::Expected<std::vector<ClangdServer::TweakRef>> Tweaks) mutable {
Ilya Biryukovc6ed7782019-01-30 14:24:17 +0000944 if (!Tweaks)
945 return Reply(Tweaks.takeError());
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000946
947 std::vector<CodeAction> Actions = std::move(FixIts);
948 Actions.reserve(Actions.size() + Tweaks->size());
949 for (const auto &T : *Tweaks)
950 Actions.push_back(toCodeAction(T, File, Selection));
951
952 if (SupportsCodeAction)
953 return Reply(llvm::json::Array(Actions));
954 std::vector<Command> Commands;
955 for (const auto &Action : Actions) {
956 if (auto Command = asCommand(Action))
957 Commands.push_back(std::move(*Command));
958 }
959 return Reply(llvm::json::Array(Commands));
960 };
961
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000962 Server->enumerateTweaks(File.file(), Params.range, std::move(ConsumeActions));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000963}
964
Ilya Biryukovb0826bd2019-01-03 13:37:12 +0000965void ClangdLSPServer::onCompletion(const CompletionParams &Params,
Sam McCall2c30fbc2018-10-18 12:32:04 +0000966 Callback<CompletionList> Reply) {
Ilya Biryukova7a11472019-06-07 16:24:38 +0000967 if (!shouldRunCompletion(Params)) {
968 // Clients sometimes auto-trigger completions in undesired places (e.g.
969 // 'a >^ '), we return empty results in those cases.
970 vlog("ignored auto-triggered completion, preceding char did not match");
971 return Reply(CompletionList());
972 }
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000973 Server->codeComplete(Params.textDocument.uri.file(), Params.position, CCOpts,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000974 [Reply = std::move(Reply),
975 this](llvm::Expected<CodeCompleteResult> List) mutable {
976 if (!List)
977 return Reply(List.takeError());
978 CompletionList LSPList;
979 LSPList.isIncomplete = List->HasMore;
980 for (const auto &R : List->Completions) {
981 CompletionItem C = R.render(CCOpts);
982 C.kind = adjustKindToCapability(
983 C.kind, SupportedCompletionItemKinds);
984 LSPList.items.push_back(std::move(C));
985 }
986 return Reply(std::move(LSPList));
987 });
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000988}
989
Sam McCall2c30fbc2018-10-18 12:32:04 +0000990void ClangdLSPServer::onSignatureHelp(const TextDocumentPositionParams &Params,
991 Callback<SignatureHelp> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000992 Server->signatureHelp(Params.textDocument.uri.file(), Params.position,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000993 [Reply = std::move(Reply), this](
994 llvm::Expected<SignatureHelp> Signature) mutable {
995 if (!Signature)
996 return Reply(Signature.takeError());
997 if (SupportsOffsetsInSignatureHelp)
998 return Reply(std::move(*Signature));
999 // Strip out the offsets from signature help for
1000 // clients that only support string labels.
1001 for (auto &SigInfo : Signature->signatures) {
1002 for (auto &Param : SigInfo.parameters)
1003 Param.labelOffsets.reset();
1004 }
1005 return Reply(std::move(*Signature));
1006 });
Ilya Biryukov652364b2018-09-26 05:48:29 +00001007}
1008
Sam McCall0dbab7f2019-02-02 05:56:00 +00001009// Go to definition has a toggle function: if def and decl are distinct, then
1010// the first press gives you the def, the second gives you the matching def.
1011// getToggle() returns the counterpart location that under the cursor.
1012//
1013// We return the toggled location alone (ignoring other symbols) to encourage
1014// editors to "bounce" quickly between locations, without showing a menu.
1015static Location *getToggle(const TextDocumentPositionParams &Point,
1016 LocatedSymbol &Sym) {
1017 // Toggle only makes sense with two distinct locations.
1018 if (!Sym.Definition || *Sym.Definition == Sym.PreferredDeclaration)
1019 return nullptr;
1020 if (Sym.Definition->uri.file() == Point.textDocument.uri.file() &&
1021 Sym.Definition->range.contains(Point.position))
1022 return &Sym.PreferredDeclaration;
1023 if (Sym.PreferredDeclaration.uri.file() == Point.textDocument.uri.file() &&
1024 Sym.PreferredDeclaration.range.contains(Point.position))
1025 return &*Sym.Definition;
1026 return nullptr;
1027}
1028
Sam McCall2c30fbc2018-10-18 12:32:04 +00001029void ClangdLSPServer::onGoToDefinition(const TextDocumentPositionParams &Params,
1030 Callback<std::vector<Location>> Reply) {
Sam McCall866ba2c2019-02-01 11:26:13 +00001031 Server->locateSymbolAt(
1032 Params.textDocument.uri.file(), Params.position,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001033 [Params, Reply = std::move(Reply)](
1034 llvm::Expected<std::vector<LocatedSymbol>> Symbols) mutable {
1035 if (!Symbols)
1036 return Reply(Symbols.takeError());
1037 std::vector<Location> Defs;
1038 for (auto &S : *Symbols) {
1039 if (Location *Toggle = getToggle(Params, S))
1040 return Reply(std::vector<Location>{std::move(*Toggle)});
1041 Defs.push_back(S.Definition.getValueOr(S.PreferredDeclaration));
1042 }
1043 Reply(std::move(Defs));
1044 });
Sam McCall866ba2c2019-02-01 11:26:13 +00001045}
1046
1047void ClangdLSPServer::onGoToDeclaration(
1048 const TextDocumentPositionParams &Params,
1049 Callback<std::vector<Location>> Reply) {
1050 Server->locateSymbolAt(
1051 Params.textDocument.uri.file(), Params.position,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001052 [Params, Reply = std::move(Reply)](
1053 llvm::Expected<std::vector<LocatedSymbol>> Symbols) mutable {
1054 if (!Symbols)
1055 return Reply(Symbols.takeError());
1056 std::vector<Location> Decls;
1057 for (auto &S : *Symbols) {
1058 if (Location *Toggle = getToggle(Params, S))
1059 return Reply(std::vector<Location>{std::move(*Toggle)});
1060 Decls.push_back(std::move(S.PreferredDeclaration));
1061 }
1062 Reply(std::move(Decls));
1063 });
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +00001064}
1065
Sam McCall111fe842019-05-07 07:55:35 +00001066void ClangdLSPServer::onSwitchSourceHeader(
1067 const TextDocumentIdentifier &Params,
Sam McCallb9ec3e92019-05-07 08:30:32 +00001068 Callback<llvm::Optional<URIForFile>> Reply) {
Haojian Wud6d5edd2019-10-01 10:21:15 +00001069 Server->switchSourceHeader(
1070 Params.uri.file(),
1071 [Reply = std::move(Reply),
1072 Params](llvm::Expected<llvm::Optional<clangd::Path>> Path) mutable {
1073 if (!Path)
1074 return Reply(Path.takeError());
1075 if (*Path)
Haojian Wu77c97002019-10-07 11:37:25 +00001076 return Reply(URIForFile::canonicalize(**Path, Params.uri.file()));
Haojian Wud6d5edd2019-10-01 10:21:15 +00001077 return Reply(llvm::None);
1078 });
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +00001079}
1080
Sam McCall2c30fbc2018-10-18 12:32:04 +00001081void ClangdLSPServer::onDocumentHighlight(
1082 const TextDocumentPositionParams &Params,
1083 Callback<std::vector<DocumentHighlight>> Reply) {
1084 Server->findDocumentHighlights(Params.textDocument.uri.file(),
1085 Params.position, std::move(Reply));
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +00001086}
1087
Sam McCall2c30fbc2018-10-18 12:32:04 +00001088void ClangdLSPServer::onHover(const TextDocumentPositionParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001089 Callback<llvm::Optional<Hover>> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +00001090 Server->findHover(Params.textDocument.uri.file(), Params.position,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001091 [Reply = std::move(Reply), this](
1092 llvm::Expected<llvm::Optional<HoverInfo>> H) mutable {
1093 if (!H)
1094 return Reply(H.takeError());
1095 if (!*H)
1096 return Reply(llvm::None);
Ilya Biryukovf9169d02019-05-29 10:01:00 +00001097
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001098 Hover R;
1099 R.contents.kind = HoverContentFormat;
1100 R.range = (*H)->SymRange;
1101 switch (HoverContentFormat) {
1102 case MarkupKind::PlainText:
Kadir Cetinkaya597c6b62019-12-10 10:28:37 +01001103 R.contents.value = (*H)->present().asPlainText();
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001104 return Reply(std::move(R));
1105 case MarkupKind::Markdown:
Kadir Cetinkaya597c6b62019-12-10 10:28:37 +01001106 R.contents.value = (*H)->present().asMarkdown();
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001107 return Reply(std::move(R));
1108 };
1109 llvm_unreachable("unhandled MarkupKind");
1110 });
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +00001111}
1112
Kadir Cetinkaya86658022019-03-19 09:27:04 +00001113void ClangdLSPServer::onTypeHierarchy(
1114 const TypeHierarchyParams &Params,
1115 Callback<Optional<TypeHierarchyItem>> Reply) {
1116 Server->typeHierarchy(Params.textDocument.uri.file(), Params.position,
1117 Params.resolve, Params.direction, std::move(Reply));
1118}
1119
Nathan Ridge087b0442019-07-13 03:24:48 +00001120void ClangdLSPServer::onResolveTypeHierarchy(
1121 const ResolveTypeHierarchyItemParams &Params,
1122 Callback<Optional<TypeHierarchyItem>> Reply) {
1123 Server->resolveTypeHierarchy(Params.item, Params.resolve, Params.direction,
1124 std::move(Reply));
1125}
1126
Simon Marchi88016782018-08-01 11:28:49 +00001127void ClangdLSPServer::applyConfiguration(
Sam McCallbc904612018-10-25 04:22:52 +00001128 const ConfigurationSettings &Settings) {
Simon Marchiabeed662018-10-16 15:55:03 +00001129 // Per-file update to the compilation database.
David Goldman60249c22020-01-13 17:01:10 -05001130 llvm::StringSet<> ModifiedFiles;
Sam McCallbc904612018-10-25 04:22:52 +00001131 for (auto &Entry : Settings.compilationDatabaseChanges) {
Sam McCallbc904612018-10-25 04:22:52 +00001132 PathRef File = Entry.first;
Sam McCallc55d09a2018-11-02 13:09:36 +00001133 auto Old = CDB->getCompileCommand(File);
1134 auto New =
1135 tooling::CompileCommand(std::move(Entry.second.workingDirectory), File,
1136 std::move(Entry.second.compilationCommand),
1137 /*Output=*/"");
Sam McCall6980edb2018-11-02 14:07:51 +00001138 if (Old != New) {
Sam McCallc55d09a2018-11-02 13:09:36 +00001139 CDB->setCompileCommand(File, std::move(New));
David Goldman60249c22020-01-13 17:01:10 -05001140 ModifiedFiles.insert(File);
Sam McCall6980edb2018-11-02 14:07:51 +00001141 }
Alex Lorenzf8087862018-08-01 17:39:29 +00001142 }
David Goldman60249c22020-01-13 17:01:10 -05001143
1144 reparseOpenedFiles(ModifiedFiles);
Simon Marchi5178f922018-02-22 14:00:39 +00001145}
1146
Johan Vikstroma848dab2019-07-04 07:53:12 +00001147void ClangdLSPServer::publishSemanticHighlighting(
1148 SemanticHighlightingParams Params) {
1149 notify("textDocument/semanticHighlighting", Params);
1150}
1151
Ilya Biryukov49c10712019-03-25 10:15:11 +00001152void ClangdLSPServer::publishDiagnostics(
1153 const URIForFile &File, std::vector<clangd::Diagnostic> Diagnostics) {
1154 // Publish diagnostics.
1155 notify("textDocument/publishDiagnostics",
1156 llvm::json::Object{
1157 {"uri", File},
1158 {"diagnostics", std::move(Diagnostics)},
1159 });
1160}
1161
Simon Marchi88016782018-08-01 11:28:49 +00001162// FIXME: This function needs to be properly tested.
1163void ClangdLSPServer::onChangeConfiguration(
Sam McCall2c30fbc2018-10-18 12:32:04 +00001164 const DidChangeConfigurationParams &Params) {
Simon Marchi88016782018-08-01 11:28:49 +00001165 applyConfiguration(Params.settings);
1166}
1167
Sam McCall2c30fbc2018-10-18 12:32:04 +00001168void ClangdLSPServer::onReference(const ReferenceParams &Params,
1169 Callback<std::vector<Location>> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +00001170 Server->findReferences(Params.textDocument.uri.file(), Params.position,
Haojian Wu5181ada2019-11-18 11:35:00 +01001171 CCOpts.Limit,
1172 [Reply = std::move(Reply)](
1173 llvm::Expected<ReferencesResult> Refs) mutable {
1174 if (!Refs)
1175 return Reply(Refs.takeError());
1176 return Reply(std::move(Refs->References));
1177 });
Sam McCall1ad142f2018-09-05 11:53:07 +00001178}
1179
Jan Korousb4067012018-11-27 16:40:46 +00001180void ClangdLSPServer::onSymbolInfo(const TextDocumentPositionParams &Params,
1181 Callback<std::vector<SymbolDetails>> Reply) {
1182 Server->symbolInfo(Params.textDocument.uri.file(), Params.position,
1183 std::move(Reply));
1184}
1185
Utkarsh Saxena55925da2019-09-24 13:38:33 +00001186void ClangdLSPServer::onSelectionRange(
1187 const SelectionRangeParams &Params,
1188 Callback<std::vector<SelectionRange>> Reply) {
1189 if (Params.positions.size() != 1) {
1190 elog("{0} positions provided to SelectionRange. Supports exactly one "
1191 "position.",
1192 Params.positions.size());
1193 return Reply(llvm::make_error<LSPError>(
1194 "SelectionRange supports exactly one position",
1195 ErrorCode::InvalidRequest));
1196 }
1197 Server->semanticRanges(
1198 Params.textDocument.uri.file(), Params.positions[0],
1199 [Reply = std::move(Reply)](
1200 llvm::Expected<std::vector<Range>> Ranges) mutable {
1201 if (!Ranges) {
1202 return Reply(Ranges.takeError());
1203 }
1204 std::vector<SelectionRange> Result;
1205 Result.emplace_back(render(std::move(*Ranges)));
1206 return Reply(std::move(Result));
1207 });
1208}
1209
Sam McCall8d7ecc12019-12-16 19:08:51 +01001210void ClangdLSPServer::onDocumentLink(
1211 const DocumentLinkParams &Params,
1212 Callback<std::vector<DocumentLink>> Reply) {
1213
1214 // TODO(forster): This currently resolves all targets eagerly. This is slow,
1215 // because it blocks on the preamble/AST being built. We could respond to the
1216 // request faster by using string matching or the lexer to find the includes
1217 // and resolving the targets lazily.
1218 Server->documentLinks(
1219 Params.textDocument.uri.file(),
1220 [Reply = std::move(Reply)](
1221 llvm::Expected<std::vector<DocumentLink>> Links) mutable {
1222 if (!Links) {
1223 return Reply(Links.takeError());
1224 }
1225 return Reply(std::move(Links));
1226 });
1227}
1228
Sam McCalla69698f2019-03-27 17:47:49 +00001229ClangdLSPServer::ClangdLSPServer(
1230 class Transport &Transp, const FileSystemProvider &FSProvider,
1231 const clangd::CodeCompleteOptions &CCOpts,
Haojian Wu34d0e1b2020-02-19 15:37:36 +01001232 const clangd::RenameOptions &RenameOpts,
Sam McCalla69698f2019-03-27 17:47:49 +00001233 llvm::Optional<Path> CompileCommandsDir, bool UseDirBasedCDB,
1234 llvm::Optional<OffsetEncoding> ForcedOffsetEncoding,
1235 const ClangdServer::Options &Opts)
Kadir Cetinkaya9d662472019-10-15 14:20:52 +00001236 : BackgroundContext(Context::current().clone()), Transp(Transp),
1237 MsgHandler(new MessageHandler(*this)), FSProvider(FSProvider),
Haojian Wu34d0e1b2020-02-19 15:37:36 +01001238 CCOpts(CCOpts), RenameOpts(RenameOpts),
1239 SupportedSymbolKinds(defaultSymbolKinds()),
Kadir Cetinkaya133d46f2018-09-27 17:13:07 +00001240 SupportedCompletionItemKinds(defaultCompletionItemKinds()),
Sam McCallc55d09a2018-11-02 13:09:36 +00001241 UseDirBasedCDB(UseDirBasedCDB),
Sam McCalla69698f2019-03-27 17:47:49 +00001242 CompileCommandsDir(std::move(CompileCommandsDir)), ClangdServerOpts(Opts),
1243 NegotiatedOffsetEncoding(ForcedOffsetEncoding) {
Sam McCall2c30fbc2018-10-18 12:32:04 +00001244 // clang-format off
1245 MsgHandler->bind("initialize", &ClangdLSPServer::onInitialize);
1246 MsgHandler->bind("shutdown", &ClangdLSPServer::onShutdown);
Sam McCall422c8282018-11-26 16:00:11 +00001247 MsgHandler->bind("sync", &ClangdLSPServer::onSync);
Sam McCall2c30fbc2018-10-18 12:32:04 +00001248 MsgHandler->bind("textDocument/rangeFormatting", &ClangdLSPServer::onDocumentRangeFormatting);
1249 MsgHandler->bind("textDocument/onTypeFormatting", &ClangdLSPServer::onDocumentOnTypeFormatting);
1250 MsgHandler->bind("textDocument/formatting", &ClangdLSPServer::onDocumentFormatting);
1251 MsgHandler->bind("textDocument/codeAction", &ClangdLSPServer::onCodeAction);
1252 MsgHandler->bind("textDocument/completion", &ClangdLSPServer::onCompletion);
1253 MsgHandler->bind("textDocument/signatureHelp", &ClangdLSPServer::onSignatureHelp);
1254 MsgHandler->bind("textDocument/definition", &ClangdLSPServer::onGoToDefinition);
Sam McCall866ba2c2019-02-01 11:26:13 +00001255 MsgHandler->bind("textDocument/declaration", &ClangdLSPServer::onGoToDeclaration);
Sam McCall2c30fbc2018-10-18 12:32:04 +00001256 MsgHandler->bind("textDocument/references", &ClangdLSPServer::onReference);
1257 MsgHandler->bind("textDocument/switchSourceHeader", &ClangdLSPServer::onSwitchSourceHeader);
Haojian Wuf429ab62019-07-24 07:49:23 +00001258 MsgHandler->bind("textDocument/prepareRename", &ClangdLSPServer::onPrepareRename);
Sam McCall2c30fbc2018-10-18 12:32:04 +00001259 MsgHandler->bind("textDocument/rename", &ClangdLSPServer::onRename);
1260 MsgHandler->bind("textDocument/hover", &ClangdLSPServer::onHover);
1261 MsgHandler->bind("textDocument/documentSymbol", &ClangdLSPServer::onDocumentSymbol);
1262 MsgHandler->bind("workspace/executeCommand", &ClangdLSPServer::onCommand);
1263 MsgHandler->bind("textDocument/documentHighlight", &ClangdLSPServer::onDocumentHighlight);
1264 MsgHandler->bind("workspace/symbol", &ClangdLSPServer::onWorkspaceSymbol);
1265 MsgHandler->bind("textDocument/didOpen", &ClangdLSPServer::onDocumentDidOpen);
1266 MsgHandler->bind("textDocument/didClose", &ClangdLSPServer::onDocumentDidClose);
1267 MsgHandler->bind("textDocument/didChange", &ClangdLSPServer::onDocumentDidChange);
1268 MsgHandler->bind("workspace/didChangeWatchedFiles", &ClangdLSPServer::onFileEvent);
1269 MsgHandler->bind("workspace/didChangeConfiguration", &ClangdLSPServer::onChangeConfiguration);
Jan Korousb4067012018-11-27 16:40:46 +00001270 MsgHandler->bind("textDocument/symbolInfo", &ClangdLSPServer::onSymbolInfo);
Kadir Cetinkaya86658022019-03-19 09:27:04 +00001271 MsgHandler->bind("textDocument/typeHierarchy", &ClangdLSPServer::onTypeHierarchy);
Nathan Ridge087b0442019-07-13 03:24:48 +00001272 MsgHandler->bind("typeHierarchy/resolve", &ClangdLSPServer::onResolveTypeHierarchy);
Utkarsh Saxena55925da2019-09-24 13:38:33 +00001273 MsgHandler->bind("textDocument/selectionRange", &ClangdLSPServer::onSelectionRange);
Sam McCall8d7ecc12019-12-16 19:08:51 +01001274 MsgHandler->bind("textDocument/documentLink", &ClangdLSPServer::onDocumentLink);
Sam McCall2c30fbc2018-10-18 12:32:04 +00001275 // clang-format on
1276}
1277
Sam McCall8bda5f22019-10-23 11:11:18 +02001278ClangdLSPServer::~ClangdLSPServer() { IsBeingDestroyed = true;
1279 // Explicitly destroy ClangdServer first, blocking on threads it owns.
1280 // This ensures they don't access any other members.
1281 Server.reset();
1282}
Ilya Biryukov38d79772017-05-16 09:38:59 +00001283
Sam McCalldc8f3cf2018-10-17 07:32:05 +00001284bool ClangdLSPServer::run() {
Ilya Biryukovafb55542017-05-16 14:40:30 +00001285 // Run the Language Server loop.
Sam McCalldc8f3cf2018-10-17 07:32:05 +00001286 bool CleanExit = true;
Sam McCall2c30fbc2018-10-18 12:32:04 +00001287 if (auto Err = Transp.loop(*MsgHandler)) {
Sam McCalldc8f3cf2018-10-17 07:32:05 +00001288 elog("Transport error: {0}", std::move(Err));
1289 CleanExit = false;
1290 }
Ilya Biryukovafb55542017-05-16 14:40:30 +00001291
Sam McCalldc8f3cf2018-10-17 07:32:05 +00001292 return CleanExit && ShutdownRequestReceived;
Ilya Biryukov38d79772017-05-16 09:38:59 +00001293}
1294
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001295std::vector<Fix> ClangdLSPServer::getFixes(llvm::StringRef File,
Ilya Biryukov71028b82018-03-12 15:28:22 +00001296 const clangd::Diagnostic &D) {
Ilya Biryukov38d79772017-05-16 09:38:59 +00001297 std::lock_guard<std::mutex> Lock(FixItsMutex);
1298 auto DiagToFixItsIter = FixItsMap.find(File);
1299 if (DiagToFixItsIter == FixItsMap.end())
1300 return {};
1301
1302 const auto &DiagToFixItsMap = DiagToFixItsIter->second;
1303 auto FixItsIter = DiagToFixItsMap.find(D);
1304 if (FixItsIter == DiagToFixItsMap.end())
1305 return {};
1306
1307 return FixItsIter->second;
1308}
1309
Ilya Biryukovb0826bd2019-01-03 13:37:12 +00001310bool ClangdLSPServer::shouldRunCompletion(
1311 const CompletionParams &Params) const {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001312 llvm::StringRef Trigger = Params.context.triggerCharacter;
Ilya Biryukovb0826bd2019-01-03 13:37:12 +00001313 if (Params.context.triggerKind != CompletionTriggerKind::TriggerCharacter ||
1314 (Trigger != ">" && Trigger != ":"))
1315 return true;
1316
1317 auto Code = DraftMgr.getDraft(Params.textDocument.uri.file());
1318 if (!Code)
1319 return true; // completion code will log the error for untracked doc.
1320
1321 // A completion request is sent when the user types '>' or ':', but we only
1322 // want to trigger on '->' and '::'. We check the preceeding character to make
1323 // sure it matches what we expected.
1324 // Running the lexer here would be more robust (e.g. we can detect comments
1325 // and avoid triggering completion there), but we choose to err on the side
1326 // of simplicity here.
1327 auto Offset = positionToOffset(*Code, Params.position,
1328 /*AllowColumnsBeyondLineLength=*/false);
1329 if (!Offset) {
1330 vlog("could not convert position '{0}' to offset for file '{1}'",
1331 Params.position, Params.textDocument.uri.file());
1332 return true;
1333 }
1334 if (*Offset < 2)
1335 return false;
1336
1337 if (Trigger == ">")
1338 return (*Code)[*Offset - 2] == '-'; // trigger only on '->'.
1339 if (Trigger == ":")
1340 return (*Code)[*Offset - 2] == ':'; // trigger only on '::'.
1341 assert(false && "unhandled trigger character");
1342 return true;
1343}
1344
Johan Vikstroma848dab2019-07-04 07:53:12 +00001345void ClangdLSPServer::onHighlightingsReady(
Haojian Wu0a6000f2019-08-26 08:38:45 +00001346 PathRef File, std::vector<HighlightingToken> Highlightings) {
Johan Vikstromc2653ef22019-08-01 08:08:44 +00001347 std::vector<HighlightingToken> Old;
1348 std::vector<HighlightingToken> HighlightingsCopy = Highlightings;
1349 {
1350 std::lock_guard<std::mutex> Lock(HighlightingsMutex);
1351 Old = std::move(FileToHighlightings[File]);
1352 FileToHighlightings[File] = std::move(HighlightingsCopy);
1353 }
1354 // LSP allows us to send incremental edits of highlightings. Also need to diff
1355 // to remove highlightings from tokens that should no longer have them.
Haojian Wu0a6000f2019-08-26 08:38:45 +00001356 std::vector<LineHighlightings> Diffed = diffHighlightings(Highlightings, Old);
Johan Vikstroma848dab2019-07-04 07:53:12 +00001357 publishSemanticHighlighting(
1358 {{URIForFile::canonicalize(File, /*TUPath=*/File)},
Johan Vikstromc2653ef22019-08-01 08:08:44 +00001359 toSemanticHighlightingInformation(Diffed)});
Johan Vikstroma848dab2019-07-04 07:53:12 +00001360}
1361
Sam McCalla7bb0cc2018-03-12 23:22:35 +00001362void ClangdLSPServer::onDiagnosticsReady(PathRef File,
1363 std::vector<Diag> Diagnostics) {
Eric Liu4d814a92018-11-28 10:30:42 +00001364 auto URI = URIForFile::canonicalize(File, /*TUPath=*/File);
Sam McCall16e70702018-10-24 07:59:38 +00001365 std::vector<Diagnostic> LSPDiagnostics;
Ilya Biryukov38d79772017-05-16 09:38:59 +00001366 DiagnosticToReplacementMap LocalFixIts; // Temporary storage
Sam McCalla7bb0cc2018-03-12 23:22:35 +00001367 for (auto &Diag : Diagnostics) {
Sam McCall16e70702018-10-24 07:59:38 +00001368 toLSPDiags(Diag, URI, DiagOpts,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001369 [&](clangd::Diagnostic Diag, llvm::ArrayRef<Fix> Fixes) {
Sam McCall16e70702018-10-24 07:59:38 +00001370 auto &FixItsForDiagnostic = LocalFixIts[Diag];
1371 llvm::copy(Fixes, std::back_inserter(FixItsForDiagnostic));
1372 LSPDiagnostics.push_back(std::move(Diag));
1373 });
Ilya Biryukov38d79772017-05-16 09:38:59 +00001374 }
1375
1376 // Cache FixIts
1377 {
Ilya Biryukov38d79772017-05-16 09:38:59 +00001378 std::lock_guard<std::mutex> Lock(FixItsMutex);
1379 FixItsMap[File] = LocalFixIts;
1380 }
1381
Ilya Biryukov49c10712019-03-25 10:15:11 +00001382 // Send a notification to the LSP client.
1383 publishDiagnostics(URI, std::move(LSPDiagnostics));
Ilya Biryukov38d79772017-05-16 09:38:59 +00001384}
Simon Marchi9569fd52018-03-16 14:30:42 +00001385
Sam McCall7d20e802020-01-22 19:41:45 +01001386void ClangdLSPServer::onBackgroundIndexProgress(
1387 const BackgroundQueue::Stats &Stats) {
1388 static const char ProgressToken[] = "backgroundIndexProgress";
1389 std::lock_guard<std::mutex> Lock(BackgroundIndexProgressMutex);
1390
1391 auto NotifyProgress = [this](const BackgroundQueue::Stats &Stats) {
1392 if (BackgroundIndexProgressState != BackgroundIndexProgress::Live) {
1393 WorkDoneProgressBegin Begin;
1394 Begin.percentage = true;
1395 Begin.title = "indexing";
1396 progress(ProgressToken, std::move(Begin));
1397 BackgroundIndexProgressState = BackgroundIndexProgress::Live;
1398 }
1399
1400 if (Stats.Completed < Stats.Enqueued) {
1401 assert(Stats.Enqueued > Stats.LastIdle);
1402 WorkDoneProgressReport Report;
1403 Report.percentage = 100.0 * (Stats.Completed - Stats.LastIdle) /
1404 (Stats.Enqueued - Stats.LastIdle);
1405 Report.message =
1406 llvm::formatv("{0}/{1}", Stats.Completed - Stats.LastIdle,
1407 Stats.Enqueued - Stats.LastIdle);
1408 progress(ProgressToken, std::move(Report));
1409 } else {
1410 assert(Stats.Completed == Stats.Enqueued);
1411 progress(ProgressToken, WorkDoneProgressEnd());
1412 BackgroundIndexProgressState = BackgroundIndexProgress::Empty;
1413 }
1414 };
1415
1416 switch (BackgroundIndexProgressState) {
1417 case BackgroundIndexProgress::Unsupported:
1418 return;
1419 case BackgroundIndexProgress::Creating:
1420 // Cache this update for when the progress bar is available.
1421 PendingBackgroundIndexProgress = Stats;
1422 return;
1423 case BackgroundIndexProgress::Empty: {
1424 if (BackgroundIndexSkipCreate) {
1425 NotifyProgress(Stats);
1426 break;
1427 }
1428 // Cache this update for when the progress bar is available.
1429 PendingBackgroundIndexProgress = Stats;
1430 BackgroundIndexProgressState = BackgroundIndexProgress::Creating;
1431 WorkDoneProgressCreateParams CreateRequest;
1432 CreateRequest.token = ProgressToken;
1433 call<std::nullptr_t>(
1434 "window/workDoneProgress/create", CreateRequest,
1435 [this, NotifyProgress](llvm::Expected<std::nullptr_t> E) {
1436 std::lock_guard<std::mutex> Lock(BackgroundIndexProgressMutex);
1437 if (E) {
1438 NotifyProgress(this->PendingBackgroundIndexProgress);
1439 } else {
1440 elog("Failed to create background index progress bar: {0}",
1441 E.takeError());
1442 // give up forever rather than thrashing about
1443 BackgroundIndexProgressState = BackgroundIndexProgress::Unsupported;
1444 }
1445 });
1446 break;
1447 }
1448 case BackgroundIndexProgress::Live:
1449 NotifyProgress(Stats);
1450 break;
1451 }
1452}
1453
Haojian Wub6188492018-12-20 15:39:12 +00001454void ClangdLSPServer::onFileUpdated(PathRef File, const TUStatus &Status) {
1455 if (!SupportFileStatus)
1456 return;
1457 // FIXME: we don't emit "BuildingFile" and `RunningAction`, as these
1458 // two statuses are running faster in practice, which leads the UI constantly
1459 // changing, and doesn't provide much value. We may want to emit status at a
1460 // reasonable time interval (e.g. 0.5s).
1461 if (Status.Action.S == TUAction::BuildingFile ||
1462 Status.Action.S == TUAction::RunningAction)
1463 return;
1464 notify("textDocument/clangd.fileStatus", Status.render(File));
1465}
1466
David Goldman60249c22020-01-13 17:01:10 -05001467void ClangdLSPServer::reparseOpenedFiles(
1468 const llvm::StringSet<> &ModifiedFiles) {
1469 if (ModifiedFiles.empty())
1470 return;
1471 // Reparse only opened files that were modified.
Simon Marchi9569fd52018-03-16 14:30:42 +00001472 for (const Path &FilePath : DraftMgr.getActiveFiles())
David Goldman60249c22020-01-13 17:01:10 -05001473 if (ModifiedFiles.find(FilePath) != ModifiedFiles.end())
1474 Server->addDocument(FilePath, *DraftMgr.getDraft(FilePath),
1475 WantDiagnostics::Auto);
Simon Marchi9569fd52018-03-16 14:30:42 +00001476}
Alex Lorenzf8087862018-08-01 17:39:29 +00001477
Sam McCallc008af62018-10-20 15:30:37 +00001478} // namespace clangd
1479} // namespace clang