blob: f58bfaf996481779a09a0d5be87b85727655f31c [file] [log] [blame]
Ilya Biryukov38d79772017-05-16 09:38:59 +00001//===--- ClangdLSPServer.cpp - LSP server ------------------------*- C++-*-===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Ilya Biryukov38d79772017-05-16 09:38:59 +00006//
Kirill Bobyrev8e35f1e2018-08-14 16:03:32 +00007//===----------------------------------------------------------------------===//
Ilya Biryukov38d79772017-05-16 09:38:59 +00008
9#include "ClangdLSPServer.h"
Kadir Cetinkaya9d662472019-10-15 14:20:52 +000010#include "Context.h"
Ilya Biryukov71028b82018-03-12 15:28:22 +000011#include "Diagnostics.h"
Kadir Cetinkaya5b270932019-09-09 12:28:44 +000012#include "DraftStore.h"
Ilya Biryukovf9169d02019-05-29 10:01:00 +000013#include "FormattedString.h"
Kadir Cetinkaya256247c2019-06-26 07:45:27 +000014#include "GlobalCompilationDatabase.h"
Ilya Biryukovcce67a32019-01-29 14:17:36 +000015#include "Protocol.h"
Johan Vikstroma848dab2019-07-04 07:53:12 +000016#include "SemanticHighlighting.h"
Sam McCallb536a2a2017-12-19 12:23:48 +000017#include "SourceCode.h"
Kadir Cetinkaya6b850322020-03-17 19:08:23 +010018#include "TUScheduler.h"
Sam McCall2c30fbc2018-10-18 12:32:04 +000019#include "Trace.h"
Eric Liu78ed91a72018-01-29 15:37:46 +000020#include "URI.h"
Sam McCall395fde72019-06-18 13:37:54 +000021#include "refactor/Tweak.h"
Sam McCall6f7dca92020-03-03 12:25:46 +010022#include "clang/Basic/Version.h"
Ilya Biryukovcce67a32019-01-29 14:17:36 +000023#include "clang/Tooling/Core/Replacement.h"
Kadir Cetinkaya256247c2019-06-26 07:45:27 +000024#include "llvm/ADT/ArrayRef.h"
Sam McCalla69698f2019-03-27 17:47:49 +000025#include "llvm/ADT/Optional.h"
Kadir Cetinkaya689bf932018-08-24 13:09:41 +000026#include "llvm/ADT/ScopeExit.h"
Kadir Cetinkaya5b270932019-09-09 12:28:44 +000027#include "llvm/ADT/StringRef.h"
Utkarsh Saxena55925da2019-09-24 13:38:33 +000028#include "llvm/ADT/iterator_range.h"
Simon Marchi9569fd52018-03-16 14:30:42 +000029#include "llvm/Support/Errc.h"
Ilya Biryukovcce67a32019-01-29 14:17:36 +000030#include "llvm/Support/Error.h"
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +000031#include "llvm/Support/FormatVariadic.h"
Utkarsh Saxena55925da2019-09-24 13:38:33 +000032#include "llvm/Support/JSON.h"
Eric Liu5740ff52018-01-31 16:26:27 +000033#include "llvm/Support/Path.h"
Kadir Cetinkaya5b270932019-09-09 12:28:44 +000034#include "llvm/Support/SHA1.h"
Sam McCall2c30fbc2018-10-18 12:32:04 +000035#include "llvm/Support/ScopedPrinter.h"
Kadir Cetinkaya5b270932019-09-09 12:28:44 +000036#include <cstddef>
Utkarsh Saxena55925da2019-09-24 13:38:33 +000037#include <memory>
Sam McCall7d20e802020-01-22 19:41:45 +010038#include <mutex>
Kadir Cetinkaya5b270932019-09-09 12:28:44 +000039#include <string>
Utkarsh Saxena55925da2019-09-24 13:38:33 +000040#include <vector>
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +000041
Sam McCallc008af62018-10-20 15:30:37 +000042namespace clang {
43namespace clangd {
Ilya Biryukovafb55542017-05-16 14:40:30 +000044namespace {
Sam McCall2cd33e62020-03-04 00:33:29 +010045
46// LSP defines file versions as numbers that increase.
47// ClangdServer treats them as opaque and therefore uses strings instead.
48std::string encodeVersion(int64_t LSPVersion) {
49 return llvm::to_string(LSPVersion);
50}
51llvm::Optional<int64_t> decodeVersion(llvm::StringRef Encoded) {
52 int64_t Result;
53 if (llvm::to_integer(Encoded, Result, 10))
54 return Result;
55 else if (!Encoded.empty()) // Empty can be e.g. diagnostics on close.
56 elog("unexpected non-numeric version {0}", Encoded);
57 return llvm::None;
58}
59
Ilya Biryukovcce67a32019-01-29 14:17:36 +000060/// Transforms a tweak into a code action that would apply it if executed.
61/// EXPECTS: T.prepare() was called and returned true.
62CodeAction toCodeAction(const ClangdServer::TweakRef &T, const URIForFile &File,
63 Range Selection) {
64 CodeAction CA;
65 CA.title = T.Title;
Sam McCall395fde72019-06-18 13:37:54 +000066 switch (T.Intent) {
67 case Tweak::Refactor:
Benjamin Krameradcd0262020-01-28 20:23:46 +010068 CA.kind = std::string(CodeAction::REFACTOR_KIND);
Sam McCall395fde72019-06-18 13:37:54 +000069 break;
70 case Tweak::Info:
Benjamin Krameradcd0262020-01-28 20:23:46 +010071 CA.kind = std::string(CodeAction::INFO_KIND);
Sam McCall395fde72019-06-18 13:37:54 +000072 break;
73 }
Ilya Biryukovcce67a32019-01-29 14:17:36 +000074 // This tweak may have an expensive second stage, we only run it if the user
75 // actually chooses it in the UI. We reply with a command that would run the
76 // corresponding tweak.
77 // FIXME: for some tweaks, computing the edits is cheap and we could send them
78 // directly.
79 CA.command.emplace();
80 CA.command->title = T.Title;
Benjamin Krameradcd0262020-01-28 20:23:46 +010081 CA.command->command = std::string(Command::CLANGD_APPLY_TWEAK);
Ilya Biryukovcce67a32019-01-29 14:17:36 +000082 CA.command->tweakArgs.emplace();
83 CA.command->tweakArgs->file = File;
84 CA.command->tweakArgs->tweakID = T.ID;
85 CA.command->tweakArgs->selection = Selection;
86 return CA;
Simon Pilgrime9a136b2019-02-03 14:08:30 +000087}
Ilya Biryukovcce67a32019-01-29 14:17:36 +000088
Ilya Biryukov19d75602018-11-23 15:21:19 +000089void adjustSymbolKinds(llvm::MutableArrayRef<DocumentSymbol> Syms,
90 SymbolKindBitset Kinds) {
91 for (auto &S : Syms) {
92 S.kind = adjustKindToCapability(S.kind, Kinds);
93 adjustSymbolKinds(S.children, Kinds);
94 }
95}
96
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +000097SymbolKindBitset defaultSymbolKinds() {
98 SymbolKindBitset Defaults;
99 for (size_t I = SymbolKindMin; I <= static_cast<size_t>(SymbolKind::Array);
100 ++I)
101 Defaults.set(I);
102 return Defaults;
103}
104
Kadir Cetinkaya133d46f2018-09-27 17:13:07 +0000105CompletionItemKindBitset defaultCompletionItemKinds() {
106 CompletionItemKindBitset Defaults;
107 for (size_t I = CompletionItemKindMin;
108 I <= static_cast<size_t>(CompletionItemKind::Reference); ++I)
109 Defaults.set(I);
110 return Defaults;
111}
112
Haojian Wu1ca2ee42019-07-04 12:27:21 +0000113// Build a lookup table (HighlightingKind => {TextMate Scopes}), which is sent
114// to the LSP client.
115std::vector<std::vector<std::string>> buildHighlightScopeLookupTable() {
116 std::vector<std::vector<std::string>> LookupTable;
117 // HighlightingKind is using as the index.
Ilya Biryukov63d5d162019-09-09 08:57:17 +0000118 for (int KindValue = 0; KindValue <= (int)HighlightingKind::LastKind;
Haojian Wu1ca2ee42019-07-04 12:27:21 +0000119 ++KindValue)
Benjamin Krameradcd0262020-01-28 20:23:46 +0100120 LookupTable.push_back(
121 {std::string(toTextMateScope((HighlightingKind)(KindValue)))});
Haojian Wu1ca2ee42019-07-04 12:27:21 +0000122 return LookupTable;
123}
124
Haojian Wu852bafa2019-10-23 14:40:20 +0200125// Makes sure edits in \p FE are applicable to latest file contents reported by
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000126// editor. If not generates an error message containing information about files
127// that needs to be saved.
Haojian Wu852bafa2019-10-23 14:40:20 +0200128llvm::Error validateEdits(const DraftStore &DraftMgr, const FileEdits &FE) {
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000129 size_t InvalidFileCount = 0;
130 llvm::StringRef LastInvalidFile;
Haojian Wu852bafa2019-10-23 14:40:20 +0200131 for (const auto &It : FE) {
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000132 if (auto Draft = DraftMgr.getDraft(It.first())) {
133 // If the file is open in user's editor, make sure the version we
134 // saw and current version are compatible as this is the text that
135 // will be replaced by editors.
Sam McCallcaf5a4d2020-03-03 15:57:39 +0100136 if (!It.second.canApplyTo(Draft->Contents)) {
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000137 ++InvalidFileCount;
138 LastInvalidFile = It.first();
139 }
140 }
141 }
142 if (!InvalidFileCount)
143 return llvm::Error::success();
144 if (InvalidFileCount == 1)
145 return llvm::createStringError(llvm::inconvertibleErrorCode(),
146 "File must be saved first: " +
147 LastInvalidFile);
148 return llvm::createStringError(
149 llvm::inconvertibleErrorCode(),
150 "Files must be saved first: " + LastInvalidFile + " (and " +
151 llvm::to_string(InvalidFileCount - 1) + " others)");
152}
153
Ilya Biryukovafb55542017-05-16 14:40:30 +0000154} // namespace
155
Sam McCall2c30fbc2018-10-18 12:32:04 +0000156// MessageHandler dispatches incoming LSP messages.
157// It handles cross-cutting concerns:
158// - serializes/deserializes protocol objects to JSON
159// - logging of inbound messages
160// - cancellation handling
161// - basic call tracing
Sam McCall3d0adbe2018-10-18 14:41:50 +0000162// MessageHandler ensures that initialize() is called before any other handler.
Sam McCall2c30fbc2018-10-18 12:32:04 +0000163class ClangdLSPServer::MessageHandler : public Transport::MessageHandler {
164public:
165 MessageHandler(ClangdLSPServer &Server) : Server(Server) {}
166
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000167 bool onNotify(llvm::StringRef Method, llvm::json::Value Params) override {
Sam McCalla69698f2019-03-27 17:47:49 +0000168 WithContext HandlerContext(handlerContext());
Sam McCall2c30fbc2018-10-18 12:32:04 +0000169 log("<-- {0}", Method);
170 if (Method == "exit")
171 return false;
Sam McCall3d0adbe2018-10-18 14:41:50 +0000172 if (!Server.Server)
173 elog("Notification {0} before initialization", Method);
174 else if (Method == "$/cancelRequest")
Sam McCall2c30fbc2018-10-18 12:32:04 +0000175 onCancel(std::move(Params));
176 else if (auto Handler = Notifications.lookup(Method))
177 Handler(std::move(Params));
178 else
179 log("unhandled notification {0}", Method);
180 return true;
181 }
182
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000183 bool onCall(llvm::StringRef Method, llvm::json::Value Params,
184 llvm::json::Value ID) override {
Sam McCalla69698f2019-03-27 17:47:49 +0000185 WithContext HandlerContext(handlerContext());
Sam McCalle2f3a732018-10-24 14:26:26 +0000186 // Calls can be canceled by the client. Add cancellation context.
187 WithContext WithCancel(cancelableRequestContext(ID));
188 trace::Span Tracer(Method);
189 SPAN_ATTACH(Tracer, "Params", Params);
190 ReplyOnce Reply(ID, Method, &Server, Tracer.Args);
Sam McCall2c30fbc2018-10-18 12:32:04 +0000191 log("<-- {0}({1})", Method, ID);
Sam McCall3d0adbe2018-10-18 14:41:50 +0000192 if (!Server.Server && Method != "initialize") {
193 elog("Call {0} before initialization.", Method);
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000194 Reply(llvm::make_error<LSPError>("server not initialized",
195 ErrorCode::ServerNotInitialized));
Sam McCall3d0adbe2018-10-18 14:41:50 +0000196 } else if (auto Handler = Calls.lookup(Method))
Sam McCalle2f3a732018-10-24 14:26:26 +0000197 Handler(std::move(Params), std::move(Reply));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000198 else
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000199 Reply(llvm::make_error<LSPError>("method not found",
200 ErrorCode::MethodNotFound));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000201 return true;
202 }
203
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000204 bool onReply(llvm::json::Value ID,
205 llvm::Expected<llvm::json::Value> Result) override {
Sam McCalla69698f2019-03-27 17:47:49 +0000206 WithContext HandlerContext(handlerContext());
Haojian Wuf2516342019-08-05 12:48:09 +0000207
208 Callback<llvm::json::Value> ReplyHandler = nullptr;
209 if (auto IntID = ID.getAsInteger()) {
210 std::lock_guard<std::mutex> Mutex(CallMutex);
211 // Find a corresponding callback for the request ID;
212 for (size_t Index = 0; Index < ReplyCallbacks.size(); ++Index) {
213 if (ReplyCallbacks[Index].first == *IntID) {
214 ReplyHandler = std::move(ReplyCallbacks[Index].second);
215 ReplyCallbacks.erase(ReplyCallbacks.begin() +
216 Index); // remove the entry
217 break;
218 }
219 }
220 }
221
222 if (!ReplyHandler) {
223 // No callback being found, use a default log callback.
224 ReplyHandler = [&ID](llvm::Expected<llvm::json::Value> Result) {
225 elog("received a reply with ID {0}, but there was no such call", ID);
226 if (!Result)
227 llvm::consumeError(Result.takeError());
228 };
229 }
230
231 // Log and run the reply handler.
232 if (Result) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000233 log("<-- reply({0})", ID);
Haojian Wuf2516342019-08-05 12:48:09 +0000234 ReplyHandler(std::move(Result));
235 } else {
236 auto Err = Result.takeError();
237 log("<-- reply({0}) error: {1}", ID, Err);
238 ReplyHandler(std::move(Err));
239 }
Sam McCall2c30fbc2018-10-18 12:32:04 +0000240 return true;
241 }
242
243 // Bind an LSP method name to a call.
Sam McCalle2f3a732018-10-24 14:26:26 +0000244 template <typename Param, typename Result>
Sam McCall2c30fbc2018-10-18 12:32:04 +0000245 void bind(const char *Method,
Sam McCalle2f3a732018-10-24 14:26:26 +0000246 void (ClangdLSPServer::*Handler)(const Param &, Callback<Result>)) {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000247 Calls[Method] = [Method, Handler, this](llvm::json::Value RawParams,
Sam McCalle2f3a732018-10-24 14:26:26 +0000248 ReplyOnce Reply) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000249 Param P;
Sam McCalle2f3a732018-10-24 14:26:26 +0000250 if (fromJSON(RawParams, P)) {
251 (Server.*Handler)(P, std::move(Reply));
252 } else {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000253 elog("Failed to decode {0} request.", Method);
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000254 Reply(llvm::make_error<LSPError>("failed to decode request",
255 ErrorCode::InvalidRequest));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000256 }
Sam McCall2c30fbc2018-10-18 12:32:04 +0000257 };
258 }
259
Haojian Wuf2516342019-08-05 12:48:09 +0000260 // Bind a reply callback to a request. The callback will be invoked when
261 // clangd receives the reply from the LSP client.
262 // Return a call id of the request.
263 llvm::json::Value bindReply(Callback<llvm::json::Value> Reply) {
264 llvm::Optional<std::pair<int, Callback<llvm::json::Value>>> OldestCB;
265 int ID;
266 {
267 std::lock_guard<std::mutex> Mutex(CallMutex);
268 ID = NextCallID++;
269 ReplyCallbacks.emplace_back(ID, std::move(Reply));
270
271 // If the queue overflows, we assume that the client didn't reply the
272 // oldest request, and run the corresponding callback which replies an
273 // error to the client.
274 if (ReplyCallbacks.size() > MaxReplayCallbacks) {
275 elog("more than {0} outstanding LSP calls, forgetting about {1}",
276 MaxReplayCallbacks, ReplyCallbacks.front().first);
277 OldestCB = std::move(ReplyCallbacks.front());
278 ReplyCallbacks.pop_front();
279 }
280 }
281 if (OldestCB)
282 OldestCB->second(llvm::createStringError(
283 llvm::inconvertibleErrorCode(),
284 llvm::formatv("failed to receive a client reply for request ({0})",
285 OldestCB->first)));
286 return ID;
287 }
288
Sam McCall2c30fbc2018-10-18 12:32:04 +0000289 // Bind an LSP method name to a notification.
290 template <typename Param>
291 void bind(const char *Method,
292 void (ClangdLSPServer::*Handler)(const Param &)) {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000293 Notifications[Method] = [Method, Handler,
294 this](llvm::json::Value RawParams) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000295 Param P;
296 if (!fromJSON(RawParams, P)) {
297 elog("Failed to decode {0} request.", Method);
298 return;
299 }
300 trace::Span Tracer(Method);
301 SPAN_ATTACH(Tracer, "Params", RawParams);
302 (Server.*Handler)(P);
303 };
304 }
305
306private:
Sam McCalle2f3a732018-10-24 14:26:26 +0000307 // Function object to reply to an LSP call.
308 // Each instance must be called exactly once, otherwise:
309 // - the bug is logged, and (in debug mode) an assert will fire
310 // - if there was no reply, an error reply is sent
311 // - if there were multiple replies, only the first is sent
312 class ReplyOnce {
313 std::atomic<bool> Replied = {false};
Sam McCalld7babe42018-10-24 15:18:40 +0000314 std::chrono::steady_clock::time_point Start;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000315 llvm::json::Value ID;
Sam McCalle2f3a732018-10-24 14:26:26 +0000316 std::string Method;
317 ClangdLSPServer *Server; // Null when moved-from.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000318 llvm::json::Object *TraceArgs;
Sam McCalle2f3a732018-10-24 14:26:26 +0000319
320 public:
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000321 ReplyOnce(const llvm::json::Value &ID, llvm::StringRef Method,
322 ClangdLSPServer *Server, llvm::json::Object *TraceArgs)
Sam McCalld7babe42018-10-24 15:18:40 +0000323 : Start(std::chrono::steady_clock::now()), ID(ID), Method(Method),
324 Server(Server), TraceArgs(TraceArgs) {
Sam McCalle2f3a732018-10-24 14:26:26 +0000325 assert(Server);
326 }
327 ReplyOnce(ReplyOnce &&Other)
Sam McCalld7babe42018-10-24 15:18:40 +0000328 : Replied(Other.Replied.load()), Start(Other.Start),
329 ID(std::move(Other.ID)), Method(std::move(Other.Method)),
330 Server(Other.Server), TraceArgs(Other.TraceArgs) {
Sam McCalle2f3a732018-10-24 14:26:26 +0000331 Other.Server = nullptr;
332 }
Ilya Biryukov22fa4652019-01-03 13:28:05 +0000333 ReplyOnce &operator=(ReplyOnce &&) = delete;
Sam McCalle2f3a732018-10-24 14:26:26 +0000334 ReplyOnce(const ReplyOnce &) = delete;
Ilya Biryukov22fa4652019-01-03 13:28:05 +0000335 ReplyOnce &operator=(const ReplyOnce &) = delete;
Sam McCalle2f3a732018-10-24 14:26:26 +0000336
337 ~ReplyOnce() {
Haojian Wuf2516342019-08-05 12:48:09 +0000338 // There's one legitimate reason to never reply to a request: clangd's
339 // request handler send a call to the client (e.g. applyEdit) and the
340 // client never replied. In this case, the ReplyOnce is owned by
341 // ClangdLSPServer's reply callback table and is destroyed along with the
342 // server. We don't attempt to send a reply in this case, there's little
343 // to be gained from doing so.
344 if (Server && !Server->IsBeingDestroyed && !Replied) {
Sam McCalle2f3a732018-10-24 14:26:26 +0000345 elog("No reply to message {0}({1})", Method, ID);
346 assert(false && "must reply to all calls!");
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000347 (*this)(llvm::make_error<LSPError>("server failed to reply",
348 ErrorCode::InternalError));
Sam McCalle2f3a732018-10-24 14:26:26 +0000349 }
350 }
351
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000352 void operator()(llvm::Expected<llvm::json::Value> Reply) {
Sam McCalle2f3a732018-10-24 14:26:26 +0000353 assert(Server && "moved-from!");
354 if (Replied.exchange(true)) {
355 elog("Replied twice to message {0}({1})", Method, ID);
356 assert(false && "must reply to each call only once!");
357 return;
358 }
Sam McCalld7babe42018-10-24 15:18:40 +0000359 auto Duration = std::chrono::steady_clock::now() - Start;
360 if (Reply) {
361 log("--> reply:{0}({1}) {2:ms}", Method, ID, Duration);
362 if (TraceArgs)
Sam McCalle2f3a732018-10-24 14:26:26 +0000363 (*TraceArgs)["Reply"] = *Reply;
Sam McCalld7babe42018-10-24 15:18:40 +0000364 std::lock_guard<std::mutex> Lock(Server->TranspWriter);
365 Server->Transp.reply(std::move(ID), std::move(Reply));
366 } else {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000367 llvm::Error Err = Reply.takeError();
Sam McCalld7babe42018-10-24 15:18:40 +0000368 log("--> reply:{0}({1}) {2:ms}, error: {3}", Method, ID, Duration, Err);
369 if (TraceArgs)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000370 (*TraceArgs)["Error"] = llvm::to_string(Err);
Sam McCalld7babe42018-10-24 15:18:40 +0000371 std::lock_guard<std::mutex> Lock(Server->TranspWriter);
372 Server->Transp.reply(std::move(ID), std::move(Err));
Sam McCalle2f3a732018-10-24 14:26:26 +0000373 }
Sam McCalle2f3a732018-10-24 14:26:26 +0000374 }
375 };
376
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000377 llvm::StringMap<std::function<void(llvm::json::Value)>> Notifications;
378 llvm::StringMap<std::function<void(llvm::json::Value, ReplyOnce)>> Calls;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000379
380 // Method calls may be cancelled by ID, so keep track of their state.
381 // This needs a mutex: handlers may finish on a different thread, and that's
382 // when we clean up entries in the map.
383 mutable std::mutex RequestCancelersMutex;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000384 llvm::StringMap<std::pair<Canceler, /*Cookie*/ unsigned>> RequestCancelers;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000385 unsigned NextRequestCookie = 0; // To disambiguate reused IDs, see below.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000386 void onCancel(const llvm::json::Value &Params) {
387 const llvm::json::Value *ID = nullptr;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000388 if (auto *O = Params.getAsObject())
389 ID = O->get("id");
390 if (!ID) {
391 elog("Bad cancellation request: {0}", Params);
392 return;
393 }
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000394 auto StrID = llvm::to_string(*ID);
Sam McCall2c30fbc2018-10-18 12:32:04 +0000395 std::lock_guard<std::mutex> Lock(RequestCancelersMutex);
396 auto It = RequestCancelers.find(StrID);
397 if (It != RequestCancelers.end())
398 It->second.first(); // Invoke the canceler.
399 }
Sam McCalla69698f2019-03-27 17:47:49 +0000400
401 Context handlerContext() const {
402 return Context::current().derive(
403 kCurrentOffsetEncoding,
404 Server.NegotiatedOffsetEncoding.getValueOr(OffsetEncoding::UTF16));
405 }
406
Sam McCall2c30fbc2018-10-18 12:32:04 +0000407 // We run cancelable requests in a context that does two things:
408 // - allows cancellation using RequestCancelers[ID]
409 // - cleans up the entry in RequestCancelers when it's no longer needed
410 // If a client reuses an ID, the last wins and the first cannot be canceled.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000411 Context cancelableRequestContext(const llvm::json::Value &ID) {
Sam McCall31db1e02020-04-11 18:19:50 +0200412 auto Task = cancelableTask(
413 /*Reason=*/static_cast<int>(ErrorCode::RequestCancelled));
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000414 auto StrID = llvm::to_string(ID); // JSON-serialize ID for map key.
Sam McCall2c30fbc2018-10-18 12:32:04 +0000415 auto Cookie = NextRequestCookie++; // No lock, only called on main thread.
416 {
417 std::lock_guard<std::mutex> Lock(RequestCancelersMutex);
418 RequestCancelers[StrID] = {std::move(Task.second), Cookie};
419 }
420 // When the request ends, we can clean up the entry we just added.
421 // The cookie lets us check that it hasn't been overwritten due to ID
422 // reuse.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000423 return Task.first.derive(llvm::make_scope_exit([this, StrID, Cookie] {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000424 std::lock_guard<std::mutex> Lock(RequestCancelersMutex);
425 auto It = RequestCancelers.find(StrID);
426 if (It != RequestCancelers.end() && It->second.second == Cookie)
427 RequestCancelers.erase(It);
428 }));
429 }
430
Kadir Cetinkaya9a3a87d2019-10-09 13:59:31 +0000431 // The maximum number of callbacks held in clangd.
432 //
433 // We bound the maximum size to the pending map to prevent memory leakage
434 // for cases where LSP clients don't reply for the request.
435 // This has to go after RequestCancellers and RequestCancellersMutex since it
436 // can contain a callback that has a cancelable context.
437 static constexpr int MaxReplayCallbacks = 100;
438 mutable std::mutex CallMutex;
439 int NextCallID = 0; /* GUARDED_BY(CallMutex) */
440 std::deque<std::pair</*RequestID*/ int,
441 /*ReplyHandler*/ Callback<llvm::json::Value>>>
442 ReplyCallbacks; /* GUARDED_BY(CallMutex) */
443
Sam McCall2c30fbc2018-10-18 12:32:04 +0000444 ClangdLSPServer &Server;
445};
Haojian Wuf2516342019-08-05 12:48:09 +0000446constexpr int ClangdLSPServer::MessageHandler::MaxReplayCallbacks;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000447
448// call(), notify(), and reply() wrap the Transport, adding logging and locking.
Haojian Wuf2516342019-08-05 12:48:09 +0000449void ClangdLSPServer::callRaw(StringRef Method, llvm::json::Value Params,
450 Callback<llvm::json::Value> CB) {
451 auto ID = MsgHandler->bindReply(std::move(CB));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000452 log("--> {0}({1})", Method, ID);
Sam McCall2c30fbc2018-10-18 12:32:04 +0000453 std::lock_guard<std::mutex> Lock(TranspWriter);
454 Transp.call(Method, std::move(Params), ID);
455}
456
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000457void ClangdLSPServer::notify(llvm::StringRef Method, llvm::json::Value Params) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000458 log("--> {0}", Method);
459 std::lock_guard<std::mutex> Lock(TranspWriter);
460 Transp.notify(Method, std::move(Params));
461}
462
Sam McCall71177ac2020-03-24 02:24:47 +0100463static std::vector<llvm::StringRef> semanticTokenTypes() {
464 std::vector<llvm::StringRef> Types;
465 for (unsigned I = 0; I <= static_cast<unsigned>(HighlightingKind::LastKind);
466 ++I)
467 Types.push_back(toSemanticTokenType(static_cast<HighlightingKind>(I)));
468 return Types;
469}
470
Sam McCall2c30fbc2018-10-18 12:32:04 +0000471void ClangdLSPServer::onInitialize(const InitializeParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000472 Callback<llvm::json::Value> Reply) {
Sam McCalla69698f2019-03-27 17:47:49 +0000473 // Determine character encoding first as it affects constructed ClangdServer.
474 if (Params.capabilities.offsetEncoding && !NegotiatedOffsetEncoding) {
475 NegotiatedOffsetEncoding = OffsetEncoding::UTF16; // fallback
476 for (OffsetEncoding Supported : *Params.capabilities.offsetEncoding)
477 if (Supported != OffsetEncoding::UnsupportedEncoding) {
478 NegotiatedOffsetEncoding = Supported;
479 break;
480 }
481 }
Sam McCalla69698f2019-03-27 17:47:49 +0000482
Sam McCalledf6a192020-03-24 00:31:14 +0100483 ClangdServerOpts.TheiaSemanticHighlighting =
484 Params.capabilities.TheiaSemanticHighlighting;
Sam McCallfc830102020-04-01 12:02:28 +0200485 if (Params.capabilities.TheiaSemanticHighlighting &&
486 Params.capabilities.SemanticTokens) {
487 log("Client supports legacy semanticHighlights notification and standard "
488 "semanticTokens request, choosing the latter (no notifications).");
489 ClangdServerOpts.TheiaSemanticHighlighting = false;
490 }
491
Sam McCall0d9b40f2018-10-19 15:42:23 +0000492 if (Params.rootUri && *Params.rootUri)
Benjamin Krameradcd0262020-01-28 20:23:46 +0100493 ClangdServerOpts.WorkspaceRoot = std::string(Params.rootUri->file());
Sam McCall0d9b40f2018-10-19 15:42:23 +0000494 else if (Params.rootPath && !Params.rootPath->empty())
495 ClangdServerOpts.WorkspaceRoot = *Params.rootPath;
Sam McCall3d0adbe2018-10-18 14:41:50 +0000496 if (Server)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000497 return Reply(llvm::make_error<LSPError>("server already initialized",
498 ErrorCode::InvalidRequest));
Sam McCallbc904612018-10-25 04:22:52 +0000499 if (const auto &Dir = Params.initializationOptions.compilationDatabasePath)
500 CompileCommandsDir = Dir;
Kadir Cetinkaya256247c2019-06-26 07:45:27 +0000501 if (UseDirBasedCDB) {
Jonas Devlieghere1c705d92019-08-14 23:52:23 +0000502 BaseCDB = std::make_unique<DirectoryBasedGlobalCompilationDatabase>(
Sam McCallc55d09a2018-11-02 13:09:36 +0000503 CompileCommandsDir);
Kadir Cetinkaya256247c2019-06-26 07:45:27 +0000504 BaseCDB = getQueryDriverDatabase(
505 llvm::makeArrayRef(ClangdServerOpts.QueryDriverGlobs),
506 std::move(BaseCDB));
507 }
Sam McCall99768b22019-11-29 19:37:48 +0100508 auto Mangler = CommandMangler::detect();
509 if (ClangdServerOpts.ResourceDir)
510 Mangler.ResourceDir = *ClangdServerOpts.ResourceDir;
Kadir Cetinkayabe6b35d2019-01-22 09:10:20 +0000511 CDB.emplace(BaseCDB.get(), Params.initializationOptions.fallbackFlags,
Sam McCall99768b22019-11-29 19:37:48 +0100512 tooling::ArgumentsAdjuster(Mangler));
Kadir Cetinkaya9d662472019-10-15 14:20:52 +0000513 {
514 // Switch caller's context with LSPServer's background context. Since we
515 // rather want to propagate information from LSPServer's context into the
516 // Server, CDB, etc.
517 WithContext MainContext(BackgroundContext.clone());
518 llvm::Optional<WithContextValue> WithOffsetEncoding;
519 if (NegotiatedOffsetEncoding)
520 WithOffsetEncoding.emplace(kCurrentOffsetEncoding,
521 *NegotiatedOffsetEncoding);
Sam McCall6ef1cce2020-01-24 14:08:56 +0100522 Server.emplace(*CDB, FSProvider, ClangdServerOpts,
523 static_cast<ClangdServer::Callbacks *>(this));
Kadir Cetinkaya9d662472019-10-15 14:20:52 +0000524 }
Sam McCallbc904612018-10-25 04:22:52 +0000525 applyConfiguration(Params.initializationOptions.ConfigSettings);
Simon Marchi88016782018-08-01 11:28:49 +0000526
Sam McCallbf6a2fc2018-10-17 07:33:42 +0000527 CCOpts.EnableSnippets = Params.capabilities.CompletionSnippets;
Sam McCall8d412942019-06-18 11:57:26 +0000528 CCOpts.IncludeFixIts = Params.capabilities.CompletionFixes;
Sam McCall5f092e32019-07-08 17:27:15 +0000529 if (!CCOpts.BundleOverloads.hasValue())
530 CCOpts.BundleOverloads = Params.capabilities.HasSignatureHelp;
Sam McCallbf6a2fc2018-10-17 07:33:42 +0000531 DiagOpts.EmbedFixesInDiagnostics = Params.capabilities.DiagnosticFixes;
532 DiagOpts.SendDiagnosticCategory = Params.capabilities.DiagnosticCategory;
Sam McCallc9e4ee92019-04-18 15:17:07 +0000533 DiagOpts.EmitRelatedLocations =
534 Params.capabilities.DiagnosticRelatedInformation;
Sam McCallbf6a2fc2018-10-17 07:33:42 +0000535 if (Params.capabilities.WorkspaceSymbolKinds)
536 SupportedSymbolKinds |= *Params.capabilities.WorkspaceSymbolKinds;
537 if (Params.capabilities.CompletionItemKinds)
538 SupportedCompletionItemKinds |= *Params.capabilities.CompletionItemKinds;
539 SupportsCodeAction = Params.capabilities.CodeActionStructure;
Ilya Biryukov19d75602018-11-23 15:21:19 +0000540 SupportsHierarchicalDocumentSymbol =
541 Params.capabilities.HierarchicalDocumentSymbol;
Haojian Wub6188492018-12-20 15:39:12 +0000542 SupportFileStatus = Params.initializationOptions.FileStatus;
Ilya Biryukovf9169d02019-05-29 10:01:00 +0000543 HoverContentFormat = Params.capabilities.HoverContentFormat;
Ilya Biryukov4ef0f822019-06-04 09:36:59 +0000544 SupportsOffsetsInSignatureHelp = Params.capabilities.OffsetsInSignatureHelp;
Sam McCall7d20e802020-01-22 19:41:45 +0100545 if (Params.capabilities.WorkDoneProgress)
546 BackgroundIndexProgressState = BackgroundIndexProgress::Empty;
547 BackgroundIndexSkipCreate = Params.capabilities.ImplicitProgressCreation;
Haojian Wuf429ab62019-07-24 07:49:23 +0000548
549 // Per LSP, renameProvider can be either boolean or RenameOptions.
550 // RenameOptions will be specified if the client states it supports prepare.
551 llvm::json::Value RenameProvider =
552 llvm::json::Object{{"prepareProvider", true}};
553 if (!Params.capabilities.RenamePrepareSupport) // Only boolean allowed per LSP
554 RenameProvider = true;
555
Haojian Wu08d93f12019-08-22 14:53:45 +0000556 // Per LSP, codeActionProvide can be either boolean or CodeActionOptions.
557 // CodeActionOptions is only valid if the client supports action literal
558 // via textDocument.codeAction.codeActionLiteralSupport.
559 llvm::json::Value CodeActionProvider = true;
560 if (Params.capabilities.CodeActionStructure)
561 CodeActionProvider = llvm::json::Object{
562 {"codeActionKinds",
563 {CodeAction::QUICKFIX_KIND, CodeAction::REFACTOR_KIND,
564 CodeAction::INFO_KIND}}};
565
Sam McCalla69698f2019-03-27 17:47:49 +0000566 llvm::json::Object Result{
Sam McCall6f7dca92020-03-03 12:25:46 +0100567 {{"serverInfo",
568 llvm::json::Object{{"name", "clangd"},
569 {"version", getClangToolFullVersion("clangd")}}},
570 {"capabilities",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000571 llvm::json::Object{
Sam McCall596b63a2020-04-10 03:27:37 +0200572 {"textDocumentSync",
573 llvm::json::Object{
574 {"openClose", true},
575 {"change", (int)TextDocumentSyncKind::Incremental},
576 {"save", true},
577 }},
Sam McCall0930ab02017-11-07 15:49:35 +0000578 {"documentFormattingProvider", true},
579 {"documentRangeFormattingProvider", true},
580 {"documentOnTypeFormattingProvider",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000581 llvm::json::Object{
Sam McCall25c62572019-06-10 14:26:21 +0000582 {"firstTriggerCharacter", "\n"},
Sam McCall0930ab02017-11-07 15:49:35 +0000583 {"moreTriggerCharacter", {}},
584 }},
Haojian Wu08d93f12019-08-22 14:53:45 +0000585 {"codeActionProvider", std::move(CodeActionProvider)},
Sam McCall0930ab02017-11-07 15:49:35 +0000586 {"completionProvider",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000587 llvm::json::Object{
Kirill Bobyrev2a095ff2020-02-18 17:55:12 +0100588 {"allCommitCharacters", " \t()[]{}<>:;,+-/*%^&#?.=\"'|"},
Sam McCall0930ab02017-11-07 15:49:35 +0000589 {"resolveProvider", false},
Ilya Biryukovb0826bd2019-01-03 13:37:12 +0000590 // We do extra checks for '>' and ':' in completion to only
591 // trigger on '->' and '::'.
Sam McCall0930ab02017-11-07 15:49:35 +0000592 {"triggerCharacters", {".", ">", ":"}},
593 }},
Sam McCall71177ac2020-03-24 02:24:47 +0100594 {"semanticTokensProvider",
595 llvm::json::Object{
Sam McCall9e3063e2020-04-01 16:21:44 +0200596 {"documentProvider", llvm::json::Object{{"edits", true}}},
Sam McCall71177ac2020-03-24 02:24:47 +0100597 {"rangeProvider", false},
598 {"legend",
599 llvm::json::Object{{"tokenTypes", semanticTokenTypes()},
600 {"tokenModifiers", llvm::json::Array()}}},
601 }},
Sam McCall0930ab02017-11-07 15:49:35 +0000602 {"signatureHelpProvider",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000603 llvm::json::Object{
Sam McCall0930ab02017-11-07 15:49:35 +0000604 {"triggerCharacters", {"(", ","}},
605 }},
Sam McCall866ba2c2019-02-01 11:26:13 +0000606 {"declarationProvider", true},
Sam McCall0930ab02017-11-07 15:49:35 +0000607 {"definitionProvider", true},
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000608 {"documentHighlightProvider", true},
Sam McCall8d7ecc12019-12-16 19:08:51 +0100609 {"documentLinkProvider",
610 llvm::json::Object{
611 {"resolveProvider", false},
612 }},
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000613 {"hoverProvider", true},
Haojian Wuf429ab62019-07-24 07:49:23 +0000614 {"renameProvider", std::move(RenameProvider)},
Utkarsh Saxena55925da2019-09-24 13:38:33 +0000615 {"selectionRangeProvider", true},
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000616 {"documentSymbolProvider", true},
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000617 {"workspaceSymbolProvider", true},
Sam McCall1ad142f2018-09-05 11:53:07 +0000618 {"referencesProvider", true},
Sam McCall0930ab02017-11-07 15:49:35 +0000619 {"executeCommandProvider",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000620 llvm::json::Object{
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000621 {"commands",
622 {ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND,
623 ExecuteCommandParams::CLANGD_APPLY_TWEAK}},
Sam McCall0930ab02017-11-07 15:49:35 +0000624 }},
Kadir Cetinkaya86658022019-03-19 09:27:04 +0000625 {"typeHierarchyProvider", true},
Sam McCalla69698f2019-03-27 17:47:49 +0000626 }}}};
627 if (NegotiatedOffsetEncoding)
628 Result["offsetEncoding"] = *NegotiatedOffsetEncoding;
Sam McCallfc830102020-04-01 12:02:28 +0200629 if (ClangdServerOpts.TheiaSemanticHighlighting)
Johan Vikstroma848dab2019-07-04 07:53:12 +0000630 Result.getObject("capabilities")
631 ->insert(
632 {"semanticHighlighting",
Haojian Wu1ca2ee42019-07-04 12:27:21 +0000633 llvm::json::Object{{"scopes", buildHighlightScopeLookupTable()}}});
Sam McCalla69698f2019-03-27 17:47:49 +0000634 Reply(std::move(Result));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000635}
636
Sam McCall8a2d2942020-03-03 12:12:14 +0100637void ClangdLSPServer::onInitialized(const InitializedParams &Params) {}
638
Sam McCall2c30fbc2018-10-18 12:32:04 +0000639void ClangdLSPServer::onShutdown(const ShutdownParams &Params,
640 Callback<std::nullptr_t> Reply) {
Ilya Biryukov0d9b8a32017-10-25 08:45:41 +0000641 // Do essentially nothing, just say we're ready to exit.
642 ShutdownRequestReceived = true;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000643 Reply(nullptr);
Sam McCall8a5dded2017-10-12 13:29:58 +0000644}
Ilya Biryukovafb55542017-05-16 14:40:30 +0000645
Sam McCall422c8282018-11-26 16:00:11 +0000646// sync is a clangd extension: it blocks until all background work completes.
647// It blocks the calling thread, so no messages are processed until it returns!
648void ClangdLSPServer::onSync(const NoParams &Params,
649 Callback<std::nullptr_t> Reply) {
650 if (Server->blockUntilIdleForTest(/*TimeoutSeconds=*/60))
651 Reply(nullptr);
652 else
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000653 Reply(llvm::createStringError(llvm::inconvertibleErrorCode(),
654 "Not idle after a minute"));
Sam McCall422c8282018-11-26 16:00:11 +0000655}
656
Sam McCall2c30fbc2018-10-18 12:32:04 +0000657void ClangdLSPServer::onDocumentDidOpen(
658 const DidOpenTextDocumentParams &Params) {
Simon Marchi9569fd52018-03-16 14:30:42 +0000659 PathRef File = Params.textDocument.uri.file();
Ilya Biryukovb10ef472018-06-13 09:20:41 +0000660
Sam McCall2c30fbc2018-10-18 12:32:04 +0000661 const std::string &Contents = Params.textDocument.text;
Simon Marchi9569fd52018-03-16 14:30:42 +0000662
Sam McCall2cd33e62020-03-04 00:33:29 +0100663 auto Version = DraftMgr.addDraft(File, Params.textDocument.version, Contents);
664 Server->addDocument(File, Contents, encodeVersion(Version),
665 WantDiagnostics::Yes);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000666}
667
Sam McCall2c30fbc2018-10-18 12:32:04 +0000668void ClangdLSPServer::onDocumentDidChange(
669 const DidChangeTextDocumentParams &Params) {
Eric Liu51fed182018-02-22 18:40:39 +0000670 auto WantDiags = WantDiagnostics::Auto;
671 if (Params.wantDiagnostics.hasValue())
672 WantDiags = Params.wantDiagnostics.getValue() ? WantDiagnostics::Yes
673 : WantDiagnostics::No;
Simon Marchi9569fd52018-03-16 14:30:42 +0000674
675 PathRef File = Params.textDocument.uri.file();
Sam McCallcaf5a4d2020-03-03 15:57:39 +0100676 llvm::Expected<DraftStore::Draft> Draft = DraftMgr.updateDraft(
677 File, Params.textDocument.version, Params.contentChanges);
678 if (!Draft) {
Simon Marchi98082622018-03-26 14:41:40 +0000679 // If this fails, we are most likely going to be not in sync anymore with
680 // the client. It is better to remove the draft and let further operations
681 // fail rather than giving wrong results.
682 DraftMgr.removeDraft(File);
Ilya Biryukov652364b2018-09-26 05:48:29 +0000683 Server->removeDocument(File);
Sam McCallcaf5a4d2020-03-03 15:57:39 +0100684 elog("Failed to update {0}: {1}", File, Draft.takeError());
Simon Marchi98082622018-03-26 14:41:40 +0000685 return;
686 }
Simon Marchi9569fd52018-03-16 14:30:42 +0000687
Sam McCall2cd33e62020-03-04 00:33:29 +0100688 Server->addDocument(File, Draft->Contents, encodeVersion(Draft->Version),
689 WantDiags, Params.forceRebuild);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000690}
691
Sam McCall596b63a2020-04-10 03:27:37 +0200692void ClangdLSPServer::onDocumentDidSave(
693 const DidSaveTextDocumentParams &Params) {
694 reparseOpenFilesIfNeeded([](llvm::StringRef) { return true; });
695}
696
Sam McCall2c30fbc2018-10-18 12:32:04 +0000697void ClangdLSPServer::onFileEvent(const DidChangeWatchedFilesParams &Params) {
Sam McCall596b63a2020-04-10 03:27:37 +0200698 // We could also reparse all open files here. However:
699 // - this could be frequent, and revalidating all the preambles isn't free
700 // - this is useful e.g. when switching git branches, but we're likely to see
701 // fresh headers but still have the old-branch main-file content
Ilya Biryukov652364b2018-09-26 05:48:29 +0000702 Server->onFileEvent(Params);
Marc-Andre Laperlebf114242017-10-02 18:00:37 +0000703}
704
Sam McCall2c30fbc2018-10-18 12:32:04 +0000705void ClangdLSPServer::onCommand(const ExecuteCommandParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000706 Callback<llvm::json::Value> Reply) {
Ilya Biryukov12864002019-08-16 12:46:41 +0000707 auto ApplyEdit = [this](WorkspaceEdit WE, std::string SuccessMessage,
708 decltype(Reply) Reply) {
Eric Liuc5105f92018-02-16 14:15:55 +0000709 ApplyWorkspaceEditParams Edit;
710 Edit.edit = std::move(WE);
Ilya Biryukov12864002019-08-16 12:46:41 +0000711 call<ApplyWorkspaceEditResponse>(
712 "workspace/applyEdit", std::move(Edit),
713 [Reply = std::move(Reply), SuccessMessage = std::move(SuccessMessage)](
714 llvm::Expected<ApplyWorkspaceEditResponse> Response) mutable {
715 if (!Response)
716 return Reply(Response.takeError());
717 if (!Response->applied) {
718 std::string Reason = Response->failureReason
719 ? *Response->failureReason
720 : "unknown reason";
721 return Reply(llvm::createStringError(
722 llvm::inconvertibleErrorCode(),
723 ("edits were not applied: " + Reason).c_str()));
724 }
725 return Reply(SuccessMessage);
726 });
Eric Liuc5105f92018-02-16 14:15:55 +0000727 };
Ilya Biryukov12864002019-08-16 12:46:41 +0000728
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000729 if (Params.command == ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND &&
730 Params.workspaceEdit) {
731 // The flow for "apply-fix" :
732 // 1. We publish a diagnostic, including fixits
733 // 2. The user clicks on the diagnostic, the editor asks us for code actions
734 // 3. We send code actions, with the fixit embedded as context
735 // 4. The user selects the fixit, the editor asks us to apply it
736 // 5. We unwrap the changes and send them back to the editor
Haojian Wuf2516342019-08-05 12:48:09 +0000737 // 6. The editor applies the changes (applyEdit), and sends us a reply
738 // 7. We unwrap the reply and send a reply to the editor.
Ilya Biryukov12864002019-08-16 12:46:41 +0000739 ApplyEdit(*Params.workspaceEdit, "Fix applied.", std::move(Reply));
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000740 } else if (Params.command == ExecuteCommandParams::CLANGD_APPLY_TWEAK &&
741 Params.tweakArgs) {
742 auto Code = DraftMgr.getDraft(Params.tweakArgs->file.file());
743 if (!Code)
744 return Reply(llvm::createStringError(
745 llvm::inconvertibleErrorCode(),
746 "trying to apply a code action for a non-added file"));
747
Ilya Biryukov12864002019-08-16 12:46:41 +0000748 auto Action = [this, ApplyEdit, Reply = std::move(Reply),
749 File = Params.tweakArgs->file, Code = std::move(*Code)](
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000750 llvm::Expected<Tweak::Effect> R) mutable {
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000751 if (!R)
752 return Reply(R.takeError());
753
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000754 assert(R->ShowMessage ||
755 (!R->ApplyEdits.empty() && "tweak has no effect"));
Ilya Biryukov12864002019-08-16 12:46:41 +0000756
Sam McCall395fde72019-06-18 13:37:54 +0000757 if (R->ShowMessage) {
758 ShowMessageParams Msg;
759 Msg.message = *R->ShowMessage;
760 Msg.type = MessageType::Info;
761 notify("window/showMessage", Msg);
762 }
Ilya Biryukov12864002019-08-16 12:46:41 +0000763 // When no edit is specified, make sure we Reply().
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000764 if (R->ApplyEdits.empty())
765 return Reply("Tweak applied.");
766
Haojian Wu852bafa2019-10-23 14:40:20 +0200767 if (auto Err = validateEdits(DraftMgr, R->ApplyEdits))
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000768 return Reply(std::move(Err));
769
770 WorkspaceEdit WE;
771 WE.changes.emplace();
772 for (const auto &It : R->ApplyEdits) {
Kadir Cetinkayae95e5162019-10-02 09:12:01 +0000773 (*WE.changes)[URI::createFile(It.first()).toString()] =
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000774 It.second.asTextEdits();
775 }
776 // ApplyEdit will take care of calling Reply().
777 return ApplyEdit(std::move(WE), "Tweak applied.", std::move(Reply));
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000778 };
779 Server->applyTweak(Params.tweakArgs->file.file(),
780 Params.tweakArgs->selection, Params.tweakArgs->tweakID,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000781 std::move(Action));
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000782 } else {
783 // We should not get here because ExecuteCommandParams would not have
784 // parsed in the first place and this handler should not be called. But if
785 // more commands are added, this will be here has a safe guard.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000786 Reply(llvm::make_error<LSPError>(
787 llvm::formatv("Unsupported command \"{0}\".", Params.command).str(),
Sam McCall2c30fbc2018-10-18 12:32:04 +0000788 ErrorCode::InvalidParams));
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000789 }
790}
791
Sam McCall2c30fbc2018-10-18 12:32:04 +0000792void ClangdLSPServer::onWorkspaceSymbol(
793 const WorkspaceSymbolParams &Params,
794 Callback<std::vector<SymbolInformation>> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000795 Server->workspaceSymbols(
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000796 Params.query, CCOpts.Limit,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000797 [Reply = std::move(Reply),
798 this](llvm::Expected<std::vector<SymbolInformation>> Items) mutable {
799 if (!Items)
800 return Reply(Items.takeError());
801 for (auto &Sym : *Items)
802 Sym.kind = adjustKindToCapability(Sym.kind, SupportedSymbolKinds);
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000803
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000804 Reply(std::move(*Items));
805 });
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000806}
807
Haojian Wuf429ab62019-07-24 07:49:23 +0000808void ClangdLSPServer::onPrepareRename(const TextDocumentPositionParams &Params,
809 Callback<llvm::Optional<Range>> Reply) {
810 Server->prepareRename(Params.textDocument.uri.file(), Params.position,
Haojian Wu34d0e1b2020-02-19 15:37:36 +0100811 RenameOpts, std::move(Reply));
Haojian Wuf429ab62019-07-24 07:49:23 +0000812}
813
Sam McCall2c30fbc2018-10-18 12:32:04 +0000814void ClangdLSPServer::onRename(const RenameParams &Params,
815 Callback<WorkspaceEdit> Reply) {
Benjamin Krameradcd0262020-01-28 20:23:46 +0100816 Path File = std::string(Params.textDocument.uri.file());
Sam McCallcaf5a4d2020-03-03 15:57:39 +0100817 if (!DraftMgr.getDraft(File))
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000818 return Reply(llvm::make_error<LSPError>(
819 "onRename called for non-added file", ErrorCode::InvalidParams));
Haojian Wu852bafa2019-10-23 14:40:20 +0200820 Server->rename(
Haojian Wu34d0e1b2020-02-19 15:37:36 +0100821 File, Params.position, Params.newName, RenameOpts,
Haojian Wu852bafa2019-10-23 14:40:20 +0200822 [File, Params, Reply = std::move(Reply),
823 this](llvm::Expected<FileEdits> Edits) mutable {
824 if (!Edits)
825 return Reply(Edits.takeError());
826 if (auto Err = validateEdits(DraftMgr, *Edits))
827 return Reply(std::move(Err));
828 WorkspaceEdit Result;
829 Result.changes.emplace();
830 for (const auto &Rep : *Edits) {
831 (*Result.changes)[URI::createFile(Rep.first()).toString()] =
832 Rep.second.asTextEdits();
833 }
834 Reply(Result);
835 });
Haojian Wu345099c2017-11-09 11:30:04 +0000836}
837
Sam McCall2c30fbc2018-10-18 12:32:04 +0000838void ClangdLSPServer::onDocumentDidClose(
839 const DidCloseTextDocumentParams &Params) {
Simon Marchi9569fd52018-03-16 14:30:42 +0000840 PathRef File = Params.textDocument.uri.file();
841 DraftMgr.removeDraft(File);
Ilya Biryukov652364b2018-09-26 05:48:29 +0000842 Server->removeDocument(File);
Ilya Biryukov49c10712019-03-25 10:15:11 +0000843
844 {
845 std::lock_guard<std::mutex> Lock(FixItsMutex);
846 FixItsMap.erase(File);
847 }
Johan Vikstromc2653ef22019-08-01 08:08:44 +0000848 {
849 std::lock_guard<std::mutex> HLock(HighlightingsMutex);
850 FileToHighlightings.erase(File);
851 }
Sam McCall9e3063e2020-04-01 16:21:44 +0200852 {
853 std::lock_guard<std::mutex> HLock(SemanticTokensMutex);
854 LastSemanticTokens.erase(File);
855 }
Ilya Biryukov49c10712019-03-25 10:15:11 +0000856 // clangd will not send updates for this file anymore, so we empty out the
857 // list of diagnostics shown on the client (e.g. in the "Problems" pane of
858 // VSCode). Note that this cannot race with actual diagnostics responses
859 // because removeDocument() guarantees no diagnostic callbacks will be
860 // executed after it returns.
Sam McCall6525a6b2020-03-03 12:44:40 +0100861 PublishDiagnosticsParams Notification;
862 Notification.uri = URIForFile::canonicalize(File, /*TUPath=*/File);
863 publishDiagnostics(Notification);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000864}
865
Sam McCall4db732a2017-09-30 10:08:52 +0000866void ClangdLSPServer::onDocumentOnTypeFormatting(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000867 const DocumentOnTypeFormattingParams &Params,
868 Callback<std::vector<TextEdit>> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000869 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000870 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000871 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000872 return Reply(llvm::make_error<LSPError>(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000873 "onDocumentOnTypeFormatting called for non-added file",
874 ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000875
Sam McCallcaf5a4d2020-03-03 15:57:39 +0100876 Reply(Server->formatOnType(Code->Contents, File, Params.position, Params.ch));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000877}
878
Sam McCall4db732a2017-09-30 10:08:52 +0000879void ClangdLSPServer::onDocumentRangeFormatting(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000880 const DocumentRangeFormattingParams &Params,
881 Callback<std::vector<TextEdit>> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000882 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000883 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000884 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000885 return Reply(llvm::make_error<LSPError>(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000886 "onDocumentRangeFormatting called for non-added file",
887 ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000888
Sam McCallcaf5a4d2020-03-03 15:57:39 +0100889 auto ReplacementsOrError =
890 Server->formatRange(Code->Contents, File, Params.range);
Raoul Wols212bcf82017-12-12 20:25:06 +0000891 if (ReplacementsOrError)
Sam McCallcaf5a4d2020-03-03 15:57:39 +0100892 Reply(replacementsToEdits(Code->Contents, ReplacementsOrError.get()));
Raoul Wols212bcf82017-12-12 20:25:06 +0000893 else
Sam McCall2c30fbc2018-10-18 12:32:04 +0000894 Reply(ReplacementsOrError.takeError());
Ilya Biryukovafb55542017-05-16 14:40:30 +0000895}
896
Sam McCall2c30fbc2018-10-18 12:32:04 +0000897void ClangdLSPServer::onDocumentFormatting(
898 const DocumentFormattingParams &Params,
899 Callback<std::vector<TextEdit>> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000900 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000901 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000902 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000903 return Reply(llvm::make_error<LSPError>(
904 "onDocumentFormatting called for non-added file",
905 ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000906
Sam McCallcaf5a4d2020-03-03 15:57:39 +0100907 auto ReplacementsOrError = Server->formatFile(Code->Contents, File);
Raoul Wols212bcf82017-12-12 20:25:06 +0000908 if (ReplacementsOrError)
Sam McCallcaf5a4d2020-03-03 15:57:39 +0100909 Reply(replacementsToEdits(Code->Contents, ReplacementsOrError.get()));
Raoul Wols212bcf82017-12-12 20:25:06 +0000910 else
Sam McCall2c30fbc2018-10-18 12:32:04 +0000911 Reply(ReplacementsOrError.takeError());
Sam McCall4db732a2017-09-30 10:08:52 +0000912}
913
Ilya Biryukov19d75602018-11-23 15:21:19 +0000914/// The functions constructs a flattened view of the DocumentSymbol hierarchy.
915/// Used by the clients that do not support the hierarchical view.
916static std::vector<SymbolInformation>
917flattenSymbolHierarchy(llvm::ArrayRef<DocumentSymbol> Symbols,
918 const URIForFile &FileURI) {
919
920 std::vector<SymbolInformation> Results;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000921 std::function<void(const DocumentSymbol &, llvm::StringRef)> Process =
922 [&](const DocumentSymbol &S, llvm::Optional<llvm::StringRef> ParentName) {
Ilya Biryukov19d75602018-11-23 15:21:19 +0000923 SymbolInformation SI;
Benjamin Krameradcd0262020-01-28 20:23:46 +0100924 SI.containerName = std::string(ParentName ? "" : *ParentName);
Ilya Biryukov19d75602018-11-23 15:21:19 +0000925 SI.name = S.name;
926 SI.kind = S.kind;
927 SI.location.range = S.range;
928 SI.location.uri = FileURI;
929
930 Results.push_back(std::move(SI));
931 std::string FullName =
932 !ParentName ? S.name : (ParentName->str() + "::" + S.name);
933 for (auto &C : S.children)
934 Process(C, /*ParentName=*/FullName);
935 };
936 for (auto &S : Symbols)
937 Process(S, /*ParentName=*/"");
938 return Results;
939}
940
941void ClangdLSPServer::onDocumentSymbol(const DocumentSymbolParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000942 Callback<llvm::json::Value> Reply) {
Ilya Biryukov19d75602018-11-23 15:21:19 +0000943 URIForFile FileURI = Params.textDocument.uri;
Ilya Biryukov652364b2018-09-26 05:48:29 +0000944 Server->documentSymbols(
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000945 Params.textDocument.uri.file(),
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000946 [this, FileURI, Reply = std::move(Reply)](
947 llvm::Expected<std::vector<DocumentSymbol>> Items) mutable {
948 if (!Items)
949 return Reply(Items.takeError());
950 adjustSymbolKinds(*Items, SupportedSymbolKinds);
951 if (SupportsHierarchicalDocumentSymbol)
952 return Reply(std::move(*Items));
953 else
954 return Reply(flattenSymbolHierarchy(*Items, FileURI));
955 });
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000956}
957
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000958static llvm::Optional<Command> asCommand(const CodeAction &Action) {
Sam McCall20841d42018-10-16 16:29:41 +0000959 Command Cmd;
960 if (Action.command && Action.edit)
Sam McCallc008af62018-10-20 15:30:37 +0000961 return None; // Not representable. (We never emit these anyway).
Sam McCall20841d42018-10-16 16:29:41 +0000962 if (Action.command) {
963 Cmd = *Action.command;
964 } else if (Action.edit) {
Benjamin Krameradcd0262020-01-28 20:23:46 +0100965 Cmd.command = std::string(Command::CLANGD_APPLY_FIX_COMMAND);
Sam McCall20841d42018-10-16 16:29:41 +0000966 Cmd.workspaceEdit = *Action.edit;
967 } else {
Sam McCallc008af62018-10-20 15:30:37 +0000968 return None;
Sam McCall20841d42018-10-16 16:29:41 +0000969 }
970 Cmd.title = Action.title;
971 if (Action.kind && *Action.kind == CodeAction::QUICKFIX_KIND)
972 Cmd.title = "Apply fix: " + Cmd.title;
973 return Cmd;
974}
975
Sam McCall2c30fbc2018-10-18 12:32:04 +0000976void ClangdLSPServer::onCodeAction(const CodeActionParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000977 Callback<llvm::json::Value> Reply) {
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000978 URIForFile File = Params.textDocument.uri;
979 auto Code = DraftMgr.getDraft(File.file());
Sam McCall2c30fbc2018-10-18 12:32:04 +0000980 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000981 return Reply(llvm::make_error<LSPError>(
982 "onCodeAction called for non-added file", ErrorCode::InvalidParams));
Sam McCall20841d42018-10-16 16:29:41 +0000983 // We provide a code action for Fixes on the specified diagnostics.
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000984 std::vector<CodeAction> FixIts;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000985 for (const Diagnostic &D : Params.context.diagnostics) {
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000986 for (auto &F : getFixes(File.file(), D)) {
987 FixIts.push_back(toCodeAction(F, Params.textDocument.uri));
988 FixIts.back().diagnostics = {D};
Sam McCalldd0566b2017-11-06 15:40:30 +0000989 }
Ilya Biryukovafb55542017-05-16 14:40:30 +0000990 }
Sam McCall20841d42018-10-16 16:29:41 +0000991
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000992 // Now enumerate the semantic code actions.
993 auto ConsumeActions =
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000994 [Reply = std::move(Reply), File, Code = std::move(*Code),
995 Selection = Params.range, FixIts = std::move(FixIts), this](
996 llvm::Expected<std::vector<ClangdServer::TweakRef>> Tweaks) mutable {
Ilya Biryukovc6ed7782019-01-30 14:24:17 +0000997 if (!Tweaks)
998 return Reply(Tweaks.takeError());
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000999
1000 std::vector<CodeAction> Actions = std::move(FixIts);
1001 Actions.reserve(Actions.size() + Tweaks->size());
1002 for (const auto &T : *Tweaks)
1003 Actions.push_back(toCodeAction(T, File, Selection));
1004
1005 if (SupportsCodeAction)
1006 return Reply(llvm::json::Array(Actions));
1007 std::vector<Command> Commands;
1008 for (const auto &Action : Actions) {
1009 if (auto Command = asCommand(Action))
1010 Commands.push_back(std::move(*Command));
1011 }
1012 return Reply(llvm::json::Array(Commands));
1013 };
1014
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001015 Server->enumerateTweaks(File.file(), Params.range, std::move(ConsumeActions));
Ilya Biryukovafb55542017-05-16 14:40:30 +00001016}
1017
Ilya Biryukovb0826bd2019-01-03 13:37:12 +00001018void ClangdLSPServer::onCompletion(const CompletionParams &Params,
Sam McCall2c30fbc2018-10-18 12:32:04 +00001019 Callback<CompletionList> Reply) {
Ilya Biryukova7a11472019-06-07 16:24:38 +00001020 if (!shouldRunCompletion(Params)) {
1021 // Clients sometimes auto-trigger completions in undesired places (e.g.
1022 // 'a >^ '), we return empty results in those cases.
1023 vlog("ignored auto-triggered completion, preceding char did not match");
1024 return Reply(CompletionList());
1025 }
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001026 Server->codeComplete(Params.textDocument.uri.file(), Params.position, CCOpts,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001027 [Reply = std::move(Reply),
1028 this](llvm::Expected<CodeCompleteResult> List) mutable {
1029 if (!List)
1030 return Reply(List.takeError());
1031 CompletionList LSPList;
1032 LSPList.isIncomplete = List->HasMore;
1033 for (const auto &R : List->Completions) {
1034 CompletionItem C = R.render(CCOpts);
1035 C.kind = adjustKindToCapability(
1036 C.kind, SupportedCompletionItemKinds);
1037 LSPList.items.push_back(std::move(C));
1038 }
1039 return Reply(std::move(LSPList));
1040 });
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +00001041}
1042
Sam McCall2c30fbc2018-10-18 12:32:04 +00001043void ClangdLSPServer::onSignatureHelp(const TextDocumentPositionParams &Params,
1044 Callback<SignatureHelp> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +00001045 Server->signatureHelp(Params.textDocument.uri.file(), Params.position,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001046 [Reply = std::move(Reply), this](
1047 llvm::Expected<SignatureHelp> Signature) mutable {
1048 if (!Signature)
1049 return Reply(Signature.takeError());
1050 if (SupportsOffsetsInSignatureHelp)
1051 return Reply(std::move(*Signature));
1052 // Strip out the offsets from signature help for
1053 // clients that only support string labels.
1054 for (auto &SigInfo : Signature->signatures) {
1055 for (auto &Param : SigInfo.parameters)
1056 Param.labelOffsets.reset();
1057 }
1058 return Reply(std::move(*Signature));
1059 });
Ilya Biryukov652364b2018-09-26 05:48:29 +00001060}
1061
Sam McCall0dbab7f2019-02-02 05:56:00 +00001062// Go to definition has a toggle function: if def and decl are distinct, then
1063// the first press gives you the def, the second gives you the matching def.
1064// getToggle() returns the counterpart location that under the cursor.
1065//
1066// We return the toggled location alone (ignoring other symbols) to encourage
1067// editors to "bounce" quickly between locations, without showing a menu.
1068static Location *getToggle(const TextDocumentPositionParams &Point,
1069 LocatedSymbol &Sym) {
1070 // Toggle only makes sense with two distinct locations.
1071 if (!Sym.Definition || *Sym.Definition == Sym.PreferredDeclaration)
1072 return nullptr;
1073 if (Sym.Definition->uri.file() == Point.textDocument.uri.file() &&
1074 Sym.Definition->range.contains(Point.position))
1075 return &Sym.PreferredDeclaration;
1076 if (Sym.PreferredDeclaration.uri.file() == Point.textDocument.uri.file() &&
1077 Sym.PreferredDeclaration.range.contains(Point.position))
1078 return &*Sym.Definition;
1079 return nullptr;
1080}
1081
Sam McCall2c30fbc2018-10-18 12:32:04 +00001082void ClangdLSPServer::onGoToDefinition(const TextDocumentPositionParams &Params,
1083 Callback<std::vector<Location>> Reply) {
Sam McCall866ba2c2019-02-01 11:26:13 +00001084 Server->locateSymbolAt(
1085 Params.textDocument.uri.file(), Params.position,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001086 [Params, Reply = std::move(Reply)](
1087 llvm::Expected<std::vector<LocatedSymbol>> Symbols) mutable {
1088 if (!Symbols)
1089 return Reply(Symbols.takeError());
1090 std::vector<Location> Defs;
1091 for (auto &S : *Symbols) {
1092 if (Location *Toggle = getToggle(Params, S))
1093 return Reply(std::vector<Location>{std::move(*Toggle)});
1094 Defs.push_back(S.Definition.getValueOr(S.PreferredDeclaration));
1095 }
1096 Reply(std::move(Defs));
1097 });
Sam McCall866ba2c2019-02-01 11:26:13 +00001098}
1099
1100void ClangdLSPServer::onGoToDeclaration(
1101 const TextDocumentPositionParams &Params,
1102 Callback<std::vector<Location>> Reply) {
1103 Server->locateSymbolAt(
1104 Params.textDocument.uri.file(), Params.position,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001105 [Params, Reply = std::move(Reply)](
1106 llvm::Expected<std::vector<LocatedSymbol>> Symbols) mutable {
1107 if (!Symbols)
1108 return Reply(Symbols.takeError());
1109 std::vector<Location> Decls;
1110 for (auto &S : *Symbols) {
1111 if (Location *Toggle = getToggle(Params, S))
1112 return Reply(std::vector<Location>{std::move(*Toggle)});
1113 Decls.push_back(std::move(S.PreferredDeclaration));
1114 }
1115 Reply(std::move(Decls));
1116 });
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +00001117}
1118
Sam McCall111fe842019-05-07 07:55:35 +00001119void ClangdLSPServer::onSwitchSourceHeader(
1120 const TextDocumentIdentifier &Params,
Sam McCallb9ec3e92019-05-07 08:30:32 +00001121 Callback<llvm::Optional<URIForFile>> Reply) {
Haojian Wud6d5edd2019-10-01 10:21:15 +00001122 Server->switchSourceHeader(
1123 Params.uri.file(),
1124 [Reply = std::move(Reply),
1125 Params](llvm::Expected<llvm::Optional<clangd::Path>> Path) mutable {
1126 if (!Path)
1127 return Reply(Path.takeError());
1128 if (*Path)
Haojian Wu77c97002019-10-07 11:37:25 +00001129 return Reply(URIForFile::canonicalize(**Path, Params.uri.file()));
Haojian Wud6d5edd2019-10-01 10:21:15 +00001130 return Reply(llvm::None);
1131 });
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +00001132}
1133
Sam McCall2c30fbc2018-10-18 12:32:04 +00001134void ClangdLSPServer::onDocumentHighlight(
1135 const TextDocumentPositionParams &Params,
1136 Callback<std::vector<DocumentHighlight>> Reply) {
1137 Server->findDocumentHighlights(Params.textDocument.uri.file(),
1138 Params.position, std::move(Reply));
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +00001139}
1140
Sam McCall2c30fbc2018-10-18 12:32:04 +00001141void ClangdLSPServer::onHover(const TextDocumentPositionParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001142 Callback<llvm::Optional<Hover>> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +00001143 Server->findHover(Params.textDocument.uri.file(), Params.position,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001144 [Reply = std::move(Reply), this](
1145 llvm::Expected<llvm::Optional<HoverInfo>> H) mutable {
1146 if (!H)
1147 return Reply(H.takeError());
1148 if (!*H)
1149 return Reply(llvm::None);
Ilya Biryukovf9169d02019-05-29 10:01:00 +00001150
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001151 Hover R;
1152 R.contents.kind = HoverContentFormat;
1153 R.range = (*H)->SymRange;
1154 switch (HoverContentFormat) {
1155 case MarkupKind::PlainText:
Kadir Cetinkaya597c6b62019-12-10 10:28:37 +01001156 R.contents.value = (*H)->present().asPlainText();
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001157 return Reply(std::move(R));
1158 case MarkupKind::Markdown:
Kadir Cetinkaya597c6b62019-12-10 10:28:37 +01001159 R.contents.value = (*H)->present().asMarkdown();
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001160 return Reply(std::move(R));
1161 };
1162 llvm_unreachable("unhandled MarkupKind");
1163 });
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +00001164}
1165
Kadir Cetinkaya86658022019-03-19 09:27:04 +00001166void ClangdLSPServer::onTypeHierarchy(
1167 const TypeHierarchyParams &Params,
1168 Callback<Optional<TypeHierarchyItem>> Reply) {
1169 Server->typeHierarchy(Params.textDocument.uri.file(), Params.position,
1170 Params.resolve, Params.direction, std::move(Reply));
1171}
1172
Nathan Ridge087b0442019-07-13 03:24:48 +00001173void ClangdLSPServer::onResolveTypeHierarchy(
1174 const ResolveTypeHierarchyItemParams &Params,
1175 Callback<Optional<TypeHierarchyItem>> Reply) {
1176 Server->resolveTypeHierarchy(Params.item, Params.resolve, Params.direction,
1177 std::move(Reply));
1178}
1179
Simon Marchi88016782018-08-01 11:28:49 +00001180void ClangdLSPServer::applyConfiguration(
Sam McCallbc904612018-10-25 04:22:52 +00001181 const ConfigurationSettings &Settings) {
Simon Marchiabeed662018-10-16 15:55:03 +00001182 // Per-file update to the compilation database.
David Goldman60249c22020-01-13 17:01:10 -05001183 llvm::StringSet<> ModifiedFiles;
Sam McCallbc904612018-10-25 04:22:52 +00001184 for (auto &Entry : Settings.compilationDatabaseChanges) {
Sam McCallbc904612018-10-25 04:22:52 +00001185 PathRef File = Entry.first;
Sam McCallc55d09a2018-11-02 13:09:36 +00001186 auto Old = CDB->getCompileCommand(File);
1187 auto New =
1188 tooling::CompileCommand(std::move(Entry.second.workingDirectory), File,
1189 std::move(Entry.second.compilationCommand),
1190 /*Output=*/"");
Sam McCall6980edb2018-11-02 14:07:51 +00001191 if (Old != New) {
Sam McCallc55d09a2018-11-02 13:09:36 +00001192 CDB->setCompileCommand(File, std::move(New));
David Goldman60249c22020-01-13 17:01:10 -05001193 ModifiedFiles.insert(File);
Sam McCall6980edb2018-11-02 14:07:51 +00001194 }
Alex Lorenzf8087862018-08-01 17:39:29 +00001195 }
David Goldman60249c22020-01-13 17:01:10 -05001196
Sam McCall596b63a2020-04-10 03:27:37 +02001197 reparseOpenFilesIfNeeded(
1198 [&](llvm::StringRef File) { return ModifiedFiles.count(File) != 0; });
Simon Marchi5178f922018-02-22 14:00:39 +00001199}
1200
Sam McCalledf6a192020-03-24 00:31:14 +01001201void ClangdLSPServer::publishTheiaSemanticHighlighting(
1202 const TheiaSemanticHighlightingParams &Params) {
Johan Vikstroma848dab2019-07-04 07:53:12 +00001203 notify("textDocument/semanticHighlighting", Params);
1204}
1205
Ilya Biryukov49c10712019-03-25 10:15:11 +00001206void ClangdLSPServer::publishDiagnostics(
Sam McCall6525a6b2020-03-03 12:44:40 +01001207 const PublishDiagnosticsParams &Params) {
1208 notify("textDocument/publishDiagnostics", Params);
Ilya Biryukov49c10712019-03-25 10:15:11 +00001209}
1210
Simon Marchi88016782018-08-01 11:28:49 +00001211// FIXME: This function needs to be properly tested.
1212void ClangdLSPServer::onChangeConfiguration(
Sam McCall2c30fbc2018-10-18 12:32:04 +00001213 const DidChangeConfigurationParams &Params) {
Simon Marchi88016782018-08-01 11:28:49 +00001214 applyConfiguration(Params.settings);
1215}
1216
Sam McCall2c30fbc2018-10-18 12:32:04 +00001217void ClangdLSPServer::onReference(const ReferenceParams &Params,
1218 Callback<std::vector<Location>> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +00001219 Server->findReferences(Params.textDocument.uri.file(), Params.position,
Haojian Wu5181ada2019-11-18 11:35:00 +01001220 CCOpts.Limit,
1221 [Reply = std::move(Reply)](
1222 llvm::Expected<ReferencesResult> Refs) mutable {
1223 if (!Refs)
1224 return Reply(Refs.takeError());
1225 return Reply(std::move(Refs->References));
1226 });
Sam McCall1ad142f2018-09-05 11:53:07 +00001227}
1228
Jan Korousb4067012018-11-27 16:40:46 +00001229void ClangdLSPServer::onSymbolInfo(const TextDocumentPositionParams &Params,
1230 Callback<std::vector<SymbolDetails>> Reply) {
1231 Server->symbolInfo(Params.textDocument.uri.file(), Params.position,
1232 std::move(Reply));
1233}
1234
Utkarsh Saxena55925da2019-09-24 13:38:33 +00001235void ClangdLSPServer::onSelectionRange(
1236 const SelectionRangeParams &Params,
1237 Callback<std::vector<SelectionRange>> Reply) {
Utkarsh Saxena55925da2019-09-24 13:38:33 +00001238 Server->semanticRanges(
Sam McCall8f237f92020-03-25 00:51:50 +01001239 Params.textDocument.uri.file(), Params.positions,
Utkarsh Saxena55925da2019-09-24 13:38:33 +00001240 [Reply = std::move(Reply)](
Sam McCall8f237f92020-03-25 00:51:50 +01001241 llvm::Expected<std::vector<SelectionRange>> Ranges) mutable {
1242 if (!Ranges)
Utkarsh Saxena55925da2019-09-24 13:38:33 +00001243 return Reply(Ranges.takeError());
Sam McCall8f237f92020-03-25 00:51:50 +01001244 return Reply(std::move(*Ranges));
Utkarsh Saxena55925da2019-09-24 13:38:33 +00001245 });
1246}
1247
Sam McCall8d7ecc12019-12-16 19:08:51 +01001248void ClangdLSPServer::onDocumentLink(
1249 const DocumentLinkParams &Params,
1250 Callback<std::vector<DocumentLink>> Reply) {
1251
1252 // TODO(forster): This currently resolves all targets eagerly. This is slow,
1253 // because it blocks on the preamble/AST being built. We could respond to the
1254 // request faster by using string matching or the lexer to find the includes
1255 // and resolving the targets lazily.
1256 Server->documentLinks(
1257 Params.textDocument.uri.file(),
1258 [Reply = std::move(Reply)](
1259 llvm::Expected<std::vector<DocumentLink>> Links) mutable {
1260 if (!Links) {
1261 return Reply(Links.takeError());
1262 }
1263 return Reply(std::move(Links));
1264 });
1265}
1266
Sam McCall9e3063e2020-04-01 16:21:44 +02001267// Increment a numeric string: "" -> 1 -> 2 -> ... -> 9 -> 10 -> 11 ...
1268static void increment(std::string &S) {
1269 for (char &C : llvm::reverse(S)) {
1270 if (C != '9') {
1271 ++C;
1272 return;
1273 }
1274 C = '0';
1275 }
1276 S.insert(S.begin(), '1');
1277}
1278
Sam McCall71177ac2020-03-24 02:24:47 +01001279void ClangdLSPServer::onSemanticTokens(const SemanticTokensParams &Params,
1280 Callback<SemanticTokens> CB) {
1281 Server->semanticHighlights(
1282 Params.textDocument.uri.file(),
Sam McCall9e3063e2020-04-01 16:21:44 +02001283 [this, File(Params.textDocument.uri.file().str()), CB(std::move(CB))](
1284 llvm::Expected<std::vector<HighlightingToken>> HT) mutable {
1285 if (!HT)
1286 return CB(HT.takeError());
Sam McCall71177ac2020-03-24 02:24:47 +01001287 SemanticTokens Result;
Sam McCall9e3063e2020-04-01 16:21:44 +02001288 Result.tokens = toSemanticTokens(*HT);
1289 {
1290 std::lock_guard<std::mutex> Lock(SemanticTokensMutex);
1291 auto& Last = LastSemanticTokens[File];
1292
1293 Last.tokens = Result.tokens;
1294 increment(Last.resultId);
1295 Result.resultId = Last.resultId;
1296 }
1297 CB(std::move(Result));
1298 });
1299}
1300
1301void ClangdLSPServer::onSemanticTokensEdits(
1302 const SemanticTokensEditsParams &Params,
1303 Callback<SemanticTokensOrEdits> CB) {
1304 Server->semanticHighlights(
1305 Params.textDocument.uri.file(),
1306 [this, PrevResultID(Params.previousResultId),
1307 File(Params.textDocument.uri.file().str()), CB(std::move(CB))](
1308 llvm::Expected<std::vector<HighlightingToken>> HT) mutable {
1309 if (!HT)
1310 return CB(HT.takeError());
1311 std::vector<SemanticToken> Toks = toSemanticTokens(*HT);
1312
1313 SemanticTokensOrEdits Result;
1314 {
1315 std::lock_guard<std::mutex> Lock(SemanticTokensMutex);
1316 auto& Last = LastSemanticTokens[File];
1317
1318 if (PrevResultID == Last.resultId) {
1319 Result.edits = diffTokens(Last.tokens, Toks);
1320 } else {
1321 vlog("semanticTokens/edits: wanted edits vs {0} but last result "
1322 "had ID {1}. Returning full token list.",
1323 PrevResultID, Last.resultId);
1324 Result.tokens = Toks;
1325 }
1326
1327 Last.tokens = std::move(Toks);
1328 increment(Last.resultId);
1329 Result.resultId = Last.resultId;
1330 }
1331
Sam McCall71177ac2020-03-24 02:24:47 +01001332 CB(std::move(Result));
1333 });
1334}
1335
Sam McCalla69698f2019-03-27 17:47:49 +00001336ClangdLSPServer::ClangdLSPServer(
1337 class Transport &Transp, const FileSystemProvider &FSProvider,
1338 const clangd::CodeCompleteOptions &CCOpts,
Haojian Wu34d0e1b2020-02-19 15:37:36 +01001339 const clangd::RenameOptions &RenameOpts,
Sam McCalla69698f2019-03-27 17:47:49 +00001340 llvm::Optional<Path> CompileCommandsDir, bool UseDirBasedCDB,
1341 llvm::Optional<OffsetEncoding> ForcedOffsetEncoding,
1342 const ClangdServer::Options &Opts)
Kadir Cetinkaya9d662472019-10-15 14:20:52 +00001343 : BackgroundContext(Context::current().clone()), Transp(Transp),
1344 MsgHandler(new MessageHandler(*this)), FSProvider(FSProvider),
Haojian Wu34d0e1b2020-02-19 15:37:36 +01001345 CCOpts(CCOpts), RenameOpts(RenameOpts),
1346 SupportedSymbolKinds(defaultSymbolKinds()),
Kadir Cetinkaya133d46f2018-09-27 17:13:07 +00001347 SupportedCompletionItemKinds(defaultCompletionItemKinds()),
Sam McCallc55d09a2018-11-02 13:09:36 +00001348 UseDirBasedCDB(UseDirBasedCDB),
Sam McCalla69698f2019-03-27 17:47:49 +00001349 CompileCommandsDir(std::move(CompileCommandsDir)), ClangdServerOpts(Opts),
1350 NegotiatedOffsetEncoding(ForcedOffsetEncoding) {
Sam McCall2c30fbc2018-10-18 12:32:04 +00001351 // clang-format off
1352 MsgHandler->bind("initialize", &ClangdLSPServer::onInitialize);
Sam McCall8a2d2942020-03-03 12:12:14 +01001353 MsgHandler->bind("initialized", &ClangdLSPServer::onInitialized);
Sam McCall2c30fbc2018-10-18 12:32:04 +00001354 MsgHandler->bind("shutdown", &ClangdLSPServer::onShutdown);
Sam McCall422c8282018-11-26 16:00:11 +00001355 MsgHandler->bind("sync", &ClangdLSPServer::onSync);
Sam McCall2c30fbc2018-10-18 12:32:04 +00001356 MsgHandler->bind("textDocument/rangeFormatting", &ClangdLSPServer::onDocumentRangeFormatting);
1357 MsgHandler->bind("textDocument/onTypeFormatting", &ClangdLSPServer::onDocumentOnTypeFormatting);
1358 MsgHandler->bind("textDocument/formatting", &ClangdLSPServer::onDocumentFormatting);
1359 MsgHandler->bind("textDocument/codeAction", &ClangdLSPServer::onCodeAction);
1360 MsgHandler->bind("textDocument/completion", &ClangdLSPServer::onCompletion);
1361 MsgHandler->bind("textDocument/signatureHelp", &ClangdLSPServer::onSignatureHelp);
1362 MsgHandler->bind("textDocument/definition", &ClangdLSPServer::onGoToDefinition);
Sam McCall866ba2c2019-02-01 11:26:13 +00001363 MsgHandler->bind("textDocument/declaration", &ClangdLSPServer::onGoToDeclaration);
Sam McCall2c30fbc2018-10-18 12:32:04 +00001364 MsgHandler->bind("textDocument/references", &ClangdLSPServer::onReference);
1365 MsgHandler->bind("textDocument/switchSourceHeader", &ClangdLSPServer::onSwitchSourceHeader);
Haojian Wuf429ab62019-07-24 07:49:23 +00001366 MsgHandler->bind("textDocument/prepareRename", &ClangdLSPServer::onPrepareRename);
Sam McCall2c30fbc2018-10-18 12:32:04 +00001367 MsgHandler->bind("textDocument/rename", &ClangdLSPServer::onRename);
1368 MsgHandler->bind("textDocument/hover", &ClangdLSPServer::onHover);
1369 MsgHandler->bind("textDocument/documentSymbol", &ClangdLSPServer::onDocumentSymbol);
1370 MsgHandler->bind("workspace/executeCommand", &ClangdLSPServer::onCommand);
1371 MsgHandler->bind("textDocument/documentHighlight", &ClangdLSPServer::onDocumentHighlight);
1372 MsgHandler->bind("workspace/symbol", &ClangdLSPServer::onWorkspaceSymbol);
1373 MsgHandler->bind("textDocument/didOpen", &ClangdLSPServer::onDocumentDidOpen);
1374 MsgHandler->bind("textDocument/didClose", &ClangdLSPServer::onDocumentDidClose);
1375 MsgHandler->bind("textDocument/didChange", &ClangdLSPServer::onDocumentDidChange);
Sam McCall596b63a2020-04-10 03:27:37 +02001376 MsgHandler->bind("textDocument/didSave", &ClangdLSPServer::onDocumentDidSave);
Sam McCall2c30fbc2018-10-18 12:32:04 +00001377 MsgHandler->bind("workspace/didChangeWatchedFiles", &ClangdLSPServer::onFileEvent);
1378 MsgHandler->bind("workspace/didChangeConfiguration", &ClangdLSPServer::onChangeConfiguration);
Jan Korousb4067012018-11-27 16:40:46 +00001379 MsgHandler->bind("textDocument/symbolInfo", &ClangdLSPServer::onSymbolInfo);
Kadir Cetinkaya86658022019-03-19 09:27:04 +00001380 MsgHandler->bind("textDocument/typeHierarchy", &ClangdLSPServer::onTypeHierarchy);
Nathan Ridge087b0442019-07-13 03:24:48 +00001381 MsgHandler->bind("typeHierarchy/resolve", &ClangdLSPServer::onResolveTypeHierarchy);
Utkarsh Saxena55925da2019-09-24 13:38:33 +00001382 MsgHandler->bind("textDocument/selectionRange", &ClangdLSPServer::onSelectionRange);
Sam McCall8d7ecc12019-12-16 19:08:51 +01001383 MsgHandler->bind("textDocument/documentLink", &ClangdLSPServer::onDocumentLink);
Sam McCall71177ac2020-03-24 02:24:47 +01001384 MsgHandler->bind("textDocument/semanticTokens", &ClangdLSPServer::onSemanticTokens);
Sam McCall9e3063e2020-04-01 16:21:44 +02001385 MsgHandler->bind("textDocument/semanticTokens/edits", &ClangdLSPServer::onSemanticTokensEdits);
Sam McCall2c30fbc2018-10-18 12:32:04 +00001386 // clang-format on
1387}
1388
Kadir Cetinkaya6b850322020-03-17 19:08:23 +01001389ClangdLSPServer::~ClangdLSPServer() {
1390 IsBeingDestroyed = true;
Sam McCall8bda5f22019-10-23 11:11:18 +02001391 // Explicitly destroy ClangdServer first, blocking on threads it owns.
1392 // This ensures they don't access any other members.
1393 Server.reset();
1394}
Ilya Biryukov38d79772017-05-16 09:38:59 +00001395
Sam McCalldc8f3cf2018-10-17 07:32:05 +00001396bool ClangdLSPServer::run() {
Ilya Biryukovafb55542017-05-16 14:40:30 +00001397 // Run the Language Server loop.
Sam McCalldc8f3cf2018-10-17 07:32:05 +00001398 bool CleanExit = true;
Sam McCall2c30fbc2018-10-18 12:32:04 +00001399 if (auto Err = Transp.loop(*MsgHandler)) {
Sam McCalldc8f3cf2018-10-17 07:32:05 +00001400 elog("Transport error: {0}", std::move(Err));
1401 CleanExit = false;
1402 }
Ilya Biryukovafb55542017-05-16 14:40:30 +00001403
Sam McCalldc8f3cf2018-10-17 07:32:05 +00001404 return CleanExit && ShutdownRequestReceived;
Ilya Biryukov38d79772017-05-16 09:38:59 +00001405}
1406
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001407std::vector<Fix> ClangdLSPServer::getFixes(llvm::StringRef File,
Ilya Biryukov71028b82018-03-12 15:28:22 +00001408 const clangd::Diagnostic &D) {
Ilya Biryukov38d79772017-05-16 09:38:59 +00001409 std::lock_guard<std::mutex> Lock(FixItsMutex);
1410 auto DiagToFixItsIter = FixItsMap.find(File);
1411 if (DiagToFixItsIter == FixItsMap.end())
1412 return {};
1413
1414 const auto &DiagToFixItsMap = DiagToFixItsIter->second;
1415 auto FixItsIter = DiagToFixItsMap.find(D);
1416 if (FixItsIter == DiagToFixItsMap.end())
1417 return {};
1418
1419 return FixItsIter->second;
1420}
1421
Ilya Biryukovb0826bd2019-01-03 13:37:12 +00001422bool ClangdLSPServer::shouldRunCompletion(
1423 const CompletionParams &Params) const {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001424 llvm::StringRef Trigger = Params.context.triggerCharacter;
Ilya Biryukovb0826bd2019-01-03 13:37:12 +00001425 if (Params.context.triggerKind != CompletionTriggerKind::TriggerCharacter ||
1426 (Trigger != ">" && Trigger != ":"))
1427 return true;
1428
1429 auto Code = DraftMgr.getDraft(Params.textDocument.uri.file());
1430 if (!Code)
1431 return true; // completion code will log the error for untracked doc.
1432
1433 // A completion request is sent when the user types '>' or ':', but we only
1434 // want to trigger on '->' and '::'. We check the preceeding character to make
1435 // sure it matches what we expected.
1436 // Running the lexer here would be more robust (e.g. we can detect comments
1437 // and avoid triggering completion there), but we choose to err on the side
1438 // of simplicity here.
Sam McCallcaf5a4d2020-03-03 15:57:39 +01001439 auto Offset = positionToOffset(Code->Contents, Params.position,
Ilya Biryukovb0826bd2019-01-03 13:37:12 +00001440 /*AllowColumnsBeyondLineLength=*/false);
1441 if (!Offset) {
1442 vlog("could not convert position '{0}' to offset for file '{1}'",
1443 Params.position, Params.textDocument.uri.file());
1444 return true;
1445 }
1446 if (*Offset < 2)
1447 return false;
1448
1449 if (Trigger == ">")
Sam McCallcaf5a4d2020-03-03 15:57:39 +01001450 return Code->Contents[*Offset - 2] == '-'; // trigger only on '->'.
Ilya Biryukovb0826bd2019-01-03 13:37:12 +00001451 if (Trigger == ":")
Sam McCallcaf5a4d2020-03-03 15:57:39 +01001452 return Code->Contents[*Offset - 2] == ':'; // trigger only on '::'.
Ilya Biryukovb0826bd2019-01-03 13:37:12 +00001453 assert(false && "unhandled trigger character");
1454 return true;
1455}
1456
Johan Vikstroma848dab2019-07-04 07:53:12 +00001457void ClangdLSPServer::onHighlightingsReady(
Sam McCall2cd33e62020-03-04 00:33:29 +01001458 PathRef File, llvm::StringRef Version,
1459 std::vector<HighlightingToken> Highlightings) {
Johan Vikstromc2653ef22019-08-01 08:08:44 +00001460 std::vector<HighlightingToken> Old;
1461 std::vector<HighlightingToken> HighlightingsCopy = Highlightings;
1462 {
1463 std::lock_guard<std::mutex> Lock(HighlightingsMutex);
1464 Old = std::move(FileToHighlightings[File]);
1465 FileToHighlightings[File] = std::move(HighlightingsCopy);
1466 }
1467 // LSP allows us to send incremental edits of highlightings. Also need to diff
1468 // to remove highlightings from tokens that should no longer have them.
Haojian Wu0a6000f2019-08-26 08:38:45 +00001469 std::vector<LineHighlightings> Diffed = diffHighlightings(Highlightings, Old);
Sam McCalledf6a192020-03-24 00:31:14 +01001470 TheiaSemanticHighlightingParams Notification;
Sam McCall2cd33e62020-03-04 00:33:29 +01001471 Notification.TextDocument.uri =
1472 URIForFile::canonicalize(File, /*TUPath=*/File);
1473 Notification.TextDocument.version = decodeVersion(Version);
Sam McCalledf6a192020-03-24 00:31:14 +01001474 Notification.Lines = toTheiaSemanticHighlightingInformation(Diffed);
1475 publishTheiaSemanticHighlighting(Notification);
Johan Vikstroma848dab2019-07-04 07:53:12 +00001476}
1477
Sam McCall2cd33e62020-03-04 00:33:29 +01001478void ClangdLSPServer::onDiagnosticsReady(PathRef File, llvm::StringRef Version,
Sam McCalla7bb0cc2018-03-12 23:22:35 +00001479 std::vector<Diag> Diagnostics) {
Sam McCall6525a6b2020-03-03 12:44:40 +01001480 PublishDiagnosticsParams Notification;
Sam McCall2cd33e62020-03-04 00:33:29 +01001481 Notification.version = decodeVersion(Version);
Sam McCall6525a6b2020-03-03 12:44:40 +01001482 Notification.uri = URIForFile::canonicalize(File, /*TUPath=*/File);
Ilya Biryukov38d79772017-05-16 09:38:59 +00001483 DiagnosticToReplacementMap LocalFixIts; // Temporary storage
Sam McCalla7bb0cc2018-03-12 23:22:35 +00001484 for (auto &Diag : Diagnostics) {
Sam McCall6525a6b2020-03-03 12:44:40 +01001485 toLSPDiags(Diag, Notification.uri, DiagOpts,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001486 [&](clangd::Diagnostic Diag, llvm::ArrayRef<Fix> Fixes) {
Sam McCall16e70702018-10-24 07:59:38 +00001487 auto &FixItsForDiagnostic = LocalFixIts[Diag];
1488 llvm::copy(Fixes, std::back_inserter(FixItsForDiagnostic));
Sam McCall6525a6b2020-03-03 12:44:40 +01001489 Notification.diagnostics.push_back(std::move(Diag));
Sam McCall16e70702018-10-24 07:59:38 +00001490 });
Ilya Biryukov38d79772017-05-16 09:38:59 +00001491 }
1492
1493 // Cache FixIts
1494 {
Ilya Biryukov38d79772017-05-16 09:38:59 +00001495 std::lock_guard<std::mutex> Lock(FixItsMutex);
1496 FixItsMap[File] = LocalFixIts;
1497 }
1498
Ilya Biryukov49c10712019-03-25 10:15:11 +00001499 // Send a notification to the LSP client.
Sam McCall6525a6b2020-03-03 12:44:40 +01001500 publishDiagnostics(Notification);
Ilya Biryukov38d79772017-05-16 09:38:59 +00001501}
Simon Marchi9569fd52018-03-16 14:30:42 +00001502
Sam McCall7d20e802020-01-22 19:41:45 +01001503void ClangdLSPServer::onBackgroundIndexProgress(
1504 const BackgroundQueue::Stats &Stats) {
1505 static const char ProgressToken[] = "backgroundIndexProgress";
1506 std::lock_guard<std::mutex> Lock(BackgroundIndexProgressMutex);
1507
1508 auto NotifyProgress = [this](const BackgroundQueue::Stats &Stats) {
1509 if (BackgroundIndexProgressState != BackgroundIndexProgress::Live) {
1510 WorkDoneProgressBegin Begin;
1511 Begin.percentage = true;
1512 Begin.title = "indexing";
1513 progress(ProgressToken, std::move(Begin));
1514 BackgroundIndexProgressState = BackgroundIndexProgress::Live;
1515 }
1516
1517 if (Stats.Completed < Stats.Enqueued) {
1518 assert(Stats.Enqueued > Stats.LastIdle);
1519 WorkDoneProgressReport Report;
1520 Report.percentage = 100.0 * (Stats.Completed - Stats.LastIdle) /
1521 (Stats.Enqueued - Stats.LastIdle);
1522 Report.message =
1523 llvm::formatv("{0}/{1}", Stats.Completed - Stats.LastIdle,
1524 Stats.Enqueued - Stats.LastIdle);
1525 progress(ProgressToken, std::move(Report));
1526 } else {
1527 assert(Stats.Completed == Stats.Enqueued);
1528 progress(ProgressToken, WorkDoneProgressEnd());
1529 BackgroundIndexProgressState = BackgroundIndexProgress::Empty;
1530 }
1531 };
1532
1533 switch (BackgroundIndexProgressState) {
1534 case BackgroundIndexProgress::Unsupported:
1535 return;
1536 case BackgroundIndexProgress::Creating:
1537 // Cache this update for when the progress bar is available.
1538 PendingBackgroundIndexProgress = Stats;
1539 return;
1540 case BackgroundIndexProgress::Empty: {
1541 if (BackgroundIndexSkipCreate) {
1542 NotifyProgress(Stats);
1543 break;
1544 }
1545 // Cache this update for when the progress bar is available.
1546 PendingBackgroundIndexProgress = Stats;
1547 BackgroundIndexProgressState = BackgroundIndexProgress::Creating;
1548 WorkDoneProgressCreateParams CreateRequest;
1549 CreateRequest.token = ProgressToken;
1550 call<std::nullptr_t>(
1551 "window/workDoneProgress/create", CreateRequest,
1552 [this, NotifyProgress](llvm::Expected<std::nullptr_t> E) {
1553 std::lock_guard<std::mutex> Lock(BackgroundIndexProgressMutex);
1554 if (E) {
1555 NotifyProgress(this->PendingBackgroundIndexProgress);
1556 } else {
1557 elog("Failed to create background index progress bar: {0}",
1558 E.takeError());
1559 // give up forever rather than thrashing about
1560 BackgroundIndexProgressState = BackgroundIndexProgress::Unsupported;
1561 }
1562 });
1563 break;
1564 }
1565 case BackgroundIndexProgress::Live:
1566 NotifyProgress(Stats);
1567 break;
1568 }
1569}
1570
Haojian Wub6188492018-12-20 15:39:12 +00001571void ClangdLSPServer::onFileUpdated(PathRef File, const TUStatus &Status) {
1572 if (!SupportFileStatus)
1573 return;
1574 // FIXME: we don't emit "BuildingFile" and `RunningAction`, as these
1575 // two statuses are running faster in practice, which leads the UI constantly
1576 // changing, and doesn't provide much value. We may want to emit status at a
1577 // reasonable time interval (e.g. 0.5s).
Kadir Cetinkaya6b850322020-03-17 19:08:23 +01001578 if (Status.PreambleActivity == PreambleAction::Idle &&
1579 (Status.ASTActivity.K == ASTAction::Building ||
1580 Status.ASTActivity.K == ASTAction::RunningAction))
Haojian Wub6188492018-12-20 15:39:12 +00001581 return;
1582 notify("textDocument/clangd.fileStatus", Status.render(File));
1583}
1584
Sam McCall596b63a2020-04-10 03:27:37 +02001585void ClangdLSPServer::reparseOpenFilesIfNeeded(
1586 llvm::function_ref<bool(llvm::StringRef File)> Filter) {
David Goldman60249c22020-01-13 17:01:10 -05001587 // Reparse only opened files that were modified.
Simon Marchi9569fd52018-03-16 14:30:42 +00001588 for (const Path &FilePath : DraftMgr.getActiveFiles())
Sam McCall596b63a2020-04-10 03:27:37 +02001589 if (Filter(FilePath))
Sam McCall2cd33e62020-03-04 00:33:29 +01001590 if (auto Draft = DraftMgr.getDraft(FilePath)) // else disappeared in race?
1591 Server->addDocument(FilePath, std::move(Draft->Contents),
1592 encodeVersion(Draft->Version),
1593 WantDiagnostics::Auto);
Simon Marchi9569fd52018-03-16 14:30:42 +00001594}
Alex Lorenzf8087862018-08-01 17:39:29 +00001595
Sam McCallc008af62018-10-20 15:30:37 +00001596} // namespace clangd
1597} // namespace clang