blob: a85736b948300c5f4cfaf5a4788d65d4e34da3e5 [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"
Sam McCall032727f2020-05-06 01:39:59 +020010#include "CodeComplete.h"
Ilya Biryukov71028b82018-03-12 15:28:22 +000011#include "Diagnostics.h"
Kadir Cetinkaya5b270932019-09-09 12:28:44 +000012#include "DraftStore.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
Kadir Cetinkayae64f99c2020-04-16 23:12:09 +020046// Tracks end-to-end latency of high level lsp calls. Measurements are in
47// seconds.
48constexpr trace::Metric LSPLatency("lsp_latency", trace::Metric::Distribution,
49 "method_name");
50
Sam McCall2cd33e62020-03-04 00:33:29 +010051// LSP defines file versions as numbers that increase.
52// ClangdServer treats them as opaque and therefore uses strings instead.
53std::string encodeVersion(int64_t LSPVersion) {
54 return llvm::to_string(LSPVersion);
55}
56llvm::Optional<int64_t> decodeVersion(llvm::StringRef Encoded) {
57 int64_t Result;
58 if (llvm::to_integer(Encoded, Result, 10))
59 return Result;
Kadir Cetinkayabceca7a2020-09-11 11:30:06 +020060 if (!Encoded.empty()) // Empty can be e.g. diagnostics on close.
Sam McCall2cd33e62020-03-04 00:33:29 +010061 elog("unexpected non-numeric version {0}", Encoded);
62 return llvm::None;
63}
64
Ilya Biryukovcce67a32019-01-29 14:17:36 +000065/// Transforms a tweak into a code action that would apply it if executed.
66/// EXPECTS: T.prepare() was called and returned true.
67CodeAction toCodeAction(const ClangdServer::TweakRef &T, const URIForFile &File,
68 Range Selection) {
69 CodeAction CA;
70 CA.title = T.Title;
Sam McCall395fde72019-06-18 13:37:54 +000071 switch (T.Intent) {
72 case Tweak::Refactor:
Benjamin Krameradcd0262020-01-28 20:23:46 +010073 CA.kind = std::string(CodeAction::REFACTOR_KIND);
Sam McCall395fde72019-06-18 13:37:54 +000074 break;
75 case Tweak::Info:
Benjamin Krameradcd0262020-01-28 20:23:46 +010076 CA.kind = std::string(CodeAction::INFO_KIND);
Sam McCall395fde72019-06-18 13:37:54 +000077 break;
78 }
Ilya Biryukovcce67a32019-01-29 14:17:36 +000079 // This tweak may have an expensive second stage, we only run it if the user
80 // actually chooses it in the UI. We reply with a command that would run the
81 // corresponding tweak.
82 // FIXME: for some tweaks, computing the edits is cheap and we could send them
83 // directly.
84 CA.command.emplace();
85 CA.command->title = T.Title;
Benjamin Krameradcd0262020-01-28 20:23:46 +010086 CA.command->command = std::string(Command::CLANGD_APPLY_TWEAK);
Ilya Biryukovcce67a32019-01-29 14:17:36 +000087 CA.command->tweakArgs.emplace();
88 CA.command->tweakArgs->file = File;
89 CA.command->tweakArgs->tweakID = T.ID;
90 CA.command->tweakArgs->selection = Selection;
91 return CA;
Simon Pilgrime9a136b2019-02-03 14:08:30 +000092}
Ilya Biryukovcce67a32019-01-29 14:17:36 +000093
Ilya Biryukov19d75602018-11-23 15:21:19 +000094void adjustSymbolKinds(llvm::MutableArrayRef<DocumentSymbol> Syms,
95 SymbolKindBitset Kinds) {
96 for (auto &S : Syms) {
97 S.kind = adjustKindToCapability(S.kind, Kinds);
98 adjustSymbolKinds(S.children, Kinds);
99 }
100}
101
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000102SymbolKindBitset defaultSymbolKinds() {
103 SymbolKindBitset Defaults;
104 for (size_t I = SymbolKindMin; I <= static_cast<size_t>(SymbolKind::Array);
105 ++I)
106 Defaults.set(I);
107 return Defaults;
108}
109
Kadir Cetinkaya133d46f2018-09-27 17:13:07 +0000110CompletionItemKindBitset defaultCompletionItemKinds() {
111 CompletionItemKindBitset Defaults;
112 for (size_t I = CompletionItemKindMin;
113 I <= static_cast<size_t>(CompletionItemKind::Reference); ++I)
114 Defaults.set(I);
115 return Defaults;
116}
117
Haojian Wu1ca2ee42019-07-04 12:27:21 +0000118// Build a lookup table (HighlightingKind => {TextMate Scopes}), which is sent
119// to the LSP client.
120std::vector<std::vector<std::string>> buildHighlightScopeLookupTable() {
121 std::vector<std::vector<std::string>> LookupTable;
122 // HighlightingKind is using as the index.
Ilya Biryukov63d5d162019-09-09 08:57:17 +0000123 for (int KindValue = 0; KindValue <= (int)HighlightingKind::LastKind;
Haojian Wu1ca2ee42019-07-04 12:27:21 +0000124 ++KindValue)
Benjamin Krameradcd0262020-01-28 20:23:46 +0100125 LookupTable.push_back(
126 {std::string(toTextMateScope((HighlightingKind)(KindValue)))});
Haojian Wu1ca2ee42019-07-04 12:27:21 +0000127 return LookupTable;
128}
129
Haojian Wu852bafa2019-10-23 14:40:20 +0200130// Makes sure edits in \p FE are applicable to latest file contents reported by
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000131// editor. If not generates an error message containing information about files
132// that needs to be saved.
Haojian Wu852bafa2019-10-23 14:40:20 +0200133llvm::Error validateEdits(const DraftStore &DraftMgr, const FileEdits &FE) {
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000134 size_t InvalidFileCount = 0;
135 llvm::StringRef LastInvalidFile;
Haojian Wu852bafa2019-10-23 14:40:20 +0200136 for (const auto &It : FE) {
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000137 if (auto Draft = DraftMgr.getDraft(It.first())) {
138 // If the file is open in user's editor, make sure the version we
139 // saw and current version are compatible as this is the text that
140 // will be replaced by editors.
Sam McCallcaf5a4d2020-03-03 15:57:39 +0100141 if (!It.second.canApplyTo(Draft->Contents)) {
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000142 ++InvalidFileCount;
143 LastInvalidFile = It.first();
144 }
145 }
146 }
147 if (!InvalidFileCount)
148 return llvm::Error::success();
149 if (InvalidFileCount == 1)
Sam McCall30667c92020-07-08 21:49:38 +0200150 return error("File must be saved first: {0}", LastInvalidFile);
151 return error("Files must be saved first: {0} (and {1} others)",
152 LastInvalidFile, InvalidFileCount - 1);
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000153}
154
Ilya Biryukovafb55542017-05-16 14:40:30 +0000155} // namespace
156
Sam McCall2c30fbc2018-10-18 12:32:04 +0000157// MessageHandler dispatches incoming LSP messages.
158// It handles cross-cutting concerns:
159// - serializes/deserializes protocol objects to JSON
160// - logging of inbound messages
161// - cancellation handling
162// - basic call tracing
Sam McCall3d0adbe2018-10-18 14:41:50 +0000163// MessageHandler ensures that initialize() is called before any other handler.
Sam McCall2c30fbc2018-10-18 12:32:04 +0000164class ClangdLSPServer::MessageHandler : public Transport::MessageHandler {
165public:
166 MessageHandler(ClangdLSPServer &Server) : Server(Server) {}
167
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000168 bool onNotify(llvm::StringRef Method, llvm::json::Value Params) override {
Sam McCalla69698f2019-03-27 17:47:49 +0000169 WithContext HandlerContext(handlerContext());
Sam McCall2c30fbc2018-10-18 12:32:04 +0000170 log("<-- {0}", Method);
171 if (Method == "exit")
172 return false;
Sam McCall3d0adbe2018-10-18 14:41:50 +0000173 if (!Server.Server)
174 elog("Notification {0} before initialization", Method);
175 else if (Method == "$/cancelRequest")
Sam McCall2c30fbc2018-10-18 12:32:04 +0000176 onCancel(std::move(Params));
177 else if (auto Handler = Notifications.lookup(Method))
178 Handler(std::move(Params));
179 else
180 log("unhandled notification {0}", Method);
181 return true;
182 }
183
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000184 bool onCall(llvm::StringRef Method, llvm::json::Value Params,
185 llvm::json::Value ID) override {
Sam McCalla69698f2019-03-27 17:47:49 +0000186 WithContext HandlerContext(handlerContext());
Sam McCalle2f3a732018-10-24 14:26:26 +0000187 // Calls can be canceled by the client. Add cancellation context.
188 WithContext WithCancel(cancelableRequestContext(ID));
Kadir Cetinkayae64f99c2020-04-16 23:12:09 +0200189 trace::Span Tracer(Method, LSPLatency);
Sam McCalle2f3a732018-10-24 14:26:26 +0000190 SPAN_ATTACH(Tracer, "Params", Params);
191 ReplyOnce Reply(ID, Method, &Server, Tracer.Args);
Sam McCall2c30fbc2018-10-18 12:32:04 +0000192 log("<-- {0}({1})", Method, ID);
Sam McCall3d0adbe2018-10-18 14:41:50 +0000193 if (!Server.Server && Method != "initialize") {
194 elog("Call {0} before initialization.", Method);
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000195 Reply(llvm::make_error<LSPError>("server not initialized",
196 ErrorCode::ServerNotInitialized));
Sam McCall3d0adbe2018-10-18 14:41:50 +0000197 } else if (auto Handler = Calls.lookup(Method))
Sam McCalle2f3a732018-10-24 14:26:26 +0000198 Handler(std::move(Params), std::move(Reply));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000199 else
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000200 Reply(llvm::make_error<LSPError>("method not found",
201 ErrorCode::MethodNotFound));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000202 return true;
203 }
204
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000205 bool onReply(llvm::json::Value ID,
206 llvm::Expected<llvm::json::Value> Result) override {
Sam McCalla69698f2019-03-27 17:47:49 +0000207 WithContext HandlerContext(handlerContext());
Haojian Wuf2516342019-08-05 12:48:09 +0000208
209 Callback<llvm::json::Value> ReplyHandler = nullptr;
210 if (auto IntID = ID.getAsInteger()) {
211 std::lock_guard<std::mutex> Mutex(CallMutex);
212 // Find a corresponding callback for the request ID;
213 for (size_t Index = 0; Index < ReplyCallbacks.size(); ++Index) {
214 if (ReplyCallbacks[Index].first == *IntID) {
215 ReplyHandler = std::move(ReplyCallbacks[Index].second);
216 ReplyCallbacks.erase(ReplyCallbacks.begin() +
217 Index); // remove the entry
218 break;
219 }
220 }
221 }
222
223 if (!ReplyHandler) {
224 // No callback being found, use a default log callback.
225 ReplyHandler = [&ID](llvm::Expected<llvm::json::Value> Result) {
226 elog("received a reply with ID {0}, but there was no such call", ID);
227 if (!Result)
228 llvm::consumeError(Result.takeError());
229 };
230 }
231
232 // Log and run the reply handler.
233 if (Result) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000234 log("<-- reply({0})", ID);
Haojian Wuf2516342019-08-05 12:48:09 +0000235 ReplyHandler(std::move(Result));
236 } else {
237 auto Err = Result.takeError();
238 log("<-- reply({0}) error: {1}", ID, Err);
239 ReplyHandler(std::move(Err));
240 }
Sam McCall2c30fbc2018-10-18 12:32:04 +0000241 return true;
242 }
243
244 // Bind an LSP method name to a call.
Sam McCalle2f3a732018-10-24 14:26:26 +0000245 template <typename Param, typename Result>
Sam McCall2c30fbc2018-10-18 12:32:04 +0000246 void bind(const char *Method,
Sam McCalle2f3a732018-10-24 14:26:26 +0000247 void (ClangdLSPServer::*Handler)(const Param &, Callback<Result>)) {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000248 Calls[Method] = [Method, Handler, this](llvm::json::Value RawParams,
Sam McCalle2f3a732018-10-24 14:26:26 +0000249 ReplyOnce Reply) {
Sam McCallfa69b602020-09-24 01:14:12 +0200250 auto P = parse<Param>(RawParams, Method, "request");
251 if (!P)
252 return Reply(P.takeError());
253 (Server.*Handler)(*P, std::move(Reply));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000254 };
255 }
256
Haojian Wuf2516342019-08-05 12:48:09 +0000257 // Bind a reply callback to a request. The callback will be invoked when
258 // clangd receives the reply from the LSP client.
259 // Return a call id of the request.
260 llvm::json::Value bindReply(Callback<llvm::json::Value> Reply) {
261 llvm::Optional<std::pair<int, Callback<llvm::json::Value>>> OldestCB;
262 int ID;
263 {
264 std::lock_guard<std::mutex> Mutex(CallMutex);
265 ID = NextCallID++;
266 ReplyCallbacks.emplace_back(ID, std::move(Reply));
267
268 // If the queue overflows, we assume that the client didn't reply the
269 // oldest request, and run the corresponding callback which replies an
270 // error to the client.
271 if (ReplyCallbacks.size() > MaxReplayCallbacks) {
272 elog("more than {0} outstanding LSP calls, forgetting about {1}",
273 MaxReplayCallbacks, ReplyCallbacks.front().first);
274 OldestCB = std::move(ReplyCallbacks.front());
275 ReplyCallbacks.pop_front();
276 }
277 }
278 if (OldestCB)
Sam McCall30667c92020-07-08 21:49:38 +0200279 OldestCB->second(
280 error("failed to receive a client reply for request ({0})",
281 OldestCB->first));
Haojian Wuf2516342019-08-05 12:48:09 +0000282 return ID;
283 }
284
Sam McCall2c30fbc2018-10-18 12:32:04 +0000285 // Bind an LSP method name to a notification.
286 template <typename Param>
287 void bind(const char *Method,
288 void (ClangdLSPServer::*Handler)(const Param &)) {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000289 Notifications[Method] = [Method, Handler,
290 this](llvm::json::Value RawParams) {
Sam McCallfa69b602020-09-24 01:14:12 +0200291 llvm::Expected<Param> P = parse<Param>(RawParams, Method, "request");
292 if (!P)
293 return llvm::consumeError(P.takeError());
Kadir Cetinkayae64f99c2020-04-16 23:12:09 +0200294 trace::Span Tracer(Method, LSPLatency);
Sam McCall2c30fbc2018-10-18 12:32:04 +0000295 SPAN_ATTACH(Tracer, "Params", RawParams);
Sam McCallfa69b602020-09-24 01:14:12 +0200296 (Server.*Handler)(*P);
Sam McCall2c30fbc2018-10-18 12:32:04 +0000297 };
298 }
299
300private:
Sam McCalle2f3a732018-10-24 14:26:26 +0000301 // Function object to reply to an LSP call.
302 // Each instance must be called exactly once, otherwise:
303 // - the bug is logged, and (in debug mode) an assert will fire
304 // - if there was no reply, an error reply is sent
305 // - if there were multiple replies, only the first is sent
306 class ReplyOnce {
307 std::atomic<bool> Replied = {false};
Sam McCalld7babe42018-10-24 15:18:40 +0000308 std::chrono::steady_clock::time_point Start;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000309 llvm::json::Value ID;
Sam McCalle2f3a732018-10-24 14:26:26 +0000310 std::string Method;
311 ClangdLSPServer *Server; // Null when moved-from.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000312 llvm::json::Object *TraceArgs;
Sam McCalle2f3a732018-10-24 14:26:26 +0000313
314 public:
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000315 ReplyOnce(const llvm::json::Value &ID, llvm::StringRef Method,
316 ClangdLSPServer *Server, llvm::json::Object *TraceArgs)
Sam McCalld7babe42018-10-24 15:18:40 +0000317 : Start(std::chrono::steady_clock::now()), ID(ID), Method(Method),
318 Server(Server), TraceArgs(TraceArgs) {
Sam McCalle2f3a732018-10-24 14:26:26 +0000319 assert(Server);
320 }
321 ReplyOnce(ReplyOnce &&Other)
Sam McCalld7babe42018-10-24 15:18:40 +0000322 : Replied(Other.Replied.load()), Start(Other.Start),
323 ID(std::move(Other.ID)), Method(std::move(Other.Method)),
324 Server(Other.Server), TraceArgs(Other.TraceArgs) {
Sam McCalle2f3a732018-10-24 14:26:26 +0000325 Other.Server = nullptr;
326 }
Ilya Biryukov22fa4652019-01-03 13:28:05 +0000327 ReplyOnce &operator=(ReplyOnce &&) = delete;
Sam McCalle2f3a732018-10-24 14:26:26 +0000328 ReplyOnce(const ReplyOnce &) = delete;
Ilya Biryukov22fa4652019-01-03 13:28:05 +0000329 ReplyOnce &operator=(const ReplyOnce &) = delete;
Sam McCalle2f3a732018-10-24 14:26:26 +0000330
331 ~ReplyOnce() {
Haojian Wuf2516342019-08-05 12:48:09 +0000332 // There's one legitimate reason to never reply to a request: clangd's
333 // request handler send a call to the client (e.g. applyEdit) and the
334 // client never replied. In this case, the ReplyOnce is owned by
335 // ClangdLSPServer's reply callback table and is destroyed along with the
336 // server. We don't attempt to send a reply in this case, there's little
337 // to be gained from doing so.
338 if (Server && !Server->IsBeingDestroyed && !Replied) {
Sam McCalle2f3a732018-10-24 14:26:26 +0000339 elog("No reply to message {0}({1})", Method, ID);
340 assert(false && "must reply to all calls!");
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000341 (*this)(llvm::make_error<LSPError>("server failed to reply",
342 ErrorCode::InternalError));
Sam McCalle2f3a732018-10-24 14:26:26 +0000343 }
344 }
345
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000346 void operator()(llvm::Expected<llvm::json::Value> Reply) {
Sam McCalle2f3a732018-10-24 14:26:26 +0000347 assert(Server && "moved-from!");
348 if (Replied.exchange(true)) {
349 elog("Replied twice to message {0}({1})", Method, ID);
350 assert(false && "must reply to each call only once!");
351 return;
352 }
Sam McCalld7babe42018-10-24 15:18:40 +0000353 auto Duration = std::chrono::steady_clock::now() - Start;
354 if (Reply) {
355 log("--> reply:{0}({1}) {2:ms}", Method, ID, Duration);
356 if (TraceArgs)
Sam McCalle2f3a732018-10-24 14:26:26 +0000357 (*TraceArgs)["Reply"] = *Reply;
Sam McCalld7babe42018-10-24 15:18:40 +0000358 std::lock_guard<std::mutex> Lock(Server->TranspWriter);
359 Server->Transp.reply(std::move(ID), std::move(Reply));
360 } else {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000361 llvm::Error Err = Reply.takeError();
Sam McCalld7babe42018-10-24 15:18:40 +0000362 log("--> reply:{0}({1}) {2:ms}, error: {3}", Method, ID, Duration, Err);
363 if (TraceArgs)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000364 (*TraceArgs)["Error"] = llvm::to_string(Err);
Sam McCalld7babe42018-10-24 15:18:40 +0000365 std::lock_guard<std::mutex> Lock(Server->TranspWriter);
366 Server->Transp.reply(std::move(ID), std::move(Err));
Sam McCalle2f3a732018-10-24 14:26:26 +0000367 }
Sam McCalle2f3a732018-10-24 14:26:26 +0000368 }
369 };
370
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000371 llvm::StringMap<std::function<void(llvm::json::Value)>> Notifications;
372 llvm::StringMap<std::function<void(llvm::json::Value, ReplyOnce)>> Calls;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000373
374 // Method calls may be cancelled by ID, so keep track of their state.
375 // This needs a mutex: handlers may finish on a different thread, and that's
376 // when we clean up entries in the map.
377 mutable std::mutex RequestCancelersMutex;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000378 llvm::StringMap<std::pair<Canceler, /*Cookie*/ unsigned>> RequestCancelers;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000379 unsigned NextRequestCookie = 0; // To disambiguate reused IDs, see below.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000380 void onCancel(const llvm::json::Value &Params) {
381 const llvm::json::Value *ID = nullptr;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000382 if (auto *O = Params.getAsObject())
383 ID = O->get("id");
384 if (!ID) {
385 elog("Bad cancellation request: {0}", Params);
386 return;
387 }
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000388 auto StrID = llvm::to_string(*ID);
Sam McCall2c30fbc2018-10-18 12:32:04 +0000389 std::lock_guard<std::mutex> Lock(RequestCancelersMutex);
390 auto It = RequestCancelers.find(StrID);
391 if (It != RequestCancelers.end())
392 It->second.first(); // Invoke the canceler.
393 }
Sam McCalla69698f2019-03-27 17:47:49 +0000394
395 Context handlerContext() const {
396 return Context::current().derive(
397 kCurrentOffsetEncoding,
Sam McCall7ba07792020-09-29 10:37:46 +0200398 Server.Opts.OffsetEncoding.getValueOr(OffsetEncoding::UTF16));
Sam McCalla69698f2019-03-27 17:47:49 +0000399 }
400
Sam McCall2c30fbc2018-10-18 12:32:04 +0000401 // We run cancelable requests in a context that does two things:
402 // - allows cancellation using RequestCancelers[ID]
403 // - cleans up the entry in RequestCancelers when it's no longer needed
404 // If a client reuses an ID, the last wins and the first cannot be canceled.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000405 Context cancelableRequestContext(const llvm::json::Value &ID) {
Sam McCall31db1e02020-04-11 18:19:50 +0200406 auto Task = cancelableTask(
407 /*Reason=*/static_cast<int>(ErrorCode::RequestCancelled));
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000408 auto StrID = llvm::to_string(ID); // JSON-serialize ID for map key.
Sam McCall2c30fbc2018-10-18 12:32:04 +0000409 auto Cookie = NextRequestCookie++; // No lock, only called on main thread.
410 {
411 std::lock_guard<std::mutex> Lock(RequestCancelersMutex);
412 RequestCancelers[StrID] = {std::move(Task.second), Cookie};
413 }
414 // When the request ends, we can clean up the entry we just added.
415 // The cookie lets us check that it hasn't been overwritten due to ID
416 // reuse.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000417 return Task.first.derive(llvm::make_scope_exit([this, StrID, Cookie] {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000418 std::lock_guard<std::mutex> Lock(RequestCancelersMutex);
419 auto It = RequestCancelers.find(StrID);
420 if (It != RequestCancelers.end() && It->second.second == Cookie)
421 RequestCancelers.erase(It);
422 }));
423 }
424
Kadir Cetinkaya9a3a87d2019-10-09 13:59:31 +0000425 // The maximum number of callbacks held in clangd.
426 //
427 // We bound the maximum size to the pending map to prevent memory leakage
428 // for cases where LSP clients don't reply for the request.
429 // This has to go after RequestCancellers and RequestCancellersMutex since it
430 // can contain a callback that has a cancelable context.
431 static constexpr int MaxReplayCallbacks = 100;
432 mutable std::mutex CallMutex;
433 int NextCallID = 0; /* GUARDED_BY(CallMutex) */
434 std::deque<std::pair</*RequestID*/ int,
435 /*ReplyHandler*/ Callback<llvm::json::Value>>>
436 ReplyCallbacks; /* GUARDED_BY(CallMutex) */
437
Sam McCall2c30fbc2018-10-18 12:32:04 +0000438 ClangdLSPServer &Server;
439};
Haojian Wuf2516342019-08-05 12:48:09 +0000440constexpr int ClangdLSPServer::MessageHandler::MaxReplayCallbacks;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000441
442// call(), notify(), and reply() wrap the Transport, adding logging and locking.
Haojian Wuf2516342019-08-05 12:48:09 +0000443void ClangdLSPServer::callRaw(StringRef Method, llvm::json::Value Params,
444 Callback<llvm::json::Value> CB) {
445 auto ID = MsgHandler->bindReply(std::move(CB));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000446 log("--> {0}({1})", Method, ID);
Sam McCall2c30fbc2018-10-18 12:32:04 +0000447 std::lock_guard<std::mutex> Lock(TranspWriter);
448 Transp.call(Method, std::move(Params), ID);
449}
450
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000451void ClangdLSPServer::notify(llvm::StringRef Method, llvm::json::Value Params) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000452 log("--> {0}", Method);
453 std::lock_guard<std::mutex> Lock(TranspWriter);
454 Transp.notify(Method, std::move(Params));
455}
456
Sam McCall71177ac2020-03-24 02:24:47 +0100457static std::vector<llvm::StringRef> semanticTokenTypes() {
458 std::vector<llvm::StringRef> Types;
459 for (unsigned I = 0; I <= static_cast<unsigned>(HighlightingKind::LastKind);
460 ++I)
461 Types.push_back(toSemanticTokenType(static_cast<HighlightingKind>(I)));
462 return Types;
463}
464
Sam McCall2c30fbc2018-10-18 12:32:04 +0000465void ClangdLSPServer::onInitialize(const InitializeParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000466 Callback<llvm::json::Value> Reply) {
Sam McCalla69698f2019-03-27 17:47:49 +0000467 // Determine character encoding first as it affects constructed ClangdServer.
Sam McCall7ba07792020-09-29 10:37:46 +0200468 if (Params.capabilities.offsetEncoding && !Opts.OffsetEncoding) {
469 Opts.OffsetEncoding = OffsetEncoding::UTF16; // fallback
Sam McCalla69698f2019-03-27 17:47:49 +0000470 for (OffsetEncoding Supported : *Params.capabilities.offsetEncoding)
471 if (Supported != OffsetEncoding::UnsupportedEncoding) {
Sam McCall7ba07792020-09-29 10:37:46 +0200472 Opts.OffsetEncoding = Supported;
Sam McCalla69698f2019-03-27 17:47:49 +0000473 break;
474 }
475 }
Sam McCalla69698f2019-03-27 17:47:49 +0000476
Sam McCall7ba07792020-09-29 10:37:46 +0200477 Opts.TheiaSemanticHighlighting =
Sam McCalledf6a192020-03-24 00:31:14 +0100478 Params.capabilities.TheiaSemanticHighlighting;
Sam McCallfc830102020-04-01 12:02:28 +0200479 if (Params.capabilities.TheiaSemanticHighlighting &&
480 Params.capabilities.SemanticTokens) {
481 log("Client supports legacy semanticHighlights notification and standard "
482 "semanticTokens request, choosing the latter (no notifications).");
Sam McCall7ba07792020-09-29 10:37:46 +0200483 Opts.TheiaSemanticHighlighting = false;
Sam McCallfc830102020-04-01 12:02:28 +0200484 }
485
Sam McCall0d9b40f2018-10-19 15:42:23 +0000486 if (Params.rootUri && *Params.rootUri)
Sam McCall7ba07792020-09-29 10:37:46 +0200487 Opts.WorkspaceRoot = std::string(Params.rootUri->file());
Sam McCall0d9b40f2018-10-19 15:42:23 +0000488 else if (Params.rootPath && !Params.rootPath->empty())
Sam McCall7ba07792020-09-29 10:37:46 +0200489 Opts.WorkspaceRoot = *Params.rootPath;
Sam McCall3d0adbe2018-10-18 14:41:50 +0000490 if (Server)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000491 return Reply(llvm::make_error<LSPError>("server already initialized",
492 ErrorCode::InvalidRequest));
Sam McCallbc904612018-10-25 04:22:52 +0000493 if (const auto &Dir = Params.initializationOptions.compilationDatabasePath)
Sam McCall7ba07792020-09-29 10:37:46 +0200494 Opts.CompileCommandsDir = Dir;
495 if (Opts.UseDirBasedCDB) {
Jonas Devlieghere1c705d92019-08-14 23:52:23 +0000496 BaseCDB = std::make_unique<DirectoryBasedGlobalCompilationDatabase>(
Sam McCall7ba07792020-09-29 10:37:46 +0200497 Opts.CompileCommandsDir);
498 BaseCDB = getQueryDriverDatabase(llvm::makeArrayRef(Opts.QueryDriverGlobs),
499 std::move(BaseCDB));
Kadir Cetinkaya256247c2019-06-26 07:45:27 +0000500 }
Sam McCall99768b22019-11-29 19:37:48 +0100501 auto Mangler = CommandMangler::detect();
Sam McCall7ba07792020-09-29 10:37:46 +0200502 if (Opts.ResourceDir)
503 Mangler.ResourceDir = *Opts.ResourceDir;
Kadir Cetinkayabe6b35d2019-01-22 09:10:20 +0000504 CDB.emplace(BaseCDB.get(), Params.initializationOptions.fallbackFlags,
Sam McCall2a3ac012020-06-09 22:54:42 +0200505 tooling::ArgumentsAdjuster(std::move(Mangler)));
Kadir Cetinkaya9d662472019-10-15 14:20:52 +0000506 {
507 // Switch caller's context with LSPServer's background context. Since we
508 // rather want to propagate information from LSPServer's context into the
509 // Server, CDB, etc.
510 WithContext MainContext(BackgroundContext.clone());
511 llvm::Optional<WithContextValue> WithOffsetEncoding;
Sam McCall7ba07792020-09-29 10:37:46 +0200512 if (Opts.OffsetEncoding)
513 WithOffsetEncoding.emplace(kCurrentOffsetEncoding, *Opts.OffsetEncoding);
514 Server.emplace(*CDB, TFS, Opts,
Sam McCall6ef1cce2020-01-24 14:08:56 +0100515 static_cast<ClangdServer::Callbacks *>(this));
Kadir Cetinkaya9d662472019-10-15 14:20:52 +0000516 }
Sam McCallbc904612018-10-25 04:22:52 +0000517 applyConfiguration(Params.initializationOptions.ConfigSettings);
Simon Marchi88016782018-08-01 11:28:49 +0000518
Sam McCall7ba07792020-09-29 10:37:46 +0200519 Opts.CodeComplete.EnableSnippets = Params.capabilities.CompletionSnippets;
520 Opts.CodeComplete.IncludeFixIts = Params.capabilities.CompletionFixes;
521 if (!Opts.CodeComplete.BundleOverloads.hasValue())
522 Opts.CodeComplete.BundleOverloads = Params.capabilities.HasSignatureHelp;
523 Opts.CodeComplete.DocumentationFormat =
Sam McCalla3a27a72020-04-30 10:49:32 +0200524 Params.capabilities.CompletionDocumentationFormat;
Sam McCallbf6a2fc2018-10-17 07:33:42 +0000525 DiagOpts.EmbedFixesInDiagnostics = Params.capabilities.DiagnosticFixes;
526 DiagOpts.SendDiagnosticCategory = Params.capabilities.DiagnosticCategory;
Sam McCallc9e4ee92019-04-18 15:17:07 +0000527 DiagOpts.EmitRelatedLocations =
528 Params.capabilities.DiagnosticRelatedInformation;
Sam McCallbf6a2fc2018-10-17 07:33:42 +0000529 if (Params.capabilities.WorkspaceSymbolKinds)
530 SupportedSymbolKinds |= *Params.capabilities.WorkspaceSymbolKinds;
531 if (Params.capabilities.CompletionItemKinds)
532 SupportedCompletionItemKinds |= *Params.capabilities.CompletionItemKinds;
533 SupportsCodeAction = Params.capabilities.CodeActionStructure;
Ilya Biryukov19d75602018-11-23 15:21:19 +0000534 SupportsHierarchicalDocumentSymbol =
535 Params.capabilities.HierarchicalDocumentSymbol;
Haojian Wub6188492018-12-20 15:39:12 +0000536 SupportFileStatus = Params.initializationOptions.FileStatus;
Ilya Biryukovf9169d02019-05-29 10:01:00 +0000537 HoverContentFormat = Params.capabilities.HoverContentFormat;
Ilya Biryukov4ef0f822019-06-04 09:36:59 +0000538 SupportsOffsetsInSignatureHelp = Params.capabilities.OffsetsInSignatureHelp;
Sam McCall7d20e802020-01-22 19:41:45 +0100539 if (Params.capabilities.WorkDoneProgress)
540 BackgroundIndexProgressState = BackgroundIndexProgress::Empty;
541 BackgroundIndexSkipCreate = Params.capabilities.ImplicitProgressCreation;
Haojian Wuf429ab62019-07-24 07:49:23 +0000542
543 // Per LSP, renameProvider can be either boolean or RenameOptions.
544 // RenameOptions will be specified if the client states it supports prepare.
545 llvm::json::Value RenameProvider =
546 llvm::json::Object{{"prepareProvider", true}};
547 if (!Params.capabilities.RenamePrepareSupport) // Only boolean allowed per LSP
548 RenameProvider = true;
549
Haojian Wu08d93f12019-08-22 14:53:45 +0000550 // Per LSP, codeActionProvide can be either boolean or CodeActionOptions.
551 // CodeActionOptions is only valid if the client supports action literal
552 // via textDocument.codeAction.codeActionLiteralSupport.
553 llvm::json::Value CodeActionProvider = true;
554 if (Params.capabilities.CodeActionStructure)
555 CodeActionProvider = llvm::json::Object{
556 {"codeActionKinds",
557 {CodeAction::QUICKFIX_KIND, CodeAction::REFACTOR_KIND,
558 CodeAction::INFO_KIND}}};
559
Sam McCalla69698f2019-03-27 17:47:49 +0000560 llvm::json::Object Result{
Sam McCall6f7dca92020-03-03 12:25:46 +0100561 {{"serverInfo",
562 llvm::json::Object{{"name", "clangd"},
563 {"version", getClangToolFullVersion("clangd")}}},
564 {"capabilities",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000565 llvm::json::Object{
Sam McCall596b63a2020-04-10 03:27:37 +0200566 {"textDocumentSync",
567 llvm::json::Object{
568 {"openClose", true},
569 {"change", (int)TextDocumentSyncKind::Incremental},
570 {"save", true},
571 }},
Sam McCall0930ab02017-11-07 15:49:35 +0000572 {"documentFormattingProvider", true},
573 {"documentRangeFormattingProvider", true},
574 {"documentOnTypeFormattingProvider",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000575 llvm::json::Object{
Sam McCall25c62572019-06-10 14:26:21 +0000576 {"firstTriggerCharacter", "\n"},
Sam McCall0930ab02017-11-07 15:49:35 +0000577 {"moreTriggerCharacter", {}},
578 }},
Haojian Wu08d93f12019-08-22 14:53:45 +0000579 {"codeActionProvider", std::move(CodeActionProvider)},
Sam McCall0930ab02017-11-07 15:49:35 +0000580 {"completionProvider",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000581 llvm::json::Object{
Kirill Bobyrev9d11e672020-08-26 17:08:00 +0200582 {"allCommitCharacters",
583 {" ", "\t", "(", ")", "[", "]", "{", "}", "<",
584 ">", ":", ";", ",", "+", "-", "/", "*", "%",
585 "^", "&", "#", "?", ".", "=", "\"", "'", "|"}},
Sam McCall0930ab02017-11-07 15:49:35 +0000586 {"resolveProvider", false},
Sam McCall032727f2020-05-06 01:39:59 +0200587 // We do extra checks, e.g. that > is part of ->.
588 {"triggerCharacters", {".", "<", ">", ":", "\"", "/"}},
Sam McCall0930ab02017-11-07 15:49:35 +0000589 }},
Sam McCall71177ac2020-03-24 02:24:47 +0100590 {"semanticTokensProvider",
591 llvm::json::Object{
Sam McCall5fea54b2020-07-10 16:08:14 +0200592 {"full", llvm::json::Object{{"delta", true}}},
593 {"range", false},
Sam McCall71177ac2020-03-24 02:24:47 +0100594 {"legend",
595 llvm::json::Object{{"tokenTypes", semanticTokenTypes()},
596 {"tokenModifiers", llvm::json::Array()}}},
597 }},
Sam McCall0930ab02017-11-07 15:49:35 +0000598 {"signatureHelpProvider",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000599 llvm::json::Object{
Sam McCall0930ab02017-11-07 15:49:35 +0000600 {"triggerCharacters", {"(", ","}},
601 }},
Sam McCall866ba2c2019-02-01 11:26:13 +0000602 {"declarationProvider", true},
Sam McCall0930ab02017-11-07 15:49:35 +0000603 {"definitionProvider", true},
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000604 {"documentHighlightProvider", true},
Sam McCall8d7ecc12019-12-16 19:08:51 +0100605 {"documentLinkProvider",
606 llvm::json::Object{
607 {"resolveProvider", false},
608 }},
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000609 {"hoverProvider", true},
Haojian Wuf429ab62019-07-24 07:49:23 +0000610 {"renameProvider", std::move(RenameProvider)},
Utkarsh Saxena55925da2019-09-24 13:38:33 +0000611 {"selectionRangeProvider", true},
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000612 {"documentSymbolProvider", true},
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000613 {"workspaceSymbolProvider", true},
Sam McCall1ad142f2018-09-05 11:53:07 +0000614 {"referencesProvider", true},
Sam McCall0930ab02017-11-07 15:49:35 +0000615 {"executeCommandProvider",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000616 llvm::json::Object{
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000617 {"commands",
618 {ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND,
619 ExecuteCommandParams::CLANGD_APPLY_TWEAK}},
Sam McCall0930ab02017-11-07 15:49:35 +0000620 }},
Kadir Cetinkaya86658022019-03-19 09:27:04 +0000621 {"typeHierarchyProvider", true},
Sam McCalla69698f2019-03-27 17:47:49 +0000622 }}}};
Sam McCall7ba07792020-09-29 10:37:46 +0200623 if (Opts.OffsetEncoding)
624 Result["offsetEncoding"] = *Opts.OffsetEncoding;
625 if (Opts.TheiaSemanticHighlighting)
Johan Vikstroma848dab2019-07-04 07:53:12 +0000626 Result.getObject("capabilities")
627 ->insert(
628 {"semanticHighlighting",
Haojian Wu1ca2ee42019-07-04 12:27:21 +0000629 llvm::json::Object{{"scopes", buildHighlightScopeLookupTable()}}});
Sam McCall7ba07792020-09-29 10:37:46 +0200630 if (Opts.FoldingRanges)
Kirill Bobyrev7a514c92020-07-14 09:28:38 +0200631 Result.getObject("capabilities")->insert({"foldingRangeProvider", true});
Sam McCalla69698f2019-03-27 17:47:49 +0000632 Reply(std::move(Result));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000633}
634
Sam McCall8a2d2942020-03-03 12:12:14 +0100635void ClangdLSPServer::onInitialized(const InitializedParams &Params) {}
636
Sam McCall2c30fbc2018-10-18 12:32:04 +0000637void ClangdLSPServer::onShutdown(const ShutdownParams &Params,
638 Callback<std::nullptr_t> Reply) {
Ilya Biryukov0d9b8a32017-10-25 08:45:41 +0000639 // Do essentially nothing, just say we're ready to exit.
640 ShutdownRequestReceived = true;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000641 Reply(nullptr);
Sam McCall8a5dded2017-10-12 13:29:58 +0000642}
Ilya Biryukovafb55542017-05-16 14:40:30 +0000643
Sam McCall422c8282018-11-26 16:00:11 +0000644// sync is a clangd extension: it blocks until all background work completes.
645// It blocks the calling thread, so no messages are processed until it returns!
646void ClangdLSPServer::onSync(const NoParams &Params,
647 Callback<std::nullptr_t> Reply) {
648 if (Server->blockUntilIdleForTest(/*TimeoutSeconds=*/60))
649 Reply(nullptr);
650 else
Sam McCall30667c92020-07-08 21:49:38 +0200651 Reply(error("Not idle after a minute"));
Sam McCall422c8282018-11-26 16:00:11 +0000652}
653
Sam McCall2c30fbc2018-10-18 12:32:04 +0000654void ClangdLSPServer::onDocumentDidOpen(
655 const DidOpenTextDocumentParams &Params) {
Simon Marchi9569fd52018-03-16 14:30:42 +0000656 PathRef File = Params.textDocument.uri.file();
Ilya Biryukovb10ef472018-06-13 09:20:41 +0000657
Sam McCall2c30fbc2018-10-18 12:32:04 +0000658 const std::string &Contents = Params.textDocument.text;
Simon Marchi9569fd52018-03-16 14:30:42 +0000659
Sam McCall2cd33e62020-03-04 00:33:29 +0100660 auto Version = DraftMgr.addDraft(File, Params.textDocument.version, Contents);
661 Server->addDocument(File, Contents, encodeVersion(Version),
662 WantDiagnostics::Yes);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000663}
664
Sam McCall2c30fbc2018-10-18 12:32:04 +0000665void ClangdLSPServer::onDocumentDidChange(
666 const DidChangeTextDocumentParams &Params) {
Eric Liu51fed182018-02-22 18:40:39 +0000667 auto WantDiags = WantDiagnostics::Auto;
668 if (Params.wantDiagnostics.hasValue())
669 WantDiags = Params.wantDiagnostics.getValue() ? WantDiagnostics::Yes
670 : WantDiagnostics::No;
Simon Marchi9569fd52018-03-16 14:30:42 +0000671
672 PathRef File = Params.textDocument.uri.file();
Sam McCallcaf5a4d2020-03-03 15:57:39 +0100673 llvm::Expected<DraftStore::Draft> Draft = DraftMgr.updateDraft(
674 File, Params.textDocument.version, Params.contentChanges);
675 if (!Draft) {
Simon Marchi98082622018-03-26 14:41:40 +0000676 // If this fails, we are most likely going to be not in sync anymore with
677 // the client. It is better to remove the draft and let further operations
678 // fail rather than giving wrong results.
679 DraftMgr.removeDraft(File);
Ilya Biryukov652364b2018-09-26 05:48:29 +0000680 Server->removeDocument(File);
Sam McCallcaf5a4d2020-03-03 15:57:39 +0100681 elog("Failed to update {0}: {1}", File, Draft.takeError());
Simon Marchi98082622018-03-26 14:41:40 +0000682 return;
683 }
Simon Marchi9569fd52018-03-16 14:30:42 +0000684
Sam McCall2cd33e62020-03-04 00:33:29 +0100685 Server->addDocument(File, Draft->Contents, encodeVersion(Draft->Version),
686 WantDiags, Params.forceRebuild);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000687}
688
Sam McCall596b63a2020-04-10 03:27:37 +0200689void ClangdLSPServer::onDocumentDidSave(
690 const DidSaveTextDocumentParams &Params) {
691 reparseOpenFilesIfNeeded([](llvm::StringRef) { return true; });
692}
693
Sam McCall2c30fbc2018-10-18 12:32:04 +0000694void ClangdLSPServer::onFileEvent(const DidChangeWatchedFilesParams &Params) {
Sam McCall596b63a2020-04-10 03:27:37 +0200695 // We could also reparse all open files here. However:
696 // - this could be frequent, and revalidating all the preambles isn't free
697 // - this is useful e.g. when switching git branches, but we're likely to see
698 // fresh headers but still have the old-branch main-file content
Ilya Biryukov652364b2018-09-26 05:48:29 +0000699 Server->onFileEvent(Params);
Marc-Andre Laperlebf114242017-10-02 18:00:37 +0000700}
701
Sam McCall2c30fbc2018-10-18 12:32:04 +0000702void ClangdLSPServer::onCommand(const ExecuteCommandParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000703 Callback<llvm::json::Value> Reply) {
Ilya Biryukov12864002019-08-16 12:46:41 +0000704 auto ApplyEdit = [this](WorkspaceEdit WE, std::string SuccessMessage,
705 decltype(Reply) Reply) {
Eric Liuc5105f92018-02-16 14:15:55 +0000706 ApplyWorkspaceEditParams Edit;
707 Edit.edit = std::move(WE);
Ilya Biryukov12864002019-08-16 12:46:41 +0000708 call<ApplyWorkspaceEditResponse>(
709 "workspace/applyEdit", std::move(Edit),
710 [Reply = std::move(Reply), SuccessMessage = std::move(SuccessMessage)](
711 llvm::Expected<ApplyWorkspaceEditResponse> Response) mutable {
712 if (!Response)
713 return Reply(Response.takeError());
714 if (!Response->applied) {
715 std::string Reason = Response->failureReason
716 ? *Response->failureReason
717 : "unknown reason";
Sam McCall30667c92020-07-08 21:49:38 +0200718 return Reply(error("edits were not applied: {0}", Reason));
Ilya Biryukov12864002019-08-16 12:46:41 +0000719 }
720 return Reply(SuccessMessage);
721 });
Eric Liuc5105f92018-02-16 14:15:55 +0000722 };
Ilya Biryukov12864002019-08-16 12:46:41 +0000723
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000724 if (Params.command == ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND &&
725 Params.workspaceEdit) {
726 // The flow for "apply-fix" :
727 // 1. We publish a diagnostic, including fixits
728 // 2. The user clicks on the diagnostic, the editor asks us for code actions
729 // 3. We send code actions, with the fixit embedded as context
730 // 4. The user selects the fixit, the editor asks us to apply it
731 // 5. We unwrap the changes and send them back to the editor
Haojian Wuf2516342019-08-05 12:48:09 +0000732 // 6. The editor applies the changes (applyEdit), and sends us a reply
733 // 7. We unwrap the reply and send a reply to the editor.
Ilya Biryukov12864002019-08-16 12:46:41 +0000734 ApplyEdit(*Params.workspaceEdit, "Fix applied.", std::move(Reply));
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000735 } else if (Params.command == ExecuteCommandParams::CLANGD_APPLY_TWEAK &&
736 Params.tweakArgs) {
737 auto Code = DraftMgr.getDraft(Params.tweakArgs->file.file());
738 if (!Code)
Sam McCall30667c92020-07-08 21:49:38 +0200739 return Reply(error("trying to apply a code action for a non-added file"));
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000740
Ilya Biryukov12864002019-08-16 12:46:41 +0000741 auto Action = [this, ApplyEdit, Reply = std::move(Reply),
742 File = Params.tweakArgs->file, Code = std::move(*Code)](
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000743 llvm::Expected<Tweak::Effect> R) mutable {
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000744 if (!R)
745 return Reply(R.takeError());
746
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000747 assert(R->ShowMessage ||
748 (!R->ApplyEdits.empty() && "tweak has no effect"));
Ilya Biryukov12864002019-08-16 12:46:41 +0000749
Sam McCall395fde72019-06-18 13:37:54 +0000750 if (R->ShowMessage) {
751 ShowMessageParams Msg;
752 Msg.message = *R->ShowMessage;
753 Msg.type = MessageType::Info;
754 notify("window/showMessage", Msg);
755 }
Ilya Biryukov12864002019-08-16 12:46:41 +0000756 // When no edit is specified, make sure we Reply().
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000757 if (R->ApplyEdits.empty())
758 return Reply("Tweak applied.");
759
Haojian Wu852bafa2019-10-23 14:40:20 +0200760 if (auto Err = validateEdits(DraftMgr, R->ApplyEdits))
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000761 return Reply(std::move(Err));
762
763 WorkspaceEdit WE;
764 WE.changes.emplace();
765 for (const auto &It : R->ApplyEdits) {
Kadir Cetinkayae95e5162019-10-02 09:12:01 +0000766 (*WE.changes)[URI::createFile(It.first()).toString()] =
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000767 It.second.asTextEdits();
768 }
769 // ApplyEdit will take care of calling Reply().
770 return ApplyEdit(std::move(WE), "Tweak applied.", std::move(Reply));
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000771 };
772 Server->applyTweak(Params.tweakArgs->file.file(),
773 Params.tweakArgs->selection, Params.tweakArgs->tweakID,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000774 std::move(Action));
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000775 } else {
776 // We should not get here because ExecuteCommandParams would not have
777 // parsed in the first place and this handler should not be called. But if
778 // more commands are added, this will be here has a safe guard.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000779 Reply(llvm::make_error<LSPError>(
780 llvm::formatv("Unsupported command \"{0}\".", Params.command).str(),
Sam McCall2c30fbc2018-10-18 12:32:04 +0000781 ErrorCode::InvalidParams));
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000782 }
783}
784
Sam McCall2c30fbc2018-10-18 12:32:04 +0000785void ClangdLSPServer::onWorkspaceSymbol(
786 const WorkspaceSymbolParams &Params,
787 Callback<std::vector<SymbolInformation>> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000788 Server->workspaceSymbols(
Sam McCall7ba07792020-09-29 10:37:46 +0200789 Params.query, Opts.CodeComplete.Limit,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000790 [Reply = std::move(Reply),
791 this](llvm::Expected<std::vector<SymbolInformation>> Items) mutable {
792 if (!Items)
793 return Reply(Items.takeError());
794 for (auto &Sym : *Items)
795 Sym.kind = adjustKindToCapability(Sym.kind, SupportedSymbolKinds);
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000796
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000797 Reply(std::move(*Items));
798 });
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000799}
800
Haojian Wuf429ab62019-07-24 07:49:23 +0000801void ClangdLSPServer::onPrepareRename(const TextDocumentPositionParams &Params,
802 Callback<llvm::Optional<Range>> Reply) {
803 Server->prepareRename(Params.textDocument.uri.file(), Params.position,
Sam McCall7ba07792020-09-29 10:37:46 +0200804 Opts.Rename, std::move(Reply));
Haojian Wuf429ab62019-07-24 07:49:23 +0000805}
806
Sam McCall2c30fbc2018-10-18 12:32:04 +0000807void ClangdLSPServer::onRename(const RenameParams &Params,
808 Callback<WorkspaceEdit> Reply) {
Benjamin Krameradcd0262020-01-28 20:23:46 +0100809 Path File = std::string(Params.textDocument.uri.file());
Sam McCallcaf5a4d2020-03-03 15:57:39 +0100810 if (!DraftMgr.getDraft(File))
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000811 return Reply(llvm::make_error<LSPError>(
812 "onRename called for non-added file", ErrorCode::InvalidParams));
Haojian Wu852bafa2019-10-23 14:40:20 +0200813 Server->rename(
Sam McCall7ba07792020-09-29 10:37:46 +0200814 File, Params.position, Params.newName, Opts.Rename,
Haojian Wu852bafa2019-10-23 14:40:20 +0200815 [File, Params, Reply = std::move(Reply),
816 this](llvm::Expected<FileEdits> Edits) mutable {
817 if (!Edits)
818 return Reply(Edits.takeError());
819 if (auto Err = validateEdits(DraftMgr, *Edits))
820 return Reply(std::move(Err));
821 WorkspaceEdit Result;
822 Result.changes.emplace();
823 for (const auto &Rep : *Edits) {
824 (*Result.changes)[URI::createFile(Rep.first()).toString()] =
825 Rep.second.asTextEdits();
826 }
827 Reply(Result);
828 });
Haojian Wu345099c2017-11-09 11:30:04 +0000829}
830
Sam McCall2c30fbc2018-10-18 12:32:04 +0000831void ClangdLSPServer::onDocumentDidClose(
832 const DidCloseTextDocumentParams &Params) {
Simon Marchi9569fd52018-03-16 14:30:42 +0000833 PathRef File = Params.textDocument.uri.file();
834 DraftMgr.removeDraft(File);
Ilya Biryukov652364b2018-09-26 05:48:29 +0000835 Server->removeDocument(File);
Ilya Biryukov49c10712019-03-25 10:15:11 +0000836
837 {
838 std::lock_guard<std::mutex> Lock(FixItsMutex);
839 FixItsMap.erase(File);
840 }
Johan Vikstromc2653ef22019-08-01 08:08:44 +0000841 {
842 std::lock_guard<std::mutex> HLock(HighlightingsMutex);
843 FileToHighlightings.erase(File);
844 }
Sam McCall9e3063e2020-04-01 16:21:44 +0200845 {
846 std::lock_guard<std::mutex> HLock(SemanticTokensMutex);
847 LastSemanticTokens.erase(File);
848 }
Ilya Biryukov49c10712019-03-25 10:15:11 +0000849 // clangd will not send updates for this file anymore, so we empty out the
850 // list of diagnostics shown on the client (e.g. in the "Problems" pane of
851 // VSCode). Note that this cannot race with actual diagnostics responses
852 // because removeDocument() guarantees no diagnostic callbacks will be
853 // executed after it returns.
Sam McCall6525a6b2020-03-03 12:44:40 +0100854 PublishDiagnosticsParams Notification;
855 Notification.uri = URIForFile::canonicalize(File, /*TUPath=*/File);
856 publishDiagnostics(Notification);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000857}
858
Sam McCall4db732a2017-09-30 10:08:52 +0000859void ClangdLSPServer::onDocumentOnTypeFormatting(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000860 const DocumentOnTypeFormattingParams &Params,
861 Callback<std::vector<TextEdit>> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000862 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000863 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000864 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000865 return Reply(llvm::make_error<LSPError>(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000866 "onDocumentOnTypeFormatting called for non-added file",
867 ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000868
Sam McCallffa63dd2020-06-26 12:57:29 +0200869 Server->formatOnType(File, Code->Contents, Params.position, Params.ch,
870 std::move(Reply));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000871}
872
Sam McCall4db732a2017-09-30 10:08:52 +0000873void ClangdLSPServer::onDocumentRangeFormatting(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000874 const DocumentRangeFormattingParams &Params,
875 Callback<std::vector<TextEdit>> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000876 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000877 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000878 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000879 return Reply(llvm::make_error<LSPError>(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000880 "onDocumentRangeFormatting called for non-added file",
881 ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000882
Sam McCallffa63dd2020-06-26 12:57:29 +0200883 Server->formatRange(
884 File, Code->Contents, Params.range,
885 [Code = Code->Contents, Reply = std::move(Reply)](
886 llvm::Expected<tooling::Replacements> Result) mutable {
887 if (Result)
888 Reply(replacementsToEdits(Code, Result.get()));
889 else
890 Reply(Result.takeError());
891 });
Ilya Biryukovafb55542017-05-16 14:40:30 +0000892}
893
Sam McCall2c30fbc2018-10-18 12:32:04 +0000894void ClangdLSPServer::onDocumentFormatting(
895 const DocumentFormattingParams &Params,
896 Callback<std::vector<TextEdit>> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000897 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000898 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000899 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000900 return Reply(llvm::make_error<LSPError>(
901 "onDocumentFormatting called for non-added file",
902 ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000903
Sam McCallffa63dd2020-06-26 12:57:29 +0200904 Server->formatFile(File, Code->Contents,
905 [Code = Code->Contents, Reply = std::move(Reply)](
906 llvm::Expected<tooling::Replacements> Result) mutable {
907 if (Result)
908 Reply(replacementsToEdits(Code, Result.get()));
909 else
910 Reply(Result.takeError());
911 });
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) {
Ilya Biryukov19d75602018-11-23 15:21:19 +0000919 std::vector<SymbolInformation> Results;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000920 std::function<void(const DocumentSymbol &, llvm::StringRef)> Process =
921 [&](const DocumentSymbol &S, llvm::Optional<llvm::StringRef> ParentName) {
Ilya Biryukov19d75602018-11-23 15:21:19 +0000922 SymbolInformation SI;
Benjamin Krameradcd0262020-01-28 20:23:46 +0100923 SI.containerName = std::string(ParentName ? "" : *ParentName);
Ilya Biryukov19d75602018-11-23 15:21:19 +0000924 SI.name = S.name;
925 SI.kind = S.kind;
926 SI.location.range = S.range;
927 SI.location.uri = FileURI;
928
929 Results.push_back(std::move(SI));
930 std::string FullName =
931 !ParentName ? S.name : (ParentName->str() + "::" + S.name);
932 for (auto &C : S.children)
933 Process(C, /*ParentName=*/FullName);
934 };
935 for (auto &S : Symbols)
936 Process(S, /*ParentName=*/"");
937 return Results;
938}
939
940void ClangdLSPServer::onDocumentSymbol(const DocumentSymbolParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000941 Callback<llvm::json::Value> Reply) {
Ilya Biryukov19d75602018-11-23 15:21:19 +0000942 URIForFile FileURI = Params.textDocument.uri;
Ilya Biryukov652364b2018-09-26 05:48:29 +0000943 Server->documentSymbols(
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000944 Params.textDocument.uri.file(),
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000945 [this, FileURI, Reply = std::move(Reply)](
946 llvm::Expected<std::vector<DocumentSymbol>> Items) mutable {
947 if (!Items)
948 return Reply(Items.takeError());
949 adjustSymbolKinds(*Items, SupportedSymbolKinds);
950 if (SupportsHierarchicalDocumentSymbol)
951 return Reply(std::move(*Items));
952 else
953 return Reply(flattenSymbolHierarchy(*Items, FileURI));
954 });
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000955}
956
Kirill Bobyrev7a514c92020-07-14 09:28:38 +0200957void ClangdLSPServer::onFoldingRange(
958 const FoldingRangeParams &Params,
959 Callback<std::vector<FoldingRange>> Reply) {
960 Server->foldingRanges(Params.textDocument.uri.file(), std::move(Reply));
961}
962
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000963static llvm::Optional<Command> asCommand(const CodeAction &Action) {
Sam McCall20841d42018-10-16 16:29:41 +0000964 Command Cmd;
965 if (Action.command && Action.edit)
Sam McCallc008af62018-10-20 15:30:37 +0000966 return None; // Not representable. (We never emit these anyway).
Sam McCall20841d42018-10-16 16:29:41 +0000967 if (Action.command) {
968 Cmd = *Action.command;
969 } else if (Action.edit) {
Benjamin Krameradcd0262020-01-28 20:23:46 +0100970 Cmd.command = std::string(Command::CLANGD_APPLY_FIX_COMMAND);
Sam McCall20841d42018-10-16 16:29:41 +0000971 Cmd.workspaceEdit = *Action.edit;
972 } else {
Sam McCallc008af62018-10-20 15:30:37 +0000973 return None;
Sam McCall20841d42018-10-16 16:29:41 +0000974 }
975 Cmd.title = Action.title;
976 if (Action.kind && *Action.kind == CodeAction::QUICKFIX_KIND)
977 Cmd.title = "Apply fix: " + Cmd.title;
978 return Cmd;
979}
980
Sam McCall2c30fbc2018-10-18 12:32:04 +0000981void ClangdLSPServer::onCodeAction(const CodeActionParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000982 Callback<llvm::json::Value> Reply) {
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000983 URIForFile File = Params.textDocument.uri;
984 auto Code = DraftMgr.getDraft(File.file());
Sam McCall2c30fbc2018-10-18 12:32:04 +0000985 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000986 return Reply(llvm::make_error<LSPError>(
987 "onCodeAction called for non-added file", ErrorCode::InvalidParams));
Sam McCall20841d42018-10-16 16:29:41 +0000988 // We provide a code action for Fixes on the specified diagnostics.
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000989 std::vector<CodeAction> FixIts;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000990 for (const Diagnostic &D : Params.context.diagnostics) {
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000991 for (auto &F : getFixes(File.file(), D)) {
992 FixIts.push_back(toCodeAction(F, Params.textDocument.uri));
993 FixIts.back().diagnostics = {D};
Sam McCalldd0566b2017-11-06 15:40:30 +0000994 }
Ilya Biryukovafb55542017-05-16 14:40:30 +0000995 }
Sam McCall20841d42018-10-16 16:29:41 +0000996
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000997 // Now enumerate the semantic code actions.
998 auto ConsumeActions =
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000999 [Reply = std::move(Reply), File, Code = std::move(*Code),
1000 Selection = Params.range, FixIts = std::move(FixIts), this](
1001 llvm::Expected<std::vector<ClangdServer::TweakRef>> Tweaks) mutable {
Ilya Biryukovc6ed7782019-01-30 14:24:17 +00001002 if (!Tweaks)
1003 return Reply(Tweaks.takeError());
Ilya Biryukovcce67a32019-01-29 14:17:36 +00001004
1005 std::vector<CodeAction> Actions = std::move(FixIts);
1006 Actions.reserve(Actions.size() + Tweaks->size());
1007 for (const auto &T : *Tweaks)
1008 Actions.push_back(toCodeAction(T, File, Selection));
1009
1010 if (SupportsCodeAction)
1011 return Reply(llvm::json::Array(Actions));
1012 std::vector<Command> Commands;
1013 for (const auto &Action : Actions) {
1014 if (auto Command = asCommand(Action))
1015 Commands.push_back(std::move(*Command));
1016 }
1017 return Reply(llvm::json::Array(Commands));
1018 };
1019
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001020 Server->enumerateTweaks(File.file(), Params.range, std::move(ConsumeActions));
Ilya Biryukovafb55542017-05-16 14:40:30 +00001021}
1022
Ilya Biryukovb0826bd2019-01-03 13:37:12 +00001023void ClangdLSPServer::onCompletion(const CompletionParams &Params,
Sam McCall2c30fbc2018-10-18 12:32:04 +00001024 Callback<CompletionList> Reply) {
Ilya Biryukova7a11472019-06-07 16:24:38 +00001025 if (!shouldRunCompletion(Params)) {
1026 // Clients sometimes auto-trigger completions in undesired places (e.g.
1027 // 'a >^ '), we return empty results in those cases.
1028 vlog("ignored auto-triggered completion, preceding char did not match");
1029 return Reply(CompletionList());
1030 }
Sam McCall7ba07792020-09-29 10:37:46 +02001031 Server->codeComplete(Params.textDocument.uri.file(), Params.position,
1032 Opts.CodeComplete,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001033 [Reply = std::move(Reply),
1034 this](llvm::Expected<CodeCompleteResult> List) mutable {
1035 if (!List)
1036 return Reply(List.takeError());
1037 CompletionList LSPList;
1038 LSPList.isIncomplete = List->HasMore;
1039 for (const auto &R : List->Completions) {
Sam McCall7ba07792020-09-29 10:37:46 +02001040 CompletionItem C = R.render(Opts.CodeComplete);
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001041 C.kind = adjustKindToCapability(
1042 C.kind, SupportedCompletionItemKinds);
1043 LSPList.items.push_back(std::move(C));
1044 }
1045 return Reply(std::move(LSPList));
1046 });
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +00001047}
1048
Sam McCall2c30fbc2018-10-18 12:32:04 +00001049void ClangdLSPServer::onSignatureHelp(const TextDocumentPositionParams &Params,
1050 Callback<SignatureHelp> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +00001051 Server->signatureHelp(Params.textDocument.uri.file(), Params.position,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001052 [Reply = std::move(Reply), this](
1053 llvm::Expected<SignatureHelp> Signature) mutable {
1054 if (!Signature)
1055 return Reply(Signature.takeError());
1056 if (SupportsOffsetsInSignatureHelp)
1057 return Reply(std::move(*Signature));
1058 // Strip out the offsets from signature help for
1059 // clients that only support string labels.
1060 for (auto &SigInfo : Signature->signatures) {
1061 for (auto &Param : SigInfo.parameters)
1062 Param.labelOffsets.reset();
1063 }
1064 return Reply(std::move(*Signature));
1065 });
Ilya Biryukov652364b2018-09-26 05:48:29 +00001066}
1067
Sam McCall0dbab7f2019-02-02 05:56:00 +00001068// Go to definition has a toggle function: if def and decl are distinct, then
1069// the first press gives you the def, the second gives you the matching def.
1070// getToggle() returns the counterpart location that under the cursor.
1071//
1072// We return the toggled location alone (ignoring other symbols) to encourage
1073// editors to "bounce" quickly between locations, without showing a menu.
1074static Location *getToggle(const TextDocumentPositionParams &Point,
1075 LocatedSymbol &Sym) {
1076 // Toggle only makes sense with two distinct locations.
1077 if (!Sym.Definition || *Sym.Definition == Sym.PreferredDeclaration)
1078 return nullptr;
1079 if (Sym.Definition->uri.file() == Point.textDocument.uri.file() &&
1080 Sym.Definition->range.contains(Point.position))
1081 return &Sym.PreferredDeclaration;
1082 if (Sym.PreferredDeclaration.uri.file() == Point.textDocument.uri.file() &&
1083 Sym.PreferredDeclaration.range.contains(Point.position))
1084 return &*Sym.Definition;
1085 return nullptr;
1086}
1087
Sam McCall2c30fbc2018-10-18 12:32:04 +00001088void ClangdLSPServer::onGoToDefinition(const TextDocumentPositionParams &Params,
1089 Callback<std::vector<Location>> Reply) {
Sam McCall866ba2c2019-02-01 11:26:13 +00001090 Server->locateSymbolAt(
1091 Params.textDocument.uri.file(), Params.position,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001092 [Params, Reply = std::move(Reply)](
1093 llvm::Expected<std::vector<LocatedSymbol>> Symbols) mutable {
1094 if (!Symbols)
1095 return Reply(Symbols.takeError());
1096 std::vector<Location> Defs;
1097 for (auto &S : *Symbols) {
1098 if (Location *Toggle = getToggle(Params, S))
1099 return Reply(std::vector<Location>{std::move(*Toggle)});
1100 Defs.push_back(S.Definition.getValueOr(S.PreferredDeclaration));
1101 }
1102 Reply(std::move(Defs));
1103 });
Sam McCall866ba2c2019-02-01 11:26:13 +00001104}
1105
1106void ClangdLSPServer::onGoToDeclaration(
1107 const TextDocumentPositionParams &Params,
1108 Callback<std::vector<Location>> Reply) {
1109 Server->locateSymbolAt(
1110 Params.textDocument.uri.file(), Params.position,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001111 [Params, Reply = std::move(Reply)](
1112 llvm::Expected<std::vector<LocatedSymbol>> Symbols) mutable {
1113 if (!Symbols)
1114 return Reply(Symbols.takeError());
1115 std::vector<Location> Decls;
1116 for (auto &S : *Symbols) {
1117 if (Location *Toggle = getToggle(Params, S))
1118 return Reply(std::vector<Location>{std::move(*Toggle)});
1119 Decls.push_back(std::move(S.PreferredDeclaration));
1120 }
1121 Reply(std::move(Decls));
1122 });
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +00001123}
1124
Sam McCall111fe842019-05-07 07:55:35 +00001125void ClangdLSPServer::onSwitchSourceHeader(
1126 const TextDocumentIdentifier &Params,
Sam McCallb9ec3e92019-05-07 08:30:32 +00001127 Callback<llvm::Optional<URIForFile>> Reply) {
Haojian Wud6d5edd2019-10-01 10:21:15 +00001128 Server->switchSourceHeader(
1129 Params.uri.file(),
1130 [Reply = std::move(Reply),
1131 Params](llvm::Expected<llvm::Optional<clangd::Path>> Path) mutable {
1132 if (!Path)
1133 return Reply(Path.takeError());
1134 if (*Path)
Haojian Wu77c97002019-10-07 11:37:25 +00001135 return Reply(URIForFile::canonicalize(**Path, Params.uri.file()));
Haojian Wud6d5edd2019-10-01 10:21:15 +00001136 return Reply(llvm::None);
1137 });
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +00001138}
1139
Sam McCall2c30fbc2018-10-18 12:32:04 +00001140void ClangdLSPServer::onDocumentHighlight(
1141 const TextDocumentPositionParams &Params,
1142 Callback<std::vector<DocumentHighlight>> Reply) {
1143 Server->findDocumentHighlights(Params.textDocument.uri.file(),
1144 Params.position, std::move(Reply));
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +00001145}
1146
Sam McCall2c30fbc2018-10-18 12:32:04 +00001147void ClangdLSPServer::onHover(const TextDocumentPositionParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001148 Callback<llvm::Optional<Hover>> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +00001149 Server->findHover(Params.textDocument.uri.file(), Params.position,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001150 [Reply = std::move(Reply), this](
1151 llvm::Expected<llvm::Optional<HoverInfo>> H) mutable {
1152 if (!H)
1153 return Reply(H.takeError());
1154 if (!*H)
1155 return Reply(llvm::None);
Ilya Biryukovf9169d02019-05-29 10:01:00 +00001156
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001157 Hover R;
1158 R.contents.kind = HoverContentFormat;
1159 R.range = (*H)->SymRange;
1160 switch (HoverContentFormat) {
1161 case MarkupKind::PlainText:
Kadir Cetinkaya597c6b62019-12-10 10:28:37 +01001162 R.contents.value = (*H)->present().asPlainText();
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001163 return Reply(std::move(R));
1164 case MarkupKind::Markdown:
Kadir Cetinkaya597c6b62019-12-10 10:28:37 +01001165 R.contents.value = (*H)->present().asMarkdown();
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001166 return Reply(std::move(R));
1167 };
1168 llvm_unreachable("unhandled MarkupKind");
1169 });
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +00001170}
1171
Kadir Cetinkaya86658022019-03-19 09:27:04 +00001172void ClangdLSPServer::onTypeHierarchy(
1173 const TypeHierarchyParams &Params,
1174 Callback<Optional<TypeHierarchyItem>> Reply) {
1175 Server->typeHierarchy(Params.textDocument.uri.file(), Params.position,
1176 Params.resolve, Params.direction, std::move(Reply));
1177}
1178
Nathan Ridge087b0442019-07-13 03:24:48 +00001179void ClangdLSPServer::onResolveTypeHierarchy(
1180 const ResolveTypeHierarchyItemParams &Params,
1181 Callback<Optional<TypeHierarchyItem>> Reply) {
1182 Server->resolveTypeHierarchy(Params.item, Params.resolve, Params.direction,
1183 std::move(Reply));
1184}
1185
Simon Marchi88016782018-08-01 11:28:49 +00001186void ClangdLSPServer::applyConfiguration(
Sam McCallbc904612018-10-25 04:22:52 +00001187 const ConfigurationSettings &Settings) {
Simon Marchiabeed662018-10-16 15:55:03 +00001188 // Per-file update to the compilation database.
David Goldman60249c22020-01-13 17:01:10 -05001189 llvm::StringSet<> ModifiedFiles;
Sam McCallbc904612018-10-25 04:22:52 +00001190 for (auto &Entry : Settings.compilationDatabaseChanges) {
Sam McCallbc904612018-10-25 04:22:52 +00001191 PathRef File = Entry.first;
Sam McCallc55d09a2018-11-02 13:09:36 +00001192 auto Old = CDB->getCompileCommand(File);
1193 auto New =
1194 tooling::CompileCommand(std::move(Entry.second.workingDirectory), File,
1195 std::move(Entry.second.compilationCommand),
1196 /*Output=*/"");
Sam McCall6980edb2018-11-02 14:07:51 +00001197 if (Old != New) {
Sam McCallc55d09a2018-11-02 13:09:36 +00001198 CDB->setCompileCommand(File, std::move(New));
David Goldman60249c22020-01-13 17:01:10 -05001199 ModifiedFiles.insert(File);
Sam McCall6980edb2018-11-02 14:07:51 +00001200 }
Alex Lorenzf8087862018-08-01 17:39:29 +00001201 }
David Goldman60249c22020-01-13 17:01:10 -05001202
Sam McCall596b63a2020-04-10 03:27:37 +02001203 reparseOpenFilesIfNeeded(
1204 [&](llvm::StringRef File) { return ModifiedFiles.count(File) != 0; });
Simon Marchi5178f922018-02-22 14:00:39 +00001205}
1206
Sam McCalledf6a192020-03-24 00:31:14 +01001207void ClangdLSPServer::publishTheiaSemanticHighlighting(
1208 const TheiaSemanticHighlightingParams &Params) {
Johan Vikstroma848dab2019-07-04 07:53:12 +00001209 notify("textDocument/semanticHighlighting", Params);
1210}
1211
Ilya Biryukov49c10712019-03-25 10:15:11 +00001212void ClangdLSPServer::publishDiagnostics(
Sam McCall6525a6b2020-03-03 12:44:40 +01001213 const PublishDiagnosticsParams &Params) {
1214 notify("textDocument/publishDiagnostics", Params);
Ilya Biryukov49c10712019-03-25 10:15:11 +00001215}
1216
Simon Marchi88016782018-08-01 11:28:49 +00001217// FIXME: This function needs to be properly tested.
1218void ClangdLSPServer::onChangeConfiguration(
Sam McCall2c30fbc2018-10-18 12:32:04 +00001219 const DidChangeConfigurationParams &Params) {
Simon Marchi88016782018-08-01 11:28:49 +00001220 applyConfiguration(Params.settings);
1221}
1222
Sam McCall2c30fbc2018-10-18 12:32:04 +00001223void ClangdLSPServer::onReference(const ReferenceParams &Params,
1224 Callback<std::vector<Location>> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +00001225 Server->findReferences(Params.textDocument.uri.file(), Params.position,
Sam McCall7ba07792020-09-29 10:37:46 +02001226 Opts.CodeComplete.Limit,
Haojian Wu5181ada2019-11-18 11:35:00 +01001227 [Reply = std::move(Reply)](
1228 llvm::Expected<ReferencesResult> Refs) mutable {
1229 if (!Refs)
1230 return Reply(Refs.takeError());
1231 return Reply(std::move(Refs->References));
1232 });
Sam McCall1ad142f2018-09-05 11:53:07 +00001233}
1234
Jan Korousb4067012018-11-27 16:40:46 +00001235void ClangdLSPServer::onSymbolInfo(const TextDocumentPositionParams &Params,
1236 Callback<std::vector<SymbolDetails>> Reply) {
1237 Server->symbolInfo(Params.textDocument.uri.file(), Params.position,
1238 std::move(Reply));
1239}
1240
Utkarsh Saxena55925da2019-09-24 13:38:33 +00001241void ClangdLSPServer::onSelectionRange(
1242 const SelectionRangeParams &Params,
1243 Callback<std::vector<SelectionRange>> Reply) {
Utkarsh Saxena55925da2019-09-24 13:38:33 +00001244 Server->semanticRanges(
Sam McCall8f237f92020-03-25 00:51:50 +01001245 Params.textDocument.uri.file(), Params.positions,
Utkarsh Saxena55925da2019-09-24 13:38:33 +00001246 [Reply = std::move(Reply)](
Sam McCall8f237f92020-03-25 00:51:50 +01001247 llvm::Expected<std::vector<SelectionRange>> Ranges) mutable {
1248 if (!Ranges)
Utkarsh Saxena55925da2019-09-24 13:38:33 +00001249 return Reply(Ranges.takeError());
Sam McCall8f237f92020-03-25 00:51:50 +01001250 return Reply(std::move(*Ranges));
Utkarsh Saxena55925da2019-09-24 13:38:33 +00001251 });
1252}
1253
Sam McCall8d7ecc12019-12-16 19:08:51 +01001254void ClangdLSPServer::onDocumentLink(
1255 const DocumentLinkParams &Params,
1256 Callback<std::vector<DocumentLink>> Reply) {
1257
1258 // TODO(forster): This currently resolves all targets eagerly. This is slow,
1259 // because it blocks on the preamble/AST being built. We could respond to the
1260 // request faster by using string matching or the lexer to find the includes
1261 // and resolving the targets lazily.
1262 Server->documentLinks(
1263 Params.textDocument.uri.file(),
1264 [Reply = std::move(Reply)](
1265 llvm::Expected<std::vector<DocumentLink>> Links) mutable {
1266 if (!Links) {
1267 return Reply(Links.takeError());
1268 }
1269 return Reply(std::move(Links));
1270 });
1271}
1272
Sam McCall9e3063e2020-04-01 16:21:44 +02001273// Increment a numeric string: "" -> 1 -> 2 -> ... -> 9 -> 10 -> 11 ...
1274static void increment(std::string &S) {
1275 for (char &C : llvm::reverse(S)) {
1276 if (C != '9') {
1277 ++C;
1278 return;
1279 }
1280 C = '0';
1281 }
1282 S.insert(S.begin(), '1');
1283}
1284
Sam McCall71177ac2020-03-24 02:24:47 +01001285void ClangdLSPServer::onSemanticTokens(const SemanticTokensParams &Params,
1286 Callback<SemanticTokens> CB) {
1287 Server->semanticHighlights(
1288 Params.textDocument.uri.file(),
Sam McCall9e3063e2020-04-01 16:21:44 +02001289 [this, File(Params.textDocument.uri.file().str()), CB(std::move(CB))](
1290 llvm::Expected<std::vector<HighlightingToken>> HT) mutable {
1291 if (!HT)
1292 return CB(HT.takeError());
Sam McCall71177ac2020-03-24 02:24:47 +01001293 SemanticTokens Result;
Sam McCall9e3063e2020-04-01 16:21:44 +02001294 Result.tokens = toSemanticTokens(*HT);
1295 {
1296 std::lock_guard<std::mutex> Lock(SemanticTokensMutex);
Kadir Cetinkayae64f99c2020-04-16 23:12:09 +02001297 auto &Last = LastSemanticTokens[File];
Sam McCall9e3063e2020-04-01 16:21:44 +02001298
1299 Last.tokens = Result.tokens;
1300 increment(Last.resultId);
1301 Result.resultId = Last.resultId;
1302 }
1303 CB(std::move(Result));
1304 });
1305}
1306
Sam McCall5fea54b2020-07-10 16:08:14 +02001307void ClangdLSPServer::onSemanticTokensDelta(
1308 const SemanticTokensDeltaParams &Params,
1309 Callback<SemanticTokensOrDelta> CB) {
Sam McCall9e3063e2020-04-01 16:21:44 +02001310 Server->semanticHighlights(
1311 Params.textDocument.uri.file(),
1312 [this, PrevResultID(Params.previousResultId),
1313 File(Params.textDocument.uri.file().str()), CB(std::move(CB))](
1314 llvm::Expected<std::vector<HighlightingToken>> HT) mutable {
1315 if (!HT)
1316 return CB(HT.takeError());
1317 std::vector<SemanticToken> Toks = toSemanticTokens(*HT);
1318
Sam McCall5fea54b2020-07-10 16:08:14 +02001319 SemanticTokensOrDelta Result;
Sam McCall9e3063e2020-04-01 16:21:44 +02001320 {
1321 std::lock_guard<std::mutex> Lock(SemanticTokensMutex);
Kadir Cetinkayae64f99c2020-04-16 23:12:09 +02001322 auto &Last = LastSemanticTokens[File];
Sam McCall9e3063e2020-04-01 16:21:44 +02001323
1324 if (PrevResultID == Last.resultId) {
1325 Result.edits = diffTokens(Last.tokens, Toks);
1326 } else {
Sam McCall5fea54b2020-07-10 16:08:14 +02001327 vlog("semanticTokens/full/delta: wanted edits vs {0} but last "
1328 "result had ID {1}. Returning full token list.",
Sam McCall9e3063e2020-04-01 16:21:44 +02001329 PrevResultID, Last.resultId);
1330 Result.tokens = Toks;
1331 }
1332
1333 Last.tokens = std::move(Toks);
1334 increment(Last.resultId);
1335 Result.resultId = Last.resultId;
1336 }
1337
Sam McCall71177ac2020-03-24 02:24:47 +01001338 CB(std::move(Result));
1339 });
1340}
1341
Sam McCall7ba07792020-09-29 10:37:46 +02001342ClangdLSPServer::ClangdLSPServer(class Transport &Transp,
1343 const ThreadsafeFS &TFS,
1344 const ClangdLSPServer::Options &Opts)
Kadir Cetinkaya9d662472019-10-15 14:20:52 +00001345 : BackgroundContext(Context::current().clone()), Transp(Transp),
Sam McCall7ba07792020-09-29 10:37:46 +02001346 MsgHandler(new MessageHandler(*this)), TFS(TFS),
1347 SupportedSymbolKinds(defaultSymbolKinds()),
1348 SupportedCompletionItemKinds(defaultCompletionItemKinds()), Opts(Opts) {
Sam McCall2c30fbc2018-10-18 12:32:04 +00001349 // clang-format off
1350 MsgHandler->bind("initialize", &ClangdLSPServer::onInitialize);
Sam McCall8a2d2942020-03-03 12:12:14 +01001351 MsgHandler->bind("initialized", &ClangdLSPServer::onInitialized);
Sam McCall2c30fbc2018-10-18 12:32:04 +00001352 MsgHandler->bind("shutdown", &ClangdLSPServer::onShutdown);
Sam McCall422c8282018-11-26 16:00:11 +00001353 MsgHandler->bind("sync", &ClangdLSPServer::onSync);
Sam McCall2c30fbc2018-10-18 12:32:04 +00001354 MsgHandler->bind("textDocument/rangeFormatting", &ClangdLSPServer::onDocumentRangeFormatting);
1355 MsgHandler->bind("textDocument/onTypeFormatting", &ClangdLSPServer::onDocumentOnTypeFormatting);
1356 MsgHandler->bind("textDocument/formatting", &ClangdLSPServer::onDocumentFormatting);
1357 MsgHandler->bind("textDocument/codeAction", &ClangdLSPServer::onCodeAction);
1358 MsgHandler->bind("textDocument/completion", &ClangdLSPServer::onCompletion);
1359 MsgHandler->bind("textDocument/signatureHelp", &ClangdLSPServer::onSignatureHelp);
1360 MsgHandler->bind("textDocument/definition", &ClangdLSPServer::onGoToDefinition);
Sam McCall866ba2c2019-02-01 11:26:13 +00001361 MsgHandler->bind("textDocument/declaration", &ClangdLSPServer::onGoToDeclaration);
Sam McCall2c30fbc2018-10-18 12:32:04 +00001362 MsgHandler->bind("textDocument/references", &ClangdLSPServer::onReference);
1363 MsgHandler->bind("textDocument/switchSourceHeader", &ClangdLSPServer::onSwitchSourceHeader);
Haojian Wuf429ab62019-07-24 07:49:23 +00001364 MsgHandler->bind("textDocument/prepareRename", &ClangdLSPServer::onPrepareRename);
Sam McCall2c30fbc2018-10-18 12:32:04 +00001365 MsgHandler->bind("textDocument/rename", &ClangdLSPServer::onRename);
1366 MsgHandler->bind("textDocument/hover", &ClangdLSPServer::onHover);
1367 MsgHandler->bind("textDocument/documentSymbol", &ClangdLSPServer::onDocumentSymbol);
1368 MsgHandler->bind("workspace/executeCommand", &ClangdLSPServer::onCommand);
1369 MsgHandler->bind("textDocument/documentHighlight", &ClangdLSPServer::onDocumentHighlight);
1370 MsgHandler->bind("workspace/symbol", &ClangdLSPServer::onWorkspaceSymbol);
1371 MsgHandler->bind("textDocument/didOpen", &ClangdLSPServer::onDocumentDidOpen);
1372 MsgHandler->bind("textDocument/didClose", &ClangdLSPServer::onDocumentDidClose);
1373 MsgHandler->bind("textDocument/didChange", &ClangdLSPServer::onDocumentDidChange);
Sam McCall596b63a2020-04-10 03:27:37 +02001374 MsgHandler->bind("textDocument/didSave", &ClangdLSPServer::onDocumentDidSave);
Sam McCall2c30fbc2018-10-18 12:32:04 +00001375 MsgHandler->bind("workspace/didChangeWatchedFiles", &ClangdLSPServer::onFileEvent);
1376 MsgHandler->bind("workspace/didChangeConfiguration", &ClangdLSPServer::onChangeConfiguration);
Jan Korousb4067012018-11-27 16:40:46 +00001377 MsgHandler->bind("textDocument/symbolInfo", &ClangdLSPServer::onSymbolInfo);
Kadir Cetinkaya86658022019-03-19 09:27:04 +00001378 MsgHandler->bind("textDocument/typeHierarchy", &ClangdLSPServer::onTypeHierarchy);
Nathan Ridge087b0442019-07-13 03:24:48 +00001379 MsgHandler->bind("typeHierarchy/resolve", &ClangdLSPServer::onResolveTypeHierarchy);
Utkarsh Saxena55925da2019-09-24 13:38:33 +00001380 MsgHandler->bind("textDocument/selectionRange", &ClangdLSPServer::onSelectionRange);
Sam McCall8d7ecc12019-12-16 19:08:51 +01001381 MsgHandler->bind("textDocument/documentLink", &ClangdLSPServer::onDocumentLink);
Sam McCall5fea54b2020-07-10 16:08:14 +02001382 MsgHandler->bind("textDocument/semanticTokens/full", &ClangdLSPServer::onSemanticTokens);
1383 MsgHandler->bind("textDocument/semanticTokens/full/delta", &ClangdLSPServer::onSemanticTokensDelta);
Kirill Bobyrev7a514c92020-07-14 09:28:38 +02001384 if (Opts.FoldingRanges)
1385 MsgHandler->bind("textDocument/foldingRange", &ClangdLSPServer::onFoldingRange);
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
Sam McCall032727f2020-05-06 01:39:59 +02001422// A completion request is sent when the user types '>' or ':', but we only
1423// want to trigger on '->' and '::'. We check the preceeding text to make
1424// sure it matches what we expected.
1425// Running the lexer here would be more robust (e.g. we can detect comments
1426// and avoid triggering completion there), but we choose to err on the side
1427// of simplicity here.
Ilya Biryukovb0826bd2019-01-03 13:37:12 +00001428bool ClangdLSPServer::shouldRunCompletion(
1429 const CompletionParams &Params) const {
Sam McCall032727f2020-05-06 01:39:59 +02001430 if (Params.context.triggerKind != CompletionTriggerKind::TriggerCharacter)
Ilya Biryukovb0826bd2019-01-03 13:37:12 +00001431 return true;
Ilya Biryukovb0826bd2019-01-03 13:37:12 +00001432 auto Code = DraftMgr.getDraft(Params.textDocument.uri.file());
1433 if (!Code)
1434 return true; // completion code will log the error for untracked doc.
Sam McCallcaf5a4d2020-03-03 15:57:39 +01001435 auto Offset = positionToOffset(Code->Contents, Params.position,
Ilya Biryukovb0826bd2019-01-03 13:37:12 +00001436 /*AllowColumnsBeyondLineLength=*/false);
1437 if (!Offset) {
1438 vlog("could not convert position '{0}' to offset for file '{1}'",
1439 Params.position, Params.textDocument.uri.file());
1440 return true;
1441 }
Sam McCall032727f2020-05-06 01:39:59 +02001442 return allowImplicitCompletion(Code->Contents, *Offset);
Ilya Biryukovb0826bd2019-01-03 13:37:12 +00001443}
1444
Johan Vikstroma848dab2019-07-04 07:53:12 +00001445void ClangdLSPServer::onHighlightingsReady(
Sam McCall2cd33e62020-03-04 00:33:29 +01001446 PathRef File, llvm::StringRef Version,
1447 std::vector<HighlightingToken> Highlightings) {
Johan Vikstromc2653ef22019-08-01 08:08:44 +00001448 std::vector<HighlightingToken> Old;
1449 std::vector<HighlightingToken> HighlightingsCopy = Highlightings;
1450 {
1451 std::lock_guard<std::mutex> Lock(HighlightingsMutex);
1452 Old = std::move(FileToHighlightings[File]);
1453 FileToHighlightings[File] = std::move(HighlightingsCopy);
1454 }
1455 // LSP allows us to send incremental edits of highlightings. Also need to diff
1456 // to remove highlightings from tokens that should no longer have them.
Haojian Wu0a6000f2019-08-26 08:38:45 +00001457 std::vector<LineHighlightings> Diffed = diffHighlightings(Highlightings, Old);
Sam McCalledf6a192020-03-24 00:31:14 +01001458 TheiaSemanticHighlightingParams Notification;
Sam McCall2cd33e62020-03-04 00:33:29 +01001459 Notification.TextDocument.uri =
1460 URIForFile::canonicalize(File, /*TUPath=*/File);
1461 Notification.TextDocument.version = decodeVersion(Version);
Sam McCalledf6a192020-03-24 00:31:14 +01001462 Notification.Lines = toTheiaSemanticHighlightingInformation(Diffed);
1463 publishTheiaSemanticHighlighting(Notification);
Johan Vikstroma848dab2019-07-04 07:53:12 +00001464}
1465
Sam McCall2cd33e62020-03-04 00:33:29 +01001466void ClangdLSPServer::onDiagnosticsReady(PathRef File, llvm::StringRef Version,
Sam McCalla7bb0cc2018-03-12 23:22:35 +00001467 std::vector<Diag> Diagnostics) {
Sam McCall6525a6b2020-03-03 12:44:40 +01001468 PublishDiagnosticsParams Notification;
Sam McCall2cd33e62020-03-04 00:33:29 +01001469 Notification.version = decodeVersion(Version);
Sam McCall6525a6b2020-03-03 12:44:40 +01001470 Notification.uri = URIForFile::canonicalize(File, /*TUPath=*/File);
Ilya Biryukov38d79772017-05-16 09:38:59 +00001471 DiagnosticToReplacementMap LocalFixIts; // Temporary storage
Sam McCalla7bb0cc2018-03-12 23:22:35 +00001472 for (auto &Diag : Diagnostics) {
Sam McCall6525a6b2020-03-03 12:44:40 +01001473 toLSPDiags(Diag, Notification.uri, DiagOpts,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001474 [&](clangd::Diagnostic Diag, llvm::ArrayRef<Fix> Fixes) {
Sam McCall16e70702018-10-24 07:59:38 +00001475 auto &FixItsForDiagnostic = LocalFixIts[Diag];
1476 llvm::copy(Fixes, std::back_inserter(FixItsForDiagnostic));
Sam McCall6525a6b2020-03-03 12:44:40 +01001477 Notification.diagnostics.push_back(std::move(Diag));
Sam McCall16e70702018-10-24 07:59:38 +00001478 });
Ilya Biryukov38d79772017-05-16 09:38:59 +00001479 }
1480
1481 // Cache FixIts
1482 {
Ilya Biryukov38d79772017-05-16 09:38:59 +00001483 std::lock_guard<std::mutex> Lock(FixItsMutex);
1484 FixItsMap[File] = LocalFixIts;
1485 }
1486
Ilya Biryukov49c10712019-03-25 10:15:11 +00001487 // Send a notification to the LSP client.
Sam McCall6525a6b2020-03-03 12:44:40 +01001488 publishDiagnostics(Notification);
Ilya Biryukov38d79772017-05-16 09:38:59 +00001489}
Simon Marchi9569fd52018-03-16 14:30:42 +00001490
Sam McCall7d20e802020-01-22 19:41:45 +01001491void ClangdLSPServer::onBackgroundIndexProgress(
1492 const BackgroundQueue::Stats &Stats) {
1493 static const char ProgressToken[] = "backgroundIndexProgress";
1494 std::lock_guard<std::mutex> Lock(BackgroundIndexProgressMutex);
1495
1496 auto NotifyProgress = [this](const BackgroundQueue::Stats &Stats) {
1497 if (BackgroundIndexProgressState != BackgroundIndexProgress::Live) {
1498 WorkDoneProgressBegin Begin;
1499 Begin.percentage = true;
1500 Begin.title = "indexing";
1501 progress(ProgressToken, std::move(Begin));
1502 BackgroundIndexProgressState = BackgroundIndexProgress::Live;
1503 }
1504
1505 if (Stats.Completed < Stats.Enqueued) {
1506 assert(Stats.Enqueued > Stats.LastIdle);
1507 WorkDoneProgressReport Report;
1508 Report.percentage = 100.0 * (Stats.Completed - Stats.LastIdle) /
1509 (Stats.Enqueued - Stats.LastIdle);
1510 Report.message =
1511 llvm::formatv("{0}/{1}", Stats.Completed - Stats.LastIdle,
1512 Stats.Enqueued - Stats.LastIdle);
1513 progress(ProgressToken, std::move(Report));
1514 } else {
1515 assert(Stats.Completed == Stats.Enqueued);
1516 progress(ProgressToken, WorkDoneProgressEnd());
1517 BackgroundIndexProgressState = BackgroundIndexProgress::Empty;
1518 }
1519 };
1520
1521 switch (BackgroundIndexProgressState) {
1522 case BackgroundIndexProgress::Unsupported:
1523 return;
1524 case BackgroundIndexProgress::Creating:
1525 // Cache this update for when the progress bar is available.
1526 PendingBackgroundIndexProgress = Stats;
1527 return;
1528 case BackgroundIndexProgress::Empty: {
1529 if (BackgroundIndexSkipCreate) {
1530 NotifyProgress(Stats);
1531 break;
1532 }
1533 // Cache this update for when the progress bar is available.
1534 PendingBackgroundIndexProgress = Stats;
1535 BackgroundIndexProgressState = BackgroundIndexProgress::Creating;
1536 WorkDoneProgressCreateParams CreateRequest;
1537 CreateRequest.token = ProgressToken;
1538 call<std::nullptr_t>(
1539 "window/workDoneProgress/create", CreateRequest,
1540 [this, NotifyProgress](llvm::Expected<std::nullptr_t> E) {
1541 std::lock_guard<std::mutex> Lock(BackgroundIndexProgressMutex);
1542 if (E) {
1543 NotifyProgress(this->PendingBackgroundIndexProgress);
1544 } else {
1545 elog("Failed to create background index progress bar: {0}",
1546 E.takeError());
1547 // give up forever rather than thrashing about
1548 BackgroundIndexProgressState = BackgroundIndexProgress::Unsupported;
1549 }
1550 });
1551 break;
1552 }
1553 case BackgroundIndexProgress::Live:
1554 NotifyProgress(Stats);
1555 break;
1556 }
1557}
1558
Haojian Wub6188492018-12-20 15:39:12 +00001559void ClangdLSPServer::onFileUpdated(PathRef File, const TUStatus &Status) {
1560 if (!SupportFileStatus)
1561 return;
1562 // FIXME: we don't emit "BuildingFile" and `RunningAction`, as these
1563 // two statuses are running faster in practice, which leads the UI constantly
1564 // changing, and doesn't provide much value. We may want to emit status at a
1565 // reasonable time interval (e.g. 0.5s).
Kadir Cetinkaya6b850322020-03-17 19:08:23 +01001566 if (Status.PreambleActivity == PreambleAction::Idle &&
1567 (Status.ASTActivity.K == ASTAction::Building ||
1568 Status.ASTActivity.K == ASTAction::RunningAction))
Haojian Wub6188492018-12-20 15:39:12 +00001569 return;
1570 notify("textDocument/clangd.fileStatus", Status.render(File));
1571}
1572
Sam McCall596b63a2020-04-10 03:27:37 +02001573void ClangdLSPServer::reparseOpenFilesIfNeeded(
1574 llvm::function_ref<bool(llvm::StringRef File)> Filter) {
David Goldman60249c22020-01-13 17:01:10 -05001575 // Reparse only opened files that were modified.
Simon Marchi9569fd52018-03-16 14:30:42 +00001576 for (const Path &FilePath : DraftMgr.getActiveFiles())
Sam McCall596b63a2020-04-10 03:27:37 +02001577 if (Filter(FilePath))
Sam McCall2cd33e62020-03-04 00:33:29 +01001578 if (auto Draft = DraftMgr.getDraft(FilePath)) // else disappeared in race?
1579 Server->addDocument(FilePath, std::move(Draft->Contents),
1580 encodeVersion(Draft->Version),
1581 WantDiagnostics::Auto);
Simon Marchi9569fd52018-03-16 14:30:42 +00001582}
Alex Lorenzf8087862018-08-01 17:39:29 +00001583
Sam McCallc008af62018-10-20 15:30:37 +00001584} // namespace clangd
1585} // namespace clang