blob: 0930c80da06f649047570e8108ea12f44a173f43 [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"
Simon Marchi9569fd52018-03-16 14:30:42 +000025#include "llvm/Support/Errc.h"
Ilya Biryukovcce67a32019-01-29 14:17:36 +000026#include "llvm/Support/Error.h"
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +000027#include "llvm/Support/FormatVariadic.h"
Eric Liu5740ff52018-01-31 16:26:27 +000028#include "llvm/Support/Path.h"
Kadir Cetinkaya5b270932019-09-09 12:28:44 +000029#include "llvm/Support/SHA1.h"
Sam McCall2c30fbc2018-10-18 12:32:04 +000030#include "llvm/Support/ScopedPrinter.h"
Kadir Cetinkaya5b270932019-09-09 12:28:44 +000031#include <cstddef>
32#include <string>
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +000033
Sam McCallc008af62018-10-20 15:30:37 +000034namespace clang {
35namespace clangd {
Ilya Biryukovafb55542017-05-16 14:40:30 +000036namespace {
Ilya Biryukovcce67a32019-01-29 14:17:36 +000037/// Transforms a tweak into a code action that would apply it if executed.
38/// EXPECTS: T.prepare() was called and returned true.
39CodeAction toCodeAction(const ClangdServer::TweakRef &T, const URIForFile &File,
40 Range Selection) {
41 CodeAction CA;
42 CA.title = T.Title;
Sam McCall395fde72019-06-18 13:37:54 +000043 switch (T.Intent) {
44 case Tweak::Refactor:
45 CA.kind = CodeAction::REFACTOR_KIND;
46 break;
47 case Tweak::Info:
48 CA.kind = CodeAction::INFO_KIND;
49 break;
50 }
Ilya Biryukovcce67a32019-01-29 14:17:36 +000051 // This tweak may have an expensive second stage, we only run it if the user
52 // actually chooses it in the UI. We reply with a command that would run the
53 // corresponding tweak.
54 // FIXME: for some tweaks, computing the edits is cheap and we could send them
55 // directly.
56 CA.command.emplace();
57 CA.command->title = T.Title;
58 CA.command->command = Command::CLANGD_APPLY_TWEAK;
59 CA.command->tweakArgs.emplace();
60 CA.command->tweakArgs->file = File;
61 CA.command->tweakArgs->tweakID = T.ID;
62 CA.command->tweakArgs->selection = Selection;
63 return CA;
Simon Pilgrime9a136b2019-02-03 14:08:30 +000064}
Ilya Biryukovcce67a32019-01-29 14:17:36 +000065
Ilya Biryukov19d75602018-11-23 15:21:19 +000066void adjustSymbolKinds(llvm::MutableArrayRef<DocumentSymbol> Syms,
67 SymbolKindBitset Kinds) {
68 for (auto &S : Syms) {
69 S.kind = adjustKindToCapability(S.kind, Kinds);
70 adjustSymbolKinds(S.children, Kinds);
71 }
72}
73
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +000074SymbolKindBitset defaultSymbolKinds() {
75 SymbolKindBitset Defaults;
76 for (size_t I = SymbolKindMin; I <= static_cast<size_t>(SymbolKind::Array);
77 ++I)
78 Defaults.set(I);
79 return Defaults;
80}
81
Kadir Cetinkaya133d46f2018-09-27 17:13:07 +000082CompletionItemKindBitset defaultCompletionItemKinds() {
83 CompletionItemKindBitset Defaults;
84 for (size_t I = CompletionItemKindMin;
85 I <= static_cast<size_t>(CompletionItemKind::Reference); ++I)
86 Defaults.set(I);
87 return Defaults;
88}
89
Haojian Wu1ca2ee42019-07-04 12:27:21 +000090// Build a lookup table (HighlightingKind => {TextMate Scopes}), which is sent
91// to the LSP client.
92std::vector<std::vector<std::string>> buildHighlightScopeLookupTable() {
93 std::vector<std::vector<std::string>> LookupTable;
94 // HighlightingKind is using as the index.
Ilya Biryukov63d5d162019-09-09 08:57:17 +000095 for (int KindValue = 0; KindValue <= (int)HighlightingKind::LastKind;
Haojian Wu1ca2ee42019-07-04 12:27:21 +000096 ++KindValue)
97 LookupTable.push_back({toTextMateScope((HighlightingKind)(KindValue))});
98 return LookupTable;
99}
100
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000101// Makes sure edits in \p E are applicable to latest file contents reported by
102// editor. If not generates an error message containing information about files
103// that needs to be saved.
104llvm::Error validateEdits(const DraftStore &DraftMgr, const Tweak::Effect &E) {
105 size_t InvalidFileCount = 0;
106 llvm::StringRef LastInvalidFile;
107 for (const auto &It : E.ApplyEdits) {
108 if (auto Draft = DraftMgr.getDraft(It.first())) {
109 // If the file is open in user's editor, make sure the version we
110 // saw and current version are compatible as this is the text that
111 // will be replaced by editors.
112 if (!It.second.canApplyTo(*Draft)) {
113 ++InvalidFileCount;
114 LastInvalidFile = It.first();
115 }
116 }
117 }
118 if (!InvalidFileCount)
119 return llvm::Error::success();
120 if (InvalidFileCount == 1)
121 return llvm::createStringError(llvm::inconvertibleErrorCode(),
122 "File must be saved first: " +
123 LastInvalidFile);
124 return llvm::createStringError(
125 llvm::inconvertibleErrorCode(),
126 "Files must be saved first: " + LastInvalidFile + " (and " +
127 llvm::to_string(InvalidFileCount - 1) + " others)");
128}
129
Ilya Biryukovafb55542017-05-16 14:40:30 +0000130} // namespace
131
Sam McCall2c30fbc2018-10-18 12:32:04 +0000132// MessageHandler dispatches incoming LSP messages.
133// It handles cross-cutting concerns:
134// - serializes/deserializes protocol objects to JSON
135// - logging of inbound messages
136// - cancellation handling
137// - basic call tracing
Sam McCall3d0adbe2018-10-18 14:41:50 +0000138// MessageHandler ensures that initialize() is called before any other handler.
Sam McCall2c30fbc2018-10-18 12:32:04 +0000139class ClangdLSPServer::MessageHandler : public Transport::MessageHandler {
140public:
141 MessageHandler(ClangdLSPServer &Server) : Server(Server) {}
142
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000143 bool onNotify(llvm::StringRef Method, llvm::json::Value Params) override {
Sam McCalla69698f2019-03-27 17:47:49 +0000144 WithContext HandlerContext(handlerContext());
Sam McCall2c30fbc2018-10-18 12:32:04 +0000145 log("<-- {0}", Method);
146 if (Method == "exit")
147 return false;
Sam McCall3d0adbe2018-10-18 14:41:50 +0000148 if (!Server.Server)
149 elog("Notification {0} before initialization", Method);
150 else if (Method == "$/cancelRequest")
Sam McCall2c30fbc2018-10-18 12:32:04 +0000151 onCancel(std::move(Params));
152 else if (auto Handler = Notifications.lookup(Method))
153 Handler(std::move(Params));
154 else
155 log("unhandled notification {0}", Method);
156 return true;
157 }
158
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000159 bool onCall(llvm::StringRef Method, llvm::json::Value Params,
160 llvm::json::Value ID) override {
Sam McCalla69698f2019-03-27 17:47:49 +0000161 WithContext HandlerContext(handlerContext());
Sam McCalle2f3a732018-10-24 14:26:26 +0000162 // Calls can be canceled by the client. Add cancellation context.
163 WithContext WithCancel(cancelableRequestContext(ID));
164 trace::Span Tracer(Method);
165 SPAN_ATTACH(Tracer, "Params", Params);
166 ReplyOnce Reply(ID, Method, &Server, Tracer.Args);
Sam McCall2c30fbc2018-10-18 12:32:04 +0000167 log("<-- {0}({1})", Method, ID);
Sam McCall3d0adbe2018-10-18 14:41:50 +0000168 if (!Server.Server && Method != "initialize") {
169 elog("Call {0} before initialization.", Method);
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000170 Reply(llvm::make_error<LSPError>("server not initialized",
171 ErrorCode::ServerNotInitialized));
Sam McCall3d0adbe2018-10-18 14:41:50 +0000172 } else if (auto Handler = Calls.lookup(Method))
Sam McCalle2f3a732018-10-24 14:26:26 +0000173 Handler(std::move(Params), std::move(Reply));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000174 else
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000175 Reply(llvm::make_error<LSPError>("method not found",
176 ErrorCode::MethodNotFound));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000177 return true;
178 }
179
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000180 bool onReply(llvm::json::Value ID,
181 llvm::Expected<llvm::json::Value> Result) override {
Sam McCalla69698f2019-03-27 17:47:49 +0000182 WithContext HandlerContext(handlerContext());
Haojian Wuf2516342019-08-05 12:48:09 +0000183
184 Callback<llvm::json::Value> ReplyHandler = nullptr;
185 if (auto IntID = ID.getAsInteger()) {
186 std::lock_guard<std::mutex> Mutex(CallMutex);
187 // Find a corresponding callback for the request ID;
188 for (size_t Index = 0; Index < ReplyCallbacks.size(); ++Index) {
189 if (ReplyCallbacks[Index].first == *IntID) {
190 ReplyHandler = std::move(ReplyCallbacks[Index].second);
191 ReplyCallbacks.erase(ReplyCallbacks.begin() +
192 Index); // remove the entry
193 break;
194 }
195 }
196 }
197
198 if (!ReplyHandler) {
199 // No callback being found, use a default log callback.
200 ReplyHandler = [&ID](llvm::Expected<llvm::json::Value> Result) {
201 elog("received a reply with ID {0}, but there was no such call", ID);
202 if (!Result)
203 llvm::consumeError(Result.takeError());
204 };
205 }
206
207 // Log and run the reply handler.
208 if (Result) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000209 log("<-- reply({0})", ID);
Haojian Wuf2516342019-08-05 12:48:09 +0000210 ReplyHandler(std::move(Result));
211 } else {
212 auto Err = Result.takeError();
213 log("<-- reply({0}) error: {1}", ID, Err);
214 ReplyHandler(std::move(Err));
215 }
Sam McCall2c30fbc2018-10-18 12:32:04 +0000216 return true;
217 }
218
219 // Bind an LSP method name to a call.
Sam McCalle2f3a732018-10-24 14:26:26 +0000220 template <typename Param, typename Result>
Sam McCall2c30fbc2018-10-18 12:32:04 +0000221 void bind(const char *Method,
Sam McCalle2f3a732018-10-24 14:26:26 +0000222 void (ClangdLSPServer::*Handler)(const Param &, Callback<Result>)) {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000223 Calls[Method] = [Method, Handler, this](llvm::json::Value RawParams,
Sam McCalle2f3a732018-10-24 14:26:26 +0000224 ReplyOnce Reply) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000225 Param P;
Sam McCalle2f3a732018-10-24 14:26:26 +0000226 if (fromJSON(RawParams, P)) {
227 (Server.*Handler)(P, std::move(Reply));
228 } else {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000229 elog("Failed to decode {0} request.", Method);
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000230 Reply(llvm::make_error<LSPError>("failed to decode request",
231 ErrorCode::InvalidRequest));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000232 }
Sam McCall2c30fbc2018-10-18 12:32:04 +0000233 };
234 }
235
Haojian Wuf2516342019-08-05 12:48:09 +0000236 // Bind a reply callback to a request. The callback will be invoked when
237 // clangd receives the reply from the LSP client.
238 // Return a call id of the request.
239 llvm::json::Value bindReply(Callback<llvm::json::Value> Reply) {
240 llvm::Optional<std::pair<int, Callback<llvm::json::Value>>> OldestCB;
241 int ID;
242 {
243 std::lock_guard<std::mutex> Mutex(CallMutex);
244 ID = NextCallID++;
245 ReplyCallbacks.emplace_back(ID, std::move(Reply));
246
247 // If the queue overflows, we assume that the client didn't reply the
248 // oldest request, and run the corresponding callback which replies an
249 // error to the client.
250 if (ReplyCallbacks.size() > MaxReplayCallbacks) {
251 elog("more than {0} outstanding LSP calls, forgetting about {1}",
252 MaxReplayCallbacks, ReplyCallbacks.front().first);
253 OldestCB = std::move(ReplyCallbacks.front());
254 ReplyCallbacks.pop_front();
255 }
256 }
257 if (OldestCB)
258 OldestCB->second(llvm::createStringError(
259 llvm::inconvertibleErrorCode(),
260 llvm::formatv("failed to receive a client reply for request ({0})",
261 OldestCB->first)));
262 return ID;
263 }
264
Sam McCall2c30fbc2018-10-18 12:32:04 +0000265 // Bind an LSP method name to a notification.
266 template <typename Param>
267 void bind(const char *Method,
268 void (ClangdLSPServer::*Handler)(const Param &)) {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000269 Notifications[Method] = [Method, Handler,
270 this](llvm::json::Value RawParams) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000271 Param P;
272 if (!fromJSON(RawParams, P)) {
273 elog("Failed to decode {0} request.", Method);
274 return;
275 }
276 trace::Span Tracer(Method);
277 SPAN_ATTACH(Tracer, "Params", RawParams);
278 (Server.*Handler)(P);
279 };
280 }
281
282private:
Sam McCalle2f3a732018-10-24 14:26:26 +0000283 // Function object to reply to an LSP call.
284 // Each instance must be called exactly once, otherwise:
285 // - the bug is logged, and (in debug mode) an assert will fire
286 // - if there was no reply, an error reply is sent
287 // - if there were multiple replies, only the first is sent
288 class ReplyOnce {
289 std::atomic<bool> Replied = {false};
Sam McCalld7babe42018-10-24 15:18:40 +0000290 std::chrono::steady_clock::time_point Start;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000291 llvm::json::Value ID;
Sam McCalle2f3a732018-10-24 14:26:26 +0000292 std::string Method;
293 ClangdLSPServer *Server; // Null when moved-from.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000294 llvm::json::Object *TraceArgs;
Sam McCalle2f3a732018-10-24 14:26:26 +0000295
296 public:
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000297 ReplyOnce(const llvm::json::Value &ID, llvm::StringRef Method,
298 ClangdLSPServer *Server, llvm::json::Object *TraceArgs)
Sam McCalld7babe42018-10-24 15:18:40 +0000299 : Start(std::chrono::steady_clock::now()), ID(ID), Method(Method),
300 Server(Server), TraceArgs(TraceArgs) {
Sam McCalle2f3a732018-10-24 14:26:26 +0000301 assert(Server);
302 }
303 ReplyOnce(ReplyOnce &&Other)
Sam McCalld7babe42018-10-24 15:18:40 +0000304 : Replied(Other.Replied.load()), Start(Other.Start),
305 ID(std::move(Other.ID)), Method(std::move(Other.Method)),
306 Server(Other.Server), TraceArgs(Other.TraceArgs) {
Sam McCalle2f3a732018-10-24 14:26:26 +0000307 Other.Server = nullptr;
308 }
Ilya Biryukov22fa4652019-01-03 13:28:05 +0000309 ReplyOnce &operator=(ReplyOnce &&) = delete;
Sam McCalle2f3a732018-10-24 14:26:26 +0000310 ReplyOnce(const ReplyOnce &) = delete;
Ilya Biryukov22fa4652019-01-03 13:28:05 +0000311 ReplyOnce &operator=(const ReplyOnce &) = delete;
Sam McCalle2f3a732018-10-24 14:26:26 +0000312
313 ~ReplyOnce() {
Haojian Wuf2516342019-08-05 12:48:09 +0000314 // There's one legitimate reason to never reply to a request: clangd's
315 // request handler send a call to the client (e.g. applyEdit) and the
316 // client never replied. In this case, the ReplyOnce is owned by
317 // ClangdLSPServer's reply callback table and is destroyed along with the
318 // server. We don't attempt to send a reply in this case, there's little
319 // to be gained from doing so.
320 if (Server && !Server->IsBeingDestroyed && !Replied) {
Sam McCalle2f3a732018-10-24 14:26:26 +0000321 elog("No reply to message {0}({1})", Method, ID);
322 assert(false && "must reply to all calls!");
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000323 (*this)(llvm::make_error<LSPError>("server failed to reply",
324 ErrorCode::InternalError));
Sam McCalle2f3a732018-10-24 14:26:26 +0000325 }
326 }
327
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000328 void operator()(llvm::Expected<llvm::json::Value> Reply) {
Sam McCalle2f3a732018-10-24 14:26:26 +0000329 assert(Server && "moved-from!");
330 if (Replied.exchange(true)) {
331 elog("Replied twice to message {0}({1})", Method, ID);
332 assert(false && "must reply to each call only once!");
333 return;
334 }
Sam McCalld7babe42018-10-24 15:18:40 +0000335 auto Duration = std::chrono::steady_clock::now() - Start;
336 if (Reply) {
337 log("--> reply:{0}({1}) {2:ms}", Method, ID, Duration);
338 if (TraceArgs)
Sam McCalle2f3a732018-10-24 14:26:26 +0000339 (*TraceArgs)["Reply"] = *Reply;
Sam McCalld7babe42018-10-24 15:18:40 +0000340 std::lock_guard<std::mutex> Lock(Server->TranspWriter);
341 Server->Transp.reply(std::move(ID), std::move(Reply));
342 } else {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000343 llvm::Error Err = Reply.takeError();
Sam McCalld7babe42018-10-24 15:18:40 +0000344 log("--> reply:{0}({1}) {2:ms}, error: {3}", Method, ID, Duration, Err);
345 if (TraceArgs)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000346 (*TraceArgs)["Error"] = llvm::to_string(Err);
Sam McCalld7babe42018-10-24 15:18:40 +0000347 std::lock_guard<std::mutex> Lock(Server->TranspWriter);
348 Server->Transp.reply(std::move(ID), std::move(Err));
Sam McCalle2f3a732018-10-24 14:26:26 +0000349 }
Sam McCalle2f3a732018-10-24 14:26:26 +0000350 }
351 };
352
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000353 llvm::StringMap<std::function<void(llvm::json::Value)>> Notifications;
354 llvm::StringMap<std::function<void(llvm::json::Value, ReplyOnce)>> Calls;
Haojian Wuf2516342019-08-05 12:48:09 +0000355 // The maximum number of callbacks held in clangd.
356 //
357 // We bound the maximum size to the pending map to prevent memory leakage
358 // for cases where LSP clients don't reply for the request.
359 static constexpr int MaxReplayCallbacks = 100;
360 mutable std::mutex CallMutex;
361 int NextCallID = 0; /* GUARDED_BY(CallMutex) */
362 std::deque<std::pair</*RequestID*/ int,
363 /*ReplyHandler*/ Callback<llvm::json::Value>>>
364 ReplyCallbacks; /* GUARDED_BY(CallMutex) */
Sam McCall2c30fbc2018-10-18 12:32:04 +0000365
366 // Method calls may be cancelled by ID, so keep track of their state.
367 // This needs a mutex: handlers may finish on a different thread, and that's
368 // when we clean up entries in the map.
369 mutable std::mutex RequestCancelersMutex;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000370 llvm::StringMap<std::pair<Canceler, /*Cookie*/ unsigned>> RequestCancelers;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000371 unsigned NextRequestCookie = 0; // To disambiguate reused IDs, see below.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000372 void onCancel(const llvm::json::Value &Params) {
373 const llvm::json::Value *ID = nullptr;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000374 if (auto *O = Params.getAsObject())
375 ID = O->get("id");
376 if (!ID) {
377 elog("Bad cancellation request: {0}", Params);
378 return;
379 }
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000380 auto StrID = llvm::to_string(*ID);
Sam McCall2c30fbc2018-10-18 12:32:04 +0000381 std::lock_guard<std::mutex> Lock(RequestCancelersMutex);
382 auto It = RequestCancelers.find(StrID);
383 if (It != RequestCancelers.end())
384 It->second.first(); // Invoke the canceler.
385 }
Sam McCalla69698f2019-03-27 17:47:49 +0000386
387 Context handlerContext() const {
388 return Context::current().derive(
389 kCurrentOffsetEncoding,
390 Server.NegotiatedOffsetEncoding.getValueOr(OffsetEncoding::UTF16));
391 }
392
Sam McCall2c30fbc2018-10-18 12:32:04 +0000393 // We run cancelable requests in a context that does two things:
394 // - allows cancellation using RequestCancelers[ID]
395 // - cleans up the entry in RequestCancelers when it's no longer needed
396 // If a client reuses an ID, the last wins and the first cannot be canceled.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000397 Context cancelableRequestContext(const llvm::json::Value &ID) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000398 auto Task = cancelableTask();
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000399 auto StrID = llvm::to_string(ID); // JSON-serialize ID for map key.
Sam McCall2c30fbc2018-10-18 12:32:04 +0000400 auto Cookie = NextRequestCookie++; // No lock, only called on main thread.
401 {
402 std::lock_guard<std::mutex> Lock(RequestCancelersMutex);
403 RequestCancelers[StrID] = {std::move(Task.second), Cookie};
404 }
405 // When the request ends, we can clean up the entry we just added.
406 // The cookie lets us check that it hasn't been overwritten due to ID
407 // reuse.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000408 return Task.first.derive(llvm::make_scope_exit([this, StrID, Cookie] {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000409 std::lock_guard<std::mutex> Lock(RequestCancelersMutex);
410 auto It = RequestCancelers.find(StrID);
411 if (It != RequestCancelers.end() && It->second.second == Cookie)
412 RequestCancelers.erase(It);
413 }));
414 }
415
416 ClangdLSPServer &Server;
417};
Haojian Wuf2516342019-08-05 12:48:09 +0000418constexpr int ClangdLSPServer::MessageHandler::MaxReplayCallbacks;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000419
420// call(), notify(), and reply() wrap the Transport, adding logging and locking.
Haojian Wuf2516342019-08-05 12:48:09 +0000421void ClangdLSPServer::callRaw(StringRef Method, llvm::json::Value Params,
422 Callback<llvm::json::Value> CB) {
423 auto ID = MsgHandler->bindReply(std::move(CB));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000424 log("--> {0}({1})", Method, ID);
Sam McCall2c30fbc2018-10-18 12:32:04 +0000425 std::lock_guard<std::mutex> Lock(TranspWriter);
426 Transp.call(Method, std::move(Params), ID);
427}
428
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000429void ClangdLSPServer::notify(llvm::StringRef Method, llvm::json::Value Params) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000430 log("--> {0}", Method);
431 std::lock_guard<std::mutex> Lock(TranspWriter);
432 Transp.notify(Method, std::move(Params));
433}
434
Sam McCall2c30fbc2018-10-18 12:32:04 +0000435void ClangdLSPServer::onInitialize(const InitializeParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000436 Callback<llvm::json::Value> Reply) {
Sam McCalla69698f2019-03-27 17:47:49 +0000437 // Determine character encoding first as it affects constructed ClangdServer.
438 if (Params.capabilities.offsetEncoding && !NegotiatedOffsetEncoding) {
439 NegotiatedOffsetEncoding = OffsetEncoding::UTF16; // fallback
440 for (OffsetEncoding Supported : *Params.capabilities.offsetEncoding)
441 if (Supported != OffsetEncoding::UnsupportedEncoding) {
442 NegotiatedOffsetEncoding = Supported;
443 break;
444 }
445 }
446 llvm::Optional<WithContextValue> WithOffsetEncoding;
447 if (NegotiatedOffsetEncoding)
448 WithOffsetEncoding.emplace(kCurrentOffsetEncoding,
449 *NegotiatedOffsetEncoding);
450
Johan Vikstroma848dab2019-07-04 07:53:12 +0000451 ClangdServerOpts.SemanticHighlighting =
452 Params.capabilities.SemanticHighlighting;
Sam McCall0d9b40f2018-10-19 15:42:23 +0000453 if (Params.rootUri && *Params.rootUri)
454 ClangdServerOpts.WorkspaceRoot = Params.rootUri->file();
455 else if (Params.rootPath && !Params.rootPath->empty())
456 ClangdServerOpts.WorkspaceRoot = *Params.rootPath;
Sam McCall3d0adbe2018-10-18 14:41:50 +0000457 if (Server)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000458 return Reply(llvm::make_error<LSPError>("server already initialized",
459 ErrorCode::InvalidRequest));
Sam McCallbc904612018-10-25 04:22:52 +0000460 if (const auto &Dir = Params.initializationOptions.compilationDatabasePath)
461 CompileCommandsDir = Dir;
Kadir Cetinkaya256247c2019-06-26 07:45:27 +0000462 if (UseDirBasedCDB) {
Jonas Devlieghere1c705d92019-08-14 23:52:23 +0000463 BaseCDB = std::make_unique<DirectoryBasedGlobalCompilationDatabase>(
Sam McCallc55d09a2018-11-02 13:09:36 +0000464 CompileCommandsDir);
Kadir Cetinkaya256247c2019-06-26 07:45:27 +0000465 BaseCDB = getQueryDriverDatabase(
466 llvm::makeArrayRef(ClangdServerOpts.QueryDriverGlobs),
467 std::move(BaseCDB));
468 }
Kadir Cetinkayabe6b35d2019-01-22 09:10:20 +0000469 CDB.emplace(BaseCDB.get(), Params.initializationOptions.fallbackFlags,
470 ClangdServerOpts.ResourceDir);
Sam McCallc55d09a2018-11-02 13:09:36 +0000471 Server.emplace(*CDB, FSProvider, static_cast<DiagnosticsConsumer &>(*this),
472 ClangdServerOpts);
Sam McCallbc904612018-10-25 04:22:52 +0000473 applyConfiguration(Params.initializationOptions.ConfigSettings);
Simon Marchi88016782018-08-01 11:28:49 +0000474
Sam McCallbf6a2fc2018-10-17 07:33:42 +0000475 CCOpts.EnableSnippets = Params.capabilities.CompletionSnippets;
Sam McCall8d412942019-06-18 11:57:26 +0000476 CCOpts.IncludeFixIts = Params.capabilities.CompletionFixes;
Sam McCall5f092e32019-07-08 17:27:15 +0000477 if (!CCOpts.BundleOverloads.hasValue())
478 CCOpts.BundleOverloads = Params.capabilities.HasSignatureHelp;
Sam McCallbf6a2fc2018-10-17 07:33:42 +0000479 DiagOpts.EmbedFixesInDiagnostics = Params.capabilities.DiagnosticFixes;
480 DiagOpts.SendDiagnosticCategory = Params.capabilities.DiagnosticCategory;
Sam McCallc9e4ee92019-04-18 15:17:07 +0000481 DiagOpts.EmitRelatedLocations =
482 Params.capabilities.DiagnosticRelatedInformation;
Sam McCallbf6a2fc2018-10-17 07:33:42 +0000483 if (Params.capabilities.WorkspaceSymbolKinds)
484 SupportedSymbolKinds |= *Params.capabilities.WorkspaceSymbolKinds;
485 if (Params.capabilities.CompletionItemKinds)
486 SupportedCompletionItemKinds |= *Params.capabilities.CompletionItemKinds;
487 SupportsCodeAction = Params.capabilities.CodeActionStructure;
Ilya Biryukov19d75602018-11-23 15:21:19 +0000488 SupportsHierarchicalDocumentSymbol =
489 Params.capabilities.HierarchicalDocumentSymbol;
Haojian Wub6188492018-12-20 15:39:12 +0000490 SupportFileStatus = Params.initializationOptions.FileStatus;
Ilya Biryukovf9169d02019-05-29 10:01:00 +0000491 HoverContentFormat = Params.capabilities.HoverContentFormat;
Ilya Biryukov4ef0f822019-06-04 09:36:59 +0000492 SupportsOffsetsInSignatureHelp = Params.capabilities.OffsetsInSignatureHelp;
Haojian Wuf429ab62019-07-24 07:49:23 +0000493
494 // Per LSP, renameProvider can be either boolean or RenameOptions.
495 // RenameOptions will be specified if the client states it supports prepare.
496 llvm::json::Value RenameProvider =
497 llvm::json::Object{{"prepareProvider", true}};
498 if (!Params.capabilities.RenamePrepareSupport) // Only boolean allowed per LSP
499 RenameProvider = true;
500
Haojian Wu08d93f12019-08-22 14:53:45 +0000501 // Per LSP, codeActionProvide can be either boolean or CodeActionOptions.
502 // CodeActionOptions is only valid if the client supports action literal
503 // via textDocument.codeAction.codeActionLiteralSupport.
504 llvm::json::Value CodeActionProvider = true;
505 if (Params.capabilities.CodeActionStructure)
506 CodeActionProvider = llvm::json::Object{
507 {"codeActionKinds",
508 {CodeAction::QUICKFIX_KIND, CodeAction::REFACTOR_KIND,
509 CodeAction::INFO_KIND}}};
510
Sam McCalla69698f2019-03-27 17:47:49 +0000511 llvm::json::Object Result{
Sam McCall0930ab02017-11-07 15:49:35 +0000512 {{"capabilities",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000513 llvm::json::Object{
Simon Marchi98082622018-03-26 14:41:40 +0000514 {"textDocumentSync", (int)TextDocumentSyncKind::Incremental},
Sam McCall0930ab02017-11-07 15:49:35 +0000515 {"documentFormattingProvider", true},
516 {"documentRangeFormattingProvider", true},
517 {"documentOnTypeFormattingProvider",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000518 llvm::json::Object{
Sam McCall25c62572019-06-10 14:26:21 +0000519 {"firstTriggerCharacter", "\n"},
Sam McCall0930ab02017-11-07 15:49:35 +0000520 {"moreTriggerCharacter", {}},
521 }},
Haojian Wu08d93f12019-08-22 14:53:45 +0000522 {"codeActionProvider", std::move(CodeActionProvider)},
Sam McCall0930ab02017-11-07 15:49:35 +0000523 {"completionProvider",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000524 llvm::json::Object{
Sam McCall0930ab02017-11-07 15:49:35 +0000525 {"resolveProvider", false},
Ilya Biryukovb0826bd2019-01-03 13:37:12 +0000526 // We do extra checks for '>' and ':' in completion to only
527 // trigger on '->' and '::'.
Sam McCall0930ab02017-11-07 15:49:35 +0000528 {"triggerCharacters", {".", ">", ":"}},
529 }},
530 {"signatureHelpProvider",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000531 llvm::json::Object{
Sam McCall0930ab02017-11-07 15:49:35 +0000532 {"triggerCharacters", {"(", ","}},
533 }},
Sam McCall866ba2c2019-02-01 11:26:13 +0000534 {"declarationProvider", true},
Sam McCall0930ab02017-11-07 15:49:35 +0000535 {"definitionProvider", true},
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000536 {"documentHighlightProvider", true},
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000537 {"hoverProvider", true},
Haojian Wuf429ab62019-07-24 07:49:23 +0000538 {"renameProvider", std::move(RenameProvider)},
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000539 {"documentSymbolProvider", true},
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000540 {"workspaceSymbolProvider", true},
Sam McCall1ad142f2018-09-05 11:53:07 +0000541 {"referencesProvider", true},
Sam McCall0930ab02017-11-07 15:49:35 +0000542 {"executeCommandProvider",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000543 llvm::json::Object{
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000544 {"commands",
545 {ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND,
546 ExecuteCommandParams::CLANGD_APPLY_TWEAK}},
Sam McCall0930ab02017-11-07 15:49:35 +0000547 }},
Kadir Cetinkaya86658022019-03-19 09:27:04 +0000548 {"typeHierarchyProvider", true},
Sam McCalla69698f2019-03-27 17:47:49 +0000549 }}}};
550 if (NegotiatedOffsetEncoding)
551 Result["offsetEncoding"] = *NegotiatedOffsetEncoding;
Johan Vikstroma848dab2019-07-04 07:53:12 +0000552 if (Params.capabilities.SemanticHighlighting)
553 Result.getObject("capabilities")
554 ->insert(
555 {"semanticHighlighting",
Haojian Wu1ca2ee42019-07-04 12:27:21 +0000556 llvm::json::Object{{"scopes", buildHighlightScopeLookupTable()}}});
Sam McCalla69698f2019-03-27 17:47:49 +0000557 Reply(std::move(Result));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000558}
559
Sam McCall2c30fbc2018-10-18 12:32:04 +0000560void ClangdLSPServer::onShutdown(const ShutdownParams &Params,
561 Callback<std::nullptr_t> Reply) {
Ilya Biryukov0d9b8a32017-10-25 08:45:41 +0000562 // Do essentially nothing, just say we're ready to exit.
563 ShutdownRequestReceived = true;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000564 Reply(nullptr);
Sam McCall8a5dded2017-10-12 13:29:58 +0000565}
Ilya Biryukovafb55542017-05-16 14:40:30 +0000566
Sam McCall422c8282018-11-26 16:00:11 +0000567// sync is a clangd extension: it blocks until all background work completes.
568// It blocks the calling thread, so no messages are processed until it returns!
569void ClangdLSPServer::onSync(const NoParams &Params,
570 Callback<std::nullptr_t> Reply) {
571 if (Server->blockUntilIdleForTest(/*TimeoutSeconds=*/60))
572 Reply(nullptr);
573 else
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000574 Reply(llvm::createStringError(llvm::inconvertibleErrorCode(),
575 "Not idle after a minute"));
Sam McCall422c8282018-11-26 16:00:11 +0000576}
577
Sam McCall2c30fbc2018-10-18 12:32:04 +0000578void ClangdLSPServer::onDocumentDidOpen(
579 const DidOpenTextDocumentParams &Params) {
Simon Marchi9569fd52018-03-16 14:30:42 +0000580 PathRef File = Params.textDocument.uri.file();
Ilya Biryukovb10ef472018-06-13 09:20:41 +0000581
Sam McCall2c30fbc2018-10-18 12:32:04 +0000582 const std::string &Contents = Params.textDocument.text;
Simon Marchi9569fd52018-03-16 14:30:42 +0000583
Simon Marchi98082622018-03-26 14:41:40 +0000584 DraftMgr.addDraft(File, Contents);
Ilya Biryukov652364b2018-09-26 05:48:29 +0000585 Server->addDocument(File, Contents, WantDiagnostics::Yes);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000586}
587
Sam McCall2c30fbc2018-10-18 12:32:04 +0000588void ClangdLSPServer::onDocumentDidChange(
589 const DidChangeTextDocumentParams &Params) {
Eric Liu51fed182018-02-22 18:40:39 +0000590 auto WantDiags = WantDiagnostics::Auto;
591 if (Params.wantDiagnostics.hasValue())
592 WantDiags = Params.wantDiagnostics.getValue() ? WantDiagnostics::Yes
593 : WantDiagnostics::No;
Simon Marchi9569fd52018-03-16 14:30:42 +0000594
595 PathRef File = Params.textDocument.uri.file();
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000596 llvm::Expected<std::string> Contents =
Simon Marchi98082622018-03-26 14:41:40 +0000597 DraftMgr.updateDraft(File, Params.contentChanges);
598 if (!Contents) {
599 // If this fails, we are most likely going to be not in sync anymore with
600 // the client. It is better to remove the draft and let further operations
601 // fail rather than giving wrong results.
602 DraftMgr.removeDraft(File);
Ilya Biryukov652364b2018-09-26 05:48:29 +0000603 Server->removeDocument(File);
Sam McCallbed58852018-07-11 10:35:11 +0000604 elog("Failed to update {0}: {1}", File, Contents.takeError());
Simon Marchi98082622018-03-26 14:41:40 +0000605 return;
606 }
Simon Marchi9569fd52018-03-16 14:30:42 +0000607
Ilya Biryukov652364b2018-09-26 05:48:29 +0000608 Server->addDocument(File, *Contents, WantDiags);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000609}
610
Sam McCall2c30fbc2018-10-18 12:32:04 +0000611void ClangdLSPServer::onFileEvent(const DidChangeWatchedFilesParams &Params) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000612 Server->onFileEvent(Params);
Marc-Andre Laperlebf114242017-10-02 18:00:37 +0000613}
614
Sam McCall2c30fbc2018-10-18 12:32:04 +0000615void ClangdLSPServer::onCommand(const ExecuteCommandParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000616 Callback<llvm::json::Value> Reply) {
Ilya Biryukov12864002019-08-16 12:46:41 +0000617 auto ApplyEdit = [this](WorkspaceEdit WE, std::string SuccessMessage,
618 decltype(Reply) Reply) {
Eric Liuc5105f92018-02-16 14:15:55 +0000619 ApplyWorkspaceEditParams Edit;
620 Edit.edit = std::move(WE);
Ilya Biryukov12864002019-08-16 12:46:41 +0000621 call<ApplyWorkspaceEditResponse>(
622 "workspace/applyEdit", std::move(Edit),
623 [Reply = std::move(Reply), SuccessMessage = std::move(SuccessMessage)](
624 llvm::Expected<ApplyWorkspaceEditResponse> Response) mutable {
625 if (!Response)
626 return Reply(Response.takeError());
627 if (!Response->applied) {
628 std::string Reason = Response->failureReason
629 ? *Response->failureReason
630 : "unknown reason";
631 return Reply(llvm::createStringError(
632 llvm::inconvertibleErrorCode(),
633 ("edits were not applied: " + Reason).c_str()));
634 }
635 return Reply(SuccessMessage);
636 });
Eric Liuc5105f92018-02-16 14:15:55 +0000637 };
Ilya Biryukov12864002019-08-16 12:46:41 +0000638
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000639 if (Params.command == ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND &&
640 Params.workspaceEdit) {
641 // The flow for "apply-fix" :
642 // 1. We publish a diagnostic, including fixits
643 // 2. The user clicks on the diagnostic, the editor asks us for code actions
644 // 3. We send code actions, with the fixit embedded as context
645 // 4. The user selects the fixit, the editor asks us to apply it
646 // 5. We unwrap the changes and send them back to the editor
Haojian Wuf2516342019-08-05 12:48:09 +0000647 // 6. The editor applies the changes (applyEdit), and sends us a reply
648 // 7. We unwrap the reply and send a reply to the editor.
Ilya Biryukov12864002019-08-16 12:46:41 +0000649 ApplyEdit(*Params.workspaceEdit, "Fix applied.", std::move(Reply));
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000650 } else if (Params.command == ExecuteCommandParams::CLANGD_APPLY_TWEAK &&
651 Params.tweakArgs) {
652 auto Code = DraftMgr.getDraft(Params.tweakArgs->file.file());
653 if (!Code)
654 return Reply(llvm::createStringError(
655 llvm::inconvertibleErrorCode(),
656 "trying to apply a code action for a non-added file"));
657
Ilya Biryukov12864002019-08-16 12:46:41 +0000658 auto Action = [this, ApplyEdit, Reply = std::move(Reply),
659 File = Params.tweakArgs->file, Code = std::move(*Code)](
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000660 llvm::Expected<Tweak::Effect> R) mutable {
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000661 if (!R)
662 return Reply(R.takeError());
663
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000664 assert(R->ShowMessage ||
665 (!R->ApplyEdits.empty() && "tweak has no effect"));
Ilya Biryukov12864002019-08-16 12:46:41 +0000666
Sam McCall395fde72019-06-18 13:37:54 +0000667 if (R->ShowMessage) {
668 ShowMessageParams Msg;
669 Msg.message = *R->ShowMessage;
670 Msg.type = MessageType::Info;
671 notify("window/showMessage", Msg);
672 }
Ilya Biryukov12864002019-08-16 12:46:41 +0000673 // When no edit is specified, make sure we Reply().
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000674 if (R->ApplyEdits.empty())
675 return Reply("Tweak applied.");
676
677 if (auto Err = validateEdits(DraftMgr, *R))
678 return Reply(std::move(Err));
679
680 WorkspaceEdit WE;
681 WE.changes.emplace();
682 for (const auto &It : R->ApplyEdits) {
683 (*WE.changes)[URI::create(It.first()).toString()] =
684 It.second.asTextEdits();
685 }
686 // ApplyEdit will take care of calling Reply().
687 return ApplyEdit(std::move(WE), "Tweak applied.", std::move(Reply));
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000688 };
689 Server->applyTweak(Params.tweakArgs->file.file(),
690 Params.tweakArgs->selection, Params.tweakArgs->tweakID,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000691 std::move(Action));
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000692 } else {
693 // We should not get here because ExecuteCommandParams would not have
694 // parsed in the first place and this handler should not be called. But if
695 // more commands are added, this will be here has a safe guard.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000696 Reply(llvm::make_error<LSPError>(
697 llvm::formatv("Unsupported command \"{0}\".", Params.command).str(),
Sam McCall2c30fbc2018-10-18 12:32:04 +0000698 ErrorCode::InvalidParams));
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000699 }
700}
701
Sam McCall2c30fbc2018-10-18 12:32:04 +0000702void ClangdLSPServer::onWorkspaceSymbol(
703 const WorkspaceSymbolParams &Params,
704 Callback<std::vector<SymbolInformation>> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000705 Server->workspaceSymbols(
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000706 Params.query, CCOpts.Limit,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000707 [Reply = std::move(Reply),
708 this](llvm::Expected<std::vector<SymbolInformation>> Items) mutable {
709 if (!Items)
710 return Reply(Items.takeError());
711 for (auto &Sym : *Items)
712 Sym.kind = adjustKindToCapability(Sym.kind, SupportedSymbolKinds);
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000713
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000714 Reply(std::move(*Items));
715 });
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000716}
717
Haojian Wuf429ab62019-07-24 07:49:23 +0000718void ClangdLSPServer::onPrepareRename(const TextDocumentPositionParams &Params,
719 Callback<llvm::Optional<Range>> Reply) {
720 Server->prepareRename(Params.textDocument.uri.file(), Params.position,
721 std::move(Reply));
722}
723
Sam McCall2c30fbc2018-10-18 12:32:04 +0000724void ClangdLSPServer::onRename(const RenameParams &Params,
725 Callback<WorkspaceEdit> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000726 Path File = Params.textDocument.uri.file();
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000727 llvm::Optional<std::string> Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000728 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000729 return Reply(llvm::make_error<LSPError>(
730 "onRename called for non-added file", ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000731
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000732 Server->rename(File, Params.position, Params.newName, /*WantFormat=*/true,
733 [File, Code, Params, Reply = std::move(Reply)](
734 llvm::Expected<std::vector<TextEdit>> Edits) mutable {
735 if (!Edits)
736 return Reply(Edits.takeError());
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000737
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000738 WorkspaceEdit WE;
739 WE.changes = {{Params.textDocument.uri.uri(), *Edits}};
740 Reply(WE);
741 });
Haojian Wu345099c2017-11-09 11:30:04 +0000742}
743
Sam McCall2c30fbc2018-10-18 12:32:04 +0000744void ClangdLSPServer::onDocumentDidClose(
745 const DidCloseTextDocumentParams &Params) {
Simon Marchi9569fd52018-03-16 14:30:42 +0000746 PathRef File = Params.textDocument.uri.file();
747 DraftMgr.removeDraft(File);
Ilya Biryukov652364b2018-09-26 05:48:29 +0000748 Server->removeDocument(File);
Ilya Biryukov49c10712019-03-25 10:15:11 +0000749
750 {
751 std::lock_guard<std::mutex> Lock(FixItsMutex);
752 FixItsMap.erase(File);
753 }
Johan Vikstromc2653ef22019-08-01 08:08:44 +0000754 {
755 std::lock_guard<std::mutex> HLock(HighlightingsMutex);
756 FileToHighlightings.erase(File);
757 }
Ilya Biryukov49c10712019-03-25 10:15:11 +0000758 // clangd will not send updates for this file anymore, so we empty out the
759 // list of diagnostics shown on the client (e.g. in the "Problems" pane of
760 // VSCode). Note that this cannot race with actual diagnostics responses
761 // because removeDocument() guarantees no diagnostic callbacks will be
762 // executed after it returns.
763 publishDiagnostics(URIForFile::canonicalize(File, /*TUPath=*/File), {});
Ilya Biryukovafb55542017-05-16 14:40:30 +0000764}
765
Sam McCall4db732a2017-09-30 10:08:52 +0000766void ClangdLSPServer::onDocumentOnTypeFormatting(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000767 const DocumentOnTypeFormattingParams &Params,
768 Callback<std::vector<TextEdit>> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000769 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000770 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000771 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000772 return Reply(llvm::make_error<LSPError>(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000773 "onDocumentOnTypeFormatting called for non-added file",
774 ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000775
Sam McCall25c62572019-06-10 14:26:21 +0000776 Reply(Server->formatOnType(*Code, File, Params.position, Params.ch));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000777}
778
Sam McCall4db732a2017-09-30 10:08:52 +0000779void ClangdLSPServer::onDocumentRangeFormatting(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000780 const DocumentRangeFormattingParams &Params,
781 Callback<std::vector<TextEdit>> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000782 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000783 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000784 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000785 return Reply(llvm::make_error<LSPError>(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000786 "onDocumentRangeFormatting called for non-added file",
787 ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000788
Ilya Biryukov652364b2018-09-26 05:48:29 +0000789 auto ReplacementsOrError = Server->formatRange(*Code, File, Params.range);
Raoul Wols212bcf82017-12-12 20:25:06 +0000790 if (ReplacementsOrError)
Sam McCall2c30fbc2018-10-18 12:32:04 +0000791 Reply(replacementsToEdits(*Code, ReplacementsOrError.get()));
Raoul Wols212bcf82017-12-12 20:25:06 +0000792 else
Sam McCall2c30fbc2018-10-18 12:32:04 +0000793 Reply(ReplacementsOrError.takeError());
Ilya Biryukovafb55542017-05-16 14:40:30 +0000794}
795
Sam McCall2c30fbc2018-10-18 12:32:04 +0000796void ClangdLSPServer::onDocumentFormatting(
797 const DocumentFormattingParams &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>(
803 "onDocumentFormatting called for non-added file",
804 ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000805
Ilya Biryukov652364b2018-09-26 05:48:29 +0000806 auto ReplacementsOrError = Server->formatFile(*Code, File);
Raoul Wols212bcf82017-12-12 20:25:06 +0000807 if (ReplacementsOrError)
Sam McCall2c30fbc2018-10-18 12:32:04 +0000808 Reply(replacementsToEdits(*Code, ReplacementsOrError.get()));
Raoul Wols212bcf82017-12-12 20:25:06 +0000809 else
Sam McCall2c30fbc2018-10-18 12:32:04 +0000810 Reply(ReplacementsOrError.takeError());
Sam McCall4db732a2017-09-30 10:08:52 +0000811}
812
Ilya Biryukov19d75602018-11-23 15:21:19 +0000813/// The functions constructs a flattened view of the DocumentSymbol hierarchy.
814/// Used by the clients that do not support the hierarchical view.
815static std::vector<SymbolInformation>
816flattenSymbolHierarchy(llvm::ArrayRef<DocumentSymbol> Symbols,
817 const URIForFile &FileURI) {
818
819 std::vector<SymbolInformation> Results;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000820 std::function<void(const DocumentSymbol &, llvm::StringRef)> Process =
821 [&](const DocumentSymbol &S, llvm::Optional<llvm::StringRef> ParentName) {
Ilya Biryukov19d75602018-11-23 15:21:19 +0000822 SymbolInformation SI;
823 SI.containerName = ParentName ? "" : *ParentName;
824 SI.name = S.name;
825 SI.kind = S.kind;
826 SI.location.range = S.range;
827 SI.location.uri = FileURI;
828
829 Results.push_back(std::move(SI));
830 std::string FullName =
831 !ParentName ? S.name : (ParentName->str() + "::" + S.name);
832 for (auto &C : S.children)
833 Process(C, /*ParentName=*/FullName);
834 };
835 for (auto &S : Symbols)
836 Process(S, /*ParentName=*/"");
837 return Results;
838}
839
840void ClangdLSPServer::onDocumentSymbol(const DocumentSymbolParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000841 Callback<llvm::json::Value> Reply) {
Ilya Biryukov19d75602018-11-23 15:21:19 +0000842 URIForFile FileURI = Params.textDocument.uri;
Ilya Biryukov652364b2018-09-26 05:48:29 +0000843 Server->documentSymbols(
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000844 Params.textDocument.uri.file(),
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000845 [this, FileURI, Reply = std::move(Reply)](
846 llvm::Expected<std::vector<DocumentSymbol>> Items) mutable {
847 if (!Items)
848 return Reply(Items.takeError());
849 adjustSymbolKinds(*Items, SupportedSymbolKinds);
850 if (SupportsHierarchicalDocumentSymbol)
851 return Reply(std::move(*Items));
852 else
853 return Reply(flattenSymbolHierarchy(*Items, FileURI));
854 });
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000855}
856
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000857static llvm::Optional<Command> asCommand(const CodeAction &Action) {
Sam McCall20841d42018-10-16 16:29:41 +0000858 Command Cmd;
859 if (Action.command && Action.edit)
Sam McCallc008af62018-10-20 15:30:37 +0000860 return None; // Not representable. (We never emit these anyway).
Sam McCall20841d42018-10-16 16:29:41 +0000861 if (Action.command) {
862 Cmd = *Action.command;
863 } else if (Action.edit) {
864 Cmd.command = Command::CLANGD_APPLY_FIX_COMMAND;
865 Cmd.workspaceEdit = *Action.edit;
866 } else {
Sam McCallc008af62018-10-20 15:30:37 +0000867 return None;
Sam McCall20841d42018-10-16 16:29:41 +0000868 }
869 Cmd.title = Action.title;
870 if (Action.kind && *Action.kind == CodeAction::QUICKFIX_KIND)
871 Cmd.title = "Apply fix: " + Cmd.title;
872 return Cmd;
873}
874
Sam McCall2c30fbc2018-10-18 12:32:04 +0000875void ClangdLSPServer::onCodeAction(const CodeActionParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000876 Callback<llvm::json::Value> Reply) {
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000877 URIForFile File = Params.textDocument.uri;
878 auto Code = DraftMgr.getDraft(File.file());
Sam McCall2c30fbc2018-10-18 12:32:04 +0000879 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000880 return Reply(llvm::make_error<LSPError>(
881 "onCodeAction called for non-added file", ErrorCode::InvalidParams));
Sam McCall20841d42018-10-16 16:29:41 +0000882 // We provide a code action for Fixes on the specified diagnostics.
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000883 std::vector<CodeAction> FixIts;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000884 for (const Diagnostic &D : Params.context.diagnostics) {
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000885 for (auto &F : getFixes(File.file(), D)) {
886 FixIts.push_back(toCodeAction(F, Params.textDocument.uri));
887 FixIts.back().diagnostics = {D};
Sam McCalldd0566b2017-11-06 15:40:30 +0000888 }
Ilya Biryukovafb55542017-05-16 14:40:30 +0000889 }
Sam McCall20841d42018-10-16 16:29:41 +0000890
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000891 // Now enumerate the semantic code actions.
892 auto ConsumeActions =
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000893 [Reply = std::move(Reply), File, Code = std::move(*Code),
894 Selection = Params.range, FixIts = std::move(FixIts), this](
895 llvm::Expected<std::vector<ClangdServer::TweakRef>> Tweaks) mutable {
Ilya Biryukovc6ed7782019-01-30 14:24:17 +0000896 if (!Tweaks)
897 return Reply(Tweaks.takeError());
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000898
899 std::vector<CodeAction> Actions = std::move(FixIts);
900 Actions.reserve(Actions.size() + Tweaks->size());
901 for (const auto &T : *Tweaks)
902 Actions.push_back(toCodeAction(T, File, Selection));
903
904 if (SupportsCodeAction)
905 return Reply(llvm::json::Array(Actions));
906 std::vector<Command> Commands;
907 for (const auto &Action : Actions) {
908 if (auto Command = asCommand(Action))
909 Commands.push_back(std::move(*Command));
910 }
911 return Reply(llvm::json::Array(Commands));
912 };
913
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000914 Server->enumerateTweaks(File.file(), Params.range, std::move(ConsumeActions));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000915}
916
Ilya Biryukovb0826bd2019-01-03 13:37:12 +0000917void ClangdLSPServer::onCompletion(const CompletionParams &Params,
Sam McCall2c30fbc2018-10-18 12:32:04 +0000918 Callback<CompletionList> Reply) {
Ilya Biryukova7a11472019-06-07 16:24:38 +0000919 if (!shouldRunCompletion(Params)) {
920 // Clients sometimes auto-trigger completions in undesired places (e.g.
921 // 'a >^ '), we return empty results in those cases.
922 vlog("ignored auto-triggered completion, preceding char did not match");
923 return Reply(CompletionList());
924 }
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000925 Server->codeComplete(Params.textDocument.uri.file(), Params.position, CCOpts,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000926 [Reply = std::move(Reply),
927 this](llvm::Expected<CodeCompleteResult> List) mutable {
928 if (!List)
929 return Reply(List.takeError());
930 CompletionList LSPList;
931 LSPList.isIncomplete = List->HasMore;
932 for (const auto &R : List->Completions) {
933 CompletionItem C = R.render(CCOpts);
934 C.kind = adjustKindToCapability(
935 C.kind, SupportedCompletionItemKinds);
936 LSPList.items.push_back(std::move(C));
937 }
938 return Reply(std::move(LSPList));
939 });
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000940}
941
Sam McCall2c30fbc2018-10-18 12:32:04 +0000942void ClangdLSPServer::onSignatureHelp(const TextDocumentPositionParams &Params,
943 Callback<SignatureHelp> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000944 Server->signatureHelp(Params.textDocument.uri.file(), Params.position,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000945 [Reply = std::move(Reply), this](
946 llvm::Expected<SignatureHelp> Signature) mutable {
947 if (!Signature)
948 return Reply(Signature.takeError());
949 if (SupportsOffsetsInSignatureHelp)
950 return Reply(std::move(*Signature));
951 // Strip out the offsets from signature help for
952 // clients that only support string labels.
953 for (auto &SigInfo : Signature->signatures) {
954 for (auto &Param : SigInfo.parameters)
955 Param.labelOffsets.reset();
956 }
957 return Reply(std::move(*Signature));
958 });
Ilya Biryukov652364b2018-09-26 05:48:29 +0000959}
960
Sam McCall0dbab7f2019-02-02 05:56:00 +0000961// Go to definition has a toggle function: if def and decl are distinct, then
962// the first press gives you the def, the second gives you the matching def.
963// getToggle() returns the counterpart location that under the cursor.
964//
965// We return the toggled location alone (ignoring other symbols) to encourage
966// editors to "bounce" quickly between locations, without showing a menu.
967static Location *getToggle(const TextDocumentPositionParams &Point,
968 LocatedSymbol &Sym) {
969 // Toggle only makes sense with two distinct locations.
970 if (!Sym.Definition || *Sym.Definition == Sym.PreferredDeclaration)
971 return nullptr;
972 if (Sym.Definition->uri.file() == Point.textDocument.uri.file() &&
973 Sym.Definition->range.contains(Point.position))
974 return &Sym.PreferredDeclaration;
975 if (Sym.PreferredDeclaration.uri.file() == Point.textDocument.uri.file() &&
976 Sym.PreferredDeclaration.range.contains(Point.position))
977 return &*Sym.Definition;
978 return nullptr;
979}
980
Sam McCall2c30fbc2018-10-18 12:32:04 +0000981void ClangdLSPServer::onGoToDefinition(const TextDocumentPositionParams &Params,
982 Callback<std::vector<Location>> Reply) {
Sam McCall866ba2c2019-02-01 11:26:13 +0000983 Server->locateSymbolAt(
984 Params.textDocument.uri.file(), Params.position,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000985 [Params, Reply = std::move(Reply)](
986 llvm::Expected<std::vector<LocatedSymbol>> Symbols) mutable {
987 if (!Symbols)
988 return Reply(Symbols.takeError());
989 std::vector<Location> Defs;
990 for (auto &S : *Symbols) {
991 if (Location *Toggle = getToggle(Params, S))
992 return Reply(std::vector<Location>{std::move(*Toggle)});
993 Defs.push_back(S.Definition.getValueOr(S.PreferredDeclaration));
994 }
995 Reply(std::move(Defs));
996 });
Sam McCall866ba2c2019-02-01 11:26:13 +0000997}
998
999void ClangdLSPServer::onGoToDeclaration(
1000 const TextDocumentPositionParams &Params,
1001 Callback<std::vector<Location>> Reply) {
1002 Server->locateSymbolAt(
1003 Params.textDocument.uri.file(), Params.position,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001004 [Params, Reply = std::move(Reply)](
1005 llvm::Expected<std::vector<LocatedSymbol>> Symbols) mutable {
1006 if (!Symbols)
1007 return Reply(Symbols.takeError());
1008 std::vector<Location> Decls;
1009 for (auto &S : *Symbols) {
1010 if (Location *Toggle = getToggle(Params, S))
1011 return Reply(std::vector<Location>{std::move(*Toggle)});
1012 Decls.push_back(std::move(S.PreferredDeclaration));
1013 }
1014 Reply(std::move(Decls));
1015 });
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +00001016}
1017
Sam McCall111fe842019-05-07 07:55:35 +00001018void ClangdLSPServer::onSwitchSourceHeader(
1019 const TextDocumentIdentifier &Params,
Sam McCallb9ec3e92019-05-07 08:30:32 +00001020 Callback<llvm::Optional<URIForFile>> Reply) {
Sam McCall111fe842019-05-07 07:55:35 +00001021 if (auto Result = Server->switchSourceHeader(Params.uri.file()))
Sam McCallb9ec3e92019-05-07 08:30:32 +00001022 Reply(URIForFile::canonicalize(*Result, Params.uri.file()));
Sam McCall111fe842019-05-07 07:55:35 +00001023 else
1024 Reply(llvm::None);
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +00001025}
1026
Sam McCall2c30fbc2018-10-18 12:32:04 +00001027void ClangdLSPServer::onDocumentHighlight(
1028 const TextDocumentPositionParams &Params,
1029 Callback<std::vector<DocumentHighlight>> Reply) {
1030 Server->findDocumentHighlights(Params.textDocument.uri.file(),
1031 Params.position, std::move(Reply));
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +00001032}
1033
Sam McCall2c30fbc2018-10-18 12:32:04 +00001034void ClangdLSPServer::onHover(const TextDocumentPositionParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001035 Callback<llvm::Optional<Hover>> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +00001036 Server->findHover(Params.textDocument.uri.file(), Params.position,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001037 [Reply = std::move(Reply), this](
1038 llvm::Expected<llvm::Optional<HoverInfo>> H) mutable {
1039 if (!H)
1040 return Reply(H.takeError());
1041 if (!*H)
1042 return Reply(llvm::None);
Ilya Biryukovf9169d02019-05-29 10:01:00 +00001043
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001044 Hover R;
1045 R.contents.kind = HoverContentFormat;
1046 R.range = (*H)->SymRange;
1047 switch (HoverContentFormat) {
1048 case MarkupKind::PlainText:
1049 R.contents.value = (*H)->present().renderAsPlainText();
1050 return Reply(std::move(R));
1051 case MarkupKind::Markdown:
1052 R.contents.value = (*H)->present().renderAsMarkdown();
1053 return Reply(std::move(R));
1054 };
1055 llvm_unreachable("unhandled MarkupKind");
1056 });
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +00001057}
1058
Kadir Cetinkaya86658022019-03-19 09:27:04 +00001059void ClangdLSPServer::onTypeHierarchy(
1060 const TypeHierarchyParams &Params,
1061 Callback<Optional<TypeHierarchyItem>> Reply) {
1062 Server->typeHierarchy(Params.textDocument.uri.file(), Params.position,
1063 Params.resolve, Params.direction, std::move(Reply));
1064}
1065
Nathan Ridge087b0442019-07-13 03:24:48 +00001066void ClangdLSPServer::onResolveTypeHierarchy(
1067 const ResolveTypeHierarchyItemParams &Params,
1068 Callback<Optional<TypeHierarchyItem>> Reply) {
1069 Server->resolveTypeHierarchy(Params.item, Params.resolve, Params.direction,
1070 std::move(Reply));
1071}
1072
Simon Marchi88016782018-08-01 11:28:49 +00001073void ClangdLSPServer::applyConfiguration(
Sam McCallbc904612018-10-25 04:22:52 +00001074 const ConfigurationSettings &Settings) {
Simon Marchiabeed662018-10-16 15:55:03 +00001075 // Per-file update to the compilation database.
Sam McCallbc904612018-10-25 04:22:52 +00001076 bool ShouldReparseOpenFiles = false;
1077 for (auto &Entry : Settings.compilationDatabaseChanges) {
1078 /// The opened files need to be reparsed only when some existing
1079 /// entries are changed.
1080 PathRef File = Entry.first;
Sam McCallc55d09a2018-11-02 13:09:36 +00001081 auto Old = CDB->getCompileCommand(File);
1082 auto New =
1083 tooling::CompileCommand(std::move(Entry.second.workingDirectory), File,
1084 std::move(Entry.second.compilationCommand),
1085 /*Output=*/"");
Sam McCall6980edb2018-11-02 14:07:51 +00001086 if (Old != New) {
Sam McCallc55d09a2018-11-02 13:09:36 +00001087 CDB->setCompileCommand(File, std::move(New));
Sam McCall6980edb2018-11-02 14:07:51 +00001088 ShouldReparseOpenFiles = true;
1089 }
Alex Lorenzf8087862018-08-01 17:39:29 +00001090 }
Sam McCallbc904612018-10-25 04:22:52 +00001091 if (ShouldReparseOpenFiles)
1092 reparseOpenedFiles();
Simon Marchi5178f922018-02-22 14:00:39 +00001093}
1094
Johan Vikstroma848dab2019-07-04 07:53:12 +00001095void ClangdLSPServer::publishSemanticHighlighting(
1096 SemanticHighlightingParams Params) {
1097 notify("textDocument/semanticHighlighting", Params);
1098}
1099
Ilya Biryukov49c10712019-03-25 10:15:11 +00001100void ClangdLSPServer::publishDiagnostics(
1101 const URIForFile &File, std::vector<clangd::Diagnostic> Diagnostics) {
1102 // Publish diagnostics.
1103 notify("textDocument/publishDiagnostics",
1104 llvm::json::Object{
1105 {"uri", File},
1106 {"diagnostics", std::move(Diagnostics)},
1107 });
1108}
1109
Simon Marchi88016782018-08-01 11:28:49 +00001110// FIXME: This function needs to be properly tested.
1111void ClangdLSPServer::onChangeConfiguration(
Sam McCall2c30fbc2018-10-18 12:32:04 +00001112 const DidChangeConfigurationParams &Params) {
Simon Marchi88016782018-08-01 11:28:49 +00001113 applyConfiguration(Params.settings);
1114}
1115
Sam McCall2c30fbc2018-10-18 12:32:04 +00001116void ClangdLSPServer::onReference(const ReferenceParams &Params,
1117 Callback<std::vector<Location>> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +00001118 Server->findReferences(Params.textDocument.uri.file(), Params.position,
Haojian Wuc34f0222019-01-14 18:11:09 +00001119 CCOpts.Limit, std::move(Reply));
Sam McCall1ad142f2018-09-05 11:53:07 +00001120}
1121
Jan Korousb4067012018-11-27 16:40:46 +00001122void ClangdLSPServer::onSymbolInfo(const TextDocumentPositionParams &Params,
1123 Callback<std::vector<SymbolDetails>> Reply) {
1124 Server->symbolInfo(Params.textDocument.uri.file(), Params.position,
1125 std::move(Reply));
1126}
1127
Sam McCalla69698f2019-03-27 17:47:49 +00001128ClangdLSPServer::ClangdLSPServer(
1129 class Transport &Transp, const FileSystemProvider &FSProvider,
1130 const clangd::CodeCompleteOptions &CCOpts,
1131 llvm::Optional<Path> CompileCommandsDir, bool UseDirBasedCDB,
1132 llvm::Optional<OffsetEncoding> ForcedOffsetEncoding,
1133 const ClangdServer::Options &Opts)
Haojian Wu1ca0c582019-01-22 09:39:05 +00001134 : Transp(Transp), MsgHandler(new MessageHandler(*this)),
1135 FSProvider(FSProvider), CCOpts(CCOpts),
Sam McCalld1c9d112018-10-23 14:19:54 +00001136 SupportedSymbolKinds(defaultSymbolKinds()),
Kadir Cetinkaya133d46f2018-09-27 17:13:07 +00001137 SupportedCompletionItemKinds(defaultCompletionItemKinds()),
Sam McCallc55d09a2018-11-02 13:09:36 +00001138 UseDirBasedCDB(UseDirBasedCDB),
Sam McCalla69698f2019-03-27 17:47:49 +00001139 CompileCommandsDir(std::move(CompileCommandsDir)), ClangdServerOpts(Opts),
1140 NegotiatedOffsetEncoding(ForcedOffsetEncoding) {
Sam McCall2c30fbc2018-10-18 12:32:04 +00001141 // clang-format off
1142 MsgHandler->bind("initialize", &ClangdLSPServer::onInitialize);
1143 MsgHandler->bind("shutdown", &ClangdLSPServer::onShutdown);
Sam McCall422c8282018-11-26 16:00:11 +00001144 MsgHandler->bind("sync", &ClangdLSPServer::onSync);
Sam McCall2c30fbc2018-10-18 12:32:04 +00001145 MsgHandler->bind("textDocument/rangeFormatting", &ClangdLSPServer::onDocumentRangeFormatting);
1146 MsgHandler->bind("textDocument/onTypeFormatting", &ClangdLSPServer::onDocumentOnTypeFormatting);
1147 MsgHandler->bind("textDocument/formatting", &ClangdLSPServer::onDocumentFormatting);
1148 MsgHandler->bind("textDocument/codeAction", &ClangdLSPServer::onCodeAction);
1149 MsgHandler->bind("textDocument/completion", &ClangdLSPServer::onCompletion);
1150 MsgHandler->bind("textDocument/signatureHelp", &ClangdLSPServer::onSignatureHelp);
1151 MsgHandler->bind("textDocument/definition", &ClangdLSPServer::onGoToDefinition);
Sam McCall866ba2c2019-02-01 11:26:13 +00001152 MsgHandler->bind("textDocument/declaration", &ClangdLSPServer::onGoToDeclaration);
Sam McCall2c30fbc2018-10-18 12:32:04 +00001153 MsgHandler->bind("textDocument/references", &ClangdLSPServer::onReference);
1154 MsgHandler->bind("textDocument/switchSourceHeader", &ClangdLSPServer::onSwitchSourceHeader);
Haojian Wuf429ab62019-07-24 07:49:23 +00001155 MsgHandler->bind("textDocument/prepareRename", &ClangdLSPServer::onPrepareRename);
Sam McCall2c30fbc2018-10-18 12:32:04 +00001156 MsgHandler->bind("textDocument/rename", &ClangdLSPServer::onRename);
1157 MsgHandler->bind("textDocument/hover", &ClangdLSPServer::onHover);
1158 MsgHandler->bind("textDocument/documentSymbol", &ClangdLSPServer::onDocumentSymbol);
1159 MsgHandler->bind("workspace/executeCommand", &ClangdLSPServer::onCommand);
1160 MsgHandler->bind("textDocument/documentHighlight", &ClangdLSPServer::onDocumentHighlight);
1161 MsgHandler->bind("workspace/symbol", &ClangdLSPServer::onWorkspaceSymbol);
1162 MsgHandler->bind("textDocument/didOpen", &ClangdLSPServer::onDocumentDidOpen);
1163 MsgHandler->bind("textDocument/didClose", &ClangdLSPServer::onDocumentDidClose);
1164 MsgHandler->bind("textDocument/didChange", &ClangdLSPServer::onDocumentDidChange);
1165 MsgHandler->bind("workspace/didChangeWatchedFiles", &ClangdLSPServer::onFileEvent);
1166 MsgHandler->bind("workspace/didChangeConfiguration", &ClangdLSPServer::onChangeConfiguration);
Jan Korousb4067012018-11-27 16:40:46 +00001167 MsgHandler->bind("textDocument/symbolInfo", &ClangdLSPServer::onSymbolInfo);
Kadir Cetinkaya86658022019-03-19 09:27:04 +00001168 MsgHandler->bind("textDocument/typeHierarchy", &ClangdLSPServer::onTypeHierarchy);
Nathan Ridge087b0442019-07-13 03:24:48 +00001169 MsgHandler->bind("typeHierarchy/resolve", &ClangdLSPServer::onResolveTypeHierarchy);
Sam McCall2c30fbc2018-10-18 12:32:04 +00001170 // clang-format on
1171}
1172
Haojian Wuf2516342019-08-05 12:48:09 +00001173ClangdLSPServer::~ClangdLSPServer() { IsBeingDestroyed = true; }
Ilya Biryukov38d79772017-05-16 09:38:59 +00001174
Sam McCalldc8f3cf2018-10-17 07:32:05 +00001175bool ClangdLSPServer::run() {
Ilya Biryukovafb55542017-05-16 14:40:30 +00001176 // Run the Language Server loop.
Sam McCalldc8f3cf2018-10-17 07:32:05 +00001177 bool CleanExit = true;
Sam McCall2c30fbc2018-10-18 12:32:04 +00001178 if (auto Err = Transp.loop(*MsgHandler)) {
Sam McCalldc8f3cf2018-10-17 07:32:05 +00001179 elog("Transport error: {0}", std::move(Err));
1180 CleanExit = false;
1181 }
Ilya Biryukovafb55542017-05-16 14:40:30 +00001182
Ilya Biryukov652364b2018-09-26 05:48:29 +00001183 // Destroy ClangdServer to ensure all worker threads finish.
1184 Server.reset();
Sam McCalldc8f3cf2018-10-17 07:32:05 +00001185 return CleanExit && ShutdownRequestReceived;
Ilya Biryukov38d79772017-05-16 09:38:59 +00001186}
1187
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001188std::vector<Fix> ClangdLSPServer::getFixes(llvm::StringRef File,
Ilya Biryukov71028b82018-03-12 15:28:22 +00001189 const clangd::Diagnostic &D) {
Ilya Biryukov38d79772017-05-16 09:38:59 +00001190 std::lock_guard<std::mutex> Lock(FixItsMutex);
1191 auto DiagToFixItsIter = FixItsMap.find(File);
1192 if (DiagToFixItsIter == FixItsMap.end())
1193 return {};
1194
1195 const auto &DiagToFixItsMap = DiagToFixItsIter->second;
1196 auto FixItsIter = DiagToFixItsMap.find(D);
1197 if (FixItsIter == DiagToFixItsMap.end())
1198 return {};
1199
1200 return FixItsIter->second;
1201}
1202
Ilya Biryukovb0826bd2019-01-03 13:37:12 +00001203bool ClangdLSPServer::shouldRunCompletion(
1204 const CompletionParams &Params) const {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001205 llvm::StringRef Trigger = Params.context.triggerCharacter;
Ilya Biryukovb0826bd2019-01-03 13:37:12 +00001206 if (Params.context.triggerKind != CompletionTriggerKind::TriggerCharacter ||
1207 (Trigger != ">" && Trigger != ":"))
1208 return true;
1209
1210 auto Code = DraftMgr.getDraft(Params.textDocument.uri.file());
1211 if (!Code)
1212 return true; // completion code will log the error for untracked doc.
1213
1214 // A completion request is sent when the user types '>' or ':', but we only
1215 // want to trigger on '->' and '::'. We check the preceeding character to make
1216 // sure it matches what we expected.
1217 // Running the lexer here would be more robust (e.g. we can detect comments
1218 // and avoid triggering completion there), but we choose to err on the side
1219 // of simplicity here.
1220 auto Offset = positionToOffset(*Code, Params.position,
1221 /*AllowColumnsBeyondLineLength=*/false);
1222 if (!Offset) {
1223 vlog("could not convert position '{0}' to offset for file '{1}'",
1224 Params.position, Params.textDocument.uri.file());
1225 return true;
1226 }
1227 if (*Offset < 2)
1228 return false;
1229
1230 if (Trigger == ">")
1231 return (*Code)[*Offset - 2] == '-'; // trigger only on '->'.
1232 if (Trigger == ":")
1233 return (*Code)[*Offset - 2] == ':'; // trigger only on '::'.
1234 assert(false && "unhandled trigger character");
1235 return true;
1236}
1237
Johan Vikstroma848dab2019-07-04 07:53:12 +00001238void ClangdLSPServer::onHighlightingsReady(
Haojian Wu0a6000f2019-08-26 08:38:45 +00001239 PathRef File, std::vector<HighlightingToken> Highlightings) {
Johan Vikstromc2653ef22019-08-01 08:08:44 +00001240 std::vector<HighlightingToken> Old;
1241 std::vector<HighlightingToken> HighlightingsCopy = Highlightings;
1242 {
1243 std::lock_guard<std::mutex> Lock(HighlightingsMutex);
1244 Old = std::move(FileToHighlightings[File]);
1245 FileToHighlightings[File] = std::move(HighlightingsCopy);
1246 }
1247 // LSP allows us to send incremental edits of highlightings. Also need to diff
1248 // to remove highlightings from tokens that should no longer have them.
Haojian Wu0a6000f2019-08-26 08:38:45 +00001249 std::vector<LineHighlightings> Diffed = diffHighlightings(Highlightings, Old);
Johan Vikstroma848dab2019-07-04 07:53:12 +00001250 publishSemanticHighlighting(
1251 {{URIForFile::canonicalize(File, /*TUPath=*/File)},
Johan Vikstromc2653ef22019-08-01 08:08:44 +00001252 toSemanticHighlightingInformation(Diffed)});
Johan Vikstroma848dab2019-07-04 07:53:12 +00001253}
1254
Sam McCalla7bb0cc2018-03-12 23:22:35 +00001255void ClangdLSPServer::onDiagnosticsReady(PathRef File,
1256 std::vector<Diag> Diagnostics) {
Eric Liu4d814a92018-11-28 10:30:42 +00001257 auto URI = URIForFile::canonicalize(File, /*TUPath=*/File);
Sam McCall16e70702018-10-24 07:59:38 +00001258 std::vector<Diagnostic> LSPDiagnostics;
Ilya Biryukov38d79772017-05-16 09:38:59 +00001259 DiagnosticToReplacementMap LocalFixIts; // Temporary storage
Sam McCalla7bb0cc2018-03-12 23:22:35 +00001260 for (auto &Diag : Diagnostics) {
Sam McCall16e70702018-10-24 07:59:38 +00001261 toLSPDiags(Diag, URI, DiagOpts,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001262 [&](clangd::Diagnostic Diag, llvm::ArrayRef<Fix> Fixes) {
Sam McCall16e70702018-10-24 07:59:38 +00001263 auto &FixItsForDiagnostic = LocalFixIts[Diag];
1264 llvm::copy(Fixes, std::back_inserter(FixItsForDiagnostic));
1265 LSPDiagnostics.push_back(std::move(Diag));
1266 });
Ilya Biryukov38d79772017-05-16 09:38:59 +00001267 }
1268
1269 // Cache FixIts
1270 {
Ilya Biryukov38d79772017-05-16 09:38:59 +00001271 std::lock_guard<std::mutex> Lock(FixItsMutex);
1272 FixItsMap[File] = LocalFixIts;
1273 }
1274
Ilya Biryukov49c10712019-03-25 10:15:11 +00001275 // Send a notification to the LSP client.
1276 publishDiagnostics(URI, std::move(LSPDiagnostics));
Ilya Biryukov38d79772017-05-16 09:38:59 +00001277}
Simon Marchi9569fd52018-03-16 14:30:42 +00001278
Haojian Wub6188492018-12-20 15:39:12 +00001279void ClangdLSPServer::onFileUpdated(PathRef File, const TUStatus &Status) {
1280 if (!SupportFileStatus)
1281 return;
1282 // FIXME: we don't emit "BuildingFile" and `RunningAction`, as these
1283 // two statuses are running faster in practice, which leads the UI constantly
1284 // changing, and doesn't provide much value. We may want to emit status at a
1285 // reasonable time interval (e.g. 0.5s).
1286 if (Status.Action.S == TUAction::BuildingFile ||
1287 Status.Action.S == TUAction::RunningAction)
1288 return;
1289 notify("textDocument/clangd.fileStatus", Status.render(File));
1290}
1291
Simon Marchi9569fd52018-03-16 14:30:42 +00001292void ClangdLSPServer::reparseOpenedFiles() {
1293 for (const Path &FilePath : DraftMgr.getActiveFiles())
Ilya Biryukov652364b2018-09-26 05:48:29 +00001294 Server->addDocument(FilePath, *DraftMgr.getDraft(FilePath),
1295 WantDiagnostics::Auto);
Simon Marchi9569fd52018-03-16 14:30:42 +00001296}
Alex Lorenzf8087862018-08-01 17:39:29 +00001297
Sam McCallc008af62018-10-20 15:30:37 +00001298} // namespace clangd
1299} // namespace clang