blob: 4dc3412538abb847b178a31eff00bc9575bc2cbc [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"
Ilya Biryukov71028b82018-03-12 15:28:22 +000010#include "Diagnostics.h"
Kadir Cetinkaya5b270932019-09-09 12:28:44 +000011#include "DraftStore.h"
Ilya Biryukovf9169d02019-05-29 10:01:00 +000012#include "FormattedString.h"
Kadir Cetinkaya256247c2019-06-26 07:45:27 +000013#include "GlobalCompilationDatabase.h"
Ilya Biryukovcce67a32019-01-29 14:17:36 +000014#include "Protocol.h"
Johan Vikstroma848dab2019-07-04 07:53:12 +000015#include "SemanticHighlighting.h"
Sam McCallb536a2a2017-12-19 12:23:48 +000016#include "SourceCode.h"
Sam McCall2c30fbc2018-10-18 12:32:04 +000017#include "Trace.h"
Eric Liu78ed91a72018-01-29 15:37:46 +000018#include "URI.h"
Sam McCall395fde72019-06-18 13:37:54 +000019#include "refactor/Tweak.h"
Ilya Biryukovcce67a32019-01-29 14:17:36 +000020#include "clang/Tooling/Core/Replacement.h"
Kadir Cetinkaya256247c2019-06-26 07:45:27 +000021#include "llvm/ADT/ArrayRef.h"
Sam McCalla69698f2019-03-27 17:47:49 +000022#include "llvm/ADT/Optional.h"
Kadir Cetinkaya689bf932018-08-24 13:09:41 +000023#include "llvm/ADT/ScopeExit.h"
Kadir Cetinkaya5b270932019-09-09 12:28:44 +000024#include "llvm/ADT/StringRef.h"
Utkarsh Saxena55925da2019-09-24 13:38:33 +000025#include "llvm/ADT/iterator_range.h"
Simon Marchi9569fd52018-03-16 14:30:42 +000026#include "llvm/Support/Errc.h"
Ilya Biryukovcce67a32019-01-29 14:17:36 +000027#include "llvm/Support/Error.h"
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +000028#include "llvm/Support/FormatVariadic.h"
Utkarsh Saxena55925da2019-09-24 13:38:33 +000029#include "llvm/Support/JSON.h"
Eric Liu5740ff52018-01-31 16:26:27 +000030#include "llvm/Support/Path.h"
Kadir Cetinkaya5b270932019-09-09 12:28:44 +000031#include "llvm/Support/SHA1.h"
Sam McCall2c30fbc2018-10-18 12:32:04 +000032#include "llvm/Support/ScopedPrinter.h"
Kadir Cetinkaya5b270932019-09-09 12:28:44 +000033#include <cstddef>
Utkarsh Saxena55925da2019-09-24 13:38:33 +000034#include <memory>
Kadir Cetinkaya5b270932019-09-09 12:28:44 +000035#include <string>
Utkarsh Saxena55925da2019-09-24 13:38:33 +000036#include <vector>
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +000037
Sam McCallc008af62018-10-20 15:30:37 +000038namespace clang {
39namespace clangd {
Ilya Biryukovafb55542017-05-16 14:40:30 +000040namespace {
Ilya Biryukovcce67a32019-01-29 14:17:36 +000041/// Transforms a tweak into a code action that would apply it if executed.
42/// EXPECTS: T.prepare() was called and returned true.
43CodeAction toCodeAction(const ClangdServer::TweakRef &T, const URIForFile &File,
44 Range Selection) {
45 CodeAction CA;
46 CA.title = T.Title;
Sam McCall395fde72019-06-18 13:37:54 +000047 switch (T.Intent) {
48 case Tweak::Refactor:
49 CA.kind = CodeAction::REFACTOR_KIND;
50 break;
51 case Tweak::Info:
52 CA.kind = CodeAction::INFO_KIND;
53 break;
54 }
Ilya Biryukovcce67a32019-01-29 14:17:36 +000055 // This tweak may have an expensive second stage, we only run it if the user
56 // actually chooses it in the UI. We reply with a command that would run the
57 // corresponding tweak.
58 // FIXME: for some tweaks, computing the edits is cheap and we could send them
59 // directly.
60 CA.command.emplace();
61 CA.command->title = T.Title;
62 CA.command->command = Command::CLANGD_APPLY_TWEAK;
63 CA.command->tweakArgs.emplace();
64 CA.command->tweakArgs->file = File;
65 CA.command->tweakArgs->tweakID = T.ID;
66 CA.command->tweakArgs->selection = Selection;
67 return CA;
Simon Pilgrime9a136b2019-02-03 14:08:30 +000068}
Ilya Biryukovcce67a32019-01-29 14:17:36 +000069
Ilya Biryukov19d75602018-11-23 15:21:19 +000070void adjustSymbolKinds(llvm::MutableArrayRef<DocumentSymbol> Syms,
71 SymbolKindBitset Kinds) {
72 for (auto &S : Syms) {
73 S.kind = adjustKindToCapability(S.kind, Kinds);
74 adjustSymbolKinds(S.children, Kinds);
75 }
76}
77
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +000078SymbolKindBitset defaultSymbolKinds() {
79 SymbolKindBitset Defaults;
80 for (size_t I = SymbolKindMin; I <= static_cast<size_t>(SymbolKind::Array);
81 ++I)
82 Defaults.set(I);
83 return Defaults;
84}
85
Kadir Cetinkaya133d46f2018-09-27 17:13:07 +000086CompletionItemKindBitset defaultCompletionItemKinds() {
87 CompletionItemKindBitset Defaults;
88 for (size_t I = CompletionItemKindMin;
89 I <= static_cast<size_t>(CompletionItemKind::Reference); ++I)
90 Defaults.set(I);
91 return Defaults;
92}
93
Haojian Wu1ca2ee42019-07-04 12:27:21 +000094// Build a lookup table (HighlightingKind => {TextMate Scopes}), which is sent
95// to the LSP client.
96std::vector<std::vector<std::string>> buildHighlightScopeLookupTable() {
97 std::vector<std::vector<std::string>> LookupTable;
98 // HighlightingKind is using as the index.
Ilya Biryukov63d5d162019-09-09 08:57:17 +000099 for (int KindValue = 0; KindValue <= (int)HighlightingKind::LastKind;
Haojian Wu1ca2ee42019-07-04 12:27:21 +0000100 ++KindValue)
101 LookupTable.push_back({toTextMateScope((HighlightingKind)(KindValue))});
102 return LookupTable;
103}
104
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000105// Makes sure edits in \p E are applicable to latest file contents reported by
106// editor. If not generates an error message containing information about files
107// that needs to be saved.
108llvm::Error validateEdits(const DraftStore &DraftMgr, const Tweak::Effect &E) {
109 size_t InvalidFileCount = 0;
110 llvm::StringRef LastInvalidFile;
111 for (const auto &It : E.ApplyEdits) {
112 if (auto Draft = DraftMgr.getDraft(It.first())) {
113 // If the file is open in user's editor, make sure the version we
114 // saw and current version are compatible as this is the text that
115 // will be replaced by editors.
116 if (!It.second.canApplyTo(*Draft)) {
117 ++InvalidFileCount;
118 LastInvalidFile = It.first();
119 }
120 }
121 }
122 if (!InvalidFileCount)
123 return llvm::Error::success();
124 if (InvalidFileCount == 1)
125 return llvm::createStringError(llvm::inconvertibleErrorCode(),
126 "File must be saved first: " +
127 LastInvalidFile);
128 return llvm::createStringError(
129 llvm::inconvertibleErrorCode(),
130 "Files must be saved first: " + LastInvalidFile + " (and " +
131 llvm::to_string(InvalidFileCount - 1) + " others)");
132}
133
Utkarsh Saxena55925da2019-09-24 13:38:33 +0000134// Converts a list of Ranges to a LinkedList of SelectionRange.
135SelectionRange render(const std::vector<Range> &Ranges) {
136 if (Ranges.empty())
137 return {};
138 SelectionRange Result;
139 Result.range = Ranges[0];
140 auto *Next = &Result.parent;
141 for (const auto &R : llvm::make_range(Ranges.begin() + 1, Ranges.end())) {
142 *Next = std::make_unique<SelectionRange>();
143 Next->get()->range = R;
144 Next = &Next->get()->parent;
145 }
146 return Result;
147}
148
Ilya Biryukovafb55542017-05-16 14:40:30 +0000149} // namespace
150
Sam McCall2c30fbc2018-10-18 12:32:04 +0000151// MessageHandler dispatches incoming LSP messages.
152// It handles cross-cutting concerns:
153// - serializes/deserializes protocol objects to JSON
154// - logging of inbound messages
155// - cancellation handling
156// - basic call tracing
Sam McCall3d0adbe2018-10-18 14:41:50 +0000157// MessageHandler ensures that initialize() is called before any other handler.
Sam McCall2c30fbc2018-10-18 12:32:04 +0000158class ClangdLSPServer::MessageHandler : public Transport::MessageHandler {
159public:
160 MessageHandler(ClangdLSPServer &Server) : Server(Server) {}
161
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000162 bool onNotify(llvm::StringRef Method, llvm::json::Value Params) override {
Sam McCalla69698f2019-03-27 17:47:49 +0000163 WithContext HandlerContext(handlerContext());
Sam McCall2c30fbc2018-10-18 12:32:04 +0000164 log("<-- {0}", Method);
165 if (Method == "exit")
166 return false;
Sam McCall3d0adbe2018-10-18 14:41:50 +0000167 if (!Server.Server)
168 elog("Notification {0} before initialization", Method);
169 else if (Method == "$/cancelRequest")
Sam McCall2c30fbc2018-10-18 12:32:04 +0000170 onCancel(std::move(Params));
171 else if (auto Handler = Notifications.lookup(Method))
172 Handler(std::move(Params));
173 else
174 log("unhandled notification {0}", Method);
175 return true;
176 }
177
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000178 bool onCall(llvm::StringRef Method, llvm::json::Value Params,
179 llvm::json::Value ID) override {
Sam McCalla69698f2019-03-27 17:47:49 +0000180 WithContext HandlerContext(handlerContext());
Sam McCalle2f3a732018-10-24 14:26:26 +0000181 // Calls can be canceled by the client. Add cancellation context.
182 WithContext WithCancel(cancelableRequestContext(ID));
183 trace::Span Tracer(Method);
184 SPAN_ATTACH(Tracer, "Params", Params);
185 ReplyOnce Reply(ID, Method, &Server, Tracer.Args);
Sam McCall2c30fbc2018-10-18 12:32:04 +0000186 log("<-- {0}({1})", Method, ID);
Sam McCall3d0adbe2018-10-18 14:41:50 +0000187 if (!Server.Server && Method != "initialize") {
188 elog("Call {0} before initialization.", Method);
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000189 Reply(llvm::make_error<LSPError>("server not initialized",
190 ErrorCode::ServerNotInitialized));
Sam McCall3d0adbe2018-10-18 14:41:50 +0000191 } else if (auto Handler = Calls.lookup(Method))
Sam McCalle2f3a732018-10-24 14:26:26 +0000192 Handler(std::move(Params), std::move(Reply));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000193 else
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000194 Reply(llvm::make_error<LSPError>("method not found",
195 ErrorCode::MethodNotFound));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000196 return true;
197 }
198
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000199 bool onReply(llvm::json::Value ID,
200 llvm::Expected<llvm::json::Value> Result) override {
Sam McCalla69698f2019-03-27 17:47:49 +0000201 WithContext HandlerContext(handlerContext());
Haojian Wuf2516342019-08-05 12:48:09 +0000202
203 Callback<llvm::json::Value> ReplyHandler = nullptr;
204 if (auto IntID = ID.getAsInteger()) {
205 std::lock_guard<std::mutex> Mutex(CallMutex);
206 // Find a corresponding callback for the request ID;
207 for (size_t Index = 0; Index < ReplyCallbacks.size(); ++Index) {
208 if (ReplyCallbacks[Index].first == *IntID) {
209 ReplyHandler = std::move(ReplyCallbacks[Index].second);
210 ReplyCallbacks.erase(ReplyCallbacks.begin() +
211 Index); // remove the entry
212 break;
213 }
214 }
215 }
216
217 if (!ReplyHandler) {
218 // No callback being found, use a default log callback.
219 ReplyHandler = [&ID](llvm::Expected<llvm::json::Value> Result) {
220 elog("received a reply with ID {0}, but there was no such call", ID);
221 if (!Result)
222 llvm::consumeError(Result.takeError());
223 };
224 }
225
226 // Log and run the reply handler.
227 if (Result) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000228 log("<-- reply({0})", ID);
Haojian Wuf2516342019-08-05 12:48:09 +0000229 ReplyHandler(std::move(Result));
230 } else {
231 auto Err = Result.takeError();
232 log("<-- reply({0}) error: {1}", ID, Err);
233 ReplyHandler(std::move(Err));
234 }
Sam McCall2c30fbc2018-10-18 12:32:04 +0000235 return true;
236 }
237
238 // Bind an LSP method name to a call.
Sam McCalle2f3a732018-10-24 14:26:26 +0000239 template <typename Param, typename Result>
Sam McCall2c30fbc2018-10-18 12:32:04 +0000240 void bind(const char *Method,
Sam McCalle2f3a732018-10-24 14:26:26 +0000241 void (ClangdLSPServer::*Handler)(const Param &, Callback<Result>)) {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000242 Calls[Method] = [Method, Handler, this](llvm::json::Value RawParams,
Sam McCalle2f3a732018-10-24 14:26:26 +0000243 ReplyOnce Reply) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000244 Param P;
Sam McCalle2f3a732018-10-24 14:26:26 +0000245 if (fromJSON(RawParams, P)) {
246 (Server.*Handler)(P, std::move(Reply));
247 } else {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000248 elog("Failed to decode {0} request.", Method);
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000249 Reply(llvm::make_error<LSPError>("failed to decode request",
250 ErrorCode::InvalidRequest));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000251 }
Sam McCall2c30fbc2018-10-18 12:32:04 +0000252 };
253 }
254
Haojian Wuf2516342019-08-05 12:48:09 +0000255 // Bind a reply callback to a request. The callback will be invoked when
256 // clangd receives the reply from the LSP client.
257 // Return a call id of the request.
258 llvm::json::Value bindReply(Callback<llvm::json::Value> Reply) {
259 llvm::Optional<std::pair<int, Callback<llvm::json::Value>>> OldestCB;
260 int ID;
261 {
262 std::lock_guard<std::mutex> Mutex(CallMutex);
263 ID = NextCallID++;
264 ReplyCallbacks.emplace_back(ID, std::move(Reply));
265
266 // If the queue overflows, we assume that the client didn't reply the
267 // oldest request, and run the corresponding callback which replies an
268 // error to the client.
269 if (ReplyCallbacks.size() > MaxReplayCallbacks) {
270 elog("more than {0} outstanding LSP calls, forgetting about {1}",
271 MaxReplayCallbacks, ReplyCallbacks.front().first);
272 OldestCB = std::move(ReplyCallbacks.front());
273 ReplyCallbacks.pop_front();
274 }
275 }
276 if (OldestCB)
277 OldestCB->second(llvm::createStringError(
278 llvm::inconvertibleErrorCode(),
279 llvm::formatv("failed to receive a client reply for request ({0})",
280 OldestCB->first)));
281 return ID;
282 }
283
Sam McCall2c30fbc2018-10-18 12:32:04 +0000284 // Bind an LSP method name to a notification.
285 template <typename Param>
286 void bind(const char *Method,
287 void (ClangdLSPServer::*Handler)(const Param &)) {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000288 Notifications[Method] = [Method, Handler,
289 this](llvm::json::Value RawParams) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000290 Param P;
291 if (!fromJSON(RawParams, P)) {
292 elog("Failed to decode {0} request.", Method);
293 return;
294 }
295 trace::Span Tracer(Method);
296 SPAN_ATTACH(Tracer, "Params", RawParams);
297 (Server.*Handler)(P);
298 };
299 }
300
301private:
Sam McCalle2f3a732018-10-24 14:26:26 +0000302 // Function object to reply to an LSP call.
303 // Each instance must be called exactly once, otherwise:
304 // - the bug is logged, and (in debug mode) an assert will fire
305 // - if there was no reply, an error reply is sent
306 // - if there were multiple replies, only the first is sent
307 class ReplyOnce {
308 std::atomic<bool> Replied = {false};
Sam McCalld7babe42018-10-24 15:18:40 +0000309 std::chrono::steady_clock::time_point Start;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000310 llvm::json::Value ID;
Sam McCalle2f3a732018-10-24 14:26:26 +0000311 std::string Method;
312 ClangdLSPServer *Server; // Null when moved-from.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000313 llvm::json::Object *TraceArgs;
Sam McCalle2f3a732018-10-24 14:26:26 +0000314
315 public:
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000316 ReplyOnce(const llvm::json::Value &ID, llvm::StringRef Method,
317 ClangdLSPServer *Server, llvm::json::Object *TraceArgs)
Sam McCalld7babe42018-10-24 15:18:40 +0000318 : Start(std::chrono::steady_clock::now()), ID(ID), Method(Method),
319 Server(Server), TraceArgs(TraceArgs) {
Sam McCalle2f3a732018-10-24 14:26:26 +0000320 assert(Server);
321 }
322 ReplyOnce(ReplyOnce &&Other)
Sam McCalld7babe42018-10-24 15:18:40 +0000323 : Replied(Other.Replied.load()), Start(Other.Start),
324 ID(std::move(Other.ID)), Method(std::move(Other.Method)),
325 Server(Other.Server), TraceArgs(Other.TraceArgs) {
Sam McCalle2f3a732018-10-24 14:26:26 +0000326 Other.Server = nullptr;
327 }
Ilya Biryukov22fa4652019-01-03 13:28:05 +0000328 ReplyOnce &operator=(ReplyOnce &&) = delete;
Sam McCalle2f3a732018-10-24 14:26:26 +0000329 ReplyOnce(const ReplyOnce &) = delete;
Ilya Biryukov22fa4652019-01-03 13:28:05 +0000330 ReplyOnce &operator=(const ReplyOnce &) = delete;
Sam McCalle2f3a732018-10-24 14:26:26 +0000331
332 ~ReplyOnce() {
Haojian Wuf2516342019-08-05 12:48:09 +0000333 // There's one legitimate reason to never reply to a request: clangd's
334 // request handler send a call to the client (e.g. applyEdit) and the
335 // client never replied. In this case, the ReplyOnce is owned by
336 // ClangdLSPServer's reply callback table and is destroyed along with the
337 // server. We don't attempt to send a reply in this case, there's little
338 // to be gained from doing so.
339 if (Server && !Server->IsBeingDestroyed && !Replied) {
Sam McCalle2f3a732018-10-24 14:26:26 +0000340 elog("No reply to message {0}({1})", Method, ID);
341 assert(false && "must reply to all calls!");
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000342 (*this)(llvm::make_error<LSPError>("server failed to reply",
343 ErrorCode::InternalError));
Sam McCalle2f3a732018-10-24 14:26:26 +0000344 }
345 }
346
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000347 void operator()(llvm::Expected<llvm::json::Value> Reply) {
Sam McCalle2f3a732018-10-24 14:26:26 +0000348 assert(Server && "moved-from!");
349 if (Replied.exchange(true)) {
350 elog("Replied twice to message {0}({1})", Method, ID);
351 assert(false && "must reply to each call only once!");
352 return;
353 }
Sam McCalld7babe42018-10-24 15:18:40 +0000354 auto Duration = std::chrono::steady_clock::now() - Start;
355 if (Reply) {
356 log("--> reply:{0}({1}) {2:ms}", Method, ID, Duration);
357 if (TraceArgs)
Sam McCalle2f3a732018-10-24 14:26:26 +0000358 (*TraceArgs)["Reply"] = *Reply;
Sam McCalld7babe42018-10-24 15:18:40 +0000359 std::lock_guard<std::mutex> Lock(Server->TranspWriter);
360 Server->Transp.reply(std::move(ID), std::move(Reply));
361 } else {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000362 llvm::Error Err = Reply.takeError();
Sam McCalld7babe42018-10-24 15:18:40 +0000363 log("--> reply:{0}({1}) {2:ms}, error: {3}", Method, ID, Duration, Err);
364 if (TraceArgs)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000365 (*TraceArgs)["Error"] = llvm::to_string(Err);
Sam McCalld7babe42018-10-24 15:18:40 +0000366 std::lock_guard<std::mutex> Lock(Server->TranspWriter);
367 Server->Transp.reply(std::move(ID), std::move(Err));
Sam McCalle2f3a732018-10-24 14:26:26 +0000368 }
Sam McCalle2f3a732018-10-24 14:26:26 +0000369 }
370 };
371
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000372 llvm::StringMap<std::function<void(llvm::json::Value)>> Notifications;
373 llvm::StringMap<std::function<void(llvm::json::Value, ReplyOnce)>> Calls;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000374
375 // Method calls may be cancelled by ID, so keep track of their state.
376 // This needs a mutex: handlers may finish on a different thread, and that's
377 // when we clean up entries in the map.
378 mutable std::mutex RequestCancelersMutex;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000379 llvm::StringMap<std::pair<Canceler, /*Cookie*/ unsigned>> RequestCancelers;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000380 unsigned NextRequestCookie = 0; // To disambiguate reused IDs, see below.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000381 void onCancel(const llvm::json::Value &Params) {
382 const llvm::json::Value *ID = nullptr;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000383 if (auto *O = Params.getAsObject())
384 ID = O->get("id");
385 if (!ID) {
386 elog("Bad cancellation request: {0}", Params);
387 return;
388 }
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000389 auto StrID = llvm::to_string(*ID);
Sam McCall2c30fbc2018-10-18 12:32:04 +0000390 std::lock_guard<std::mutex> Lock(RequestCancelersMutex);
391 auto It = RequestCancelers.find(StrID);
392 if (It != RequestCancelers.end())
393 It->second.first(); // Invoke the canceler.
394 }
Sam McCalla69698f2019-03-27 17:47:49 +0000395
396 Context handlerContext() const {
397 return Context::current().derive(
398 kCurrentOffsetEncoding,
399 Server.NegotiatedOffsetEncoding.getValueOr(OffsetEncoding::UTF16));
400 }
401
Sam McCall2c30fbc2018-10-18 12:32:04 +0000402 // We run cancelable requests in a context that does two things:
403 // - allows cancellation using RequestCancelers[ID]
404 // - cleans up the entry in RequestCancelers when it's no longer needed
405 // If a client reuses an ID, the last wins and the first cannot be canceled.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000406 Context cancelableRequestContext(const llvm::json::Value &ID) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000407 auto Task = cancelableTask();
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000408 auto StrID = llvm::to_string(ID); // JSON-serialize ID for map key.
Sam McCall2c30fbc2018-10-18 12:32:04 +0000409 auto Cookie = NextRequestCookie++; // No lock, only called on main thread.
410 {
411 std::lock_guard<std::mutex> Lock(RequestCancelersMutex);
412 RequestCancelers[StrID] = {std::move(Task.second), Cookie};
413 }
414 // When the request ends, we can clean up the entry we just added.
415 // The cookie lets us check that it hasn't been overwritten due to ID
416 // reuse.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000417 return Task.first.derive(llvm::make_scope_exit([this, StrID, Cookie] {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000418 std::lock_guard<std::mutex> Lock(RequestCancelersMutex);
419 auto It = RequestCancelers.find(StrID);
420 if (It != RequestCancelers.end() && It->second.second == Cookie)
421 RequestCancelers.erase(It);
422 }));
423 }
424
Kadir Cetinkaya9a3a87d2019-10-09 13:59:31 +0000425 // The maximum number of callbacks held in clangd.
426 //
427 // We bound the maximum size to the pending map to prevent memory leakage
428 // for cases where LSP clients don't reply for the request.
429 // This has to go after RequestCancellers and RequestCancellersMutex since it
430 // can contain a callback that has a cancelable context.
431 static constexpr int MaxReplayCallbacks = 100;
432 mutable std::mutex CallMutex;
433 int NextCallID = 0; /* GUARDED_BY(CallMutex) */
434 std::deque<std::pair</*RequestID*/ int,
435 /*ReplyHandler*/ Callback<llvm::json::Value>>>
436 ReplyCallbacks; /* GUARDED_BY(CallMutex) */
437
Sam McCall2c30fbc2018-10-18 12:32:04 +0000438 ClangdLSPServer &Server;
439};
Haojian Wuf2516342019-08-05 12:48:09 +0000440constexpr int ClangdLSPServer::MessageHandler::MaxReplayCallbacks;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000441
442// call(), notify(), and reply() wrap the Transport, adding logging and locking.
Haojian Wuf2516342019-08-05 12:48:09 +0000443void ClangdLSPServer::callRaw(StringRef Method, llvm::json::Value Params,
444 Callback<llvm::json::Value> CB) {
445 auto ID = MsgHandler->bindReply(std::move(CB));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000446 log("--> {0}({1})", Method, ID);
Sam McCall2c30fbc2018-10-18 12:32:04 +0000447 std::lock_guard<std::mutex> Lock(TranspWriter);
448 Transp.call(Method, std::move(Params), ID);
449}
450
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000451void ClangdLSPServer::notify(llvm::StringRef Method, llvm::json::Value Params) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000452 log("--> {0}", Method);
453 std::lock_guard<std::mutex> Lock(TranspWriter);
454 Transp.notify(Method, std::move(Params));
455}
456
Sam McCall2c30fbc2018-10-18 12:32:04 +0000457void ClangdLSPServer::onInitialize(const InitializeParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000458 Callback<llvm::json::Value> Reply) {
Sam McCalla69698f2019-03-27 17:47:49 +0000459 // Determine character encoding first as it affects constructed ClangdServer.
460 if (Params.capabilities.offsetEncoding && !NegotiatedOffsetEncoding) {
461 NegotiatedOffsetEncoding = OffsetEncoding::UTF16; // fallback
462 for (OffsetEncoding Supported : *Params.capabilities.offsetEncoding)
463 if (Supported != OffsetEncoding::UnsupportedEncoding) {
464 NegotiatedOffsetEncoding = Supported;
465 break;
466 }
467 }
468 llvm::Optional<WithContextValue> WithOffsetEncoding;
469 if (NegotiatedOffsetEncoding)
470 WithOffsetEncoding.emplace(kCurrentOffsetEncoding,
471 *NegotiatedOffsetEncoding);
472
Johan Vikstroma848dab2019-07-04 07:53:12 +0000473 ClangdServerOpts.SemanticHighlighting =
474 Params.capabilities.SemanticHighlighting;
Sam McCall0d9b40f2018-10-19 15:42:23 +0000475 if (Params.rootUri && *Params.rootUri)
476 ClangdServerOpts.WorkspaceRoot = Params.rootUri->file();
477 else if (Params.rootPath && !Params.rootPath->empty())
478 ClangdServerOpts.WorkspaceRoot = *Params.rootPath;
Sam McCall3d0adbe2018-10-18 14:41:50 +0000479 if (Server)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000480 return Reply(llvm::make_error<LSPError>("server already initialized",
481 ErrorCode::InvalidRequest));
Sam McCallbc904612018-10-25 04:22:52 +0000482 if (const auto &Dir = Params.initializationOptions.compilationDatabasePath)
483 CompileCommandsDir = Dir;
Kadir Cetinkaya256247c2019-06-26 07:45:27 +0000484 if (UseDirBasedCDB) {
Jonas Devlieghere1c705d92019-08-14 23:52:23 +0000485 BaseCDB = std::make_unique<DirectoryBasedGlobalCompilationDatabase>(
Sam McCallc55d09a2018-11-02 13:09:36 +0000486 CompileCommandsDir);
Kadir Cetinkaya256247c2019-06-26 07:45:27 +0000487 BaseCDB = getQueryDriverDatabase(
488 llvm::makeArrayRef(ClangdServerOpts.QueryDriverGlobs),
489 std::move(BaseCDB));
490 }
Kadir Cetinkayabe6b35d2019-01-22 09:10:20 +0000491 CDB.emplace(BaseCDB.get(), Params.initializationOptions.fallbackFlags,
492 ClangdServerOpts.ResourceDir);
Sam McCallc55d09a2018-11-02 13:09:36 +0000493 Server.emplace(*CDB, FSProvider, static_cast<DiagnosticsConsumer &>(*this),
494 ClangdServerOpts);
Sam McCallbc904612018-10-25 04:22:52 +0000495 applyConfiguration(Params.initializationOptions.ConfigSettings);
Simon Marchi88016782018-08-01 11:28:49 +0000496
Sam McCallbf6a2fc2018-10-17 07:33:42 +0000497 CCOpts.EnableSnippets = Params.capabilities.CompletionSnippets;
Sam McCall8d412942019-06-18 11:57:26 +0000498 CCOpts.IncludeFixIts = Params.capabilities.CompletionFixes;
Sam McCall5f092e32019-07-08 17:27:15 +0000499 if (!CCOpts.BundleOverloads.hasValue())
500 CCOpts.BundleOverloads = Params.capabilities.HasSignatureHelp;
Sam McCallbf6a2fc2018-10-17 07:33:42 +0000501 DiagOpts.EmbedFixesInDiagnostics = Params.capabilities.DiagnosticFixes;
502 DiagOpts.SendDiagnosticCategory = Params.capabilities.DiagnosticCategory;
Sam McCallc9e4ee92019-04-18 15:17:07 +0000503 DiagOpts.EmitRelatedLocations =
504 Params.capabilities.DiagnosticRelatedInformation;
Sam McCallbf6a2fc2018-10-17 07:33:42 +0000505 if (Params.capabilities.WorkspaceSymbolKinds)
506 SupportedSymbolKinds |= *Params.capabilities.WorkspaceSymbolKinds;
507 if (Params.capabilities.CompletionItemKinds)
508 SupportedCompletionItemKinds |= *Params.capabilities.CompletionItemKinds;
509 SupportsCodeAction = Params.capabilities.CodeActionStructure;
Ilya Biryukov19d75602018-11-23 15:21:19 +0000510 SupportsHierarchicalDocumentSymbol =
511 Params.capabilities.HierarchicalDocumentSymbol;
Haojian Wub6188492018-12-20 15:39:12 +0000512 SupportFileStatus = Params.initializationOptions.FileStatus;
Ilya Biryukovf9169d02019-05-29 10:01:00 +0000513 HoverContentFormat = Params.capabilities.HoverContentFormat;
Ilya Biryukov4ef0f822019-06-04 09:36:59 +0000514 SupportsOffsetsInSignatureHelp = Params.capabilities.OffsetsInSignatureHelp;
Haojian Wuf429ab62019-07-24 07:49:23 +0000515
516 // Per LSP, renameProvider can be either boolean or RenameOptions.
517 // RenameOptions will be specified if the client states it supports prepare.
518 llvm::json::Value RenameProvider =
519 llvm::json::Object{{"prepareProvider", true}};
520 if (!Params.capabilities.RenamePrepareSupport) // Only boolean allowed per LSP
521 RenameProvider = true;
522
Haojian Wu08d93f12019-08-22 14:53:45 +0000523 // Per LSP, codeActionProvide can be either boolean or CodeActionOptions.
524 // CodeActionOptions is only valid if the client supports action literal
525 // via textDocument.codeAction.codeActionLiteralSupport.
526 llvm::json::Value CodeActionProvider = true;
527 if (Params.capabilities.CodeActionStructure)
528 CodeActionProvider = llvm::json::Object{
529 {"codeActionKinds",
530 {CodeAction::QUICKFIX_KIND, CodeAction::REFACTOR_KIND,
531 CodeAction::INFO_KIND}}};
532
Sam McCalla69698f2019-03-27 17:47:49 +0000533 llvm::json::Object Result{
Sam McCall0930ab02017-11-07 15:49:35 +0000534 {{"capabilities",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000535 llvm::json::Object{
Simon Marchi98082622018-03-26 14:41:40 +0000536 {"textDocumentSync", (int)TextDocumentSyncKind::Incremental},
Sam McCall0930ab02017-11-07 15:49:35 +0000537 {"documentFormattingProvider", true},
538 {"documentRangeFormattingProvider", true},
539 {"documentOnTypeFormattingProvider",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000540 llvm::json::Object{
Sam McCall25c62572019-06-10 14:26:21 +0000541 {"firstTriggerCharacter", "\n"},
Sam McCall0930ab02017-11-07 15:49:35 +0000542 {"moreTriggerCharacter", {}},
543 }},
Haojian Wu08d93f12019-08-22 14:53:45 +0000544 {"codeActionProvider", std::move(CodeActionProvider)},
Sam McCall0930ab02017-11-07 15:49:35 +0000545 {"completionProvider",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000546 llvm::json::Object{
Sam McCall0930ab02017-11-07 15:49:35 +0000547 {"resolveProvider", false},
Ilya Biryukovb0826bd2019-01-03 13:37:12 +0000548 // We do extra checks for '>' and ':' in completion to only
549 // trigger on '->' and '::'.
Sam McCall0930ab02017-11-07 15:49:35 +0000550 {"triggerCharacters", {".", ">", ":"}},
551 }},
552 {"signatureHelpProvider",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000553 llvm::json::Object{
Sam McCall0930ab02017-11-07 15:49:35 +0000554 {"triggerCharacters", {"(", ","}},
555 }},
Sam McCall866ba2c2019-02-01 11:26:13 +0000556 {"declarationProvider", true},
Sam McCall0930ab02017-11-07 15:49:35 +0000557 {"definitionProvider", true},
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000558 {"documentHighlightProvider", true},
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000559 {"hoverProvider", true},
Haojian Wuf429ab62019-07-24 07:49:23 +0000560 {"renameProvider", std::move(RenameProvider)},
Utkarsh Saxena55925da2019-09-24 13:38:33 +0000561 {"selectionRangeProvider", true},
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000562 {"documentSymbolProvider", true},
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000563 {"workspaceSymbolProvider", true},
Sam McCall1ad142f2018-09-05 11:53:07 +0000564 {"referencesProvider", true},
Sam McCall0930ab02017-11-07 15:49:35 +0000565 {"executeCommandProvider",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000566 llvm::json::Object{
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000567 {"commands",
568 {ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND,
569 ExecuteCommandParams::CLANGD_APPLY_TWEAK}},
Sam McCall0930ab02017-11-07 15:49:35 +0000570 }},
Kadir Cetinkaya86658022019-03-19 09:27:04 +0000571 {"typeHierarchyProvider", true},
Sam McCalla69698f2019-03-27 17:47:49 +0000572 }}}};
573 if (NegotiatedOffsetEncoding)
574 Result["offsetEncoding"] = *NegotiatedOffsetEncoding;
Johan Vikstroma848dab2019-07-04 07:53:12 +0000575 if (Params.capabilities.SemanticHighlighting)
576 Result.getObject("capabilities")
577 ->insert(
578 {"semanticHighlighting",
Haojian Wu1ca2ee42019-07-04 12:27:21 +0000579 llvm::json::Object{{"scopes", buildHighlightScopeLookupTable()}}});
Sam McCalla69698f2019-03-27 17:47:49 +0000580 Reply(std::move(Result));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000581}
582
Sam McCall2c30fbc2018-10-18 12:32:04 +0000583void ClangdLSPServer::onShutdown(const ShutdownParams &Params,
584 Callback<std::nullptr_t> Reply) {
Ilya Biryukov0d9b8a32017-10-25 08:45:41 +0000585 // Do essentially nothing, just say we're ready to exit.
586 ShutdownRequestReceived = true;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000587 Reply(nullptr);
Sam McCall8a5dded2017-10-12 13:29:58 +0000588}
Ilya Biryukovafb55542017-05-16 14:40:30 +0000589
Sam McCall422c8282018-11-26 16:00:11 +0000590// sync is a clangd extension: it blocks until all background work completes.
591// It blocks the calling thread, so no messages are processed until it returns!
592void ClangdLSPServer::onSync(const NoParams &Params,
593 Callback<std::nullptr_t> Reply) {
594 if (Server->blockUntilIdleForTest(/*TimeoutSeconds=*/60))
595 Reply(nullptr);
596 else
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000597 Reply(llvm::createStringError(llvm::inconvertibleErrorCode(),
598 "Not idle after a minute"));
Sam McCall422c8282018-11-26 16:00:11 +0000599}
600
Sam McCall2c30fbc2018-10-18 12:32:04 +0000601void ClangdLSPServer::onDocumentDidOpen(
602 const DidOpenTextDocumentParams &Params) {
Simon Marchi9569fd52018-03-16 14:30:42 +0000603 PathRef File = Params.textDocument.uri.file();
Ilya Biryukovb10ef472018-06-13 09:20:41 +0000604
Sam McCall2c30fbc2018-10-18 12:32:04 +0000605 const std::string &Contents = Params.textDocument.text;
Simon Marchi9569fd52018-03-16 14:30:42 +0000606
Simon Marchi98082622018-03-26 14:41:40 +0000607 DraftMgr.addDraft(File, Contents);
Ilya Biryukov652364b2018-09-26 05:48:29 +0000608 Server->addDocument(File, Contents, WantDiagnostics::Yes);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000609}
610
Sam McCall2c30fbc2018-10-18 12:32:04 +0000611void ClangdLSPServer::onDocumentDidChange(
612 const DidChangeTextDocumentParams &Params) {
Eric Liu51fed182018-02-22 18:40:39 +0000613 auto WantDiags = WantDiagnostics::Auto;
614 if (Params.wantDiagnostics.hasValue())
615 WantDiags = Params.wantDiagnostics.getValue() ? WantDiagnostics::Yes
616 : WantDiagnostics::No;
Simon Marchi9569fd52018-03-16 14:30:42 +0000617
618 PathRef File = Params.textDocument.uri.file();
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000619 llvm::Expected<std::string> Contents =
Simon Marchi98082622018-03-26 14:41:40 +0000620 DraftMgr.updateDraft(File, Params.contentChanges);
621 if (!Contents) {
622 // If this fails, we are most likely going to be not in sync anymore with
623 // the client. It is better to remove the draft and let further operations
624 // fail rather than giving wrong results.
625 DraftMgr.removeDraft(File);
Ilya Biryukov652364b2018-09-26 05:48:29 +0000626 Server->removeDocument(File);
Sam McCallbed58852018-07-11 10:35:11 +0000627 elog("Failed to update {0}: {1}", File, Contents.takeError());
Simon Marchi98082622018-03-26 14:41:40 +0000628 return;
629 }
Simon Marchi9569fd52018-03-16 14:30:42 +0000630
Ilya Biryukov652364b2018-09-26 05:48:29 +0000631 Server->addDocument(File, *Contents, WantDiags);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000632}
633
Sam McCall2c30fbc2018-10-18 12:32:04 +0000634void ClangdLSPServer::onFileEvent(const DidChangeWatchedFilesParams &Params) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000635 Server->onFileEvent(Params);
Marc-Andre Laperlebf114242017-10-02 18:00:37 +0000636}
637
Sam McCall2c30fbc2018-10-18 12:32:04 +0000638void ClangdLSPServer::onCommand(const ExecuteCommandParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000639 Callback<llvm::json::Value> Reply) {
Ilya Biryukov12864002019-08-16 12:46:41 +0000640 auto ApplyEdit = [this](WorkspaceEdit WE, std::string SuccessMessage,
641 decltype(Reply) Reply) {
Eric Liuc5105f92018-02-16 14:15:55 +0000642 ApplyWorkspaceEditParams Edit;
643 Edit.edit = std::move(WE);
Ilya Biryukov12864002019-08-16 12:46:41 +0000644 call<ApplyWorkspaceEditResponse>(
645 "workspace/applyEdit", std::move(Edit),
646 [Reply = std::move(Reply), SuccessMessage = std::move(SuccessMessage)](
647 llvm::Expected<ApplyWorkspaceEditResponse> Response) mutable {
648 if (!Response)
649 return Reply(Response.takeError());
650 if (!Response->applied) {
651 std::string Reason = Response->failureReason
652 ? *Response->failureReason
653 : "unknown reason";
654 return Reply(llvm::createStringError(
655 llvm::inconvertibleErrorCode(),
656 ("edits were not applied: " + Reason).c_str()));
657 }
658 return Reply(SuccessMessage);
659 });
Eric Liuc5105f92018-02-16 14:15:55 +0000660 };
Ilya Biryukov12864002019-08-16 12:46:41 +0000661
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000662 if (Params.command == ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND &&
663 Params.workspaceEdit) {
664 // The flow for "apply-fix" :
665 // 1. We publish a diagnostic, including fixits
666 // 2. The user clicks on the diagnostic, the editor asks us for code actions
667 // 3. We send code actions, with the fixit embedded as context
668 // 4. The user selects the fixit, the editor asks us to apply it
669 // 5. We unwrap the changes and send them back to the editor
Haojian Wuf2516342019-08-05 12:48:09 +0000670 // 6. The editor applies the changes (applyEdit), and sends us a reply
671 // 7. We unwrap the reply and send a reply to the editor.
Ilya Biryukov12864002019-08-16 12:46:41 +0000672 ApplyEdit(*Params.workspaceEdit, "Fix applied.", std::move(Reply));
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000673 } else if (Params.command == ExecuteCommandParams::CLANGD_APPLY_TWEAK &&
674 Params.tweakArgs) {
675 auto Code = DraftMgr.getDraft(Params.tweakArgs->file.file());
676 if (!Code)
677 return Reply(llvm::createStringError(
678 llvm::inconvertibleErrorCode(),
679 "trying to apply a code action for a non-added file"));
680
Ilya Biryukov12864002019-08-16 12:46:41 +0000681 auto Action = [this, ApplyEdit, Reply = std::move(Reply),
682 File = Params.tweakArgs->file, Code = std::move(*Code)](
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000683 llvm::Expected<Tweak::Effect> R) mutable {
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000684 if (!R)
685 return Reply(R.takeError());
686
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000687 assert(R->ShowMessage ||
688 (!R->ApplyEdits.empty() && "tweak has no effect"));
Ilya Biryukov12864002019-08-16 12:46:41 +0000689
Sam McCall395fde72019-06-18 13:37:54 +0000690 if (R->ShowMessage) {
691 ShowMessageParams Msg;
692 Msg.message = *R->ShowMessage;
693 Msg.type = MessageType::Info;
694 notify("window/showMessage", Msg);
695 }
Ilya Biryukov12864002019-08-16 12:46:41 +0000696 // When no edit is specified, make sure we Reply().
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000697 if (R->ApplyEdits.empty())
698 return Reply("Tweak applied.");
699
700 if (auto Err = validateEdits(DraftMgr, *R))
701 return Reply(std::move(Err));
702
703 WorkspaceEdit WE;
704 WE.changes.emplace();
705 for (const auto &It : R->ApplyEdits) {
Kadir Cetinkayae95e5162019-10-02 09:12:01 +0000706 (*WE.changes)[URI::createFile(It.first()).toString()] =
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000707 It.second.asTextEdits();
708 }
709 // ApplyEdit will take care of calling Reply().
710 return ApplyEdit(std::move(WE), "Tweak applied.", std::move(Reply));
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000711 };
712 Server->applyTweak(Params.tweakArgs->file.file(),
713 Params.tweakArgs->selection, Params.tweakArgs->tweakID,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000714 std::move(Action));
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000715 } else {
716 // We should not get here because ExecuteCommandParams would not have
717 // parsed in the first place and this handler should not be called. But if
718 // more commands are added, this will be here has a safe guard.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000719 Reply(llvm::make_error<LSPError>(
720 llvm::formatv("Unsupported command \"{0}\".", Params.command).str(),
Sam McCall2c30fbc2018-10-18 12:32:04 +0000721 ErrorCode::InvalidParams));
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000722 }
723}
724
Sam McCall2c30fbc2018-10-18 12:32:04 +0000725void ClangdLSPServer::onWorkspaceSymbol(
726 const WorkspaceSymbolParams &Params,
727 Callback<std::vector<SymbolInformation>> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000728 Server->workspaceSymbols(
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000729 Params.query, CCOpts.Limit,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000730 [Reply = std::move(Reply),
731 this](llvm::Expected<std::vector<SymbolInformation>> Items) mutable {
732 if (!Items)
733 return Reply(Items.takeError());
734 for (auto &Sym : *Items)
735 Sym.kind = adjustKindToCapability(Sym.kind, SupportedSymbolKinds);
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000736
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000737 Reply(std::move(*Items));
738 });
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000739}
740
Haojian Wuf429ab62019-07-24 07:49:23 +0000741void ClangdLSPServer::onPrepareRename(const TextDocumentPositionParams &Params,
742 Callback<llvm::Optional<Range>> Reply) {
743 Server->prepareRename(Params.textDocument.uri.file(), Params.position,
744 std::move(Reply));
745}
746
Sam McCall2c30fbc2018-10-18 12:32:04 +0000747void ClangdLSPServer::onRename(const RenameParams &Params,
748 Callback<WorkspaceEdit> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000749 Path File = Params.textDocument.uri.file();
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000750 llvm::Optional<std::string> Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000751 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000752 return Reply(llvm::make_error<LSPError>(
753 "onRename called for non-added file", ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000754
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000755 Server->rename(File, Params.position, Params.newName, /*WantFormat=*/true,
756 [File, Code, Params, Reply = std::move(Reply)](
757 llvm::Expected<std::vector<TextEdit>> Edits) mutable {
758 if (!Edits)
759 return Reply(Edits.takeError());
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000760
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000761 WorkspaceEdit WE;
762 WE.changes = {{Params.textDocument.uri.uri(), *Edits}};
763 Reply(WE);
764 });
Haojian Wu345099c2017-11-09 11:30:04 +0000765}
766
Sam McCall2c30fbc2018-10-18 12:32:04 +0000767void ClangdLSPServer::onDocumentDidClose(
768 const DidCloseTextDocumentParams &Params) {
Simon Marchi9569fd52018-03-16 14:30:42 +0000769 PathRef File = Params.textDocument.uri.file();
770 DraftMgr.removeDraft(File);
Ilya Biryukov652364b2018-09-26 05:48:29 +0000771 Server->removeDocument(File);
Ilya Biryukov49c10712019-03-25 10:15:11 +0000772
773 {
774 std::lock_guard<std::mutex> Lock(FixItsMutex);
775 FixItsMap.erase(File);
776 }
Johan Vikstromc2653ef22019-08-01 08:08:44 +0000777 {
778 std::lock_guard<std::mutex> HLock(HighlightingsMutex);
779 FileToHighlightings.erase(File);
780 }
Ilya Biryukov49c10712019-03-25 10:15:11 +0000781 // clangd will not send updates for this file anymore, so we empty out the
782 // list of diagnostics shown on the client (e.g. in the "Problems" pane of
783 // VSCode). Note that this cannot race with actual diagnostics responses
784 // because removeDocument() guarantees no diagnostic callbacks will be
785 // executed after it returns.
786 publishDiagnostics(URIForFile::canonicalize(File, /*TUPath=*/File), {});
Ilya Biryukovafb55542017-05-16 14:40:30 +0000787}
788
Sam McCall4db732a2017-09-30 10:08:52 +0000789void ClangdLSPServer::onDocumentOnTypeFormatting(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000790 const DocumentOnTypeFormattingParams &Params,
791 Callback<std::vector<TextEdit>> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000792 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000793 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000794 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000795 return Reply(llvm::make_error<LSPError>(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000796 "onDocumentOnTypeFormatting called for non-added file",
797 ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000798
Sam McCall25c62572019-06-10 14:26:21 +0000799 Reply(Server->formatOnType(*Code, File, Params.position, Params.ch));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000800}
801
Sam McCall4db732a2017-09-30 10:08:52 +0000802void ClangdLSPServer::onDocumentRangeFormatting(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000803 const DocumentRangeFormattingParams &Params,
804 Callback<std::vector<TextEdit>> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000805 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000806 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000807 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000808 return Reply(llvm::make_error<LSPError>(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000809 "onDocumentRangeFormatting called for non-added file",
810 ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000811
Ilya Biryukov652364b2018-09-26 05:48:29 +0000812 auto ReplacementsOrError = Server->formatRange(*Code, File, Params.range);
Raoul Wols212bcf82017-12-12 20:25:06 +0000813 if (ReplacementsOrError)
Sam McCall2c30fbc2018-10-18 12:32:04 +0000814 Reply(replacementsToEdits(*Code, ReplacementsOrError.get()));
Raoul Wols212bcf82017-12-12 20:25:06 +0000815 else
Sam McCall2c30fbc2018-10-18 12:32:04 +0000816 Reply(ReplacementsOrError.takeError());
Ilya Biryukovafb55542017-05-16 14:40:30 +0000817}
818
Sam McCall2c30fbc2018-10-18 12:32:04 +0000819void ClangdLSPServer::onDocumentFormatting(
820 const DocumentFormattingParams &Params,
821 Callback<std::vector<TextEdit>> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000822 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000823 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000824 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000825 return Reply(llvm::make_error<LSPError>(
826 "onDocumentFormatting called for non-added file",
827 ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000828
Ilya Biryukov652364b2018-09-26 05:48:29 +0000829 auto ReplacementsOrError = Server->formatFile(*Code, File);
Raoul Wols212bcf82017-12-12 20:25:06 +0000830 if (ReplacementsOrError)
Sam McCall2c30fbc2018-10-18 12:32:04 +0000831 Reply(replacementsToEdits(*Code, ReplacementsOrError.get()));
Raoul Wols212bcf82017-12-12 20:25:06 +0000832 else
Sam McCall2c30fbc2018-10-18 12:32:04 +0000833 Reply(ReplacementsOrError.takeError());
Sam McCall4db732a2017-09-30 10:08:52 +0000834}
835
Ilya Biryukov19d75602018-11-23 15:21:19 +0000836/// The functions constructs a flattened view of the DocumentSymbol hierarchy.
837/// Used by the clients that do not support the hierarchical view.
838static std::vector<SymbolInformation>
839flattenSymbolHierarchy(llvm::ArrayRef<DocumentSymbol> Symbols,
840 const URIForFile &FileURI) {
841
842 std::vector<SymbolInformation> Results;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000843 std::function<void(const DocumentSymbol &, llvm::StringRef)> Process =
844 [&](const DocumentSymbol &S, llvm::Optional<llvm::StringRef> ParentName) {
Ilya Biryukov19d75602018-11-23 15:21:19 +0000845 SymbolInformation SI;
846 SI.containerName = ParentName ? "" : *ParentName;
847 SI.name = S.name;
848 SI.kind = S.kind;
849 SI.location.range = S.range;
850 SI.location.uri = FileURI;
851
852 Results.push_back(std::move(SI));
853 std::string FullName =
854 !ParentName ? S.name : (ParentName->str() + "::" + S.name);
855 for (auto &C : S.children)
856 Process(C, /*ParentName=*/FullName);
857 };
858 for (auto &S : Symbols)
859 Process(S, /*ParentName=*/"");
860 return Results;
861}
862
863void ClangdLSPServer::onDocumentSymbol(const DocumentSymbolParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000864 Callback<llvm::json::Value> Reply) {
Ilya Biryukov19d75602018-11-23 15:21:19 +0000865 URIForFile FileURI = Params.textDocument.uri;
Ilya Biryukov652364b2018-09-26 05:48:29 +0000866 Server->documentSymbols(
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000867 Params.textDocument.uri.file(),
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000868 [this, FileURI, Reply = std::move(Reply)](
869 llvm::Expected<std::vector<DocumentSymbol>> Items) mutable {
870 if (!Items)
871 return Reply(Items.takeError());
872 adjustSymbolKinds(*Items, SupportedSymbolKinds);
873 if (SupportsHierarchicalDocumentSymbol)
874 return Reply(std::move(*Items));
875 else
876 return Reply(flattenSymbolHierarchy(*Items, FileURI));
877 });
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000878}
879
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000880static llvm::Optional<Command> asCommand(const CodeAction &Action) {
Sam McCall20841d42018-10-16 16:29:41 +0000881 Command Cmd;
882 if (Action.command && Action.edit)
Sam McCallc008af62018-10-20 15:30:37 +0000883 return None; // Not representable. (We never emit these anyway).
Sam McCall20841d42018-10-16 16:29:41 +0000884 if (Action.command) {
885 Cmd = *Action.command;
886 } else if (Action.edit) {
887 Cmd.command = Command::CLANGD_APPLY_FIX_COMMAND;
888 Cmd.workspaceEdit = *Action.edit;
889 } else {
Sam McCallc008af62018-10-20 15:30:37 +0000890 return None;
Sam McCall20841d42018-10-16 16:29:41 +0000891 }
892 Cmd.title = Action.title;
893 if (Action.kind && *Action.kind == CodeAction::QUICKFIX_KIND)
894 Cmd.title = "Apply fix: " + Cmd.title;
895 return Cmd;
896}
897
Sam McCall2c30fbc2018-10-18 12:32:04 +0000898void ClangdLSPServer::onCodeAction(const CodeActionParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000899 Callback<llvm::json::Value> Reply) {
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000900 URIForFile File = Params.textDocument.uri;
901 auto Code = DraftMgr.getDraft(File.file());
Sam McCall2c30fbc2018-10-18 12:32:04 +0000902 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000903 return Reply(llvm::make_error<LSPError>(
904 "onCodeAction called for non-added file", ErrorCode::InvalidParams));
Sam McCall20841d42018-10-16 16:29:41 +0000905 // We provide a code action for Fixes on the specified diagnostics.
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000906 std::vector<CodeAction> FixIts;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000907 for (const Diagnostic &D : Params.context.diagnostics) {
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000908 for (auto &F : getFixes(File.file(), D)) {
909 FixIts.push_back(toCodeAction(F, Params.textDocument.uri));
910 FixIts.back().diagnostics = {D};
Sam McCalldd0566b2017-11-06 15:40:30 +0000911 }
Ilya Biryukovafb55542017-05-16 14:40:30 +0000912 }
Sam McCall20841d42018-10-16 16:29:41 +0000913
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000914 // Now enumerate the semantic code actions.
915 auto ConsumeActions =
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000916 [Reply = std::move(Reply), File, Code = std::move(*Code),
917 Selection = Params.range, FixIts = std::move(FixIts), this](
918 llvm::Expected<std::vector<ClangdServer::TweakRef>> Tweaks) mutable {
Ilya Biryukovc6ed7782019-01-30 14:24:17 +0000919 if (!Tweaks)
920 return Reply(Tweaks.takeError());
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000921
922 std::vector<CodeAction> Actions = std::move(FixIts);
923 Actions.reserve(Actions.size() + Tweaks->size());
924 for (const auto &T : *Tweaks)
925 Actions.push_back(toCodeAction(T, File, Selection));
926
927 if (SupportsCodeAction)
928 return Reply(llvm::json::Array(Actions));
929 std::vector<Command> Commands;
930 for (const auto &Action : Actions) {
931 if (auto Command = asCommand(Action))
932 Commands.push_back(std::move(*Command));
933 }
934 return Reply(llvm::json::Array(Commands));
935 };
936
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000937 Server->enumerateTweaks(File.file(), Params.range, std::move(ConsumeActions));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000938}
939
Ilya Biryukovb0826bd2019-01-03 13:37:12 +0000940void ClangdLSPServer::onCompletion(const CompletionParams &Params,
Sam McCall2c30fbc2018-10-18 12:32:04 +0000941 Callback<CompletionList> Reply) {
Ilya Biryukova7a11472019-06-07 16:24:38 +0000942 if (!shouldRunCompletion(Params)) {
943 // Clients sometimes auto-trigger completions in undesired places (e.g.
944 // 'a >^ '), we return empty results in those cases.
945 vlog("ignored auto-triggered completion, preceding char did not match");
946 return Reply(CompletionList());
947 }
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000948 Server->codeComplete(Params.textDocument.uri.file(), Params.position, CCOpts,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000949 [Reply = std::move(Reply),
950 this](llvm::Expected<CodeCompleteResult> List) mutable {
951 if (!List)
952 return Reply(List.takeError());
953 CompletionList LSPList;
954 LSPList.isIncomplete = List->HasMore;
955 for (const auto &R : List->Completions) {
956 CompletionItem C = R.render(CCOpts);
957 C.kind = adjustKindToCapability(
958 C.kind, SupportedCompletionItemKinds);
959 LSPList.items.push_back(std::move(C));
960 }
961 return Reply(std::move(LSPList));
962 });
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000963}
964
Sam McCall2c30fbc2018-10-18 12:32:04 +0000965void ClangdLSPServer::onSignatureHelp(const TextDocumentPositionParams &Params,
966 Callback<SignatureHelp> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000967 Server->signatureHelp(Params.textDocument.uri.file(), Params.position,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000968 [Reply = std::move(Reply), this](
969 llvm::Expected<SignatureHelp> Signature) mutable {
970 if (!Signature)
971 return Reply(Signature.takeError());
972 if (SupportsOffsetsInSignatureHelp)
973 return Reply(std::move(*Signature));
974 // Strip out the offsets from signature help for
975 // clients that only support string labels.
976 for (auto &SigInfo : Signature->signatures) {
977 for (auto &Param : SigInfo.parameters)
978 Param.labelOffsets.reset();
979 }
980 return Reply(std::move(*Signature));
981 });
Ilya Biryukov652364b2018-09-26 05:48:29 +0000982}
983
Sam McCall0dbab7f2019-02-02 05:56:00 +0000984// Go to definition has a toggle function: if def and decl are distinct, then
985// the first press gives you the def, the second gives you the matching def.
986// getToggle() returns the counterpart location that under the cursor.
987//
988// We return the toggled location alone (ignoring other symbols) to encourage
989// editors to "bounce" quickly between locations, without showing a menu.
990static Location *getToggle(const TextDocumentPositionParams &Point,
991 LocatedSymbol &Sym) {
992 // Toggle only makes sense with two distinct locations.
993 if (!Sym.Definition || *Sym.Definition == Sym.PreferredDeclaration)
994 return nullptr;
995 if (Sym.Definition->uri.file() == Point.textDocument.uri.file() &&
996 Sym.Definition->range.contains(Point.position))
997 return &Sym.PreferredDeclaration;
998 if (Sym.PreferredDeclaration.uri.file() == Point.textDocument.uri.file() &&
999 Sym.PreferredDeclaration.range.contains(Point.position))
1000 return &*Sym.Definition;
1001 return nullptr;
1002}
1003
Sam McCall2c30fbc2018-10-18 12:32:04 +00001004void ClangdLSPServer::onGoToDefinition(const TextDocumentPositionParams &Params,
1005 Callback<std::vector<Location>> Reply) {
Sam McCall866ba2c2019-02-01 11:26:13 +00001006 Server->locateSymbolAt(
1007 Params.textDocument.uri.file(), Params.position,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001008 [Params, Reply = std::move(Reply)](
1009 llvm::Expected<std::vector<LocatedSymbol>> Symbols) mutable {
1010 if (!Symbols)
1011 return Reply(Symbols.takeError());
1012 std::vector<Location> Defs;
1013 for (auto &S : *Symbols) {
1014 if (Location *Toggle = getToggle(Params, S))
1015 return Reply(std::vector<Location>{std::move(*Toggle)});
1016 Defs.push_back(S.Definition.getValueOr(S.PreferredDeclaration));
1017 }
1018 Reply(std::move(Defs));
1019 });
Sam McCall866ba2c2019-02-01 11:26:13 +00001020}
1021
1022void ClangdLSPServer::onGoToDeclaration(
1023 const TextDocumentPositionParams &Params,
1024 Callback<std::vector<Location>> Reply) {
1025 Server->locateSymbolAt(
1026 Params.textDocument.uri.file(), Params.position,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001027 [Params, Reply = std::move(Reply)](
1028 llvm::Expected<std::vector<LocatedSymbol>> Symbols) mutable {
1029 if (!Symbols)
1030 return Reply(Symbols.takeError());
1031 std::vector<Location> Decls;
1032 for (auto &S : *Symbols) {
1033 if (Location *Toggle = getToggle(Params, S))
1034 return Reply(std::vector<Location>{std::move(*Toggle)});
1035 Decls.push_back(std::move(S.PreferredDeclaration));
1036 }
1037 Reply(std::move(Decls));
1038 });
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +00001039}
1040
Sam McCall111fe842019-05-07 07:55:35 +00001041void ClangdLSPServer::onSwitchSourceHeader(
1042 const TextDocumentIdentifier &Params,
Sam McCallb9ec3e92019-05-07 08:30:32 +00001043 Callback<llvm::Optional<URIForFile>> Reply) {
Haojian Wud6d5edd2019-10-01 10:21:15 +00001044 Server->switchSourceHeader(
1045 Params.uri.file(),
1046 [Reply = std::move(Reply),
1047 Params](llvm::Expected<llvm::Optional<clangd::Path>> Path) mutable {
1048 if (!Path)
1049 return Reply(Path.takeError());
1050 if (*Path)
Haojian Wu77c97002019-10-07 11:37:25 +00001051 return Reply(URIForFile::canonicalize(**Path, Params.uri.file()));
Haojian Wud6d5edd2019-10-01 10:21:15 +00001052 return Reply(llvm::None);
1053 });
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +00001054}
1055
Sam McCall2c30fbc2018-10-18 12:32:04 +00001056void ClangdLSPServer::onDocumentHighlight(
1057 const TextDocumentPositionParams &Params,
1058 Callback<std::vector<DocumentHighlight>> Reply) {
1059 Server->findDocumentHighlights(Params.textDocument.uri.file(),
1060 Params.position, std::move(Reply));
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +00001061}
1062
Sam McCall2c30fbc2018-10-18 12:32:04 +00001063void ClangdLSPServer::onHover(const TextDocumentPositionParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001064 Callback<llvm::Optional<Hover>> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +00001065 Server->findHover(Params.textDocument.uri.file(), Params.position,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001066 [Reply = std::move(Reply), this](
1067 llvm::Expected<llvm::Optional<HoverInfo>> H) mutable {
1068 if (!H)
1069 return Reply(H.takeError());
1070 if (!*H)
1071 return Reply(llvm::None);
Ilya Biryukovf9169d02019-05-29 10:01:00 +00001072
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001073 Hover R;
1074 R.contents.kind = HoverContentFormat;
1075 R.range = (*H)->SymRange;
1076 switch (HoverContentFormat) {
1077 case MarkupKind::PlainText:
1078 R.contents.value = (*H)->present().renderAsPlainText();
1079 return Reply(std::move(R));
1080 case MarkupKind::Markdown:
1081 R.contents.value = (*H)->present().renderAsMarkdown();
1082 return Reply(std::move(R));
1083 };
1084 llvm_unreachable("unhandled MarkupKind");
1085 });
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +00001086}
1087
Kadir Cetinkaya86658022019-03-19 09:27:04 +00001088void ClangdLSPServer::onTypeHierarchy(
1089 const TypeHierarchyParams &Params,
1090 Callback<Optional<TypeHierarchyItem>> Reply) {
1091 Server->typeHierarchy(Params.textDocument.uri.file(), Params.position,
1092 Params.resolve, Params.direction, std::move(Reply));
1093}
1094
Nathan Ridge087b0442019-07-13 03:24:48 +00001095void ClangdLSPServer::onResolveTypeHierarchy(
1096 const ResolveTypeHierarchyItemParams &Params,
1097 Callback<Optional<TypeHierarchyItem>> Reply) {
1098 Server->resolveTypeHierarchy(Params.item, Params.resolve, Params.direction,
1099 std::move(Reply));
1100}
1101
Simon Marchi88016782018-08-01 11:28:49 +00001102void ClangdLSPServer::applyConfiguration(
Sam McCallbc904612018-10-25 04:22:52 +00001103 const ConfigurationSettings &Settings) {
Simon Marchiabeed662018-10-16 15:55:03 +00001104 // Per-file update to the compilation database.
Sam McCallbc904612018-10-25 04:22:52 +00001105 bool ShouldReparseOpenFiles = false;
1106 for (auto &Entry : Settings.compilationDatabaseChanges) {
1107 /// The opened files need to be reparsed only when some existing
1108 /// entries are changed.
1109 PathRef File = Entry.first;
Sam McCallc55d09a2018-11-02 13:09:36 +00001110 auto Old = CDB->getCompileCommand(File);
1111 auto New =
1112 tooling::CompileCommand(std::move(Entry.second.workingDirectory), File,
1113 std::move(Entry.second.compilationCommand),
1114 /*Output=*/"");
Sam McCall6980edb2018-11-02 14:07:51 +00001115 if (Old != New) {
Sam McCallc55d09a2018-11-02 13:09:36 +00001116 CDB->setCompileCommand(File, std::move(New));
Sam McCall6980edb2018-11-02 14:07:51 +00001117 ShouldReparseOpenFiles = true;
1118 }
Alex Lorenzf8087862018-08-01 17:39:29 +00001119 }
Sam McCallbc904612018-10-25 04:22:52 +00001120 if (ShouldReparseOpenFiles)
1121 reparseOpenedFiles();
Simon Marchi5178f922018-02-22 14:00:39 +00001122}
1123
Johan Vikstroma848dab2019-07-04 07:53:12 +00001124void ClangdLSPServer::publishSemanticHighlighting(
1125 SemanticHighlightingParams Params) {
1126 notify("textDocument/semanticHighlighting", Params);
1127}
1128
Ilya Biryukov49c10712019-03-25 10:15:11 +00001129void ClangdLSPServer::publishDiagnostics(
1130 const URIForFile &File, std::vector<clangd::Diagnostic> Diagnostics) {
1131 // Publish diagnostics.
1132 notify("textDocument/publishDiagnostics",
1133 llvm::json::Object{
1134 {"uri", File},
1135 {"diagnostics", std::move(Diagnostics)},
1136 });
1137}
1138
Simon Marchi88016782018-08-01 11:28:49 +00001139// FIXME: This function needs to be properly tested.
1140void ClangdLSPServer::onChangeConfiguration(
Sam McCall2c30fbc2018-10-18 12:32:04 +00001141 const DidChangeConfigurationParams &Params) {
Simon Marchi88016782018-08-01 11:28:49 +00001142 applyConfiguration(Params.settings);
1143}
1144
Sam McCall2c30fbc2018-10-18 12:32:04 +00001145void ClangdLSPServer::onReference(const ReferenceParams &Params,
1146 Callback<std::vector<Location>> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +00001147 Server->findReferences(Params.textDocument.uri.file(), Params.position,
Haojian Wuc34f0222019-01-14 18:11:09 +00001148 CCOpts.Limit, std::move(Reply));
Sam McCall1ad142f2018-09-05 11:53:07 +00001149}
1150
Jan Korousb4067012018-11-27 16:40:46 +00001151void ClangdLSPServer::onSymbolInfo(const TextDocumentPositionParams &Params,
1152 Callback<std::vector<SymbolDetails>> Reply) {
1153 Server->symbolInfo(Params.textDocument.uri.file(), Params.position,
1154 std::move(Reply));
1155}
1156
Utkarsh Saxena55925da2019-09-24 13:38:33 +00001157void ClangdLSPServer::onSelectionRange(
1158 const SelectionRangeParams &Params,
1159 Callback<std::vector<SelectionRange>> Reply) {
1160 if (Params.positions.size() != 1) {
1161 elog("{0} positions provided to SelectionRange. Supports exactly one "
1162 "position.",
1163 Params.positions.size());
1164 return Reply(llvm::make_error<LSPError>(
1165 "SelectionRange supports exactly one position",
1166 ErrorCode::InvalidRequest));
1167 }
1168 Server->semanticRanges(
1169 Params.textDocument.uri.file(), Params.positions[0],
1170 [Reply = std::move(Reply)](
1171 llvm::Expected<std::vector<Range>> Ranges) mutable {
1172 if (!Ranges) {
1173 return Reply(Ranges.takeError());
1174 }
1175 std::vector<SelectionRange> Result;
1176 Result.emplace_back(render(std::move(*Ranges)));
1177 return Reply(std::move(Result));
1178 });
1179}
1180
Sam McCalla69698f2019-03-27 17:47:49 +00001181ClangdLSPServer::ClangdLSPServer(
1182 class Transport &Transp, const FileSystemProvider &FSProvider,
1183 const clangd::CodeCompleteOptions &CCOpts,
1184 llvm::Optional<Path> CompileCommandsDir, bool UseDirBasedCDB,
1185 llvm::Optional<OffsetEncoding> ForcedOffsetEncoding,
1186 const ClangdServer::Options &Opts)
Haojian Wu1ca0c582019-01-22 09:39:05 +00001187 : Transp(Transp), MsgHandler(new MessageHandler(*this)),
1188 FSProvider(FSProvider), CCOpts(CCOpts),
Sam McCalld1c9d112018-10-23 14:19:54 +00001189 SupportedSymbolKinds(defaultSymbolKinds()),
Kadir Cetinkaya133d46f2018-09-27 17:13:07 +00001190 SupportedCompletionItemKinds(defaultCompletionItemKinds()),
Sam McCallc55d09a2018-11-02 13:09:36 +00001191 UseDirBasedCDB(UseDirBasedCDB),
Sam McCalla69698f2019-03-27 17:47:49 +00001192 CompileCommandsDir(std::move(CompileCommandsDir)), ClangdServerOpts(Opts),
1193 NegotiatedOffsetEncoding(ForcedOffsetEncoding) {
Sam McCall2c30fbc2018-10-18 12:32:04 +00001194 // clang-format off
1195 MsgHandler->bind("initialize", &ClangdLSPServer::onInitialize);
1196 MsgHandler->bind("shutdown", &ClangdLSPServer::onShutdown);
Sam McCall422c8282018-11-26 16:00:11 +00001197 MsgHandler->bind("sync", &ClangdLSPServer::onSync);
Sam McCall2c30fbc2018-10-18 12:32:04 +00001198 MsgHandler->bind("textDocument/rangeFormatting", &ClangdLSPServer::onDocumentRangeFormatting);
1199 MsgHandler->bind("textDocument/onTypeFormatting", &ClangdLSPServer::onDocumentOnTypeFormatting);
1200 MsgHandler->bind("textDocument/formatting", &ClangdLSPServer::onDocumentFormatting);
1201 MsgHandler->bind("textDocument/codeAction", &ClangdLSPServer::onCodeAction);
1202 MsgHandler->bind("textDocument/completion", &ClangdLSPServer::onCompletion);
1203 MsgHandler->bind("textDocument/signatureHelp", &ClangdLSPServer::onSignatureHelp);
1204 MsgHandler->bind("textDocument/definition", &ClangdLSPServer::onGoToDefinition);
Sam McCall866ba2c2019-02-01 11:26:13 +00001205 MsgHandler->bind("textDocument/declaration", &ClangdLSPServer::onGoToDeclaration);
Sam McCall2c30fbc2018-10-18 12:32:04 +00001206 MsgHandler->bind("textDocument/references", &ClangdLSPServer::onReference);
1207 MsgHandler->bind("textDocument/switchSourceHeader", &ClangdLSPServer::onSwitchSourceHeader);
Haojian Wuf429ab62019-07-24 07:49:23 +00001208 MsgHandler->bind("textDocument/prepareRename", &ClangdLSPServer::onPrepareRename);
Sam McCall2c30fbc2018-10-18 12:32:04 +00001209 MsgHandler->bind("textDocument/rename", &ClangdLSPServer::onRename);
1210 MsgHandler->bind("textDocument/hover", &ClangdLSPServer::onHover);
1211 MsgHandler->bind("textDocument/documentSymbol", &ClangdLSPServer::onDocumentSymbol);
1212 MsgHandler->bind("workspace/executeCommand", &ClangdLSPServer::onCommand);
1213 MsgHandler->bind("textDocument/documentHighlight", &ClangdLSPServer::onDocumentHighlight);
1214 MsgHandler->bind("workspace/symbol", &ClangdLSPServer::onWorkspaceSymbol);
1215 MsgHandler->bind("textDocument/didOpen", &ClangdLSPServer::onDocumentDidOpen);
1216 MsgHandler->bind("textDocument/didClose", &ClangdLSPServer::onDocumentDidClose);
1217 MsgHandler->bind("textDocument/didChange", &ClangdLSPServer::onDocumentDidChange);
1218 MsgHandler->bind("workspace/didChangeWatchedFiles", &ClangdLSPServer::onFileEvent);
1219 MsgHandler->bind("workspace/didChangeConfiguration", &ClangdLSPServer::onChangeConfiguration);
Jan Korousb4067012018-11-27 16:40:46 +00001220 MsgHandler->bind("textDocument/symbolInfo", &ClangdLSPServer::onSymbolInfo);
Kadir Cetinkaya86658022019-03-19 09:27:04 +00001221 MsgHandler->bind("textDocument/typeHierarchy", &ClangdLSPServer::onTypeHierarchy);
Nathan Ridge087b0442019-07-13 03:24:48 +00001222 MsgHandler->bind("typeHierarchy/resolve", &ClangdLSPServer::onResolveTypeHierarchy);
Utkarsh Saxena55925da2019-09-24 13:38:33 +00001223 MsgHandler->bind("textDocument/selectionRange", &ClangdLSPServer::onSelectionRange);
Sam McCall2c30fbc2018-10-18 12:32:04 +00001224 // clang-format on
1225}
1226
Haojian Wuf2516342019-08-05 12:48:09 +00001227ClangdLSPServer::~ClangdLSPServer() { IsBeingDestroyed = true; }
Ilya Biryukov38d79772017-05-16 09:38:59 +00001228
Sam McCalldc8f3cf2018-10-17 07:32:05 +00001229bool ClangdLSPServer::run() {
Ilya Biryukovafb55542017-05-16 14:40:30 +00001230 // Run the Language Server loop.
Sam McCalldc8f3cf2018-10-17 07:32:05 +00001231 bool CleanExit = true;
Sam McCall2c30fbc2018-10-18 12:32:04 +00001232 if (auto Err = Transp.loop(*MsgHandler)) {
Sam McCalldc8f3cf2018-10-17 07:32:05 +00001233 elog("Transport error: {0}", std::move(Err));
1234 CleanExit = false;
1235 }
Ilya Biryukovafb55542017-05-16 14:40:30 +00001236
Ilya Biryukov652364b2018-09-26 05:48:29 +00001237 // Destroy ClangdServer to ensure all worker threads finish.
1238 Server.reset();
Sam McCalldc8f3cf2018-10-17 07:32:05 +00001239 return CleanExit && ShutdownRequestReceived;
Ilya Biryukov38d79772017-05-16 09:38:59 +00001240}
1241
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001242std::vector<Fix> ClangdLSPServer::getFixes(llvm::StringRef File,
Ilya Biryukov71028b82018-03-12 15:28:22 +00001243 const clangd::Diagnostic &D) {
Ilya Biryukov38d79772017-05-16 09:38:59 +00001244 std::lock_guard<std::mutex> Lock(FixItsMutex);
1245 auto DiagToFixItsIter = FixItsMap.find(File);
1246 if (DiagToFixItsIter == FixItsMap.end())
1247 return {};
1248
1249 const auto &DiagToFixItsMap = DiagToFixItsIter->second;
1250 auto FixItsIter = DiagToFixItsMap.find(D);
1251 if (FixItsIter == DiagToFixItsMap.end())
1252 return {};
1253
1254 return FixItsIter->second;
1255}
1256
Ilya Biryukovb0826bd2019-01-03 13:37:12 +00001257bool ClangdLSPServer::shouldRunCompletion(
1258 const CompletionParams &Params) const {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001259 llvm::StringRef Trigger = Params.context.triggerCharacter;
Ilya Biryukovb0826bd2019-01-03 13:37:12 +00001260 if (Params.context.triggerKind != CompletionTriggerKind::TriggerCharacter ||
1261 (Trigger != ">" && Trigger != ":"))
1262 return true;
1263
1264 auto Code = DraftMgr.getDraft(Params.textDocument.uri.file());
1265 if (!Code)
1266 return true; // completion code will log the error for untracked doc.
1267
1268 // A completion request is sent when the user types '>' or ':', but we only
1269 // want to trigger on '->' and '::'. We check the preceeding character to make
1270 // sure it matches what we expected.
1271 // Running the lexer here would be more robust (e.g. we can detect comments
1272 // and avoid triggering completion there), but we choose to err on the side
1273 // of simplicity here.
1274 auto Offset = positionToOffset(*Code, Params.position,
1275 /*AllowColumnsBeyondLineLength=*/false);
1276 if (!Offset) {
1277 vlog("could not convert position '{0}' to offset for file '{1}'",
1278 Params.position, Params.textDocument.uri.file());
1279 return true;
1280 }
1281 if (*Offset < 2)
1282 return false;
1283
1284 if (Trigger == ">")
1285 return (*Code)[*Offset - 2] == '-'; // trigger only on '->'.
1286 if (Trigger == ":")
1287 return (*Code)[*Offset - 2] == ':'; // trigger only on '::'.
1288 assert(false && "unhandled trigger character");
1289 return true;
1290}
1291
Johan Vikstroma848dab2019-07-04 07:53:12 +00001292void ClangdLSPServer::onHighlightingsReady(
Haojian Wu0a6000f2019-08-26 08:38:45 +00001293 PathRef File, std::vector<HighlightingToken> Highlightings) {
Johan Vikstromc2653ef22019-08-01 08:08:44 +00001294 std::vector<HighlightingToken> Old;
1295 std::vector<HighlightingToken> HighlightingsCopy = Highlightings;
1296 {
1297 std::lock_guard<std::mutex> Lock(HighlightingsMutex);
1298 Old = std::move(FileToHighlightings[File]);
1299 FileToHighlightings[File] = std::move(HighlightingsCopy);
1300 }
1301 // LSP allows us to send incremental edits of highlightings. Also need to diff
1302 // to remove highlightings from tokens that should no longer have them.
Haojian Wu0a6000f2019-08-26 08:38:45 +00001303 std::vector<LineHighlightings> Diffed = diffHighlightings(Highlightings, Old);
Johan Vikstroma848dab2019-07-04 07:53:12 +00001304 publishSemanticHighlighting(
1305 {{URIForFile::canonicalize(File, /*TUPath=*/File)},
Johan Vikstromc2653ef22019-08-01 08:08:44 +00001306 toSemanticHighlightingInformation(Diffed)});
Johan Vikstroma848dab2019-07-04 07:53:12 +00001307}
1308
Sam McCalla7bb0cc2018-03-12 23:22:35 +00001309void ClangdLSPServer::onDiagnosticsReady(PathRef File,
1310 std::vector<Diag> Diagnostics) {
Eric Liu4d814a92018-11-28 10:30:42 +00001311 auto URI = URIForFile::canonicalize(File, /*TUPath=*/File);
Sam McCall16e70702018-10-24 07:59:38 +00001312 std::vector<Diagnostic> LSPDiagnostics;
Ilya Biryukov38d79772017-05-16 09:38:59 +00001313 DiagnosticToReplacementMap LocalFixIts; // Temporary storage
Sam McCalla7bb0cc2018-03-12 23:22:35 +00001314 for (auto &Diag : Diagnostics) {
Sam McCall16e70702018-10-24 07:59:38 +00001315 toLSPDiags(Diag, URI, DiagOpts,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001316 [&](clangd::Diagnostic Diag, llvm::ArrayRef<Fix> Fixes) {
Sam McCall16e70702018-10-24 07:59:38 +00001317 auto &FixItsForDiagnostic = LocalFixIts[Diag];
1318 llvm::copy(Fixes, std::back_inserter(FixItsForDiagnostic));
1319 LSPDiagnostics.push_back(std::move(Diag));
1320 });
Ilya Biryukov38d79772017-05-16 09:38:59 +00001321 }
1322
1323 // Cache FixIts
1324 {
Ilya Biryukov38d79772017-05-16 09:38:59 +00001325 std::lock_guard<std::mutex> Lock(FixItsMutex);
1326 FixItsMap[File] = LocalFixIts;
1327 }
1328
Ilya Biryukov49c10712019-03-25 10:15:11 +00001329 // Send a notification to the LSP client.
1330 publishDiagnostics(URI, std::move(LSPDiagnostics));
Ilya Biryukov38d79772017-05-16 09:38:59 +00001331}
Simon Marchi9569fd52018-03-16 14:30:42 +00001332
Haojian Wub6188492018-12-20 15:39:12 +00001333void ClangdLSPServer::onFileUpdated(PathRef File, const TUStatus &Status) {
1334 if (!SupportFileStatus)
1335 return;
1336 // FIXME: we don't emit "BuildingFile" and `RunningAction`, as these
1337 // two statuses are running faster in practice, which leads the UI constantly
1338 // changing, and doesn't provide much value. We may want to emit status at a
1339 // reasonable time interval (e.g. 0.5s).
1340 if (Status.Action.S == TUAction::BuildingFile ||
1341 Status.Action.S == TUAction::RunningAction)
1342 return;
1343 notify("textDocument/clangd.fileStatus", Status.render(File));
1344}
1345
Simon Marchi9569fd52018-03-16 14:30:42 +00001346void ClangdLSPServer::reparseOpenedFiles() {
1347 for (const Path &FilePath : DraftMgr.getActiveFiles())
Ilya Biryukov652364b2018-09-26 05:48:29 +00001348 Server->addDocument(FilePath, *DraftMgr.getDraft(FilePath),
1349 WantDiagnostics::Auto);
Simon Marchi9569fd52018-03-16 14:30:42 +00001350}
Alex Lorenzf8087862018-08-01 17:39:29 +00001351
Sam McCallc008af62018-10-20 15:30:37 +00001352} // namespace clangd
1353} // namespace clang