blob: 9ed635c88e71950ef6bbe7a458cab367642e9080 [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 McCall17747d22020-09-28 18:12:37 +020071 CA.kind = T.Kind.str();
Ilya Biryukovcce67a32019-01-29 14:17:36 +000072 // This tweak may have an expensive second stage, we only run it if the user
73 // actually chooses it in the UI. We reply with a command that would run the
74 // corresponding tweak.
75 // FIXME: for some tweaks, computing the edits is cheap and we could send them
76 // directly.
77 CA.command.emplace();
78 CA.command->title = T.Title;
Benjamin Krameradcd0262020-01-28 20:23:46 +010079 CA.command->command = std::string(Command::CLANGD_APPLY_TWEAK);
Ilya Biryukovcce67a32019-01-29 14:17:36 +000080 CA.command->tweakArgs.emplace();
81 CA.command->tweakArgs->file = File;
82 CA.command->tweakArgs->tweakID = T.ID;
83 CA.command->tweakArgs->selection = Selection;
84 return CA;
Simon Pilgrime9a136b2019-02-03 14:08:30 +000085}
Ilya Biryukovcce67a32019-01-29 14:17:36 +000086
Ilya Biryukov19d75602018-11-23 15:21:19 +000087void adjustSymbolKinds(llvm::MutableArrayRef<DocumentSymbol> Syms,
88 SymbolKindBitset Kinds) {
89 for (auto &S : Syms) {
90 S.kind = adjustKindToCapability(S.kind, Kinds);
91 adjustSymbolKinds(S.children, Kinds);
92 }
93}
94
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +000095SymbolKindBitset defaultSymbolKinds() {
96 SymbolKindBitset Defaults;
97 for (size_t I = SymbolKindMin; I <= static_cast<size_t>(SymbolKind::Array);
98 ++I)
99 Defaults.set(I);
100 return Defaults;
101}
102
Kadir Cetinkaya133d46f2018-09-27 17:13:07 +0000103CompletionItemKindBitset defaultCompletionItemKinds() {
104 CompletionItemKindBitset Defaults;
105 for (size_t I = CompletionItemKindMin;
106 I <= static_cast<size_t>(CompletionItemKind::Reference); ++I)
107 Defaults.set(I);
108 return Defaults;
109}
110
Haojian Wu1ca2ee42019-07-04 12:27:21 +0000111// Build a lookup table (HighlightingKind => {TextMate Scopes}), which is sent
112// to the LSP client.
113std::vector<std::vector<std::string>> buildHighlightScopeLookupTable() {
114 std::vector<std::vector<std::string>> LookupTable;
115 // HighlightingKind is using as the index.
Ilya Biryukov63d5d162019-09-09 08:57:17 +0000116 for (int KindValue = 0; KindValue <= (int)HighlightingKind::LastKind;
Haojian Wu1ca2ee42019-07-04 12:27:21 +0000117 ++KindValue)
Benjamin Krameradcd0262020-01-28 20:23:46 +0100118 LookupTable.push_back(
119 {std::string(toTextMateScope((HighlightingKind)(KindValue)))});
Haojian Wu1ca2ee42019-07-04 12:27:21 +0000120 return LookupTable;
121}
122
Haojian Wu852bafa2019-10-23 14:40:20 +0200123// Makes sure edits in \p FE are applicable to latest file contents reported by
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000124// editor. If not generates an error message containing information about files
125// that needs to be saved.
Haojian Wu852bafa2019-10-23 14:40:20 +0200126llvm::Error validateEdits(const DraftStore &DraftMgr, const FileEdits &FE) {
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000127 size_t InvalidFileCount = 0;
128 llvm::StringRef LastInvalidFile;
Haojian Wu852bafa2019-10-23 14:40:20 +0200129 for (const auto &It : FE) {
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000130 if (auto Draft = DraftMgr.getDraft(It.first())) {
131 // If the file is open in user's editor, make sure the version we
132 // saw and current version are compatible as this is the text that
133 // will be replaced by editors.
Sam McCallcaf5a4d2020-03-03 15:57:39 +0100134 if (!It.second.canApplyTo(Draft->Contents)) {
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000135 ++InvalidFileCount;
136 LastInvalidFile = It.first();
137 }
138 }
139 }
140 if (!InvalidFileCount)
141 return llvm::Error::success();
142 if (InvalidFileCount == 1)
Sam McCall30667c92020-07-08 21:49:38 +0200143 return error("File must be saved first: {0}", LastInvalidFile);
144 return error("Files must be saved first: {0} (and {1} others)",
145 LastInvalidFile, InvalidFileCount - 1);
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000146}
147
Ilya Biryukovafb55542017-05-16 14:40:30 +0000148} // namespace
149
Sam McCall2c30fbc2018-10-18 12:32:04 +0000150// MessageHandler dispatches incoming LSP messages.
151// It handles cross-cutting concerns:
152// - serializes/deserializes protocol objects to JSON
153// - logging of inbound messages
154// - cancellation handling
155// - basic call tracing
Sam McCall3d0adbe2018-10-18 14:41:50 +0000156// MessageHandler ensures that initialize() is called before any other handler.
Sam McCall2c30fbc2018-10-18 12:32:04 +0000157class ClangdLSPServer::MessageHandler : public Transport::MessageHandler {
158public:
159 MessageHandler(ClangdLSPServer &Server) : Server(Server) {}
160
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000161 bool onNotify(llvm::StringRef Method, llvm::json::Value Params) override {
Sam McCalla69698f2019-03-27 17:47:49 +0000162 WithContext HandlerContext(handlerContext());
Sam McCall2c30fbc2018-10-18 12:32:04 +0000163 log("<-- {0}", Method);
164 if (Method == "exit")
165 return false;
Sam McCall3d0adbe2018-10-18 14:41:50 +0000166 if (!Server.Server)
167 elog("Notification {0} before initialization", Method);
168 else if (Method == "$/cancelRequest")
Sam McCall2c30fbc2018-10-18 12:32:04 +0000169 onCancel(std::move(Params));
170 else if (auto Handler = Notifications.lookup(Method))
171 Handler(std::move(Params));
172 else
173 log("unhandled notification {0}", Method);
174 return true;
175 }
176
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000177 bool onCall(llvm::StringRef Method, llvm::json::Value Params,
178 llvm::json::Value ID) override {
Sam McCalla69698f2019-03-27 17:47:49 +0000179 WithContext HandlerContext(handlerContext());
Sam McCalle2f3a732018-10-24 14:26:26 +0000180 // Calls can be canceled by the client. Add cancellation context.
181 WithContext WithCancel(cancelableRequestContext(ID));
Kadir Cetinkayae64f99c2020-04-16 23:12:09 +0200182 trace::Span Tracer(Method, LSPLatency);
Sam McCalle2f3a732018-10-24 14:26:26 +0000183 SPAN_ATTACH(Tracer, "Params", Params);
184 ReplyOnce Reply(ID, Method, &Server, Tracer.Args);
Sam McCall2c30fbc2018-10-18 12:32:04 +0000185 log("<-- {0}({1})", Method, ID);
Sam McCall3d0adbe2018-10-18 14:41:50 +0000186 if (!Server.Server && Method != "initialize") {
187 elog("Call {0} before initialization.", Method);
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000188 Reply(llvm::make_error<LSPError>("server not initialized",
189 ErrorCode::ServerNotInitialized));
Sam McCall3d0adbe2018-10-18 14:41:50 +0000190 } else if (auto Handler = Calls.lookup(Method))
Sam McCalle2f3a732018-10-24 14:26:26 +0000191 Handler(std::move(Params), std::move(Reply));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000192 else
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000193 Reply(llvm::make_error<LSPError>("method not found",
194 ErrorCode::MethodNotFound));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000195 return true;
196 }
197
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000198 bool onReply(llvm::json::Value ID,
199 llvm::Expected<llvm::json::Value> Result) override {
Sam McCalla69698f2019-03-27 17:47:49 +0000200 WithContext HandlerContext(handlerContext());
Haojian Wuf2516342019-08-05 12:48:09 +0000201
202 Callback<llvm::json::Value> ReplyHandler = nullptr;
203 if (auto IntID = ID.getAsInteger()) {
204 std::lock_guard<std::mutex> Mutex(CallMutex);
205 // Find a corresponding callback for the request ID;
206 for (size_t Index = 0; Index < ReplyCallbacks.size(); ++Index) {
207 if (ReplyCallbacks[Index].first == *IntID) {
208 ReplyHandler = std::move(ReplyCallbacks[Index].second);
209 ReplyCallbacks.erase(ReplyCallbacks.begin() +
210 Index); // remove the entry
211 break;
212 }
213 }
214 }
215
216 if (!ReplyHandler) {
217 // No callback being found, use a default log callback.
218 ReplyHandler = [&ID](llvm::Expected<llvm::json::Value> Result) {
219 elog("received a reply with ID {0}, but there was no such call", ID);
220 if (!Result)
221 llvm::consumeError(Result.takeError());
222 };
223 }
224
225 // Log and run the reply handler.
226 if (Result) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000227 log("<-- reply({0})", ID);
Haojian Wuf2516342019-08-05 12:48:09 +0000228 ReplyHandler(std::move(Result));
229 } else {
230 auto Err = Result.takeError();
231 log("<-- reply({0}) error: {1}", ID, Err);
232 ReplyHandler(std::move(Err));
233 }
Sam McCall2c30fbc2018-10-18 12:32:04 +0000234 return true;
235 }
236
237 // Bind an LSP method name to a call.
Sam McCalle2f3a732018-10-24 14:26:26 +0000238 template <typename Param, typename Result>
Sam McCall2c30fbc2018-10-18 12:32:04 +0000239 void bind(const char *Method,
Sam McCalle2f3a732018-10-24 14:26:26 +0000240 void (ClangdLSPServer::*Handler)(const Param &, Callback<Result>)) {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000241 Calls[Method] = [Method, Handler, this](llvm::json::Value RawParams,
Sam McCalle2f3a732018-10-24 14:26:26 +0000242 ReplyOnce Reply) {
Sam McCallfa69b602020-09-24 01:14:12 +0200243 auto P = parse<Param>(RawParams, Method, "request");
244 if (!P)
245 return Reply(P.takeError());
246 (Server.*Handler)(*P, std::move(Reply));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000247 };
248 }
249
Haojian Wuf2516342019-08-05 12:48:09 +0000250 // Bind a reply callback to a request. The callback will be invoked when
251 // clangd receives the reply from the LSP client.
252 // Return a call id of the request.
253 llvm::json::Value bindReply(Callback<llvm::json::Value> Reply) {
254 llvm::Optional<std::pair<int, Callback<llvm::json::Value>>> OldestCB;
255 int ID;
256 {
257 std::lock_guard<std::mutex> Mutex(CallMutex);
258 ID = NextCallID++;
259 ReplyCallbacks.emplace_back(ID, std::move(Reply));
260
261 // If the queue overflows, we assume that the client didn't reply the
262 // oldest request, and run the corresponding callback which replies an
263 // error to the client.
264 if (ReplyCallbacks.size() > MaxReplayCallbacks) {
265 elog("more than {0} outstanding LSP calls, forgetting about {1}",
266 MaxReplayCallbacks, ReplyCallbacks.front().first);
267 OldestCB = std::move(ReplyCallbacks.front());
268 ReplyCallbacks.pop_front();
269 }
270 }
271 if (OldestCB)
Sam McCall30667c92020-07-08 21:49:38 +0200272 OldestCB->second(
273 error("failed to receive a client reply for request ({0})",
274 OldestCB->first));
Haojian Wuf2516342019-08-05 12:48:09 +0000275 return ID;
276 }
277
Sam McCall2c30fbc2018-10-18 12:32:04 +0000278 // Bind an LSP method name to a notification.
279 template <typename Param>
280 void bind(const char *Method,
281 void (ClangdLSPServer::*Handler)(const Param &)) {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000282 Notifications[Method] = [Method, Handler,
283 this](llvm::json::Value RawParams) {
Sam McCallfa69b602020-09-24 01:14:12 +0200284 llvm::Expected<Param> P = parse<Param>(RawParams, Method, "request");
285 if (!P)
286 return llvm::consumeError(P.takeError());
Kadir Cetinkayae64f99c2020-04-16 23:12:09 +0200287 trace::Span Tracer(Method, LSPLatency);
Sam McCall2c30fbc2018-10-18 12:32:04 +0000288 SPAN_ATTACH(Tracer, "Params", RawParams);
Sam McCallfa69b602020-09-24 01:14:12 +0200289 (Server.*Handler)(*P);
Sam McCall2c30fbc2018-10-18 12:32:04 +0000290 };
291 }
292
293private:
Sam McCalle2f3a732018-10-24 14:26:26 +0000294 // Function object to reply to an LSP call.
295 // Each instance must be called exactly once, otherwise:
296 // - the bug is logged, and (in debug mode) an assert will fire
297 // - if there was no reply, an error reply is sent
298 // - if there were multiple replies, only the first is sent
299 class ReplyOnce {
300 std::atomic<bool> Replied = {false};
Sam McCalld7babe42018-10-24 15:18:40 +0000301 std::chrono::steady_clock::time_point Start;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000302 llvm::json::Value ID;
Sam McCalle2f3a732018-10-24 14:26:26 +0000303 std::string Method;
304 ClangdLSPServer *Server; // Null when moved-from.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000305 llvm::json::Object *TraceArgs;
Sam McCalle2f3a732018-10-24 14:26:26 +0000306
307 public:
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000308 ReplyOnce(const llvm::json::Value &ID, llvm::StringRef Method,
309 ClangdLSPServer *Server, llvm::json::Object *TraceArgs)
Sam McCalld7babe42018-10-24 15:18:40 +0000310 : Start(std::chrono::steady_clock::now()), ID(ID), Method(Method),
311 Server(Server), TraceArgs(TraceArgs) {
Sam McCalle2f3a732018-10-24 14:26:26 +0000312 assert(Server);
313 }
314 ReplyOnce(ReplyOnce &&Other)
Sam McCalld7babe42018-10-24 15:18:40 +0000315 : Replied(Other.Replied.load()), Start(Other.Start),
316 ID(std::move(Other.ID)), Method(std::move(Other.Method)),
317 Server(Other.Server), TraceArgs(Other.TraceArgs) {
Sam McCalle2f3a732018-10-24 14:26:26 +0000318 Other.Server = nullptr;
319 }
Ilya Biryukov22fa4652019-01-03 13:28:05 +0000320 ReplyOnce &operator=(ReplyOnce &&) = delete;
Sam McCalle2f3a732018-10-24 14:26:26 +0000321 ReplyOnce(const ReplyOnce &) = delete;
Ilya Biryukov22fa4652019-01-03 13:28:05 +0000322 ReplyOnce &operator=(const ReplyOnce &) = delete;
Sam McCalle2f3a732018-10-24 14:26:26 +0000323
324 ~ReplyOnce() {
Haojian Wuf2516342019-08-05 12:48:09 +0000325 // There's one legitimate reason to never reply to a request: clangd's
326 // request handler send a call to the client (e.g. applyEdit) and the
327 // client never replied. In this case, the ReplyOnce is owned by
328 // ClangdLSPServer's reply callback table and is destroyed along with the
329 // server. We don't attempt to send a reply in this case, there's little
330 // to be gained from doing so.
331 if (Server && !Server->IsBeingDestroyed && !Replied) {
Sam McCalle2f3a732018-10-24 14:26:26 +0000332 elog("No reply to message {0}({1})", Method, ID);
333 assert(false && "must reply to all calls!");
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000334 (*this)(llvm::make_error<LSPError>("server failed to reply",
335 ErrorCode::InternalError));
Sam McCalle2f3a732018-10-24 14:26:26 +0000336 }
337 }
338
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000339 void operator()(llvm::Expected<llvm::json::Value> Reply) {
Sam McCalle2f3a732018-10-24 14:26:26 +0000340 assert(Server && "moved-from!");
341 if (Replied.exchange(true)) {
342 elog("Replied twice to message {0}({1})", Method, ID);
343 assert(false && "must reply to each call only once!");
344 return;
345 }
Sam McCalld7babe42018-10-24 15:18:40 +0000346 auto Duration = std::chrono::steady_clock::now() - Start;
347 if (Reply) {
348 log("--> reply:{0}({1}) {2:ms}", Method, ID, Duration);
349 if (TraceArgs)
Sam McCalle2f3a732018-10-24 14:26:26 +0000350 (*TraceArgs)["Reply"] = *Reply;
Sam McCalld7babe42018-10-24 15:18:40 +0000351 std::lock_guard<std::mutex> Lock(Server->TranspWriter);
352 Server->Transp.reply(std::move(ID), std::move(Reply));
353 } else {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000354 llvm::Error Err = Reply.takeError();
Sam McCalld7babe42018-10-24 15:18:40 +0000355 log("--> reply:{0}({1}) {2:ms}, error: {3}", Method, ID, Duration, Err);
356 if (TraceArgs)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000357 (*TraceArgs)["Error"] = llvm::to_string(Err);
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(Err));
Sam McCalle2f3a732018-10-24 14:26:26 +0000360 }
Sam McCalle2f3a732018-10-24 14:26:26 +0000361 }
362 };
363
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000364 llvm::StringMap<std::function<void(llvm::json::Value)>> Notifications;
365 llvm::StringMap<std::function<void(llvm::json::Value, ReplyOnce)>> Calls;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000366
367 // Method calls may be cancelled by ID, so keep track of their state.
368 // This needs a mutex: handlers may finish on a different thread, and that's
369 // when we clean up entries in the map.
370 mutable std::mutex RequestCancelersMutex;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000371 llvm::StringMap<std::pair<Canceler, /*Cookie*/ unsigned>> RequestCancelers;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000372 unsigned NextRequestCookie = 0; // To disambiguate reused IDs, see below.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000373 void onCancel(const llvm::json::Value &Params) {
374 const llvm::json::Value *ID = nullptr;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000375 if (auto *O = Params.getAsObject())
376 ID = O->get("id");
377 if (!ID) {
378 elog("Bad cancellation request: {0}", Params);
379 return;
380 }
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000381 auto StrID = llvm::to_string(*ID);
Sam McCall2c30fbc2018-10-18 12:32:04 +0000382 std::lock_guard<std::mutex> Lock(RequestCancelersMutex);
383 auto It = RequestCancelers.find(StrID);
384 if (It != RequestCancelers.end())
385 It->second.first(); // Invoke the canceler.
386 }
Sam McCalla69698f2019-03-27 17:47:49 +0000387
388 Context handlerContext() const {
389 return Context::current().derive(
390 kCurrentOffsetEncoding,
Sam McCall6342b382020-09-30 10:56:43 +0200391 Server.Opts.Encoding.getValueOr(OffsetEncoding::UTF16));
Sam McCalla69698f2019-03-27 17:47:49 +0000392 }
393
Sam McCall2c30fbc2018-10-18 12:32:04 +0000394 // We run cancelable requests in a context that does two things:
395 // - allows cancellation using RequestCancelers[ID]
396 // - cleans up the entry in RequestCancelers when it's no longer needed
397 // If a client reuses an ID, the last wins and the first cannot be canceled.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000398 Context cancelableRequestContext(const llvm::json::Value &ID) {
Sam McCall31db1e02020-04-11 18:19:50 +0200399 auto Task = cancelableTask(
400 /*Reason=*/static_cast<int>(ErrorCode::RequestCancelled));
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000401 auto StrID = llvm::to_string(ID); // JSON-serialize ID for map key.
Sam McCall2c30fbc2018-10-18 12:32:04 +0000402 auto Cookie = NextRequestCookie++; // No lock, only called on main thread.
403 {
404 std::lock_guard<std::mutex> Lock(RequestCancelersMutex);
405 RequestCancelers[StrID] = {std::move(Task.second), Cookie};
406 }
407 // When the request ends, we can clean up the entry we just added.
408 // The cookie lets us check that it hasn't been overwritten due to ID
409 // reuse.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000410 return Task.first.derive(llvm::make_scope_exit([this, StrID, Cookie] {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000411 std::lock_guard<std::mutex> Lock(RequestCancelersMutex);
412 auto It = RequestCancelers.find(StrID);
413 if (It != RequestCancelers.end() && It->second.second == Cookie)
414 RequestCancelers.erase(It);
415 }));
416 }
417
Kadir Cetinkaya9a3a87d2019-10-09 13:59:31 +0000418 // The maximum number of callbacks held in clangd.
419 //
420 // We bound the maximum size to the pending map to prevent memory leakage
421 // for cases where LSP clients don't reply for the request.
422 // This has to go after RequestCancellers and RequestCancellersMutex since it
423 // can contain a callback that has a cancelable context.
424 static constexpr int MaxReplayCallbacks = 100;
425 mutable std::mutex CallMutex;
426 int NextCallID = 0; /* GUARDED_BY(CallMutex) */
427 std::deque<std::pair</*RequestID*/ int,
428 /*ReplyHandler*/ Callback<llvm::json::Value>>>
429 ReplyCallbacks; /* GUARDED_BY(CallMutex) */
430
Sam McCall2c30fbc2018-10-18 12:32:04 +0000431 ClangdLSPServer &Server;
432};
Haojian Wuf2516342019-08-05 12:48:09 +0000433constexpr int ClangdLSPServer::MessageHandler::MaxReplayCallbacks;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000434
435// call(), notify(), and reply() wrap the Transport, adding logging and locking.
Haojian Wuf2516342019-08-05 12:48:09 +0000436void ClangdLSPServer::callRaw(StringRef Method, llvm::json::Value Params,
437 Callback<llvm::json::Value> CB) {
438 auto ID = MsgHandler->bindReply(std::move(CB));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000439 log("--> {0}({1})", Method, ID);
Sam McCall2c30fbc2018-10-18 12:32:04 +0000440 std::lock_guard<std::mutex> Lock(TranspWriter);
441 Transp.call(Method, std::move(Params), ID);
442}
443
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000444void ClangdLSPServer::notify(llvm::StringRef Method, llvm::json::Value Params) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000445 log("--> {0}", Method);
446 std::lock_guard<std::mutex> Lock(TranspWriter);
447 Transp.notify(Method, std::move(Params));
448}
449
Sam McCall71177ac2020-03-24 02:24:47 +0100450static std::vector<llvm::StringRef> semanticTokenTypes() {
451 std::vector<llvm::StringRef> Types;
452 for (unsigned I = 0; I <= static_cast<unsigned>(HighlightingKind::LastKind);
453 ++I)
454 Types.push_back(toSemanticTokenType(static_cast<HighlightingKind>(I)));
455 return Types;
456}
457
Sam McCall2c30fbc2018-10-18 12:32:04 +0000458void ClangdLSPServer::onInitialize(const InitializeParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000459 Callback<llvm::json::Value> Reply) {
Sam McCalla69698f2019-03-27 17:47:49 +0000460 // Determine character encoding first as it affects constructed ClangdServer.
Sam McCall6342b382020-09-30 10:56:43 +0200461 if (Params.capabilities.offsetEncoding && !Opts.Encoding) {
462 Opts.Encoding = OffsetEncoding::UTF16; // fallback
Sam McCalla69698f2019-03-27 17:47:49 +0000463 for (OffsetEncoding Supported : *Params.capabilities.offsetEncoding)
464 if (Supported != OffsetEncoding::UnsupportedEncoding) {
Sam McCall6342b382020-09-30 10:56:43 +0200465 Opts.Encoding = Supported;
Sam McCalla69698f2019-03-27 17:47:49 +0000466 break;
467 }
468 }
Sam McCalla69698f2019-03-27 17:47:49 +0000469
Sam McCall7ba07792020-09-29 10:37:46 +0200470 Opts.TheiaSemanticHighlighting =
Sam McCalledf6a192020-03-24 00:31:14 +0100471 Params.capabilities.TheiaSemanticHighlighting;
Sam McCallfc830102020-04-01 12:02:28 +0200472 if (Params.capabilities.TheiaSemanticHighlighting &&
473 Params.capabilities.SemanticTokens) {
474 log("Client supports legacy semanticHighlights notification and standard "
475 "semanticTokens request, choosing the latter (no notifications).");
Sam McCall7ba07792020-09-29 10:37:46 +0200476 Opts.TheiaSemanticHighlighting = false;
Sam McCallfc830102020-04-01 12:02:28 +0200477 }
478
Sam McCall0d9b40f2018-10-19 15:42:23 +0000479 if (Params.rootUri && *Params.rootUri)
Sam McCall7ba07792020-09-29 10:37:46 +0200480 Opts.WorkspaceRoot = std::string(Params.rootUri->file());
Sam McCall0d9b40f2018-10-19 15:42:23 +0000481 else if (Params.rootPath && !Params.rootPath->empty())
Sam McCall7ba07792020-09-29 10:37:46 +0200482 Opts.WorkspaceRoot = *Params.rootPath;
Sam McCall3d0adbe2018-10-18 14:41:50 +0000483 if (Server)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000484 return Reply(llvm::make_error<LSPError>("server already initialized",
485 ErrorCode::InvalidRequest));
Sam McCallbc904612018-10-25 04:22:52 +0000486 if (const auto &Dir = Params.initializationOptions.compilationDatabasePath)
Sam McCall7ba07792020-09-29 10:37:46 +0200487 Opts.CompileCommandsDir = Dir;
488 if (Opts.UseDirBasedCDB) {
Jonas Devlieghere1c705d92019-08-14 23:52:23 +0000489 BaseCDB = std::make_unique<DirectoryBasedGlobalCompilationDatabase>(
Sam McCall7ba07792020-09-29 10:37:46 +0200490 Opts.CompileCommandsDir);
491 BaseCDB = getQueryDriverDatabase(llvm::makeArrayRef(Opts.QueryDriverGlobs),
492 std::move(BaseCDB));
Kadir Cetinkaya256247c2019-06-26 07:45:27 +0000493 }
Sam McCall99768b22019-11-29 19:37:48 +0100494 auto Mangler = CommandMangler::detect();
Sam McCall7ba07792020-09-29 10:37:46 +0200495 if (Opts.ResourceDir)
496 Mangler.ResourceDir = *Opts.ResourceDir;
Kadir Cetinkayabe6b35d2019-01-22 09:10:20 +0000497 CDB.emplace(BaseCDB.get(), Params.initializationOptions.fallbackFlags,
Sam McCall2a3ac012020-06-09 22:54:42 +0200498 tooling::ArgumentsAdjuster(std::move(Mangler)));
Kadir Cetinkaya9d662472019-10-15 14:20:52 +0000499 {
500 // Switch caller's context with LSPServer's background context. Since we
501 // rather want to propagate information from LSPServer's context into the
502 // Server, CDB, etc.
503 WithContext MainContext(BackgroundContext.clone());
504 llvm::Optional<WithContextValue> WithOffsetEncoding;
Sam McCall6342b382020-09-30 10:56:43 +0200505 if (Opts.Encoding)
506 WithOffsetEncoding.emplace(kCurrentOffsetEncoding, *Opts.Encoding);
Sam McCall7ba07792020-09-29 10:37:46 +0200507 Server.emplace(*CDB, TFS, Opts,
Sam McCall6ef1cce2020-01-24 14:08:56 +0100508 static_cast<ClangdServer::Callbacks *>(this));
Kadir Cetinkaya9d662472019-10-15 14:20:52 +0000509 }
Sam McCallbc904612018-10-25 04:22:52 +0000510 applyConfiguration(Params.initializationOptions.ConfigSettings);
Simon Marchi88016782018-08-01 11:28:49 +0000511
Sam McCall7ba07792020-09-29 10:37:46 +0200512 Opts.CodeComplete.EnableSnippets = Params.capabilities.CompletionSnippets;
513 Opts.CodeComplete.IncludeFixIts = Params.capabilities.CompletionFixes;
514 if (!Opts.CodeComplete.BundleOverloads.hasValue())
515 Opts.CodeComplete.BundleOverloads = Params.capabilities.HasSignatureHelp;
516 Opts.CodeComplete.DocumentationFormat =
Sam McCalla3a27a72020-04-30 10:49:32 +0200517 Params.capabilities.CompletionDocumentationFormat;
Sam McCallbf6a2fc2018-10-17 07:33:42 +0000518 DiagOpts.EmbedFixesInDiagnostics = Params.capabilities.DiagnosticFixes;
519 DiagOpts.SendDiagnosticCategory = Params.capabilities.DiagnosticCategory;
Sam McCallc9e4ee92019-04-18 15:17:07 +0000520 DiagOpts.EmitRelatedLocations =
521 Params.capabilities.DiagnosticRelatedInformation;
Sam McCallbf6a2fc2018-10-17 07:33:42 +0000522 if (Params.capabilities.WorkspaceSymbolKinds)
523 SupportedSymbolKinds |= *Params.capabilities.WorkspaceSymbolKinds;
524 if (Params.capabilities.CompletionItemKinds)
525 SupportedCompletionItemKinds |= *Params.capabilities.CompletionItemKinds;
526 SupportsCodeAction = Params.capabilities.CodeActionStructure;
Ilya Biryukov19d75602018-11-23 15:21:19 +0000527 SupportsHierarchicalDocumentSymbol =
528 Params.capabilities.HierarchicalDocumentSymbol;
Haojian Wub6188492018-12-20 15:39:12 +0000529 SupportFileStatus = Params.initializationOptions.FileStatus;
Ilya Biryukovf9169d02019-05-29 10:01:00 +0000530 HoverContentFormat = Params.capabilities.HoverContentFormat;
Ilya Biryukov4ef0f822019-06-04 09:36:59 +0000531 SupportsOffsetsInSignatureHelp = Params.capabilities.OffsetsInSignatureHelp;
Sam McCall7d20e802020-01-22 19:41:45 +0100532 if (Params.capabilities.WorkDoneProgress)
533 BackgroundIndexProgressState = BackgroundIndexProgress::Empty;
534 BackgroundIndexSkipCreate = Params.capabilities.ImplicitProgressCreation;
Haojian Wuf429ab62019-07-24 07:49:23 +0000535
536 // Per LSP, renameProvider can be either boolean or RenameOptions.
537 // RenameOptions will be specified if the client states it supports prepare.
538 llvm::json::Value RenameProvider =
539 llvm::json::Object{{"prepareProvider", true}};
540 if (!Params.capabilities.RenamePrepareSupport) // Only boolean allowed per LSP
541 RenameProvider = true;
542
Haojian Wu08d93f12019-08-22 14:53:45 +0000543 // Per LSP, codeActionProvide can be either boolean or CodeActionOptions.
544 // CodeActionOptions is only valid if the client supports action literal
545 // via textDocument.codeAction.codeActionLiteralSupport.
546 llvm::json::Value CodeActionProvider = true;
547 if (Params.capabilities.CodeActionStructure)
548 CodeActionProvider = llvm::json::Object{
549 {"codeActionKinds",
550 {CodeAction::QUICKFIX_KIND, CodeAction::REFACTOR_KIND,
551 CodeAction::INFO_KIND}}};
552
Sam McCalla69698f2019-03-27 17:47:49 +0000553 llvm::json::Object Result{
Sam McCall6f7dca92020-03-03 12:25:46 +0100554 {{"serverInfo",
555 llvm::json::Object{{"name", "clangd"},
556 {"version", getClangToolFullVersion("clangd")}}},
557 {"capabilities",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000558 llvm::json::Object{
Sam McCall596b63a2020-04-10 03:27:37 +0200559 {"textDocumentSync",
560 llvm::json::Object{
561 {"openClose", true},
562 {"change", (int)TextDocumentSyncKind::Incremental},
563 {"save", true},
564 }},
Sam McCall0930ab02017-11-07 15:49:35 +0000565 {"documentFormattingProvider", true},
566 {"documentRangeFormattingProvider", true},
567 {"documentOnTypeFormattingProvider",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000568 llvm::json::Object{
Sam McCall25c62572019-06-10 14:26:21 +0000569 {"firstTriggerCharacter", "\n"},
Sam McCall0930ab02017-11-07 15:49:35 +0000570 {"moreTriggerCharacter", {}},
571 }},
Haojian Wu08d93f12019-08-22 14:53:45 +0000572 {"codeActionProvider", std::move(CodeActionProvider)},
Sam McCall0930ab02017-11-07 15:49:35 +0000573 {"completionProvider",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000574 llvm::json::Object{
Kirill Bobyrev9d11e672020-08-26 17:08:00 +0200575 {"allCommitCharacters",
576 {" ", "\t", "(", ")", "[", "]", "{", "}", "<",
577 ">", ":", ";", ",", "+", "-", "/", "*", "%",
578 "^", "&", "#", "?", ".", "=", "\"", "'", "|"}},
Sam McCall0930ab02017-11-07 15:49:35 +0000579 {"resolveProvider", false},
Sam McCall032727f2020-05-06 01:39:59 +0200580 // We do extra checks, e.g. that > is part of ->.
581 {"triggerCharacters", {".", "<", ">", ":", "\"", "/"}},
Sam McCall0930ab02017-11-07 15:49:35 +0000582 }},
Sam McCall71177ac2020-03-24 02:24:47 +0100583 {"semanticTokensProvider",
584 llvm::json::Object{
Sam McCall5fea54b2020-07-10 16:08:14 +0200585 {"full", llvm::json::Object{{"delta", true}}},
586 {"range", false},
Sam McCall71177ac2020-03-24 02:24:47 +0100587 {"legend",
588 llvm::json::Object{{"tokenTypes", semanticTokenTypes()},
589 {"tokenModifiers", llvm::json::Array()}}},
590 }},
Sam McCall0930ab02017-11-07 15:49:35 +0000591 {"signatureHelpProvider",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000592 llvm::json::Object{
Sam McCall0930ab02017-11-07 15:49:35 +0000593 {"triggerCharacters", {"(", ","}},
594 }},
Sam McCall866ba2c2019-02-01 11:26:13 +0000595 {"declarationProvider", true},
Sam McCall0930ab02017-11-07 15:49:35 +0000596 {"definitionProvider", true},
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000597 {"documentHighlightProvider", true},
Sam McCall8d7ecc12019-12-16 19:08:51 +0100598 {"documentLinkProvider",
599 llvm::json::Object{
600 {"resolveProvider", false},
601 }},
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000602 {"hoverProvider", true},
Haojian Wuf429ab62019-07-24 07:49:23 +0000603 {"renameProvider", std::move(RenameProvider)},
Utkarsh Saxena55925da2019-09-24 13:38:33 +0000604 {"selectionRangeProvider", true},
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000605 {"documentSymbolProvider", true},
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000606 {"workspaceSymbolProvider", true},
Sam McCall1ad142f2018-09-05 11:53:07 +0000607 {"referencesProvider", true},
Sam McCall0930ab02017-11-07 15:49:35 +0000608 {"executeCommandProvider",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000609 llvm::json::Object{
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000610 {"commands",
611 {ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND,
612 ExecuteCommandParams::CLANGD_APPLY_TWEAK}},
Sam McCall0930ab02017-11-07 15:49:35 +0000613 }},
Kadir Cetinkaya86658022019-03-19 09:27:04 +0000614 {"typeHierarchyProvider", true},
Sam McCalla69698f2019-03-27 17:47:49 +0000615 }}}};
Sam McCall6342b382020-09-30 10:56:43 +0200616 if (Opts.Encoding)
617 Result["offsetEncoding"] = *Opts.Encoding;
Sam McCall7ba07792020-09-29 10:37:46 +0200618 if (Opts.TheiaSemanticHighlighting)
Johan Vikstroma848dab2019-07-04 07:53:12 +0000619 Result.getObject("capabilities")
620 ->insert(
621 {"semanticHighlighting",
Haojian Wu1ca2ee42019-07-04 12:27:21 +0000622 llvm::json::Object{{"scopes", buildHighlightScopeLookupTable()}}});
Sam McCall7ba07792020-09-29 10:37:46 +0200623 if (Opts.FoldingRanges)
Kirill Bobyrev7a514c92020-07-14 09:28:38 +0200624 Result.getObject("capabilities")->insert({"foldingRangeProvider", true});
Sam McCalla69698f2019-03-27 17:47:49 +0000625 Reply(std::move(Result));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000626}
627
Sam McCall8a2d2942020-03-03 12:12:14 +0100628void ClangdLSPServer::onInitialized(const InitializedParams &Params) {}
629
Sam McCall2c30fbc2018-10-18 12:32:04 +0000630void ClangdLSPServer::onShutdown(const ShutdownParams &Params,
631 Callback<std::nullptr_t> Reply) {
Ilya Biryukov0d9b8a32017-10-25 08:45:41 +0000632 // Do essentially nothing, just say we're ready to exit.
633 ShutdownRequestReceived = true;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000634 Reply(nullptr);
Sam McCall8a5dded2017-10-12 13:29:58 +0000635}
Ilya Biryukovafb55542017-05-16 14:40:30 +0000636
Sam McCall422c8282018-11-26 16:00:11 +0000637// sync is a clangd extension: it blocks until all background work completes.
638// It blocks the calling thread, so no messages are processed until it returns!
639void ClangdLSPServer::onSync(const NoParams &Params,
640 Callback<std::nullptr_t> Reply) {
641 if (Server->blockUntilIdleForTest(/*TimeoutSeconds=*/60))
642 Reply(nullptr);
643 else
Sam McCall30667c92020-07-08 21:49:38 +0200644 Reply(error("Not idle after a minute"));
Sam McCall422c8282018-11-26 16:00:11 +0000645}
646
Sam McCall2c30fbc2018-10-18 12:32:04 +0000647void ClangdLSPServer::onDocumentDidOpen(
648 const DidOpenTextDocumentParams &Params) {
Simon Marchi9569fd52018-03-16 14:30:42 +0000649 PathRef File = Params.textDocument.uri.file();
Ilya Biryukovb10ef472018-06-13 09:20:41 +0000650
Sam McCall2c30fbc2018-10-18 12:32:04 +0000651 const std::string &Contents = Params.textDocument.text;
Simon Marchi9569fd52018-03-16 14:30:42 +0000652
Sam McCall2cd33e62020-03-04 00:33:29 +0100653 auto Version = DraftMgr.addDraft(File, Params.textDocument.version, Contents);
654 Server->addDocument(File, Contents, encodeVersion(Version),
655 WantDiagnostics::Yes);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000656}
657
Sam McCall2c30fbc2018-10-18 12:32:04 +0000658void ClangdLSPServer::onDocumentDidChange(
659 const DidChangeTextDocumentParams &Params) {
Eric Liu51fed182018-02-22 18:40:39 +0000660 auto WantDiags = WantDiagnostics::Auto;
661 if (Params.wantDiagnostics.hasValue())
662 WantDiags = Params.wantDiagnostics.getValue() ? WantDiagnostics::Yes
663 : WantDiagnostics::No;
Simon Marchi9569fd52018-03-16 14:30:42 +0000664
665 PathRef File = Params.textDocument.uri.file();
Sam McCallcaf5a4d2020-03-03 15:57:39 +0100666 llvm::Expected<DraftStore::Draft> Draft = DraftMgr.updateDraft(
667 File, Params.textDocument.version, Params.contentChanges);
668 if (!Draft) {
Simon Marchi98082622018-03-26 14:41:40 +0000669 // If this fails, we are most likely going to be not in sync anymore with
670 // the client. It is better to remove the draft and let further operations
671 // fail rather than giving wrong results.
672 DraftMgr.removeDraft(File);
Ilya Biryukov652364b2018-09-26 05:48:29 +0000673 Server->removeDocument(File);
Sam McCallcaf5a4d2020-03-03 15:57:39 +0100674 elog("Failed to update {0}: {1}", File, Draft.takeError());
Simon Marchi98082622018-03-26 14:41:40 +0000675 return;
676 }
Simon Marchi9569fd52018-03-16 14:30:42 +0000677
Sam McCall2cd33e62020-03-04 00:33:29 +0100678 Server->addDocument(File, Draft->Contents, encodeVersion(Draft->Version),
679 WantDiags, Params.forceRebuild);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000680}
681
Sam McCall596b63a2020-04-10 03:27:37 +0200682void ClangdLSPServer::onDocumentDidSave(
683 const DidSaveTextDocumentParams &Params) {
684 reparseOpenFilesIfNeeded([](llvm::StringRef) { return true; });
685}
686
Sam McCall2c30fbc2018-10-18 12:32:04 +0000687void ClangdLSPServer::onFileEvent(const DidChangeWatchedFilesParams &Params) {
Sam McCall596b63a2020-04-10 03:27:37 +0200688 // We could also reparse all open files here. However:
689 // - this could be frequent, and revalidating all the preambles isn't free
690 // - this is useful e.g. when switching git branches, but we're likely to see
691 // fresh headers but still have the old-branch main-file content
Ilya Biryukov652364b2018-09-26 05:48:29 +0000692 Server->onFileEvent(Params);
Marc-Andre Laperlebf114242017-10-02 18:00:37 +0000693}
694
Sam McCall2c30fbc2018-10-18 12:32:04 +0000695void ClangdLSPServer::onCommand(const ExecuteCommandParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000696 Callback<llvm::json::Value> Reply) {
Ilya Biryukov12864002019-08-16 12:46:41 +0000697 auto ApplyEdit = [this](WorkspaceEdit WE, std::string SuccessMessage,
698 decltype(Reply) Reply) {
Eric Liuc5105f92018-02-16 14:15:55 +0000699 ApplyWorkspaceEditParams Edit;
700 Edit.edit = std::move(WE);
Ilya Biryukov12864002019-08-16 12:46:41 +0000701 call<ApplyWorkspaceEditResponse>(
702 "workspace/applyEdit", std::move(Edit),
703 [Reply = std::move(Reply), SuccessMessage = std::move(SuccessMessage)](
704 llvm::Expected<ApplyWorkspaceEditResponse> Response) mutable {
705 if (!Response)
706 return Reply(Response.takeError());
707 if (!Response->applied) {
708 std::string Reason = Response->failureReason
709 ? *Response->failureReason
710 : "unknown reason";
Sam McCall30667c92020-07-08 21:49:38 +0200711 return Reply(error("edits were not applied: {0}", Reason));
Ilya Biryukov12864002019-08-16 12:46:41 +0000712 }
713 return Reply(SuccessMessage);
714 });
Eric Liuc5105f92018-02-16 14:15:55 +0000715 };
Ilya Biryukov12864002019-08-16 12:46:41 +0000716
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000717 if (Params.command == ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND &&
718 Params.workspaceEdit) {
719 // The flow for "apply-fix" :
720 // 1. We publish a diagnostic, including fixits
721 // 2. The user clicks on the diagnostic, the editor asks us for code actions
722 // 3. We send code actions, with the fixit embedded as context
723 // 4. The user selects the fixit, the editor asks us to apply it
724 // 5. We unwrap the changes and send them back to the editor
Haojian Wuf2516342019-08-05 12:48:09 +0000725 // 6. The editor applies the changes (applyEdit), and sends us a reply
726 // 7. We unwrap the reply and send a reply to the editor.
Ilya Biryukov12864002019-08-16 12:46:41 +0000727 ApplyEdit(*Params.workspaceEdit, "Fix applied.", std::move(Reply));
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000728 } else if (Params.command == ExecuteCommandParams::CLANGD_APPLY_TWEAK &&
729 Params.tweakArgs) {
730 auto Code = DraftMgr.getDraft(Params.tweakArgs->file.file());
731 if (!Code)
Sam McCall30667c92020-07-08 21:49:38 +0200732 return Reply(error("trying to apply a code action for a non-added file"));
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000733
Ilya Biryukov12864002019-08-16 12:46:41 +0000734 auto Action = [this, ApplyEdit, Reply = std::move(Reply),
735 File = Params.tweakArgs->file, Code = std::move(*Code)](
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000736 llvm::Expected<Tweak::Effect> R) mutable {
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000737 if (!R)
738 return Reply(R.takeError());
739
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000740 assert(R->ShowMessage ||
741 (!R->ApplyEdits.empty() && "tweak has no effect"));
Ilya Biryukov12864002019-08-16 12:46:41 +0000742
Sam McCall395fde72019-06-18 13:37:54 +0000743 if (R->ShowMessage) {
744 ShowMessageParams Msg;
745 Msg.message = *R->ShowMessage;
746 Msg.type = MessageType::Info;
747 notify("window/showMessage", Msg);
748 }
Ilya Biryukov12864002019-08-16 12:46:41 +0000749 // When no edit is specified, make sure we Reply().
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000750 if (R->ApplyEdits.empty())
751 return Reply("Tweak applied.");
752
Haojian Wu852bafa2019-10-23 14:40:20 +0200753 if (auto Err = validateEdits(DraftMgr, R->ApplyEdits))
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000754 return Reply(std::move(Err));
755
756 WorkspaceEdit WE;
757 WE.changes.emplace();
758 for (const auto &It : R->ApplyEdits) {
Kadir Cetinkayae95e5162019-10-02 09:12:01 +0000759 (*WE.changes)[URI::createFile(It.first()).toString()] =
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000760 It.second.asTextEdits();
761 }
762 // ApplyEdit will take care of calling Reply().
763 return ApplyEdit(std::move(WE), "Tweak applied.", std::move(Reply));
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000764 };
765 Server->applyTweak(Params.tweakArgs->file.file(),
766 Params.tweakArgs->selection, Params.tweakArgs->tweakID,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000767 std::move(Action));
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000768 } else {
769 // We should not get here because ExecuteCommandParams would not have
770 // parsed in the first place and this handler should not be called. But if
771 // more commands are added, this will be here has a safe guard.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000772 Reply(llvm::make_error<LSPError>(
773 llvm::formatv("Unsupported command \"{0}\".", Params.command).str(),
Sam McCall2c30fbc2018-10-18 12:32:04 +0000774 ErrorCode::InvalidParams));
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000775 }
776}
777
Sam McCall2c30fbc2018-10-18 12:32:04 +0000778void ClangdLSPServer::onWorkspaceSymbol(
779 const WorkspaceSymbolParams &Params,
780 Callback<std::vector<SymbolInformation>> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000781 Server->workspaceSymbols(
Sam McCall7ba07792020-09-29 10:37:46 +0200782 Params.query, Opts.CodeComplete.Limit,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000783 [Reply = std::move(Reply),
784 this](llvm::Expected<std::vector<SymbolInformation>> Items) mutable {
785 if (!Items)
786 return Reply(Items.takeError());
787 for (auto &Sym : *Items)
788 Sym.kind = adjustKindToCapability(Sym.kind, SupportedSymbolKinds);
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000789
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000790 Reply(std::move(*Items));
791 });
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000792}
793
Haojian Wuf429ab62019-07-24 07:49:23 +0000794void ClangdLSPServer::onPrepareRename(const TextDocumentPositionParams &Params,
795 Callback<llvm::Optional<Range>> Reply) {
Haojian Wu0f0cbcc2020-10-02 16:01:25 +0200796 Server->prepareRename(
Haojian Wu9c09e202020-10-07 21:16:45 +0200797 Params.textDocument.uri.file(), Params.position, /*NewName*/ llvm::None,
798 Opts.Rename,
Haojian Wu0f0cbcc2020-10-02 16:01:25 +0200799 [Reply = std::move(Reply)](llvm::Expected<RenameResult> Result) mutable {
800 if (!Result)
801 return Reply(Result.takeError());
802 return Reply(std::move(Result->Target));
803 });
Haojian Wuf429ab62019-07-24 07:49:23 +0000804}
805
Sam McCall2c30fbc2018-10-18 12:32:04 +0000806void ClangdLSPServer::onRename(const RenameParams &Params,
807 Callback<WorkspaceEdit> Reply) {
Benjamin Krameradcd0262020-01-28 20:23:46 +0100808 Path File = std::string(Params.textDocument.uri.file());
Sam McCallcaf5a4d2020-03-03 15:57:39 +0100809 if (!DraftMgr.getDraft(File))
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000810 return Reply(llvm::make_error<LSPError>(
811 "onRename called for non-added file", ErrorCode::InvalidParams));
Haojian Wu852bafa2019-10-23 14:40:20 +0200812 Server->rename(
Sam McCall7ba07792020-09-29 10:37:46 +0200813 File, Params.position, Params.newName, Opts.Rename,
Haojian Wu852bafa2019-10-23 14:40:20 +0200814 [File, Params, Reply = std::move(Reply),
Haojian Wu0f0cbcc2020-10-02 16:01:25 +0200815 this](llvm::Expected<RenameResult> R) mutable {
816 if (!R)
817 return Reply(R.takeError());
818 if (auto Err = validateEdits(DraftMgr, R->GlobalChanges))
Haojian Wu852bafa2019-10-23 14:40:20 +0200819 return Reply(std::move(Err));
820 WorkspaceEdit Result;
821 Result.changes.emplace();
Haojian Wu0f0cbcc2020-10-02 16:01:25 +0200822 for (const auto &Rep : R->GlobalChanges) {
Haojian Wu852bafa2019-10-23 14:40:20 +0200823 (*Result.changes)[URI::createFile(Rep.first()).toString()] =
824 Rep.second.asTextEdits();
825 }
826 Reply(Result);
827 });
Haojian Wu345099c2017-11-09 11:30:04 +0000828}
829
Sam McCall2c30fbc2018-10-18 12:32:04 +0000830void ClangdLSPServer::onDocumentDidClose(
831 const DidCloseTextDocumentParams &Params) {
Simon Marchi9569fd52018-03-16 14:30:42 +0000832 PathRef File = Params.textDocument.uri.file();
833 DraftMgr.removeDraft(File);
Ilya Biryukov652364b2018-09-26 05:48:29 +0000834 Server->removeDocument(File);
Ilya Biryukov49c10712019-03-25 10:15:11 +0000835
836 {
837 std::lock_guard<std::mutex> Lock(FixItsMutex);
838 FixItsMap.erase(File);
839 }
Johan Vikstromc2653ef22019-08-01 08:08:44 +0000840 {
841 std::lock_guard<std::mutex> HLock(HighlightingsMutex);
842 FileToHighlightings.erase(File);
843 }
Sam McCall9e3063e2020-04-01 16:21:44 +0200844 {
845 std::lock_guard<std::mutex> HLock(SemanticTokensMutex);
846 LastSemanticTokens.erase(File);
847 }
Ilya Biryukov49c10712019-03-25 10:15:11 +0000848 // clangd will not send updates for this file anymore, so we empty out the
849 // list of diagnostics shown on the client (e.g. in the "Problems" pane of
850 // VSCode). Note that this cannot race with actual diagnostics responses
851 // because removeDocument() guarantees no diagnostic callbacks will be
852 // executed after it returns.
Sam McCall6525a6b2020-03-03 12:44:40 +0100853 PublishDiagnosticsParams Notification;
854 Notification.uri = URIForFile::canonicalize(File, /*TUPath=*/File);
855 publishDiagnostics(Notification);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000856}
857
Sam McCall4db732a2017-09-30 10:08:52 +0000858void ClangdLSPServer::onDocumentOnTypeFormatting(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000859 const DocumentOnTypeFormattingParams &Params,
860 Callback<std::vector<TextEdit>> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000861 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000862 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000863 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000864 return Reply(llvm::make_error<LSPError>(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000865 "onDocumentOnTypeFormatting called for non-added file",
866 ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000867
Sam McCallffa63dd2020-06-26 12:57:29 +0200868 Server->formatOnType(File, Code->Contents, Params.position, Params.ch,
869 std::move(Reply));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000870}
871
Sam McCall4db732a2017-09-30 10:08:52 +0000872void ClangdLSPServer::onDocumentRangeFormatting(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000873 const DocumentRangeFormattingParams &Params,
874 Callback<std::vector<TextEdit>> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000875 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000876 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000877 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000878 return Reply(llvm::make_error<LSPError>(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000879 "onDocumentRangeFormatting called for non-added file",
880 ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000881
Sam McCallffa63dd2020-06-26 12:57:29 +0200882 Server->formatRange(
883 File, Code->Contents, Params.range,
884 [Code = Code->Contents, Reply = std::move(Reply)](
885 llvm::Expected<tooling::Replacements> Result) mutable {
886 if (Result)
887 Reply(replacementsToEdits(Code, Result.get()));
888 else
889 Reply(Result.takeError());
890 });
Ilya Biryukovafb55542017-05-16 14:40:30 +0000891}
892
Sam McCall2c30fbc2018-10-18 12:32:04 +0000893void ClangdLSPServer::onDocumentFormatting(
894 const DocumentFormattingParams &Params,
895 Callback<std::vector<TextEdit>> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000896 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000897 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000898 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000899 return Reply(llvm::make_error<LSPError>(
900 "onDocumentFormatting called for non-added file",
901 ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000902
Sam McCallffa63dd2020-06-26 12:57:29 +0200903 Server->formatFile(File, Code->Contents,
904 [Code = Code->Contents, Reply = std::move(Reply)](
905 llvm::Expected<tooling::Replacements> Result) mutable {
906 if (Result)
907 Reply(replacementsToEdits(Code, Result.get()));
908 else
909 Reply(Result.takeError());
910 });
Sam McCall4db732a2017-09-30 10:08:52 +0000911}
912
Ilya Biryukov19d75602018-11-23 15:21:19 +0000913/// The functions constructs a flattened view of the DocumentSymbol hierarchy.
914/// Used by the clients that do not support the hierarchical view.
915static std::vector<SymbolInformation>
916flattenSymbolHierarchy(llvm::ArrayRef<DocumentSymbol> Symbols,
917 const URIForFile &FileURI) {
Ilya Biryukov19d75602018-11-23 15:21:19 +0000918 std::vector<SymbolInformation> Results;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000919 std::function<void(const DocumentSymbol &, llvm::StringRef)> Process =
920 [&](const DocumentSymbol &S, llvm::Optional<llvm::StringRef> ParentName) {
Ilya Biryukov19d75602018-11-23 15:21:19 +0000921 SymbolInformation SI;
Benjamin Krameradcd0262020-01-28 20:23:46 +0100922 SI.containerName = std::string(ParentName ? "" : *ParentName);
Ilya Biryukov19d75602018-11-23 15:21:19 +0000923 SI.name = S.name;
924 SI.kind = S.kind;
925 SI.location.range = S.range;
926 SI.location.uri = FileURI;
927
928 Results.push_back(std::move(SI));
929 std::string FullName =
930 !ParentName ? S.name : (ParentName->str() + "::" + S.name);
931 for (auto &C : S.children)
932 Process(C, /*ParentName=*/FullName);
933 };
934 for (auto &S : Symbols)
935 Process(S, /*ParentName=*/"");
936 return Results;
937}
938
939void ClangdLSPServer::onDocumentSymbol(const DocumentSymbolParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000940 Callback<llvm::json::Value> Reply) {
Ilya Biryukov19d75602018-11-23 15:21:19 +0000941 URIForFile FileURI = Params.textDocument.uri;
Ilya Biryukov652364b2018-09-26 05:48:29 +0000942 Server->documentSymbols(
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000943 Params.textDocument.uri.file(),
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000944 [this, FileURI, Reply = std::move(Reply)](
945 llvm::Expected<std::vector<DocumentSymbol>> Items) mutable {
946 if (!Items)
947 return Reply(Items.takeError());
948 adjustSymbolKinds(*Items, SupportedSymbolKinds);
949 if (SupportsHierarchicalDocumentSymbol)
950 return Reply(std::move(*Items));
951 else
952 return Reply(flattenSymbolHierarchy(*Items, FileURI));
953 });
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000954}
955
Kirill Bobyrev7a514c92020-07-14 09:28:38 +0200956void ClangdLSPServer::onFoldingRange(
957 const FoldingRangeParams &Params,
958 Callback<std::vector<FoldingRange>> Reply) {
959 Server->foldingRanges(Params.textDocument.uri.file(), std::move(Reply));
960}
961
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000962static llvm::Optional<Command> asCommand(const CodeAction &Action) {
Sam McCall20841d42018-10-16 16:29:41 +0000963 Command Cmd;
964 if (Action.command && Action.edit)
Sam McCallc008af62018-10-20 15:30:37 +0000965 return None; // Not representable. (We never emit these anyway).
Sam McCall20841d42018-10-16 16:29:41 +0000966 if (Action.command) {
967 Cmd = *Action.command;
968 } else if (Action.edit) {
Benjamin Krameradcd0262020-01-28 20:23:46 +0100969 Cmd.command = std::string(Command::CLANGD_APPLY_FIX_COMMAND);
Sam McCall20841d42018-10-16 16:29:41 +0000970 Cmd.workspaceEdit = *Action.edit;
971 } else {
Sam McCallc008af62018-10-20 15:30:37 +0000972 return None;
Sam McCall20841d42018-10-16 16:29:41 +0000973 }
974 Cmd.title = Action.title;
975 if (Action.kind && *Action.kind == CodeAction::QUICKFIX_KIND)
976 Cmd.title = "Apply fix: " + Cmd.title;
977 return Cmd;
978}
979
Sam McCall2c30fbc2018-10-18 12:32:04 +0000980void ClangdLSPServer::onCodeAction(const CodeActionParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000981 Callback<llvm::json::Value> Reply) {
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000982 URIForFile File = Params.textDocument.uri;
983 auto Code = DraftMgr.getDraft(File.file());
Sam McCall2c30fbc2018-10-18 12:32:04 +0000984 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000985 return Reply(llvm::make_error<LSPError>(
986 "onCodeAction called for non-added file", ErrorCode::InvalidParams));
Sam McCall20841d42018-10-16 16:29:41 +0000987 // We provide a code action for Fixes on the specified diagnostics.
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000988 std::vector<CodeAction> FixIts;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000989 for (const Diagnostic &D : Params.context.diagnostics) {
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000990 for (auto &F : getFixes(File.file(), D)) {
991 FixIts.push_back(toCodeAction(F, Params.textDocument.uri));
992 FixIts.back().diagnostics = {D};
Sam McCalldd0566b2017-11-06 15:40:30 +0000993 }
Ilya Biryukovafb55542017-05-16 14:40:30 +0000994 }
Sam McCall20841d42018-10-16 16:29:41 +0000995
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000996 // Now enumerate the semantic code actions.
997 auto ConsumeActions =
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000998 [Reply = std::move(Reply), File, Code = std::move(*Code),
999 Selection = Params.range, FixIts = std::move(FixIts), this](
1000 llvm::Expected<std::vector<ClangdServer::TweakRef>> Tweaks) mutable {
Ilya Biryukovc6ed7782019-01-30 14:24:17 +00001001 if (!Tweaks)
1002 return Reply(Tweaks.takeError());
Ilya Biryukovcce67a32019-01-29 14:17:36 +00001003
1004 std::vector<CodeAction> Actions = std::move(FixIts);
1005 Actions.reserve(Actions.size() + Tweaks->size());
1006 for (const auto &T : *Tweaks)
1007 Actions.push_back(toCodeAction(T, File, Selection));
1008
Sam McCall83926852020-09-29 16:28:50 +02001009 // If there's exactly one quick-fix, call it "preferred".
1010 // We never consider refactorings etc as preferred.
1011 CodeAction *OnlyFix = nullptr;
1012 for (auto &Action : Actions) {
1013 if (Action.kind && *Action.kind == CodeAction::QUICKFIX_KIND) {
1014 if (OnlyFix) {
1015 OnlyFix->isPreferred = false;
1016 break;
1017 }
1018 Action.isPreferred = true;
1019 OnlyFix = &Action;
1020 }
1021 }
1022
Ilya Biryukovcce67a32019-01-29 14:17:36 +00001023 if (SupportsCodeAction)
1024 return Reply(llvm::json::Array(Actions));
1025 std::vector<Command> Commands;
1026 for (const auto &Action : Actions) {
1027 if (auto Command = asCommand(Action))
1028 Commands.push_back(std::move(*Command));
1029 }
1030 return Reply(llvm::json::Array(Commands));
1031 };
1032
Sam McCall7530b252020-10-02 11:34:40 +02001033 Server->enumerateTweaks(
1034 File.file(), Params.range,
1035 [&](const Tweak &T) {
1036 if (!Opts.TweakFilter(T))
1037 return false;
1038 // FIXME: also consider CodeActionContext.only
1039 return true;
1040 },
1041 std::move(ConsumeActions));
Ilya Biryukovafb55542017-05-16 14:40:30 +00001042}
1043
Ilya Biryukovb0826bd2019-01-03 13:37:12 +00001044void ClangdLSPServer::onCompletion(const CompletionParams &Params,
Sam McCall2c30fbc2018-10-18 12:32:04 +00001045 Callback<CompletionList> Reply) {
Ilya Biryukova7a11472019-06-07 16:24:38 +00001046 if (!shouldRunCompletion(Params)) {
1047 // Clients sometimes auto-trigger completions in undesired places (e.g.
1048 // 'a >^ '), we return empty results in those cases.
1049 vlog("ignored auto-triggered completion, preceding char did not match");
1050 return Reply(CompletionList());
1051 }
Sam McCall7ba07792020-09-29 10:37:46 +02001052 Server->codeComplete(Params.textDocument.uri.file(), Params.position,
1053 Opts.CodeComplete,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001054 [Reply = std::move(Reply),
1055 this](llvm::Expected<CodeCompleteResult> List) mutable {
1056 if (!List)
1057 return Reply(List.takeError());
1058 CompletionList LSPList;
1059 LSPList.isIncomplete = List->HasMore;
1060 for (const auto &R : List->Completions) {
Sam McCall7ba07792020-09-29 10:37:46 +02001061 CompletionItem C = R.render(Opts.CodeComplete);
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001062 C.kind = adjustKindToCapability(
1063 C.kind, SupportedCompletionItemKinds);
1064 LSPList.items.push_back(std::move(C));
1065 }
1066 return Reply(std::move(LSPList));
1067 });
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +00001068}
1069
Sam McCall2c30fbc2018-10-18 12:32:04 +00001070void ClangdLSPServer::onSignatureHelp(const TextDocumentPositionParams &Params,
1071 Callback<SignatureHelp> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +00001072 Server->signatureHelp(Params.textDocument.uri.file(), Params.position,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001073 [Reply = std::move(Reply), this](
1074 llvm::Expected<SignatureHelp> Signature) mutable {
1075 if (!Signature)
1076 return Reply(Signature.takeError());
1077 if (SupportsOffsetsInSignatureHelp)
1078 return Reply(std::move(*Signature));
1079 // Strip out the offsets from signature help for
1080 // clients that only support string labels.
1081 for (auto &SigInfo : Signature->signatures) {
1082 for (auto &Param : SigInfo.parameters)
1083 Param.labelOffsets.reset();
1084 }
1085 return Reply(std::move(*Signature));
1086 });
Ilya Biryukov652364b2018-09-26 05:48:29 +00001087}
1088
Sam McCall0dbab7f2019-02-02 05:56:00 +00001089// Go to definition has a toggle function: if def and decl are distinct, then
1090// the first press gives you the def, the second gives you the matching def.
1091// getToggle() returns the counterpart location that under the cursor.
1092//
1093// We return the toggled location alone (ignoring other symbols) to encourage
1094// editors to "bounce" quickly between locations, without showing a menu.
1095static Location *getToggle(const TextDocumentPositionParams &Point,
1096 LocatedSymbol &Sym) {
1097 // Toggle only makes sense with two distinct locations.
1098 if (!Sym.Definition || *Sym.Definition == Sym.PreferredDeclaration)
1099 return nullptr;
1100 if (Sym.Definition->uri.file() == Point.textDocument.uri.file() &&
1101 Sym.Definition->range.contains(Point.position))
1102 return &Sym.PreferredDeclaration;
1103 if (Sym.PreferredDeclaration.uri.file() == Point.textDocument.uri.file() &&
1104 Sym.PreferredDeclaration.range.contains(Point.position))
1105 return &*Sym.Definition;
1106 return nullptr;
1107}
1108
Sam McCall2c30fbc2018-10-18 12:32:04 +00001109void ClangdLSPServer::onGoToDefinition(const TextDocumentPositionParams &Params,
1110 Callback<std::vector<Location>> Reply) {
Sam McCall866ba2c2019-02-01 11:26:13 +00001111 Server->locateSymbolAt(
1112 Params.textDocument.uri.file(), Params.position,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001113 [Params, Reply = std::move(Reply)](
1114 llvm::Expected<std::vector<LocatedSymbol>> Symbols) mutable {
1115 if (!Symbols)
1116 return Reply(Symbols.takeError());
1117 std::vector<Location> Defs;
1118 for (auto &S : *Symbols) {
1119 if (Location *Toggle = getToggle(Params, S))
1120 return Reply(std::vector<Location>{std::move(*Toggle)});
1121 Defs.push_back(S.Definition.getValueOr(S.PreferredDeclaration));
1122 }
1123 Reply(std::move(Defs));
1124 });
Sam McCall866ba2c2019-02-01 11:26:13 +00001125}
1126
1127void ClangdLSPServer::onGoToDeclaration(
1128 const TextDocumentPositionParams &Params,
1129 Callback<std::vector<Location>> Reply) {
1130 Server->locateSymbolAt(
1131 Params.textDocument.uri.file(), Params.position,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001132 [Params, Reply = std::move(Reply)](
1133 llvm::Expected<std::vector<LocatedSymbol>> Symbols) mutable {
1134 if (!Symbols)
1135 return Reply(Symbols.takeError());
1136 std::vector<Location> Decls;
1137 for (auto &S : *Symbols) {
1138 if (Location *Toggle = getToggle(Params, S))
1139 return Reply(std::vector<Location>{std::move(*Toggle)});
1140 Decls.push_back(std::move(S.PreferredDeclaration));
1141 }
1142 Reply(std::move(Decls));
1143 });
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +00001144}
1145
Sam McCall111fe842019-05-07 07:55:35 +00001146void ClangdLSPServer::onSwitchSourceHeader(
1147 const TextDocumentIdentifier &Params,
Sam McCallb9ec3e92019-05-07 08:30:32 +00001148 Callback<llvm::Optional<URIForFile>> Reply) {
Haojian Wud6d5edd2019-10-01 10:21:15 +00001149 Server->switchSourceHeader(
1150 Params.uri.file(),
1151 [Reply = std::move(Reply),
1152 Params](llvm::Expected<llvm::Optional<clangd::Path>> Path) mutable {
1153 if (!Path)
1154 return Reply(Path.takeError());
1155 if (*Path)
Haojian Wu77c97002019-10-07 11:37:25 +00001156 return Reply(URIForFile::canonicalize(**Path, Params.uri.file()));
Haojian Wud6d5edd2019-10-01 10:21:15 +00001157 return Reply(llvm::None);
1158 });
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +00001159}
1160
Sam McCall2c30fbc2018-10-18 12:32:04 +00001161void ClangdLSPServer::onDocumentHighlight(
1162 const TextDocumentPositionParams &Params,
1163 Callback<std::vector<DocumentHighlight>> Reply) {
1164 Server->findDocumentHighlights(Params.textDocument.uri.file(),
1165 Params.position, std::move(Reply));
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +00001166}
1167
Sam McCall2c30fbc2018-10-18 12:32:04 +00001168void ClangdLSPServer::onHover(const TextDocumentPositionParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001169 Callback<llvm::Optional<Hover>> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +00001170 Server->findHover(Params.textDocument.uri.file(), Params.position,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001171 [Reply = std::move(Reply), this](
1172 llvm::Expected<llvm::Optional<HoverInfo>> H) mutable {
1173 if (!H)
1174 return Reply(H.takeError());
1175 if (!*H)
1176 return Reply(llvm::None);
Ilya Biryukovf9169d02019-05-29 10:01:00 +00001177
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001178 Hover R;
1179 R.contents.kind = HoverContentFormat;
1180 R.range = (*H)->SymRange;
1181 switch (HoverContentFormat) {
1182 case MarkupKind::PlainText:
Kadir Cetinkaya597c6b62019-12-10 10:28:37 +01001183 R.contents.value = (*H)->present().asPlainText();
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001184 return Reply(std::move(R));
1185 case MarkupKind::Markdown:
Kadir Cetinkaya597c6b62019-12-10 10:28:37 +01001186 R.contents.value = (*H)->present().asMarkdown();
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001187 return Reply(std::move(R));
1188 };
1189 llvm_unreachable("unhandled MarkupKind");
1190 });
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +00001191}
1192
Kadir Cetinkaya86658022019-03-19 09:27:04 +00001193void ClangdLSPServer::onTypeHierarchy(
1194 const TypeHierarchyParams &Params,
1195 Callback<Optional<TypeHierarchyItem>> Reply) {
1196 Server->typeHierarchy(Params.textDocument.uri.file(), Params.position,
1197 Params.resolve, Params.direction, std::move(Reply));
1198}
1199
Nathan Ridge087b0442019-07-13 03:24:48 +00001200void ClangdLSPServer::onResolveTypeHierarchy(
1201 const ResolveTypeHierarchyItemParams &Params,
1202 Callback<Optional<TypeHierarchyItem>> Reply) {
1203 Server->resolveTypeHierarchy(Params.item, Params.resolve, Params.direction,
1204 std::move(Reply));
1205}
1206
Simon Marchi88016782018-08-01 11:28:49 +00001207void ClangdLSPServer::applyConfiguration(
Sam McCallbc904612018-10-25 04:22:52 +00001208 const ConfigurationSettings &Settings) {
Simon Marchiabeed662018-10-16 15:55:03 +00001209 // Per-file update to the compilation database.
David Goldman60249c22020-01-13 17:01:10 -05001210 llvm::StringSet<> ModifiedFiles;
Sam McCallbc904612018-10-25 04:22:52 +00001211 for (auto &Entry : Settings.compilationDatabaseChanges) {
Sam McCallbc904612018-10-25 04:22:52 +00001212 PathRef File = Entry.first;
Sam McCallc55d09a2018-11-02 13:09:36 +00001213 auto Old = CDB->getCompileCommand(File);
1214 auto New =
1215 tooling::CompileCommand(std::move(Entry.second.workingDirectory), File,
1216 std::move(Entry.second.compilationCommand),
1217 /*Output=*/"");
Sam McCall6980edb2018-11-02 14:07:51 +00001218 if (Old != New) {
Sam McCallc55d09a2018-11-02 13:09:36 +00001219 CDB->setCompileCommand(File, std::move(New));
David Goldman60249c22020-01-13 17:01:10 -05001220 ModifiedFiles.insert(File);
Sam McCall6980edb2018-11-02 14:07:51 +00001221 }
Alex Lorenzf8087862018-08-01 17:39:29 +00001222 }
David Goldman60249c22020-01-13 17:01:10 -05001223
Sam McCall596b63a2020-04-10 03:27:37 +02001224 reparseOpenFilesIfNeeded(
1225 [&](llvm::StringRef File) { return ModifiedFiles.count(File) != 0; });
Simon Marchi5178f922018-02-22 14:00:39 +00001226}
1227
Sam McCalledf6a192020-03-24 00:31:14 +01001228void ClangdLSPServer::publishTheiaSemanticHighlighting(
1229 const TheiaSemanticHighlightingParams &Params) {
Johan Vikstroma848dab2019-07-04 07:53:12 +00001230 notify("textDocument/semanticHighlighting", Params);
1231}
1232
Ilya Biryukov49c10712019-03-25 10:15:11 +00001233void ClangdLSPServer::publishDiagnostics(
Sam McCall6525a6b2020-03-03 12:44:40 +01001234 const PublishDiagnosticsParams &Params) {
1235 notify("textDocument/publishDiagnostics", Params);
Ilya Biryukov49c10712019-03-25 10:15:11 +00001236}
1237
Simon Marchi88016782018-08-01 11:28:49 +00001238// FIXME: This function needs to be properly tested.
1239void ClangdLSPServer::onChangeConfiguration(
Sam McCall2c30fbc2018-10-18 12:32:04 +00001240 const DidChangeConfigurationParams &Params) {
Simon Marchi88016782018-08-01 11:28:49 +00001241 applyConfiguration(Params.settings);
1242}
1243
Sam McCall2c30fbc2018-10-18 12:32:04 +00001244void ClangdLSPServer::onReference(const ReferenceParams &Params,
1245 Callback<std::vector<Location>> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +00001246 Server->findReferences(Params.textDocument.uri.file(), Params.position,
Sam McCall7ba07792020-09-29 10:37:46 +02001247 Opts.CodeComplete.Limit,
Haojian Wu5181ada2019-11-18 11:35:00 +01001248 [Reply = std::move(Reply)](
1249 llvm::Expected<ReferencesResult> Refs) mutable {
1250 if (!Refs)
1251 return Reply(Refs.takeError());
1252 return Reply(std::move(Refs->References));
1253 });
Sam McCall1ad142f2018-09-05 11:53:07 +00001254}
1255
Jan Korousb4067012018-11-27 16:40:46 +00001256void ClangdLSPServer::onSymbolInfo(const TextDocumentPositionParams &Params,
1257 Callback<std::vector<SymbolDetails>> Reply) {
1258 Server->symbolInfo(Params.textDocument.uri.file(), Params.position,
1259 std::move(Reply));
1260}
1261
Utkarsh Saxena55925da2019-09-24 13:38:33 +00001262void ClangdLSPServer::onSelectionRange(
1263 const SelectionRangeParams &Params,
1264 Callback<std::vector<SelectionRange>> Reply) {
Utkarsh Saxena55925da2019-09-24 13:38:33 +00001265 Server->semanticRanges(
Sam McCall8f237f92020-03-25 00:51:50 +01001266 Params.textDocument.uri.file(), Params.positions,
Utkarsh Saxena55925da2019-09-24 13:38:33 +00001267 [Reply = std::move(Reply)](
Sam McCall8f237f92020-03-25 00:51:50 +01001268 llvm::Expected<std::vector<SelectionRange>> Ranges) mutable {
1269 if (!Ranges)
Utkarsh Saxena55925da2019-09-24 13:38:33 +00001270 return Reply(Ranges.takeError());
Sam McCall8f237f92020-03-25 00:51:50 +01001271 return Reply(std::move(*Ranges));
Utkarsh Saxena55925da2019-09-24 13:38:33 +00001272 });
1273}
1274
Sam McCall8d7ecc12019-12-16 19:08:51 +01001275void ClangdLSPServer::onDocumentLink(
1276 const DocumentLinkParams &Params,
1277 Callback<std::vector<DocumentLink>> Reply) {
1278
1279 // TODO(forster): This currently resolves all targets eagerly. This is slow,
1280 // because it blocks on the preamble/AST being built. We could respond to the
1281 // request faster by using string matching or the lexer to find the includes
1282 // and resolving the targets lazily.
1283 Server->documentLinks(
1284 Params.textDocument.uri.file(),
1285 [Reply = std::move(Reply)](
1286 llvm::Expected<std::vector<DocumentLink>> Links) mutable {
1287 if (!Links) {
1288 return Reply(Links.takeError());
1289 }
1290 return Reply(std::move(Links));
1291 });
1292}
1293
Sam McCall9e3063e2020-04-01 16:21:44 +02001294// Increment a numeric string: "" -> 1 -> 2 -> ... -> 9 -> 10 -> 11 ...
1295static void increment(std::string &S) {
1296 for (char &C : llvm::reverse(S)) {
1297 if (C != '9') {
1298 ++C;
1299 return;
1300 }
1301 C = '0';
1302 }
1303 S.insert(S.begin(), '1');
1304}
1305
Sam McCall71177ac2020-03-24 02:24:47 +01001306void ClangdLSPServer::onSemanticTokens(const SemanticTokensParams &Params,
1307 Callback<SemanticTokens> CB) {
1308 Server->semanticHighlights(
1309 Params.textDocument.uri.file(),
Sam McCall9e3063e2020-04-01 16:21:44 +02001310 [this, File(Params.textDocument.uri.file().str()), CB(std::move(CB))](
1311 llvm::Expected<std::vector<HighlightingToken>> HT) mutable {
1312 if (!HT)
1313 return CB(HT.takeError());
Sam McCall71177ac2020-03-24 02:24:47 +01001314 SemanticTokens Result;
Sam McCall9e3063e2020-04-01 16:21:44 +02001315 Result.tokens = toSemanticTokens(*HT);
1316 {
1317 std::lock_guard<std::mutex> Lock(SemanticTokensMutex);
Kadir Cetinkayae64f99c2020-04-16 23:12:09 +02001318 auto &Last = LastSemanticTokens[File];
Sam McCall9e3063e2020-04-01 16:21:44 +02001319
1320 Last.tokens = Result.tokens;
1321 increment(Last.resultId);
1322 Result.resultId = Last.resultId;
1323 }
1324 CB(std::move(Result));
1325 });
1326}
1327
Sam McCall5fea54b2020-07-10 16:08:14 +02001328void ClangdLSPServer::onSemanticTokensDelta(
1329 const SemanticTokensDeltaParams &Params,
1330 Callback<SemanticTokensOrDelta> CB) {
Sam McCall9e3063e2020-04-01 16:21:44 +02001331 Server->semanticHighlights(
1332 Params.textDocument.uri.file(),
1333 [this, PrevResultID(Params.previousResultId),
1334 File(Params.textDocument.uri.file().str()), CB(std::move(CB))](
1335 llvm::Expected<std::vector<HighlightingToken>> HT) mutable {
1336 if (!HT)
1337 return CB(HT.takeError());
1338 std::vector<SemanticToken> Toks = toSemanticTokens(*HT);
1339
Sam McCall5fea54b2020-07-10 16:08:14 +02001340 SemanticTokensOrDelta Result;
Sam McCall9e3063e2020-04-01 16:21:44 +02001341 {
1342 std::lock_guard<std::mutex> Lock(SemanticTokensMutex);
Kadir Cetinkayae64f99c2020-04-16 23:12:09 +02001343 auto &Last = LastSemanticTokens[File];
Sam McCall9e3063e2020-04-01 16:21:44 +02001344
1345 if (PrevResultID == Last.resultId) {
1346 Result.edits = diffTokens(Last.tokens, Toks);
1347 } else {
Sam McCall5fea54b2020-07-10 16:08:14 +02001348 vlog("semanticTokens/full/delta: wanted edits vs {0} but last "
1349 "result had ID {1}. Returning full token list.",
Sam McCall9e3063e2020-04-01 16:21:44 +02001350 PrevResultID, Last.resultId);
1351 Result.tokens = Toks;
1352 }
1353
1354 Last.tokens = std::move(Toks);
1355 increment(Last.resultId);
1356 Result.resultId = Last.resultId;
1357 }
1358
Sam McCall71177ac2020-03-24 02:24:47 +01001359 CB(std::move(Result));
1360 });
1361}
1362
Sam McCall7ba07792020-09-29 10:37:46 +02001363ClangdLSPServer::ClangdLSPServer(class Transport &Transp,
1364 const ThreadsafeFS &TFS,
1365 const ClangdLSPServer::Options &Opts)
Kadir Cetinkaya9d662472019-10-15 14:20:52 +00001366 : BackgroundContext(Context::current().clone()), Transp(Transp),
Sam McCall7ba07792020-09-29 10:37:46 +02001367 MsgHandler(new MessageHandler(*this)), TFS(TFS),
1368 SupportedSymbolKinds(defaultSymbolKinds()),
1369 SupportedCompletionItemKinds(defaultCompletionItemKinds()), Opts(Opts) {
Sam McCall2c30fbc2018-10-18 12:32:04 +00001370 // clang-format off
1371 MsgHandler->bind("initialize", &ClangdLSPServer::onInitialize);
Sam McCall8a2d2942020-03-03 12:12:14 +01001372 MsgHandler->bind("initialized", &ClangdLSPServer::onInitialized);
Sam McCall2c30fbc2018-10-18 12:32:04 +00001373 MsgHandler->bind("shutdown", &ClangdLSPServer::onShutdown);
Sam McCall422c8282018-11-26 16:00:11 +00001374 MsgHandler->bind("sync", &ClangdLSPServer::onSync);
Sam McCall2c30fbc2018-10-18 12:32:04 +00001375 MsgHandler->bind("textDocument/rangeFormatting", &ClangdLSPServer::onDocumentRangeFormatting);
1376 MsgHandler->bind("textDocument/onTypeFormatting", &ClangdLSPServer::onDocumentOnTypeFormatting);
1377 MsgHandler->bind("textDocument/formatting", &ClangdLSPServer::onDocumentFormatting);
1378 MsgHandler->bind("textDocument/codeAction", &ClangdLSPServer::onCodeAction);
1379 MsgHandler->bind("textDocument/completion", &ClangdLSPServer::onCompletion);
1380 MsgHandler->bind("textDocument/signatureHelp", &ClangdLSPServer::onSignatureHelp);
1381 MsgHandler->bind("textDocument/definition", &ClangdLSPServer::onGoToDefinition);
Sam McCall866ba2c2019-02-01 11:26:13 +00001382 MsgHandler->bind("textDocument/declaration", &ClangdLSPServer::onGoToDeclaration);
Sam McCall2c30fbc2018-10-18 12:32:04 +00001383 MsgHandler->bind("textDocument/references", &ClangdLSPServer::onReference);
1384 MsgHandler->bind("textDocument/switchSourceHeader", &ClangdLSPServer::onSwitchSourceHeader);
Haojian Wuf429ab62019-07-24 07:49:23 +00001385 MsgHandler->bind("textDocument/prepareRename", &ClangdLSPServer::onPrepareRename);
Sam McCall2c30fbc2018-10-18 12:32:04 +00001386 MsgHandler->bind("textDocument/rename", &ClangdLSPServer::onRename);
1387 MsgHandler->bind("textDocument/hover", &ClangdLSPServer::onHover);
1388 MsgHandler->bind("textDocument/documentSymbol", &ClangdLSPServer::onDocumentSymbol);
1389 MsgHandler->bind("workspace/executeCommand", &ClangdLSPServer::onCommand);
1390 MsgHandler->bind("textDocument/documentHighlight", &ClangdLSPServer::onDocumentHighlight);
1391 MsgHandler->bind("workspace/symbol", &ClangdLSPServer::onWorkspaceSymbol);
1392 MsgHandler->bind("textDocument/didOpen", &ClangdLSPServer::onDocumentDidOpen);
1393 MsgHandler->bind("textDocument/didClose", &ClangdLSPServer::onDocumentDidClose);
1394 MsgHandler->bind("textDocument/didChange", &ClangdLSPServer::onDocumentDidChange);
Sam McCall596b63a2020-04-10 03:27:37 +02001395 MsgHandler->bind("textDocument/didSave", &ClangdLSPServer::onDocumentDidSave);
Sam McCall2c30fbc2018-10-18 12:32:04 +00001396 MsgHandler->bind("workspace/didChangeWatchedFiles", &ClangdLSPServer::onFileEvent);
1397 MsgHandler->bind("workspace/didChangeConfiguration", &ClangdLSPServer::onChangeConfiguration);
Jan Korousb4067012018-11-27 16:40:46 +00001398 MsgHandler->bind("textDocument/symbolInfo", &ClangdLSPServer::onSymbolInfo);
Kadir Cetinkaya86658022019-03-19 09:27:04 +00001399 MsgHandler->bind("textDocument/typeHierarchy", &ClangdLSPServer::onTypeHierarchy);
Nathan Ridge087b0442019-07-13 03:24:48 +00001400 MsgHandler->bind("typeHierarchy/resolve", &ClangdLSPServer::onResolveTypeHierarchy);
Utkarsh Saxena55925da2019-09-24 13:38:33 +00001401 MsgHandler->bind("textDocument/selectionRange", &ClangdLSPServer::onSelectionRange);
Sam McCall8d7ecc12019-12-16 19:08:51 +01001402 MsgHandler->bind("textDocument/documentLink", &ClangdLSPServer::onDocumentLink);
Sam McCall5fea54b2020-07-10 16:08:14 +02001403 MsgHandler->bind("textDocument/semanticTokens/full", &ClangdLSPServer::onSemanticTokens);
1404 MsgHandler->bind("textDocument/semanticTokens/full/delta", &ClangdLSPServer::onSemanticTokensDelta);
Kirill Bobyrev7a514c92020-07-14 09:28:38 +02001405 if (Opts.FoldingRanges)
1406 MsgHandler->bind("textDocument/foldingRange", &ClangdLSPServer::onFoldingRange);
Sam McCall2c30fbc2018-10-18 12:32:04 +00001407 // clang-format on
1408}
1409
Kadir Cetinkaya6b850322020-03-17 19:08:23 +01001410ClangdLSPServer::~ClangdLSPServer() {
1411 IsBeingDestroyed = true;
Sam McCall8bda5f22019-10-23 11:11:18 +02001412 // Explicitly destroy ClangdServer first, blocking on threads it owns.
1413 // This ensures they don't access any other members.
1414 Server.reset();
1415}
Ilya Biryukov38d79772017-05-16 09:38:59 +00001416
Sam McCalldc8f3cf2018-10-17 07:32:05 +00001417bool ClangdLSPServer::run() {
Ilya Biryukovafb55542017-05-16 14:40:30 +00001418 // Run the Language Server loop.
Sam McCalldc8f3cf2018-10-17 07:32:05 +00001419 bool CleanExit = true;
Sam McCall2c30fbc2018-10-18 12:32:04 +00001420 if (auto Err = Transp.loop(*MsgHandler)) {
Sam McCalldc8f3cf2018-10-17 07:32:05 +00001421 elog("Transport error: {0}", std::move(Err));
1422 CleanExit = false;
1423 }
Ilya Biryukovafb55542017-05-16 14:40:30 +00001424
Sam McCalldc8f3cf2018-10-17 07:32:05 +00001425 return CleanExit && ShutdownRequestReceived;
Ilya Biryukov38d79772017-05-16 09:38:59 +00001426}
1427
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001428std::vector<Fix> ClangdLSPServer::getFixes(llvm::StringRef File,
Ilya Biryukov71028b82018-03-12 15:28:22 +00001429 const clangd::Diagnostic &D) {
Ilya Biryukov38d79772017-05-16 09:38:59 +00001430 std::lock_guard<std::mutex> Lock(FixItsMutex);
1431 auto DiagToFixItsIter = FixItsMap.find(File);
1432 if (DiagToFixItsIter == FixItsMap.end())
1433 return {};
1434
1435 const auto &DiagToFixItsMap = DiagToFixItsIter->second;
1436 auto FixItsIter = DiagToFixItsMap.find(D);
1437 if (FixItsIter == DiagToFixItsMap.end())
1438 return {};
1439
1440 return FixItsIter->second;
1441}
1442
Sam McCall032727f2020-05-06 01:39:59 +02001443// A completion request is sent when the user types '>' or ':', but we only
1444// want to trigger on '->' and '::'. We check the preceeding text to make
1445// sure it matches what we expected.
1446// Running the lexer here would be more robust (e.g. we can detect comments
1447// and avoid triggering completion there), but we choose to err on the side
1448// of simplicity here.
Ilya Biryukovb0826bd2019-01-03 13:37:12 +00001449bool ClangdLSPServer::shouldRunCompletion(
1450 const CompletionParams &Params) const {
Sam McCall032727f2020-05-06 01:39:59 +02001451 if (Params.context.triggerKind != CompletionTriggerKind::TriggerCharacter)
Ilya Biryukovb0826bd2019-01-03 13:37:12 +00001452 return true;
Ilya Biryukovb0826bd2019-01-03 13:37:12 +00001453 auto Code = DraftMgr.getDraft(Params.textDocument.uri.file());
1454 if (!Code)
1455 return true; // completion code will log the error for untracked doc.
Sam McCallcaf5a4d2020-03-03 15:57:39 +01001456 auto Offset = positionToOffset(Code->Contents, Params.position,
Ilya Biryukovb0826bd2019-01-03 13:37:12 +00001457 /*AllowColumnsBeyondLineLength=*/false);
1458 if (!Offset) {
1459 vlog("could not convert position '{0}' to offset for file '{1}'",
1460 Params.position, Params.textDocument.uri.file());
1461 return true;
1462 }
Sam McCall032727f2020-05-06 01:39:59 +02001463 return allowImplicitCompletion(Code->Contents, *Offset);
Ilya Biryukovb0826bd2019-01-03 13:37:12 +00001464}
1465
Johan Vikstroma848dab2019-07-04 07:53:12 +00001466void ClangdLSPServer::onHighlightingsReady(
Sam McCall2cd33e62020-03-04 00:33:29 +01001467 PathRef File, llvm::StringRef Version,
1468 std::vector<HighlightingToken> Highlightings) {
Johan Vikstromc2653ef22019-08-01 08:08:44 +00001469 std::vector<HighlightingToken> Old;
1470 std::vector<HighlightingToken> HighlightingsCopy = Highlightings;
1471 {
1472 std::lock_guard<std::mutex> Lock(HighlightingsMutex);
1473 Old = std::move(FileToHighlightings[File]);
1474 FileToHighlightings[File] = std::move(HighlightingsCopy);
1475 }
1476 // LSP allows us to send incremental edits of highlightings. Also need to diff
1477 // to remove highlightings from tokens that should no longer have them.
Haojian Wu0a6000f2019-08-26 08:38:45 +00001478 std::vector<LineHighlightings> Diffed = diffHighlightings(Highlightings, Old);
Sam McCalledf6a192020-03-24 00:31:14 +01001479 TheiaSemanticHighlightingParams Notification;
Sam McCall2cd33e62020-03-04 00:33:29 +01001480 Notification.TextDocument.uri =
1481 URIForFile::canonicalize(File, /*TUPath=*/File);
1482 Notification.TextDocument.version = decodeVersion(Version);
Sam McCalledf6a192020-03-24 00:31:14 +01001483 Notification.Lines = toTheiaSemanticHighlightingInformation(Diffed);
1484 publishTheiaSemanticHighlighting(Notification);
Johan Vikstroma848dab2019-07-04 07:53:12 +00001485}
1486
Sam McCall2cd33e62020-03-04 00:33:29 +01001487void ClangdLSPServer::onDiagnosticsReady(PathRef File, llvm::StringRef Version,
Sam McCalla7bb0cc2018-03-12 23:22:35 +00001488 std::vector<Diag> Diagnostics) {
Sam McCall6525a6b2020-03-03 12:44:40 +01001489 PublishDiagnosticsParams Notification;
Sam McCall2cd33e62020-03-04 00:33:29 +01001490 Notification.version = decodeVersion(Version);
Sam McCall6525a6b2020-03-03 12:44:40 +01001491 Notification.uri = URIForFile::canonicalize(File, /*TUPath=*/File);
Ilya Biryukov38d79772017-05-16 09:38:59 +00001492 DiagnosticToReplacementMap LocalFixIts; // Temporary storage
Sam McCalla7bb0cc2018-03-12 23:22:35 +00001493 for (auto &Diag : Diagnostics) {
Sam McCall6525a6b2020-03-03 12:44:40 +01001494 toLSPDiags(Diag, Notification.uri, DiagOpts,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001495 [&](clangd::Diagnostic Diag, llvm::ArrayRef<Fix> Fixes) {
Sam McCall16e70702018-10-24 07:59:38 +00001496 auto &FixItsForDiagnostic = LocalFixIts[Diag];
1497 llvm::copy(Fixes, std::back_inserter(FixItsForDiagnostic));
Sam McCall6525a6b2020-03-03 12:44:40 +01001498 Notification.diagnostics.push_back(std::move(Diag));
Sam McCall16e70702018-10-24 07:59:38 +00001499 });
Ilya Biryukov38d79772017-05-16 09:38:59 +00001500 }
1501
1502 // Cache FixIts
1503 {
Ilya Biryukov38d79772017-05-16 09:38:59 +00001504 std::lock_guard<std::mutex> Lock(FixItsMutex);
1505 FixItsMap[File] = LocalFixIts;
1506 }
1507
Ilya Biryukov49c10712019-03-25 10:15:11 +00001508 // Send a notification to the LSP client.
Sam McCall6525a6b2020-03-03 12:44:40 +01001509 publishDiagnostics(Notification);
Ilya Biryukov38d79772017-05-16 09:38:59 +00001510}
Simon Marchi9569fd52018-03-16 14:30:42 +00001511
Sam McCall7d20e802020-01-22 19:41:45 +01001512void ClangdLSPServer::onBackgroundIndexProgress(
1513 const BackgroundQueue::Stats &Stats) {
1514 static const char ProgressToken[] = "backgroundIndexProgress";
1515 std::lock_guard<std::mutex> Lock(BackgroundIndexProgressMutex);
1516
1517 auto NotifyProgress = [this](const BackgroundQueue::Stats &Stats) {
1518 if (BackgroundIndexProgressState != BackgroundIndexProgress::Live) {
1519 WorkDoneProgressBegin Begin;
1520 Begin.percentage = true;
1521 Begin.title = "indexing";
1522 progress(ProgressToken, std::move(Begin));
1523 BackgroundIndexProgressState = BackgroundIndexProgress::Live;
1524 }
1525
1526 if (Stats.Completed < Stats.Enqueued) {
1527 assert(Stats.Enqueued > Stats.LastIdle);
1528 WorkDoneProgressReport Report;
1529 Report.percentage = 100.0 * (Stats.Completed - Stats.LastIdle) /
1530 (Stats.Enqueued - Stats.LastIdle);
1531 Report.message =
1532 llvm::formatv("{0}/{1}", Stats.Completed - Stats.LastIdle,
1533 Stats.Enqueued - Stats.LastIdle);
1534 progress(ProgressToken, std::move(Report));
1535 } else {
1536 assert(Stats.Completed == Stats.Enqueued);
1537 progress(ProgressToken, WorkDoneProgressEnd());
1538 BackgroundIndexProgressState = BackgroundIndexProgress::Empty;
1539 }
1540 };
1541
1542 switch (BackgroundIndexProgressState) {
1543 case BackgroundIndexProgress::Unsupported:
1544 return;
1545 case BackgroundIndexProgress::Creating:
1546 // Cache this update for when the progress bar is available.
1547 PendingBackgroundIndexProgress = Stats;
1548 return;
1549 case BackgroundIndexProgress::Empty: {
1550 if (BackgroundIndexSkipCreate) {
1551 NotifyProgress(Stats);
1552 break;
1553 }
1554 // Cache this update for when the progress bar is available.
1555 PendingBackgroundIndexProgress = Stats;
1556 BackgroundIndexProgressState = BackgroundIndexProgress::Creating;
1557 WorkDoneProgressCreateParams CreateRequest;
1558 CreateRequest.token = ProgressToken;
1559 call<std::nullptr_t>(
1560 "window/workDoneProgress/create", CreateRequest,
1561 [this, NotifyProgress](llvm::Expected<std::nullptr_t> E) {
1562 std::lock_guard<std::mutex> Lock(BackgroundIndexProgressMutex);
1563 if (E) {
1564 NotifyProgress(this->PendingBackgroundIndexProgress);
1565 } else {
1566 elog("Failed to create background index progress bar: {0}",
1567 E.takeError());
1568 // give up forever rather than thrashing about
1569 BackgroundIndexProgressState = BackgroundIndexProgress::Unsupported;
1570 }
1571 });
1572 break;
1573 }
1574 case BackgroundIndexProgress::Live:
1575 NotifyProgress(Stats);
1576 break;
1577 }
1578}
1579
Haojian Wub6188492018-12-20 15:39:12 +00001580void ClangdLSPServer::onFileUpdated(PathRef File, const TUStatus &Status) {
1581 if (!SupportFileStatus)
1582 return;
1583 // FIXME: we don't emit "BuildingFile" and `RunningAction`, as these
1584 // two statuses are running faster in practice, which leads the UI constantly
1585 // changing, and doesn't provide much value. We may want to emit status at a
1586 // reasonable time interval (e.g. 0.5s).
Kadir Cetinkaya6b850322020-03-17 19:08:23 +01001587 if (Status.PreambleActivity == PreambleAction::Idle &&
1588 (Status.ASTActivity.K == ASTAction::Building ||
1589 Status.ASTActivity.K == ASTAction::RunningAction))
Haojian Wub6188492018-12-20 15:39:12 +00001590 return;
1591 notify("textDocument/clangd.fileStatus", Status.render(File));
1592}
1593
Sam McCall596b63a2020-04-10 03:27:37 +02001594void ClangdLSPServer::reparseOpenFilesIfNeeded(
1595 llvm::function_ref<bool(llvm::StringRef File)> Filter) {
David Goldman60249c22020-01-13 17:01:10 -05001596 // Reparse only opened files that were modified.
Simon Marchi9569fd52018-03-16 14:30:42 +00001597 for (const Path &FilePath : DraftMgr.getActiveFiles())
Sam McCall596b63a2020-04-10 03:27:37 +02001598 if (Filter(FilePath))
Sam McCall2cd33e62020-03-04 00:33:29 +01001599 if (auto Draft = DraftMgr.getDraft(FilePath)) // else disappeared in race?
1600 Server->addDocument(FilePath, std::move(Draft->Contents),
1601 encodeVersion(Draft->Version),
1602 WantDiagnostics::Auto);
Simon Marchi9569fd52018-03-16 14:30:42 +00001603}
Alex Lorenzf8087862018-08-01 17:39:29 +00001604
Sam McCallc008af62018-10-20 15:30:37 +00001605} // namespace clangd
1606} // namespace clang