blob: 4fe81581807499b69cf188b282d1451b2e498ae6 [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
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000106// Makes sure edits in \p E are applicable to latest file contents reported by
107// editor. If not generates an error message containing information about files
108// that needs to be saved.
109llvm::Error validateEdits(const DraftStore &DraftMgr, const Tweak::Effect &E) {
110 size_t InvalidFileCount = 0;
111 llvm::StringRef LastInvalidFile;
112 for (const auto &It : E.ApplyEdits) {
113 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 }
Kadir Cetinkayabe6b35d2019-01-22 09:10:20 +0000488 CDB.emplace(BaseCDB.get(), Params.initializationOptions.fallbackFlags,
489 ClangdServerOpts.ResourceDir);
Kadir Cetinkaya9d662472019-10-15 14:20:52 +0000490 {
491 // Switch caller's context with LSPServer's background context. Since we
492 // rather want to propagate information from LSPServer's context into the
493 // Server, CDB, etc.
494 WithContext MainContext(BackgroundContext.clone());
495 llvm::Optional<WithContextValue> WithOffsetEncoding;
496 if (NegotiatedOffsetEncoding)
497 WithOffsetEncoding.emplace(kCurrentOffsetEncoding,
498 *NegotiatedOffsetEncoding);
499 Server.emplace(*CDB, FSProvider, static_cast<DiagnosticsConsumer &>(*this),
500 ClangdServerOpts);
501 }
Sam McCallbc904612018-10-25 04:22:52 +0000502 applyConfiguration(Params.initializationOptions.ConfigSettings);
Simon Marchi88016782018-08-01 11:28:49 +0000503
Sam McCallbf6a2fc2018-10-17 07:33:42 +0000504 CCOpts.EnableSnippets = Params.capabilities.CompletionSnippets;
Sam McCall8d412942019-06-18 11:57:26 +0000505 CCOpts.IncludeFixIts = Params.capabilities.CompletionFixes;
Sam McCall5f092e32019-07-08 17:27:15 +0000506 if (!CCOpts.BundleOverloads.hasValue())
507 CCOpts.BundleOverloads = Params.capabilities.HasSignatureHelp;
Sam McCallbf6a2fc2018-10-17 07:33:42 +0000508 DiagOpts.EmbedFixesInDiagnostics = Params.capabilities.DiagnosticFixes;
509 DiagOpts.SendDiagnosticCategory = Params.capabilities.DiagnosticCategory;
Sam McCallc9e4ee92019-04-18 15:17:07 +0000510 DiagOpts.EmitRelatedLocations =
511 Params.capabilities.DiagnosticRelatedInformation;
Sam McCallbf6a2fc2018-10-17 07:33:42 +0000512 if (Params.capabilities.WorkspaceSymbolKinds)
513 SupportedSymbolKinds |= *Params.capabilities.WorkspaceSymbolKinds;
514 if (Params.capabilities.CompletionItemKinds)
515 SupportedCompletionItemKinds |= *Params.capabilities.CompletionItemKinds;
516 SupportsCodeAction = Params.capabilities.CodeActionStructure;
Ilya Biryukov19d75602018-11-23 15:21:19 +0000517 SupportsHierarchicalDocumentSymbol =
518 Params.capabilities.HierarchicalDocumentSymbol;
Haojian Wub6188492018-12-20 15:39:12 +0000519 SupportFileStatus = Params.initializationOptions.FileStatus;
Ilya Biryukovf9169d02019-05-29 10:01:00 +0000520 HoverContentFormat = Params.capabilities.HoverContentFormat;
Ilya Biryukov4ef0f822019-06-04 09:36:59 +0000521 SupportsOffsetsInSignatureHelp = Params.capabilities.OffsetsInSignatureHelp;
Haojian Wuf429ab62019-07-24 07:49:23 +0000522
523 // Per LSP, renameProvider can be either boolean or RenameOptions.
524 // RenameOptions will be specified if the client states it supports prepare.
525 llvm::json::Value RenameProvider =
526 llvm::json::Object{{"prepareProvider", true}};
527 if (!Params.capabilities.RenamePrepareSupport) // Only boolean allowed per LSP
528 RenameProvider = true;
529
Haojian Wu08d93f12019-08-22 14:53:45 +0000530 // Per LSP, codeActionProvide can be either boolean or CodeActionOptions.
531 // CodeActionOptions is only valid if the client supports action literal
532 // via textDocument.codeAction.codeActionLiteralSupport.
533 llvm::json::Value CodeActionProvider = true;
534 if (Params.capabilities.CodeActionStructure)
535 CodeActionProvider = llvm::json::Object{
536 {"codeActionKinds",
537 {CodeAction::QUICKFIX_KIND, CodeAction::REFACTOR_KIND,
538 CodeAction::INFO_KIND}}};
539
Sam McCalla69698f2019-03-27 17:47:49 +0000540 llvm::json::Object Result{
Sam McCall0930ab02017-11-07 15:49:35 +0000541 {{"capabilities",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000542 llvm::json::Object{
Simon Marchi98082622018-03-26 14:41:40 +0000543 {"textDocumentSync", (int)TextDocumentSyncKind::Incremental},
Sam McCall0930ab02017-11-07 15:49:35 +0000544 {"documentFormattingProvider", true},
545 {"documentRangeFormattingProvider", true},
546 {"documentOnTypeFormattingProvider",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000547 llvm::json::Object{
Sam McCall25c62572019-06-10 14:26:21 +0000548 {"firstTriggerCharacter", "\n"},
Sam McCall0930ab02017-11-07 15:49:35 +0000549 {"moreTriggerCharacter", {}},
550 }},
Haojian Wu08d93f12019-08-22 14:53:45 +0000551 {"codeActionProvider", std::move(CodeActionProvider)},
Sam McCall0930ab02017-11-07 15:49:35 +0000552 {"completionProvider",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000553 llvm::json::Object{
Sam McCall0930ab02017-11-07 15:49:35 +0000554 {"resolveProvider", false},
Ilya Biryukovb0826bd2019-01-03 13:37:12 +0000555 // We do extra checks for '>' and ':' in completion to only
556 // trigger on '->' and '::'.
Sam McCall0930ab02017-11-07 15:49:35 +0000557 {"triggerCharacters", {".", ">", ":"}},
558 }},
559 {"signatureHelpProvider",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000560 llvm::json::Object{
Sam McCall0930ab02017-11-07 15:49:35 +0000561 {"triggerCharacters", {"(", ","}},
562 }},
Sam McCall866ba2c2019-02-01 11:26:13 +0000563 {"declarationProvider", true},
Sam McCall0930ab02017-11-07 15:49:35 +0000564 {"definitionProvider", true},
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000565 {"documentHighlightProvider", true},
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000566 {"hoverProvider", true},
Haojian Wuf429ab62019-07-24 07:49:23 +0000567 {"renameProvider", std::move(RenameProvider)},
Utkarsh Saxena55925da2019-09-24 13:38:33 +0000568 {"selectionRangeProvider", true},
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000569 {"documentSymbolProvider", true},
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000570 {"workspaceSymbolProvider", true},
Sam McCall1ad142f2018-09-05 11:53:07 +0000571 {"referencesProvider", true},
Sam McCall0930ab02017-11-07 15:49:35 +0000572 {"executeCommandProvider",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000573 llvm::json::Object{
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000574 {"commands",
575 {ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND,
576 ExecuteCommandParams::CLANGD_APPLY_TWEAK}},
Sam McCall0930ab02017-11-07 15:49:35 +0000577 }},
Kadir Cetinkaya86658022019-03-19 09:27:04 +0000578 {"typeHierarchyProvider", true},
Sam McCalla69698f2019-03-27 17:47:49 +0000579 }}}};
580 if (NegotiatedOffsetEncoding)
581 Result["offsetEncoding"] = *NegotiatedOffsetEncoding;
Johan Vikstroma848dab2019-07-04 07:53:12 +0000582 if (Params.capabilities.SemanticHighlighting)
583 Result.getObject("capabilities")
584 ->insert(
585 {"semanticHighlighting",
Haojian Wu1ca2ee42019-07-04 12:27:21 +0000586 llvm::json::Object{{"scopes", buildHighlightScopeLookupTable()}}});
Sam McCalla69698f2019-03-27 17:47:49 +0000587 Reply(std::move(Result));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000588}
589
Sam McCall2c30fbc2018-10-18 12:32:04 +0000590void ClangdLSPServer::onShutdown(const ShutdownParams &Params,
591 Callback<std::nullptr_t> Reply) {
Ilya Biryukov0d9b8a32017-10-25 08:45:41 +0000592 // Do essentially nothing, just say we're ready to exit.
593 ShutdownRequestReceived = true;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000594 Reply(nullptr);
Sam McCall8a5dded2017-10-12 13:29:58 +0000595}
Ilya Biryukovafb55542017-05-16 14:40:30 +0000596
Sam McCall422c8282018-11-26 16:00:11 +0000597// sync is a clangd extension: it blocks until all background work completes.
598// It blocks the calling thread, so no messages are processed until it returns!
599void ClangdLSPServer::onSync(const NoParams &Params,
600 Callback<std::nullptr_t> Reply) {
601 if (Server->blockUntilIdleForTest(/*TimeoutSeconds=*/60))
602 Reply(nullptr);
603 else
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000604 Reply(llvm::createStringError(llvm::inconvertibleErrorCode(),
605 "Not idle after a minute"));
Sam McCall422c8282018-11-26 16:00:11 +0000606}
607
Sam McCall2c30fbc2018-10-18 12:32:04 +0000608void ClangdLSPServer::onDocumentDidOpen(
609 const DidOpenTextDocumentParams &Params) {
Simon Marchi9569fd52018-03-16 14:30:42 +0000610 PathRef File = Params.textDocument.uri.file();
Ilya Biryukovb10ef472018-06-13 09:20:41 +0000611
Sam McCall2c30fbc2018-10-18 12:32:04 +0000612 const std::string &Contents = Params.textDocument.text;
Simon Marchi9569fd52018-03-16 14:30:42 +0000613
Simon Marchi98082622018-03-26 14:41:40 +0000614 DraftMgr.addDraft(File, Contents);
Ilya Biryukov652364b2018-09-26 05:48:29 +0000615 Server->addDocument(File, Contents, WantDiagnostics::Yes);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000616}
617
Sam McCall2c30fbc2018-10-18 12:32:04 +0000618void ClangdLSPServer::onDocumentDidChange(
619 const DidChangeTextDocumentParams &Params) {
Eric Liu51fed182018-02-22 18:40:39 +0000620 auto WantDiags = WantDiagnostics::Auto;
621 if (Params.wantDiagnostics.hasValue())
622 WantDiags = Params.wantDiagnostics.getValue() ? WantDiagnostics::Yes
623 : WantDiagnostics::No;
Simon Marchi9569fd52018-03-16 14:30:42 +0000624
625 PathRef File = Params.textDocument.uri.file();
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000626 llvm::Expected<std::string> Contents =
Simon Marchi98082622018-03-26 14:41:40 +0000627 DraftMgr.updateDraft(File, Params.contentChanges);
628 if (!Contents) {
629 // If this fails, we are most likely going to be not in sync anymore with
630 // the client. It is better to remove the draft and let further operations
631 // fail rather than giving wrong results.
632 DraftMgr.removeDraft(File);
Ilya Biryukov652364b2018-09-26 05:48:29 +0000633 Server->removeDocument(File);
Sam McCallbed58852018-07-11 10:35:11 +0000634 elog("Failed to update {0}: {1}", File, Contents.takeError());
Simon Marchi98082622018-03-26 14:41:40 +0000635 return;
636 }
Simon Marchi9569fd52018-03-16 14:30:42 +0000637
Ilya Biryukov652364b2018-09-26 05:48:29 +0000638 Server->addDocument(File, *Contents, WantDiags);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000639}
640
Sam McCall2c30fbc2018-10-18 12:32:04 +0000641void ClangdLSPServer::onFileEvent(const DidChangeWatchedFilesParams &Params) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000642 Server->onFileEvent(Params);
Marc-Andre Laperlebf114242017-10-02 18:00:37 +0000643}
644
Sam McCall2c30fbc2018-10-18 12:32:04 +0000645void ClangdLSPServer::onCommand(const ExecuteCommandParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000646 Callback<llvm::json::Value> Reply) {
Ilya Biryukov12864002019-08-16 12:46:41 +0000647 auto ApplyEdit = [this](WorkspaceEdit WE, std::string SuccessMessage,
648 decltype(Reply) Reply) {
Eric Liuc5105f92018-02-16 14:15:55 +0000649 ApplyWorkspaceEditParams Edit;
650 Edit.edit = std::move(WE);
Ilya Biryukov12864002019-08-16 12:46:41 +0000651 call<ApplyWorkspaceEditResponse>(
652 "workspace/applyEdit", std::move(Edit),
653 [Reply = std::move(Reply), SuccessMessage = std::move(SuccessMessage)](
654 llvm::Expected<ApplyWorkspaceEditResponse> Response) mutable {
655 if (!Response)
656 return Reply(Response.takeError());
657 if (!Response->applied) {
658 std::string Reason = Response->failureReason
659 ? *Response->failureReason
660 : "unknown reason";
661 return Reply(llvm::createStringError(
662 llvm::inconvertibleErrorCode(),
663 ("edits were not applied: " + Reason).c_str()));
664 }
665 return Reply(SuccessMessage);
666 });
Eric Liuc5105f92018-02-16 14:15:55 +0000667 };
Ilya Biryukov12864002019-08-16 12:46:41 +0000668
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000669 if (Params.command == ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND &&
670 Params.workspaceEdit) {
671 // The flow for "apply-fix" :
672 // 1. We publish a diagnostic, including fixits
673 // 2. The user clicks on the diagnostic, the editor asks us for code actions
674 // 3. We send code actions, with the fixit embedded as context
675 // 4. The user selects the fixit, the editor asks us to apply it
676 // 5. We unwrap the changes and send them back to the editor
Haojian Wuf2516342019-08-05 12:48:09 +0000677 // 6. The editor applies the changes (applyEdit), and sends us a reply
678 // 7. We unwrap the reply and send a reply to the editor.
Ilya Biryukov12864002019-08-16 12:46:41 +0000679 ApplyEdit(*Params.workspaceEdit, "Fix applied.", std::move(Reply));
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000680 } else if (Params.command == ExecuteCommandParams::CLANGD_APPLY_TWEAK &&
681 Params.tweakArgs) {
682 auto Code = DraftMgr.getDraft(Params.tweakArgs->file.file());
683 if (!Code)
684 return Reply(llvm::createStringError(
685 llvm::inconvertibleErrorCode(),
686 "trying to apply a code action for a non-added file"));
687
Ilya Biryukov12864002019-08-16 12:46:41 +0000688 auto Action = [this, ApplyEdit, Reply = std::move(Reply),
689 File = Params.tweakArgs->file, Code = std::move(*Code)](
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000690 llvm::Expected<Tweak::Effect> R) mutable {
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000691 if (!R)
692 return Reply(R.takeError());
693
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000694 assert(R->ShowMessage ||
695 (!R->ApplyEdits.empty() && "tweak has no effect"));
Ilya Biryukov12864002019-08-16 12:46:41 +0000696
Sam McCall395fde72019-06-18 13:37:54 +0000697 if (R->ShowMessage) {
698 ShowMessageParams Msg;
699 Msg.message = *R->ShowMessage;
700 Msg.type = MessageType::Info;
701 notify("window/showMessage", Msg);
702 }
Ilya Biryukov12864002019-08-16 12:46:41 +0000703 // When no edit is specified, make sure we Reply().
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000704 if (R->ApplyEdits.empty())
705 return Reply("Tweak applied.");
706
707 if (auto Err = validateEdits(DraftMgr, *R))
708 return Reply(std::move(Err));
709
710 WorkspaceEdit WE;
711 WE.changes.emplace();
712 for (const auto &It : R->ApplyEdits) {
Kadir Cetinkayae95e5162019-10-02 09:12:01 +0000713 (*WE.changes)[URI::createFile(It.first()).toString()] =
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000714 It.second.asTextEdits();
715 }
716 // ApplyEdit will take care of calling Reply().
717 return ApplyEdit(std::move(WE), "Tweak applied.", std::move(Reply));
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000718 };
719 Server->applyTweak(Params.tweakArgs->file.file(),
720 Params.tweakArgs->selection, Params.tweakArgs->tweakID,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000721 std::move(Action));
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000722 } else {
723 // We should not get here because ExecuteCommandParams would not have
724 // parsed in the first place and this handler should not be called. But if
725 // more commands are added, this will be here has a safe guard.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000726 Reply(llvm::make_error<LSPError>(
727 llvm::formatv("Unsupported command \"{0}\".", Params.command).str(),
Sam McCall2c30fbc2018-10-18 12:32:04 +0000728 ErrorCode::InvalidParams));
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000729 }
730}
731
Sam McCall2c30fbc2018-10-18 12:32:04 +0000732void ClangdLSPServer::onWorkspaceSymbol(
733 const WorkspaceSymbolParams &Params,
734 Callback<std::vector<SymbolInformation>> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000735 Server->workspaceSymbols(
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000736 Params.query, CCOpts.Limit,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000737 [Reply = std::move(Reply),
738 this](llvm::Expected<std::vector<SymbolInformation>> Items) mutable {
739 if (!Items)
740 return Reply(Items.takeError());
741 for (auto &Sym : *Items)
742 Sym.kind = adjustKindToCapability(Sym.kind, SupportedSymbolKinds);
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000743
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000744 Reply(std::move(*Items));
745 });
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000746}
747
Haojian Wuf429ab62019-07-24 07:49:23 +0000748void ClangdLSPServer::onPrepareRename(const TextDocumentPositionParams &Params,
749 Callback<llvm::Optional<Range>> Reply) {
750 Server->prepareRename(Params.textDocument.uri.file(), Params.position,
751 std::move(Reply));
752}
753
Sam McCall2c30fbc2018-10-18 12:32:04 +0000754void ClangdLSPServer::onRename(const RenameParams &Params,
755 Callback<WorkspaceEdit> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000756 Path File = Params.textDocument.uri.file();
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000757 llvm::Optional<std::string> Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000758 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000759 return Reply(llvm::make_error<LSPError>(
760 "onRename called for non-added file", ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000761
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000762 Server->rename(File, Params.position, Params.newName, /*WantFormat=*/true,
763 [File, Code, Params, Reply = std::move(Reply)](
764 llvm::Expected<std::vector<TextEdit>> Edits) mutable {
765 if (!Edits)
766 return Reply(Edits.takeError());
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000767
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000768 WorkspaceEdit WE;
769 WE.changes = {{Params.textDocument.uri.uri(), *Edits}};
770 Reply(WE);
771 });
Haojian Wu345099c2017-11-09 11:30:04 +0000772}
773
Sam McCall2c30fbc2018-10-18 12:32:04 +0000774void ClangdLSPServer::onDocumentDidClose(
775 const DidCloseTextDocumentParams &Params) {
Simon Marchi9569fd52018-03-16 14:30:42 +0000776 PathRef File = Params.textDocument.uri.file();
777 DraftMgr.removeDraft(File);
Ilya Biryukov652364b2018-09-26 05:48:29 +0000778 Server->removeDocument(File);
Ilya Biryukov49c10712019-03-25 10:15:11 +0000779
780 {
781 std::lock_guard<std::mutex> Lock(FixItsMutex);
782 FixItsMap.erase(File);
783 }
Johan Vikstromc2653ef22019-08-01 08:08:44 +0000784 {
785 std::lock_guard<std::mutex> HLock(HighlightingsMutex);
786 FileToHighlightings.erase(File);
787 }
Ilya Biryukov49c10712019-03-25 10:15:11 +0000788 // clangd will not send updates for this file anymore, so we empty out the
789 // list of diagnostics shown on the client (e.g. in the "Problems" pane of
790 // VSCode). Note that this cannot race with actual diagnostics responses
791 // because removeDocument() guarantees no diagnostic callbacks will be
792 // executed after it returns.
793 publishDiagnostics(URIForFile::canonicalize(File, /*TUPath=*/File), {});
Ilya Biryukovafb55542017-05-16 14:40:30 +0000794}
795
Sam McCall4db732a2017-09-30 10:08:52 +0000796void ClangdLSPServer::onDocumentOnTypeFormatting(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000797 const DocumentOnTypeFormattingParams &Params,
798 Callback<std::vector<TextEdit>> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000799 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000800 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000801 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000802 return Reply(llvm::make_error<LSPError>(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000803 "onDocumentOnTypeFormatting called for non-added file",
804 ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000805
Sam McCall25c62572019-06-10 14:26:21 +0000806 Reply(Server->formatOnType(*Code, File, Params.position, Params.ch));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000807}
808
Sam McCall4db732a2017-09-30 10:08:52 +0000809void ClangdLSPServer::onDocumentRangeFormatting(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000810 const DocumentRangeFormattingParams &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 "onDocumentRangeFormatting called for non-added file",
817 ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000818
Ilya Biryukov652364b2018-09-26 05:48:29 +0000819 auto ReplacementsOrError = Server->formatRange(*Code, File, Params.range);
Raoul Wols212bcf82017-12-12 20:25:06 +0000820 if (ReplacementsOrError)
Sam McCall2c30fbc2018-10-18 12:32:04 +0000821 Reply(replacementsToEdits(*Code, ReplacementsOrError.get()));
Raoul Wols212bcf82017-12-12 20:25:06 +0000822 else
Sam McCall2c30fbc2018-10-18 12:32:04 +0000823 Reply(ReplacementsOrError.takeError());
Ilya Biryukovafb55542017-05-16 14:40:30 +0000824}
825
Sam McCall2c30fbc2018-10-18 12:32:04 +0000826void ClangdLSPServer::onDocumentFormatting(
827 const DocumentFormattingParams &Params,
828 Callback<std::vector<TextEdit>> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000829 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000830 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000831 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000832 return Reply(llvm::make_error<LSPError>(
833 "onDocumentFormatting called for non-added file",
834 ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000835
Ilya Biryukov652364b2018-09-26 05:48:29 +0000836 auto ReplacementsOrError = Server->formatFile(*Code, File);
Raoul Wols212bcf82017-12-12 20:25:06 +0000837 if (ReplacementsOrError)
Sam McCall2c30fbc2018-10-18 12:32:04 +0000838 Reply(replacementsToEdits(*Code, ReplacementsOrError.get()));
Raoul Wols212bcf82017-12-12 20:25:06 +0000839 else
Sam McCall2c30fbc2018-10-18 12:32:04 +0000840 Reply(ReplacementsOrError.takeError());
Sam McCall4db732a2017-09-30 10:08:52 +0000841}
842
Ilya Biryukov19d75602018-11-23 15:21:19 +0000843/// The functions constructs a flattened view of the DocumentSymbol hierarchy.
844/// Used by the clients that do not support the hierarchical view.
845static std::vector<SymbolInformation>
846flattenSymbolHierarchy(llvm::ArrayRef<DocumentSymbol> Symbols,
847 const URIForFile &FileURI) {
848
849 std::vector<SymbolInformation> Results;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000850 std::function<void(const DocumentSymbol &, llvm::StringRef)> Process =
851 [&](const DocumentSymbol &S, llvm::Optional<llvm::StringRef> ParentName) {
Ilya Biryukov19d75602018-11-23 15:21:19 +0000852 SymbolInformation SI;
853 SI.containerName = ParentName ? "" : *ParentName;
854 SI.name = S.name;
855 SI.kind = S.kind;
856 SI.location.range = S.range;
857 SI.location.uri = FileURI;
858
859 Results.push_back(std::move(SI));
860 std::string FullName =
861 !ParentName ? S.name : (ParentName->str() + "::" + S.name);
862 for (auto &C : S.children)
863 Process(C, /*ParentName=*/FullName);
864 };
865 for (auto &S : Symbols)
866 Process(S, /*ParentName=*/"");
867 return Results;
868}
869
870void ClangdLSPServer::onDocumentSymbol(const DocumentSymbolParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000871 Callback<llvm::json::Value> Reply) {
Ilya Biryukov19d75602018-11-23 15:21:19 +0000872 URIForFile FileURI = Params.textDocument.uri;
Ilya Biryukov652364b2018-09-26 05:48:29 +0000873 Server->documentSymbols(
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000874 Params.textDocument.uri.file(),
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000875 [this, FileURI, Reply = std::move(Reply)](
876 llvm::Expected<std::vector<DocumentSymbol>> Items) mutable {
877 if (!Items)
878 return Reply(Items.takeError());
879 adjustSymbolKinds(*Items, SupportedSymbolKinds);
880 if (SupportsHierarchicalDocumentSymbol)
881 return Reply(std::move(*Items));
882 else
883 return Reply(flattenSymbolHierarchy(*Items, FileURI));
884 });
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000885}
886
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000887static llvm::Optional<Command> asCommand(const CodeAction &Action) {
Sam McCall20841d42018-10-16 16:29:41 +0000888 Command Cmd;
889 if (Action.command && Action.edit)
Sam McCallc008af62018-10-20 15:30:37 +0000890 return None; // Not representable. (We never emit these anyway).
Sam McCall20841d42018-10-16 16:29:41 +0000891 if (Action.command) {
892 Cmd = *Action.command;
893 } else if (Action.edit) {
894 Cmd.command = Command::CLANGD_APPLY_FIX_COMMAND;
895 Cmd.workspaceEdit = *Action.edit;
896 } else {
Sam McCallc008af62018-10-20 15:30:37 +0000897 return None;
Sam McCall20841d42018-10-16 16:29:41 +0000898 }
899 Cmd.title = Action.title;
900 if (Action.kind && *Action.kind == CodeAction::QUICKFIX_KIND)
901 Cmd.title = "Apply fix: " + Cmd.title;
902 return Cmd;
903}
904
Sam McCall2c30fbc2018-10-18 12:32:04 +0000905void ClangdLSPServer::onCodeAction(const CodeActionParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000906 Callback<llvm::json::Value> Reply) {
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000907 URIForFile File = Params.textDocument.uri;
908 auto Code = DraftMgr.getDraft(File.file());
Sam McCall2c30fbc2018-10-18 12:32:04 +0000909 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000910 return Reply(llvm::make_error<LSPError>(
911 "onCodeAction called for non-added file", ErrorCode::InvalidParams));
Sam McCall20841d42018-10-16 16:29:41 +0000912 // We provide a code action for Fixes on the specified diagnostics.
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000913 std::vector<CodeAction> FixIts;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000914 for (const Diagnostic &D : Params.context.diagnostics) {
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000915 for (auto &F : getFixes(File.file(), D)) {
916 FixIts.push_back(toCodeAction(F, Params.textDocument.uri));
917 FixIts.back().diagnostics = {D};
Sam McCalldd0566b2017-11-06 15:40:30 +0000918 }
Ilya Biryukovafb55542017-05-16 14:40:30 +0000919 }
Sam McCall20841d42018-10-16 16:29:41 +0000920
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000921 // Now enumerate the semantic code actions.
922 auto ConsumeActions =
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000923 [Reply = std::move(Reply), File, Code = std::move(*Code),
924 Selection = Params.range, FixIts = std::move(FixIts), this](
925 llvm::Expected<std::vector<ClangdServer::TweakRef>> Tweaks) mutable {
Ilya Biryukovc6ed7782019-01-30 14:24:17 +0000926 if (!Tweaks)
927 return Reply(Tweaks.takeError());
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000928
929 std::vector<CodeAction> Actions = std::move(FixIts);
930 Actions.reserve(Actions.size() + Tweaks->size());
931 for (const auto &T : *Tweaks)
932 Actions.push_back(toCodeAction(T, File, Selection));
933
934 if (SupportsCodeAction)
935 return Reply(llvm::json::Array(Actions));
936 std::vector<Command> Commands;
937 for (const auto &Action : Actions) {
938 if (auto Command = asCommand(Action))
939 Commands.push_back(std::move(*Command));
940 }
941 return Reply(llvm::json::Array(Commands));
942 };
943
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000944 Server->enumerateTweaks(File.file(), Params.range, std::move(ConsumeActions));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000945}
946
Ilya Biryukovb0826bd2019-01-03 13:37:12 +0000947void ClangdLSPServer::onCompletion(const CompletionParams &Params,
Sam McCall2c30fbc2018-10-18 12:32:04 +0000948 Callback<CompletionList> Reply) {
Ilya Biryukova7a11472019-06-07 16:24:38 +0000949 if (!shouldRunCompletion(Params)) {
950 // Clients sometimes auto-trigger completions in undesired places (e.g.
951 // 'a >^ '), we return empty results in those cases.
952 vlog("ignored auto-triggered completion, preceding char did not match");
953 return Reply(CompletionList());
954 }
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000955 Server->codeComplete(Params.textDocument.uri.file(), Params.position, CCOpts,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000956 [Reply = std::move(Reply),
957 this](llvm::Expected<CodeCompleteResult> List) mutable {
958 if (!List)
959 return Reply(List.takeError());
960 CompletionList LSPList;
961 LSPList.isIncomplete = List->HasMore;
962 for (const auto &R : List->Completions) {
963 CompletionItem C = R.render(CCOpts);
964 C.kind = adjustKindToCapability(
965 C.kind, SupportedCompletionItemKinds);
966 LSPList.items.push_back(std::move(C));
967 }
968 return Reply(std::move(LSPList));
969 });
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000970}
971
Sam McCall2c30fbc2018-10-18 12:32:04 +0000972void ClangdLSPServer::onSignatureHelp(const TextDocumentPositionParams &Params,
973 Callback<SignatureHelp> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000974 Server->signatureHelp(Params.textDocument.uri.file(), Params.position,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000975 [Reply = std::move(Reply), this](
976 llvm::Expected<SignatureHelp> Signature) mutable {
977 if (!Signature)
978 return Reply(Signature.takeError());
979 if (SupportsOffsetsInSignatureHelp)
980 return Reply(std::move(*Signature));
981 // Strip out the offsets from signature help for
982 // clients that only support string labels.
983 for (auto &SigInfo : Signature->signatures) {
984 for (auto &Param : SigInfo.parameters)
985 Param.labelOffsets.reset();
986 }
987 return Reply(std::move(*Signature));
988 });
Ilya Biryukov652364b2018-09-26 05:48:29 +0000989}
990
Sam McCall0dbab7f2019-02-02 05:56:00 +0000991// Go to definition has a toggle function: if def and decl are distinct, then
992// the first press gives you the def, the second gives you the matching def.
993// getToggle() returns the counterpart location that under the cursor.
994//
995// We return the toggled location alone (ignoring other symbols) to encourage
996// editors to "bounce" quickly between locations, without showing a menu.
997static Location *getToggle(const TextDocumentPositionParams &Point,
998 LocatedSymbol &Sym) {
999 // Toggle only makes sense with two distinct locations.
1000 if (!Sym.Definition || *Sym.Definition == Sym.PreferredDeclaration)
1001 return nullptr;
1002 if (Sym.Definition->uri.file() == Point.textDocument.uri.file() &&
1003 Sym.Definition->range.contains(Point.position))
1004 return &Sym.PreferredDeclaration;
1005 if (Sym.PreferredDeclaration.uri.file() == Point.textDocument.uri.file() &&
1006 Sym.PreferredDeclaration.range.contains(Point.position))
1007 return &*Sym.Definition;
1008 return nullptr;
1009}
1010
Sam McCall2c30fbc2018-10-18 12:32:04 +00001011void ClangdLSPServer::onGoToDefinition(const TextDocumentPositionParams &Params,
1012 Callback<std::vector<Location>> Reply) {
Sam McCall866ba2c2019-02-01 11:26:13 +00001013 Server->locateSymbolAt(
1014 Params.textDocument.uri.file(), Params.position,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001015 [Params, Reply = std::move(Reply)](
1016 llvm::Expected<std::vector<LocatedSymbol>> Symbols) mutable {
1017 if (!Symbols)
1018 return Reply(Symbols.takeError());
1019 std::vector<Location> Defs;
1020 for (auto &S : *Symbols) {
1021 if (Location *Toggle = getToggle(Params, S))
1022 return Reply(std::vector<Location>{std::move(*Toggle)});
1023 Defs.push_back(S.Definition.getValueOr(S.PreferredDeclaration));
1024 }
1025 Reply(std::move(Defs));
1026 });
Sam McCall866ba2c2019-02-01 11:26:13 +00001027}
1028
1029void ClangdLSPServer::onGoToDeclaration(
1030 const TextDocumentPositionParams &Params,
1031 Callback<std::vector<Location>> Reply) {
1032 Server->locateSymbolAt(
1033 Params.textDocument.uri.file(), Params.position,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001034 [Params, Reply = std::move(Reply)](
1035 llvm::Expected<std::vector<LocatedSymbol>> Symbols) mutable {
1036 if (!Symbols)
1037 return Reply(Symbols.takeError());
1038 std::vector<Location> Decls;
1039 for (auto &S : *Symbols) {
1040 if (Location *Toggle = getToggle(Params, S))
1041 return Reply(std::vector<Location>{std::move(*Toggle)});
1042 Decls.push_back(std::move(S.PreferredDeclaration));
1043 }
1044 Reply(std::move(Decls));
1045 });
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +00001046}
1047
Sam McCall111fe842019-05-07 07:55:35 +00001048void ClangdLSPServer::onSwitchSourceHeader(
1049 const TextDocumentIdentifier &Params,
Sam McCallb9ec3e92019-05-07 08:30:32 +00001050 Callback<llvm::Optional<URIForFile>> Reply) {
Haojian Wud6d5edd2019-10-01 10:21:15 +00001051 Server->switchSourceHeader(
1052 Params.uri.file(),
1053 [Reply = std::move(Reply),
1054 Params](llvm::Expected<llvm::Optional<clangd::Path>> Path) mutable {
1055 if (!Path)
1056 return Reply(Path.takeError());
1057 if (*Path)
Haojian Wu77c97002019-10-07 11:37:25 +00001058 return Reply(URIForFile::canonicalize(**Path, Params.uri.file()));
Haojian Wud6d5edd2019-10-01 10:21:15 +00001059 return Reply(llvm::None);
1060 });
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +00001061}
1062
Sam McCall2c30fbc2018-10-18 12:32:04 +00001063void ClangdLSPServer::onDocumentHighlight(
1064 const TextDocumentPositionParams &Params,
1065 Callback<std::vector<DocumentHighlight>> Reply) {
1066 Server->findDocumentHighlights(Params.textDocument.uri.file(),
1067 Params.position, std::move(Reply));
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +00001068}
1069
Sam McCall2c30fbc2018-10-18 12:32:04 +00001070void ClangdLSPServer::onHover(const TextDocumentPositionParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001071 Callback<llvm::Optional<Hover>> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +00001072 Server->findHover(Params.textDocument.uri.file(), Params.position,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001073 [Reply = std::move(Reply), this](
1074 llvm::Expected<llvm::Optional<HoverInfo>> H) mutable {
1075 if (!H)
1076 return Reply(H.takeError());
1077 if (!*H)
1078 return Reply(llvm::None);
Ilya Biryukovf9169d02019-05-29 10:01:00 +00001079
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001080 Hover R;
1081 R.contents.kind = HoverContentFormat;
1082 R.range = (*H)->SymRange;
1083 switch (HoverContentFormat) {
1084 case MarkupKind::PlainText:
1085 R.contents.value = (*H)->present().renderAsPlainText();
1086 return Reply(std::move(R));
1087 case MarkupKind::Markdown:
1088 R.contents.value = (*H)->present().renderAsMarkdown();
1089 return Reply(std::move(R));
1090 };
1091 llvm_unreachable("unhandled MarkupKind");
1092 });
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +00001093}
1094
Kadir Cetinkaya86658022019-03-19 09:27:04 +00001095void ClangdLSPServer::onTypeHierarchy(
1096 const TypeHierarchyParams &Params,
1097 Callback<Optional<TypeHierarchyItem>> Reply) {
1098 Server->typeHierarchy(Params.textDocument.uri.file(), Params.position,
1099 Params.resolve, Params.direction, std::move(Reply));
1100}
1101
Nathan Ridge087b0442019-07-13 03:24:48 +00001102void ClangdLSPServer::onResolveTypeHierarchy(
1103 const ResolveTypeHierarchyItemParams &Params,
1104 Callback<Optional<TypeHierarchyItem>> Reply) {
1105 Server->resolveTypeHierarchy(Params.item, Params.resolve, Params.direction,
1106 std::move(Reply));
1107}
1108
Simon Marchi88016782018-08-01 11:28:49 +00001109void ClangdLSPServer::applyConfiguration(
Sam McCallbc904612018-10-25 04:22:52 +00001110 const ConfigurationSettings &Settings) {
Simon Marchiabeed662018-10-16 15:55:03 +00001111 // Per-file update to the compilation database.
Sam McCallbc904612018-10-25 04:22:52 +00001112 bool ShouldReparseOpenFiles = false;
1113 for (auto &Entry : Settings.compilationDatabaseChanges) {
1114 /// The opened files need to be reparsed only when some existing
1115 /// entries are changed.
1116 PathRef File = Entry.first;
Sam McCallc55d09a2018-11-02 13:09:36 +00001117 auto Old = CDB->getCompileCommand(File);
1118 auto New =
1119 tooling::CompileCommand(std::move(Entry.second.workingDirectory), File,
1120 std::move(Entry.second.compilationCommand),
1121 /*Output=*/"");
Sam McCall6980edb2018-11-02 14:07:51 +00001122 if (Old != New) {
Sam McCallc55d09a2018-11-02 13:09:36 +00001123 CDB->setCompileCommand(File, std::move(New));
Sam McCall6980edb2018-11-02 14:07:51 +00001124 ShouldReparseOpenFiles = true;
1125 }
Alex Lorenzf8087862018-08-01 17:39:29 +00001126 }
Sam McCallbc904612018-10-25 04:22:52 +00001127 if (ShouldReparseOpenFiles)
1128 reparseOpenedFiles();
Simon Marchi5178f922018-02-22 14:00:39 +00001129}
1130
Johan Vikstroma848dab2019-07-04 07:53:12 +00001131void ClangdLSPServer::publishSemanticHighlighting(
1132 SemanticHighlightingParams Params) {
1133 notify("textDocument/semanticHighlighting", Params);
1134}
1135
Ilya Biryukov49c10712019-03-25 10:15:11 +00001136void ClangdLSPServer::publishDiagnostics(
1137 const URIForFile &File, std::vector<clangd::Diagnostic> Diagnostics) {
1138 // Publish diagnostics.
1139 notify("textDocument/publishDiagnostics",
1140 llvm::json::Object{
1141 {"uri", File},
1142 {"diagnostics", std::move(Diagnostics)},
1143 });
1144}
1145
Simon Marchi88016782018-08-01 11:28:49 +00001146// FIXME: This function needs to be properly tested.
1147void ClangdLSPServer::onChangeConfiguration(
Sam McCall2c30fbc2018-10-18 12:32:04 +00001148 const DidChangeConfigurationParams &Params) {
Simon Marchi88016782018-08-01 11:28:49 +00001149 applyConfiguration(Params.settings);
1150}
1151
Sam McCall2c30fbc2018-10-18 12:32:04 +00001152void ClangdLSPServer::onReference(const ReferenceParams &Params,
1153 Callback<std::vector<Location>> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +00001154 Server->findReferences(Params.textDocument.uri.file(), Params.position,
Haojian Wu5181ada2019-11-18 11:35:00 +01001155 CCOpts.Limit,
1156 [Reply = std::move(Reply)](
1157 llvm::Expected<ReferencesResult> Refs) mutable {
1158 if (!Refs)
1159 return Reply(Refs.takeError());
1160 return Reply(std::move(Refs->References));
1161 });
Sam McCall1ad142f2018-09-05 11:53:07 +00001162}
1163
Jan Korousb4067012018-11-27 16:40:46 +00001164void ClangdLSPServer::onSymbolInfo(const TextDocumentPositionParams &Params,
1165 Callback<std::vector<SymbolDetails>> Reply) {
1166 Server->symbolInfo(Params.textDocument.uri.file(), Params.position,
1167 std::move(Reply));
1168}
1169
Utkarsh Saxena55925da2019-09-24 13:38:33 +00001170void ClangdLSPServer::onSelectionRange(
1171 const SelectionRangeParams &Params,
1172 Callback<std::vector<SelectionRange>> Reply) {
1173 if (Params.positions.size() != 1) {
1174 elog("{0} positions provided to SelectionRange. Supports exactly one "
1175 "position.",
1176 Params.positions.size());
1177 return Reply(llvm::make_error<LSPError>(
1178 "SelectionRange supports exactly one position",
1179 ErrorCode::InvalidRequest));
1180 }
1181 Server->semanticRanges(
1182 Params.textDocument.uri.file(), Params.positions[0],
1183 [Reply = std::move(Reply)](
1184 llvm::Expected<std::vector<Range>> Ranges) mutable {
1185 if (!Ranges) {
1186 return Reply(Ranges.takeError());
1187 }
1188 std::vector<SelectionRange> Result;
1189 Result.emplace_back(render(std::move(*Ranges)));
1190 return Reply(std::move(Result));
1191 });
1192}
1193
Sam McCalla69698f2019-03-27 17:47:49 +00001194ClangdLSPServer::ClangdLSPServer(
1195 class Transport &Transp, const FileSystemProvider &FSProvider,
1196 const clangd::CodeCompleteOptions &CCOpts,
1197 llvm::Optional<Path> CompileCommandsDir, bool UseDirBasedCDB,
1198 llvm::Optional<OffsetEncoding> ForcedOffsetEncoding,
1199 const ClangdServer::Options &Opts)
Kadir Cetinkaya9d662472019-10-15 14:20:52 +00001200 : BackgroundContext(Context::current().clone()), Transp(Transp),
1201 MsgHandler(new MessageHandler(*this)), FSProvider(FSProvider),
1202 CCOpts(CCOpts), SupportedSymbolKinds(defaultSymbolKinds()),
Kadir Cetinkaya133d46f2018-09-27 17:13:07 +00001203 SupportedCompletionItemKinds(defaultCompletionItemKinds()),
Sam McCallc55d09a2018-11-02 13:09:36 +00001204 UseDirBasedCDB(UseDirBasedCDB),
Sam McCalla69698f2019-03-27 17:47:49 +00001205 CompileCommandsDir(std::move(CompileCommandsDir)), ClangdServerOpts(Opts),
1206 NegotiatedOffsetEncoding(ForcedOffsetEncoding) {
Sam McCall2c30fbc2018-10-18 12:32:04 +00001207 // clang-format off
1208 MsgHandler->bind("initialize", &ClangdLSPServer::onInitialize);
1209 MsgHandler->bind("shutdown", &ClangdLSPServer::onShutdown);
Sam McCall422c8282018-11-26 16:00:11 +00001210 MsgHandler->bind("sync", &ClangdLSPServer::onSync);
Sam McCall2c30fbc2018-10-18 12:32:04 +00001211 MsgHandler->bind("textDocument/rangeFormatting", &ClangdLSPServer::onDocumentRangeFormatting);
1212 MsgHandler->bind("textDocument/onTypeFormatting", &ClangdLSPServer::onDocumentOnTypeFormatting);
1213 MsgHandler->bind("textDocument/formatting", &ClangdLSPServer::onDocumentFormatting);
1214 MsgHandler->bind("textDocument/codeAction", &ClangdLSPServer::onCodeAction);
1215 MsgHandler->bind("textDocument/completion", &ClangdLSPServer::onCompletion);
1216 MsgHandler->bind("textDocument/signatureHelp", &ClangdLSPServer::onSignatureHelp);
1217 MsgHandler->bind("textDocument/definition", &ClangdLSPServer::onGoToDefinition);
Sam McCall866ba2c2019-02-01 11:26:13 +00001218 MsgHandler->bind("textDocument/declaration", &ClangdLSPServer::onGoToDeclaration);
Sam McCall2c30fbc2018-10-18 12:32:04 +00001219 MsgHandler->bind("textDocument/references", &ClangdLSPServer::onReference);
1220 MsgHandler->bind("textDocument/switchSourceHeader", &ClangdLSPServer::onSwitchSourceHeader);
Haojian Wuf429ab62019-07-24 07:49:23 +00001221 MsgHandler->bind("textDocument/prepareRename", &ClangdLSPServer::onPrepareRename);
Sam McCall2c30fbc2018-10-18 12:32:04 +00001222 MsgHandler->bind("textDocument/rename", &ClangdLSPServer::onRename);
1223 MsgHandler->bind("textDocument/hover", &ClangdLSPServer::onHover);
1224 MsgHandler->bind("textDocument/documentSymbol", &ClangdLSPServer::onDocumentSymbol);
1225 MsgHandler->bind("workspace/executeCommand", &ClangdLSPServer::onCommand);
1226 MsgHandler->bind("textDocument/documentHighlight", &ClangdLSPServer::onDocumentHighlight);
1227 MsgHandler->bind("workspace/symbol", &ClangdLSPServer::onWorkspaceSymbol);
1228 MsgHandler->bind("textDocument/didOpen", &ClangdLSPServer::onDocumentDidOpen);
1229 MsgHandler->bind("textDocument/didClose", &ClangdLSPServer::onDocumentDidClose);
1230 MsgHandler->bind("textDocument/didChange", &ClangdLSPServer::onDocumentDidChange);
1231 MsgHandler->bind("workspace/didChangeWatchedFiles", &ClangdLSPServer::onFileEvent);
1232 MsgHandler->bind("workspace/didChangeConfiguration", &ClangdLSPServer::onChangeConfiguration);
Jan Korousb4067012018-11-27 16:40:46 +00001233 MsgHandler->bind("textDocument/symbolInfo", &ClangdLSPServer::onSymbolInfo);
Kadir Cetinkaya86658022019-03-19 09:27:04 +00001234 MsgHandler->bind("textDocument/typeHierarchy", &ClangdLSPServer::onTypeHierarchy);
Nathan Ridge087b0442019-07-13 03:24:48 +00001235 MsgHandler->bind("typeHierarchy/resolve", &ClangdLSPServer::onResolveTypeHierarchy);
Utkarsh Saxena55925da2019-09-24 13:38:33 +00001236 MsgHandler->bind("textDocument/selectionRange", &ClangdLSPServer::onSelectionRange);
Sam McCall2c30fbc2018-10-18 12:32:04 +00001237 // clang-format on
1238}
1239
Sam McCall8bda5f22019-10-23 11:11:18 +02001240ClangdLSPServer::~ClangdLSPServer() { IsBeingDestroyed = true;
1241 // Explicitly destroy ClangdServer first, blocking on threads it owns.
1242 // This ensures they don't access any other members.
1243 Server.reset();
1244}
Ilya Biryukov38d79772017-05-16 09:38:59 +00001245
Sam McCalldc8f3cf2018-10-17 07:32:05 +00001246bool ClangdLSPServer::run() {
Ilya Biryukovafb55542017-05-16 14:40:30 +00001247 // Run the Language Server loop.
Sam McCalldc8f3cf2018-10-17 07:32:05 +00001248 bool CleanExit = true;
Sam McCall2c30fbc2018-10-18 12:32:04 +00001249 if (auto Err = Transp.loop(*MsgHandler)) {
Sam McCalldc8f3cf2018-10-17 07:32:05 +00001250 elog("Transport error: {0}", std::move(Err));
1251 CleanExit = false;
1252 }
Ilya Biryukovafb55542017-05-16 14:40:30 +00001253
Sam McCalldc8f3cf2018-10-17 07:32:05 +00001254 return CleanExit && ShutdownRequestReceived;
Ilya Biryukov38d79772017-05-16 09:38:59 +00001255}
1256
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001257std::vector<Fix> ClangdLSPServer::getFixes(llvm::StringRef File,
Ilya Biryukov71028b82018-03-12 15:28:22 +00001258 const clangd::Diagnostic &D) {
Ilya Biryukov38d79772017-05-16 09:38:59 +00001259 std::lock_guard<std::mutex> Lock(FixItsMutex);
1260 auto DiagToFixItsIter = FixItsMap.find(File);
1261 if (DiagToFixItsIter == FixItsMap.end())
1262 return {};
1263
1264 const auto &DiagToFixItsMap = DiagToFixItsIter->second;
1265 auto FixItsIter = DiagToFixItsMap.find(D);
1266 if (FixItsIter == DiagToFixItsMap.end())
1267 return {};
1268
1269 return FixItsIter->second;
1270}
1271
Ilya Biryukovb0826bd2019-01-03 13:37:12 +00001272bool ClangdLSPServer::shouldRunCompletion(
1273 const CompletionParams &Params) const {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001274 llvm::StringRef Trigger = Params.context.triggerCharacter;
Ilya Biryukovb0826bd2019-01-03 13:37:12 +00001275 if (Params.context.triggerKind != CompletionTriggerKind::TriggerCharacter ||
1276 (Trigger != ">" && Trigger != ":"))
1277 return true;
1278
1279 auto Code = DraftMgr.getDraft(Params.textDocument.uri.file());
1280 if (!Code)
1281 return true; // completion code will log the error for untracked doc.
1282
1283 // A completion request is sent when the user types '>' or ':', but we only
1284 // want to trigger on '->' and '::'. We check the preceeding character to make
1285 // sure it matches what we expected.
1286 // Running the lexer here would be more robust (e.g. we can detect comments
1287 // and avoid triggering completion there), but we choose to err on the side
1288 // of simplicity here.
1289 auto Offset = positionToOffset(*Code, Params.position,
1290 /*AllowColumnsBeyondLineLength=*/false);
1291 if (!Offset) {
1292 vlog("could not convert position '{0}' to offset for file '{1}'",
1293 Params.position, Params.textDocument.uri.file());
1294 return true;
1295 }
1296 if (*Offset < 2)
1297 return false;
1298
1299 if (Trigger == ">")
1300 return (*Code)[*Offset - 2] == '-'; // trigger only on '->'.
1301 if (Trigger == ":")
1302 return (*Code)[*Offset - 2] == ':'; // trigger only on '::'.
1303 assert(false && "unhandled trigger character");
1304 return true;
1305}
1306
Johan Vikstroma848dab2019-07-04 07:53:12 +00001307void ClangdLSPServer::onHighlightingsReady(
Haojian Wu0a6000f2019-08-26 08:38:45 +00001308 PathRef File, std::vector<HighlightingToken> Highlightings) {
Johan Vikstromc2653ef22019-08-01 08:08:44 +00001309 std::vector<HighlightingToken> Old;
1310 std::vector<HighlightingToken> HighlightingsCopy = Highlightings;
1311 {
1312 std::lock_guard<std::mutex> Lock(HighlightingsMutex);
1313 Old = std::move(FileToHighlightings[File]);
1314 FileToHighlightings[File] = std::move(HighlightingsCopy);
1315 }
1316 // LSP allows us to send incremental edits of highlightings. Also need to diff
1317 // to remove highlightings from tokens that should no longer have them.
Haojian Wu0a6000f2019-08-26 08:38:45 +00001318 std::vector<LineHighlightings> Diffed = diffHighlightings(Highlightings, Old);
Johan Vikstroma848dab2019-07-04 07:53:12 +00001319 publishSemanticHighlighting(
1320 {{URIForFile::canonicalize(File, /*TUPath=*/File)},
Johan Vikstromc2653ef22019-08-01 08:08:44 +00001321 toSemanticHighlightingInformation(Diffed)});
Johan Vikstroma848dab2019-07-04 07:53:12 +00001322}
1323
Sam McCalla7bb0cc2018-03-12 23:22:35 +00001324void ClangdLSPServer::onDiagnosticsReady(PathRef File,
1325 std::vector<Diag> Diagnostics) {
Eric Liu4d814a92018-11-28 10:30:42 +00001326 auto URI = URIForFile::canonicalize(File, /*TUPath=*/File);
Sam McCall16e70702018-10-24 07:59:38 +00001327 std::vector<Diagnostic> LSPDiagnostics;
Ilya Biryukov38d79772017-05-16 09:38:59 +00001328 DiagnosticToReplacementMap LocalFixIts; // Temporary storage
Sam McCalla7bb0cc2018-03-12 23:22:35 +00001329 for (auto &Diag : Diagnostics) {
Sam McCall16e70702018-10-24 07:59:38 +00001330 toLSPDiags(Diag, URI, DiagOpts,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001331 [&](clangd::Diagnostic Diag, llvm::ArrayRef<Fix> Fixes) {
Sam McCall16e70702018-10-24 07:59:38 +00001332 auto &FixItsForDiagnostic = LocalFixIts[Diag];
1333 llvm::copy(Fixes, std::back_inserter(FixItsForDiagnostic));
1334 LSPDiagnostics.push_back(std::move(Diag));
1335 });
Ilya Biryukov38d79772017-05-16 09:38:59 +00001336 }
1337
1338 // Cache FixIts
1339 {
Ilya Biryukov38d79772017-05-16 09:38:59 +00001340 std::lock_guard<std::mutex> Lock(FixItsMutex);
1341 FixItsMap[File] = LocalFixIts;
1342 }
1343
Ilya Biryukov49c10712019-03-25 10:15:11 +00001344 // Send a notification to the LSP client.
1345 publishDiagnostics(URI, std::move(LSPDiagnostics));
Ilya Biryukov38d79772017-05-16 09:38:59 +00001346}
Simon Marchi9569fd52018-03-16 14:30:42 +00001347
Haojian Wub6188492018-12-20 15:39:12 +00001348void ClangdLSPServer::onFileUpdated(PathRef File, const TUStatus &Status) {
1349 if (!SupportFileStatus)
1350 return;
1351 // FIXME: we don't emit "BuildingFile" and `RunningAction`, as these
1352 // two statuses are running faster in practice, which leads the UI constantly
1353 // changing, and doesn't provide much value. We may want to emit status at a
1354 // reasonable time interval (e.g. 0.5s).
1355 if (Status.Action.S == TUAction::BuildingFile ||
1356 Status.Action.S == TUAction::RunningAction)
1357 return;
1358 notify("textDocument/clangd.fileStatus", Status.render(File));
1359}
1360
Simon Marchi9569fd52018-03-16 14:30:42 +00001361void ClangdLSPServer::reparseOpenedFiles() {
1362 for (const Path &FilePath : DraftMgr.getActiveFiles())
Ilya Biryukov652364b2018-09-26 05:48:29 +00001363 Server->addDocument(FilePath, *DraftMgr.getDraft(FilePath),
1364 WantDiagnostics::Auto);
Simon Marchi9569fd52018-03-16 14:30:42 +00001365}
Alex Lorenzf8087862018-08-01 17:39:29 +00001366
Sam McCallc008af62018-10-20 15:30:37 +00001367} // namespace clangd
1368} // namespace clang