blob: 882df4abf1ced0aa7e9acda6037a6f7e83e89308 [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"
Kadir Cetinkaya6b850322020-03-17 19:08:23 +010017#include "TUScheduler.h"
Eric Liu78ed91a72018-01-29 15:37:46 +000018#include "URI.h"
Sam McCall395fde72019-06-18 13:37:54 +000019#include "refactor/Tweak.h"
Sam McCallad97ccf2020-04-28 17:49:17 +020020#include "support/Context.h"
21#include "support/Trace.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 McCalla3a27a72020-04-30 10:49:32 +0200531 CCOpts.DocumentationFormat =
532 Params.capabilities.CompletionDocumentationFormat;
Sam McCallbf6a2fc2018-10-17 07:33:42 +0000533 DiagOpts.EmbedFixesInDiagnostics = Params.capabilities.DiagnosticFixes;
534 DiagOpts.SendDiagnosticCategory = Params.capabilities.DiagnosticCategory;
Sam McCallc9e4ee92019-04-18 15:17:07 +0000535 DiagOpts.EmitRelatedLocations =
536 Params.capabilities.DiagnosticRelatedInformation;
Sam McCallbf6a2fc2018-10-17 07:33:42 +0000537 if (Params.capabilities.WorkspaceSymbolKinds)
538 SupportedSymbolKinds |= *Params.capabilities.WorkspaceSymbolKinds;
539 if (Params.capabilities.CompletionItemKinds)
540 SupportedCompletionItemKinds |= *Params.capabilities.CompletionItemKinds;
541 SupportsCodeAction = Params.capabilities.CodeActionStructure;
Ilya Biryukov19d75602018-11-23 15:21:19 +0000542 SupportsHierarchicalDocumentSymbol =
543 Params.capabilities.HierarchicalDocumentSymbol;
Haojian Wub6188492018-12-20 15:39:12 +0000544 SupportFileStatus = Params.initializationOptions.FileStatus;
Ilya Biryukovf9169d02019-05-29 10:01:00 +0000545 HoverContentFormat = Params.capabilities.HoverContentFormat;
Ilya Biryukov4ef0f822019-06-04 09:36:59 +0000546 SupportsOffsetsInSignatureHelp = Params.capabilities.OffsetsInSignatureHelp;
Sam McCall7d20e802020-01-22 19:41:45 +0100547 if (Params.capabilities.WorkDoneProgress)
548 BackgroundIndexProgressState = BackgroundIndexProgress::Empty;
549 BackgroundIndexSkipCreate = Params.capabilities.ImplicitProgressCreation;
Haojian Wuf429ab62019-07-24 07:49:23 +0000550
551 // Per LSP, renameProvider can be either boolean or RenameOptions.
552 // RenameOptions will be specified if the client states it supports prepare.
553 llvm::json::Value RenameProvider =
554 llvm::json::Object{{"prepareProvider", true}};
555 if (!Params.capabilities.RenamePrepareSupport) // Only boolean allowed per LSP
556 RenameProvider = true;
557
Haojian Wu08d93f12019-08-22 14:53:45 +0000558 // Per LSP, codeActionProvide can be either boolean or CodeActionOptions.
559 // CodeActionOptions is only valid if the client supports action literal
560 // via textDocument.codeAction.codeActionLiteralSupport.
561 llvm::json::Value CodeActionProvider = true;
562 if (Params.capabilities.CodeActionStructure)
563 CodeActionProvider = llvm::json::Object{
564 {"codeActionKinds",
565 {CodeAction::QUICKFIX_KIND, CodeAction::REFACTOR_KIND,
566 CodeAction::INFO_KIND}}};
567
Sam McCalla69698f2019-03-27 17:47:49 +0000568 llvm::json::Object Result{
Sam McCall6f7dca92020-03-03 12:25:46 +0100569 {{"serverInfo",
570 llvm::json::Object{{"name", "clangd"},
571 {"version", getClangToolFullVersion("clangd")}}},
572 {"capabilities",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000573 llvm::json::Object{
Sam McCall596b63a2020-04-10 03:27:37 +0200574 {"textDocumentSync",
575 llvm::json::Object{
576 {"openClose", true},
577 {"change", (int)TextDocumentSyncKind::Incremental},
578 {"save", true},
579 }},
Sam McCall0930ab02017-11-07 15:49:35 +0000580 {"documentFormattingProvider", true},
581 {"documentRangeFormattingProvider", true},
582 {"documentOnTypeFormattingProvider",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000583 llvm::json::Object{
Sam McCall25c62572019-06-10 14:26:21 +0000584 {"firstTriggerCharacter", "\n"},
Sam McCall0930ab02017-11-07 15:49:35 +0000585 {"moreTriggerCharacter", {}},
586 }},
Haojian Wu08d93f12019-08-22 14:53:45 +0000587 {"codeActionProvider", std::move(CodeActionProvider)},
Sam McCall0930ab02017-11-07 15:49:35 +0000588 {"completionProvider",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000589 llvm::json::Object{
Kirill Bobyrev2a095ff2020-02-18 17:55:12 +0100590 {"allCommitCharacters", " \t()[]{}<>:;,+-/*%^&#?.=\"'|"},
Sam McCall0930ab02017-11-07 15:49:35 +0000591 {"resolveProvider", false},
Ilya Biryukovb0826bd2019-01-03 13:37:12 +0000592 // We do extra checks for '>' and ':' in completion to only
593 // trigger on '->' and '::'.
Sam McCall0930ab02017-11-07 15:49:35 +0000594 {"triggerCharacters", {".", ">", ":"}},
595 }},
Sam McCall71177ac2020-03-24 02:24:47 +0100596 {"semanticTokensProvider",
597 llvm::json::Object{
Sam McCall9e3063e2020-04-01 16:21:44 +0200598 {"documentProvider", llvm::json::Object{{"edits", true}}},
Sam McCall71177ac2020-03-24 02:24:47 +0100599 {"rangeProvider", false},
600 {"legend",
601 llvm::json::Object{{"tokenTypes", semanticTokenTypes()},
602 {"tokenModifiers", llvm::json::Array()}}},
603 }},
Sam McCall0930ab02017-11-07 15:49:35 +0000604 {"signatureHelpProvider",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000605 llvm::json::Object{
Sam McCall0930ab02017-11-07 15:49:35 +0000606 {"triggerCharacters", {"(", ","}},
607 }},
Sam McCall866ba2c2019-02-01 11:26:13 +0000608 {"declarationProvider", true},
Sam McCall0930ab02017-11-07 15:49:35 +0000609 {"definitionProvider", true},
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000610 {"documentHighlightProvider", true},
Sam McCall8d7ecc12019-12-16 19:08:51 +0100611 {"documentLinkProvider",
612 llvm::json::Object{
613 {"resolveProvider", false},
614 }},
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000615 {"hoverProvider", true},
Haojian Wuf429ab62019-07-24 07:49:23 +0000616 {"renameProvider", std::move(RenameProvider)},
Utkarsh Saxena55925da2019-09-24 13:38:33 +0000617 {"selectionRangeProvider", true},
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000618 {"documentSymbolProvider", true},
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000619 {"workspaceSymbolProvider", true},
Sam McCall1ad142f2018-09-05 11:53:07 +0000620 {"referencesProvider", true},
Sam McCall0930ab02017-11-07 15:49:35 +0000621 {"executeCommandProvider",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000622 llvm::json::Object{
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000623 {"commands",
624 {ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND,
625 ExecuteCommandParams::CLANGD_APPLY_TWEAK}},
Sam McCall0930ab02017-11-07 15:49:35 +0000626 }},
Kadir Cetinkaya86658022019-03-19 09:27:04 +0000627 {"typeHierarchyProvider", true},
Sam McCalla69698f2019-03-27 17:47:49 +0000628 }}}};
629 if (NegotiatedOffsetEncoding)
630 Result["offsetEncoding"] = *NegotiatedOffsetEncoding;
Sam McCallfc830102020-04-01 12:02:28 +0200631 if (ClangdServerOpts.TheiaSemanticHighlighting)
Johan Vikstroma848dab2019-07-04 07:53:12 +0000632 Result.getObject("capabilities")
633 ->insert(
634 {"semanticHighlighting",
Haojian Wu1ca2ee42019-07-04 12:27:21 +0000635 llvm::json::Object{{"scopes", buildHighlightScopeLookupTable()}}});
Sam McCalla69698f2019-03-27 17:47:49 +0000636 Reply(std::move(Result));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000637}
638
Sam McCall8a2d2942020-03-03 12:12:14 +0100639void ClangdLSPServer::onInitialized(const InitializedParams &Params) {}
640
Sam McCall2c30fbc2018-10-18 12:32:04 +0000641void ClangdLSPServer::onShutdown(const ShutdownParams &Params,
642 Callback<std::nullptr_t> Reply) {
Ilya Biryukov0d9b8a32017-10-25 08:45:41 +0000643 // Do essentially nothing, just say we're ready to exit.
644 ShutdownRequestReceived = true;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000645 Reply(nullptr);
Sam McCall8a5dded2017-10-12 13:29:58 +0000646}
Ilya Biryukovafb55542017-05-16 14:40:30 +0000647
Sam McCall422c8282018-11-26 16:00:11 +0000648// sync is a clangd extension: it blocks until all background work completes.
649// It blocks the calling thread, so no messages are processed until it returns!
650void ClangdLSPServer::onSync(const NoParams &Params,
651 Callback<std::nullptr_t> Reply) {
652 if (Server->blockUntilIdleForTest(/*TimeoutSeconds=*/60))
653 Reply(nullptr);
654 else
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000655 Reply(llvm::createStringError(llvm::inconvertibleErrorCode(),
656 "Not idle after a minute"));
Sam McCall422c8282018-11-26 16:00:11 +0000657}
658
Sam McCall2c30fbc2018-10-18 12:32:04 +0000659void ClangdLSPServer::onDocumentDidOpen(
660 const DidOpenTextDocumentParams &Params) {
Simon Marchi9569fd52018-03-16 14:30:42 +0000661 PathRef File = Params.textDocument.uri.file();
Ilya Biryukovb10ef472018-06-13 09:20:41 +0000662
Sam McCall2c30fbc2018-10-18 12:32:04 +0000663 const std::string &Contents = Params.textDocument.text;
Simon Marchi9569fd52018-03-16 14:30:42 +0000664
Sam McCall2cd33e62020-03-04 00:33:29 +0100665 auto Version = DraftMgr.addDraft(File, Params.textDocument.version, Contents);
666 Server->addDocument(File, Contents, encodeVersion(Version),
667 WantDiagnostics::Yes);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000668}
669
Sam McCall2c30fbc2018-10-18 12:32:04 +0000670void ClangdLSPServer::onDocumentDidChange(
671 const DidChangeTextDocumentParams &Params) {
Eric Liu51fed182018-02-22 18:40:39 +0000672 auto WantDiags = WantDiagnostics::Auto;
673 if (Params.wantDiagnostics.hasValue())
674 WantDiags = Params.wantDiagnostics.getValue() ? WantDiagnostics::Yes
675 : WantDiagnostics::No;
Simon Marchi9569fd52018-03-16 14:30:42 +0000676
677 PathRef File = Params.textDocument.uri.file();
Sam McCallcaf5a4d2020-03-03 15:57:39 +0100678 llvm::Expected<DraftStore::Draft> Draft = DraftMgr.updateDraft(
679 File, Params.textDocument.version, Params.contentChanges);
680 if (!Draft) {
Simon Marchi98082622018-03-26 14:41:40 +0000681 // If this fails, we are most likely going to be not in sync anymore with
682 // the client. It is better to remove the draft and let further operations
683 // fail rather than giving wrong results.
684 DraftMgr.removeDraft(File);
Ilya Biryukov652364b2018-09-26 05:48:29 +0000685 Server->removeDocument(File);
Sam McCallcaf5a4d2020-03-03 15:57:39 +0100686 elog("Failed to update {0}: {1}", File, Draft.takeError());
Simon Marchi98082622018-03-26 14:41:40 +0000687 return;
688 }
Simon Marchi9569fd52018-03-16 14:30:42 +0000689
Sam McCall2cd33e62020-03-04 00:33:29 +0100690 Server->addDocument(File, Draft->Contents, encodeVersion(Draft->Version),
691 WantDiags, Params.forceRebuild);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000692}
693
Sam McCall596b63a2020-04-10 03:27:37 +0200694void ClangdLSPServer::onDocumentDidSave(
695 const DidSaveTextDocumentParams &Params) {
696 reparseOpenFilesIfNeeded([](llvm::StringRef) { return true; });
697}
698
Sam McCall2c30fbc2018-10-18 12:32:04 +0000699void ClangdLSPServer::onFileEvent(const DidChangeWatchedFilesParams &Params) {
Sam McCall596b63a2020-04-10 03:27:37 +0200700 // We could also reparse all open files here. However:
701 // - this could be frequent, and revalidating all the preambles isn't free
702 // - this is useful e.g. when switching git branches, but we're likely to see
703 // fresh headers but still have the old-branch main-file content
Ilya Biryukov652364b2018-09-26 05:48:29 +0000704 Server->onFileEvent(Params);
Marc-Andre Laperlebf114242017-10-02 18:00:37 +0000705}
706
Sam McCall2c30fbc2018-10-18 12:32:04 +0000707void ClangdLSPServer::onCommand(const ExecuteCommandParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000708 Callback<llvm::json::Value> Reply) {
Ilya Biryukov12864002019-08-16 12:46:41 +0000709 auto ApplyEdit = [this](WorkspaceEdit WE, std::string SuccessMessage,
710 decltype(Reply) Reply) {
Eric Liuc5105f92018-02-16 14:15:55 +0000711 ApplyWorkspaceEditParams Edit;
712 Edit.edit = std::move(WE);
Ilya Biryukov12864002019-08-16 12:46:41 +0000713 call<ApplyWorkspaceEditResponse>(
714 "workspace/applyEdit", std::move(Edit),
715 [Reply = std::move(Reply), SuccessMessage = std::move(SuccessMessage)](
716 llvm::Expected<ApplyWorkspaceEditResponse> Response) mutable {
717 if (!Response)
718 return Reply(Response.takeError());
719 if (!Response->applied) {
720 std::string Reason = Response->failureReason
721 ? *Response->failureReason
722 : "unknown reason";
723 return Reply(llvm::createStringError(
724 llvm::inconvertibleErrorCode(),
725 ("edits were not applied: " + Reason).c_str()));
726 }
727 return Reply(SuccessMessage);
728 });
Eric Liuc5105f92018-02-16 14:15:55 +0000729 };
Ilya Biryukov12864002019-08-16 12:46:41 +0000730
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000731 if (Params.command == ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND &&
732 Params.workspaceEdit) {
733 // The flow for "apply-fix" :
734 // 1. We publish a diagnostic, including fixits
735 // 2. The user clicks on the diagnostic, the editor asks us for code actions
736 // 3. We send code actions, with the fixit embedded as context
737 // 4. The user selects the fixit, the editor asks us to apply it
738 // 5. We unwrap the changes and send them back to the editor
Haojian Wuf2516342019-08-05 12:48:09 +0000739 // 6. The editor applies the changes (applyEdit), and sends us a reply
740 // 7. We unwrap the reply and send a reply to the editor.
Ilya Biryukov12864002019-08-16 12:46:41 +0000741 ApplyEdit(*Params.workspaceEdit, "Fix applied.", std::move(Reply));
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000742 } else if (Params.command == ExecuteCommandParams::CLANGD_APPLY_TWEAK &&
743 Params.tweakArgs) {
744 auto Code = DraftMgr.getDraft(Params.tweakArgs->file.file());
745 if (!Code)
746 return Reply(llvm::createStringError(
747 llvm::inconvertibleErrorCode(),
748 "trying to apply a code action for a non-added file"));
749
Ilya Biryukov12864002019-08-16 12:46:41 +0000750 auto Action = [this, ApplyEdit, Reply = std::move(Reply),
751 File = Params.tweakArgs->file, Code = std::move(*Code)](
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000752 llvm::Expected<Tweak::Effect> R) mutable {
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000753 if (!R)
754 return Reply(R.takeError());
755
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000756 assert(R->ShowMessage ||
757 (!R->ApplyEdits.empty() && "tweak has no effect"));
Ilya Biryukov12864002019-08-16 12:46:41 +0000758
Sam McCall395fde72019-06-18 13:37:54 +0000759 if (R->ShowMessage) {
760 ShowMessageParams Msg;
761 Msg.message = *R->ShowMessage;
762 Msg.type = MessageType::Info;
763 notify("window/showMessage", Msg);
764 }
Ilya Biryukov12864002019-08-16 12:46:41 +0000765 // When no edit is specified, make sure we Reply().
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000766 if (R->ApplyEdits.empty())
767 return Reply("Tweak applied.");
768
Haojian Wu852bafa2019-10-23 14:40:20 +0200769 if (auto Err = validateEdits(DraftMgr, R->ApplyEdits))
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000770 return Reply(std::move(Err));
771
772 WorkspaceEdit WE;
773 WE.changes.emplace();
774 for (const auto &It : R->ApplyEdits) {
Kadir Cetinkayae95e5162019-10-02 09:12:01 +0000775 (*WE.changes)[URI::createFile(It.first()).toString()] =
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000776 It.second.asTextEdits();
777 }
778 // ApplyEdit will take care of calling Reply().
779 return ApplyEdit(std::move(WE), "Tweak applied.", std::move(Reply));
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000780 };
781 Server->applyTweak(Params.tweakArgs->file.file(),
782 Params.tweakArgs->selection, Params.tweakArgs->tweakID,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000783 std::move(Action));
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000784 } else {
785 // We should not get here because ExecuteCommandParams would not have
786 // parsed in the first place and this handler should not be called. But if
787 // more commands are added, this will be here has a safe guard.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000788 Reply(llvm::make_error<LSPError>(
789 llvm::formatv("Unsupported command \"{0}\".", Params.command).str(),
Sam McCall2c30fbc2018-10-18 12:32:04 +0000790 ErrorCode::InvalidParams));
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000791 }
792}
793
Sam McCall2c30fbc2018-10-18 12:32:04 +0000794void ClangdLSPServer::onWorkspaceSymbol(
795 const WorkspaceSymbolParams &Params,
796 Callback<std::vector<SymbolInformation>> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000797 Server->workspaceSymbols(
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000798 Params.query, CCOpts.Limit,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000799 [Reply = std::move(Reply),
800 this](llvm::Expected<std::vector<SymbolInformation>> Items) mutable {
801 if (!Items)
802 return Reply(Items.takeError());
803 for (auto &Sym : *Items)
804 Sym.kind = adjustKindToCapability(Sym.kind, SupportedSymbolKinds);
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000805
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000806 Reply(std::move(*Items));
807 });
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000808}
809
Haojian Wuf429ab62019-07-24 07:49:23 +0000810void ClangdLSPServer::onPrepareRename(const TextDocumentPositionParams &Params,
811 Callback<llvm::Optional<Range>> Reply) {
812 Server->prepareRename(Params.textDocument.uri.file(), Params.position,
Haojian Wu34d0e1b2020-02-19 15:37:36 +0100813 RenameOpts, std::move(Reply));
Haojian Wuf429ab62019-07-24 07:49:23 +0000814}
815
Sam McCall2c30fbc2018-10-18 12:32:04 +0000816void ClangdLSPServer::onRename(const RenameParams &Params,
817 Callback<WorkspaceEdit> Reply) {
Benjamin Krameradcd0262020-01-28 20:23:46 +0100818 Path File = std::string(Params.textDocument.uri.file());
Sam McCallcaf5a4d2020-03-03 15:57:39 +0100819 if (!DraftMgr.getDraft(File))
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000820 return Reply(llvm::make_error<LSPError>(
821 "onRename called for non-added file", ErrorCode::InvalidParams));
Haojian Wu852bafa2019-10-23 14:40:20 +0200822 Server->rename(
Haojian Wu34d0e1b2020-02-19 15:37:36 +0100823 File, Params.position, Params.newName, RenameOpts,
Haojian Wu852bafa2019-10-23 14:40:20 +0200824 [File, Params, Reply = std::move(Reply),
825 this](llvm::Expected<FileEdits> Edits) mutable {
826 if (!Edits)
827 return Reply(Edits.takeError());
828 if (auto Err = validateEdits(DraftMgr, *Edits))
829 return Reply(std::move(Err));
830 WorkspaceEdit Result;
831 Result.changes.emplace();
832 for (const auto &Rep : *Edits) {
833 (*Result.changes)[URI::createFile(Rep.first()).toString()] =
834 Rep.second.asTextEdits();
835 }
836 Reply(Result);
837 });
Haojian Wu345099c2017-11-09 11:30:04 +0000838}
839
Sam McCall2c30fbc2018-10-18 12:32:04 +0000840void ClangdLSPServer::onDocumentDidClose(
841 const DidCloseTextDocumentParams &Params) {
Simon Marchi9569fd52018-03-16 14:30:42 +0000842 PathRef File = Params.textDocument.uri.file();
843 DraftMgr.removeDraft(File);
Ilya Biryukov652364b2018-09-26 05:48:29 +0000844 Server->removeDocument(File);
Ilya Biryukov49c10712019-03-25 10:15:11 +0000845
846 {
847 std::lock_guard<std::mutex> Lock(FixItsMutex);
848 FixItsMap.erase(File);
849 }
Johan Vikstromc2653ef22019-08-01 08:08:44 +0000850 {
851 std::lock_guard<std::mutex> HLock(HighlightingsMutex);
852 FileToHighlightings.erase(File);
853 }
Sam McCall9e3063e2020-04-01 16:21:44 +0200854 {
855 std::lock_guard<std::mutex> HLock(SemanticTokensMutex);
856 LastSemanticTokens.erase(File);
857 }
Ilya Biryukov49c10712019-03-25 10:15:11 +0000858 // clangd will not send updates for this file anymore, so we empty out the
859 // list of diagnostics shown on the client (e.g. in the "Problems" pane of
860 // VSCode). Note that this cannot race with actual diagnostics responses
861 // because removeDocument() guarantees no diagnostic callbacks will be
862 // executed after it returns.
Sam McCall6525a6b2020-03-03 12:44:40 +0100863 PublishDiagnosticsParams Notification;
864 Notification.uri = URIForFile::canonicalize(File, /*TUPath=*/File);
865 publishDiagnostics(Notification);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000866}
867
Sam McCall4db732a2017-09-30 10:08:52 +0000868void ClangdLSPServer::onDocumentOnTypeFormatting(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000869 const DocumentOnTypeFormattingParams &Params,
870 Callback<std::vector<TextEdit>> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000871 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000872 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000873 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000874 return Reply(llvm::make_error<LSPError>(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000875 "onDocumentOnTypeFormatting called for non-added file",
876 ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000877
Sam McCallcaf5a4d2020-03-03 15:57:39 +0100878 Reply(Server->formatOnType(Code->Contents, File, Params.position, Params.ch));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000879}
880
Sam McCall4db732a2017-09-30 10:08:52 +0000881void ClangdLSPServer::onDocumentRangeFormatting(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000882 const DocumentRangeFormattingParams &Params,
883 Callback<std::vector<TextEdit>> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000884 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000885 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000886 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000887 return Reply(llvm::make_error<LSPError>(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000888 "onDocumentRangeFormatting called for non-added file",
889 ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000890
Sam McCallcaf5a4d2020-03-03 15:57:39 +0100891 auto ReplacementsOrError =
892 Server->formatRange(Code->Contents, File, Params.range);
Raoul Wols212bcf82017-12-12 20:25:06 +0000893 if (ReplacementsOrError)
Sam McCallcaf5a4d2020-03-03 15:57:39 +0100894 Reply(replacementsToEdits(Code->Contents, ReplacementsOrError.get()));
Raoul Wols212bcf82017-12-12 20:25:06 +0000895 else
Sam McCall2c30fbc2018-10-18 12:32:04 +0000896 Reply(ReplacementsOrError.takeError());
Ilya Biryukovafb55542017-05-16 14:40:30 +0000897}
898
Sam McCall2c30fbc2018-10-18 12:32:04 +0000899void ClangdLSPServer::onDocumentFormatting(
900 const DocumentFormattingParams &Params,
901 Callback<std::vector<TextEdit>> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000902 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000903 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000904 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000905 return Reply(llvm::make_error<LSPError>(
906 "onDocumentFormatting called for non-added file",
907 ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000908
Sam McCallcaf5a4d2020-03-03 15:57:39 +0100909 auto ReplacementsOrError = Server->formatFile(Code->Contents, File);
Raoul Wols212bcf82017-12-12 20:25:06 +0000910 if (ReplacementsOrError)
Sam McCallcaf5a4d2020-03-03 15:57:39 +0100911 Reply(replacementsToEdits(Code->Contents, ReplacementsOrError.get()));
Raoul Wols212bcf82017-12-12 20:25:06 +0000912 else
Sam McCall2c30fbc2018-10-18 12:32:04 +0000913 Reply(ReplacementsOrError.takeError());
Sam McCall4db732a2017-09-30 10:08:52 +0000914}
915
Ilya Biryukov19d75602018-11-23 15:21:19 +0000916/// The functions constructs a flattened view of the DocumentSymbol hierarchy.
917/// Used by the clients that do not support the hierarchical view.
918static std::vector<SymbolInformation>
919flattenSymbolHierarchy(llvm::ArrayRef<DocumentSymbol> Symbols,
920 const URIForFile &FileURI) {
921
922 std::vector<SymbolInformation> Results;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000923 std::function<void(const DocumentSymbol &, llvm::StringRef)> Process =
924 [&](const DocumentSymbol &S, llvm::Optional<llvm::StringRef> ParentName) {
Ilya Biryukov19d75602018-11-23 15:21:19 +0000925 SymbolInformation SI;
Benjamin Krameradcd0262020-01-28 20:23:46 +0100926 SI.containerName = std::string(ParentName ? "" : *ParentName);
Ilya Biryukov19d75602018-11-23 15:21:19 +0000927 SI.name = S.name;
928 SI.kind = S.kind;
929 SI.location.range = S.range;
930 SI.location.uri = FileURI;
931
932 Results.push_back(std::move(SI));
933 std::string FullName =
934 !ParentName ? S.name : (ParentName->str() + "::" + S.name);
935 for (auto &C : S.children)
936 Process(C, /*ParentName=*/FullName);
937 };
938 for (auto &S : Symbols)
939 Process(S, /*ParentName=*/"");
940 return Results;
941}
942
943void ClangdLSPServer::onDocumentSymbol(const DocumentSymbolParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000944 Callback<llvm::json::Value> Reply) {
Ilya Biryukov19d75602018-11-23 15:21:19 +0000945 URIForFile FileURI = Params.textDocument.uri;
Ilya Biryukov652364b2018-09-26 05:48:29 +0000946 Server->documentSymbols(
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000947 Params.textDocument.uri.file(),
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000948 [this, FileURI, Reply = std::move(Reply)](
949 llvm::Expected<std::vector<DocumentSymbol>> Items) mutable {
950 if (!Items)
951 return Reply(Items.takeError());
952 adjustSymbolKinds(*Items, SupportedSymbolKinds);
953 if (SupportsHierarchicalDocumentSymbol)
954 return Reply(std::move(*Items));
955 else
956 return Reply(flattenSymbolHierarchy(*Items, FileURI));
957 });
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000958}
959
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000960static llvm::Optional<Command> asCommand(const CodeAction &Action) {
Sam McCall20841d42018-10-16 16:29:41 +0000961 Command Cmd;
962 if (Action.command && Action.edit)
Sam McCallc008af62018-10-20 15:30:37 +0000963 return None; // Not representable. (We never emit these anyway).
Sam McCall20841d42018-10-16 16:29:41 +0000964 if (Action.command) {
965 Cmd = *Action.command;
966 } else if (Action.edit) {
Benjamin Krameradcd0262020-01-28 20:23:46 +0100967 Cmd.command = std::string(Command::CLANGD_APPLY_FIX_COMMAND);
Sam McCall20841d42018-10-16 16:29:41 +0000968 Cmd.workspaceEdit = *Action.edit;
969 } else {
Sam McCallc008af62018-10-20 15:30:37 +0000970 return None;
Sam McCall20841d42018-10-16 16:29:41 +0000971 }
972 Cmd.title = Action.title;
973 if (Action.kind && *Action.kind == CodeAction::QUICKFIX_KIND)
974 Cmd.title = "Apply fix: " + Cmd.title;
975 return Cmd;
976}
977
Sam McCall2c30fbc2018-10-18 12:32:04 +0000978void ClangdLSPServer::onCodeAction(const CodeActionParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000979 Callback<llvm::json::Value> Reply) {
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000980 URIForFile File = Params.textDocument.uri;
981 auto Code = DraftMgr.getDraft(File.file());
Sam McCall2c30fbc2018-10-18 12:32:04 +0000982 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000983 return Reply(llvm::make_error<LSPError>(
984 "onCodeAction called for non-added file", ErrorCode::InvalidParams));
Sam McCall20841d42018-10-16 16:29:41 +0000985 // We provide a code action for Fixes on the specified diagnostics.
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000986 std::vector<CodeAction> FixIts;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000987 for (const Diagnostic &D : Params.context.diagnostics) {
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000988 for (auto &F : getFixes(File.file(), D)) {
989 FixIts.push_back(toCodeAction(F, Params.textDocument.uri));
990 FixIts.back().diagnostics = {D};
Sam McCalldd0566b2017-11-06 15:40:30 +0000991 }
Ilya Biryukovafb55542017-05-16 14:40:30 +0000992 }
Sam McCall20841d42018-10-16 16:29:41 +0000993
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000994 // Now enumerate the semantic code actions.
995 auto ConsumeActions =
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000996 [Reply = std::move(Reply), File, Code = std::move(*Code),
997 Selection = Params.range, FixIts = std::move(FixIts), this](
998 llvm::Expected<std::vector<ClangdServer::TweakRef>> Tweaks) mutable {
Ilya Biryukovc6ed7782019-01-30 14:24:17 +0000999 if (!Tweaks)
1000 return Reply(Tweaks.takeError());
Ilya Biryukovcce67a32019-01-29 14:17:36 +00001001
1002 std::vector<CodeAction> Actions = std::move(FixIts);
1003 Actions.reserve(Actions.size() + Tweaks->size());
1004 for (const auto &T : *Tweaks)
1005 Actions.push_back(toCodeAction(T, File, Selection));
1006
1007 if (SupportsCodeAction)
1008 return Reply(llvm::json::Array(Actions));
1009 std::vector<Command> Commands;
1010 for (const auto &Action : Actions) {
1011 if (auto Command = asCommand(Action))
1012 Commands.push_back(std::move(*Command));
1013 }
1014 return Reply(llvm::json::Array(Commands));
1015 };
1016
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001017 Server->enumerateTweaks(File.file(), Params.range, std::move(ConsumeActions));
Ilya Biryukovafb55542017-05-16 14:40:30 +00001018}
1019
Ilya Biryukovb0826bd2019-01-03 13:37:12 +00001020void ClangdLSPServer::onCompletion(const CompletionParams &Params,
Sam McCall2c30fbc2018-10-18 12:32:04 +00001021 Callback<CompletionList> Reply) {
Ilya Biryukova7a11472019-06-07 16:24:38 +00001022 if (!shouldRunCompletion(Params)) {
1023 // Clients sometimes auto-trigger completions in undesired places (e.g.
1024 // 'a >^ '), we return empty results in those cases.
1025 vlog("ignored auto-triggered completion, preceding char did not match");
1026 return Reply(CompletionList());
1027 }
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001028 Server->codeComplete(Params.textDocument.uri.file(), Params.position, CCOpts,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001029 [Reply = std::move(Reply),
1030 this](llvm::Expected<CodeCompleteResult> List) mutable {
1031 if (!List)
1032 return Reply(List.takeError());
1033 CompletionList LSPList;
1034 LSPList.isIncomplete = List->HasMore;
1035 for (const auto &R : List->Completions) {
1036 CompletionItem C = R.render(CCOpts);
1037 C.kind = adjustKindToCapability(
1038 C.kind, SupportedCompletionItemKinds);
1039 LSPList.items.push_back(std::move(C));
1040 }
1041 return Reply(std::move(LSPList));
1042 });
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +00001043}
1044
Sam McCall2c30fbc2018-10-18 12:32:04 +00001045void ClangdLSPServer::onSignatureHelp(const TextDocumentPositionParams &Params,
1046 Callback<SignatureHelp> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +00001047 Server->signatureHelp(Params.textDocument.uri.file(), Params.position,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001048 [Reply = std::move(Reply), this](
1049 llvm::Expected<SignatureHelp> Signature) mutable {
1050 if (!Signature)
1051 return Reply(Signature.takeError());
1052 if (SupportsOffsetsInSignatureHelp)
1053 return Reply(std::move(*Signature));
1054 // Strip out the offsets from signature help for
1055 // clients that only support string labels.
1056 for (auto &SigInfo : Signature->signatures) {
1057 for (auto &Param : SigInfo.parameters)
1058 Param.labelOffsets.reset();
1059 }
1060 return Reply(std::move(*Signature));
1061 });
Ilya Biryukov652364b2018-09-26 05:48:29 +00001062}
1063
Sam McCall0dbab7f2019-02-02 05:56:00 +00001064// Go to definition has a toggle function: if def and decl are distinct, then
1065// the first press gives you the def, the second gives you the matching def.
1066// getToggle() returns the counterpart location that under the cursor.
1067//
1068// We return the toggled location alone (ignoring other symbols) to encourage
1069// editors to "bounce" quickly between locations, without showing a menu.
1070static Location *getToggle(const TextDocumentPositionParams &Point,
1071 LocatedSymbol &Sym) {
1072 // Toggle only makes sense with two distinct locations.
1073 if (!Sym.Definition || *Sym.Definition == Sym.PreferredDeclaration)
1074 return nullptr;
1075 if (Sym.Definition->uri.file() == Point.textDocument.uri.file() &&
1076 Sym.Definition->range.contains(Point.position))
1077 return &Sym.PreferredDeclaration;
1078 if (Sym.PreferredDeclaration.uri.file() == Point.textDocument.uri.file() &&
1079 Sym.PreferredDeclaration.range.contains(Point.position))
1080 return &*Sym.Definition;
1081 return nullptr;
1082}
1083
Sam McCall2c30fbc2018-10-18 12:32:04 +00001084void ClangdLSPServer::onGoToDefinition(const TextDocumentPositionParams &Params,
1085 Callback<std::vector<Location>> Reply) {
Sam McCall866ba2c2019-02-01 11:26:13 +00001086 Server->locateSymbolAt(
1087 Params.textDocument.uri.file(), Params.position,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001088 [Params, Reply = std::move(Reply)](
1089 llvm::Expected<std::vector<LocatedSymbol>> Symbols) mutable {
1090 if (!Symbols)
1091 return Reply(Symbols.takeError());
1092 std::vector<Location> Defs;
1093 for (auto &S : *Symbols) {
1094 if (Location *Toggle = getToggle(Params, S))
1095 return Reply(std::vector<Location>{std::move(*Toggle)});
1096 Defs.push_back(S.Definition.getValueOr(S.PreferredDeclaration));
1097 }
1098 Reply(std::move(Defs));
1099 });
Sam McCall866ba2c2019-02-01 11:26:13 +00001100}
1101
1102void ClangdLSPServer::onGoToDeclaration(
1103 const TextDocumentPositionParams &Params,
1104 Callback<std::vector<Location>> Reply) {
1105 Server->locateSymbolAt(
1106 Params.textDocument.uri.file(), Params.position,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001107 [Params, Reply = std::move(Reply)](
1108 llvm::Expected<std::vector<LocatedSymbol>> Symbols) mutable {
1109 if (!Symbols)
1110 return Reply(Symbols.takeError());
1111 std::vector<Location> Decls;
1112 for (auto &S : *Symbols) {
1113 if (Location *Toggle = getToggle(Params, S))
1114 return Reply(std::vector<Location>{std::move(*Toggle)});
1115 Decls.push_back(std::move(S.PreferredDeclaration));
1116 }
1117 Reply(std::move(Decls));
1118 });
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +00001119}
1120
Sam McCall111fe842019-05-07 07:55:35 +00001121void ClangdLSPServer::onSwitchSourceHeader(
1122 const TextDocumentIdentifier &Params,
Sam McCallb9ec3e92019-05-07 08:30:32 +00001123 Callback<llvm::Optional<URIForFile>> Reply) {
Haojian Wud6d5edd2019-10-01 10:21:15 +00001124 Server->switchSourceHeader(
1125 Params.uri.file(),
1126 [Reply = std::move(Reply),
1127 Params](llvm::Expected<llvm::Optional<clangd::Path>> Path) mutable {
1128 if (!Path)
1129 return Reply(Path.takeError());
1130 if (*Path)
Haojian Wu77c97002019-10-07 11:37:25 +00001131 return Reply(URIForFile::canonicalize(**Path, Params.uri.file()));
Haojian Wud6d5edd2019-10-01 10:21:15 +00001132 return Reply(llvm::None);
1133 });
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +00001134}
1135
Sam McCall2c30fbc2018-10-18 12:32:04 +00001136void ClangdLSPServer::onDocumentHighlight(
1137 const TextDocumentPositionParams &Params,
1138 Callback<std::vector<DocumentHighlight>> Reply) {
1139 Server->findDocumentHighlights(Params.textDocument.uri.file(),
1140 Params.position, std::move(Reply));
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +00001141}
1142
Sam McCall2c30fbc2018-10-18 12:32:04 +00001143void ClangdLSPServer::onHover(const TextDocumentPositionParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001144 Callback<llvm::Optional<Hover>> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +00001145 Server->findHover(Params.textDocument.uri.file(), Params.position,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001146 [Reply = std::move(Reply), this](
1147 llvm::Expected<llvm::Optional<HoverInfo>> H) mutable {
1148 if (!H)
1149 return Reply(H.takeError());
1150 if (!*H)
1151 return Reply(llvm::None);
Ilya Biryukovf9169d02019-05-29 10:01:00 +00001152
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001153 Hover R;
1154 R.contents.kind = HoverContentFormat;
1155 R.range = (*H)->SymRange;
1156 switch (HoverContentFormat) {
1157 case MarkupKind::PlainText:
Kadir Cetinkaya597c6b62019-12-10 10:28:37 +01001158 R.contents.value = (*H)->present().asPlainText();
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001159 return Reply(std::move(R));
1160 case MarkupKind::Markdown:
Kadir Cetinkaya597c6b62019-12-10 10:28:37 +01001161 R.contents.value = (*H)->present().asMarkdown();
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001162 return Reply(std::move(R));
1163 };
1164 llvm_unreachable("unhandled MarkupKind");
1165 });
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +00001166}
1167
Kadir Cetinkaya86658022019-03-19 09:27:04 +00001168void ClangdLSPServer::onTypeHierarchy(
1169 const TypeHierarchyParams &Params,
1170 Callback<Optional<TypeHierarchyItem>> Reply) {
1171 Server->typeHierarchy(Params.textDocument.uri.file(), Params.position,
1172 Params.resolve, Params.direction, std::move(Reply));
1173}
1174
Nathan Ridge087b0442019-07-13 03:24:48 +00001175void ClangdLSPServer::onResolveTypeHierarchy(
1176 const ResolveTypeHierarchyItemParams &Params,
1177 Callback<Optional<TypeHierarchyItem>> Reply) {
1178 Server->resolveTypeHierarchy(Params.item, Params.resolve, Params.direction,
1179 std::move(Reply));
1180}
1181
Simon Marchi88016782018-08-01 11:28:49 +00001182void ClangdLSPServer::applyConfiguration(
Sam McCallbc904612018-10-25 04:22:52 +00001183 const ConfigurationSettings &Settings) {
Simon Marchiabeed662018-10-16 15:55:03 +00001184 // Per-file update to the compilation database.
David Goldman60249c22020-01-13 17:01:10 -05001185 llvm::StringSet<> ModifiedFiles;
Sam McCallbc904612018-10-25 04:22:52 +00001186 for (auto &Entry : Settings.compilationDatabaseChanges) {
Sam McCallbc904612018-10-25 04:22:52 +00001187 PathRef File = Entry.first;
Sam McCallc55d09a2018-11-02 13:09:36 +00001188 auto Old = CDB->getCompileCommand(File);
1189 auto New =
1190 tooling::CompileCommand(std::move(Entry.second.workingDirectory), File,
1191 std::move(Entry.second.compilationCommand),
1192 /*Output=*/"");
Sam McCall6980edb2018-11-02 14:07:51 +00001193 if (Old != New) {
Sam McCallc55d09a2018-11-02 13:09:36 +00001194 CDB->setCompileCommand(File, std::move(New));
David Goldman60249c22020-01-13 17:01:10 -05001195 ModifiedFiles.insert(File);
Sam McCall6980edb2018-11-02 14:07:51 +00001196 }
Alex Lorenzf8087862018-08-01 17:39:29 +00001197 }
David Goldman60249c22020-01-13 17:01:10 -05001198
Sam McCall596b63a2020-04-10 03:27:37 +02001199 reparseOpenFilesIfNeeded(
1200 [&](llvm::StringRef File) { return ModifiedFiles.count(File) != 0; });
Simon Marchi5178f922018-02-22 14:00:39 +00001201}
1202
Sam McCalledf6a192020-03-24 00:31:14 +01001203void ClangdLSPServer::publishTheiaSemanticHighlighting(
1204 const TheiaSemanticHighlightingParams &Params) {
Johan Vikstroma848dab2019-07-04 07:53:12 +00001205 notify("textDocument/semanticHighlighting", Params);
1206}
1207
Ilya Biryukov49c10712019-03-25 10:15:11 +00001208void ClangdLSPServer::publishDiagnostics(
Sam McCall6525a6b2020-03-03 12:44:40 +01001209 const PublishDiagnosticsParams &Params) {
1210 notify("textDocument/publishDiagnostics", Params);
Ilya Biryukov49c10712019-03-25 10:15:11 +00001211}
1212
Simon Marchi88016782018-08-01 11:28:49 +00001213// FIXME: This function needs to be properly tested.
1214void ClangdLSPServer::onChangeConfiguration(
Sam McCall2c30fbc2018-10-18 12:32:04 +00001215 const DidChangeConfigurationParams &Params) {
Simon Marchi88016782018-08-01 11:28:49 +00001216 applyConfiguration(Params.settings);
1217}
1218
Sam McCall2c30fbc2018-10-18 12:32:04 +00001219void ClangdLSPServer::onReference(const ReferenceParams &Params,
1220 Callback<std::vector<Location>> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +00001221 Server->findReferences(Params.textDocument.uri.file(), Params.position,
Haojian Wu5181ada2019-11-18 11:35:00 +01001222 CCOpts.Limit,
1223 [Reply = std::move(Reply)](
1224 llvm::Expected<ReferencesResult> Refs) mutable {
1225 if (!Refs)
1226 return Reply(Refs.takeError());
1227 return Reply(std::move(Refs->References));
1228 });
Sam McCall1ad142f2018-09-05 11:53:07 +00001229}
1230
Jan Korousb4067012018-11-27 16:40:46 +00001231void ClangdLSPServer::onSymbolInfo(const TextDocumentPositionParams &Params,
1232 Callback<std::vector<SymbolDetails>> Reply) {
1233 Server->symbolInfo(Params.textDocument.uri.file(), Params.position,
1234 std::move(Reply));
1235}
1236
Utkarsh Saxena55925da2019-09-24 13:38:33 +00001237void ClangdLSPServer::onSelectionRange(
1238 const SelectionRangeParams &Params,
1239 Callback<std::vector<SelectionRange>> Reply) {
Utkarsh Saxena55925da2019-09-24 13:38:33 +00001240 Server->semanticRanges(
Sam McCall8f237f92020-03-25 00:51:50 +01001241 Params.textDocument.uri.file(), Params.positions,
Utkarsh Saxena55925da2019-09-24 13:38:33 +00001242 [Reply = std::move(Reply)](
Sam McCall8f237f92020-03-25 00:51:50 +01001243 llvm::Expected<std::vector<SelectionRange>> Ranges) mutable {
1244 if (!Ranges)
Utkarsh Saxena55925da2019-09-24 13:38:33 +00001245 return Reply(Ranges.takeError());
Sam McCall8f237f92020-03-25 00:51:50 +01001246 return Reply(std::move(*Ranges));
Utkarsh Saxena55925da2019-09-24 13:38:33 +00001247 });
1248}
1249
Sam McCall8d7ecc12019-12-16 19:08:51 +01001250void ClangdLSPServer::onDocumentLink(
1251 const DocumentLinkParams &Params,
1252 Callback<std::vector<DocumentLink>> Reply) {
1253
1254 // TODO(forster): This currently resolves all targets eagerly. This is slow,
1255 // because it blocks on the preamble/AST being built. We could respond to the
1256 // request faster by using string matching or the lexer to find the includes
1257 // and resolving the targets lazily.
1258 Server->documentLinks(
1259 Params.textDocument.uri.file(),
1260 [Reply = std::move(Reply)](
1261 llvm::Expected<std::vector<DocumentLink>> Links) mutable {
1262 if (!Links) {
1263 return Reply(Links.takeError());
1264 }
1265 return Reply(std::move(Links));
1266 });
1267}
1268
Sam McCall9e3063e2020-04-01 16:21:44 +02001269// Increment a numeric string: "" -> 1 -> 2 -> ... -> 9 -> 10 -> 11 ...
1270static void increment(std::string &S) {
1271 for (char &C : llvm::reverse(S)) {
1272 if (C != '9') {
1273 ++C;
1274 return;
1275 }
1276 C = '0';
1277 }
1278 S.insert(S.begin(), '1');
1279}
1280
Sam McCall71177ac2020-03-24 02:24:47 +01001281void ClangdLSPServer::onSemanticTokens(const SemanticTokensParams &Params,
1282 Callback<SemanticTokens> CB) {
1283 Server->semanticHighlights(
1284 Params.textDocument.uri.file(),
Sam McCall9e3063e2020-04-01 16:21:44 +02001285 [this, File(Params.textDocument.uri.file().str()), CB(std::move(CB))](
1286 llvm::Expected<std::vector<HighlightingToken>> HT) mutable {
1287 if (!HT)
1288 return CB(HT.takeError());
Sam McCall71177ac2020-03-24 02:24:47 +01001289 SemanticTokens Result;
Sam McCall9e3063e2020-04-01 16:21:44 +02001290 Result.tokens = toSemanticTokens(*HT);
1291 {
1292 std::lock_guard<std::mutex> Lock(SemanticTokensMutex);
1293 auto& Last = LastSemanticTokens[File];
1294
1295 Last.tokens = Result.tokens;
1296 increment(Last.resultId);
1297 Result.resultId = Last.resultId;
1298 }
1299 CB(std::move(Result));
1300 });
1301}
1302
1303void ClangdLSPServer::onSemanticTokensEdits(
1304 const SemanticTokensEditsParams &Params,
1305 Callback<SemanticTokensOrEdits> CB) {
1306 Server->semanticHighlights(
1307 Params.textDocument.uri.file(),
1308 [this, PrevResultID(Params.previousResultId),
1309 File(Params.textDocument.uri.file().str()), CB(std::move(CB))](
1310 llvm::Expected<std::vector<HighlightingToken>> HT) mutable {
1311 if (!HT)
1312 return CB(HT.takeError());
1313 std::vector<SemanticToken> Toks = toSemanticTokens(*HT);
1314
1315 SemanticTokensOrEdits Result;
1316 {
1317 std::lock_guard<std::mutex> Lock(SemanticTokensMutex);
1318 auto& Last = LastSemanticTokens[File];
1319
1320 if (PrevResultID == Last.resultId) {
1321 Result.edits = diffTokens(Last.tokens, Toks);
1322 } else {
1323 vlog("semanticTokens/edits: wanted edits vs {0} but last result "
1324 "had ID {1}. Returning full token list.",
1325 PrevResultID, Last.resultId);
1326 Result.tokens = Toks;
1327 }
1328
1329 Last.tokens = std::move(Toks);
1330 increment(Last.resultId);
1331 Result.resultId = Last.resultId;
1332 }
1333
Sam McCall71177ac2020-03-24 02:24:47 +01001334 CB(std::move(Result));
1335 });
1336}
1337
Sam McCalla69698f2019-03-27 17:47:49 +00001338ClangdLSPServer::ClangdLSPServer(
1339 class Transport &Transp, const FileSystemProvider &FSProvider,
1340 const clangd::CodeCompleteOptions &CCOpts,
Haojian Wu34d0e1b2020-02-19 15:37:36 +01001341 const clangd::RenameOptions &RenameOpts,
Sam McCalla69698f2019-03-27 17:47:49 +00001342 llvm::Optional<Path> CompileCommandsDir, bool UseDirBasedCDB,
1343 llvm::Optional<OffsetEncoding> ForcedOffsetEncoding,
1344 const ClangdServer::Options &Opts)
Kadir Cetinkaya9d662472019-10-15 14:20:52 +00001345 : BackgroundContext(Context::current().clone()), Transp(Transp),
1346 MsgHandler(new MessageHandler(*this)), FSProvider(FSProvider),
Haojian Wu34d0e1b2020-02-19 15:37:36 +01001347 CCOpts(CCOpts), RenameOpts(RenameOpts),
1348 SupportedSymbolKinds(defaultSymbolKinds()),
Kadir Cetinkaya133d46f2018-09-27 17:13:07 +00001349 SupportedCompletionItemKinds(defaultCompletionItemKinds()),
Sam McCallc55d09a2018-11-02 13:09:36 +00001350 UseDirBasedCDB(UseDirBasedCDB),
Sam McCalla69698f2019-03-27 17:47:49 +00001351 CompileCommandsDir(std::move(CompileCommandsDir)), ClangdServerOpts(Opts),
1352 NegotiatedOffsetEncoding(ForcedOffsetEncoding) {
Sam McCall2c30fbc2018-10-18 12:32:04 +00001353 // clang-format off
1354 MsgHandler->bind("initialize", &ClangdLSPServer::onInitialize);
Sam McCall8a2d2942020-03-03 12:12:14 +01001355 MsgHandler->bind("initialized", &ClangdLSPServer::onInitialized);
Sam McCall2c30fbc2018-10-18 12:32:04 +00001356 MsgHandler->bind("shutdown", &ClangdLSPServer::onShutdown);
Sam McCall422c8282018-11-26 16:00:11 +00001357 MsgHandler->bind("sync", &ClangdLSPServer::onSync);
Sam McCall2c30fbc2018-10-18 12:32:04 +00001358 MsgHandler->bind("textDocument/rangeFormatting", &ClangdLSPServer::onDocumentRangeFormatting);
1359 MsgHandler->bind("textDocument/onTypeFormatting", &ClangdLSPServer::onDocumentOnTypeFormatting);
1360 MsgHandler->bind("textDocument/formatting", &ClangdLSPServer::onDocumentFormatting);
1361 MsgHandler->bind("textDocument/codeAction", &ClangdLSPServer::onCodeAction);
1362 MsgHandler->bind("textDocument/completion", &ClangdLSPServer::onCompletion);
1363 MsgHandler->bind("textDocument/signatureHelp", &ClangdLSPServer::onSignatureHelp);
1364 MsgHandler->bind("textDocument/definition", &ClangdLSPServer::onGoToDefinition);
Sam McCall866ba2c2019-02-01 11:26:13 +00001365 MsgHandler->bind("textDocument/declaration", &ClangdLSPServer::onGoToDeclaration);
Sam McCall2c30fbc2018-10-18 12:32:04 +00001366 MsgHandler->bind("textDocument/references", &ClangdLSPServer::onReference);
1367 MsgHandler->bind("textDocument/switchSourceHeader", &ClangdLSPServer::onSwitchSourceHeader);
Haojian Wuf429ab62019-07-24 07:49:23 +00001368 MsgHandler->bind("textDocument/prepareRename", &ClangdLSPServer::onPrepareRename);
Sam McCall2c30fbc2018-10-18 12:32:04 +00001369 MsgHandler->bind("textDocument/rename", &ClangdLSPServer::onRename);
1370 MsgHandler->bind("textDocument/hover", &ClangdLSPServer::onHover);
1371 MsgHandler->bind("textDocument/documentSymbol", &ClangdLSPServer::onDocumentSymbol);
1372 MsgHandler->bind("workspace/executeCommand", &ClangdLSPServer::onCommand);
1373 MsgHandler->bind("textDocument/documentHighlight", &ClangdLSPServer::onDocumentHighlight);
1374 MsgHandler->bind("workspace/symbol", &ClangdLSPServer::onWorkspaceSymbol);
1375 MsgHandler->bind("textDocument/didOpen", &ClangdLSPServer::onDocumentDidOpen);
1376 MsgHandler->bind("textDocument/didClose", &ClangdLSPServer::onDocumentDidClose);
1377 MsgHandler->bind("textDocument/didChange", &ClangdLSPServer::onDocumentDidChange);
Sam McCall596b63a2020-04-10 03:27:37 +02001378 MsgHandler->bind("textDocument/didSave", &ClangdLSPServer::onDocumentDidSave);
Sam McCall2c30fbc2018-10-18 12:32:04 +00001379 MsgHandler->bind("workspace/didChangeWatchedFiles", &ClangdLSPServer::onFileEvent);
1380 MsgHandler->bind("workspace/didChangeConfiguration", &ClangdLSPServer::onChangeConfiguration);
Jan Korousb4067012018-11-27 16:40:46 +00001381 MsgHandler->bind("textDocument/symbolInfo", &ClangdLSPServer::onSymbolInfo);
Kadir Cetinkaya86658022019-03-19 09:27:04 +00001382 MsgHandler->bind("textDocument/typeHierarchy", &ClangdLSPServer::onTypeHierarchy);
Nathan Ridge087b0442019-07-13 03:24:48 +00001383 MsgHandler->bind("typeHierarchy/resolve", &ClangdLSPServer::onResolveTypeHierarchy);
Utkarsh Saxena55925da2019-09-24 13:38:33 +00001384 MsgHandler->bind("textDocument/selectionRange", &ClangdLSPServer::onSelectionRange);
Sam McCall8d7ecc12019-12-16 19:08:51 +01001385 MsgHandler->bind("textDocument/documentLink", &ClangdLSPServer::onDocumentLink);
Sam McCall71177ac2020-03-24 02:24:47 +01001386 MsgHandler->bind("textDocument/semanticTokens", &ClangdLSPServer::onSemanticTokens);
Sam McCall9e3063e2020-04-01 16:21:44 +02001387 MsgHandler->bind("textDocument/semanticTokens/edits", &ClangdLSPServer::onSemanticTokensEdits);
Sam McCall2c30fbc2018-10-18 12:32:04 +00001388 // clang-format on
1389}
1390
Kadir Cetinkaya6b850322020-03-17 19:08:23 +01001391ClangdLSPServer::~ClangdLSPServer() {
1392 IsBeingDestroyed = true;
Sam McCall8bda5f22019-10-23 11:11:18 +02001393 // Explicitly destroy ClangdServer first, blocking on threads it owns.
1394 // This ensures they don't access any other members.
1395 Server.reset();
1396}
Ilya Biryukov38d79772017-05-16 09:38:59 +00001397
Sam McCalldc8f3cf2018-10-17 07:32:05 +00001398bool ClangdLSPServer::run() {
Ilya Biryukovafb55542017-05-16 14:40:30 +00001399 // Run the Language Server loop.
Sam McCalldc8f3cf2018-10-17 07:32:05 +00001400 bool CleanExit = true;
Sam McCall2c30fbc2018-10-18 12:32:04 +00001401 if (auto Err = Transp.loop(*MsgHandler)) {
Sam McCalldc8f3cf2018-10-17 07:32:05 +00001402 elog("Transport error: {0}", std::move(Err));
1403 CleanExit = false;
1404 }
Ilya Biryukovafb55542017-05-16 14:40:30 +00001405
Sam McCalldc8f3cf2018-10-17 07:32:05 +00001406 return CleanExit && ShutdownRequestReceived;
Ilya Biryukov38d79772017-05-16 09:38:59 +00001407}
1408
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001409std::vector<Fix> ClangdLSPServer::getFixes(llvm::StringRef File,
Ilya Biryukov71028b82018-03-12 15:28:22 +00001410 const clangd::Diagnostic &D) {
Ilya Biryukov38d79772017-05-16 09:38:59 +00001411 std::lock_guard<std::mutex> Lock(FixItsMutex);
1412 auto DiagToFixItsIter = FixItsMap.find(File);
1413 if (DiagToFixItsIter == FixItsMap.end())
1414 return {};
1415
1416 const auto &DiagToFixItsMap = DiagToFixItsIter->second;
1417 auto FixItsIter = DiagToFixItsMap.find(D);
1418 if (FixItsIter == DiagToFixItsMap.end())
1419 return {};
1420
1421 return FixItsIter->second;
1422}
1423
Ilya Biryukovb0826bd2019-01-03 13:37:12 +00001424bool ClangdLSPServer::shouldRunCompletion(
1425 const CompletionParams &Params) const {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001426 llvm::StringRef Trigger = Params.context.triggerCharacter;
Ilya Biryukovb0826bd2019-01-03 13:37:12 +00001427 if (Params.context.triggerKind != CompletionTriggerKind::TriggerCharacter ||
1428 (Trigger != ">" && Trigger != ":"))
1429 return true;
1430
1431 auto Code = DraftMgr.getDraft(Params.textDocument.uri.file());
1432 if (!Code)
1433 return true; // completion code will log the error for untracked doc.
1434
1435 // A completion request is sent when the user types '>' or ':', but we only
1436 // want to trigger on '->' and '::'. We check the preceeding character to make
1437 // sure it matches what we expected.
1438 // Running the lexer here would be more robust (e.g. we can detect comments
1439 // and avoid triggering completion there), but we choose to err on the side
1440 // of simplicity here.
Sam McCallcaf5a4d2020-03-03 15:57:39 +01001441 auto Offset = positionToOffset(Code->Contents, Params.position,
Ilya Biryukovb0826bd2019-01-03 13:37:12 +00001442 /*AllowColumnsBeyondLineLength=*/false);
1443 if (!Offset) {
1444 vlog("could not convert position '{0}' to offset for file '{1}'",
1445 Params.position, Params.textDocument.uri.file());
1446 return true;
1447 }
1448 if (*Offset < 2)
1449 return false;
1450
1451 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 if (Trigger == ":")
Sam McCallcaf5a4d2020-03-03 15:57:39 +01001454 return Code->Contents[*Offset - 2] == ':'; // trigger only on '::'.
Ilya Biryukovb0826bd2019-01-03 13:37:12 +00001455 assert(false && "unhandled trigger character");
1456 return true;
1457}
1458
Johan Vikstroma848dab2019-07-04 07:53:12 +00001459void ClangdLSPServer::onHighlightingsReady(
Sam McCall2cd33e62020-03-04 00:33:29 +01001460 PathRef File, llvm::StringRef Version,
1461 std::vector<HighlightingToken> Highlightings) {
Johan Vikstromc2653ef22019-08-01 08:08:44 +00001462 std::vector<HighlightingToken> Old;
1463 std::vector<HighlightingToken> HighlightingsCopy = Highlightings;
1464 {
1465 std::lock_guard<std::mutex> Lock(HighlightingsMutex);
1466 Old = std::move(FileToHighlightings[File]);
1467 FileToHighlightings[File] = std::move(HighlightingsCopy);
1468 }
1469 // LSP allows us to send incremental edits of highlightings. Also need to diff
1470 // to remove highlightings from tokens that should no longer have them.
Haojian Wu0a6000f2019-08-26 08:38:45 +00001471 std::vector<LineHighlightings> Diffed = diffHighlightings(Highlightings, Old);
Sam McCalledf6a192020-03-24 00:31:14 +01001472 TheiaSemanticHighlightingParams Notification;
Sam McCall2cd33e62020-03-04 00:33:29 +01001473 Notification.TextDocument.uri =
1474 URIForFile::canonicalize(File, /*TUPath=*/File);
1475 Notification.TextDocument.version = decodeVersion(Version);
Sam McCalledf6a192020-03-24 00:31:14 +01001476 Notification.Lines = toTheiaSemanticHighlightingInformation(Diffed);
1477 publishTheiaSemanticHighlighting(Notification);
Johan Vikstroma848dab2019-07-04 07:53:12 +00001478}
1479
Sam McCall2cd33e62020-03-04 00:33:29 +01001480void ClangdLSPServer::onDiagnosticsReady(PathRef File, llvm::StringRef Version,
Sam McCalla7bb0cc2018-03-12 23:22:35 +00001481 std::vector<Diag> Diagnostics) {
Sam McCall6525a6b2020-03-03 12:44:40 +01001482 PublishDiagnosticsParams Notification;
Sam McCall2cd33e62020-03-04 00:33:29 +01001483 Notification.version = decodeVersion(Version);
Sam McCall6525a6b2020-03-03 12:44:40 +01001484 Notification.uri = URIForFile::canonicalize(File, /*TUPath=*/File);
Ilya Biryukov38d79772017-05-16 09:38:59 +00001485 DiagnosticToReplacementMap LocalFixIts; // Temporary storage
Sam McCalla7bb0cc2018-03-12 23:22:35 +00001486 for (auto &Diag : Diagnostics) {
Sam McCall6525a6b2020-03-03 12:44:40 +01001487 toLSPDiags(Diag, Notification.uri, DiagOpts,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001488 [&](clangd::Diagnostic Diag, llvm::ArrayRef<Fix> Fixes) {
Sam McCall16e70702018-10-24 07:59:38 +00001489 auto &FixItsForDiagnostic = LocalFixIts[Diag];
1490 llvm::copy(Fixes, std::back_inserter(FixItsForDiagnostic));
Sam McCall6525a6b2020-03-03 12:44:40 +01001491 Notification.diagnostics.push_back(std::move(Diag));
Sam McCall16e70702018-10-24 07:59:38 +00001492 });
Ilya Biryukov38d79772017-05-16 09:38:59 +00001493 }
1494
1495 // Cache FixIts
1496 {
Ilya Biryukov38d79772017-05-16 09:38:59 +00001497 std::lock_guard<std::mutex> Lock(FixItsMutex);
1498 FixItsMap[File] = LocalFixIts;
1499 }
1500
Ilya Biryukov49c10712019-03-25 10:15:11 +00001501 // Send a notification to the LSP client.
Sam McCall6525a6b2020-03-03 12:44:40 +01001502 publishDiagnostics(Notification);
Ilya Biryukov38d79772017-05-16 09:38:59 +00001503}
Simon Marchi9569fd52018-03-16 14:30:42 +00001504
Sam McCall7d20e802020-01-22 19:41:45 +01001505void ClangdLSPServer::onBackgroundIndexProgress(
1506 const BackgroundQueue::Stats &Stats) {
1507 static const char ProgressToken[] = "backgroundIndexProgress";
1508 std::lock_guard<std::mutex> Lock(BackgroundIndexProgressMutex);
1509
1510 auto NotifyProgress = [this](const BackgroundQueue::Stats &Stats) {
1511 if (BackgroundIndexProgressState != BackgroundIndexProgress::Live) {
1512 WorkDoneProgressBegin Begin;
1513 Begin.percentage = true;
1514 Begin.title = "indexing";
1515 progress(ProgressToken, std::move(Begin));
1516 BackgroundIndexProgressState = BackgroundIndexProgress::Live;
1517 }
1518
1519 if (Stats.Completed < Stats.Enqueued) {
1520 assert(Stats.Enqueued > Stats.LastIdle);
1521 WorkDoneProgressReport Report;
1522 Report.percentage = 100.0 * (Stats.Completed - Stats.LastIdle) /
1523 (Stats.Enqueued - Stats.LastIdle);
1524 Report.message =
1525 llvm::formatv("{0}/{1}", Stats.Completed - Stats.LastIdle,
1526 Stats.Enqueued - Stats.LastIdle);
1527 progress(ProgressToken, std::move(Report));
1528 } else {
1529 assert(Stats.Completed == Stats.Enqueued);
1530 progress(ProgressToken, WorkDoneProgressEnd());
1531 BackgroundIndexProgressState = BackgroundIndexProgress::Empty;
1532 }
1533 };
1534
1535 switch (BackgroundIndexProgressState) {
1536 case BackgroundIndexProgress::Unsupported:
1537 return;
1538 case BackgroundIndexProgress::Creating:
1539 // Cache this update for when the progress bar is available.
1540 PendingBackgroundIndexProgress = Stats;
1541 return;
1542 case BackgroundIndexProgress::Empty: {
1543 if (BackgroundIndexSkipCreate) {
1544 NotifyProgress(Stats);
1545 break;
1546 }
1547 // Cache this update for when the progress bar is available.
1548 PendingBackgroundIndexProgress = Stats;
1549 BackgroundIndexProgressState = BackgroundIndexProgress::Creating;
1550 WorkDoneProgressCreateParams CreateRequest;
1551 CreateRequest.token = ProgressToken;
1552 call<std::nullptr_t>(
1553 "window/workDoneProgress/create", CreateRequest,
1554 [this, NotifyProgress](llvm::Expected<std::nullptr_t> E) {
1555 std::lock_guard<std::mutex> Lock(BackgroundIndexProgressMutex);
1556 if (E) {
1557 NotifyProgress(this->PendingBackgroundIndexProgress);
1558 } else {
1559 elog("Failed to create background index progress bar: {0}",
1560 E.takeError());
1561 // give up forever rather than thrashing about
1562 BackgroundIndexProgressState = BackgroundIndexProgress::Unsupported;
1563 }
1564 });
1565 break;
1566 }
1567 case BackgroundIndexProgress::Live:
1568 NotifyProgress(Stats);
1569 break;
1570 }
1571}
1572
Haojian Wub6188492018-12-20 15:39:12 +00001573void ClangdLSPServer::onFileUpdated(PathRef File, const TUStatus &Status) {
1574 if (!SupportFileStatus)
1575 return;
1576 // FIXME: we don't emit "BuildingFile" and `RunningAction`, as these
1577 // two statuses are running faster in practice, which leads the UI constantly
1578 // changing, and doesn't provide much value. We may want to emit status at a
1579 // reasonable time interval (e.g. 0.5s).
Kadir Cetinkaya6b850322020-03-17 19:08:23 +01001580 if (Status.PreambleActivity == PreambleAction::Idle &&
1581 (Status.ASTActivity.K == ASTAction::Building ||
1582 Status.ASTActivity.K == ASTAction::RunningAction))
Haojian Wub6188492018-12-20 15:39:12 +00001583 return;
1584 notify("textDocument/clangd.fileStatus", Status.render(File));
1585}
1586
Sam McCall596b63a2020-04-10 03:27:37 +02001587void ClangdLSPServer::reparseOpenFilesIfNeeded(
1588 llvm::function_ref<bool(llvm::StringRef File)> Filter) {
David Goldman60249c22020-01-13 17:01:10 -05001589 // Reparse only opened files that were modified.
Simon Marchi9569fd52018-03-16 14:30:42 +00001590 for (const Path &FilePath : DraftMgr.getActiveFiles())
Sam McCall596b63a2020-04-10 03:27:37 +02001591 if (Filter(FilePath))
Sam McCall2cd33e62020-03-04 00:33:29 +01001592 if (auto Draft = DraftMgr.getDraft(FilePath)) // else disappeared in race?
1593 Server->addDocument(FilePath, std::move(Draft->Contents),
1594 encodeVersion(Draft->Version),
1595 WantDiagnostics::Auto);
Simon Marchi9569fd52018-03-16 14:30:42 +00001596}
Alex Lorenzf8087862018-08-01 17:39:29 +00001597
Sam McCallc008af62018-10-20 15:30:37 +00001598} // namespace clangd
1599} // namespace clang