blob: fd5b3444f3410ee0e5f6e38f15de69191b395ff7 [file] [log] [blame]
Ilya Biryukov38d79772017-05-16 09:38:59 +00001//===--- ClangdLSPServer.cpp - LSP server ------------------------*- C++-*-===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Ilya Biryukov38d79772017-05-16 09:38:59 +00006//
Kirill Bobyrev8e35f1e2018-08-14 16:03:32 +00007//===----------------------------------------------------------------------===//
Ilya Biryukov38d79772017-05-16 09:38:59 +00008
9#include "ClangdLSPServer.h"
Ilya Biryukov71028b82018-03-12 15:28:22 +000010#include "Diagnostics.h"
Kadir Cetinkaya5b270932019-09-09 12:28:44 +000011#include "DraftStore.h"
Ilya Biryukovf9169d02019-05-29 10:01:00 +000012#include "FormattedString.h"
Kadir Cetinkaya256247c2019-06-26 07:45:27 +000013#include "GlobalCompilationDatabase.h"
Ilya Biryukovcce67a32019-01-29 14:17:36 +000014#include "Protocol.h"
Johan Vikstroma848dab2019-07-04 07:53:12 +000015#include "SemanticHighlighting.h"
Sam McCallb536a2a2017-12-19 12:23:48 +000016#include "SourceCode.h"
Sam McCall2c30fbc2018-10-18 12:32:04 +000017#include "Trace.h"
Eric Liu78ed91a72018-01-29 15:37:46 +000018#include "URI.h"
Sam McCall395fde72019-06-18 13:37:54 +000019#include "refactor/Tweak.h"
Ilya Biryukovcce67a32019-01-29 14:17:36 +000020#include "clang/Tooling/Core/Replacement.h"
Kadir Cetinkaya256247c2019-06-26 07:45:27 +000021#include "llvm/ADT/ArrayRef.h"
Sam McCalla69698f2019-03-27 17:47:49 +000022#include "llvm/ADT/Optional.h"
Kadir Cetinkaya689bf932018-08-24 13:09:41 +000023#include "llvm/ADT/ScopeExit.h"
Kadir Cetinkaya5b270932019-09-09 12:28:44 +000024#include "llvm/ADT/StringRef.h"
Utkarsh Saxena55925da2019-09-24 13:38:33 +000025#include "llvm/ADT/iterator_range.h"
Simon Marchi9569fd52018-03-16 14:30:42 +000026#include "llvm/Support/Errc.h"
Ilya Biryukovcce67a32019-01-29 14:17:36 +000027#include "llvm/Support/Error.h"
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +000028#include "llvm/Support/FormatVariadic.h"
Utkarsh Saxena55925da2019-09-24 13:38:33 +000029#include "llvm/Support/JSON.h"
Eric Liu5740ff52018-01-31 16:26:27 +000030#include "llvm/Support/Path.h"
Kadir Cetinkaya5b270932019-09-09 12:28:44 +000031#include "llvm/Support/SHA1.h"
Sam McCall2c30fbc2018-10-18 12:32:04 +000032#include "llvm/Support/ScopedPrinter.h"
Kadir Cetinkaya5b270932019-09-09 12:28:44 +000033#include <cstddef>
Utkarsh Saxena55925da2019-09-24 13:38:33 +000034#include <memory>
Kadir Cetinkaya5b270932019-09-09 12:28:44 +000035#include <string>
Utkarsh Saxena55925da2019-09-24 13:38:33 +000036#include <vector>
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +000037
Sam McCallc008af62018-10-20 15:30:37 +000038namespace clang {
39namespace clangd {
Ilya Biryukovafb55542017-05-16 14:40:30 +000040namespace {
Ilya Biryukovcce67a32019-01-29 14:17:36 +000041/// Transforms a tweak into a code action that would apply it if executed.
42/// EXPECTS: T.prepare() was called and returned true.
43CodeAction toCodeAction(const ClangdServer::TweakRef &T, const URIForFile &File,
44 Range Selection) {
45 CodeAction CA;
46 CA.title = T.Title;
Sam McCall395fde72019-06-18 13:37:54 +000047 switch (T.Intent) {
48 case Tweak::Refactor:
49 CA.kind = CodeAction::REFACTOR_KIND;
50 break;
51 case Tweak::Info:
52 CA.kind = CodeAction::INFO_KIND;
53 break;
54 }
Ilya Biryukovcce67a32019-01-29 14:17:36 +000055 // This tweak may have an expensive second stage, we only run it if the user
56 // actually chooses it in the UI. We reply with a command that would run the
57 // corresponding tweak.
58 // FIXME: for some tweaks, computing the edits is cheap and we could send them
59 // directly.
60 CA.command.emplace();
61 CA.command->title = T.Title;
62 CA.command->command = Command::CLANGD_APPLY_TWEAK;
63 CA.command->tweakArgs.emplace();
64 CA.command->tweakArgs->file = File;
65 CA.command->tweakArgs->tweakID = T.ID;
66 CA.command->tweakArgs->selection = Selection;
67 return CA;
Simon Pilgrime9a136b2019-02-03 14:08:30 +000068}
Ilya Biryukovcce67a32019-01-29 14:17:36 +000069
Ilya Biryukov19d75602018-11-23 15:21:19 +000070void adjustSymbolKinds(llvm::MutableArrayRef<DocumentSymbol> Syms,
71 SymbolKindBitset Kinds) {
72 for (auto &S : Syms) {
73 S.kind = adjustKindToCapability(S.kind, Kinds);
74 adjustSymbolKinds(S.children, Kinds);
75 }
76}
77
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +000078SymbolKindBitset defaultSymbolKinds() {
79 SymbolKindBitset Defaults;
80 for (size_t I = SymbolKindMin; I <= static_cast<size_t>(SymbolKind::Array);
81 ++I)
82 Defaults.set(I);
83 return Defaults;
84}
85
Kadir Cetinkaya133d46f2018-09-27 17:13:07 +000086CompletionItemKindBitset defaultCompletionItemKinds() {
87 CompletionItemKindBitset Defaults;
88 for (size_t I = CompletionItemKindMin;
89 I <= static_cast<size_t>(CompletionItemKind::Reference); ++I)
90 Defaults.set(I);
91 return Defaults;
92}
93
Haojian Wu1ca2ee42019-07-04 12:27:21 +000094// Build a lookup table (HighlightingKind => {TextMate Scopes}), which is sent
95// to the LSP client.
96std::vector<std::vector<std::string>> buildHighlightScopeLookupTable() {
97 std::vector<std::vector<std::string>> LookupTable;
98 // HighlightingKind is using as the index.
Ilya Biryukov63d5d162019-09-09 08:57:17 +000099 for (int KindValue = 0; KindValue <= (int)HighlightingKind::LastKind;
Haojian Wu1ca2ee42019-07-04 12:27:21 +0000100 ++KindValue)
101 LookupTable.push_back({toTextMateScope((HighlightingKind)(KindValue))});
102 return LookupTable;
103}
104
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000105// Makes sure edits in \p E are applicable to latest file contents reported by
106// editor. If not generates an error message containing information about files
107// that needs to be saved.
108llvm::Error validateEdits(const DraftStore &DraftMgr, const Tweak::Effect &E) {
109 size_t InvalidFileCount = 0;
110 llvm::StringRef LastInvalidFile;
111 for (const auto &It : E.ApplyEdits) {
112 if (auto Draft = DraftMgr.getDraft(It.first())) {
113 // If the file is open in user's editor, make sure the version we
114 // saw and current version are compatible as this is the text that
115 // will be replaced by editors.
116 if (!It.second.canApplyTo(*Draft)) {
117 ++InvalidFileCount;
118 LastInvalidFile = It.first();
119 }
120 }
121 }
122 if (!InvalidFileCount)
123 return llvm::Error::success();
124 if (InvalidFileCount == 1)
125 return llvm::createStringError(llvm::inconvertibleErrorCode(),
126 "File must be saved first: " +
127 LastInvalidFile);
128 return llvm::createStringError(
129 llvm::inconvertibleErrorCode(),
130 "Files must be saved first: " + LastInvalidFile + " (and " +
131 llvm::to_string(InvalidFileCount - 1) + " others)");
132}
133
Utkarsh Saxena55925da2019-09-24 13:38:33 +0000134// Converts a list of Ranges to a LinkedList of SelectionRange.
135SelectionRange render(const std::vector<Range> &Ranges) {
136 if (Ranges.empty())
137 return {};
138 SelectionRange Result;
139 Result.range = Ranges[0];
140 auto *Next = &Result.parent;
141 for (const auto &R : llvm::make_range(Ranges.begin() + 1, Ranges.end())) {
142 *Next = std::make_unique<SelectionRange>();
143 Next->get()->range = R;
144 Next = &Next->get()->parent;
145 }
146 return Result;
147}
148
Ilya Biryukovafb55542017-05-16 14:40:30 +0000149} // namespace
150
Sam McCall2c30fbc2018-10-18 12:32:04 +0000151// MessageHandler dispatches incoming LSP messages.
152// It handles cross-cutting concerns:
153// - serializes/deserializes protocol objects to JSON
154// - logging of inbound messages
155// - cancellation handling
156// - basic call tracing
Sam McCall3d0adbe2018-10-18 14:41:50 +0000157// MessageHandler ensures that initialize() is called before any other handler.
Sam McCall2c30fbc2018-10-18 12:32:04 +0000158class ClangdLSPServer::MessageHandler : public Transport::MessageHandler {
159public:
160 MessageHandler(ClangdLSPServer &Server) : Server(Server) {}
161
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000162 bool onNotify(llvm::StringRef Method, llvm::json::Value Params) override {
Sam McCalla69698f2019-03-27 17:47:49 +0000163 WithContext HandlerContext(handlerContext());
Sam McCall2c30fbc2018-10-18 12:32:04 +0000164 log("<-- {0}", Method);
165 if (Method == "exit")
166 return false;
Sam McCall3d0adbe2018-10-18 14:41:50 +0000167 if (!Server.Server)
168 elog("Notification {0} before initialization", Method);
169 else if (Method == "$/cancelRequest")
Sam McCall2c30fbc2018-10-18 12:32:04 +0000170 onCancel(std::move(Params));
171 else if (auto Handler = Notifications.lookup(Method))
172 Handler(std::move(Params));
173 else
174 log("unhandled notification {0}", Method);
175 return true;
176 }
177
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000178 bool onCall(llvm::StringRef Method, llvm::json::Value Params,
179 llvm::json::Value ID) override {
Sam McCalla69698f2019-03-27 17:47:49 +0000180 WithContext HandlerContext(handlerContext());
Sam McCalle2f3a732018-10-24 14:26:26 +0000181 // Calls can be canceled by the client. Add cancellation context.
182 WithContext WithCancel(cancelableRequestContext(ID));
183 trace::Span Tracer(Method);
184 SPAN_ATTACH(Tracer, "Params", Params);
185 ReplyOnce Reply(ID, Method, &Server, Tracer.Args);
Sam McCall2c30fbc2018-10-18 12:32:04 +0000186 log("<-- {0}({1})", Method, ID);
Sam McCall3d0adbe2018-10-18 14:41:50 +0000187 if (!Server.Server && Method != "initialize") {
188 elog("Call {0} before initialization.", Method);
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000189 Reply(llvm::make_error<LSPError>("server not initialized",
190 ErrorCode::ServerNotInitialized));
Sam McCall3d0adbe2018-10-18 14:41:50 +0000191 } else if (auto Handler = Calls.lookup(Method))
Sam McCalle2f3a732018-10-24 14:26:26 +0000192 Handler(std::move(Params), std::move(Reply));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000193 else
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000194 Reply(llvm::make_error<LSPError>("method not found",
195 ErrorCode::MethodNotFound));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000196 return true;
197 }
198
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000199 bool onReply(llvm::json::Value ID,
200 llvm::Expected<llvm::json::Value> Result) override {
Sam McCalla69698f2019-03-27 17:47:49 +0000201 WithContext HandlerContext(handlerContext());
Haojian Wuf2516342019-08-05 12:48:09 +0000202
203 Callback<llvm::json::Value> ReplyHandler = nullptr;
204 if (auto IntID = ID.getAsInteger()) {
205 std::lock_guard<std::mutex> Mutex(CallMutex);
206 // Find a corresponding callback for the request ID;
207 for (size_t Index = 0; Index < ReplyCallbacks.size(); ++Index) {
208 if (ReplyCallbacks[Index].first == *IntID) {
209 ReplyHandler = std::move(ReplyCallbacks[Index].second);
210 ReplyCallbacks.erase(ReplyCallbacks.begin() +
211 Index); // remove the entry
212 break;
213 }
214 }
215 }
216
217 if (!ReplyHandler) {
218 // No callback being found, use a default log callback.
219 ReplyHandler = [&ID](llvm::Expected<llvm::json::Value> Result) {
220 elog("received a reply with ID {0}, but there was no such call", ID);
221 if (!Result)
222 llvm::consumeError(Result.takeError());
223 };
224 }
225
226 // Log and run the reply handler.
227 if (Result) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000228 log("<-- reply({0})", ID);
Haojian Wuf2516342019-08-05 12:48:09 +0000229 ReplyHandler(std::move(Result));
230 } else {
231 auto Err = Result.takeError();
232 log("<-- reply({0}) error: {1}", ID, Err);
233 ReplyHandler(std::move(Err));
234 }
Sam McCall2c30fbc2018-10-18 12:32:04 +0000235 return true;
236 }
237
238 // Bind an LSP method name to a call.
Sam McCalle2f3a732018-10-24 14:26:26 +0000239 template <typename Param, typename Result>
Sam McCall2c30fbc2018-10-18 12:32:04 +0000240 void bind(const char *Method,
Sam McCalle2f3a732018-10-24 14:26:26 +0000241 void (ClangdLSPServer::*Handler)(const Param &, Callback<Result>)) {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000242 Calls[Method] = [Method, Handler, this](llvm::json::Value RawParams,
Sam McCalle2f3a732018-10-24 14:26:26 +0000243 ReplyOnce Reply) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000244 Param P;
Sam McCalle2f3a732018-10-24 14:26:26 +0000245 if (fromJSON(RawParams, P)) {
246 (Server.*Handler)(P, std::move(Reply));
247 } else {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000248 elog("Failed to decode {0} request.", Method);
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000249 Reply(llvm::make_error<LSPError>("failed to decode request",
250 ErrorCode::InvalidRequest));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000251 }
Sam McCall2c30fbc2018-10-18 12:32:04 +0000252 };
253 }
254
Haojian Wuf2516342019-08-05 12:48:09 +0000255 // Bind a reply callback to a request. The callback will be invoked when
256 // clangd receives the reply from the LSP client.
257 // Return a call id of the request.
258 llvm::json::Value bindReply(Callback<llvm::json::Value> Reply) {
259 llvm::Optional<std::pair<int, Callback<llvm::json::Value>>> OldestCB;
260 int ID;
261 {
262 std::lock_guard<std::mutex> Mutex(CallMutex);
263 ID = NextCallID++;
264 ReplyCallbacks.emplace_back(ID, std::move(Reply));
265
266 // If the queue overflows, we assume that the client didn't reply the
267 // oldest request, and run the corresponding callback which replies an
268 // error to the client.
269 if (ReplyCallbacks.size() > MaxReplayCallbacks) {
270 elog("more than {0} outstanding LSP calls, forgetting about {1}",
271 MaxReplayCallbacks, ReplyCallbacks.front().first);
272 OldestCB = std::move(ReplyCallbacks.front());
273 ReplyCallbacks.pop_front();
274 }
275 }
276 if (OldestCB)
277 OldestCB->second(llvm::createStringError(
278 llvm::inconvertibleErrorCode(),
279 llvm::formatv("failed to receive a client reply for request ({0})",
280 OldestCB->first)));
281 return ID;
282 }
283
Sam McCall2c30fbc2018-10-18 12:32:04 +0000284 // Bind an LSP method name to a notification.
285 template <typename Param>
286 void bind(const char *Method,
287 void (ClangdLSPServer::*Handler)(const Param &)) {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000288 Notifications[Method] = [Method, Handler,
289 this](llvm::json::Value RawParams) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000290 Param P;
291 if (!fromJSON(RawParams, P)) {
292 elog("Failed to decode {0} request.", Method);
293 return;
294 }
295 trace::Span Tracer(Method);
296 SPAN_ATTACH(Tracer, "Params", RawParams);
297 (Server.*Handler)(P);
298 };
299 }
300
301private:
Sam McCalle2f3a732018-10-24 14:26:26 +0000302 // Function object to reply to an LSP call.
303 // Each instance must be called exactly once, otherwise:
304 // - the bug is logged, and (in debug mode) an assert will fire
305 // - if there was no reply, an error reply is sent
306 // - if there were multiple replies, only the first is sent
307 class ReplyOnce {
308 std::atomic<bool> Replied = {false};
Sam McCalld7babe42018-10-24 15:18:40 +0000309 std::chrono::steady_clock::time_point Start;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000310 llvm::json::Value ID;
Sam McCalle2f3a732018-10-24 14:26:26 +0000311 std::string Method;
312 ClangdLSPServer *Server; // Null when moved-from.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000313 llvm::json::Object *TraceArgs;
Sam McCalle2f3a732018-10-24 14:26:26 +0000314
315 public:
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000316 ReplyOnce(const llvm::json::Value &ID, llvm::StringRef Method,
317 ClangdLSPServer *Server, llvm::json::Object *TraceArgs)
Sam McCalld7babe42018-10-24 15:18:40 +0000318 : Start(std::chrono::steady_clock::now()), ID(ID), Method(Method),
319 Server(Server), TraceArgs(TraceArgs) {
Sam McCalle2f3a732018-10-24 14:26:26 +0000320 assert(Server);
321 }
322 ReplyOnce(ReplyOnce &&Other)
Sam McCalld7babe42018-10-24 15:18:40 +0000323 : Replied(Other.Replied.load()), Start(Other.Start),
324 ID(std::move(Other.ID)), Method(std::move(Other.Method)),
325 Server(Other.Server), TraceArgs(Other.TraceArgs) {
Sam McCalle2f3a732018-10-24 14:26:26 +0000326 Other.Server = nullptr;
327 }
Ilya Biryukov22fa4652019-01-03 13:28:05 +0000328 ReplyOnce &operator=(ReplyOnce &&) = delete;
Sam McCalle2f3a732018-10-24 14:26:26 +0000329 ReplyOnce(const ReplyOnce &) = delete;
Ilya Biryukov22fa4652019-01-03 13:28:05 +0000330 ReplyOnce &operator=(const ReplyOnce &) = delete;
Sam McCalle2f3a732018-10-24 14:26:26 +0000331
332 ~ReplyOnce() {
Haojian Wuf2516342019-08-05 12:48:09 +0000333 // There's one legitimate reason to never reply to a request: clangd's
334 // request handler send a call to the client (e.g. applyEdit) and the
335 // client never replied. In this case, the ReplyOnce is owned by
336 // ClangdLSPServer's reply callback table and is destroyed along with the
337 // server. We don't attempt to send a reply in this case, there's little
338 // to be gained from doing so.
339 if (Server && !Server->IsBeingDestroyed && !Replied) {
Sam McCalle2f3a732018-10-24 14:26:26 +0000340 elog("No reply to message {0}({1})", Method, ID);
341 assert(false && "must reply to all calls!");
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000342 (*this)(llvm::make_error<LSPError>("server failed to reply",
343 ErrorCode::InternalError));
Sam McCalle2f3a732018-10-24 14:26:26 +0000344 }
345 }
346
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000347 void operator()(llvm::Expected<llvm::json::Value> Reply) {
Sam McCalle2f3a732018-10-24 14:26:26 +0000348 assert(Server && "moved-from!");
349 if (Replied.exchange(true)) {
350 elog("Replied twice to message {0}({1})", Method, ID);
351 assert(false && "must reply to each call only once!");
352 return;
353 }
Sam McCalld7babe42018-10-24 15:18:40 +0000354 auto Duration = std::chrono::steady_clock::now() - Start;
355 if (Reply) {
356 log("--> reply:{0}({1}) {2:ms}", Method, ID, Duration);
357 if (TraceArgs)
Sam McCalle2f3a732018-10-24 14:26:26 +0000358 (*TraceArgs)["Reply"] = *Reply;
Sam McCalld7babe42018-10-24 15:18:40 +0000359 std::lock_guard<std::mutex> Lock(Server->TranspWriter);
360 Server->Transp.reply(std::move(ID), std::move(Reply));
361 } else {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000362 llvm::Error Err = Reply.takeError();
Sam McCalld7babe42018-10-24 15:18:40 +0000363 log("--> reply:{0}({1}) {2:ms}, error: {3}", Method, ID, Duration, Err);
364 if (TraceArgs)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000365 (*TraceArgs)["Error"] = llvm::to_string(Err);
Sam McCalld7babe42018-10-24 15:18:40 +0000366 std::lock_guard<std::mutex> Lock(Server->TranspWriter);
367 Server->Transp.reply(std::move(ID), std::move(Err));
Sam McCalle2f3a732018-10-24 14:26:26 +0000368 }
Sam McCalle2f3a732018-10-24 14:26:26 +0000369 }
370 };
371
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000372 llvm::StringMap<std::function<void(llvm::json::Value)>> Notifications;
373 llvm::StringMap<std::function<void(llvm::json::Value, ReplyOnce)>> Calls;
Haojian Wuf2516342019-08-05 12:48:09 +0000374 // The maximum number of callbacks held in clangd.
375 //
376 // We bound the maximum size to the pending map to prevent memory leakage
377 // for cases where LSP clients don't reply for the request.
378 static constexpr int MaxReplayCallbacks = 100;
379 mutable std::mutex CallMutex;
380 int NextCallID = 0; /* GUARDED_BY(CallMutex) */
381 std::deque<std::pair</*RequestID*/ int,
382 /*ReplyHandler*/ Callback<llvm::json::Value>>>
383 ReplyCallbacks; /* GUARDED_BY(CallMutex) */
Sam McCall2c30fbc2018-10-18 12:32:04 +0000384
385 // Method calls may be cancelled by ID, so keep track of their state.
386 // This needs a mutex: handlers may finish on a different thread, and that's
387 // when we clean up entries in the map.
388 mutable std::mutex RequestCancelersMutex;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000389 llvm::StringMap<std::pair<Canceler, /*Cookie*/ unsigned>> RequestCancelers;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000390 unsigned NextRequestCookie = 0; // To disambiguate reused IDs, see below.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000391 void onCancel(const llvm::json::Value &Params) {
392 const llvm::json::Value *ID = nullptr;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000393 if (auto *O = Params.getAsObject())
394 ID = O->get("id");
395 if (!ID) {
396 elog("Bad cancellation request: {0}", Params);
397 return;
398 }
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000399 auto StrID = llvm::to_string(*ID);
Sam McCall2c30fbc2018-10-18 12:32:04 +0000400 std::lock_guard<std::mutex> Lock(RequestCancelersMutex);
401 auto It = RequestCancelers.find(StrID);
402 if (It != RequestCancelers.end())
403 It->second.first(); // Invoke the canceler.
404 }
Sam McCalla69698f2019-03-27 17:47:49 +0000405
406 Context handlerContext() const {
407 return Context::current().derive(
408 kCurrentOffsetEncoding,
409 Server.NegotiatedOffsetEncoding.getValueOr(OffsetEncoding::UTF16));
410 }
411
Sam McCall2c30fbc2018-10-18 12:32:04 +0000412 // We run cancelable requests in a context that does two things:
413 // - allows cancellation using RequestCancelers[ID]
414 // - cleans up the entry in RequestCancelers when it's no longer needed
415 // If a client reuses an ID, the last wins and the first cannot be canceled.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000416 Context cancelableRequestContext(const llvm::json::Value &ID) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000417 auto Task = cancelableTask();
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000418 auto StrID = llvm::to_string(ID); // JSON-serialize ID for map key.
Sam McCall2c30fbc2018-10-18 12:32:04 +0000419 auto Cookie = NextRequestCookie++; // No lock, only called on main thread.
420 {
421 std::lock_guard<std::mutex> Lock(RequestCancelersMutex);
422 RequestCancelers[StrID] = {std::move(Task.second), Cookie};
423 }
424 // When the request ends, we can clean up the entry we just added.
425 // The cookie lets us check that it hasn't been overwritten due to ID
426 // reuse.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000427 return Task.first.derive(llvm::make_scope_exit([this, StrID, Cookie] {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000428 std::lock_guard<std::mutex> Lock(RequestCancelersMutex);
429 auto It = RequestCancelers.find(StrID);
430 if (It != RequestCancelers.end() && It->second.second == Cookie)
431 RequestCancelers.erase(It);
432 }));
433 }
434
435 ClangdLSPServer &Server;
436};
Haojian Wuf2516342019-08-05 12:48:09 +0000437constexpr int ClangdLSPServer::MessageHandler::MaxReplayCallbacks;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000438
439// call(), notify(), and reply() wrap the Transport, adding logging and locking.
Haojian Wuf2516342019-08-05 12:48:09 +0000440void ClangdLSPServer::callRaw(StringRef Method, llvm::json::Value Params,
441 Callback<llvm::json::Value> CB) {
442 auto ID = MsgHandler->bindReply(std::move(CB));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000443 log("--> {0}({1})", Method, ID);
Sam McCall2c30fbc2018-10-18 12:32:04 +0000444 std::lock_guard<std::mutex> Lock(TranspWriter);
445 Transp.call(Method, std::move(Params), ID);
446}
447
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000448void ClangdLSPServer::notify(llvm::StringRef Method, llvm::json::Value Params) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000449 log("--> {0}", Method);
450 std::lock_guard<std::mutex> Lock(TranspWriter);
451 Transp.notify(Method, std::move(Params));
452}
453
Sam McCall2c30fbc2018-10-18 12:32:04 +0000454void ClangdLSPServer::onInitialize(const InitializeParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000455 Callback<llvm::json::Value> Reply) {
Sam McCalla69698f2019-03-27 17:47:49 +0000456 // Determine character encoding first as it affects constructed ClangdServer.
457 if (Params.capabilities.offsetEncoding && !NegotiatedOffsetEncoding) {
458 NegotiatedOffsetEncoding = OffsetEncoding::UTF16; // fallback
459 for (OffsetEncoding Supported : *Params.capabilities.offsetEncoding)
460 if (Supported != OffsetEncoding::UnsupportedEncoding) {
461 NegotiatedOffsetEncoding = Supported;
462 break;
463 }
464 }
465 llvm::Optional<WithContextValue> WithOffsetEncoding;
466 if (NegotiatedOffsetEncoding)
467 WithOffsetEncoding.emplace(kCurrentOffsetEncoding,
468 *NegotiatedOffsetEncoding);
469
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);
Sam McCallc55d09a2018-11-02 13:09:36 +0000490 Server.emplace(*CDB, FSProvider, static_cast<DiagnosticsConsumer &>(*this),
491 ClangdServerOpts);
Sam McCallbc904612018-10-25 04:22:52 +0000492 applyConfiguration(Params.initializationOptions.ConfigSettings);
Simon Marchi88016782018-08-01 11:28:49 +0000493
Sam McCallbf6a2fc2018-10-17 07:33:42 +0000494 CCOpts.EnableSnippets = Params.capabilities.CompletionSnippets;
Sam McCall8d412942019-06-18 11:57:26 +0000495 CCOpts.IncludeFixIts = Params.capabilities.CompletionFixes;
Sam McCall5f092e32019-07-08 17:27:15 +0000496 if (!CCOpts.BundleOverloads.hasValue())
497 CCOpts.BundleOverloads = Params.capabilities.HasSignatureHelp;
Sam McCallbf6a2fc2018-10-17 07:33:42 +0000498 DiagOpts.EmbedFixesInDiagnostics = Params.capabilities.DiagnosticFixes;
499 DiagOpts.SendDiagnosticCategory = Params.capabilities.DiagnosticCategory;
Sam McCallc9e4ee92019-04-18 15:17:07 +0000500 DiagOpts.EmitRelatedLocations =
501 Params.capabilities.DiagnosticRelatedInformation;
Sam McCallbf6a2fc2018-10-17 07:33:42 +0000502 if (Params.capabilities.WorkspaceSymbolKinds)
503 SupportedSymbolKinds |= *Params.capabilities.WorkspaceSymbolKinds;
504 if (Params.capabilities.CompletionItemKinds)
505 SupportedCompletionItemKinds |= *Params.capabilities.CompletionItemKinds;
506 SupportsCodeAction = Params.capabilities.CodeActionStructure;
Ilya Biryukov19d75602018-11-23 15:21:19 +0000507 SupportsHierarchicalDocumentSymbol =
508 Params.capabilities.HierarchicalDocumentSymbol;
Haojian Wub6188492018-12-20 15:39:12 +0000509 SupportFileStatus = Params.initializationOptions.FileStatus;
Ilya Biryukovf9169d02019-05-29 10:01:00 +0000510 HoverContentFormat = Params.capabilities.HoverContentFormat;
Ilya Biryukov4ef0f822019-06-04 09:36:59 +0000511 SupportsOffsetsInSignatureHelp = Params.capabilities.OffsetsInSignatureHelp;
Haojian Wuf429ab62019-07-24 07:49:23 +0000512
513 // Per LSP, renameProvider can be either boolean or RenameOptions.
514 // RenameOptions will be specified if the client states it supports prepare.
515 llvm::json::Value RenameProvider =
516 llvm::json::Object{{"prepareProvider", true}};
517 if (!Params.capabilities.RenamePrepareSupport) // Only boolean allowed per LSP
518 RenameProvider = true;
519
Haojian Wu08d93f12019-08-22 14:53:45 +0000520 // Per LSP, codeActionProvide can be either boolean or CodeActionOptions.
521 // CodeActionOptions is only valid if the client supports action literal
522 // via textDocument.codeAction.codeActionLiteralSupport.
523 llvm::json::Value CodeActionProvider = true;
524 if (Params.capabilities.CodeActionStructure)
525 CodeActionProvider = llvm::json::Object{
526 {"codeActionKinds",
527 {CodeAction::QUICKFIX_KIND, CodeAction::REFACTOR_KIND,
528 CodeAction::INFO_KIND}}};
529
Sam McCalla69698f2019-03-27 17:47:49 +0000530 llvm::json::Object Result{
Sam McCall0930ab02017-11-07 15:49:35 +0000531 {{"capabilities",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000532 llvm::json::Object{
Simon Marchi98082622018-03-26 14:41:40 +0000533 {"textDocumentSync", (int)TextDocumentSyncKind::Incremental},
Sam McCall0930ab02017-11-07 15:49:35 +0000534 {"documentFormattingProvider", true},
535 {"documentRangeFormattingProvider", true},
536 {"documentOnTypeFormattingProvider",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000537 llvm::json::Object{
Sam McCall25c62572019-06-10 14:26:21 +0000538 {"firstTriggerCharacter", "\n"},
Sam McCall0930ab02017-11-07 15:49:35 +0000539 {"moreTriggerCharacter", {}},
540 }},
Haojian Wu08d93f12019-08-22 14:53:45 +0000541 {"codeActionProvider", std::move(CodeActionProvider)},
Sam McCall0930ab02017-11-07 15:49:35 +0000542 {"completionProvider",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000543 llvm::json::Object{
Sam McCall0930ab02017-11-07 15:49:35 +0000544 {"resolveProvider", false},
Ilya Biryukovb0826bd2019-01-03 13:37:12 +0000545 // We do extra checks for '>' and ':' in completion to only
546 // trigger on '->' and '::'.
Sam McCall0930ab02017-11-07 15:49:35 +0000547 {"triggerCharacters", {".", ">", ":"}},
548 }},
549 {"signatureHelpProvider",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000550 llvm::json::Object{
Sam McCall0930ab02017-11-07 15:49:35 +0000551 {"triggerCharacters", {"(", ","}},
552 }},
Sam McCall866ba2c2019-02-01 11:26:13 +0000553 {"declarationProvider", true},
Sam McCall0930ab02017-11-07 15:49:35 +0000554 {"definitionProvider", true},
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000555 {"documentHighlightProvider", true},
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000556 {"hoverProvider", true},
Haojian Wuf429ab62019-07-24 07:49:23 +0000557 {"renameProvider", std::move(RenameProvider)},
Utkarsh Saxena55925da2019-09-24 13:38:33 +0000558 {"selectionRangeProvider", true},
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000559 {"documentSymbolProvider", true},
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000560 {"workspaceSymbolProvider", true},
Sam McCall1ad142f2018-09-05 11:53:07 +0000561 {"referencesProvider", true},
Sam McCall0930ab02017-11-07 15:49:35 +0000562 {"executeCommandProvider",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000563 llvm::json::Object{
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000564 {"commands",
565 {ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND,
566 ExecuteCommandParams::CLANGD_APPLY_TWEAK}},
Sam McCall0930ab02017-11-07 15:49:35 +0000567 }},
Kadir Cetinkaya86658022019-03-19 09:27:04 +0000568 {"typeHierarchyProvider", true},
Sam McCalla69698f2019-03-27 17:47:49 +0000569 }}}};
570 if (NegotiatedOffsetEncoding)
571 Result["offsetEncoding"] = *NegotiatedOffsetEncoding;
Johan Vikstroma848dab2019-07-04 07:53:12 +0000572 if (Params.capabilities.SemanticHighlighting)
573 Result.getObject("capabilities")
574 ->insert(
575 {"semanticHighlighting",
Haojian Wu1ca2ee42019-07-04 12:27:21 +0000576 llvm::json::Object{{"scopes", buildHighlightScopeLookupTable()}}});
Sam McCalla69698f2019-03-27 17:47:49 +0000577 Reply(std::move(Result));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000578}
579
Sam McCall2c30fbc2018-10-18 12:32:04 +0000580void ClangdLSPServer::onShutdown(const ShutdownParams &Params,
581 Callback<std::nullptr_t> Reply) {
Ilya Biryukov0d9b8a32017-10-25 08:45:41 +0000582 // Do essentially nothing, just say we're ready to exit.
583 ShutdownRequestReceived = true;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000584 Reply(nullptr);
Sam McCall8a5dded2017-10-12 13:29:58 +0000585}
Ilya Biryukovafb55542017-05-16 14:40:30 +0000586
Sam McCall422c8282018-11-26 16:00:11 +0000587// sync is a clangd extension: it blocks until all background work completes.
588// It blocks the calling thread, so no messages are processed until it returns!
589void ClangdLSPServer::onSync(const NoParams &Params,
590 Callback<std::nullptr_t> Reply) {
591 if (Server->blockUntilIdleForTest(/*TimeoutSeconds=*/60))
592 Reply(nullptr);
593 else
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000594 Reply(llvm::createStringError(llvm::inconvertibleErrorCode(),
595 "Not idle after a minute"));
Sam McCall422c8282018-11-26 16:00:11 +0000596}
597
Sam McCall2c30fbc2018-10-18 12:32:04 +0000598void ClangdLSPServer::onDocumentDidOpen(
599 const DidOpenTextDocumentParams &Params) {
Simon Marchi9569fd52018-03-16 14:30:42 +0000600 PathRef File = Params.textDocument.uri.file();
Ilya Biryukovb10ef472018-06-13 09:20:41 +0000601
Sam McCall2c30fbc2018-10-18 12:32:04 +0000602 const std::string &Contents = Params.textDocument.text;
Simon Marchi9569fd52018-03-16 14:30:42 +0000603
Simon Marchi98082622018-03-26 14:41:40 +0000604 DraftMgr.addDraft(File, Contents);
Ilya Biryukov652364b2018-09-26 05:48:29 +0000605 Server->addDocument(File, Contents, WantDiagnostics::Yes);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000606}
607
Sam McCall2c30fbc2018-10-18 12:32:04 +0000608void ClangdLSPServer::onDocumentDidChange(
609 const DidChangeTextDocumentParams &Params) {
Eric Liu51fed182018-02-22 18:40:39 +0000610 auto WantDiags = WantDiagnostics::Auto;
611 if (Params.wantDiagnostics.hasValue())
612 WantDiags = Params.wantDiagnostics.getValue() ? WantDiagnostics::Yes
613 : WantDiagnostics::No;
Simon Marchi9569fd52018-03-16 14:30:42 +0000614
615 PathRef File = Params.textDocument.uri.file();
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000616 llvm::Expected<std::string> Contents =
Simon Marchi98082622018-03-26 14:41:40 +0000617 DraftMgr.updateDraft(File, Params.contentChanges);
618 if (!Contents) {
619 // If this fails, we are most likely going to be not in sync anymore with
620 // the client. It is better to remove the draft and let further operations
621 // fail rather than giving wrong results.
622 DraftMgr.removeDraft(File);
Ilya Biryukov652364b2018-09-26 05:48:29 +0000623 Server->removeDocument(File);
Sam McCallbed58852018-07-11 10:35:11 +0000624 elog("Failed to update {0}: {1}", File, Contents.takeError());
Simon Marchi98082622018-03-26 14:41:40 +0000625 return;
626 }
Simon Marchi9569fd52018-03-16 14:30:42 +0000627
Ilya Biryukov652364b2018-09-26 05:48:29 +0000628 Server->addDocument(File, *Contents, WantDiags);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000629}
630
Sam McCall2c30fbc2018-10-18 12:32:04 +0000631void ClangdLSPServer::onFileEvent(const DidChangeWatchedFilesParams &Params) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000632 Server->onFileEvent(Params);
Marc-Andre Laperlebf114242017-10-02 18:00:37 +0000633}
634
Sam McCall2c30fbc2018-10-18 12:32:04 +0000635void ClangdLSPServer::onCommand(const ExecuteCommandParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000636 Callback<llvm::json::Value> Reply) {
Ilya Biryukov12864002019-08-16 12:46:41 +0000637 auto ApplyEdit = [this](WorkspaceEdit WE, std::string SuccessMessage,
638 decltype(Reply) Reply) {
Eric Liuc5105f92018-02-16 14:15:55 +0000639 ApplyWorkspaceEditParams Edit;
640 Edit.edit = std::move(WE);
Ilya Biryukov12864002019-08-16 12:46:41 +0000641 call<ApplyWorkspaceEditResponse>(
642 "workspace/applyEdit", std::move(Edit),
643 [Reply = std::move(Reply), SuccessMessage = std::move(SuccessMessage)](
644 llvm::Expected<ApplyWorkspaceEditResponse> Response) mutable {
645 if (!Response)
646 return Reply(Response.takeError());
647 if (!Response->applied) {
648 std::string Reason = Response->failureReason
649 ? *Response->failureReason
650 : "unknown reason";
651 return Reply(llvm::createStringError(
652 llvm::inconvertibleErrorCode(),
653 ("edits were not applied: " + Reason).c_str()));
654 }
655 return Reply(SuccessMessage);
656 });
Eric Liuc5105f92018-02-16 14:15:55 +0000657 };
Ilya Biryukov12864002019-08-16 12:46:41 +0000658
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000659 if (Params.command == ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND &&
660 Params.workspaceEdit) {
661 // The flow for "apply-fix" :
662 // 1. We publish a diagnostic, including fixits
663 // 2. The user clicks on the diagnostic, the editor asks us for code actions
664 // 3. We send code actions, with the fixit embedded as context
665 // 4. The user selects the fixit, the editor asks us to apply it
666 // 5. We unwrap the changes and send them back to the editor
Haojian Wuf2516342019-08-05 12:48:09 +0000667 // 6. The editor applies the changes (applyEdit), and sends us a reply
668 // 7. We unwrap the reply and send a reply to the editor.
Ilya Biryukov12864002019-08-16 12:46:41 +0000669 ApplyEdit(*Params.workspaceEdit, "Fix applied.", std::move(Reply));
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000670 } else if (Params.command == ExecuteCommandParams::CLANGD_APPLY_TWEAK &&
671 Params.tweakArgs) {
672 auto Code = DraftMgr.getDraft(Params.tweakArgs->file.file());
673 if (!Code)
674 return Reply(llvm::createStringError(
675 llvm::inconvertibleErrorCode(),
676 "trying to apply a code action for a non-added file"));
677
Ilya Biryukov12864002019-08-16 12:46:41 +0000678 auto Action = [this, ApplyEdit, Reply = std::move(Reply),
679 File = Params.tweakArgs->file, Code = std::move(*Code)](
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000680 llvm::Expected<Tweak::Effect> R) mutable {
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000681 if (!R)
682 return Reply(R.takeError());
683
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000684 assert(R->ShowMessage ||
685 (!R->ApplyEdits.empty() && "tweak has no effect"));
Ilya Biryukov12864002019-08-16 12:46:41 +0000686
Sam McCall395fde72019-06-18 13:37:54 +0000687 if (R->ShowMessage) {
688 ShowMessageParams Msg;
689 Msg.message = *R->ShowMessage;
690 Msg.type = MessageType::Info;
691 notify("window/showMessage", Msg);
692 }
Ilya Biryukov12864002019-08-16 12:46:41 +0000693 // When no edit is specified, make sure we Reply().
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000694 if (R->ApplyEdits.empty())
695 return Reply("Tweak applied.");
696
697 if (auto Err = validateEdits(DraftMgr, *R))
698 return Reply(std::move(Err));
699
700 WorkspaceEdit WE;
701 WE.changes.emplace();
702 for (const auto &It : R->ApplyEdits) {
703 (*WE.changes)[URI::create(It.first()).toString()] =
704 It.second.asTextEdits();
705 }
706 // ApplyEdit will take care of calling Reply().
707 return ApplyEdit(std::move(WE), "Tweak applied.", std::move(Reply));
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000708 };
709 Server->applyTweak(Params.tweakArgs->file.file(),
710 Params.tweakArgs->selection, Params.tweakArgs->tweakID,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000711 std::move(Action));
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000712 } else {
713 // We should not get here because ExecuteCommandParams would not have
714 // parsed in the first place and this handler should not be called. But if
715 // more commands are added, this will be here has a safe guard.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000716 Reply(llvm::make_error<LSPError>(
717 llvm::formatv("Unsupported command \"{0}\".", Params.command).str(),
Sam McCall2c30fbc2018-10-18 12:32:04 +0000718 ErrorCode::InvalidParams));
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000719 }
720}
721
Sam McCall2c30fbc2018-10-18 12:32:04 +0000722void ClangdLSPServer::onWorkspaceSymbol(
723 const WorkspaceSymbolParams &Params,
724 Callback<std::vector<SymbolInformation>> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000725 Server->workspaceSymbols(
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000726 Params.query, CCOpts.Limit,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000727 [Reply = std::move(Reply),
728 this](llvm::Expected<std::vector<SymbolInformation>> Items) mutable {
729 if (!Items)
730 return Reply(Items.takeError());
731 for (auto &Sym : *Items)
732 Sym.kind = adjustKindToCapability(Sym.kind, SupportedSymbolKinds);
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000733
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000734 Reply(std::move(*Items));
735 });
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000736}
737
Haojian Wuf429ab62019-07-24 07:49:23 +0000738void ClangdLSPServer::onPrepareRename(const TextDocumentPositionParams &Params,
739 Callback<llvm::Optional<Range>> Reply) {
740 Server->prepareRename(Params.textDocument.uri.file(), Params.position,
741 std::move(Reply));
742}
743
Sam McCall2c30fbc2018-10-18 12:32:04 +0000744void ClangdLSPServer::onRename(const RenameParams &Params,
745 Callback<WorkspaceEdit> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000746 Path File = Params.textDocument.uri.file();
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000747 llvm::Optional<std::string> Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000748 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000749 return Reply(llvm::make_error<LSPError>(
750 "onRename called for non-added file", ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000751
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000752 Server->rename(File, Params.position, Params.newName, /*WantFormat=*/true,
753 [File, Code, Params, Reply = std::move(Reply)](
754 llvm::Expected<std::vector<TextEdit>> Edits) mutable {
755 if (!Edits)
756 return Reply(Edits.takeError());
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000757
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000758 WorkspaceEdit WE;
759 WE.changes = {{Params.textDocument.uri.uri(), *Edits}};
760 Reply(WE);
761 });
Haojian Wu345099c2017-11-09 11:30:04 +0000762}
763
Sam McCall2c30fbc2018-10-18 12:32:04 +0000764void ClangdLSPServer::onDocumentDidClose(
765 const DidCloseTextDocumentParams &Params) {
Simon Marchi9569fd52018-03-16 14:30:42 +0000766 PathRef File = Params.textDocument.uri.file();
767 DraftMgr.removeDraft(File);
Ilya Biryukov652364b2018-09-26 05:48:29 +0000768 Server->removeDocument(File);
Ilya Biryukov49c10712019-03-25 10:15:11 +0000769
770 {
771 std::lock_guard<std::mutex> Lock(FixItsMutex);
772 FixItsMap.erase(File);
773 }
Johan Vikstromc2653ef22019-08-01 08:08:44 +0000774 {
775 std::lock_guard<std::mutex> HLock(HighlightingsMutex);
776 FileToHighlightings.erase(File);
777 }
Ilya Biryukov49c10712019-03-25 10:15:11 +0000778 // clangd will not send updates for this file anymore, so we empty out the
779 // list of diagnostics shown on the client (e.g. in the "Problems" pane of
780 // VSCode). Note that this cannot race with actual diagnostics responses
781 // because removeDocument() guarantees no diagnostic callbacks will be
782 // executed after it returns.
783 publishDiagnostics(URIForFile::canonicalize(File, /*TUPath=*/File), {});
Ilya Biryukovafb55542017-05-16 14:40:30 +0000784}
785
Sam McCall4db732a2017-09-30 10:08:52 +0000786void ClangdLSPServer::onDocumentOnTypeFormatting(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000787 const DocumentOnTypeFormattingParams &Params,
788 Callback<std::vector<TextEdit>> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000789 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000790 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000791 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000792 return Reply(llvm::make_error<LSPError>(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000793 "onDocumentOnTypeFormatting called for non-added file",
794 ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000795
Sam McCall25c62572019-06-10 14:26:21 +0000796 Reply(Server->formatOnType(*Code, File, Params.position, Params.ch));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000797}
798
Sam McCall4db732a2017-09-30 10:08:52 +0000799void ClangdLSPServer::onDocumentRangeFormatting(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000800 const DocumentRangeFormattingParams &Params,
801 Callback<std::vector<TextEdit>> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000802 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000803 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000804 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000805 return Reply(llvm::make_error<LSPError>(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000806 "onDocumentRangeFormatting called for non-added file",
807 ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000808
Ilya Biryukov652364b2018-09-26 05:48:29 +0000809 auto ReplacementsOrError = Server->formatRange(*Code, File, Params.range);
Raoul Wols212bcf82017-12-12 20:25:06 +0000810 if (ReplacementsOrError)
Sam McCall2c30fbc2018-10-18 12:32:04 +0000811 Reply(replacementsToEdits(*Code, ReplacementsOrError.get()));
Raoul Wols212bcf82017-12-12 20:25:06 +0000812 else
Sam McCall2c30fbc2018-10-18 12:32:04 +0000813 Reply(ReplacementsOrError.takeError());
Ilya Biryukovafb55542017-05-16 14:40:30 +0000814}
815
Sam McCall2c30fbc2018-10-18 12:32:04 +0000816void ClangdLSPServer::onDocumentFormatting(
817 const DocumentFormattingParams &Params,
818 Callback<std::vector<TextEdit>> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000819 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000820 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000821 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000822 return Reply(llvm::make_error<LSPError>(
823 "onDocumentFormatting called for non-added file",
824 ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000825
Ilya Biryukov652364b2018-09-26 05:48:29 +0000826 auto ReplacementsOrError = Server->formatFile(*Code, File);
Raoul Wols212bcf82017-12-12 20:25:06 +0000827 if (ReplacementsOrError)
Sam McCall2c30fbc2018-10-18 12:32:04 +0000828 Reply(replacementsToEdits(*Code, ReplacementsOrError.get()));
Raoul Wols212bcf82017-12-12 20:25:06 +0000829 else
Sam McCall2c30fbc2018-10-18 12:32:04 +0000830 Reply(ReplacementsOrError.takeError());
Sam McCall4db732a2017-09-30 10:08:52 +0000831}
832
Ilya Biryukov19d75602018-11-23 15:21:19 +0000833/// The functions constructs a flattened view of the DocumentSymbol hierarchy.
834/// Used by the clients that do not support the hierarchical view.
835static std::vector<SymbolInformation>
836flattenSymbolHierarchy(llvm::ArrayRef<DocumentSymbol> Symbols,
837 const URIForFile &FileURI) {
838
839 std::vector<SymbolInformation> Results;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000840 std::function<void(const DocumentSymbol &, llvm::StringRef)> Process =
841 [&](const DocumentSymbol &S, llvm::Optional<llvm::StringRef> ParentName) {
Ilya Biryukov19d75602018-11-23 15:21:19 +0000842 SymbolInformation SI;
843 SI.containerName = ParentName ? "" : *ParentName;
844 SI.name = S.name;
845 SI.kind = S.kind;
846 SI.location.range = S.range;
847 SI.location.uri = FileURI;
848
849 Results.push_back(std::move(SI));
850 std::string FullName =
851 !ParentName ? S.name : (ParentName->str() + "::" + S.name);
852 for (auto &C : S.children)
853 Process(C, /*ParentName=*/FullName);
854 };
855 for (auto &S : Symbols)
856 Process(S, /*ParentName=*/"");
857 return Results;
858}
859
860void ClangdLSPServer::onDocumentSymbol(const DocumentSymbolParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000861 Callback<llvm::json::Value> Reply) {
Ilya Biryukov19d75602018-11-23 15:21:19 +0000862 URIForFile FileURI = Params.textDocument.uri;
Ilya Biryukov652364b2018-09-26 05:48:29 +0000863 Server->documentSymbols(
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000864 Params.textDocument.uri.file(),
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000865 [this, FileURI, Reply = std::move(Reply)](
866 llvm::Expected<std::vector<DocumentSymbol>> Items) mutable {
867 if (!Items)
868 return Reply(Items.takeError());
869 adjustSymbolKinds(*Items, SupportedSymbolKinds);
870 if (SupportsHierarchicalDocumentSymbol)
871 return Reply(std::move(*Items));
872 else
873 return Reply(flattenSymbolHierarchy(*Items, FileURI));
874 });
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000875}
876
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000877static llvm::Optional<Command> asCommand(const CodeAction &Action) {
Sam McCall20841d42018-10-16 16:29:41 +0000878 Command Cmd;
879 if (Action.command && Action.edit)
Sam McCallc008af62018-10-20 15:30:37 +0000880 return None; // Not representable. (We never emit these anyway).
Sam McCall20841d42018-10-16 16:29:41 +0000881 if (Action.command) {
882 Cmd = *Action.command;
883 } else if (Action.edit) {
884 Cmd.command = Command::CLANGD_APPLY_FIX_COMMAND;
885 Cmd.workspaceEdit = *Action.edit;
886 } else {
Sam McCallc008af62018-10-20 15:30:37 +0000887 return None;
Sam McCall20841d42018-10-16 16:29:41 +0000888 }
889 Cmd.title = Action.title;
890 if (Action.kind && *Action.kind == CodeAction::QUICKFIX_KIND)
891 Cmd.title = "Apply fix: " + Cmd.title;
892 return Cmd;
893}
894
Sam McCall2c30fbc2018-10-18 12:32:04 +0000895void ClangdLSPServer::onCodeAction(const CodeActionParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000896 Callback<llvm::json::Value> Reply) {
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000897 URIForFile File = Params.textDocument.uri;
898 auto Code = DraftMgr.getDraft(File.file());
Sam McCall2c30fbc2018-10-18 12:32:04 +0000899 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000900 return Reply(llvm::make_error<LSPError>(
901 "onCodeAction called for non-added file", ErrorCode::InvalidParams));
Sam McCall20841d42018-10-16 16:29:41 +0000902 // We provide a code action for Fixes on the specified diagnostics.
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000903 std::vector<CodeAction> FixIts;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000904 for (const Diagnostic &D : Params.context.diagnostics) {
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000905 for (auto &F : getFixes(File.file(), D)) {
906 FixIts.push_back(toCodeAction(F, Params.textDocument.uri));
907 FixIts.back().diagnostics = {D};
Sam McCalldd0566b2017-11-06 15:40:30 +0000908 }
Ilya Biryukovafb55542017-05-16 14:40:30 +0000909 }
Sam McCall20841d42018-10-16 16:29:41 +0000910
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000911 // Now enumerate the semantic code actions.
912 auto ConsumeActions =
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000913 [Reply = std::move(Reply), File, Code = std::move(*Code),
914 Selection = Params.range, FixIts = std::move(FixIts), this](
915 llvm::Expected<std::vector<ClangdServer::TweakRef>> Tweaks) mutable {
Ilya Biryukovc6ed7782019-01-30 14:24:17 +0000916 if (!Tweaks)
917 return Reply(Tweaks.takeError());
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000918
919 std::vector<CodeAction> Actions = std::move(FixIts);
920 Actions.reserve(Actions.size() + Tweaks->size());
921 for (const auto &T : *Tweaks)
922 Actions.push_back(toCodeAction(T, File, Selection));
923
924 if (SupportsCodeAction)
925 return Reply(llvm::json::Array(Actions));
926 std::vector<Command> Commands;
927 for (const auto &Action : Actions) {
928 if (auto Command = asCommand(Action))
929 Commands.push_back(std::move(*Command));
930 }
931 return Reply(llvm::json::Array(Commands));
932 };
933
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000934 Server->enumerateTweaks(File.file(), Params.range, std::move(ConsumeActions));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000935}
936
Ilya Biryukovb0826bd2019-01-03 13:37:12 +0000937void ClangdLSPServer::onCompletion(const CompletionParams &Params,
Sam McCall2c30fbc2018-10-18 12:32:04 +0000938 Callback<CompletionList> Reply) {
Ilya Biryukova7a11472019-06-07 16:24:38 +0000939 if (!shouldRunCompletion(Params)) {
940 // Clients sometimes auto-trigger completions in undesired places (e.g.
941 // 'a >^ '), we return empty results in those cases.
942 vlog("ignored auto-triggered completion, preceding char did not match");
943 return Reply(CompletionList());
944 }
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000945 Server->codeComplete(Params.textDocument.uri.file(), Params.position, CCOpts,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000946 [Reply = std::move(Reply),
947 this](llvm::Expected<CodeCompleteResult> List) mutable {
948 if (!List)
949 return Reply(List.takeError());
950 CompletionList LSPList;
951 LSPList.isIncomplete = List->HasMore;
952 for (const auto &R : List->Completions) {
953 CompletionItem C = R.render(CCOpts);
954 C.kind = adjustKindToCapability(
955 C.kind, SupportedCompletionItemKinds);
956 LSPList.items.push_back(std::move(C));
957 }
958 return Reply(std::move(LSPList));
959 });
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000960}
961
Sam McCall2c30fbc2018-10-18 12:32:04 +0000962void ClangdLSPServer::onSignatureHelp(const TextDocumentPositionParams &Params,
963 Callback<SignatureHelp> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000964 Server->signatureHelp(Params.textDocument.uri.file(), Params.position,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000965 [Reply = std::move(Reply), this](
966 llvm::Expected<SignatureHelp> Signature) mutable {
967 if (!Signature)
968 return Reply(Signature.takeError());
969 if (SupportsOffsetsInSignatureHelp)
970 return Reply(std::move(*Signature));
971 // Strip out the offsets from signature help for
972 // clients that only support string labels.
973 for (auto &SigInfo : Signature->signatures) {
974 for (auto &Param : SigInfo.parameters)
975 Param.labelOffsets.reset();
976 }
977 return Reply(std::move(*Signature));
978 });
Ilya Biryukov652364b2018-09-26 05:48:29 +0000979}
980
Sam McCall0dbab7f2019-02-02 05:56:00 +0000981// Go to definition has a toggle function: if def and decl are distinct, then
982// the first press gives you the def, the second gives you the matching def.
983// getToggle() returns the counterpart location that under the cursor.
984//
985// We return the toggled location alone (ignoring other symbols) to encourage
986// editors to "bounce" quickly between locations, without showing a menu.
987static Location *getToggle(const TextDocumentPositionParams &Point,
988 LocatedSymbol &Sym) {
989 // Toggle only makes sense with two distinct locations.
990 if (!Sym.Definition || *Sym.Definition == Sym.PreferredDeclaration)
991 return nullptr;
992 if (Sym.Definition->uri.file() == Point.textDocument.uri.file() &&
993 Sym.Definition->range.contains(Point.position))
994 return &Sym.PreferredDeclaration;
995 if (Sym.PreferredDeclaration.uri.file() == Point.textDocument.uri.file() &&
996 Sym.PreferredDeclaration.range.contains(Point.position))
997 return &*Sym.Definition;
998 return nullptr;
999}
1000
Sam McCall2c30fbc2018-10-18 12:32:04 +00001001void ClangdLSPServer::onGoToDefinition(const TextDocumentPositionParams &Params,
1002 Callback<std::vector<Location>> Reply) {
Sam McCall866ba2c2019-02-01 11:26:13 +00001003 Server->locateSymbolAt(
1004 Params.textDocument.uri.file(), Params.position,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001005 [Params, Reply = std::move(Reply)](
1006 llvm::Expected<std::vector<LocatedSymbol>> Symbols) mutable {
1007 if (!Symbols)
1008 return Reply(Symbols.takeError());
1009 std::vector<Location> Defs;
1010 for (auto &S : *Symbols) {
1011 if (Location *Toggle = getToggle(Params, S))
1012 return Reply(std::vector<Location>{std::move(*Toggle)});
1013 Defs.push_back(S.Definition.getValueOr(S.PreferredDeclaration));
1014 }
1015 Reply(std::move(Defs));
1016 });
Sam McCall866ba2c2019-02-01 11:26:13 +00001017}
1018
1019void ClangdLSPServer::onGoToDeclaration(
1020 const TextDocumentPositionParams &Params,
1021 Callback<std::vector<Location>> Reply) {
1022 Server->locateSymbolAt(
1023 Params.textDocument.uri.file(), Params.position,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001024 [Params, Reply = std::move(Reply)](
1025 llvm::Expected<std::vector<LocatedSymbol>> Symbols) mutable {
1026 if (!Symbols)
1027 return Reply(Symbols.takeError());
1028 std::vector<Location> Decls;
1029 for (auto &S : *Symbols) {
1030 if (Location *Toggle = getToggle(Params, S))
1031 return Reply(std::vector<Location>{std::move(*Toggle)});
1032 Decls.push_back(std::move(S.PreferredDeclaration));
1033 }
1034 Reply(std::move(Decls));
1035 });
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +00001036}
1037
Sam McCall111fe842019-05-07 07:55:35 +00001038void ClangdLSPServer::onSwitchSourceHeader(
1039 const TextDocumentIdentifier &Params,
Sam McCallb9ec3e92019-05-07 08:30:32 +00001040 Callback<llvm::Optional<URIForFile>> Reply) {
Sam McCall111fe842019-05-07 07:55:35 +00001041 if (auto Result = Server->switchSourceHeader(Params.uri.file()))
Sam McCallb9ec3e92019-05-07 08:30:32 +00001042 Reply(URIForFile::canonicalize(*Result, Params.uri.file()));
Sam McCall111fe842019-05-07 07:55:35 +00001043 else
1044 Reply(llvm::None);
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +00001045}
1046
Sam McCall2c30fbc2018-10-18 12:32:04 +00001047void ClangdLSPServer::onDocumentHighlight(
1048 const TextDocumentPositionParams &Params,
1049 Callback<std::vector<DocumentHighlight>> Reply) {
1050 Server->findDocumentHighlights(Params.textDocument.uri.file(),
1051 Params.position, std::move(Reply));
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +00001052}
1053
Sam McCall2c30fbc2018-10-18 12:32:04 +00001054void ClangdLSPServer::onHover(const TextDocumentPositionParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001055 Callback<llvm::Optional<Hover>> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +00001056 Server->findHover(Params.textDocument.uri.file(), Params.position,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001057 [Reply = std::move(Reply), this](
1058 llvm::Expected<llvm::Optional<HoverInfo>> H) mutable {
1059 if (!H)
1060 return Reply(H.takeError());
1061 if (!*H)
1062 return Reply(llvm::None);
Ilya Biryukovf9169d02019-05-29 10:01:00 +00001063
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001064 Hover R;
1065 R.contents.kind = HoverContentFormat;
1066 R.range = (*H)->SymRange;
1067 switch (HoverContentFormat) {
1068 case MarkupKind::PlainText:
1069 R.contents.value = (*H)->present().renderAsPlainText();
1070 return Reply(std::move(R));
1071 case MarkupKind::Markdown:
1072 R.contents.value = (*H)->present().renderAsMarkdown();
1073 return Reply(std::move(R));
1074 };
1075 llvm_unreachable("unhandled MarkupKind");
1076 });
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +00001077}
1078
Kadir Cetinkaya86658022019-03-19 09:27:04 +00001079void ClangdLSPServer::onTypeHierarchy(
1080 const TypeHierarchyParams &Params,
1081 Callback<Optional<TypeHierarchyItem>> Reply) {
1082 Server->typeHierarchy(Params.textDocument.uri.file(), Params.position,
1083 Params.resolve, Params.direction, std::move(Reply));
1084}
1085
Nathan Ridge087b0442019-07-13 03:24:48 +00001086void ClangdLSPServer::onResolveTypeHierarchy(
1087 const ResolveTypeHierarchyItemParams &Params,
1088 Callback<Optional<TypeHierarchyItem>> Reply) {
1089 Server->resolveTypeHierarchy(Params.item, Params.resolve, Params.direction,
1090 std::move(Reply));
1091}
1092
Simon Marchi88016782018-08-01 11:28:49 +00001093void ClangdLSPServer::applyConfiguration(
Sam McCallbc904612018-10-25 04:22:52 +00001094 const ConfigurationSettings &Settings) {
Simon Marchiabeed662018-10-16 15:55:03 +00001095 // Per-file update to the compilation database.
Sam McCallbc904612018-10-25 04:22:52 +00001096 bool ShouldReparseOpenFiles = false;
1097 for (auto &Entry : Settings.compilationDatabaseChanges) {
1098 /// The opened files need to be reparsed only when some existing
1099 /// entries are changed.
1100 PathRef File = Entry.first;
Sam McCallc55d09a2018-11-02 13:09:36 +00001101 auto Old = CDB->getCompileCommand(File);
1102 auto New =
1103 tooling::CompileCommand(std::move(Entry.second.workingDirectory), File,
1104 std::move(Entry.second.compilationCommand),
1105 /*Output=*/"");
Sam McCall6980edb2018-11-02 14:07:51 +00001106 if (Old != New) {
Sam McCallc55d09a2018-11-02 13:09:36 +00001107 CDB->setCompileCommand(File, std::move(New));
Sam McCall6980edb2018-11-02 14:07:51 +00001108 ShouldReparseOpenFiles = true;
1109 }
Alex Lorenzf8087862018-08-01 17:39:29 +00001110 }
Sam McCallbc904612018-10-25 04:22:52 +00001111 if (ShouldReparseOpenFiles)
1112 reparseOpenedFiles();
Simon Marchi5178f922018-02-22 14:00:39 +00001113}
1114
Johan Vikstroma848dab2019-07-04 07:53:12 +00001115void ClangdLSPServer::publishSemanticHighlighting(
1116 SemanticHighlightingParams Params) {
1117 notify("textDocument/semanticHighlighting", Params);
1118}
1119
Ilya Biryukov49c10712019-03-25 10:15:11 +00001120void ClangdLSPServer::publishDiagnostics(
1121 const URIForFile &File, std::vector<clangd::Diagnostic> Diagnostics) {
1122 // Publish diagnostics.
1123 notify("textDocument/publishDiagnostics",
1124 llvm::json::Object{
1125 {"uri", File},
1126 {"diagnostics", std::move(Diagnostics)},
1127 });
1128}
1129
Simon Marchi88016782018-08-01 11:28:49 +00001130// FIXME: This function needs to be properly tested.
1131void ClangdLSPServer::onChangeConfiguration(
Sam McCall2c30fbc2018-10-18 12:32:04 +00001132 const DidChangeConfigurationParams &Params) {
Simon Marchi88016782018-08-01 11:28:49 +00001133 applyConfiguration(Params.settings);
1134}
1135
Sam McCall2c30fbc2018-10-18 12:32:04 +00001136void ClangdLSPServer::onReference(const ReferenceParams &Params,
1137 Callback<std::vector<Location>> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +00001138 Server->findReferences(Params.textDocument.uri.file(), Params.position,
Haojian Wuc34f0222019-01-14 18:11:09 +00001139 CCOpts.Limit, std::move(Reply));
Sam McCall1ad142f2018-09-05 11:53:07 +00001140}
1141
Jan Korousb4067012018-11-27 16:40:46 +00001142void ClangdLSPServer::onSymbolInfo(const TextDocumentPositionParams &Params,
1143 Callback<std::vector<SymbolDetails>> Reply) {
1144 Server->symbolInfo(Params.textDocument.uri.file(), Params.position,
1145 std::move(Reply));
1146}
1147
Utkarsh Saxena55925da2019-09-24 13:38:33 +00001148void ClangdLSPServer::onSelectionRange(
1149 const SelectionRangeParams &Params,
1150 Callback<std::vector<SelectionRange>> Reply) {
1151 if (Params.positions.size() != 1) {
1152 elog("{0} positions provided to SelectionRange. Supports exactly one "
1153 "position.",
1154 Params.positions.size());
1155 return Reply(llvm::make_error<LSPError>(
1156 "SelectionRange supports exactly one position",
1157 ErrorCode::InvalidRequest));
1158 }
1159 Server->semanticRanges(
1160 Params.textDocument.uri.file(), Params.positions[0],
1161 [Reply = std::move(Reply)](
1162 llvm::Expected<std::vector<Range>> Ranges) mutable {
1163 if (!Ranges) {
1164 return Reply(Ranges.takeError());
1165 }
1166 std::vector<SelectionRange> Result;
1167 Result.emplace_back(render(std::move(*Ranges)));
1168 return Reply(std::move(Result));
1169 });
1170}
1171
Sam McCalla69698f2019-03-27 17:47:49 +00001172ClangdLSPServer::ClangdLSPServer(
1173 class Transport &Transp, const FileSystemProvider &FSProvider,
1174 const clangd::CodeCompleteOptions &CCOpts,
1175 llvm::Optional<Path> CompileCommandsDir, bool UseDirBasedCDB,
1176 llvm::Optional<OffsetEncoding> ForcedOffsetEncoding,
1177 const ClangdServer::Options &Opts)
Haojian Wu1ca0c582019-01-22 09:39:05 +00001178 : Transp(Transp), MsgHandler(new MessageHandler(*this)),
1179 FSProvider(FSProvider), CCOpts(CCOpts),
Sam McCalld1c9d112018-10-23 14:19:54 +00001180 SupportedSymbolKinds(defaultSymbolKinds()),
Kadir Cetinkaya133d46f2018-09-27 17:13:07 +00001181 SupportedCompletionItemKinds(defaultCompletionItemKinds()),
Sam McCallc55d09a2018-11-02 13:09:36 +00001182 UseDirBasedCDB(UseDirBasedCDB),
Sam McCalla69698f2019-03-27 17:47:49 +00001183 CompileCommandsDir(std::move(CompileCommandsDir)), ClangdServerOpts(Opts),
1184 NegotiatedOffsetEncoding(ForcedOffsetEncoding) {
Sam McCall2c30fbc2018-10-18 12:32:04 +00001185 // clang-format off
1186 MsgHandler->bind("initialize", &ClangdLSPServer::onInitialize);
1187 MsgHandler->bind("shutdown", &ClangdLSPServer::onShutdown);
Sam McCall422c8282018-11-26 16:00:11 +00001188 MsgHandler->bind("sync", &ClangdLSPServer::onSync);
Sam McCall2c30fbc2018-10-18 12:32:04 +00001189 MsgHandler->bind("textDocument/rangeFormatting", &ClangdLSPServer::onDocumentRangeFormatting);
1190 MsgHandler->bind("textDocument/onTypeFormatting", &ClangdLSPServer::onDocumentOnTypeFormatting);
1191 MsgHandler->bind("textDocument/formatting", &ClangdLSPServer::onDocumentFormatting);
1192 MsgHandler->bind("textDocument/codeAction", &ClangdLSPServer::onCodeAction);
1193 MsgHandler->bind("textDocument/completion", &ClangdLSPServer::onCompletion);
1194 MsgHandler->bind("textDocument/signatureHelp", &ClangdLSPServer::onSignatureHelp);
1195 MsgHandler->bind("textDocument/definition", &ClangdLSPServer::onGoToDefinition);
Sam McCall866ba2c2019-02-01 11:26:13 +00001196 MsgHandler->bind("textDocument/declaration", &ClangdLSPServer::onGoToDeclaration);
Sam McCall2c30fbc2018-10-18 12:32:04 +00001197 MsgHandler->bind("textDocument/references", &ClangdLSPServer::onReference);
1198 MsgHandler->bind("textDocument/switchSourceHeader", &ClangdLSPServer::onSwitchSourceHeader);
Haojian Wuf429ab62019-07-24 07:49:23 +00001199 MsgHandler->bind("textDocument/prepareRename", &ClangdLSPServer::onPrepareRename);
Sam McCall2c30fbc2018-10-18 12:32:04 +00001200 MsgHandler->bind("textDocument/rename", &ClangdLSPServer::onRename);
1201 MsgHandler->bind("textDocument/hover", &ClangdLSPServer::onHover);
1202 MsgHandler->bind("textDocument/documentSymbol", &ClangdLSPServer::onDocumentSymbol);
1203 MsgHandler->bind("workspace/executeCommand", &ClangdLSPServer::onCommand);
1204 MsgHandler->bind("textDocument/documentHighlight", &ClangdLSPServer::onDocumentHighlight);
1205 MsgHandler->bind("workspace/symbol", &ClangdLSPServer::onWorkspaceSymbol);
1206 MsgHandler->bind("textDocument/didOpen", &ClangdLSPServer::onDocumentDidOpen);
1207 MsgHandler->bind("textDocument/didClose", &ClangdLSPServer::onDocumentDidClose);
1208 MsgHandler->bind("textDocument/didChange", &ClangdLSPServer::onDocumentDidChange);
1209 MsgHandler->bind("workspace/didChangeWatchedFiles", &ClangdLSPServer::onFileEvent);
1210 MsgHandler->bind("workspace/didChangeConfiguration", &ClangdLSPServer::onChangeConfiguration);
Jan Korousb4067012018-11-27 16:40:46 +00001211 MsgHandler->bind("textDocument/symbolInfo", &ClangdLSPServer::onSymbolInfo);
Kadir Cetinkaya86658022019-03-19 09:27:04 +00001212 MsgHandler->bind("textDocument/typeHierarchy", &ClangdLSPServer::onTypeHierarchy);
Nathan Ridge087b0442019-07-13 03:24:48 +00001213 MsgHandler->bind("typeHierarchy/resolve", &ClangdLSPServer::onResolveTypeHierarchy);
Utkarsh Saxena55925da2019-09-24 13:38:33 +00001214 MsgHandler->bind("textDocument/selectionRange", &ClangdLSPServer::onSelectionRange);
Sam McCall2c30fbc2018-10-18 12:32:04 +00001215 // clang-format on
1216}
1217
Haojian Wuf2516342019-08-05 12:48:09 +00001218ClangdLSPServer::~ClangdLSPServer() { IsBeingDestroyed = true; }
Ilya Biryukov38d79772017-05-16 09:38:59 +00001219
Sam McCalldc8f3cf2018-10-17 07:32:05 +00001220bool ClangdLSPServer::run() {
Ilya Biryukovafb55542017-05-16 14:40:30 +00001221 // Run the Language Server loop.
Sam McCalldc8f3cf2018-10-17 07:32:05 +00001222 bool CleanExit = true;
Sam McCall2c30fbc2018-10-18 12:32:04 +00001223 if (auto Err = Transp.loop(*MsgHandler)) {
Sam McCalldc8f3cf2018-10-17 07:32:05 +00001224 elog("Transport error: {0}", std::move(Err));
1225 CleanExit = false;
1226 }
Ilya Biryukovafb55542017-05-16 14:40:30 +00001227
Ilya Biryukov652364b2018-09-26 05:48:29 +00001228 // Destroy ClangdServer to ensure all worker threads finish.
1229 Server.reset();
Sam McCalldc8f3cf2018-10-17 07:32:05 +00001230 return CleanExit && ShutdownRequestReceived;
Ilya Biryukov38d79772017-05-16 09:38:59 +00001231}
1232
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001233std::vector<Fix> ClangdLSPServer::getFixes(llvm::StringRef File,
Ilya Biryukov71028b82018-03-12 15:28:22 +00001234 const clangd::Diagnostic &D) {
Ilya Biryukov38d79772017-05-16 09:38:59 +00001235 std::lock_guard<std::mutex> Lock(FixItsMutex);
1236 auto DiagToFixItsIter = FixItsMap.find(File);
1237 if (DiagToFixItsIter == FixItsMap.end())
1238 return {};
1239
1240 const auto &DiagToFixItsMap = DiagToFixItsIter->second;
1241 auto FixItsIter = DiagToFixItsMap.find(D);
1242 if (FixItsIter == DiagToFixItsMap.end())
1243 return {};
1244
1245 return FixItsIter->second;
1246}
1247
Ilya Biryukovb0826bd2019-01-03 13:37:12 +00001248bool ClangdLSPServer::shouldRunCompletion(
1249 const CompletionParams &Params) const {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001250 llvm::StringRef Trigger = Params.context.triggerCharacter;
Ilya Biryukovb0826bd2019-01-03 13:37:12 +00001251 if (Params.context.triggerKind != CompletionTriggerKind::TriggerCharacter ||
1252 (Trigger != ">" && Trigger != ":"))
1253 return true;
1254
1255 auto Code = DraftMgr.getDraft(Params.textDocument.uri.file());
1256 if (!Code)
1257 return true; // completion code will log the error for untracked doc.
1258
1259 // A completion request is sent when the user types '>' or ':', but we only
1260 // want to trigger on '->' and '::'. We check the preceeding character to make
1261 // sure it matches what we expected.
1262 // Running the lexer here would be more robust (e.g. we can detect comments
1263 // and avoid triggering completion there), but we choose to err on the side
1264 // of simplicity here.
1265 auto Offset = positionToOffset(*Code, Params.position,
1266 /*AllowColumnsBeyondLineLength=*/false);
1267 if (!Offset) {
1268 vlog("could not convert position '{0}' to offset for file '{1}'",
1269 Params.position, Params.textDocument.uri.file());
1270 return true;
1271 }
1272 if (*Offset < 2)
1273 return false;
1274
1275 if (Trigger == ">")
1276 return (*Code)[*Offset - 2] == '-'; // trigger only on '->'.
1277 if (Trigger == ":")
1278 return (*Code)[*Offset - 2] == ':'; // trigger only on '::'.
1279 assert(false && "unhandled trigger character");
1280 return true;
1281}
1282
Johan Vikstroma848dab2019-07-04 07:53:12 +00001283void ClangdLSPServer::onHighlightingsReady(
Haojian Wu0a6000f2019-08-26 08:38:45 +00001284 PathRef File, std::vector<HighlightingToken> Highlightings) {
Johan Vikstromc2653ef22019-08-01 08:08:44 +00001285 std::vector<HighlightingToken> Old;
1286 std::vector<HighlightingToken> HighlightingsCopy = Highlightings;
1287 {
1288 std::lock_guard<std::mutex> Lock(HighlightingsMutex);
1289 Old = std::move(FileToHighlightings[File]);
1290 FileToHighlightings[File] = std::move(HighlightingsCopy);
1291 }
1292 // LSP allows us to send incremental edits of highlightings. Also need to diff
1293 // to remove highlightings from tokens that should no longer have them.
Haojian Wu0a6000f2019-08-26 08:38:45 +00001294 std::vector<LineHighlightings> Diffed = diffHighlightings(Highlightings, Old);
Johan Vikstroma848dab2019-07-04 07:53:12 +00001295 publishSemanticHighlighting(
1296 {{URIForFile::canonicalize(File, /*TUPath=*/File)},
Johan Vikstromc2653ef22019-08-01 08:08:44 +00001297 toSemanticHighlightingInformation(Diffed)});
Johan Vikstroma848dab2019-07-04 07:53:12 +00001298}
1299
Sam McCalla7bb0cc2018-03-12 23:22:35 +00001300void ClangdLSPServer::onDiagnosticsReady(PathRef File,
1301 std::vector<Diag> Diagnostics) {
Eric Liu4d814a92018-11-28 10:30:42 +00001302 auto URI = URIForFile::canonicalize(File, /*TUPath=*/File);
Sam McCall16e70702018-10-24 07:59:38 +00001303 std::vector<Diagnostic> LSPDiagnostics;
Ilya Biryukov38d79772017-05-16 09:38:59 +00001304 DiagnosticToReplacementMap LocalFixIts; // Temporary storage
Sam McCalla7bb0cc2018-03-12 23:22:35 +00001305 for (auto &Diag : Diagnostics) {
Sam McCall16e70702018-10-24 07:59:38 +00001306 toLSPDiags(Diag, URI, DiagOpts,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001307 [&](clangd::Diagnostic Diag, llvm::ArrayRef<Fix> Fixes) {
Sam McCall16e70702018-10-24 07:59:38 +00001308 auto &FixItsForDiagnostic = LocalFixIts[Diag];
1309 llvm::copy(Fixes, std::back_inserter(FixItsForDiagnostic));
1310 LSPDiagnostics.push_back(std::move(Diag));
1311 });
Ilya Biryukov38d79772017-05-16 09:38:59 +00001312 }
1313
1314 // Cache FixIts
1315 {
Ilya Biryukov38d79772017-05-16 09:38:59 +00001316 std::lock_guard<std::mutex> Lock(FixItsMutex);
1317 FixItsMap[File] = LocalFixIts;
1318 }
1319
Ilya Biryukov49c10712019-03-25 10:15:11 +00001320 // Send a notification to the LSP client.
1321 publishDiagnostics(URI, std::move(LSPDiagnostics));
Ilya Biryukov38d79772017-05-16 09:38:59 +00001322}
Simon Marchi9569fd52018-03-16 14:30:42 +00001323
Haojian Wub6188492018-12-20 15:39:12 +00001324void ClangdLSPServer::onFileUpdated(PathRef File, const TUStatus &Status) {
1325 if (!SupportFileStatus)
1326 return;
1327 // FIXME: we don't emit "BuildingFile" and `RunningAction`, as these
1328 // two statuses are running faster in practice, which leads the UI constantly
1329 // changing, and doesn't provide much value. We may want to emit status at a
1330 // reasonable time interval (e.g. 0.5s).
1331 if (Status.Action.S == TUAction::BuildingFile ||
1332 Status.Action.S == TUAction::RunningAction)
1333 return;
1334 notify("textDocument/clangd.fileStatus", Status.render(File));
1335}
1336
Simon Marchi9569fd52018-03-16 14:30:42 +00001337void ClangdLSPServer::reparseOpenedFiles() {
1338 for (const Path &FilePath : DraftMgr.getActiveFiles())
Ilya Biryukov652364b2018-09-26 05:48:29 +00001339 Server->addDocument(FilePath, *DraftMgr.getDraft(FilePath),
1340 WantDiagnostics::Auto);
Simon Marchi9569fd52018-03-16 14:30:42 +00001341}
Alex Lorenzf8087862018-08-01 17:39:29 +00001342
Sam McCallc008af62018-10-20 15:30:37 +00001343} // namespace clangd
1344} // namespace clang