blob: 0f87a81227a9500d83fe69e0373370dec4d22310 [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:
51 CA.kind = CodeAction::REFACTOR_KIND;
52 break;
53 case Tweak::Info:
54 CA.kind = CodeAction::INFO_KIND;
55 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;
64 CA.command->command = Command::CLANGD_APPLY_TWEAK;
65 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)
103 LookupTable.push_back({toTextMateScope((HighlightingKind)(KindValue))});
104 return LookupTable;
105}
106
Haojian Wu852bafa2019-10-23 14:40:20 +0200107// Makes sure edits in \p FE are applicable to latest file contents reported by
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000108// editor. If not generates an error message containing information about files
109// that needs to be saved.
Haojian Wu852bafa2019-10-23 14:40:20 +0200110llvm::Error validateEdits(const DraftStore &DraftMgr, const FileEdits &FE) {
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000111 size_t InvalidFileCount = 0;
112 llvm::StringRef LastInvalidFile;
Haojian Wu852bafa2019-10-23 14:40:20 +0200113 for (const auto &It : FE) {
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000114 if (auto Draft = DraftMgr.getDraft(It.first())) {
115 // If the file is open in user's editor, make sure the version we
116 // saw and current version are compatible as this is the text that
117 // will be replaced by editors.
118 if (!It.second.canApplyTo(*Draft)) {
119 ++InvalidFileCount;
120 LastInvalidFile = It.first();
121 }
122 }
123 }
124 if (!InvalidFileCount)
125 return llvm::Error::success();
126 if (InvalidFileCount == 1)
127 return llvm::createStringError(llvm::inconvertibleErrorCode(),
128 "File must be saved first: " +
129 LastInvalidFile);
130 return llvm::createStringError(
131 llvm::inconvertibleErrorCode(),
132 "Files must be saved first: " + LastInvalidFile + " (and " +
133 llvm::to_string(InvalidFileCount - 1) + " others)");
134}
135
Utkarsh Saxena55925da2019-09-24 13:38:33 +0000136// Converts a list of Ranges to a LinkedList of SelectionRange.
137SelectionRange render(const std::vector<Range> &Ranges) {
138 if (Ranges.empty())
139 return {};
140 SelectionRange Result;
141 Result.range = Ranges[0];
142 auto *Next = &Result.parent;
143 for (const auto &R : llvm::make_range(Ranges.begin() + 1, Ranges.end())) {
144 *Next = std::make_unique<SelectionRange>();
145 Next->get()->range = R;
146 Next = &Next->get()->parent;
147 }
148 return Result;
149}
150
Ilya Biryukovafb55542017-05-16 14:40:30 +0000151} // namespace
152
Sam McCall2c30fbc2018-10-18 12:32:04 +0000153// MessageHandler dispatches incoming LSP messages.
154// It handles cross-cutting concerns:
155// - serializes/deserializes protocol objects to JSON
156// - logging of inbound messages
157// - cancellation handling
158// - basic call tracing
Sam McCall3d0adbe2018-10-18 14:41:50 +0000159// MessageHandler ensures that initialize() is called before any other handler.
Sam McCall2c30fbc2018-10-18 12:32:04 +0000160class ClangdLSPServer::MessageHandler : public Transport::MessageHandler {
161public:
162 MessageHandler(ClangdLSPServer &Server) : Server(Server) {}
163
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000164 bool onNotify(llvm::StringRef Method, llvm::json::Value Params) override {
Sam McCalla69698f2019-03-27 17:47:49 +0000165 WithContext HandlerContext(handlerContext());
Sam McCall2c30fbc2018-10-18 12:32:04 +0000166 log("<-- {0}", Method);
167 if (Method == "exit")
168 return false;
Sam McCall3d0adbe2018-10-18 14:41:50 +0000169 if (!Server.Server)
170 elog("Notification {0} before initialization", Method);
171 else if (Method == "$/cancelRequest")
Sam McCall2c30fbc2018-10-18 12:32:04 +0000172 onCancel(std::move(Params));
173 else if (auto Handler = Notifications.lookup(Method))
174 Handler(std::move(Params));
175 else
176 log("unhandled notification {0}", Method);
177 return true;
178 }
179
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000180 bool onCall(llvm::StringRef Method, llvm::json::Value Params,
181 llvm::json::Value ID) override {
Sam McCalla69698f2019-03-27 17:47:49 +0000182 WithContext HandlerContext(handlerContext());
Sam McCalle2f3a732018-10-24 14:26:26 +0000183 // Calls can be canceled by the client. Add cancellation context.
184 WithContext WithCancel(cancelableRequestContext(ID));
185 trace::Span Tracer(Method);
186 SPAN_ATTACH(Tracer, "Params", Params);
187 ReplyOnce Reply(ID, Method, &Server, Tracer.Args);
Sam McCall2c30fbc2018-10-18 12:32:04 +0000188 log("<-- {0}({1})", Method, ID);
Sam McCall3d0adbe2018-10-18 14:41:50 +0000189 if (!Server.Server && Method != "initialize") {
190 elog("Call {0} before initialization.", Method);
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000191 Reply(llvm::make_error<LSPError>("server not initialized",
192 ErrorCode::ServerNotInitialized));
Sam McCall3d0adbe2018-10-18 14:41:50 +0000193 } else if (auto Handler = Calls.lookup(Method))
Sam McCalle2f3a732018-10-24 14:26:26 +0000194 Handler(std::move(Params), std::move(Reply));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000195 else
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000196 Reply(llvm::make_error<LSPError>("method not found",
197 ErrorCode::MethodNotFound));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000198 return true;
199 }
200
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000201 bool onReply(llvm::json::Value ID,
202 llvm::Expected<llvm::json::Value> Result) override {
Sam McCalla69698f2019-03-27 17:47:49 +0000203 WithContext HandlerContext(handlerContext());
Haojian Wuf2516342019-08-05 12:48:09 +0000204
205 Callback<llvm::json::Value> ReplyHandler = nullptr;
206 if (auto IntID = ID.getAsInteger()) {
207 std::lock_guard<std::mutex> Mutex(CallMutex);
208 // Find a corresponding callback for the request ID;
209 for (size_t Index = 0; Index < ReplyCallbacks.size(); ++Index) {
210 if (ReplyCallbacks[Index].first == *IntID) {
211 ReplyHandler = std::move(ReplyCallbacks[Index].second);
212 ReplyCallbacks.erase(ReplyCallbacks.begin() +
213 Index); // remove the entry
214 break;
215 }
216 }
217 }
218
219 if (!ReplyHandler) {
220 // No callback being found, use a default log callback.
221 ReplyHandler = [&ID](llvm::Expected<llvm::json::Value> Result) {
222 elog("received a reply with ID {0}, but there was no such call", ID);
223 if (!Result)
224 llvm::consumeError(Result.takeError());
225 };
226 }
227
228 // Log and run the reply handler.
229 if (Result) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000230 log("<-- reply({0})", ID);
Haojian Wuf2516342019-08-05 12:48:09 +0000231 ReplyHandler(std::move(Result));
232 } else {
233 auto Err = Result.takeError();
234 log("<-- reply({0}) error: {1}", ID, Err);
235 ReplyHandler(std::move(Err));
236 }
Sam McCall2c30fbc2018-10-18 12:32:04 +0000237 return true;
238 }
239
240 // Bind an LSP method name to a call.
Sam McCalle2f3a732018-10-24 14:26:26 +0000241 template <typename Param, typename Result>
Sam McCall2c30fbc2018-10-18 12:32:04 +0000242 void bind(const char *Method,
Sam McCalle2f3a732018-10-24 14:26:26 +0000243 void (ClangdLSPServer::*Handler)(const Param &, Callback<Result>)) {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000244 Calls[Method] = [Method, Handler, this](llvm::json::Value RawParams,
Sam McCalle2f3a732018-10-24 14:26:26 +0000245 ReplyOnce Reply) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000246 Param P;
Sam McCalle2f3a732018-10-24 14:26:26 +0000247 if (fromJSON(RawParams, P)) {
248 (Server.*Handler)(P, std::move(Reply));
249 } else {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000250 elog("Failed to decode {0} request.", Method);
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000251 Reply(llvm::make_error<LSPError>("failed to decode request",
252 ErrorCode::InvalidRequest));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000253 }
Sam McCall2c30fbc2018-10-18 12:32:04 +0000254 };
255 }
256
Haojian Wuf2516342019-08-05 12:48:09 +0000257 // Bind a reply callback to a request. The callback will be invoked when
258 // clangd receives the reply from the LSP client.
259 // Return a call id of the request.
260 llvm::json::Value bindReply(Callback<llvm::json::Value> Reply) {
261 llvm::Optional<std::pair<int, Callback<llvm::json::Value>>> OldestCB;
262 int ID;
263 {
264 std::lock_guard<std::mutex> Mutex(CallMutex);
265 ID = NextCallID++;
266 ReplyCallbacks.emplace_back(ID, std::move(Reply));
267
268 // If the queue overflows, we assume that the client didn't reply the
269 // oldest request, and run the corresponding callback which replies an
270 // error to the client.
271 if (ReplyCallbacks.size() > MaxReplayCallbacks) {
272 elog("more than {0} outstanding LSP calls, forgetting about {1}",
273 MaxReplayCallbacks, ReplyCallbacks.front().first);
274 OldestCB = std::move(ReplyCallbacks.front());
275 ReplyCallbacks.pop_front();
276 }
277 }
278 if (OldestCB)
279 OldestCB->second(llvm::createStringError(
280 llvm::inconvertibleErrorCode(),
281 llvm::formatv("failed to receive a client reply for request ({0})",
282 OldestCB->first)));
283 return ID;
284 }
285
Sam McCall2c30fbc2018-10-18 12:32:04 +0000286 // Bind an LSP method name to a notification.
287 template <typename Param>
288 void bind(const char *Method,
289 void (ClangdLSPServer::*Handler)(const Param &)) {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000290 Notifications[Method] = [Method, Handler,
291 this](llvm::json::Value RawParams) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000292 Param P;
293 if (!fromJSON(RawParams, P)) {
294 elog("Failed to decode {0} request.", Method);
295 return;
296 }
297 trace::Span Tracer(Method);
298 SPAN_ATTACH(Tracer, "Params", RawParams);
299 (Server.*Handler)(P);
300 };
301 }
302
303private:
Sam McCalle2f3a732018-10-24 14:26:26 +0000304 // Function object to reply to an LSP call.
305 // Each instance must be called exactly once, otherwise:
306 // - the bug is logged, and (in debug mode) an assert will fire
307 // - if there was no reply, an error reply is sent
308 // - if there were multiple replies, only the first is sent
309 class ReplyOnce {
310 std::atomic<bool> Replied = {false};
Sam McCalld7babe42018-10-24 15:18:40 +0000311 std::chrono::steady_clock::time_point Start;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000312 llvm::json::Value ID;
Sam McCalle2f3a732018-10-24 14:26:26 +0000313 std::string Method;
314 ClangdLSPServer *Server; // Null when moved-from.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000315 llvm::json::Object *TraceArgs;
Sam McCalle2f3a732018-10-24 14:26:26 +0000316
317 public:
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000318 ReplyOnce(const llvm::json::Value &ID, llvm::StringRef Method,
319 ClangdLSPServer *Server, llvm::json::Object *TraceArgs)
Sam McCalld7babe42018-10-24 15:18:40 +0000320 : Start(std::chrono::steady_clock::now()), ID(ID), Method(Method),
321 Server(Server), TraceArgs(TraceArgs) {
Sam McCalle2f3a732018-10-24 14:26:26 +0000322 assert(Server);
323 }
324 ReplyOnce(ReplyOnce &&Other)
Sam McCalld7babe42018-10-24 15:18:40 +0000325 : Replied(Other.Replied.load()), Start(Other.Start),
326 ID(std::move(Other.ID)), Method(std::move(Other.Method)),
327 Server(Other.Server), TraceArgs(Other.TraceArgs) {
Sam McCalle2f3a732018-10-24 14:26:26 +0000328 Other.Server = nullptr;
329 }
Ilya Biryukov22fa4652019-01-03 13:28:05 +0000330 ReplyOnce &operator=(ReplyOnce &&) = delete;
Sam McCalle2f3a732018-10-24 14:26:26 +0000331 ReplyOnce(const ReplyOnce &) = delete;
Ilya Biryukov22fa4652019-01-03 13:28:05 +0000332 ReplyOnce &operator=(const ReplyOnce &) = delete;
Sam McCalle2f3a732018-10-24 14:26:26 +0000333
334 ~ReplyOnce() {
Haojian Wuf2516342019-08-05 12:48:09 +0000335 // There's one legitimate reason to never reply to a request: clangd's
336 // request handler send a call to the client (e.g. applyEdit) and the
337 // client never replied. In this case, the ReplyOnce is owned by
338 // ClangdLSPServer's reply callback table and is destroyed along with the
339 // server. We don't attempt to send a reply in this case, there's little
340 // to be gained from doing so.
341 if (Server && !Server->IsBeingDestroyed && !Replied) {
Sam McCalle2f3a732018-10-24 14:26:26 +0000342 elog("No reply to message {0}({1})", Method, ID);
343 assert(false && "must reply to all calls!");
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000344 (*this)(llvm::make_error<LSPError>("server failed to reply",
345 ErrorCode::InternalError));
Sam McCalle2f3a732018-10-24 14:26:26 +0000346 }
347 }
348
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000349 void operator()(llvm::Expected<llvm::json::Value> Reply) {
Sam McCalle2f3a732018-10-24 14:26:26 +0000350 assert(Server && "moved-from!");
351 if (Replied.exchange(true)) {
352 elog("Replied twice to message {0}({1})", Method, ID);
353 assert(false && "must reply to each call only once!");
354 return;
355 }
Sam McCalld7babe42018-10-24 15:18:40 +0000356 auto Duration = std::chrono::steady_clock::now() - Start;
357 if (Reply) {
358 log("--> reply:{0}({1}) {2:ms}", Method, ID, Duration);
359 if (TraceArgs)
Sam McCalle2f3a732018-10-24 14:26:26 +0000360 (*TraceArgs)["Reply"] = *Reply;
Sam McCalld7babe42018-10-24 15:18:40 +0000361 std::lock_guard<std::mutex> Lock(Server->TranspWriter);
362 Server->Transp.reply(std::move(ID), std::move(Reply));
363 } else {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000364 llvm::Error Err = Reply.takeError();
Sam McCalld7babe42018-10-24 15:18:40 +0000365 log("--> reply:{0}({1}) {2:ms}, error: {3}", Method, ID, Duration, Err);
366 if (TraceArgs)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000367 (*TraceArgs)["Error"] = llvm::to_string(Err);
Sam McCalld7babe42018-10-24 15:18:40 +0000368 std::lock_guard<std::mutex> Lock(Server->TranspWriter);
369 Server->Transp.reply(std::move(ID), std::move(Err));
Sam McCalle2f3a732018-10-24 14:26:26 +0000370 }
Sam McCalle2f3a732018-10-24 14:26:26 +0000371 }
372 };
373
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000374 llvm::StringMap<std::function<void(llvm::json::Value)>> Notifications;
375 llvm::StringMap<std::function<void(llvm::json::Value, ReplyOnce)>> Calls;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000376
377 // Method calls may be cancelled by ID, so keep track of their state.
378 // This needs a mutex: handlers may finish on a different thread, and that's
379 // when we clean up entries in the map.
380 mutable std::mutex RequestCancelersMutex;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000381 llvm::StringMap<std::pair<Canceler, /*Cookie*/ unsigned>> RequestCancelers;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000382 unsigned NextRequestCookie = 0; // To disambiguate reused IDs, see below.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000383 void onCancel(const llvm::json::Value &Params) {
384 const llvm::json::Value *ID = nullptr;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000385 if (auto *O = Params.getAsObject())
386 ID = O->get("id");
387 if (!ID) {
388 elog("Bad cancellation request: {0}", Params);
389 return;
390 }
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000391 auto StrID = llvm::to_string(*ID);
Sam McCall2c30fbc2018-10-18 12:32:04 +0000392 std::lock_guard<std::mutex> Lock(RequestCancelersMutex);
393 auto It = RequestCancelers.find(StrID);
394 if (It != RequestCancelers.end())
395 It->second.first(); // Invoke the canceler.
396 }
Sam McCalla69698f2019-03-27 17:47:49 +0000397
398 Context handlerContext() const {
399 return Context::current().derive(
400 kCurrentOffsetEncoding,
401 Server.NegotiatedOffsetEncoding.getValueOr(OffsetEncoding::UTF16));
402 }
403
Sam McCall2c30fbc2018-10-18 12:32:04 +0000404 // We run cancelable requests in a context that does two things:
405 // - allows cancellation using RequestCancelers[ID]
406 // - cleans up the entry in RequestCancelers when it's no longer needed
407 // If a client reuses an ID, the last wins and the first cannot be canceled.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000408 Context cancelableRequestContext(const llvm::json::Value &ID) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000409 auto Task = cancelableTask();
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000410 auto StrID = llvm::to_string(ID); // JSON-serialize ID for map key.
Sam McCall2c30fbc2018-10-18 12:32:04 +0000411 auto Cookie = NextRequestCookie++; // No lock, only called on main thread.
412 {
413 std::lock_guard<std::mutex> Lock(RequestCancelersMutex);
414 RequestCancelers[StrID] = {std::move(Task.second), Cookie};
415 }
416 // When the request ends, we can clean up the entry we just added.
417 // The cookie lets us check that it hasn't been overwritten due to ID
418 // reuse.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000419 return Task.first.derive(llvm::make_scope_exit([this, StrID, Cookie] {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000420 std::lock_guard<std::mutex> Lock(RequestCancelersMutex);
421 auto It = RequestCancelers.find(StrID);
422 if (It != RequestCancelers.end() && It->second.second == Cookie)
423 RequestCancelers.erase(It);
424 }));
425 }
426
Kadir Cetinkaya9a3a87d2019-10-09 13:59:31 +0000427 // The maximum number of callbacks held in clangd.
428 //
429 // We bound the maximum size to the pending map to prevent memory leakage
430 // for cases where LSP clients don't reply for the request.
431 // This has to go after RequestCancellers and RequestCancellersMutex since it
432 // can contain a callback that has a cancelable context.
433 static constexpr int MaxReplayCallbacks = 100;
434 mutable std::mutex CallMutex;
435 int NextCallID = 0; /* GUARDED_BY(CallMutex) */
436 std::deque<std::pair</*RequestID*/ int,
437 /*ReplyHandler*/ Callback<llvm::json::Value>>>
438 ReplyCallbacks; /* GUARDED_BY(CallMutex) */
439
Sam McCall2c30fbc2018-10-18 12:32:04 +0000440 ClangdLSPServer &Server;
441};
Haojian Wuf2516342019-08-05 12:48:09 +0000442constexpr int ClangdLSPServer::MessageHandler::MaxReplayCallbacks;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000443
444// call(), notify(), and reply() wrap the Transport, adding logging and locking.
Haojian Wuf2516342019-08-05 12:48:09 +0000445void ClangdLSPServer::callRaw(StringRef Method, llvm::json::Value Params,
446 Callback<llvm::json::Value> CB) {
447 auto ID = MsgHandler->bindReply(std::move(CB));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000448 log("--> {0}({1})", Method, ID);
Sam McCall2c30fbc2018-10-18 12:32:04 +0000449 std::lock_guard<std::mutex> Lock(TranspWriter);
450 Transp.call(Method, std::move(Params), ID);
451}
452
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000453void ClangdLSPServer::notify(llvm::StringRef Method, llvm::json::Value Params) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000454 log("--> {0}", Method);
455 std::lock_guard<std::mutex> Lock(TranspWriter);
456 Transp.notify(Method, std::move(Params));
457}
458
Sam McCall2c30fbc2018-10-18 12:32:04 +0000459void ClangdLSPServer::onInitialize(const InitializeParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000460 Callback<llvm::json::Value> Reply) {
Sam McCalla69698f2019-03-27 17:47:49 +0000461 // Determine character encoding first as it affects constructed ClangdServer.
462 if (Params.capabilities.offsetEncoding && !NegotiatedOffsetEncoding) {
463 NegotiatedOffsetEncoding = OffsetEncoding::UTF16; // fallback
464 for (OffsetEncoding Supported : *Params.capabilities.offsetEncoding)
465 if (Supported != OffsetEncoding::UnsupportedEncoding) {
466 NegotiatedOffsetEncoding = Supported;
467 break;
468 }
469 }
Sam McCalla69698f2019-03-27 17:47:49 +0000470
Johan Vikstroma848dab2019-07-04 07:53:12 +0000471 ClangdServerOpts.SemanticHighlighting =
472 Params.capabilities.SemanticHighlighting;
Sam McCall0d9b40f2018-10-19 15:42:23 +0000473 if (Params.rootUri && *Params.rootUri)
474 ClangdServerOpts.WorkspaceRoot = Params.rootUri->file();
475 else if (Params.rootPath && !Params.rootPath->empty())
476 ClangdServerOpts.WorkspaceRoot = *Params.rootPath;
Sam McCall3d0adbe2018-10-18 14:41:50 +0000477 if (Server)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000478 return Reply(llvm::make_error<LSPError>("server already initialized",
479 ErrorCode::InvalidRequest));
Sam McCallbc904612018-10-25 04:22:52 +0000480 if (const auto &Dir = Params.initializationOptions.compilationDatabasePath)
481 CompileCommandsDir = Dir;
Kadir Cetinkaya256247c2019-06-26 07:45:27 +0000482 if (UseDirBasedCDB) {
Jonas Devlieghere1c705d92019-08-14 23:52:23 +0000483 BaseCDB = std::make_unique<DirectoryBasedGlobalCompilationDatabase>(
Sam McCallc55d09a2018-11-02 13:09:36 +0000484 CompileCommandsDir);
Kadir Cetinkaya256247c2019-06-26 07:45:27 +0000485 BaseCDB = getQueryDriverDatabase(
486 llvm::makeArrayRef(ClangdServerOpts.QueryDriverGlobs),
487 std::move(BaseCDB));
488 }
Sam McCall99768b22019-11-29 19:37:48 +0100489 auto Mangler = CommandMangler::detect();
490 if (ClangdServerOpts.ResourceDir)
491 Mangler.ResourceDir = *ClangdServerOpts.ResourceDir;
Kadir Cetinkayabe6b35d2019-01-22 09:10:20 +0000492 CDB.emplace(BaseCDB.get(), Params.initializationOptions.fallbackFlags,
Sam McCall99768b22019-11-29 19:37:48 +0100493 tooling::ArgumentsAdjuster(Mangler));
Kadir Cetinkaya9d662472019-10-15 14:20:52 +0000494 {
495 // Switch caller's context with LSPServer's background context. Since we
496 // rather want to propagate information from LSPServer's context into the
497 // Server, CDB, etc.
498 WithContext MainContext(BackgroundContext.clone());
499 llvm::Optional<WithContextValue> WithOffsetEncoding;
500 if (NegotiatedOffsetEncoding)
501 WithOffsetEncoding.emplace(kCurrentOffsetEncoding,
502 *NegotiatedOffsetEncoding);
Sam McCall6ef1cce2020-01-24 14:08:56 +0100503 Server.emplace(*CDB, FSProvider, ClangdServerOpts,
504 static_cast<ClangdServer::Callbacks *>(this));
Kadir Cetinkaya9d662472019-10-15 14:20:52 +0000505 }
Sam McCallbc904612018-10-25 04:22:52 +0000506 applyConfiguration(Params.initializationOptions.ConfigSettings);
Simon Marchi88016782018-08-01 11:28:49 +0000507
Sam McCallbf6a2fc2018-10-17 07:33:42 +0000508 CCOpts.EnableSnippets = Params.capabilities.CompletionSnippets;
Sam McCall8d412942019-06-18 11:57:26 +0000509 CCOpts.IncludeFixIts = Params.capabilities.CompletionFixes;
Sam McCall5f092e32019-07-08 17:27:15 +0000510 if (!CCOpts.BundleOverloads.hasValue())
511 CCOpts.BundleOverloads = Params.capabilities.HasSignatureHelp;
Sam McCallbf6a2fc2018-10-17 07:33:42 +0000512 DiagOpts.EmbedFixesInDiagnostics = Params.capabilities.DiagnosticFixes;
513 DiagOpts.SendDiagnosticCategory = Params.capabilities.DiagnosticCategory;
Sam McCallc9e4ee92019-04-18 15:17:07 +0000514 DiagOpts.EmitRelatedLocations =
515 Params.capabilities.DiagnosticRelatedInformation;
Sam McCallbf6a2fc2018-10-17 07:33:42 +0000516 if (Params.capabilities.WorkspaceSymbolKinds)
517 SupportedSymbolKinds |= *Params.capabilities.WorkspaceSymbolKinds;
518 if (Params.capabilities.CompletionItemKinds)
519 SupportedCompletionItemKinds |= *Params.capabilities.CompletionItemKinds;
520 SupportsCodeAction = Params.capabilities.CodeActionStructure;
Ilya Biryukov19d75602018-11-23 15:21:19 +0000521 SupportsHierarchicalDocumentSymbol =
522 Params.capabilities.HierarchicalDocumentSymbol;
Haojian Wub6188492018-12-20 15:39:12 +0000523 SupportFileStatus = Params.initializationOptions.FileStatus;
Ilya Biryukovf9169d02019-05-29 10:01:00 +0000524 HoverContentFormat = Params.capabilities.HoverContentFormat;
Ilya Biryukov4ef0f822019-06-04 09:36:59 +0000525 SupportsOffsetsInSignatureHelp = Params.capabilities.OffsetsInSignatureHelp;
Sam McCall7d20e802020-01-22 19:41:45 +0100526 if (Params.capabilities.WorkDoneProgress)
527 BackgroundIndexProgressState = BackgroundIndexProgress::Empty;
528 BackgroundIndexSkipCreate = Params.capabilities.ImplicitProgressCreation;
Haojian Wuf429ab62019-07-24 07:49:23 +0000529
530 // Per LSP, renameProvider can be either boolean or RenameOptions.
531 // RenameOptions will be specified if the client states it supports prepare.
532 llvm::json::Value RenameProvider =
533 llvm::json::Object{{"prepareProvider", true}};
534 if (!Params.capabilities.RenamePrepareSupport) // Only boolean allowed per LSP
535 RenameProvider = true;
536
Haojian Wu08d93f12019-08-22 14:53:45 +0000537 // Per LSP, codeActionProvide can be either boolean or CodeActionOptions.
538 // CodeActionOptions is only valid if the client supports action literal
539 // via textDocument.codeAction.codeActionLiteralSupport.
540 llvm::json::Value CodeActionProvider = true;
541 if (Params.capabilities.CodeActionStructure)
542 CodeActionProvider = llvm::json::Object{
543 {"codeActionKinds",
544 {CodeAction::QUICKFIX_KIND, CodeAction::REFACTOR_KIND,
545 CodeAction::INFO_KIND}}};
546
Sam McCalla69698f2019-03-27 17:47:49 +0000547 llvm::json::Object Result{
Sam McCall0930ab02017-11-07 15:49:35 +0000548 {{"capabilities",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000549 llvm::json::Object{
Simon Marchi98082622018-03-26 14:41:40 +0000550 {"textDocumentSync", (int)TextDocumentSyncKind::Incremental},
Sam McCall0930ab02017-11-07 15:49:35 +0000551 {"documentFormattingProvider", true},
552 {"documentRangeFormattingProvider", true},
553 {"documentOnTypeFormattingProvider",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000554 llvm::json::Object{
Sam McCall25c62572019-06-10 14:26:21 +0000555 {"firstTriggerCharacter", "\n"},
Sam McCall0930ab02017-11-07 15:49:35 +0000556 {"moreTriggerCharacter", {}},
557 }},
Haojian Wu08d93f12019-08-22 14:53:45 +0000558 {"codeActionProvider", std::move(CodeActionProvider)},
Sam McCall0930ab02017-11-07 15:49:35 +0000559 {"completionProvider",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000560 llvm::json::Object{
Sam McCall0930ab02017-11-07 15:49:35 +0000561 {"resolveProvider", false},
Ilya Biryukovb0826bd2019-01-03 13:37:12 +0000562 // We do extra checks for '>' and ':' in completion to only
563 // trigger on '->' and '::'.
Sam McCall0930ab02017-11-07 15:49:35 +0000564 {"triggerCharacters", {".", ">", ":"}},
565 }},
566 {"signatureHelpProvider",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000567 llvm::json::Object{
Sam McCall0930ab02017-11-07 15:49:35 +0000568 {"triggerCharacters", {"(", ","}},
569 }},
Sam McCall866ba2c2019-02-01 11:26:13 +0000570 {"declarationProvider", true},
Sam McCall0930ab02017-11-07 15:49:35 +0000571 {"definitionProvider", true},
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000572 {"documentHighlightProvider", true},
Sam McCall8d7ecc12019-12-16 19:08:51 +0100573 {"documentLinkProvider",
574 llvm::json::Object{
575 {"resolveProvider", false},
576 }},
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000577 {"hoverProvider", true},
Haojian Wuf429ab62019-07-24 07:49:23 +0000578 {"renameProvider", std::move(RenameProvider)},
Utkarsh Saxena55925da2019-09-24 13:38:33 +0000579 {"selectionRangeProvider", true},
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000580 {"documentSymbolProvider", true},
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000581 {"workspaceSymbolProvider", true},
Sam McCall1ad142f2018-09-05 11:53:07 +0000582 {"referencesProvider", true},
Sam McCall0930ab02017-11-07 15:49:35 +0000583 {"executeCommandProvider",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000584 llvm::json::Object{
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000585 {"commands",
586 {ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND,
587 ExecuteCommandParams::CLANGD_APPLY_TWEAK}},
Sam McCall0930ab02017-11-07 15:49:35 +0000588 }},
Kadir Cetinkaya86658022019-03-19 09:27:04 +0000589 {"typeHierarchyProvider", true},
Sam McCalla69698f2019-03-27 17:47:49 +0000590 }}}};
591 if (NegotiatedOffsetEncoding)
592 Result["offsetEncoding"] = *NegotiatedOffsetEncoding;
Johan Vikstroma848dab2019-07-04 07:53:12 +0000593 if (Params.capabilities.SemanticHighlighting)
594 Result.getObject("capabilities")
595 ->insert(
596 {"semanticHighlighting",
Haojian Wu1ca2ee42019-07-04 12:27:21 +0000597 llvm::json::Object{{"scopes", buildHighlightScopeLookupTable()}}});
Sam McCalla69698f2019-03-27 17:47:49 +0000598 Reply(std::move(Result));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000599}
600
Sam McCall2c30fbc2018-10-18 12:32:04 +0000601void ClangdLSPServer::onShutdown(const ShutdownParams &Params,
602 Callback<std::nullptr_t> Reply) {
Ilya Biryukov0d9b8a32017-10-25 08:45:41 +0000603 // Do essentially nothing, just say we're ready to exit.
604 ShutdownRequestReceived = true;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000605 Reply(nullptr);
Sam McCall8a5dded2017-10-12 13:29:58 +0000606}
Ilya Biryukovafb55542017-05-16 14:40:30 +0000607
Sam McCall422c8282018-11-26 16:00:11 +0000608// sync is a clangd extension: it blocks until all background work completes.
609// It blocks the calling thread, so no messages are processed until it returns!
610void ClangdLSPServer::onSync(const NoParams &Params,
611 Callback<std::nullptr_t> Reply) {
612 if (Server->blockUntilIdleForTest(/*TimeoutSeconds=*/60))
613 Reply(nullptr);
614 else
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000615 Reply(llvm::createStringError(llvm::inconvertibleErrorCode(),
616 "Not idle after a minute"));
Sam McCall422c8282018-11-26 16:00:11 +0000617}
618
Sam McCall2c30fbc2018-10-18 12:32:04 +0000619void ClangdLSPServer::onDocumentDidOpen(
620 const DidOpenTextDocumentParams &Params) {
Simon Marchi9569fd52018-03-16 14:30:42 +0000621 PathRef File = Params.textDocument.uri.file();
Ilya Biryukovb10ef472018-06-13 09:20:41 +0000622
Sam McCall2c30fbc2018-10-18 12:32:04 +0000623 const std::string &Contents = Params.textDocument.text;
Simon Marchi9569fd52018-03-16 14:30:42 +0000624
Simon Marchi98082622018-03-26 14:41:40 +0000625 DraftMgr.addDraft(File, Contents);
Ilya Biryukov652364b2018-09-26 05:48:29 +0000626 Server->addDocument(File, Contents, WantDiagnostics::Yes);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000627}
628
Sam McCall2c30fbc2018-10-18 12:32:04 +0000629void ClangdLSPServer::onDocumentDidChange(
630 const DidChangeTextDocumentParams &Params) {
Eric Liu51fed182018-02-22 18:40:39 +0000631 auto WantDiags = WantDiagnostics::Auto;
632 if (Params.wantDiagnostics.hasValue())
633 WantDiags = Params.wantDiagnostics.getValue() ? WantDiagnostics::Yes
634 : WantDiagnostics::No;
Simon Marchi9569fd52018-03-16 14:30:42 +0000635
636 PathRef File = Params.textDocument.uri.file();
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000637 llvm::Expected<std::string> Contents =
Simon Marchi98082622018-03-26 14:41:40 +0000638 DraftMgr.updateDraft(File, Params.contentChanges);
639 if (!Contents) {
640 // If this fails, we are most likely going to be not in sync anymore with
641 // the client. It is better to remove the draft and let further operations
642 // fail rather than giving wrong results.
643 DraftMgr.removeDraft(File);
Ilya Biryukov652364b2018-09-26 05:48:29 +0000644 Server->removeDocument(File);
Sam McCallbed58852018-07-11 10:35:11 +0000645 elog("Failed to update {0}: {1}", File, Contents.takeError());
Simon Marchi98082622018-03-26 14:41:40 +0000646 return;
647 }
Simon Marchi9569fd52018-03-16 14:30:42 +0000648
Ilya Biryukov652364b2018-09-26 05:48:29 +0000649 Server->addDocument(File, *Contents, WantDiags);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000650}
651
Sam McCall2c30fbc2018-10-18 12:32:04 +0000652void ClangdLSPServer::onFileEvent(const DidChangeWatchedFilesParams &Params) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000653 Server->onFileEvent(Params);
Marc-Andre Laperlebf114242017-10-02 18:00:37 +0000654}
655
Sam McCall2c30fbc2018-10-18 12:32:04 +0000656void ClangdLSPServer::onCommand(const ExecuteCommandParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000657 Callback<llvm::json::Value> Reply) {
Ilya Biryukov12864002019-08-16 12:46:41 +0000658 auto ApplyEdit = [this](WorkspaceEdit WE, std::string SuccessMessage,
659 decltype(Reply) Reply) {
Eric Liuc5105f92018-02-16 14:15:55 +0000660 ApplyWorkspaceEditParams Edit;
661 Edit.edit = std::move(WE);
Ilya Biryukov12864002019-08-16 12:46:41 +0000662 call<ApplyWorkspaceEditResponse>(
663 "workspace/applyEdit", std::move(Edit),
664 [Reply = std::move(Reply), SuccessMessage = std::move(SuccessMessage)](
665 llvm::Expected<ApplyWorkspaceEditResponse> Response) mutable {
666 if (!Response)
667 return Reply(Response.takeError());
668 if (!Response->applied) {
669 std::string Reason = Response->failureReason
670 ? *Response->failureReason
671 : "unknown reason";
672 return Reply(llvm::createStringError(
673 llvm::inconvertibleErrorCode(),
674 ("edits were not applied: " + Reason).c_str()));
675 }
676 return Reply(SuccessMessage);
677 });
Eric Liuc5105f92018-02-16 14:15:55 +0000678 };
Ilya Biryukov12864002019-08-16 12:46:41 +0000679
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000680 if (Params.command == ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND &&
681 Params.workspaceEdit) {
682 // The flow for "apply-fix" :
683 // 1. We publish a diagnostic, including fixits
684 // 2. The user clicks on the diagnostic, the editor asks us for code actions
685 // 3. We send code actions, with the fixit embedded as context
686 // 4. The user selects the fixit, the editor asks us to apply it
687 // 5. We unwrap the changes and send them back to the editor
Haojian Wuf2516342019-08-05 12:48:09 +0000688 // 6. The editor applies the changes (applyEdit), and sends us a reply
689 // 7. We unwrap the reply and send a reply to the editor.
Ilya Biryukov12864002019-08-16 12:46:41 +0000690 ApplyEdit(*Params.workspaceEdit, "Fix applied.", std::move(Reply));
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000691 } else if (Params.command == ExecuteCommandParams::CLANGD_APPLY_TWEAK &&
692 Params.tweakArgs) {
693 auto Code = DraftMgr.getDraft(Params.tweakArgs->file.file());
694 if (!Code)
695 return Reply(llvm::createStringError(
696 llvm::inconvertibleErrorCode(),
697 "trying to apply a code action for a non-added file"));
698
Ilya Biryukov12864002019-08-16 12:46:41 +0000699 auto Action = [this, ApplyEdit, Reply = std::move(Reply),
700 File = Params.tweakArgs->file, Code = std::move(*Code)](
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000701 llvm::Expected<Tweak::Effect> R) mutable {
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000702 if (!R)
703 return Reply(R.takeError());
704
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000705 assert(R->ShowMessage ||
706 (!R->ApplyEdits.empty() && "tweak has no effect"));
Ilya Biryukov12864002019-08-16 12:46:41 +0000707
Sam McCall395fde72019-06-18 13:37:54 +0000708 if (R->ShowMessage) {
709 ShowMessageParams Msg;
710 Msg.message = *R->ShowMessage;
711 Msg.type = MessageType::Info;
712 notify("window/showMessage", Msg);
713 }
Ilya Biryukov12864002019-08-16 12:46:41 +0000714 // When no edit is specified, make sure we Reply().
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000715 if (R->ApplyEdits.empty())
716 return Reply("Tweak applied.");
717
Haojian Wu852bafa2019-10-23 14:40:20 +0200718 if (auto Err = validateEdits(DraftMgr, R->ApplyEdits))
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000719 return Reply(std::move(Err));
720
721 WorkspaceEdit WE;
722 WE.changes.emplace();
723 for (const auto &It : R->ApplyEdits) {
Kadir Cetinkayae95e5162019-10-02 09:12:01 +0000724 (*WE.changes)[URI::createFile(It.first()).toString()] =
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000725 It.second.asTextEdits();
726 }
727 // ApplyEdit will take care of calling Reply().
728 return ApplyEdit(std::move(WE), "Tweak applied.", std::move(Reply));
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000729 };
730 Server->applyTweak(Params.tweakArgs->file.file(),
731 Params.tweakArgs->selection, Params.tweakArgs->tweakID,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000732 std::move(Action));
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000733 } else {
734 // We should not get here because ExecuteCommandParams would not have
735 // parsed in the first place and this handler should not be called. But if
736 // more commands are added, this will be here has a safe guard.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000737 Reply(llvm::make_error<LSPError>(
738 llvm::formatv("Unsupported command \"{0}\".", Params.command).str(),
Sam McCall2c30fbc2018-10-18 12:32:04 +0000739 ErrorCode::InvalidParams));
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000740 }
741}
742
Sam McCall2c30fbc2018-10-18 12:32:04 +0000743void ClangdLSPServer::onWorkspaceSymbol(
744 const WorkspaceSymbolParams &Params,
745 Callback<std::vector<SymbolInformation>> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000746 Server->workspaceSymbols(
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000747 Params.query, CCOpts.Limit,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000748 [Reply = std::move(Reply),
749 this](llvm::Expected<std::vector<SymbolInformation>> Items) mutable {
750 if (!Items)
751 return Reply(Items.takeError());
752 for (auto &Sym : *Items)
753 Sym.kind = adjustKindToCapability(Sym.kind, SupportedSymbolKinds);
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000754
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000755 Reply(std::move(*Items));
756 });
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000757}
758
Haojian Wuf429ab62019-07-24 07:49:23 +0000759void ClangdLSPServer::onPrepareRename(const TextDocumentPositionParams &Params,
760 Callback<llvm::Optional<Range>> Reply) {
761 Server->prepareRename(Params.textDocument.uri.file(), Params.position,
762 std::move(Reply));
763}
764
Sam McCall2c30fbc2018-10-18 12:32:04 +0000765void ClangdLSPServer::onRename(const RenameParams &Params,
766 Callback<WorkspaceEdit> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000767 Path File = Params.textDocument.uri.file();
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000768 llvm::Optional<std::string> Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000769 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000770 return Reply(llvm::make_error<LSPError>(
771 "onRename called for non-added file", ErrorCode::InvalidParams));
Haojian Wu852bafa2019-10-23 14:40:20 +0200772 Server->rename(
773 File, Params.position, Params.newName,
774 /*WantFormat=*/true,
775 [File, Params, Reply = std::move(Reply),
776 this](llvm::Expected<FileEdits> Edits) mutable {
777 if (!Edits)
778 return Reply(Edits.takeError());
779 if (auto Err = validateEdits(DraftMgr, *Edits))
780 return Reply(std::move(Err));
781 WorkspaceEdit Result;
782 Result.changes.emplace();
783 for (const auto &Rep : *Edits) {
784 (*Result.changes)[URI::createFile(Rep.first()).toString()] =
785 Rep.second.asTextEdits();
786 }
787 Reply(Result);
788 });
Haojian Wu345099c2017-11-09 11:30:04 +0000789}
790
Sam McCall2c30fbc2018-10-18 12:32:04 +0000791void ClangdLSPServer::onDocumentDidClose(
792 const DidCloseTextDocumentParams &Params) {
Simon Marchi9569fd52018-03-16 14:30:42 +0000793 PathRef File = Params.textDocument.uri.file();
794 DraftMgr.removeDraft(File);
Ilya Biryukov652364b2018-09-26 05:48:29 +0000795 Server->removeDocument(File);
Ilya Biryukov49c10712019-03-25 10:15:11 +0000796
797 {
798 std::lock_guard<std::mutex> Lock(FixItsMutex);
799 FixItsMap.erase(File);
800 }
Johan Vikstromc2653ef22019-08-01 08:08:44 +0000801 {
802 std::lock_guard<std::mutex> HLock(HighlightingsMutex);
803 FileToHighlightings.erase(File);
804 }
Ilya Biryukov49c10712019-03-25 10:15:11 +0000805 // clangd will not send updates for this file anymore, so we empty out the
806 // list of diagnostics shown on the client (e.g. in the "Problems" pane of
807 // VSCode). Note that this cannot race with actual diagnostics responses
808 // because removeDocument() guarantees no diagnostic callbacks will be
809 // executed after it returns.
810 publishDiagnostics(URIForFile::canonicalize(File, /*TUPath=*/File), {});
Ilya Biryukovafb55542017-05-16 14:40:30 +0000811}
812
Sam McCall4db732a2017-09-30 10:08:52 +0000813void ClangdLSPServer::onDocumentOnTypeFormatting(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000814 const DocumentOnTypeFormattingParams &Params,
815 Callback<std::vector<TextEdit>> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000816 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000817 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000818 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000819 return Reply(llvm::make_error<LSPError>(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000820 "onDocumentOnTypeFormatting called for non-added file",
821 ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000822
Sam McCall25c62572019-06-10 14:26:21 +0000823 Reply(Server->formatOnType(*Code, File, Params.position, Params.ch));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000824}
825
Sam McCall4db732a2017-09-30 10:08:52 +0000826void ClangdLSPServer::onDocumentRangeFormatting(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000827 const DocumentRangeFormattingParams &Params,
828 Callback<std::vector<TextEdit>> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000829 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000830 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000831 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000832 return Reply(llvm::make_error<LSPError>(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000833 "onDocumentRangeFormatting called for non-added file",
834 ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000835
Ilya Biryukov652364b2018-09-26 05:48:29 +0000836 auto ReplacementsOrError = Server->formatRange(*Code, File, Params.range);
Raoul Wols212bcf82017-12-12 20:25:06 +0000837 if (ReplacementsOrError)
Sam McCall2c30fbc2018-10-18 12:32:04 +0000838 Reply(replacementsToEdits(*Code, ReplacementsOrError.get()));
Raoul Wols212bcf82017-12-12 20:25:06 +0000839 else
Sam McCall2c30fbc2018-10-18 12:32:04 +0000840 Reply(ReplacementsOrError.takeError());
Ilya Biryukovafb55542017-05-16 14:40:30 +0000841}
842
Sam McCall2c30fbc2018-10-18 12:32:04 +0000843void ClangdLSPServer::onDocumentFormatting(
844 const DocumentFormattingParams &Params,
845 Callback<std::vector<TextEdit>> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000846 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000847 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000848 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000849 return Reply(llvm::make_error<LSPError>(
850 "onDocumentFormatting called for non-added file",
851 ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000852
Ilya Biryukov652364b2018-09-26 05:48:29 +0000853 auto ReplacementsOrError = Server->formatFile(*Code, File);
Raoul Wols212bcf82017-12-12 20:25:06 +0000854 if (ReplacementsOrError)
Sam McCall2c30fbc2018-10-18 12:32:04 +0000855 Reply(replacementsToEdits(*Code, ReplacementsOrError.get()));
Raoul Wols212bcf82017-12-12 20:25:06 +0000856 else
Sam McCall2c30fbc2018-10-18 12:32:04 +0000857 Reply(ReplacementsOrError.takeError());
Sam McCall4db732a2017-09-30 10:08:52 +0000858}
859
Ilya Biryukov19d75602018-11-23 15:21:19 +0000860/// The functions constructs a flattened view of the DocumentSymbol hierarchy.
861/// Used by the clients that do not support the hierarchical view.
862static std::vector<SymbolInformation>
863flattenSymbolHierarchy(llvm::ArrayRef<DocumentSymbol> Symbols,
864 const URIForFile &FileURI) {
865
866 std::vector<SymbolInformation> Results;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000867 std::function<void(const DocumentSymbol &, llvm::StringRef)> Process =
868 [&](const DocumentSymbol &S, llvm::Optional<llvm::StringRef> ParentName) {
Ilya Biryukov19d75602018-11-23 15:21:19 +0000869 SymbolInformation SI;
870 SI.containerName = ParentName ? "" : *ParentName;
871 SI.name = S.name;
872 SI.kind = S.kind;
873 SI.location.range = S.range;
874 SI.location.uri = FileURI;
875
876 Results.push_back(std::move(SI));
877 std::string FullName =
878 !ParentName ? S.name : (ParentName->str() + "::" + S.name);
879 for (auto &C : S.children)
880 Process(C, /*ParentName=*/FullName);
881 };
882 for (auto &S : Symbols)
883 Process(S, /*ParentName=*/"");
884 return Results;
885}
886
887void ClangdLSPServer::onDocumentSymbol(const DocumentSymbolParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000888 Callback<llvm::json::Value> Reply) {
Ilya Biryukov19d75602018-11-23 15:21:19 +0000889 URIForFile FileURI = Params.textDocument.uri;
Ilya Biryukov652364b2018-09-26 05:48:29 +0000890 Server->documentSymbols(
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000891 Params.textDocument.uri.file(),
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000892 [this, FileURI, Reply = std::move(Reply)](
893 llvm::Expected<std::vector<DocumentSymbol>> Items) mutable {
894 if (!Items)
895 return Reply(Items.takeError());
896 adjustSymbolKinds(*Items, SupportedSymbolKinds);
897 if (SupportsHierarchicalDocumentSymbol)
898 return Reply(std::move(*Items));
899 else
900 return Reply(flattenSymbolHierarchy(*Items, FileURI));
901 });
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000902}
903
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000904static llvm::Optional<Command> asCommand(const CodeAction &Action) {
Sam McCall20841d42018-10-16 16:29:41 +0000905 Command Cmd;
906 if (Action.command && Action.edit)
Sam McCallc008af62018-10-20 15:30:37 +0000907 return None; // Not representable. (We never emit these anyway).
Sam McCall20841d42018-10-16 16:29:41 +0000908 if (Action.command) {
909 Cmd = *Action.command;
910 } else if (Action.edit) {
911 Cmd.command = Command::CLANGD_APPLY_FIX_COMMAND;
912 Cmd.workspaceEdit = *Action.edit;
913 } else {
Sam McCallc008af62018-10-20 15:30:37 +0000914 return None;
Sam McCall20841d42018-10-16 16:29:41 +0000915 }
916 Cmd.title = Action.title;
917 if (Action.kind && *Action.kind == CodeAction::QUICKFIX_KIND)
918 Cmd.title = "Apply fix: " + Cmd.title;
919 return Cmd;
920}
921
Sam McCall2c30fbc2018-10-18 12:32:04 +0000922void ClangdLSPServer::onCodeAction(const CodeActionParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000923 Callback<llvm::json::Value> Reply) {
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000924 URIForFile File = Params.textDocument.uri;
925 auto Code = DraftMgr.getDraft(File.file());
Sam McCall2c30fbc2018-10-18 12:32:04 +0000926 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000927 return Reply(llvm::make_error<LSPError>(
928 "onCodeAction called for non-added file", ErrorCode::InvalidParams));
Sam McCall20841d42018-10-16 16:29:41 +0000929 // We provide a code action for Fixes on the specified diagnostics.
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000930 std::vector<CodeAction> FixIts;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000931 for (const Diagnostic &D : Params.context.diagnostics) {
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000932 for (auto &F : getFixes(File.file(), D)) {
933 FixIts.push_back(toCodeAction(F, Params.textDocument.uri));
934 FixIts.back().diagnostics = {D};
Sam McCalldd0566b2017-11-06 15:40:30 +0000935 }
Ilya Biryukovafb55542017-05-16 14:40:30 +0000936 }
Sam McCall20841d42018-10-16 16:29:41 +0000937
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000938 // Now enumerate the semantic code actions.
939 auto ConsumeActions =
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000940 [Reply = std::move(Reply), File, Code = std::move(*Code),
941 Selection = Params.range, FixIts = std::move(FixIts), this](
942 llvm::Expected<std::vector<ClangdServer::TweakRef>> Tweaks) mutable {
Ilya Biryukovc6ed7782019-01-30 14:24:17 +0000943 if (!Tweaks)
944 return Reply(Tweaks.takeError());
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000945
946 std::vector<CodeAction> Actions = std::move(FixIts);
947 Actions.reserve(Actions.size() + Tweaks->size());
948 for (const auto &T : *Tweaks)
949 Actions.push_back(toCodeAction(T, File, Selection));
950
951 if (SupportsCodeAction)
952 return Reply(llvm::json::Array(Actions));
953 std::vector<Command> Commands;
954 for (const auto &Action : Actions) {
955 if (auto Command = asCommand(Action))
956 Commands.push_back(std::move(*Command));
957 }
958 return Reply(llvm::json::Array(Commands));
959 };
960
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000961 Server->enumerateTweaks(File.file(), Params.range, std::move(ConsumeActions));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000962}
963
Ilya Biryukovb0826bd2019-01-03 13:37:12 +0000964void ClangdLSPServer::onCompletion(const CompletionParams &Params,
Sam McCall2c30fbc2018-10-18 12:32:04 +0000965 Callback<CompletionList> Reply) {
Ilya Biryukova7a11472019-06-07 16:24:38 +0000966 if (!shouldRunCompletion(Params)) {
967 // Clients sometimes auto-trigger completions in undesired places (e.g.
968 // 'a >^ '), we return empty results in those cases.
969 vlog("ignored auto-triggered completion, preceding char did not match");
970 return Reply(CompletionList());
971 }
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000972 Server->codeComplete(Params.textDocument.uri.file(), Params.position, CCOpts,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000973 [Reply = std::move(Reply),
974 this](llvm::Expected<CodeCompleteResult> List) mutable {
975 if (!List)
976 return Reply(List.takeError());
977 CompletionList LSPList;
978 LSPList.isIncomplete = List->HasMore;
979 for (const auto &R : List->Completions) {
980 CompletionItem C = R.render(CCOpts);
981 C.kind = adjustKindToCapability(
982 C.kind, SupportedCompletionItemKinds);
983 LSPList.items.push_back(std::move(C));
984 }
985 return Reply(std::move(LSPList));
986 });
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000987}
988
Sam McCall2c30fbc2018-10-18 12:32:04 +0000989void ClangdLSPServer::onSignatureHelp(const TextDocumentPositionParams &Params,
990 Callback<SignatureHelp> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000991 Server->signatureHelp(Params.textDocument.uri.file(), Params.position,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000992 [Reply = std::move(Reply), this](
993 llvm::Expected<SignatureHelp> Signature) mutable {
994 if (!Signature)
995 return Reply(Signature.takeError());
996 if (SupportsOffsetsInSignatureHelp)
997 return Reply(std::move(*Signature));
998 // Strip out the offsets from signature help for
999 // clients that only support string labels.
1000 for (auto &SigInfo : Signature->signatures) {
1001 for (auto &Param : SigInfo.parameters)
1002 Param.labelOffsets.reset();
1003 }
1004 return Reply(std::move(*Signature));
1005 });
Ilya Biryukov652364b2018-09-26 05:48:29 +00001006}
1007
Sam McCall0dbab7f2019-02-02 05:56:00 +00001008// Go to definition has a toggle function: if def and decl are distinct, then
1009// the first press gives you the def, the second gives you the matching def.
1010// getToggle() returns the counterpart location that under the cursor.
1011//
1012// We return the toggled location alone (ignoring other symbols) to encourage
1013// editors to "bounce" quickly between locations, without showing a menu.
1014static Location *getToggle(const TextDocumentPositionParams &Point,
1015 LocatedSymbol &Sym) {
1016 // Toggle only makes sense with two distinct locations.
1017 if (!Sym.Definition || *Sym.Definition == Sym.PreferredDeclaration)
1018 return nullptr;
1019 if (Sym.Definition->uri.file() == Point.textDocument.uri.file() &&
1020 Sym.Definition->range.contains(Point.position))
1021 return &Sym.PreferredDeclaration;
1022 if (Sym.PreferredDeclaration.uri.file() == Point.textDocument.uri.file() &&
1023 Sym.PreferredDeclaration.range.contains(Point.position))
1024 return &*Sym.Definition;
1025 return nullptr;
1026}
1027
Sam McCall2c30fbc2018-10-18 12:32:04 +00001028void ClangdLSPServer::onGoToDefinition(const TextDocumentPositionParams &Params,
1029 Callback<std::vector<Location>> Reply) {
Sam McCall866ba2c2019-02-01 11:26:13 +00001030 Server->locateSymbolAt(
1031 Params.textDocument.uri.file(), Params.position,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001032 [Params, Reply = std::move(Reply)](
1033 llvm::Expected<std::vector<LocatedSymbol>> Symbols) mutable {
1034 if (!Symbols)
1035 return Reply(Symbols.takeError());
1036 std::vector<Location> Defs;
1037 for (auto &S : *Symbols) {
1038 if (Location *Toggle = getToggle(Params, S))
1039 return Reply(std::vector<Location>{std::move(*Toggle)});
1040 Defs.push_back(S.Definition.getValueOr(S.PreferredDeclaration));
1041 }
1042 Reply(std::move(Defs));
1043 });
Sam McCall866ba2c2019-02-01 11:26:13 +00001044}
1045
1046void ClangdLSPServer::onGoToDeclaration(
1047 const TextDocumentPositionParams &Params,
1048 Callback<std::vector<Location>> Reply) {
1049 Server->locateSymbolAt(
1050 Params.textDocument.uri.file(), Params.position,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001051 [Params, Reply = std::move(Reply)](
1052 llvm::Expected<std::vector<LocatedSymbol>> Symbols) mutable {
1053 if (!Symbols)
1054 return Reply(Symbols.takeError());
1055 std::vector<Location> Decls;
1056 for (auto &S : *Symbols) {
1057 if (Location *Toggle = getToggle(Params, S))
1058 return Reply(std::vector<Location>{std::move(*Toggle)});
1059 Decls.push_back(std::move(S.PreferredDeclaration));
1060 }
1061 Reply(std::move(Decls));
1062 });
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +00001063}
1064
Sam McCall111fe842019-05-07 07:55:35 +00001065void ClangdLSPServer::onSwitchSourceHeader(
1066 const TextDocumentIdentifier &Params,
Sam McCallb9ec3e92019-05-07 08:30:32 +00001067 Callback<llvm::Optional<URIForFile>> Reply) {
Haojian Wud6d5edd2019-10-01 10:21:15 +00001068 Server->switchSourceHeader(
1069 Params.uri.file(),
1070 [Reply = std::move(Reply),
1071 Params](llvm::Expected<llvm::Optional<clangd::Path>> Path) mutable {
1072 if (!Path)
1073 return Reply(Path.takeError());
1074 if (*Path)
Haojian Wu77c97002019-10-07 11:37:25 +00001075 return Reply(URIForFile::canonicalize(**Path, Params.uri.file()));
Haojian Wud6d5edd2019-10-01 10:21:15 +00001076 return Reply(llvm::None);
1077 });
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +00001078}
1079
Sam McCall2c30fbc2018-10-18 12:32:04 +00001080void ClangdLSPServer::onDocumentHighlight(
1081 const TextDocumentPositionParams &Params,
1082 Callback<std::vector<DocumentHighlight>> Reply) {
1083 Server->findDocumentHighlights(Params.textDocument.uri.file(),
1084 Params.position, std::move(Reply));
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +00001085}
1086
Sam McCall2c30fbc2018-10-18 12:32:04 +00001087void ClangdLSPServer::onHover(const TextDocumentPositionParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001088 Callback<llvm::Optional<Hover>> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +00001089 Server->findHover(Params.textDocument.uri.file(), Params.position,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001090 [Reply = std::move(Reply), this](
1091 llvm::Expected<llvm::Optional<HoverInfo>> H) mutable {
1092 if (!H)
1093 return Reply(H.takeError());
1094 if (!*H)
1095 return Reply(llvm::None);
Ilya Biryukovf9169d02019-05-29 10:01:00 +00001096
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001097 Hover R;
1098 R.contents.kind = HoverContentFormat;
1099 R.range = (*H)->SymRange;
1100 switch (HoverContentFormat) {
1101 case MarkupKind::PlainText:
Kadir Cetinkaya597c6b62019-12-10 10:28:37 +01001102 R.contents.value = (*H)->present().asPlainText();
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001103 return Reply(std::move(R));
1104 case MarkupKind::Markdown:
Kadir Cetinkaya597c6b62019-12-10 10:28:37 +01001105 R.contents.value = (*H)->present().asMarkdown();
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001106 return Reply(std::move(R));
1107 };
1108 llvm_unreachable("unhandled MarkupKind");
1109 });
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +00001110}
1111
Kadir Cetinkaya86658022019-03-19 09:27:04 +00001112void ClangdLSPServer::onTypeHierarchy(
1113 const TypeHierarchyParams &Params,
1114 Callback<Optional<TypeHierarchyItem>> Reply) {
1115 Server->typeHierarchy(Params.textDocument.uri.file(), Params.position,
1116 Params.resolve, Params.direction, std::move(Reply));
1117}
1118
Nathan Ridge087b0442019-07-13 03:24:48 +00001119void ClangdLSPServer::onResolveTypeHierarchy(
1120 const ResolveTypeHierarchyItemParams &Params,
1121 Callback<Optional<TypeHierarchyItem>> Reply) {
1122 Server->resolveTypeHierarchy(Params.item, Params.resolve, Params.direction,
1123 std::move(Reply));
1124}
1125
Simon Marchi88016782018-08-01 11:28:49 +00001126void ClangdLSPServer::applyConfiguration(
Sam McCallbc904612018-10-25 04:22:52 +00001127 const ConfigurationSettings &Settings) {
Simon Marchiabeed662018-10-16 15:55:03 +00001128 // Per-file update to the compilation database.
Sam McCallbc904612018-10-25 04:22:52 +00001129 bool ShouldReparseOpenFiles = false;
1130 for (auto &Entry : Settings.compilationDatabaseChanges) {
1131 /// The opened files need to be reparsed only when some existing
1132 /// entries are changed.
1133 PathRef File = Entry.first;
Sam McCallc55d09a2018-11-02 13:09:36 +00001134 auto Old = CDB->getCompileCommand(File);
1135 auto New =
1136 tooling::CompileCommand(std::move(Entry.second.workingDirectory), File,
1137 std::move(Entry.second.compilationCommand),
1138 /*Output=*/"");
Sam McCall6980edb2018-11-02 14:07:51 +00001139 if (Old != New) {
Sam McCallc55d09a2018-11-02 13:09:36 +00001140 CDB->setCompileCommand(File, std::move(New));
Sam McCall6980edb2018-11-02 14:07:51 +00001141 ShouldReparseOpenFiles = true;
1142 }
Alex Lorenzf8087862018-08-01 17:39:29 +00001143 }
Sam McCallbc904612018-10-25 04:22:52 +00001144 if (ShouldReparseOpenFiles)
1145 reparseOpenedFiles();
Simon Marchi5178f922018-02-22 14:00:39 +00001146}
1147
Johan Vikstroma848dab2019-07-04 07:53:12 +00001148void ClangdLSPServer::publishSemanticHighlighting(
1149 SemanticHighlightingParams Params) {
1150 notify("textDocument/semanticHighlighting", Params);
1151}
1152
Ilya Biryukov49c10712019-03-25 10:15:11 +00001153void ClangdLSPServer::publishDiagnostics(
1154 const URIForFile &File, std::vector<clangd::Diagnostic> Diagnostics) {
1155 // Publish diagnostics.
1156 notify("textDocument/publishDiagnostics",
1157 llvm::json::Object{
1158 {"uri", File},
1159 {"diagnostics", std::move(Diagnostics)},
1160 });
1161}
1162
Simon Marchi88016782018-08-01 11:28:49 +00001163// FIXME: This function needs to be properly tested.
1164void ClangdLSPServer::onChangeConfiguration(
Sam McCall2c30fbc2018-10-18 12:32:04 +00001165 const DidChangeConfigurationParams &Params) {
Simon Marchi88016782018-08-01 11:28:49 +00001166 applyConfiguration(Params.settings);
1167}
1168
Sam McCall2c30fbc2018-10-18 12:32:04 +00001169void ClangdLSPServer::onReference(const ReferenceParams &Params,
1170 Callback<std::vector<Location>> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +00001171 Server->findReferences(Params.textDocument.uri.file(), Params.position,
Haojian Wu5181ada2019-11-18 11:35:00 +01001172 CCOpts.Limit,
1173 [Reply = std::move(Reply)](
1174 llvm::Expected<ReferencesResult> Refs) mutable {
1175 if (!Refs)
1176 return Reply(Refs.takeError());
1177 return Reply(std::move(Refs->References));
1178 });
Sam McCall1ad142f2018-09-05 11:53:07 +00001179}
1180
Jan Korousb4067012018-11-27 16:40:46 +00001181void ClangdLSPServer::onSymbolInfo(const TextDocumentPositionParams &Params,
1182 Callback<std::vector<SymbolDetails>> Reply) {
1183 Server->symbolInfo(Params.textDocument.uri.file(), Params.position,
1184 std::move(Reply));
1185}
1186
Utkarsh Saxena55925da2019-09-24 13:38:33 +00001187void ClangdLSPServer::onSelectionRange(
1188 const SelectionRangeParams &Params,
1189 Callback<std::vector<SelectionRange>> Reply) {
1190 if (Params.positions.size() != 1) {
1191 elog("{0} positions provided to SelectionRange. Supports exactly one "
1192 "position.",
1193 Params.positions.size());
1194 return Reply(llvm::make_error<LSPError>(
1195 "SelectionRange supports exactly one position",
1196 ErrorCode::InvalidRequest));
1197 }
1198 Server->semanticRanges(
1199 Params.textDocument.uri.file(), Params.positions[0],
1200 [Reply = std::move(Reply)](
1201 llvm::Expected<std::vector<Range>> Ranges) mutable {
1202 if (!Ranges) {
1203 return Reply(Ranges.takeError());
1204 }
1205 std::vector<SelectionRange> Result;
1206 Result.emplace_back(render(std::move(*Ranges)));
1207 return Reply(std::move(Result));
1208 });
1209}
1210
Sam McCall8d7ecc12019-12-16 19:08:51 +01001211void ClangdLSPServer::onDocumentLink(
1212 const DocumentLinkParams &Params,
1213 Callback<std::vector<DocumentLink>> Reply) {
1214
1215 // TODO(forster): This currently resolves all targets eagerly. This is slow,
1216 // because it blocks on the preamble/AST being built. We could respond to the
1217 // request faster by using string matching or the lexer to find the includes
1218 // and resolving the targets lazily.
1219 Server->documentLinks(
1220 Params.textDocument.uri.file(),
1221 [Reply = std::move(Reply)](
1222 llvm::Expected<std::vector<DocumentLink>> Links) mutable {
1223 if (!Links) {
1224 return Reply(Links.takeError());
1225 }
1226 return Reply(std::move(Links));
1227 });
1228}
1229
Sam McCalla69698f2019-03-27 17:47:49 +00001230ClangdLSPServer::ClangdLSPServer(
1231 class Transport &Transp, const FileSystemProvider &FSProvider,
1232 const clangd::CodeCompleteOptions &CCOpts,
1233 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),
1238 CCOpts(CCOpts), SupportedSymbolKinds(defaultSymbolKinds()),
Kadir Cetinkaya133d46f2018-09-27 17:13:07 +00001239 SupportedCompletionItemKinds(defaultCompletionItemKinds()),
Sam McCallc55d09a2018-11-02 13:09:36 +00001240 UseDirBasedCDB(UseDirBasedCDB),
Sam McCalla69698f2019-03-27 17:47:49 +00001241 CompileCommandsDir(std::move(CompileCommandsDir)), ClangdServerOpts(Opts),
1242 NegotiatedOffsetEncoding(ForcedOffsetEncoding) {
Sam McCall2c30fbc2018-10-18 12:32:04 +00001243 // clang-format off
1244 MsgHandler->bind("initialize", &ClangdLSPServer::onInitialize);
1245 MsgHandler->bind("shutdown", &ClangdLSPServer::onShutdown);
Sam McCall422c8282018-11-26 16:00:11 +00001246 MsgHandler->bind("sync", &ClangdLSPServer::onSync);
Sam McCall2c30fbc2018-10-18 12:32:04 +00001247 MsgHandler->bind("textDocument/rangeFormatting", &ClangdLSPServer::onDocumentRangeFormatting);
1248 MsgHandler->bind("textDocument/onTypeFormatting", &ClangdLSPServer::onDocumentOnTypeFormatting);
1249 MsgHandler->bind("textDocument/formatting", &ClangdLSPServer::onDocumentFormatting);
1250 MsgHandler->bind("textDocument/codeAction", &ClangdLSPServer::onCodeAction);
1251 MsgHandler->bind("textDocument/completion", &ClangdLSPServer::onCompletion);
1252 MsgHandler->bind("textDocument/signatureHelp", &ClangdLSPServer::onSignatureHelp);
1253 MsgHandler->bind("textDocument/definition", &ClangdLSPServer::onGoToDefinition);
Sam McCall866ba2c2019-02-01 11:26:13 +00001254 MsgHandler->bind("textDocument/declaration", &ClangdLSPServer::onGoToDeclaration);
Sam McCall2c30fbc2018-10-18 12:32:04 +00001255 MsgHandler->bind("textDocument/references", &ClangdLSPServer::onReference);
1256 MsgHandler->bind("textDocument/switchSourceHeader", &ClangdLSPServer::onSwitchSourceHeader);
Haojian Wuf429ab62019-07-24 07:49:23 +00001257 MsgHandler->bind("textDocument/prepareRename", &ClangdLSPServer::onPrepareRename);
Sam McCall2c30fbc2018-10-18 12:32:04 +00001258 MsgHandler->bind("textDocument/rename", &ClangdLSPServer::onRename);
1259 MsgHandler->bind("textDocument/hover", &ClangdLSPServer::onHover);
1260 MsgHandler->bind("textDocument/documentSymbol", &ClangdLSPServer::onDocumentSymbol);
1261 MsgHandler->bind("workspace/executeCommand", &ClangdLSPServer::onCommand);
1262 MsgHandler->bind("textDocument/documentHighlight", &ClangdLSPServer::onDocumentHighlight);
1263 MsgHandler->bind("workspace/symbol", &ClangdLSPServer::onWorkspaceSymbol);
1264 MsgHandler->bind("textDocument/didOpen", &ClangdLSPServer::onDocumentDidOpen);
1265 MsgHandler->bind("textDocument/didClose", &ClangdLSPServer::onDocumentDidClose);
1266 MsgHandler->bind("textDocument/didChange", &ClangdLSPServer::onDocumentDidChange);
1267 MsgHandler->bind("workspace/didChangeWatchedFiles", &ClangdLSPServer::onFileEvent);
1268 MsgHandler->bind("workspace/didChangeConfiguration", &ClangdLSPServer::onChangeConfiguration);
Jan Korousb4067012018-11-27 16:40:46 +00001269 MsgHandler->bind("textDocument/symbolInfo", &ClangdLSPServer::onSymbolInfo);
Kadir Cetinkaya86658022019-03-19 09:27:04 +00001270 MsgHandler->bind("textDocument/typeHierarchy", &ClangdLSPServer::onTypeHierarchy);
Nathan Ridge087b0442019-07-13 03:24:48 +00001271 MsgHandler->bind("typeHierarchy/resolve", &ClangdLSPServer::onResolveTypeHierarchy);
Utkarsh Saxena55925da2019-09-24 13:38:33 +00001272 MsgHandler->bind("textDocument/selectionRange", &ClangdLSPServer::onSelectionRange);
Sam McCall8d7ecc12019-12-16 19:08:51 +01001273 MsgHandler->bind("textDocument/documentLink", &ClangdLSPServer::onDocumentLink);
Sam McCall2c30fbc2018-10-18 12:32:04 +00001274 // clang-format on
1275}
1276
Sam McCall8bda5f22019-10-23 11:11:18 +02001277ClangdLSPServer::~ClangdLSPServer() { IsBeingDestroyed = true;
1278 // Explicitly destroy ClangdServer first, blocking on threads it owns.
1279 // This ensures they don't access any other members.
1280 Server.reset();
1281}
Ilya Biryukov38d79772017-05-16 09:38:59 +00001282
Sam McCalldc8f3cf2018-10-17 07:32:05 +00001283bool ClangdLSPServer::run() {
Ilya Biryukovafb55542017-05-16 14:40:30 +00001284 // Run the Language Server loop.
Sam McCalldc8f3cf2018-10-17 07:32:05 +00001285 bool CleanExit = true;
Sam McCall2c30fbc2018-10-18 12:32:04 +00001286 if (auto Err = Transp.loop(*MsgHandler)) {
Sam McCalldc8f3cf2018-10-17 07:32:05 +00001287 elog("Transport error: {0}", std::move(Err));
1288 CleanExit = false;
1289 }
Ilya Biryukovafb55542017-05-16 14:40:30 +00001290
Sam McCalldc8f3cf2018-10-17 07:32:05 +00001291 return CleanExit && ShutdownRequestReceived;
Ilya Biryukov38d79772017-05-16 09:38:59 +00001292}
1293
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001294std::vector<Fix> ClangdLSPServer::getFixes(llvm::StringRef File,
Ilya Biryukov71028b82018-03-12 15:28:22 +00001295 const clangd::Diagnostic &D) {
Ilya Biryukov38d79772017-05-16 09:38:59 +00001296 std::lock_guard<std::mutex> Lock(FixItsMutex);
1297 auto DiagToFixItsIter = FixItsMap.find(File);
1298 if (DiagToFixItsIter == FixItsMap.end())
1299 return {};
1300
1301 const auto &DiagToFixItsMap = DiagToFixItsIter->second;
1302 auto FixItsIter = DiagToFixItsMap.find(D);
1303 if (FixItsIter == DiagToFixItsMap.end())
1304 return {};
1305
1306 return FixItsIter->second;
1307}
1308
Ilya Biryukovb0826bd2019-01-03 13:37:12 +00001309bool ClangdLSPServer::shouldRunCompletion(
1310 const CompletionParams &Params) const {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001311 llvm::StringRef Trigger = Params.context.triggerCharacter;
Ilya Biryukovb0826bd2019-01-03 13:37:12 +00001312 if (Params.context.triggerKind != CompletionTriggerKind::TriggerCharacter ||
1313 (Trigger != ">" && Trigger != ":"))
1314 return true;
1315
1316 auto Code = DraftMgr.getDraft(Params.textDocument.uri.file());
1317 if (!Code)
1318 return true; // completion code will log the error for untracked doc.
1319
1320 // A completion request is sent when the user types '>' or ':', but we only
1321 // want to trigger on '->' and '::'. We check the preceeding character to make
1322 // sure it matches what we expected.
1323 // Running the lexer here would be more robust (e.g. we can detect comments
1324 // and avoid triggering completion there), but we choose to err on the side
1325 // of simplicity here.
1326 auto Offset = positionToOffset(*Code, Params.position,
1327 /*AllowColumnsBeyondLineLength=*/false);
1328 if (!Offset) {
1329 vlog("could not convert position '{0}' to offset for file '{1}'",
1330 Params.position, Params.textDocument.uri.file());
1331 return true;
1332 }
1333 if (*Offset < 2)
1334 return false;
1335
1336 if (Trigger == ">")
1337 return (*Code)[*Offset - 2] == '-'; // trigger only on '->'.
1338 if (Trigger == ":")
1339 return (*Code)[*Offset - 2] == ':'; // trigger only on '::'.
1340 assert(false && "unhandled trigger character");
1341 return true;
1342}
1343
Johan Vikstroma848dab2019-07-04 07:53:12 +00001344void ClangdLSPServer::onHighlightingsReady(
Haojian Wu0a6000f2019-08-26 08:38:45 +00001345 PathRef File, std::vector<HighlightingToken> Highlightings) {
Johan Vikstromc2653ef22019-08-01 08:08:44 +00001346 std::vector<HighlightingToken> Old;
1347 std::vector<HighlightingToken> HighlightingsCopy = Highlightings;
1348 {
1349 std::lock_guard<std::mutex> Lock(HighlightingsMutex);
1350 Old = std::move(FileToHighlightings[File]);
1351 FileToHighlightings[File] = std::move(HighlightingsCopy);
1352 }
1353 // LSP allows us to send incremental edits of highlightings. Also need to diff
1354 // to remove highlightings from tokens that should no longer have them.
Haojian Wu0a6000f2019-08-26 08:38:45 +00001355 std::vector<LineHighlightings> Diffed = diffHighlightings(Highlightings, Old);
Johan Vikstroma848dab2019-07-04 07:53:12 +00001356 publishSemanticHighlighting(
1357 {{URIForFile::canonicalize(File, /*TUPath=*/File)},
Johan Vikstromc2653ef22019-08-01 08:08:44 +00001358 toSemanticHighlightingInformation(Diffed)});
Johan Vikstroma848dab2019-07-04 07:53:12 +00001359}
1360
Sam McCalla7bb0cc2018-03-12 23:22:35 +00001361void ClangdLSPServer::onDiagnosticsReady(PathRef File,
1362 std::vector<Diag> Diagnostics) {
Eric Liu4d814a92018-11-28 10:30:42 +00001363 auto URI = URIForFile::canonicalize(File, /*TUPath=*/File);
Sam McCall16e70702018-10-24 07:59:38 +00001364 std::vector<Diagnostic> LSPDiagnostics;
Ilya Biryukov38d79772017-05-16 09:38:59 +00001365 DiagnosticToReplacementMap LocalFixIts; // Temporary storage
Sam McCalla7bb0cc2018-03-12 23:22:35 +00001366 for (auto &Diag : Diagnostics) {
Sam McCall16e70702018-10-24 07:59:38 +00001367 toLSPDiags(Diag, URI, DiagOpts,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001368 [&](clangd::Diagnostic Diag, llvm::ArrayRef<Fix> Fixes) {
Sam McCall16e70702018-10-24 07:59:38 +00001369 auto &FixItsForDiagnostic = LocalFixIts[Diag];
1370 llvm::copy(Fixes, std::back_inserter(FixItsForDiagnostic));
1371 LSPDiagnostics.push_back(std::move(Diag));
1372 });
Ilya Biryukov38d79772017-05-16 09:38:59 +00001373 }
1374
1375 // Cache FixIts
1376 {
Ilya Biryukov38d79772017-05-16 09:38:59 +00001377 std::lock_guard<std::mutex> Lock(FixItsMutex);
1378 FixItsMap[File] = LocalFixIts;
1379 }
1380
Ilya Biryukov49c10712019-03-25 10:15:11 +00001381 // Send a notification to the LSP client.
1382 publishDiagnostics(URI, std::move(LSPDiagnostics));
Ilya Biryukov38d79772017-05-16 09:38:59 +00001383}
Simon Marchi9569fd52018-03-16 14:30:42 +00001384
Sam McCall7d20e802020-01-22 19:41:45 +01001385void ClangdLSPServer::onBackgroundIndexProgress(
1386 const BackgroundQueue::Stats &Stats) {
1387 static const char ProgressToken[] = "backgroundIndexProgress";
1388 std::lock_guard<std::mutex> Lock(BackgroundIndexProgressMutex);
1389
1390 auto NotifyProgress = [this](const BackgroundQueue::Stats &Stats) {
1391 if (BackgroundIndexProgressState != BackgroundIndexProgress::Live) {
1392 WorkDoneProgressBegin Begin;
1393 Begin.percentage = true;
1394 Begin.title = "indexing";
1395 progress(ProgressToken, std::move(Begin));
1396 BackgroundIndexProgressState = BackgroundIndexProgress::Live;
1397 }
1398
1399 if (Stats.Completed < Stats.Enqueued) {
1400 assert(Stats.Enqueued > Stats.LastIdle);
1401 WorkDoneProgressReport Report;
1402 Report.percentage = 100.0 * (Stats.Completed - Stats.LastIdle) /
1403 (Stats.Enqueued - Stats.LastIdle);
1404 Report.message =
1405 llvm::formatv("{0}/{1}", Stats.Completed - Stats.LastIdle,
1406 Stats.Enqueued - Stats.LastIdle);
1407 progress(ProgressToken, std::move(Report));
1408 } else {
1409 assert(Stats.Completed == Stats.Enqueued);
1410 progress(ProgressToken, WorkDoneProgressEnd());
1411 BackgroundIndexProgressState = BackgroundIndexProgress::Empty;
1412 }
1413 };
1414
1415 switch (BackgroundIndexProgressState) {
1416 case BackgroundIndexProgress::Unsupported:
1417 return;
1418 case BackgroundIndexProgress::Creating:
1419 // Cache this update for when the progress bar is available.
1420 PendingBackgroundIndexProgress = Stats;
1421 return;
1422 case BackgroundIndexProgress::Empty: {
1423 if (BackgroundIndexSkipCreate) {
1424 NotifyProgress(Stats);
1425 break;
1426 }
1427 // Cache this update for when the progress bar is available.
1428 PendingBackgroundIndexProgress = Stats;
1429 BackgroundIndexProgressState = BackgroundIndexProgress::Creating;
1430 WorkDoneProgressCreateParams CreateRequest;
1431 CreateRequest.token = ProgressToken;
1432 call<std::nullptr_t>(
1433 "window/workDoneProgress/create", CreateRequest,
1434 [this, NotifyProgress](llvm::Expected<std::nullptr_t> E) {
1435 std::lock_guard<std::mutex> Lock(BackgroundIndexProgressMutex);
1436 if (E) {
1437 NotifyProgress(this->PendingBackgroundIndexProgress);
1438 } else {
1439 elog("Failed to create background index progress bar: {0}",
1440 E.takeError());
1441 // give up forever rather than thrashing about
1442 BackgroundIndexProgressState = BackgroundIndexProgress::Unsupported;
1443 }
1444 });
1445 break;
1446 }
1447 case BackgroundIndexProgress::Live:
1448 NotifyProgress(Stats);
1449 break;
1450 }
1451}
1452
Haojian Wub6188492018-12-20 15:39:12 +00001453void ClangdLSPServer::onFileUpdated(PathRef File, const TUStatus &Status) {
1454 if (!SupportFileStatus)
1455 return;
1456 // FIXME: we don't emit "BuildingFile" and `RunningAction`, as these
1457 // two statuses are running faster in practice, which leads the UI constantly
1458 // changing, and doesn't provide much value. We may want to emit status at a
1459 // reasonable time interval (e.g. 0.5s).
1460 if (Status.Action.S == TUAction::BuildingFile ||
1461 Status.Action.S == TUAction::RunningAction)
1462 return;
1463 notify("textDocument/clangd.fileStatus", Status.render(File));
1464}
1465
Simon Marchi9569fd52018-03-16 14:30:42 +00001466void ClangdLSPServer::reparseOpenedFiles() {
1467 for (const Path &FilePath : DraftMgr.getActiveFiles())
Ilya Biryukov652364b2018-09-26 05:48:29 +00001468 Server->addDocument(FilePath, *DraftMgr.getDraft(FilePath),
1469 WantDiagnostics::Auto);
Simon Marchi9569fd52018-03-16 14:30:42 +00001470}
Alex Lorenzf8087862018-08-01 17:39:29 +00001471
Sam McCallc008af62018-10-20 15:30:37 +00001472} // namespace clangd
1473} // namespace clang