blob: 69b4308a1c9e6f1161d16520ef49a6c9ecef37b2 [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>
Kadir Cetinkaya5b270932019-09-09 12:28:44 +000036#include <string>
Utkarsh Saxena55925da2019-09-24 13:38:33 +000037#include <vector>
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +000038
Sam McCallc008af62018-10-20 15:30:37 +000039namespace clang {
40namespace clangd {
Ilya Biryukovafb55542017-05-16 14:40:30 +000041namespace {
Ilya Biryukovcce67a32019-01-29 14:17:36 +000042/// Transforms a tweak into a code action that would apply it if executed.
43/// EXPECTS: T.prepare() was called and returned true.
44CodeAction toCodeAction(const ClangdServer::TweakRef &T, const URIForFile &File,
45 Range Selection) {
46 CodeAction CA;
47 CA.title = T.Title;
Sam McCall395fde72019-06-18 13:37:54 +000048 switch (T.Intent) {
49 case Tweak::Refactor:
50 CA.kind = CodeAction::REFACTOR_KIND;
51 break;
52 case Tweak::Info:
53 CA.kind = CodeAction::INFO_KIND;
54 break;
55 }
Ilya Biryukovcce67a32019-01-29 14:17:36 +000056 // This tweak may have an expensive second stage, we only run it if the user
57 // actually chooses it in the UI. We reply with a command that would run the
58 // corresponding tweak.
59 // FIXME: for some tweaks, computing the edits is cheap and we could send them
60 // directly.
61 CA.command.emplace();
62 CA.command->title = T.Title;
63 CA.command->command = Command::CLANGD_APPLY_TWEAK;
64 CA.command->tweakArgs.emplace();
65 CA.command->tweakArgs->file = File;
66 CA.command->tweakArgs->tweakID = T.ID;
67 CA.command->tweakArgs->selection = Selection;
68 return CA;
Simon Pilgrime9a136b2019-02-03 14:08:30 +000069}
Ilya Biryukovcce67a32019-01-29 14:17:36 +000070
Ilya Biryukov19d75602018-11-23 15:21:19 +000071void adjustSymbolKinds(llvm::MutableArrayRef<DocumentSymbol> Syms,
72 SymbolKindBitset Kinds) {
73 for (auto &S : Syms) {
74 S.kind = adjustKindToCapability(S.kind, Kinds);
75 adjustSymbolKinds(S.children, Kinds);
76 }
77}
78
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +000079SymbolKindBitset defaultSymbolKinds() {
80 SymbolKindBitset Defaults;
81 for (size_t I = SymbolKindMin; I <= static_cast<size_t>(SymbolKind::Array);
82 ++I)
83 Defaults.set(I);
84 return Defaults;
85}
86
Kadir Cetinkaya133d46f2018-09-27 17:13:07 +000087CompletionItemKindBitset defaultCompletionItemKinds() {
88 CompletionItemKindBitset Defaults;
89 for (size_t I = CompletionItemKindMin;
90 I <= static_cast<size_t>(CompletionItemKind::Reference); ++I)
91 Defaults.set(I);
92 return Defaults;
93}
94
Haojian Wu1ca2ee42019-07-04 12:27:21 +000095// Build a lookup table (HighlightingKind => {TextMate Scopes}), which is sent
96// to the LSP client.
97std::vector<std::vector<std::string>> buildHighlightScopeLookupTable() {
98 std::vector<std::vector<std::string>> LookupTable;
99 // HighlightingKind is using as the index.
Ilya Biryukov63d5d162019-09-09 08:57:17 +0000100 for (int KindValue = 0; KindValue <= (int)HighlightingKind::LastKind;
Haojian Wu1ca2ee42019-07-04 12:27:21 +0000101 ++KindValue)
102 LookupTable.push_back({toTextMateScope((HighlightingKind)(KindValue))});
103 return LookupTable;
104}
105
Haojian Wu852bafa2019-10-23 14:40:20 +0200106// Makes sure edits in \p FE are applicable to latest file contents reported by
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000107// editor. If not generates an error message containing information about files
108// that needs to be saved.
Haojian Wu852bafa2019-10-23 14:40:20 +0200109llvm::Error validateEdits(const DraftStore &DraftMgr, const FileEdits &FE) {
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000110 size_t InvalidFileCount = 0;
111 llvm::StringRef LastInvalidFile;
Haojian Wu852bafa2019-10-23 14:40:20 +0200112 for (const auto &It : FE) {
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000113 if (auto Draft = DraftMgr.getDraft(It.first())) {
114 // If the file is open in user's editor, make sure the version we
115 // saw and current version are compatible as this is the text that
116 // will be replaced by editors.
117 if (!It.second.canApplyTo(*Draft)) {
118 ++InvalidFileCount;
119 LastInvalidFile = It.first();
120 }
121 }
122 }
123 if (!InvalidFileCount)
124 return llvm::Error::success();
125 if (InvalidFileCount == 1)
126 return llvm::createStringError(llvm::inconvertibleErrorCode(),
127 "File must be saved first: " +
128 LastInvalidFile);
129 return llvm::createStringError(
130 llvm::inconvertibleErrorCode(),
131 "Files must be saved first: " + LastInvalidFile + " (and " +
132 llvm::to_string(InvalidFileCount - 1) + " others)");
133}
134
Utkarsh Saxena55925da2019-09-24 13:38:33 +0000135// Converts a list of Ranges to a LinkedList of SelectionRange.
136SelectionRange render(const std::vector<Range> &Ranges) {
137 if (Ranges.empty())
138 return {};
139 SelectionRange Result;
140 Result.range = Ranges[0];
141 auto *Next = &Result.parent;
142 for (const auto &R : llvm::make_range(Ranges.begin() + 1, Ranges.end())) {
143 *Next = std::make_unique<SelectionRange>();
144 Next->get()->range = R;
145 Next = &Next->get()->parent;
146 }
147 return Result;
148}
149
Ilya Biryukovafb55542017-05-16 14:40:30 +0000150} // namespace
151
Sam McCall2c30fbc2018-10-18 12:32:04 +0000152// MessageHandler dispatches incoming LSP messages.
153// It handles cross-cutting concerns:
154// - serializes/deserializes protocol objects to JSON
155// - logging of inbound messages
156// - cancellation handling
157// - basic call tracing
Sam McCall3d0adbe2018-10-18 14:41:50 +0000158// MessageHandler ensures that initialize() is called before any other handler.
Sam McCall2c30fbc2018-10-18 12:32:04 +0000159class ClangdLSPServer::MessageHandler : public Transport::MessageHandler {
160public:
161 MessageHandler(ClangdLSPServer &Server) : Server(Server) {}
162
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000163 bool onNotify(llvm::StringRef Method, llvm::json::Value Params) override {
Sam McCalla69698f2019-03-27 17:47:49 +0000164 WithContext HandlerContext(handlerContext());
Sam McCall2c30fbc2018-10-18 12:32:04 +0000165 log("<-- {0}", Method);
166 if (Method == "exit")
167 return false;
Sam McCall3d0adbe2018-10-18 14:41:50 +0000168 if (!Server.Server)
169 elog("Notification {0} before initialization", Method);
170 else if (Method == "$/cancelRequest")
Sam McCall2c30fbc2018-10-18 12:32:04 +0000171 onCancel(std::move(Params));
172 else if (auto Handler = Notifications.lookup(Method))
173 Handler(std::move(Params));
174 else
175 log("unhandled notification {0}", Method);
176 return true;
177 }
178
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000179 bool onCall(llvm::StringRef Method, llvm::json::Value Params,
180 llvm::json::Value ID) override {
Sam McCalla69698f2019-03-27 17:47:49 +0000181 WithContext HandlerContext(handlerContext());
Sam McCalle2f3a732018-10-24 14:26:26 +0000182 // Calls can be canceled by the client. Add cancellation context.
183 WithContext WithCancel(cancelableRequestContext(ID));
184 trace::Span Tracer(Method);
185 SPAN_ATTACH(Tracer, "Params", Params);
186 ReplyOnce Reply(ID, Method, &Server, Tracer.Args);
Sam McCall2c30fbc2018-10-18 12:32:04 +0000187 log("<-- {0}({1})", Method, ID);
Sam McCall3d0adbe2018-10-18 14:41:50 +0000188 if (!Server.Server && Method != "initialize") {
189 elog("Call {0} before initialization.", Method);
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000190 Reply(llvm::make_error<LSPError>("server not initialized",
191 ErrorCode::ServerNotInitialized));
Sam McCall3d0adbe2018-10-18 14:41:50 +0000192 } else if (auto Handler = Calls.lookup(Method))
Sam McCalle2f3a732018-10-24 14:26:26 +0000193 Handler(std::move(Params), std::move(Reply));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000194 else
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000195 Reply(llvm::make_error<LSPError>("method not found",
196 ErrorCode::MethodNotFound));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000197 return true;
198 }
199
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000200 bool onReply(llvm::json::Value ID,
201 llvm::Expected<llvm::json::Value> Result) override {
Sam McCalla69698f2019-03-27 17:47:49 +0000202 WithContext HandlerContext(handlerContext());
Haojian Wuf2516342019-08-05 12:48:09 +0000203
204 Callback<llvm::json::Value> ReplyHandler = nullptr;
205 if (auto IntID = ID.getAsInteger()) {
206 std::lock_guard<std::mutex> Mutex(CallMutex);
207 // Find a corresponding callback for the request ID;
208 for (size_t Index = 0; Index < ReplyCallbacks.size(); ++Index) {
209 if (ReplyCallbacks[Index].first == *IntID) {
210 ReplyHandler = std::move(ReplyCallbacks[Index].second);
211 ReplyCallbacks.erase(ReplyCallbacks.begin() +
212 Index); // remove the entry
213 break;
214 }
215 }
216 }
217
218 if (!ReplyHandler) {
219 // No callback being found, use a default log callback.
220 ReplyHandler = [&ID](llvm::Expected<llvm::json::Value> Result) {
221 elog("received a reply with ID {0}, but there was no such call", ID);
222 if (!Result)
223 llvm::consumeError(Result.takeError());
224 };
225 }
226
227 // Log and run the reply handler.
228 if (Result) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000229 log("<-- reply({0})", ID);
Haojian Wuf2516342019-08-05 12:48:09 +0000230 ReplyHandler(std::move(Result));
231 } else {
232 auto Err = Result.takeError();
233 log("<-- reply({0}) error: {1}", ID, Err);
234 ReplyHandler(std::move(Err));
235 }
Sam McCall2c30fbc2018-10-18 12:32:04 +0000236 return true;
237 }
238
239 // Bind an LSP method name to a call.
Sam McCalle2f3a732018-10-24 14:26:26 +0000240 template <typename Param, typename Result>
Sam McCall2c30fbc2018-10-18 12:32:04 +0000241 void bind(const char *Method,
Sam McCalle2f3a732018-10-24 14:26:26 +0000242 void (ClangdLSPServer::*Handler)(const Param &, Callback<Result>)) {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000243 Calls[Method] = [Method, Handler, this](llvm::json::Value RawParams,
Sam McCalle2f3a732018-10-24 14:26:26 +0000244 ReplyOnce Reply) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000245 Param P;
Sam McCalle2f3a732018-10-24 14:26:26 +0000246 if (fromJSON(RawParams, P)) {
247 (Server.*Handler)(P, std::move(Reply));
248 } else {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000249 elog("Failed to decode {0} request.", Method);
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000250 Reply(llvm::make_error<LSPError>("failed to decode request",
251 ErrorCode::InvalidRequest));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000252 }
Sam McCall2c30fbc2018-10-18 12:32:04 +0000253 };
254 }
255
Haojian Wuf2516342019-08-05 12:48:09 +0000256 // Bind a reply callback to a request. The callback will be invoked when
257 // clangd receives the reply from the LSP client.
258 // Return a call id of the request.
259 llvm::json::Value bindReply(Callback<llvm::json::Value> Reply) {
260 llvm::Optional<std::pair<int, Callback<llvm::json::Value>>> OldestCB;
261 int ID;
262 {
263 std::lock_guard<std::mutex> Mutex(CallMutex);
264 ID = NextCallID++;
265 ReplyCallbacks.emplace_back(ID, std::move(Reply));
266
267 // If the queue overflows, we assume that the client didn't reply the
268 // oldest request, and run the corresponding callback which replies an
269 // error to the client.
270 if (ReplyCallbacks.size() > MaxReplayCallbacks) {
271 elog("more than {0} outstanding LSP calls, forgetting about {1}",
272 MaxReplayCallbacks, ReplyCallbacks.front().first);
273 OldestCB = std::move(ReplyCallbacks.front());
274 ReplyCallbacks.pop_front();
275 }
276 }
277 if (OldestCB)
278 OldestCB->second(llvm::createStringError(
279 llvm::inconvertibleErrorCode(),
280 llvm::formatv("failed to receive a client reply for request ({0})",
281 OldestCB->first)));
282 return ID;
283 }
284
Sam McCall2c30fbc2018-10-18 12:32:04 +0000285 // Bind an LSP method name to a notification.
286 template <typename Param>
287 void bind(const char *Method,
288 void (ClangdLSPServer::*Handler)(const Param &)) {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000289 Notifications[Method] = [Method, Handler,
290 this](llvm::json::Value RawParams) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000291 Param P;
292 if (!fromJSON(RawParams, P)) {
293 elog("Failed to decode {0} request.", Method);
294 return;
295 }
296 trace::Span Tracer(Method);
297 SPAN_ATTACH(Tracer, "Params", RawParams);
298 (Server.*Handler)(P);
299 };
300 }
301
302private:
Sam McCalle2f3a732018-10-24 14:26:26 +0000303 // Function object to reply to an LSP call.
304 // Each instance must be called exactly once, otherwise:
305 // - the bug is logged, and (in debug mode) an assert will fire
306 // - if there was no reply, an error reply is sent
307 // - if there were multiple replies, only the first is sent
308 class ReplyOnce {
309 std::atomic<bool> Replied = {false};
Sam McCalld7babe42018-10-24 15:18:40 +0000310 std::chrono::steady_clock::time_point Start;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000311 llvm::json::Value ID;
Sam McCalle2f3a732018-10-24 14:26:26 +0000312 std::string Method;
313 ClangdLSPServer *Server; // Null when moved-from.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000314 llvm::json::Object *TraceArgs;
Sam McCalle2f3a732018-10-24 14:26:26 +0000315
316 public:
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000317 ReplyOnce(const llvm::json::Value &ID, llvm::StringRef Method,
318 ClangdLSPServer *Server, llvm::json::Object *TraceArgs)
Sam McCalld7babe42018-10-24 15:18:40 +0000319 : Start(std::chrono::steady_clock::now()), ID(ID), Method(Method),
320 Server(Server), TraceArgs(TraceArgs) {
Sam McCalle2f3a732018-10-24 14:26:26 +0000321 assert(Server);
322 }
323 ReplyOnce(ReplyOnce &&Other)
Sam McCalld7babe42018-10-24 15:18:40 +0000324 : Replied(Other.Replied.load()), Start(Other.Start),
325 ID(std::move(Other.ID)), Method(std::move(Other.Method)),
326 Server(Other.Server), TraceArgs(Other.TraceArgs) {
Sam McCalle2f3a732018-10-24 14:26:26 +0000327 Other.Server = nullptr;
328 }
Ilya Biryukov22fa4652019-01-03 13:28:05 +0000329 ReplyOnce &operator=(ReplyOnce &&) = delete;
Sam McCalle2f3a732018-10-24 14:26:26 +0000330 ReplyOnce(const ReplyOnce &) = delete;
Ilya Biryukov22fa4652019-01-03 13:28:05 +0000331 ReplyOnce &operator=(const ReplyOnce &) = delete;
Sam McCalle2f3a732018-10-24 14:26:26 +0000332
333 ~ReplyOnce() {
Haojian Wuf2516342019-08-05 12:48:09 +0000334 // There's one legitimate reason to never reply to a request: clangd's
335 // request handler send a call to the client (e.g. applyEdit) and the
336 // client never replied. In this case, the ReplyOnce is owned by
337 // ClangdLSPServer's reply callback table and is destroyed along with the
338 // server. We don't attempt to send a reply in this case, there's little
339 // to be gained from doing so.
340 if (Server && !Server->IsBeingDestroyed && !Replied) {
Sam McCalle2f3a732018-10-24 14:26:26 +0000341 elog("No reply to message {0}({1})", Method, ID);
342 assert(false && "must reply to all calls!");
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000343 (*this)(llvm::make_error<LSPError>("server failed to reply",
344 ErrorCode::InternalError));
Sam McCalle2f3a732018-10-24 14:26:26 +0000345 }
346 }
347
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000348 void operator()(llvm::Expected<llvm::json::Value> Reply) {
Sam McCalle2f3a732018-10-24 14:26:26 +0000349 assert(Server && "moved-from!");
350 if (Replied.exchange(true)) {
351 elog("Replied twice to message {0}({1})", Method, ID);
352 assert(false && "must reply to each call only once!");
353 return;
354 }
Sam McCalld7babe42018-10-24 15:18:40 +0000355 auto Duration = std::chrono::steady_clock::now() - Start;
356 if (Reply) {
357 log("--> reply:{0}({1}) {2:ms}", Method, ID, Duration);
358 if (TraceArgs)
Sam McCalle2f3a732018-10-24 14:26:26 +0000359 (*TraceArgs)["Reply"] = *Reply;
Sam McCalld7babe42018-10-24 15:18:40 +0000360 std::lock_guard<std::mutex> Lock(Server->TranspWriter);
361 Server->Transp.reply(std::move(ID), std::move(Reply));
362 } else {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000363 llvm::Error Err = Reply.takeError();
Sam McCalld7babe42018-10-24 15:18:40 +0000364 log("--> reply:{0}({1}) {2:ms}, error: {3}", Method, ID, Duration, Err);
365 if (TraceArgs)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000366 (*TraceArgs)["Error"] = llvm::to_string(Err);
Sam McCalld7babe42018-10-24 15:18:40 +0000367 std::lock_guard<std::mutex> Lock(Server->TranspWriter);
368 Server->Transp.reply(std::move(ID), std::move(Err));
Sam McCalle2f3a732018-10-24 14:26:26 +0000369 }
Sam McCalle2f3a732018-10-24 14:26:26 +0000370 }
371 };
372
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000373 llvm::StringMap<std::function<void(llvm::json::Value)>> Notifications;
374 llvm::StringMap<std::function<void(llvm::json::Value, ReplyOnce)>> Calls;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000375
376 // Method calls may be cancelled by ID, so keep track of their state.
377 // This needs a mutex: handlers may finish on a different thread, and that's
378 // when we clean up entries in the map.
379 mutable std::mutex RequestCancelersMutex;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000380 llvm::StringMap<std::pair<Canceler, /*Cookie*/ unsigned>> RequestCancelers;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000381 unsigned NextRequestCookie = 0; // To disambiguate reused IDs, see below.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000382 void onCancel(const llvm::json::Value &Params) {
383 const llvm::json::Value *ID = nullptr;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000384 if (auto *O = Params.getAsObject())
385 ID = O->get("id");
386 if (!ID) {
387 elog("Bad cancellation request: {0}", Params);
388 return;
389 }
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000390 auto StrID = llvm::to_string(*ID);
Sam McCall2c30fbc2018-10-18 12:32:04 +0000391 std::lock_guard<std::mutex> Lock(RequestCancelersMutex);
392 auto It = RequestCancelers.find(StrID);
393 if (It != RequestCancelers.end())
394 It->second.first(); // Invoke the canceler.
395 }
Sam McCalla69698f2019-03-27 17:47:49 +0000396
397 Context handlerContext() const {
398 return Context::current().derive(
399 kCurrentOffsetEncoding,
400 Server.NegotiatedOffsetEncoding.getValueOr(OffsetEncoding::UTF16));
401 }
402
Sam McCall2c30fbc2018-10-18 12:32:04 +0000403 // We run cancelable requests in a context that does two things:
404 // - allows cancellation using RequestCancelers[ID]
405 // - cleans up the entry in RequestCancelers when it's no longer needed
406 // If a client reuses an ID, the last wins and the first cannot be canceled.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000407 Context cancelableRequestContext(const llvm::json::Value &ID) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000408 auto Task = cancelableTask();
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000409 auto StrID = llvm::to_string(ID); // JSON-serialize ID for map key.
Sam McCall2c30fbc2018-10-18 12:32:04 +0000410 auto Cookie = NextRequestCookie++; // No lock, only called on main thread.
411 {
412 std::lock_guard<std::mutex> Lock(RequestCancelersMutex);
413 RequestCancelers[StrID] = {std::move(Task.second), Cookie};
414 }
415 // When the request ends, we can clean up the entry we just added.
416 // The cookie lets us check that it hasn't been overwritten due to ID
417 // reuse.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000418 return Task.first.derive(llvm::make_scope_exit([this, StrID, Cookie] {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000419 std::lock_guard<std::mutex> Lock(RequestCancelersMutex);
420 auto It = RequestCancelers.find(StrID);
421 if (It != RequestCancelers.end() && It->second.second == Cookie)
422 RequestCancelers.erase(It);
423 }));
424 }
425
Kadir Cetinkaya9a3a87d2019-10-09 13:59:31 +0000426 // The maximum number of callbacks held in clangd.
427 //
428 // We bound the maximum size to the pending map to prevent memory leakage
429 // for cases where LSP clients don't reply for the request.
430 // This has to go after RequestCancellers and RequestCancellersMutex since it
431 // can contain a callback that has a cancelable context.
432 static constexpr int MaxReplayCallbacks = 100;
433 mutable std::mutex CallMutex;
434 int NextCallID = 0; /* GUARDED_BY(CallMutex) */
435 std::deque<std::pair</*RequestID*/ int,
436 /*ReplyHandler*/ Callback<llvm::json::Value>>>
437 ReplyCallbacks; /* GUARDED_BY(CallMutex) */
438
Sam McCall2c30fbc2018-10-18 12:32:04 +0000439 ClangdLSPServer &Server;
440};
Haojian Wuf2516342019-08-05 12:48:09 +0000441constexpr int ClangdLSPServer::MessageHandler::MaxReplayCallbacks;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000442
443// call(), notify(), and reply() wrap the Transport, adding logging and locking.
Haojian Wuf2516342019-08-05 12:48:09 +0000444void ClangdLSPServer::callRaw(StringRef Method, llvm::json::Value Params,
445 Callback<llvm::json::Value> CB) {
446 auto ID = MsgHandler->bindReply(std::move(CB));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000447 log("--> {0}({1})", Method, ID);
Sam McCall2c30fbc2018-10-18 12:32:04 +0000448 std::lock_guard<std::mutex> Lock(TranspWriter);
449 Transp.call(Method, std::move(Params), ID);
450}
451
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000452void ClangdLSPServer::notify(llvm::StringRef Method, llvm::json::Value Params) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000453 log("--> {0}", Method);
454 std::lock_guard<std::mutex> Lock(TranspWriter);
455 Transp.notify(Method, std::move(Params));
456}
457
Sam McCall2c30fbc2018-10-18 12:32:04 +0000458void ClangdLSPServer::onInitialize(const InitializeParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000459 Callback<llvm::json::Value> Reply) {
Sam McCalla69698f2019-03-27 17:47:49 +0000460 // Determine character encoding first as it affects constructed ClangdServer.
461 if (Params.capabilities.offsetEncoding && !NegotiatedOffsetEncoding) {
462 NegotiatedOffsetEncoding = OffsetEncoding::UTF16; // fallback
463 for (OffsetEncoding Supported : *Params.capabilities.offsetEncoding)
464 if (Supported != OffsetEncoding::UnsupportedEncoding) {
465 NegotiatedOffsetEncoding = Supported;
466 break;
467 }
468 }
Sam McCalla69698f2019-03-27 17:47:49 +0000469
Johan Vikstroma848dab2019-07-04 07:53:12 +0000470 ClangdServerOpts.SemanticHighlighting =
471 Params.capabilities.SemanticHighlighting;
Sam McCall0d9b40f2018-10-19 15:42:23 +0000472 if (Params.rootUri && *Params.rootUri)
473 ClangdServerOpts.WorkspaceRoot = Params.rootUri->file();
474 else if (Params.rootPath && !Params.rootPath->empty())
475 ClangdServerOpts.WorkspaceRoot = *Params.rootPath;
Sam McCall3d0adbe2018-10-18 14:41:50 +0000476 if (Server)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000477 return Reply(llvm::make_error<LSPError>("server already initialized",
478 ErrorCode::InvalidRequest));
Sam McCallbc904612018-10-25 04:22:52 +0000479 if (const auto &Dir = Params.initializationOptions.compilationDatabasePath)
480 CompileCommandsDir = Dir;
Kadir Cetinkaya256247c2019-06-26 07:45:27 +0000481 if (UseDirBasedCDB) {
Jonas Devlieghere1c705d92019-08-14 23:52:23 +0000482 BaseCDB = std::make_unique<DirectoryBasedGlobalCompilationDatabase>(
Sam McCallc55d09a2018-11-02 13:09:36 +0000483 CompileCommandsDir);
Kadir Cetinkaya256247c2019-06-26 07:45:27 +0000484 BaseCDB = getQueryDriverDatabase(
485 llvm::makeArrayRef(ClangdServerOpts.QueryDriverGlobs),
486 std::move(BaseCDB));
487 }
Sam McCall99768b22019-11-29 19:37:48 +0100488 auto Mangler = CommandMangler::detect();
489 if (ClangdServerOpts.ResourceDir)
490 Mangler.ResourceDir = *ClangdServerOpts.ResourceDir;
Kadir Cetinkayabe6b35d2019-01-22 09:10:20 +0000491 CDB.emplace(BaseCDB.get(), Params.initializationOptions.fallbackFlags,
Sam McCall99768b22019-11-29 19:37:48 +0100492 tooling::ArgumentsAdjuster(Mangler));
Kadir Cetinkaya9d662472019-10-15 14:20:52 +0000493 {
494 // Switch caller's context with LSPServer's background context. Since we
495 // rather want to propagate information from LSPServer's context into the
496 // Server, CDB, etc.
497 WithContext MainContext(BackgroundContext.clone());
498 llvm::Optional<WithContextValue> WithOffsetEncoding;
499 if (NegotiatedOffsetEncoding)
500 WithOffsetEncoding.emplace(kCurrentOffsetEncoding,
501 *NegotiatedOffsetEncoding);
502 Server.emplace(*CDB, FSProvider, static_cast<DiagnosticsConsumer &>(*this),
503 ClangdServerOpts);
504 }
Sam McCallbc904612018-10-25 04:22:52 +0000505 applyConfiguration(Params.initializationOptions.ConfigSettings);
Simon Marchi88016782018-08-01 11:28:49 +0000506
Sam McCallbf6a2fc2018-10-17 07:33:42 +0000507 CCOpts.EnableSnippets = Params.capabilities.CompletionSnippets;
Sam McCall8d412942019-06-18 11:57:26 +0000508 CCOpts.IncludeFixIts = Params.capabilities.CompletionFixes;
Sam McCall5f092e32019-07-08 17:27:15 +0000509 if (!CCOpts.BundleOverloads.hasValue())
510 CCOpts.BundleOverloads = Params.capabilities.HasSignatureHelp;
Sam McCallbf6a2fc2018-10-17 07:33:42 +0000511 DiagOpts.EmbedFixesInDiagnostics = Params.capabilities.DiagnosticFixes;
512 DiagOpts.SendDiagnosticCategory = Params.capabilities.DiagnosticCategory;
Sam McCallc9e4ee92019-04-18 15:17:07 +0000513 DiagOpts.EmitRelatedLocations =
514 Params.capabilities.DiagnosticRelatedInformation;
Sam McCallbf6a2fc2018-10-17 07:33:42 +0000515 if (Params.capabilities.WorkspaceSymbolKinds)
516 SupportedSymbolKinds |= *Params.capabilities.WorkspaceSymbolKinds;
517 if (Params.capabilities.CompletionItemKinds)
518 SupportedCompletionItemKinds |= *Params.capabilities.CompletionItemKinds;
519 SupportsCodeAction = Params.capabilities.CodeActionStructure;
Ilya Biryukov19d75602018-11-23 15:21:19 +0000520 SupportsHierarchicalDocumentSymbol =
521 Params.capabilities.HierarchicalDocumentSymbol;
Haojian Wub6188492018-12-20 15:39:12 +0000522 SupportFileStatus = Params.initializationOptions.FileStatus;
Ilya Biryukovf9169d02019-05-29 10:01:00 +0000523 HoverContentFormat = Params.capabilities.HoverContentFormat;
Ilya Biryukov4ef0f822019-06-04 09:36:59 +0000524 SupportsOffsetsInSignatureHelp = Params.capabilities.OffsetsInSignatureHelp;
Haojian Wuf429ab62019-07-24 07:49:23 +0000525
526 // Per LSP, renameProvider can be either boolean or RenameOptions.
527 // RenameOptions will be specified if the client states it supports prepare.
528 llvm::json::Value RenameProvider =
529 llvm::json::Object{{"prepareProvider", true}};
530 if (!Params.capabilities.RenamePrepareSupport) // Only boolean allowed per LSP
531 RenameProvider = true;
532
Haojian Wu08d93f12019-08-22 14:53:45 +0000533 // Per LSP, codeActionProvide can be either boolean or CodeActionOptions.
534 // CodeActionOptions is only valid if the client supports action literal
535 // via textDocument.codeAction.codeActionLiteralSupport.
536 llvm::json::Value CodeActionProvider = true;
537 if (Params.capabilities.CodeActionStructure)
538 CodeActionProvider = llvm::json::Object{
539 {"codeActionKinds",
540 {CodeAction::QUICKFIX_KIND, CodeAction::REFACTOR_KIND,
541 CodeAction::INFO_KIND}}};
542
Sam McCalla69698f2019-03-27 17:47:49 +0000543 llvm::json::Object Result{
Sam McCall0930ab02017-11-07 15:49:35 +0000544 {{"capabilities",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000545 llvm::json::Object{
Simon Marchi98082622018-03-26 14:41:40 +0000546 {"textDocumentSync", (int)TextDocumentSyncKind::Incremental},
Sam McCall0930ab02017-11-07 15:49:35 +0000547 {"documentFormattingProvider", true},
548 {"documentRangeFormattingProvider", true},
549 {"documentOnTypeFormattingProvider",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000550 llvm::json::Object{
Sam McCall25c62572019-06-10 14:26:21 +0000551 {"firstTriggerCharacter", "\n"},
Sam McCall0930ab02017-11-07 15:49:35 +0000552 {"moreTriggerCharacter", {}},
553 }},
Haojian Wu08d93f12019-08-22 14:53:45 +0000554 {"codeActionProvider", std::move(CodeActionProvider)},
Sam McCall0930ab02017-11-07 15:49:35 +0000555 {"completionProvider",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000556 llvm::json::Object{
Sam McCall0930ab02017-11-07 15:49:35 +0000557 {"resolveProvider", false},
Ilya Biryukovb0826bd2019-01-03 13:37:12 +0000558 // We do extra checks for '>' and ':' in completion to only
559 // trigger on '->' and '::'.
Sam McCall0930ab02017-11-07 15:49:35 +0000560 {"triggerCharacters", {".", ">", ":"}},
561 }},
562 {"signatureHelpProvider",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000563 llvm::json::Object{
Sam McCall0930ab02017-11-07 15:49:35 +0000564 {"triggerCharacters", {"(", ","}},
565 }},
Sam McCall866ba2c2019-02-01 11:26:13 +0000566 {"declarationProvider", true},
Sam McCall0930ab02017-11-07 15:49:35 +0000567 {"definitionProvider", true},
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000568 {"documentHighlightProvider", true},
Michael Forsterd6417f52019-12-12 14:30:02 +0100569 {"documentLinkProvider",
570 llvm::json::Object{
571 {"resolveProvider", false},
572 }},
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000573 {"hoverProvider", true},
Haojian Wuf429ab62019-07-24 07:49:23 +0000574 {"renameProvider", std::move(RenameProvider)},
Utkarsh Saxena55925da2019-09-24 13:38:33 +0000575 {"selectionRangeProvider", true},
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000576 {"documentSymbolProvider", true},
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000577 {"workspaceSymbolProvider", true},
Sam McCall1ad142f2018-09-05 11:53:07 +0000578 {"referencesProvider", true},
Sam McCall0930ab02017-11-07 15:49:35 +0000579 {"executeCommandProvider",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000580 llvm::json::Object{
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000581 {"commands",
582 {ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND,
583 ExecuteCommandParams::CLANGD_APPLY_TWEAK}},
Sam McCall0930ab02017-11-07 15:49:35 +0000584 }},
Kadir Cetinkaya86658022019-03-19 09:27:04 +0000585 {"typeHierarchyProvider", true},
Sam McCalla69698f2019-03-27 17:47:49 +0000586 }}}};
587 if (NegotiatedOffsetEncoding)
588 Result["offsetEncoding"] = *NegotiatedOffsetEncoding;
Johan Vikstroma848dab2019-07-04 07:53:12 +0000589 if (Params.capabilities.SemanticHighlighting)
590 Result.getObject("capabilities")
591 ->insert(
592 {"semanticHighlighting",
Haojian Wu1ca2ee42019-07-04 12:27:21 +0000593 llvm::json::Object{{"scopes", buildHighlightScopeLookupTable()}}});
Sam McCalla69698f2019-03-27 17:47:49 +0000594 Reply(std::move(Result));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000595}
596
Sam McCall2c30fbc2018-10-18 12:32:04 +0000597void ClangdLSPServer::onShutdown(const ShutdownParams &Params,
598 Callback<std::nullptr_t> Reply) {
Ilya Biryukov0d9b8a32017-10-25 08:45:41 +0000599 // Do essentially nothing, just say we're ready to exit.
600 ShutdownRequestReceived = true;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000601 Reply(nullptr);
Sam McCall8a5dded2017-10-12 13:29:58 +0000602}
Ilya Biryukovafb55542017-05-16 14:40:30 +0000603
Sam McCall422c8282018-11-26 16:00:11 +0000604// sync is a clangd extension: it blocks until all background work completes.
605// It blocks the calling thread, so no messages are processed until it returns!
606void ClangdLSPServer::onSync(const NoParams &Params,
607 Callback<std::nullptr_t> Reply) {
608 if (Server->blockUntilIdleForTest(/*TimeoutSeconds=*/60))
609 Reply(nullptr);
610 else
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000611 Reply(llvm::createStringError(llvm::inconvertibleErrorCode(),
612 "Not idle after a minute"));
Sam McCall422c8282018-11-26 16:00:11 +0000613}
614
Sam McCall2c30fbc2018-10-18 12:32:04 +0000615void ClangdLSPServer::onDocumentDidOpen(
616 const DidOpenTextDocumentParams &Params) {
Simon Marchi9569fd52018-03-16 14:30:42 +0000617 PathRef File = Params.textDocument.uri.file();
Ilya Biryukovb10ef472018-06-13 09:20:41 +0000618
Sam McCall2c30fbc2018-10-18 12:32:04 +0000619 const std::string &Contents = Params.textDocument.text;
Simon Marchi9569fd52018-03-16 14:30:42 +0000620
Simon Marchi98082622018-03-26 14:41:40 +0000621 DraftMgr.addDraft(File, Contents);
Ilya Biryukov652364b2018-09-26 05:48:29 +0000622 Server->addDocument(File, Contents, WantDiagnostics::Yes);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000623}
624
Sam McCall2c30fbc2018-10-18 12:32:04 +0000625void ClangdLSPServer::onDocumentDidChange(
626 const DidChangeTextDocumentParams &Params) {
Eric Liu51fed182018-02-22 18:40:39 +0000627 auto WantDiags = WantDiagnostics::Auto;
628 if (Params.wantDiagnostics.hasValue())
629 WantDiags = Params.wantDiagnostics.getValue() ? WantDiagnostics::Yes
630 : WantDiagnostics::No;
Simon Marchi9569fd52018-03-16 14:30:42 +0000631
632 PathRef File = Params.textDocument.uri.file();
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000633 llvm::Expected<std::string> Contents =
Simon Marchi98082622018-03-26 14:41:40 +0000634 DraftMgr.updateDraft(File, Params.contentChanges);
635 if (!Contents) {
636 // If this fails, we are most likely going to be not in sync anymore with
637 // the client. It is better to remove the draft and let further operations
638 // fail rather than giving wrong results.
639 DraftMgr.removeDraft(File);
Ilya Biryukov652364b2018-09-26 05:48:29 +0000640 Server->removeDocument(File);
Sam McCallbed58852018-07-11 10:35:11 +0000641 elog("Failed to update {0}: {1}", File, Contents.takeError());
Simon Marchi98082622018-03-26 14:41:40 +0000642 return;
643 }
Simon Marchi9569fd52018-03-16 14:30:42 +0000644
Ilya Biryukov652364b2018-09-26 05:48:29 +0000645 Server->addDocument(File, *Contents, WantDiags);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000646}
647
Sam McCall2c30fbc2018-10-18 12:32:04 +0000648void ClangdLSPServer::onFileEvent(const DidChangeWatchedFilesParams &Params) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000649 Server->onFileEvent(Params);
Marc-Andre Laperlebf114242017-10-02 18:00:37 +0000650}
651
Sam McCall2c30fbc2018-10-18 12:32:04 +0000652void ClangdLSPServer::onCommand(const ExecuteCommandParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000653 Callback<llvm::json::Value> Reply) {
Ilya Biryukov12864002019-08-16 12:46:41 +0000654 auto ApplyEdit = [this](WorkspaceEdit WE, std::string SuccessMessage,
655 decltype(Reply) Reply) {
Eric Liuc5105f92018-02-16 14:15:55 +0000656 ApplyWorkspaceEditParams Edit;
657 Edit.edit = std::move(WE);
Ilya Biryukov12864002019-08-16 12:46:41 +0000658 call<ApplyWorkspaceEditResponse>(
659 "workspace/applyEdit", std::move(Edit),
660 [Reply = std::move(Reply), SuccessMessage = std::move(SuccessMessage)](
661 llvm::Expected<ApplyWorkspaceEditResponse> Response) mutable {
662 if (!Response)
663 return Reply(Response.takeError());
664 if (!Response->applied) {
665 std::string Reason = Response->failureReason
666 ? *Response->failureReason
667 : "unknown reason";
668 return Reply(llvm::createStringError(
669 llvm::inconvertibleErrorCode(),
670 ("edits were not applied: " + Reason).c_str()));
671 }
672 return Reply(SuccessMessage);
673 });
Eric Liuc5105f92018-02-16 14:15:55 +0000674 };
Ilya Biryukov12864002019-08-16 12:46:41 +0000675
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000676 if (Params.command == ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND &&
677 Params.workspaceEdit) {
678 // The flow for "apply-fix" :
679 // 1. We publish a diagnostic, including fixits
680 // 2. The user clicks on the diagnostic, the editor asks us for code actions
681 // 3. We send code actions, with the fixit embedded as context
682 // 4. The user selects the fixit, the editor asks us to apply it
683 // 5. We unwrap the changes and send them back to the editor
Haojian Wuf2516342019-08-05 12:48:09 +0000684 // 6. The editor applies the changes (applyEdit), and sends us a reply
685 // 7. We unwrap the reply and send a reply to the editor.
Ilya Biryukov12864002019-08-16 12:46:41 +0000686 ApplyEdit(*Params.workspaceEdit, "Fix applied.", std::move(Reply));
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000687 } else if (Params.command == ExecuteCommandParams::CLANGD_APPLY_TWEAK &&
688 Params.tweakArgs) {
689 auto Code = DraftMgr.getDraft(Params.tweakArgs->file.file());
690 if (!Code)
691 return Reply(llvm::createStringError(
692 llvm::inconvertibleErrorCode(),
693 "trying to apply a code action for a non-added file"));
694
Ilya Biryukov12864002019-08-16 12:46:41 +0000695 auto Action = [this, ApplyEdit, Reply = std::move(Reply),
696 File = Params.tweakArgs->file, Code = std::move(*Code)](
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000697 llvm::Expected<Tweak::Effect> R) mutable {
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000698 if (!R)
699 return Reply(R.takeError());
700
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000701 assert(R->ShowMessage ||
702 (!R->ApplyEdits.empty() && "tweak has no effect"));
Ilya Biryukov12864002019-08-16 12:46:41 +0000703
Sam McCall395fde72019-06-18 13:37:54 +0000704 if (R->ShowMessage) {
705 ShowMessageParams Msg;
706 Msg.message = *R->ShowMessage;
707 Msg.type = MessageType::Info;
708 notify("window/showMessage", Msg);
709 }
Ilya Biryukov12864002019-08-16 12:46:41 +0000710 // When no edit is specified, make sure we Reply().
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000711 if (R->ApplyEdits.empty())
712 return Reply("Tweak applied.");
713
Haojian Wu852bafa2019-10-23 14:40:20 +0200714 if (auto Err = validateEdits(DraftMgr, R->ApplyEdits))
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000715 return Reply(std::move(Err));
716
717 WorkspaceEdit WE;
718 WE.changes.emplace();
719 for (const auto &It : R->ApplyEdits) {
Kadir Cetinkayae95e5162019-10-02 09:12:01 +0000720 (*WE.changes)[URI::createFile(It.first()).toString()] =
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000721 It.second.asTextEdits();
722 }
723 // ApplyEdit will take care of calling Reply().
724 return ApplyEdit(std::move(WE), "Tweak applied.", std::move(Reply));
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000725 };
726 Server->applyTweak(Params.tweakArgs->file.file(),
727 Params.tweakArgs->selection, Params.tweakArgs->tweakID,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000728 std::move(Action));
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000729 } else {
730 // We should not get here because ExecuteCommandParams would not have
731 // parsed in the first place and this handler should not be called. But if
732 // more commands are added, this will be here has a safe guard.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000733 Reply(llvm::make_error<LSPError>(
734 llvm::formatv("Unsupported command \"{0}\".", Params.command).str(),
Sam McCall2c30fbc2018-10-18 12:32:04 +0000735 ErrorCode::InvalidParams));
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000736 }
737}
738
Sam McCall2c30fbc2018-10-18 12:32:04 +0000739void ClangdLSPServer::onWorkspaceSymbol(
740 const WorkspaceSymbolParams &Params,
741 Callback<std::vector<SymbolInformation>> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000742 Server->workspaceSymbols(
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000743 Params.query, CCOpts.Limit,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000744 [Reply = std::move(Reply),
745 this](llvm::Expected<std::vector<SymbolInformation>> Items) mutable {
746 if (!Items)
747 return Reply(Items.takeError());
748 for (auto &Sym : *Items)
749 Sym.kind = adjustKindToCapability(Sym.kind, SupportedSymbolKinds);
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000750
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000751 Reply(std::move(*Items));
752 });
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000753}
754
Haojian Wuf429ab62019-07-24 07:49:23 +0000755void ClangdLSPServer::onPrepareRename(const TextDocumentPositionParams &Params,
756 Callback<llvm::Optional<Range>> Reply) {
757 Server->prepareRename(Params.textDocument.uri.file(), Params.position,
758 std::move(Reply));
759}
760
Sam McCall2c30fbc2018-10-18 12:32:04 +0000761void ClangdLSPServer::onRename(const RenameParams &Params,
762 Callback<WorkspaceEdit> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000763 Path File = Params.textDocument.uri.file();
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000764 llvm::Optional<std::string> Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000765 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000766 return Reply(llvm::make_error<LSPError>(
767 "onRename called for non-added file", ErrorCode::InvalidParams));
Haojian Wu852bafa2019-10-23 14:40:20 +0200768 Server->rename(
769 File, Params.position, Params.newName,
770 /*WantFormat=*/true,
771 [File, Params, Reply = std::move(Reply),
772 this](llvm::Expected<FileEdits> Edits) mutable {
773 if (!Edits)
774 return Reply(Edits.takeError());
775 if (auto Err = validateEdits(DraftMgr, *Edits))
776 return Reply(std::move(Err));
777 WorkspaceEdit Result;
778 Result.changes.emplace();
779 for (const auto &Rep : *Edits) {
780 (*Result.changes)[URI::createFile(Rep.first()).toString()] =
781 Rep.second.asTextEdits();
782 }
783 Reply(Result);
784 });
Haojian Wu345099c2017-11-09 11:30:04 +0000785}
786
Sam McCall2c30fbc2018-10-18 12:32:04 +0000787void ClangdLSPServer::onDocumentDidClose(
788 const DidCloseTextDocumentParams &Params) {
Simon Marchi9569fd52018-03-16 14:30:42 +0000789 PathRef File = Params.textDocument.uri.file();
790 DraftMgr.removeDraft(File);
Ilya Biryukov652364b2018-09-26 05:48:29 +0000791 Server->removeDocument(File);
Ilya Biryukov49c10712019-03-25 10:15:11 +0000792
793 {
794 std::lock_guard<std::mutex> Lock(FixItsMutex);
795 FixItsMap.erase(File);
796 }
Johan Vikstromc2653ef22019-08-01 08:08:44 +0000797 {
798 std::lock_guard<std::mutex> HLock(HighlightingsMutex);
799 FileToHighlightings.erase(File);
800 }
Ilya Biryukov49c10712019-03-25 10:15:11 +0000801 // clangd will not send updates for this file anymore, so we empty out the
802 // list of diagnostics shown on the client (e.g. in the "Problems" pane of
803 // VSCode). Note that this cannot race with actual diagnostics responses
804 // because removeDocument() guarantees no diagnostic callbacks will be
805 // executed after it returns.
806 publishDiagnostics(URIForFile::canonicalize(File, /*TUPath=*/File), {});
Ilya Biryukovafb55542017-05-16 14:40:30 +0000807}
808
Sam McCall4db732a2017-09-30 10:08:52 +0000809void ClangdLSPServer::onDocumentOnTypeFormatting(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000810 const DocumentOnTypeFormattingParams &Params,
811 Callback<std::vector<TextEdit>> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000812 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000813 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000814 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000815 return Reply(llvm::make_error<LSPError>(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000816 "onDocumentOnTypeFormatting called for non-added file",
817 ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000818
Sam McCall25c62572019-06-10 14:26:21 +0000819 Reply(Server->formatOnType(*Code, File, Params.position, Params.ch));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000820}
821
Sam McCall4db732a2017-09-30 10:08:52 +0000822void ClangdLSPServer::onDocumentRangeFormatting(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000823 const DocumentRangeFormattingParams &Params,
824 Callback<std::vector<TextEdit>> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000825 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000826 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000827 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000828 return Reply(llvm::make_error<LSPError>(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000829 "onDocumentRangeFormatting called for non-added file",
830 ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000831
Ilya Biryukov652364b2018-09-26 05:48:29 +0000832 auto ReplacementsOrError = Server->formatRange(*Code, File, Params.range);
Raoul Wols212bcf82017-12-12 20:25:06 +0000833 if (ReplacementsOrError)
Sam McCall2c30fbc2018-10-18 12:32:04 +0000834 Reply(replacementsToEdits(*Code, ReplacementsOrError.get()));
Raoul Wols212bcf82017-12-12 20:25:06 +0000835 else
Sam McCall2c30fbc2018-10-18 12:32:04 +0000836 Reply(ReplacementsOrError.takeError());
Ilya Biryukovafb55542017-05-16 14:40:30 +0000837}
838
Sam McCall2c30fbc2018-10-18 12:32:04 +0000839void ClangdLSPServer::onDocumentFormatting(
840 const DocumentFormattingParams &Params,
841 Callback<std::vector<TextEdit>> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000842 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000843 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000844 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000845 return Reply(llvm::make_error<LSPError>(
846 "onDocumentFormatting called for non-added file",
847 ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000848
Ilya Biryukov652364b2018-09-26 05:48:29 +0000849 auto ReplacementsOrError = Server->formatFile(*Code, File);
Raoul Wols212bcf82017-12-12 20:25:06 +0000850 if (ReplacementsOrError)
Sam McCall2c30fbc2018-10-18 12:32:04 +0000851 Reply(replacementsToEdits(*Code, ReplacementsOrError.get()));
Raoul Wols212bcf82017-12-12 20:25:06 +0000852 else
Sam McCall2c30fbc2018-10-18 12:32:04 +0000853 Reply(ReplacementsOrError.takeError());
Sam McCall4db732a2017-09-30 10:08:52 +0000854}
855
Ilya Biryukov19d75602018-11-23 15:21:19 +0000856/// The functions constructs a flattened view of the DocumentSymbol hierarchy.
857/// Used by the clients that do not support the hierarchical view.
858static std::vector<SymbolInformation>
859flattenSymbolHierarchy(llvm::ArrayRef<DocumentSymbol> Symbols,
860 const URIForFile &FileURI) {
861
862 std::vector<SymbolInformation> Results;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000863 std::function<void(const DocumentSymbol &, llvm::StringRef)> Process =
864 [&](const DocumentSymbol &S, llvm::Optional<llvm::StringRef> ParentName) {
Ilya Biryukov19d75602018-11-23 15:21:19 +0000865 SymbolInformation SI;
866 SI.containerName = ParentName ? "" : *ParentName;
867 SI.name = S.name;
868 SI.kind = S.kind;
869 SI.location.range = S.range;
870 SI.location.uri = FileURI;
871
872 Results.push_back(std::move(SI));
873 std::string FullName =
874 !ParentName ? S.name : (ParentName->str() + "::" + S.name);
875 for (auto &C : S.children)
876 Process(C, /*ParentName=*/FullName);
877 };
878 for (auto &S : Symbols)
879 Process(S, /*ParentName=*/"");
880 return Results;
881}
882
883void ClangdLSPServer::onDocumentSymbol(const DocumentSymbolParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000884 Callback<llvm::json::Value> Reply) {
Ilya Biryukov19d75602018-11-23 15:21:19 +0000885 URIForFile FileURI = Params.textDocument.uri;
Ilya Biryukov652364b2018-09-26 05:48:29 +0000886 Server->documentSymbols(
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000887 Params.textDocument.uri.file(),
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000888 [this, FileURI, Reply = std::move(Reply)](
889 llvm::Expected<std::vector<DocumentSymbol>> Items) mutable {
890 if (!Items)
891 return Reply(Items.takeError());
892 adjustSymbolKinds(*Items, SupportedSymbolKinds);
893 if (SupportsHierarchicalDocumentSymbol)
894 return Reply(std::move(*Items));
895 else
896 return Reply(flattenSymbolHierarchy(*Items, FileURI));
897 });
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000898}
899
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000900static llvm::Optional<Command> asCommand(const CodeAction &Action) {
Sam McCall20841d42018-10-16 16:29:41 +0000901 Command Cmd;
902 if (Action.command && Action.edit)
Sam McCallc008af62018-10-20 15:30:37 +0000903 return None; // Not representable. (We never emit these anyway).
Sam McCall20841d42018-10-16 16:29:41 +0000904 if (Action.command) {
905 Cmd = *Action.command;
906 } else if (Action.edit) {
907 Cmd.command = Command::CLANGD_APPLY_FIX_COMMAND;
908 Cmd.workspaceEdit = *Action.edit;
909 } else {
Sam McCallc008af62018-10-20 15:30:37 +0000910 return None;
Sam McCall20841d42018-10-16 16:29:41 +0000911 }
912 Cmd.title = Action.title;
913 if (Action.kind && *Action.kind == CodeAction::QUICKFIX_KIND)
914 Cmd.title = "Apply fix: " + Cmd.title;
915 return Cmd;
916}
917
Sam McCall2c30fbc2018-10-18 12:32:04 +0000918void ClangdLSPServer::onCodeAction(const CodeActionParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000919 Callback<llvm::json::Value> Reply) {
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000920 URIForFile File = Params.textDocument.uri;
921 auto Code = DraftMgr.getDraft(File.file());
Sam McCall2c30fbc2018-10-18 12:32:04 +0000922 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000923 return Reply(llvm::make_error<LSPError>(
924 "onCodeAction called for non-added file", ErrorCode::InvalidParams));
Sam McCall20841d42018-10-16 16:29:41 +0000925 // We provide a code action for Fixes on the specified diagnostics.
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000926 std::vector<CodeAction> FixIts;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000927 for (const Diagnostic &D : Params.context.diagnostics) {
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000928 for (auto &F : getFixes(File.file(), D)) {
929 FixIts.push_back(toCodeAction(F, Params.textDocument.uri));
930 FixIts.back().diagnostics = {D};
Sam McCalldd0566b2017-11-06 15:40:30 +0000931 }
Ilya Biryukovafb55542017-05-16 14:40:30 +0000932 }
Sam McCall20841d42018-10-16 16:29:41 +0000933
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000934 // Now enumerate the semantic code actions.
935 auto ConsumeActions =
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000936 [Reply = std::move(Reply), File, Code = std::move(*Code),
937 Selection = Params.range, FixIts = std::move(FixIts), this](
938 llvm::Expected<std::vector<ClangdServer::TweakRef>> Tweaks) mutable {
Ilya Biryukovc6ed7782019-01-30 14:24:17 +0000939 if (!Tweaks)
940 return Reply(Tweaks.takeError());
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000941
942 std::vector<CodeAction> Actions = std::move(FixIts);
943 Actions.reserve(Actions.size() + Tweaks->size());
944 for (const auto &T : *Tweaks)
945 Actions.push_back(toCodeAction(T, File, Selection));
946
947 if (SupportsCodeAction)
948 return Reply(llvm::json::Array(Actions));
949 std::vector<Command> Commands;
950 for (const auto &Action : Actions) {
951 if (auto Command = asCommand(Action))
952 Commands.push_back(std::move(*Command));
953 }
954 return Reply(llvm::json::Array(Commands));
955 };
956
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000957 Server->enumerateTweaks(File.file(), Params.range, std::move(ConsumeActions));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000958}
959
Ilya Biryukovb0826bd2019-01-03 13:37:12 +0000960void ClangdLSPServer::onCompletion(const CompletionParams &Params,
Sam McCall2c30fbc2018-10-18 12:32:04 +0000961 Callback<CompletionList> Reply) {
Ilya Biryukova7a11472019-06-07 16:24:38 +0000962 if (!shouldRunCompletion(Params)) {
963 // Clients sometimes auto-trigger completions in undesired places (e.g.
964 // 'a >^ '), we return empty results in those cases.
965 vlog("ignored auto-triggered completion, preceding char did not match");
966 return Reply(CompletionList());
967 }
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000968 Server->codeComplete(Params.textDocument.uri.file(), Params.position, CCOpts,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000969 [Reply = std::move(Reply),
970 this](llvm::Expected<CodeCompleteResult> List) mutable {
971 if (!List)
972 return Reply(List.takeError());
973 CompletionList LSPList;
974 LSPList.isIncomplete = List->HasMore;
975 for (const auto &R : List->Completions) {
976 CompletionItem C = R.render(CCOpts);
977 C.kind = adjustKindToCapability(
978 C.kind, SupportedCompletionItemKinds);
979 LSPList.items.push_back(std::move(C));
980 }
981 return Reply(std::move(LSPList));
982 });
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000983}
984
Sam McCall2c30fbc2018-10-18 12:32:04 +0000985void ClangdLSPServer::onSignatureHelp(const TextDocumentPositionParams &Params,
986 Callback<SignatureHelp> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000987 Server->signatureHelp(Params.textDocument.uri.file(), Params.position,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000988 [Reply = std::move(Reply), this](
989 llvm::Expected<SignatureHelp> Signature) mutable {
990 if (!Signature)
991 return Reply(Signature.takeError());
992 if (SupportsOffsetsInSignatureHelp)
993 return Reply(std::move(*Signature));
994 // Strip out the offsets from signature help for
995 // clients that only support string labels.
996 for (auto &SigInfo : Signature->signatures) {
997 for (auto &Param : SigInfo.parameters)
998 Param.labelOffsets.reset();
999 }
1000 return Reply(std::move(*Signature));
1001 });
Ilya Biryukov652364b2018-09-26 05:48:29 +00001002}
1003
Sam McCall0dbab7f2019-02-02 05:56:00 +00001004// Go to definition has a toggle function: if def and decl are distinct, then
1005// the first press gives you the def, the second gives you the matching def.
1006// getToggle() returns the counterpart location that under the cursor.
1007//
1008// We return the toggled location alone (ignoring other symbols) to encourage
1009// editors to "bounce" quickly between locations, without showing a menu.
1010static Location *getToggle(const TextDocumentPositionParams &Point,
1011 LocatedSymbol &Sym) {
1012 // Toggle only makes sense with two distinct locations.
1013 if (!Sym.Definition || *Sym.Definition == Sym.PreferredDeclaration)
1014 return nullptr;
1015 if (Sym.Definition->uri.file() == Point.textDocument.uri.file() &&
1016 Sym.Definition->range.contains(Point.position))
1017 return &Sym.PreferredDeclaration;
1018 if (Sym.PreferredDeclaration.uri.file() == Point.textDocument.uri.file() &&
1019 Sym.PreferredDeclaration.range.contains(Point.position))
1020 return &*Sym.Definition;
1021 return nullptr;
1022}
1023
Sam McCall2c30fbc2018-10-18 12:32:04 +00001024void ClangdLSPServer::onGoToDefinition(const TextDocumentPositionParams &Params,
1025 Callback<std::vector<Location>> Reply) {
Sam McCall866ba2c2019-02-01 11:26:13 +00001026 Server->locateSymbolAt(
1027 Params.textDocument.uri.file(), Params.position,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001028 [Params, Reply = std::move(Reply)](
1029 llvm::Expected<std::vector<LocatedSymbol>> Symbols) mutable {
1030 if (!Symbols)
1031 return Reply(Symbols.takeError());
1032 std::vector<Location> Defs;
1033 for (auto &S : *Symbols) {
1034 if (Location *Toggle = getToggle(Params, S))
1035 return Reply(std::vector<Location>{std::move(*Toggle)});
1036 Defs.push_back(S.Definition.getValueOr(S.PreferredDeclaration));
1037 }
1038 Reply(std::move(Defs));
1039 });
Sam McCall866ba2c2019-02-01 11:26:13 +00001040}
1041
1042void ClangdLSPServer::onGoToDeclaration(
1043 const TextDocumentPositionParams &Params,
1044 Callback<std::vector<Location>> Reply) {
1045 Server->locateSymbolAt(
1046 Params.textDocument.uri.file(), Params.position,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001047 [Params, Reply = std::move(Reply)](
1048 llvm::Expected<std::vector<LocatedSymbol>> Symbols) mutable {
1049 if (!Symbols)
1050 return Reply(Symbols.takeError());
1051 std::vector<Location> Decls;
1052 for (auto &S : *Symbols) {
1053 if (Location *Toggle = getToggle(Params, S))
1054 return Reply(std::vector<Location>{std::move(*Toggle)});
1055 Decls.push_back(std::move(S.PreferredDeclaration));
1056 }
1057 Reply(std::move(Decls));
1058 });
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +00001059}
1060
Sam McCall111fe842019-05-07 07:55:35 +00001061void ClangdLSPServer::onSwitchSourceHeader(
1062 const TextDocumentIdentifier &Params,
Sam McCallb9ec3e92019-05-07 08:30:32 +00001063 Callback<llvm::Optional<URIForFile>> Reply) {
Haojian Wud6d5edd2019-10-01 10:21:15 +00001064 Server->switchSourceHeader(
1065 Params.uri.file(),
1066 [Reply = std::move(Reply),
1067 Params](llvm::Expected<llvm::Optional<clangd::Path>> Path) mutable {
1068 if (!Path)
1069 return Reply(Path.takeError());
1070 if (*Path)
Haojian Wu77c97002019-10-07 11:37:25 +00001071 return Reply(URIForFile::canonicalize(**Path, Params.uri.file()));
Haojian Wud6d5edd2019-10-01 10:21:15 +00001072 return Reply(llvm::None);
1073 });
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +00001074}
1075
Sam McCall2c30fbc2018-10-18 12:32:04 +00001076void ClangdLSPServer::onDocumentHighlight(
1077 const TextDocumentPositionParams &Params,
1078 Callback<std::vector<DocumentHighlight>> Reply) {
1079 Server->findDocumentHighlights(Params.textDocument.uri.file(),
1080 Params.position, std::move(Reply));
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +00001081}
1082
Sam McCall2c30fbc2018-10-18 12:32:04 +00001083void ClangdLSPServer::onHover(const TextDocumentPositionParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001084 Callback<llvm::Optional<Hover>> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +00001085 Server->findHover(Params.textDocument.uri.file(), Params.position,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001086 [Reply = std::move(Reply), this](
1087 llvm::Expected<llvm::Optional<HoverInfo>> H) mutable {
1088 if (!H)
1089 return Reply(H.takeError());
1090 if (!*H)
1091 return Reply(llvm::None);
Ilya Biryukovf9169d02019-05-29 10:01:00 +00001092
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001093 Hover R;
1094 R.contents.kind = HoverContentFormat;
1095 R.range = (*H)->SymRange;
1096 switch (HoverContentFormat) {
1097 case MarkupKind::PlainText:
Kadir Cetinkaya597c6b62019-12-10 10:28:37 +01001098 R.contents.value = (*H)->present().asPlainText();
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001099 return Reply(std::move(R));
1100 case MarkupKind::Markdown:
Kadir Cetinkaya597c6b62019-12-10 10:28:37 +01001101 R.contents.value = (*H)->present().asMarkdown();
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001102 return Reply(std::move(R));
1103 };
1104 llvm_unreachable("unhandled MarkupKind");
1105 });
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +00001106}
1107
Kadir Cetinkaya86658022019-03-19 09:27:04 +00001108void ClangdLSPServer::onTypeHierarchy(
1109 const TypeHierarchyParams &Params,
1110 Callback<Optional<TypeHierarchyItem>> Reply) {
1111 Server->typeHierarchy(Params.textDocument.uri.file(), Params.position,
1112 Params.resolve, Params.direction, std::move(Reply));
1113}
1114
Nathan Ridge087b0442019-07-13 03:24:48 +00001115void ClangdLSPServer::onResolveTypeHierarchy(
1116 const ResolveTypeHierarchyItemParams &Params,
1117 Callback<Optional<TypeHierarchyItem>> Reply) {
1118 Server->resolveTypeHierarchy(Params.item, Params.resolve, Params.direction,
1119 std::move(Reply));
1120}
1121
Simon Marchi88016782018-08-01 11:28:49 +00001122void ClangdLSPServer::applyConfiguration(
Sam McCallbc904612018-10-25 04:22:52 +00001123 const ConfigurationSettings &Settings) {
Simon Marchiabeed662018-10-16 15:55:03 +00001124 // Per-file update to the compilation database.
Sam McCallbc904612018-10-25 04:22:52 +00001125 bool ShouldReparseOpenFiles = false;
1126 for (auto &Entry : Settings.compilationDatabaseChanges) {
1127 /// The opened files need to be reparsed only when some existing
1128 /// entries are changed.
1129 PathRef File = Entry.first;
Sam McCallc55d09a2018-11-02 13:09:36 +00001130 auto Old = CDB->getCompileCommand(File);
1131 auto New =
1132 tooling::CompileCommand(std::move(Entry.second.workingDirectory), File,
1133 std::move(Entry.second.compilationCommand),
1134 /*Output=*/"");
Sam McCall6980edb2018-11-02 14:07:51 +00001135 if (Old != New) {
Sam McCallc55d09a2018-11-02 13:09:36 +00001136 CDB->setCompileCommand(File, std::move(New));
Sam McCall6980edb2018-11-02 14:07:51 +00001137 ShouldReparseOpenFiles = true;
1138 }
Alex Lorenzf8087862018-08-01 17:39:29 +00001139 }
Sam McCallbc904612018-10-25 04:22:52 +00001140 if (ShouldReparseOpenFiles)
1141 reparseOpenedFiles();
Simon Marchi5178f922018-02-22 14:00:39 +00001142}
1143
Johan Vikstroma848dab2019-07-04 07:53:12 +00001144void ClangdLSPServer::publishSemanticHighlighting(
1145 SemanticHighlightingParams Params) {
1146 notify("textDocument/semanticHighlighting", Params);
1147}
1148
Ilya Biryukov49c10712019-03-25 10:15:11 +00001149void ClangdLSPServer::publishDiagnostics(
1150 const URIForFile &File, std::vector<clangd::Diagnostic> Diagnostics) {
1151 // Publish diagnostics.
1152 notify("textDocument/publishDiagnostics",
1153 llvm::json::Object{
1154 {"uri", File},
1155 {"diagnostics", std::move(Diagnostics)},
1156 });
1157}
1158
Simon Marchi88016782018-08-01 11:28:49 +00001159// FIXME: This function needs to be properly tested.
1160void ClangdLSPServer::onChangeConfiguration(
Sam McCall2c30fbc2018-10-18 12:32:04 +00001161 const DidChangeConfigurationParams &Params) {
Simon Marchi88016782018-08-01 11:28:49 +00001162 applyConfiguration(Params.settings);
1163}
1164
Sam McCall2c30fbc2018-10-18 12:32:04 +00001165void ClangdLSPServer::onReference(const ReferenceParams &Params,
1166 Callback<std::vector<Location>> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +00001167 Server->findReferences(Params.textDocument.uri.file(), Params.position,
Haojian Wu5181ada2019-11-18 11:35:00 +01001168 CCOpts.Limit,
1169 [Reply = std::move(Reply)](
1170 llvm::Expected<ReferencesResult> Refs) mutable {
1171 if (!Refs)
1172 return Reply(Refs.takeError());
1173 return Reply(std::move(Refs->References));
1174 });
Sam McCall1ad142f2018-09-05 11:53:07 +00001175}
1176
Jan Korousb4067012018-11-27 16:40:46 +00001177void ClangdLSPServer::onSymbolInfo(const TextDocumentPositionParams &Params,
1178 Callback<std::vector<SymbolDetails>> Reply) {
1179 Server->symbolInfo(Params.textDocument.uri.file(), Params.position,
1180 std::move(Reply));
1181}
1182
Utkarsh Saxena55925da2019-09-24 13:38:33 +00001183void ClangdLSPServer::onSelectionRange(
1184 const SelectionRangeParams &Params,
1185 Callback<std::vector<SelectionRange>> Reply) {
1186 if (Params.positions.size() != 1) {
1187 elog("{0} positions provided to SelectionRange. Supports exactly one "
1188 "position.",
1189 Params.positions.size());
1190 return Reply(llvm::make_error<LSPError>(
1191 "SelectionRange supports exactly one position",
1192 ErrorCode::InvalidRequest));
1193 }
1194 Server->semanticRanges(
1195 Params.textDocument.uri.file(), Params.positions[0],
1196 [Reply = std::move(Reply)](
1197 llvm::Expected<std::vector<Range>> Ranges) mutable {
1198 if (!Ranges) {
1199 return Reply(Ranges.takeError());
1200 }
1201 std::vector<SelectionRange> Result;
1202 Result.emplace_back(render(std::move(*Ranges)));
1203 return Reply(std::move(Result));
1204 });
1205}
1206
Michael Forsterd6417f52019-12-12 14:30:02 +01001207void ClangdLSPServer::onDocumentLink(
1208 const DocumentLinkParams &Params,
1209 Callback<std::vector<DocumentLink>> Reply) {
1210
1211 // TODO(forster): This currently resolves all targets eagerly. This is slow,
1212 // because it blocks on the preamble/AST being built. We could respond to the
1213 // request faster by using string matching or the lexer to find the includes
1214 // and resolving the targets lazily.
1215 Server->documentLinks(
1216 Params.textDocument.uri.file(),
1217 [Reply = std::move(Reply)](
1218 llvm::Expected<std::vector<DocumentLink>> Links) mutable {
1219 if (!Links) {
1220 return Reply(Links.takeError());
1221 }
1222 return Reply(std::move(Links));
1223 });
1224}
1225
Sam McCalla69698f2019-03-27 17:47:49 +00001226ClangdLSPServer::ClangdLSPServer(
1227 class Transport &Transp, const FileSystemProvider &FSProvider,
1228 const clangd::CodeCompleteOptions &CCOpts,
1229 llvm::Optional<Path> CompileCommandsDir, bool UseDirBasedCDB,
1230 llvm::Optional<OffsetEncoding> ForcedOffsetEncoding,
1231 const ClangdServer::Options &Opts)
Kadir Cetinkaya9d662472019-10-15 14:20:52 +00001232 : BackgroundContext(Context::current().clone()), Transp(Transp),
1233 MsgHandler(new MessageHandler(*this)), FSProvider(FSProvider),
1234 CCOpts(CCOpts), SupportedSymbolKinds(defaultSymbolKinds()),
Kadir Cetinkaya133d46f2018-09-27 17:13:07 +00001235 SupportedCompletionItemKinds(defaultCompletionItemKinds()),
Sam McCallc55d09a2018-11-02 13:09:36 +00001236 UseDirBasedCDB(UseDirBasedCDB),
Sam McCalla69698f2019-03-27 17:47:49 +00001237 CompileCommandsDir(std::move(CompileCommandsDir)), ClangdServerOpts(Opts),
1238 NegotiatedOffsetEncoding(ForcedOffsetEncoding) {
Sam McCall2c30fbc2018-10-18 12:32:04 +00001239 // clang-format off
1240 MsgHandler->bind("initialize", &ClangdLSPServer::onInitialize);
1241 MsgHandler->bind("shutdown", &ClangdLSPServer::onShutdown);
Sam McCall422c8282018-11-26 16:00:11 +00001242 MsgHandler->bind("sync", &ClangdLSPServer::onSync);
Sam McCall2c30fbc2018-10-18 12:32:04 +00001243 MsgHandler->bind("textDocument/rangeFormatting", &ClangdLSPServer::onDocumentRangeFormatting);
1244 MsgHandler->bind("textDocument/onTypeFormatting", &ClangdLSPServer::onDocumentOnTypeFormatting);
1245 MsgHandler->bind("textDocument/formatting", &ClangdLSPServer::onDocumentFormatting);
1246 MsgHandler->bind("textDocument/codeAction", &ClangdLSPServer::onCodeAction);
1247 MsgHandler->bind("textDocument/completion", &ClangdLSPServer::onCompletion);
1248 MsgHandler->bind("textDocument/signatureHelp", &ClangdLSPServer::onSignatureHelp);
1249 MsgHandler->bind("textDocument/definition", &ClangdLSPServer::onGoToDefinition);
Sam McCall866ba2c2019-02-01 11:26:13 +00001250 MsgHandler->bind("textDocument/declaration", &ClangdLSPServer::onGoToDeclaration);
Sam McCall2c30fbc2018-10-18 12:32:04 +00001251 MsgHandler->bind("textDocument/references", &ClangdLSPServer::onReference);
1252 MsgHandler->bind("textDocument/switchSourceHeader", &ClangdLSPServer::onSwitchSourceHeader);
Haojian Wuf429ab62019-07-24 07:49:23 +00001253 MsgHandler->bind("textDocument/prepareRename", &ClangdLSPServer::onPrepareRename);
Sam McCall2c30fbc2018-10-18 12:32:04 +00001254 MsgHandler->bind("textDocument/rename", &ClangdLSPServer::onRename);
1255 MsgHandler->bind("textDocument/hover", &ClangdLSPServer::onHover);
1256 MsgHandler->bind("textDocument/documentSymbol", &ClangdLSPServer::onDocumentSymbol);
1257 MsgHandler->bind("workspace/executeCommand", &ClangdLSPServer::onCommand);
1258 MsgHandler->bind("textDocument/documentHighlight", &ClangdLSPServer::onDocumentHighlight);
1259 MsgHandler->bind("workspace/symbol", &ClangdLSPServer::onWorkspaceSymbol);
1260 MsgHandler->bind("textDocument/didOpen", &ClangdLSPServer::onDocumentDidOpen);
1261 MsgHandler->bind("textDocument/didClose", &ClangdLSPServer::onDocumentDidClose);
1262 MsgHandler->bind("textDocument/didChange", &ClangdLSPServer::onDocumentDidChange);
1263 MsgHandler->bind("workspace/didChangeWatchedFiles", &ClangdLSPServer::onFileEvent);
1264 MsgHandler->bind("workspace/didChangeConfiguration", &ClangdLSPServer::onChangeConfiguration);
Jan Korousb4067012018-11-27 16:40:46 +00001265 MsgHandler->bind("textDocument/symbolInfo", &ClangdLSPServer::onSymbolInfo);
Kadir Cetinkaya86658022019-03-19 09:27:04 +00001266 MsgHandler->bind("textDocument/typeHierarchy", &ClangdLSPServer::onTypeHierarchy);
Nathan Ridge087b0442019-07-13 03:24:48 +00001267 MsgHandler->bind("typeHierarchy/resolve", &ClangdLSPServer::onResolveTypeHierarchy);
Utkarsh Saxena55925da2019-09-24 13:38:33 +00001268 MsgHandler->bind("textDocument/selectionRange", &ClangdLSPServer::onSelectionRange);
Michael Forsterd6417f52019-12-12 14:30:02 +01001269 MsgHandler->bind("textDocument/documentLink", &ClangdLSPServer::onDocumentLink);
Sam McCall2c30fbc2018-10-18 12:32:04 +00001270 // clang-format on
1271}
1272
Sam McCall8bda5f22019-10-23 11:11:18 +02001273ClangdLSPServer::~ClangdLSPServer() { IsBeingDestroyed = true;
1274 // Explicitly destroy ClangdServer first, blocking on threads it owns.
1275 // This ensures they don't access any other members.
1276 Server.reset();
1277}
Ilya Biryukov38d79772017-05-16 09:38:59 +00001278
Sam McCalldc8f3cf2018-10-17 07:32:05 +00001279bool ClangdLSPServer::run() {
Ilya Biryukovafb55542017-05-16 14:40:30 +00001280 // Run the Language Server loop.
Sam McCalldc8f3cf2018-10-17 07:32:05 +00001281 bool CleanExit = true;
Sam McCall2c30fbc2018-10-18 12:32:04 +00001282 if (auto Err = Transp.loop(*MsgHandler)) {
Sam McCalldc8f3cf2018-10-17 07:32:05 +00001283 elog("Transport error: {0}", std::move(Err));
1284 CleanExit = false;
1285 }
Ilya Biryukovafb55542017-05-16 14:40:30 +00001286
Sam McCalldc8f3cf2018-10-17 07:32:05 +00001287 return CleanExit && ShutdownRequestReceived;
Ilya Biryukov38d79772017-05-16 09:38:59 +00001288}
1289
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001290std::vector<Fix> ClangdLSPServer::getFixes(llvm::StringRef File,
Ilya Biryukov71028b82018-03-12 15:28:22 +00001291 const clangd::Diagnostic &D) {
Ilya Biryukov38d79772017-05-16 09:38:59 +00001292 std::lock_guard<std::mutex> Lock(FixItsMutex);
1293 auto DiagToFixItsIter = FixItsMap.find(File);
1294 if (DiagToFixItsIter == FixItsMap.end())
1295 return {};
1296
1297 const auto &DiagToFixItsMap = DiagToFixItsIter->second;
1298 auto FixItsIter = DiagToFixItsMap.find(D);
1299 if (FixItsIter == DiagToFixItsMap.end())
1300 return {};
1301
1302 return FixItsIter->second;
1303}
1304
Ilya Biryukovb0826bd2019-01-03 13:37:12 +00001305bool ClangdLSPServer::shouldRunCompletion(
1306 const CompletionParams &Params) const {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001307 llvm::StringRef Trigger = Params.context.triggerCharacter;
Ilya Biryukovb0826bd2019-01-03 13:37:12 +00001308 if (Params.context.triggerKind != CompletionTriggerKind::TriggerCharacter ||
1309 (Trigger != ">" && Trigger != ":"))
1310 return true;
1311
1312 auto Code = DraftMgr.getDraft(Params.textDocument.uri.file());
1313 if (!Code)
1314 return true; // completion code will log the error for untracked doc.
1315
1316 // A completion request is sent when the user types '>' or ':', but we only
1317 // want to trigger on '->' and '::'. We check the preceeding character to make
1318 // sure it matches what we expected.
1319 // Running the lexer here would be more robust (e.g. we can detect comments
1320 // and avoid triggering completion there), but we choose to err on the side
1321 // of simplicity here.
1322 auto Offset = positionToOffset(*Code, Params.position,
1323 /*AllowColumnsBeyondLineLength=*/false);
1324 if (!Offset) {
1325 vlog("could not convert position '{0}' to offset for file '{1}'",
1326 Params.position, Params.textDocument.uri.file());
1327 return true;
1328 }
1329 if (*Offset < 2)
1330 return false;
1331
1332 if (Trigger == ">")
1333 return (*Code)[*Offset - 2] == '-'; // trigger only on '->'.
1334 if (Trigger == ":")
1335 return (*Code)[*Offset - 2] == ':'; // trigger only on '::'.
1336 assert(false && "unhandled trigger character");
1337 return true;
1338}
1339
Johan Vikstroma848dab2019-07-04 07:53:12 +00001340void ClangdLSPServer::onHighlightingsReady(
Haojian Wu0a6000f2019-08-26 08:38:45 +00001341 PathRef File, std::vector<HighlightingToken> Highlightings) {
Johan Vikstromc2653ef22019-08-01 08:08:44 +00001342 std::vector<HighlightingToken> Old;
1343 std::vector<HighlightingToken> HighlightingsCopy = Highlightings;
1344 {
1345 std::lock_guard<std::mutex> Lock(HighlightingsMutex);
1346 Old = std::move(FileToHighlightings[File]);
1347 FileToHighlightings[File] = std::move(HighlightingsCopy);
1348 }
1349 // LSP allows us to send incremental edits of highlightings. Also need to diff
1350 // to remove highlightings from tokens that should no longer have them.
Haojian Wu0a6000f2019-08-26 08:38:45 +00001351 std::vector<LineHighlightings> Diffed = diffHighlightings(Highlightings, Old);
Johan Vikstroma848dab2019-07-04 07:53:12 +00001352 publishSemanticHighlighting(
1353 {{URIForFile::canonicalize(File, /*TUPath=*/File)},
Johan Vikstromc2653ef22019-08-01 08:08:44 +00001354 toSemanticHighlightingInformation(Diffed)});
Johan Vikstroma848dab2019-07-04 07:53:12 +00001355}
1356
Sam McCalla7bb0cc2018-03-12 23:22:35 +00001357void ClangdLSPServer::onDiagnosticsReady(PathRef File,
1358 std::vector<Diag> Diagnostics) {
Eric Liu4d814a92018-11-28 10:30:42 +00001359 auto URI = URIForFile::canonicalize(File, /*TUPath=*/File);
Sam McCall16e70702018-10-24 07:59:38 +00001360 std::vector<Diagnostic> LSPDiagnostics;
Ilya Biryukov38d79772017-05-16 09:38:59 +00001361 DiagnosticToReplacementMap LocalFixIts; // Temporary storage
Sam McCalla7bb0cc2018-03-12 23:22:35 +00001362 for (auto &Diag : Diagnostics) {
Sam McCall16e70702018-10-24 07:59:38 +00001363 toLSPDiags(Diag, URI, DiagOpts,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001364 [&](clangd::Diagnostic Diag, llvm::ArrayRef<Fix> Fixes) {
Sam McCall16e70702018-10-24 07:59:38 +00001365 auto &FixItsForDiagnostic = LocalFixIts[Diag];
1366 llvm::copy(Fixes, std::back_inserter(FixItsForDiagnostic));
1367 LSPDiagnostics.push_back(std::move(Diag));
1368 });
Ilya Biryukov38d79772017-05-16 09:38:59 +00001369 }
1370
1371 // Cache FixIts
1372 {
Ilya Biryukov38d79772017-05-16 09:38:59 +00001373 std::lock_guard<std::mutex> Lock(FixItsMutex);
1374 FixItsMap[File] = LocalFixIts;
1375 }
1376
Ilya Biryukov49c10712019-03-25 10:15:11 +00001377 // Send a notification to the LSP client.
1378 publishDiagnostics(URI, std::move(LSPDiagnostics));
Ilya Biryukov38d79772017-05-16 09:38:59 +00001379}
Simon Marchi9569fd52018-03-16 14:30:42 +00001380
Haojian Wub6188492018-12-20 15:39:12 +00001381void ClangdLSPServer::onFileUpdated(PathRef File, const TUStatus &Status) {
1382 if (!SupportFileStatus)
1383 return;
1384 // FIXME: we don't emit "BuildingFile" and `RunningAction`, as these
1385 // two statuses are running faster in practice, which leads the UI constantly
1386 // changing, and doesn't provide much value. We may want to emit status at a
1387 // reasonable time interval (e.g. 0.5s).
1388 if (Status.Action.S == TUAction::BuildingFile ||
1389 Status.Action.S == TUAction::RunningAction)
1390 return;
1391 notify("textDocument/clangd.fileStatus", Status.render(File));
1392}
1393
Simon Marchi9569fd52018-03-16 14:30:42 +00001394void ClangdLSPServer::reparseOpenedFiles() {
1395 for (const Path &FilePath : DraftMgr.getActiveFiles())
Ilya Biryukov652364b2018-09-26 05:48:29 +00001396 Server->addDocument(FilePath, *DraftMgr.getDraft(FilePath),
1397 WantDiagnostics::Auto);
Simon Marchi9569fd52018-03-16 14:30:42 +00001398}
Alex Lorenzf8087862018-08-01 17:39:29 +00001399
Sam McCallc008af62018-10-20 15:30:37 +00001400} // namespace clangd
1401} // namespace clang