blob: 66dee68ec474a1034787c95a827ac1eccf700a3a [file] [log] [blame]
Ilya Biryukov38d79772017-05-16 09:38:59 +00001//===--- ClangdLSPServer.cpp - LSP server ------------------------*- C++-*-===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Ilya Biryukov38d79772017-05-16 09:38:59 +00006//
Kirill Bobyrev8e35f1e2018-08-14 16:03:32 +00007//===----------------------------------------------------------------------===//
Ilya Biryukov38d79772017-05-16 09:38:59 +00008
9#include "ClangdLSPServer.h"
Kadir Cetinkaya35871fd2020-09-28 15:09:55 +020010#include "ClangdServer.h"
Sam McCall032727f2020-05-06 01:39:59 +020011#include "CodeComplete.h"
Ilya Biryukov71028b82018-03-12 15:28:22 +000012#include "Diagnostics.h"
Kadir Cetinkaya5b270932019-09-09 12:28:44 +000013#include "DraftStore.h"
Sam McCall8adc4d12020-10-16 20:03:48 +020014#include "DumpAST.h"
Kadir Cetinkaya256247c2019-06-26 07:45:27 +000015#include "GlobalCompilationDatabase.h"
Ilya Biryukovcce67a32019-01-29 14:17:36 +000016#include "Protocol.h"
Johan Vikstroma848dab2019-07-04 07:53:12 +000017#include "SemanticHighlighting.h"
Sam McCallb536a2a2017-12-19 12:23:48 +000018#include "SourceCode.h"
Kadir Cetinkaya6b850322020-03-17 19:08:23 +010019#include "TUScheduler.h"
Eric Liu78ed91a72018-01-29 15:37:46 +000020#include "URI.h"
Sam McCall395fde72019-06-18 13:37:54 +000021#include "refactor/Tweak.h"
Sam McCallad97ccf2020-04-28 17:49:17 +020022#include "support/Context.h"
Kadir Cetinkaya35871fd2020-09-28 15:09:55 +020023#include "support/MemoryTree.h"
Sam McCallad97ccf2020-04-28 17:49:17 +020024#include "support/Trace.h"
Sam McCall8adc4d12020-10-16 20:03:48 +020025#include "clang/AST/ASTContext.h"
Sam McCall6f7dca92020-03-03 12:25:46 +010026#include "clang/Basic/Version.h"
Ilya Biryukovcce67a32019-01-29 14:17:36 +000027#include "clang/Tooling/Core/Replacement.h"
Kadir Cetinkaya256247c2019-06-26 07:45:27 +000028#include "llvm/ADT/ArrayRef.h"
Sam McCalla69698f2019-03-27 17:47:49 +000029#include "llvm/ADT/Optional.h"
Kadir Cetinkaya689bf932018-08-24 13:09:41 +000030#include "llvm/ADT/ScopeExit.h"
Kadir Cetinkaya5b270932019-09-09 12:28:44 +000031#include "llvm/ADT/StringRef.h"
Utkarsh Saxena55925da2019-09-24 13:38:33 +000032#include "llvm/ADT/iterator_range.h"
Kadir Cetinkaya35871fd2020-09-28 15:09:55 +020033#include "llvm/Support/Allocator.h"
Simon Marchi9569fd52018-03-16 14:30:42 +000034#include "llvm/Support/Errc.h"
Ilya Biryukovcce67a32019-01-29 14:17:36 +000035#include "llvm/Support/Error.h"
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +000036#include "llvm/Support/FormatVariadic.h"
Utkarsh Saxena55925da2019-09-24 13:38:33 +000037#include "llvm/Support/JSON.h"
Eric Liu5740ff52018-01-31 16:26:27 +000038#include "llvm/Support/Path.h"
Kadir Cetinkaya5b270932019-09-09 12:28:44 +000039#include "llvm/Support/SHA1.h"
Sam McCall2c30fbc2018-10-18 12:32:04 +000040#include "llvm/Support/ScopedPrinter.h"
Kadir Cetinkayad0f28742020-10-13 00:10:04 +020041#include "llvm/Support/raw_ostream.h"
Kadir Cetinkaya35871fd2020-09-28 15:09:55 +020042#include <chrono>
Kadir Cetinkaya5b270932019-09-09 12:28:44 +000043#include <cstddef>
Kadir Cetinkayad0f28742020-10-13 00:10:04 +020044#include <cstdint>
45#include <functional>
Utkarsh Saxena55925da2019-09-24 13:38:33 +000046#include <memory>
Sam McCall7d20e802020-01-22 19:41:45 +010047#include <mutex>
Kadir Cetinkaya5b270932019-09-09 12:28:44 +000048#include <string>
Utkarsh Saxena55925da2019-09-24 13:38:33 +000049#include <vector>
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +000050
Sam McCallc008af62018-10-20 15:30:37 +000051namespace clang {
52namespace clangd {
Ilya Biryukovafb55542017-05-16 14:40:30 +000053namespace {
Sam McCall2cd33e62020-03-04 00:33:29 +010054
Kadir Cetinkayae64f99c2020-04-16 23:12:09 +020055// Tracks end-to-end latency of high level lsp calls. Measurements are in
56// seconds.
57constexpr trace::Metric LSPLatency("lsp_latency", trace::Metric::Distribution,
58 "method_name");
59
Sam McCall2cd33e62020-03-04 00:33:29 +010060// LSP defines file versions as numbers that increase.
61// ClangdServer treats them as opaque and therefore uses strings instead.
62std::string encodeVersion(int64_t LSPVersion) {
63 return llvm::to_string(LSPVersion);
64}
65llvm::Optional<int64_t> decodeVersion(llvm::StringRef Encoded) {
66 int64_t Result;
67 if (llvm::to_integer(Encoded, Result, 10))
68 return Result;
Kadir Cetinkayabceca7a2020-09-11 11:30:06 +020069 if (!Encoded.empty()) // Empty can be e.g. diagnostics on close.
Sam McCall2cd33e62020-03-04 00:33:29 +010070 elog("unexpected non-numeric version {0}", Encoded);
71 return llvm::None;
72}
73
Ilya Biryukovcce67a32019-01-29 14:17:36 +000074/// Transforms a tweak into a code action that would apply it if executed.
75/// EXPECTS: T.prepare() was called and returned true.
76CodeAction toCodeAction(const ClangdServer::TweakRef &T, const URIForFile &File,
77 Range Selection) {
78 CodeAction CA;
79 CA.title = T.Title;
Sam McCall17747d22020-09-28 18:12:37 +020080 CA.kind = T.Kind.str();
Ilya Biryukovcce67a32019-01-29 14:17:36 +000081 // This tweak may have an expensive second stage, we only run it if the user
82 // actually chooses it in the UI. We reply with a command that would run the
83 // corresponding tweak.
84 // FIXME: for some tweaks, computing the edits is cheap and we could send them
85 // directly.
86 CA.command.emplace();
87 CA.command->title = T.Title;
Benjamin Krameradcd0262020-01-28 20:23:46 +010088 CA.command->command = std::string(Command::CLANGD_APPLY_TWEAK);
Ilya Biryukovcce67a32019-01-29 14:17:36 +000089 CA.command->tweakArgs.emplace();
90 CA.command->tweakArgs->file = File;
91 CA.command->tweakArgs->tweakID = T.ID;
92 CA.command->tweakArgs->selection = Selection;
93 return CA;
Simon Pilgrime9a136b2019-02-03 14:08:30 +000094}
Ilya Biryukovcce67a32019-01-29 14:17:36 +000095
Ilya Biryukov19d75602018-11-23 15:21:19 +000096void adjustSymbolKinds(llvm::MutableArrayRef<DocumentSymbol> Syms,
97 SymbolKindBitset Kinds) {
98 for (auto &S : Syms) {
99 S.kind = adjustKindToCapability(S.kind, Kinds);
100 adjustSymbolKinds(S.children, Kinds);
101 }
102}
103
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000104SymbolKindBitset defaultSymbolKinds() {
105 SymbolKindBitset Defaults;
106 for (size_t I = SymbolKindMin; I <= static_cast<size_t>(SymbolKind::Array);
107 ++I)
108 Defaults.set(I);
109 return Defaults;
110}
111
Kadir Cetinkaya133d46f2018-09-27 17:13:07 +0000112CompletionItemKindBitset defaultCompletionItemKinds() {
113 CompletionItemKindBitset Defaults;
114 for (size_t I = CompletionItemKindMin;
115 I <= static_cast<size_t>(CompletionItemKind::Reference); ++I)
116 Defaults.set(I);
117 return Defaults;
118}
119
Haojian Wu1ca2ee42019-07-04 12:27:21 +0000120// Build a lookup table (HighlightingKind => {TextMate Scopes}), which is sent
121// to the LSP client.
122std::vector<std::vector<std::string>> buildHighlightScopeLookupTable() {
123 std::vector<std::vector<std::string>> LookupTable;
124 // HighlightingKind is using as the index.
Ilya Biryukov63d5d162019-09-09 08:57:17 +0000125 for (int KindValue = 0; KindValue <= (int)HighlightingKind::LastKind;
Haojian Wu1ca2ee42019-07-04 12:27:21 +0000126 ++KindValue)
Benjamin Krameradcd0262020-01-28 20:23:46 +0100127 LookupTable.push_back(
128 {std::string(toTextMateScope((HighlightingKind)(KindValue)))});
Haojian Wu1ca2ee42019-07-04 12:27:21 +0000129 return LookupTable;
130}
131
Haojian Wu852bafa2019-10-23 14:40:20 +0200132// Makes sure edits in \p FE are applicable to latest file contents reported by
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000133// editor. If not generates an error message containing information about files
134// that needs to be saved.
Haojian Wu852bafa2019-10-23 14:40:20 +0200135llvm::Error validateEdits(const DraftStore &DraftMgr, const FileEdits &FE) {
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000136 size_t InvalidFileCount = 0;
137 llvm::StringRef LastInvalidFile;
Haojian Wu852bafa2019-10-23 14:40:20 +0200138 for (const auto &It : FE) {
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000139 if (auto Draft = DraftMgr.getDraft(It.first())) {
140 // If the file is open in user's editor, make sure the version we
141 // saw and current version are compatible as this is the text that
142 // will be replaced by editors.
Sam McCallcaf5a4d2020-03-03 15:57:39 +0100143 if (!It.second.canApplyTo(Draft->Contents)) {
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000144 ++InvalidFileCount;
145 LastInvalidFile = It.first();
146 }
147 }
148 }
149 if (!InvalidFileCount)
150 return llvm::Error::success();
151 if (InvalidFileCount == 1)
Sam McCall30667c92020-07-08 21:49:38 +0200152 return error("File must be saved first: {0}", LastInvalidFile);
153 return error("Files must be saved first: {0} (and {1} others)",
154 LastInvalidFile, InvalidFileCount - 1);
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000155}
Ilya Biryukovafb55542017-05-16 14:40:30 +0000156} // namespace
157
Sam McCall2c30fbc2018-10-18 12:32:04 +0000158// MessageHandler dispatches incoming LSP messages.
159// It handles cross-cutting concerns:
160// - serializes/deserializes protocol objects to JSON
161// - logging of inbound messages
162// - cancellation handling
163// - basic call tracing
Sam McCall3d0adbe2018-10-18 14:41:50 +0000164// MessageHandler ensures that initialize() is called before any other handler.
Sam McCall2c30fbc2018-10-18 12:32:04 +0000165class ClangdLSPServer::MessageHandler : public Transport::MessageHandler {
166public:
167 MessageHandler(ClangdLSPServer &Server) : Server(Server) {}
168
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000169 bool onNotify(llvm::StringRef Method, llvm::json::Value Params) override {
Sam McCalla69698f2019-03-27 17:47:49 +0000170 WithContext HandlerContext(handlerContext());
Sam McCall2c30fbc2018-10-18 12:32:04 +0000171 log("<-- {0}", Method);
172 if (Method == "exit")
173 return false;
Kadir Cetinkaya35871fd2020-09-28 15:09:55 +0200174 if (!Server.Server) {
Sam McCall3d0adbe2018-10-18 14:41:50 +0000175 elog("Notification {0} before initialization", Method);
Kadir Cetinkaya35871fd2020-09-28 15:09:55 +0200176 } else if (Method == "$/cancelRequest") {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000177 onCancel(std::move(Params));
Kadir Cetinkaya35871fd2020-09-28 15:09:55 +0200178 } else if (auto Handler = Notifications.lookup(Method)) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000179 Handler(std::move(Params));
Kadir Cetinkaya35871fd2020-09-28 15:09:55 +0200180 Server.maybeExportMemoryProfile();
181 } else {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000182 log("unhandled notification {0}", Method);
Kadir Cetinkaya35871fd2020-09-28 15:09:55 +0200183 }
Sam McCall2c30fbc2018-10-18 12:32:04 +0000184 return true;
185 }
186
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000187 bool onCall(llvm::StringRef Method, llvm::json::Value Params,
188 llvm::json::Value ID) override {
Sam McCalla69698f2019-03-27 17:47:49 +0000189 WithContext HandlerContext(handlerContext());
Sam McCalle2f3a732018-10-24 14:26:26 +0000190 // Calls can be canceled by the client. Add cancellation context.
191 WithContext WithCancel(cancelableRequestContext(ID));
Kadir Cetinkayae64f99c2020-04-16 23:12:09 +0200192 trace::Span Tracer(Method, LSPLatency);
Sam McCalle2f3a732018-10-24 14:26:26 +0000193 SPAN_ATTACH(Tracer, "Params", Params);
194 ReplyOnce Reply(ID, Method, &Server, Tracer.Args);
Sam McCall2c30fbc2018-10-18 12:32:04 +0000195 log("<-- {0}({1})", Method, ID);
Sam McCall3d0adbe2018-10-18 14:41:50 +0000196 if (!Server.Server && Method != "initialize") {
197 elog("Call {0} before initialization.", Method);
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000198 Reply(llvm::make_error<LSPError>("server not initialized",
199 ErrorCode::ServerNotInitialized));
Sam McCall3d0adbe2018-10-18 14:41:50 +0000200 } else if (auto Handler = Calls.lookup(Method))
Sam McCalle2f3a732018-10-24 14:26:26 +0000201 Handler(std::move(Params), std::move(Reply));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000202 else
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000203 Reply(llvm::make_error<LSPError>("method not found",
204 ErrorCode::MethodNotFound));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000205 return true;
206 }
207
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000208 bool onReply(llvm::json::Value ID,
209 llvm::Expected<llvm::json::Value> Result) override {
Sam McCalla69698f2019-03-27 17:47:49 +0000210 WithContext HandlerContext(handlerContext());
Haojian Wuf2516342019-08-05 12:48:09 +0000211
212 Callback<llvm::json::Value> ReplyHandler = nullptr;
213 if (auto IntID = ID.getAsInteger()) {
214 std::lock_guard<std::mutex> Mutex(CallMutex);
215 // Find a corresponding callback for the request ID;
216 for (size_t Index = 0; Index < ReplyCallbacks.size(); ++Index) {
217 if (ReplyCallbacks[Index].first == *IntID) {
218 ReplyHandler = std::move(ReplyCallbacks[Index].second);
219 ReplyCallbacks.erase(ReplyCallbacks.begin() +
220 Index); // remove the entry
221 break;
222 }
223 }
224 }
225
226 if (!ReplyHandler) {
227 // No callback being found, use a default log callback.
228 ReplyHandler = [&ID](llvm::Expected<llvm::json::Value> Result) {
229 elog("received a reply with ID {0}, but there was no such call", ID);
230 if (!Result)
231 llvm::consumeError(Result.takeError());
232 };
233 }
234
235 // Log and run the reply handler.
236 if (Result) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000237 log("<-- reply({0})", ID);
Haojian Wuf2516342019-08-05 12:48:09 +0000238 ReplyHandler(std::move(Result));
239 } else {
240 auto Err = Result.takeError();
241 log("<-- reply({0}) error: {1}", ID, Err);
242 ReplyHandler(std::move(Err));
243 }
Sam McCall2c30fbc2018-10-18 12:32:04 +0000244 return true;
245 }
246
247 // Bind an LSP method name to a call.
Sam McCalle2f3a732018-10-24 14:26:26 +0000248 template <typename Param, typename Result>
Sam McCall2c30fbc2018-10-18 12:32:04 +0000249 void bind(const char *Method,
Sam McCalle2f3a732018-10-24 14:26:26 +0000250 void (ClangdLSPServer::*Handler)(const Param &, Callback<Result>)) {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000251 Calls[Method] = [Method, Handler, this](llvm::json::Value RawParams,
Sam McCalle2f3a732018-10-24 14:26:26 +0000252 ReplyOnce Reply) {
Sam McCallfa69b602020-09-24 01:14:12 +0200253 auto P = parse<Param>(RawParams, Method, "request");
254 if (!P)
255 return Reply(P.takeError());
256 (Server.*Handler)(*P, std::move(Reply));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000257 };
258 }
259
Haojian Wuf2516342019-08-05 12:48:09 +0000260 // Bind a reply callback to a request. The callback will be invoked when
261 // clangd receives the reply from the LSP client.
262 // Return a call id of the request.
263 llvm::json::Value bindReply(Callback<llvm::json::Value> Reply) {
264 llvm::Optional<std::pair<int, Callback<llvm::json::Value>>> OldestCB;
265 int ID;
266 {
267 std::lock_guard<std::mutex> Mutex(CallMutex);
268 ID = NextCallID++;
269 ReplyCallbacks.emplace_back(ID, std::move(Reply));
270
271 // If the queue overflows, we assume that the client didn't reply the
272 // oldest request, and run the corresponding callback which replies an
273 // error to the client.
274 if (ReplyCallbacks.size() > MaxReplayCallbacks) {
275 elog("more than {0} outstanding LSP calls, forgetting about {1}",
276 MaxReplayCallbacks, ReplyCallbacks.front().first);
277 OldestCB = std::move(ReplyCallbacks.front());
278 ReplyCallbacks.pop_front();
279 }
280 }
281 if (OldestCB)
Sam McCall30667c92020-07-08 21:49:38 +0200282 OldestCB->second(
283 error("failed to receive a client reply for request ({0})",
284 OldestCB->first));
Haojian Wuf2516342019-08-05 12:48:09 +0000285 return ID;
286 }
287
Sam McCall2c30fbc2018-10-18 12:32:04 +0000288 // Bind an LSP method name to a notification.
289 template <typename Param>
290 void bind(const char *Method,
291 void (ClangdLSPServer::*Handler)(const Param &)) {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000292 Notifications[Method] = [Method, Handler,
293 this](llvm::json::Value RawParams) {
Sam McCallfa69b602020-09-24 01:14:12 +0200294 llvm::Expected<Param> P = parse<Param>(RawParams, Method, "request");
295 if (!P)
296 return llvm::consumeError(P.takeError());
Kadir Cetinkayae64f99c2020-04-16 23:12:09 +0200297 trace::Span Tracer(Method, LSPLatency);
Sam McCall2c30fbc2018-10-18 12:32:04 +0000298 SPAN_ATTACH(Tracer, "Params", RawParams);
Sam McCallfa69b602020-09-24 01:14:12 +0200299 (Server.*Handler)(*P);
Sam McCall2c30fbc2018-10-18 12:32:04 +0000300 };
301 }
302
303private:
Sam McCalle2f3a732018-10-24 14:26:26 +0000304 // Function object to reply to an LSP call.
305 // Each instance must be called exactly once, otherwise:
306 // - the bug is logged, and (in debug mode) an assert will fire
307 // - if there was no reply, an error reply is sent
308 // - if there were multiple replies, only the first is sent
309 class ReplyOnce {
310 std::atomic<bool> Replied = {false};
Sam McCalld7babe42018-10-24 15:18:40 +0000311 std::chrono::steady_clock::time_point Start;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000312 llvm::json::Value ID;
Sam McCalle2f3a732018-10-24 14:26:26 +0000313 std::string Method;
314 ClangdLSPServer *Server; // Null when moved-from.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000315 llvm::json::Object *TraceArgs;
Sam McCalle2f3a732018-10-24 14:26:26 +0000316
317 public:
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000318 ReplyOnce(const llvm::json::Value &ID, llvm::StringRef Method,
319 ClangdLSPServer *Server, llvm::json::Object *TraceArgs)
Sam McCalld7babe42018-10-24 15:18:40 +0000320 : Start(std::chrono::steady_clock::now()), ID(ID), Method(Method),
321 Server(Server), TraceArgs(TraceArgs) {
Sam McCalle2f3a732018-10-24 14:26:26 +0000322 assert(Server);
323 }
324 ReplyOnce(ReplyOnce &&Other)
Sam McCalld7babe42018-10-24 15:18:40 +0000325 : Replied(Other.Replied.load()), Start(Other.Start),
326 ID(std::move(Other.ID)), Method(std::move(Other.Method)),
327 Server(Other.Server), TraceArgs(Other.TraceArgs) {
Sam McCalle2f3a732018-10-24 14:26:26 +0000328 Other.Server = nullptr;
329 }
Ilya Biryukov22fa4652019-01-03 13:28:05 +0000330 ReplyOnce &operator=(ReplyOnce &&) = delete;
Sam McCalle2f3a732018-10-24 14:26:26 +0000331 ReplyOnce(const ReplyOnce &) = delete;
Ilya Biryukov22fa4652019-01-03 13:28:05 +0000332 ReplyOnce &operator=(const ReplyOnce &) = delete;
Sam McCalle2f3a732018-10-24 14:26:26 +0000333
334 ~ReplyOnce() {
Haojian Wuf2516342019-08-05 12:48:09 +0000335 // There's one legitimate reason to never reply to a request: clangd's
336 // request handler send a call to the client (e.g. applyEdit) and the
337 // client never replied. In this case, the ReplyOnce is owned by
338 // ClangdLSPServer's reply callback table and is destroyed along with the
339 // server. We don't attempt to send a reply in this case, there's little
340 // to be gained from doing so.
341 if (Server && !Server->IsBeingDestroyed && !Replied) {
Sam McCalle2f3a732018-10-24 14:26:26 +0000342 elog("No reply to message {0}({1})", Method, ID);
343 assert(false && "must reply to all calls!");
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000344 (*this)(llvm::make_error<LSPError>("server failed to reply",
345 ErrorCode::InternalError));
Sam McCalle2f3a732018-10-24 14:26:26 +0000346 }
347 }
348
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000349 void operator()(llvm::Expected<llvm::json::Value> Reply) {
Sam McCalle2f3a732018-10-24 14:26:26 +0000350 assert(Server && "moved-from!");
351 if (Replied.exchange(true)) {
352 elog("Replied twice to message {0}({1})", Method, ID);
353 assert(false && "must reply to each call only once!");
354 return;
355 }
Sam McCalld7babe42018-10-24 15:18:40 +0000356 auto Duration = std::chrono::steady_clock::now() - Start;
357 if (Reply) {
358 log("--> reply:{0}({1}) {2:ms}", Method, ID, Duration);
359 if (TraceArgs)
Sam McCalle2f3a732018-10-24 14:26:26 +0000360 (*TraceArgs)["Reply"] = *Reply;
Sam McCalld7babe42018-10-24 15:18:40 +0000361 std::lock_guard<std::mutex> Lock(Server->TranspWriter);
362 Server->Transp.reply(std::move(ID), std::move(Reply));
363 } else {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000364 llvm::Error Err = Reply.takeError();
Sam McCalld7babe42018-10-24 15:18:40 +0000365 log("--> reply:{0}({1}) {2:ms}, error: {3}", Method, ID, Duration, Err);
366 if (TraceArgs)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000367 (*TraceArgs)["Error"] = llvm::to_string(Err);
Sam McCalld7babe42018-10-24 15:18:40 +0000368 std::lock_guard<std::mutex> Lock(Server->TranspWriter);
369 Server->Transp.reply(std::move(ID), std::move(Err));
Sam McCalle2f3a732018-10-24 14:26:26 +0000370 }
Sam McCalle2f3a732018-10-24 14:26:26 +0000371 }
372 };
373
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000374 llvm::StringMap<std::function<void(llvm::json::Value)>> Notifications;
375 llvm::StringMap<std::function<void(llvm::json::Value, ReplyOnce)>> Calls;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000376
377 // Method calls may be cancelled by ID, so keep track of their state.
378 // This needs a mutex: handlers may finish on a different thread, and that's
379 // when we clean up entries in the map.
380 mutable std::mutex RequestCancelersMutex;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000381 llvm::StringMap<std::pair<Canceler, /*Cookie*/ unsigned>> RequestCancelers;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000382 unsigned NextRequestCookie = 0; // To disambiguate reused IDs, see below.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000383 void onCancel(const llvm::json::Value &Params) {
384 const llvm::json::Value *ID = nullptr;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000385 if (auto *O = Params.getAsObject())
386 ID = O->get("id");
387 if (!ID) {
388 elog("Bad cancellation request: {0}", Params);
389 return;
390 }
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000391 auto StrID = llvm::to_string(*ID);
Sam McCall2c30fbc2018-10-18 12:32:04 +0000392 std::lock_guard<std::mutex> Lock(RequestCancelersMutex);
393 auto It = RequestCancelers.find(StrID);
394 if (It != RequestCancelers.end())
395 It->second.first(); // Invoke the canceler.
396 }
Sam McCalla69698f2019-03-27 17:47:49 +0000397
398 Context handlerContext() const {
399 return Context::current().derive(
400 kCurrentOffsetEncoding,
Sam McCall6342b382020-09-30 10:56:43 +0200401 Server.Opts.Encoding.getValueOr(OffsetEncoding::UTF16));
Sam McCalla69698f2019-03-27 17:47:49 +0000402 }
403
Sam McCall2c30fbc2018-10-18 12:32:04 +0000404 // We run cancelable requests in a context that does two things:
405 // - allows cancellation using RequestCancelers[ID]
406 // - cleans up the entry in RequestCancelers when it's no longer needed
407 // If a client reuses an ID, the last wins and the first cannot be canceled.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000408 Context cancelableRequestContext(const llvm::json::Value &ID) {
Sam McCall31db1e02020-04-11 18:19:50 +0200409 auto Task = cancelableTask(
410 /*Reason=*/static_cast<int>(ErrorCode::RequestCancelled));
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000411 auto StrID = llvm::to_string(ID); // JSON-serialize ID for map key.
Sam McCall2c30fbc2018-10-18 12:32:04 +0000412 auto Cookie = NextRequestCookie++; // No lock, only called on main thread.
413 {
414 std::lock_guard<std::mutex> Lock(RequestCancelersMutex);
415 RequestCancelers[StrID] = {std::move(Task.second), Cookie};
416 }
417 // When the request ends, we can clean up the entry we just added.
418 // The cookie lets us check that it hasn't been overwritten due to ID
419 // reuse.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000420 return Task.first.derive(llvm::make_scope_exit([this, StrID, Cookie] {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000421 std::lock_guard<std::mutex> Lock(RequestCancelersMutex);
422 auto It = RequestCancelers.find(StrID);
423 if (It != RequestCancelers.end() && It->second.second == Cookie)
424 RequestCancelers.erase(It);
425 }));
426 }
427
Kadir Cetinkaya9a3a87d2019-10-09 13:59:31 +0000428 // The maximum number of callbacks held in clangd.
429 //
430 // We bound the maximum size to the pending map to prevent memory leakage
431 // for cases where LSP clients don't reply for the request.
432 // This has to go after RequestCancellers and RequestCancellersMutex since it
433 // can contain a callback that has a cancelable context.
434 static constexpr int MaxReplayCallbacks = 100;
435 mutable std::mutex CallMutex;
436 int NextCallID = 0; /* GUARDED_BY(CallMutex) */
437 std::deque<std::pair</*RequestID*/ int,
438 /*ReplyHandler*/ Callback<llvm::json::Value>>>
439 ReplyCallbacks; /* GUARDED_BY(CallMutex) */
440
Sam McCall2c30fbc2018-10-18 12:32:04 +0000441 ClangdLSPServer &Server;
442};
Haojian Wuf2516342019-08-05 12:48:09 +0000443constexpr int ClangdLSPServer::MessageHandler::MaxReplayCallbacks;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000444
445// call(), notify(), and reply() wrap the Transport, adding logging and locking.
Haojian Wuf2516342019-08-05 12:48:09 +0000446void ClangdLSPServer::callRaw(StringRef Method, llvm::json::Value Params,
447 Callback<llvm::json::Value> CB) {
448 auto ID = MsgHandler->bindReply(std::move(CB));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000449 log("--> {0}({1})", Method, ID);
Sam McCall2c30fbc2018-10-18 12:32:04 +0000450 std::lock_guard<std::mutex> Lock(TranspWriter);
451 Transp.call(Method, std::move(Params), ID);
452}
453
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000454void ClangdLSPServer::notify(llvm::StringRef Method, llvm::json::Value Params) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000455 log("--> {0}", Method);
456 std::lock_guard<std::mutex> Lock(TranspWriter);
457 Transp.notify(Method, std::move(Params));
458}
459
Sam McCall71177ac2020-03-24 02:24:47 +0100460static std::vector<llvm::StringRef> semanticTokenTypes() {
461 std::vector<llvm::StringRef> Types;
462 for (unsigned I = 0; I <= static_cast<unsigned>(HighlightingKind::LastKind);
463 ++I)
464 Types.push_back(toSemanticTokenType(static_cast<HighlightingKind>(I)));
465 return Types;
466}
467
Sam McCall2c30fbc2018-10-18 12:32:04 +0000468void ClangdLSPServer::onInitialize(const InitializeParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000469 Callback<llvm::json::Value> Reply) {
Sam McCalla69698f2019-03-27 17:47:49 +0000470 // Determine character encoding first as it affects constructed ClangdServer.
Sam McCall6342b382020-09-30 10:56:43 +0200471 if (Params.capabilities.offsetEncoding && !Opts.Encoding) {
472 Opts.Encoding = OffsetEncoding::UTF16; // fallback
Sam McCalla69698f2019-03-27 17:47:49 +0000473 for (OffsetEncoding Supported : *Params.capabilities.offsetEncoding)
474 if (Supported != OffsetEncoding::UnsupportedEncoding) {
Sam McCall6342b382020-09-30 10:56:43 +0200475 Opts.Encoding = Supported;
Sam McCalla69698f2019-03-27 17:47:49 +0000476 break;
477 }
478 }
Sam McCalla69698f2019-03-27 17:47:49 +0000479
Sam McCall7ba07792020-09-29 10:37:46 +0200480 Opts.TheiaSemanticHighlighting =
Sam McCalledf6a192020-03-24 00:31:14 +0100481 Params.capabilities.TheiaSemanticHighlighting;
Sam McCallfc830102020-04-01 12:02:28 +0200482 if (Params.capabilities.TheiaSemanticHighlighting &&
483 Params.capabilities.SemanticTokens) {
484 log("Client supports legacy semanticHighlights notification and standard "
485 "semanticTokens request, choosing the latter (no notifications).");
Sam McCall7ba07792020-09-29 10:37:46 +0200486 Opts.TheiaSemanticHighlighting = false;
Sam McCallfc830102020-04-01 12:02:28 +0200487 }
488
Sam McCall0d9b40f2018-10-19 15:42:23 +0000489 if (Params.rootUri && *Params.rootUri)
Sam McCall7ba07792020-09-29 10:37:46 +0200490 Opts.WorkspaceRoot = std::string(Params.rootUri->file());
Sam McCall0d9b40f2018-10-19 15:42:23 +0000491 else if (Params.rootPath && !Params.rootPath->empty())
Sam McCall7ba07792020-09-29 10:37:46 +0200492 Opts.WorkspaceRoot = *Params.rootPath;
Sam McCall3d0adbe2018-10-18 14:41:50 +0000493 if (Server)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000494 return Reply(llvm::make_error<LSPError>("server already initialized",
495 ErrorCode::InvalidRequest));
Sam McCallbc904612018-10-25 04:22:52 +0000496 if (const auto &Dir = Params.initializationOptions.compilationDatabasePath)
Sam McCall7ba07792020-09-29 10:37:46 +0200497 Opts.CompileCommandsDir = Dir;
498 if (Opts.UseDirBasedCDB) {
Jonas Devlieghere1c705d92019-08-14 23:52:23 +0000499 BaseCDB = std::make_unique<DirectoryBasedGlobalCompilationDatabase>(
Sam McCall7ba07792020-09-29 10:37:46 +0200500 Opts.CompileCommandsDir);
501 BaseCDB = getQueryDriverDatabase(llvm::makeArrayRef(Opts.QueryDriverGlobs),
502 std::move(BaseCDB));
Kadir Cetinkaya256247c2019-06-26 07:45:27 +0000503 }
Sam McCall99768b22019-11-29 19:37:48 +0100504 auto Mangler = CommandMangler::detect();
Sam McCall7ba07792020-09-29 10:37:46 +0200505 if (Opts.ResourceDir)
506 Mangler.ResourceDir = *Opts.ResourceDir;
Kadir Cetinkayabe6b35d2019-01-22 09:10:20 +0000507 CDB.emplace(BaseCDB.get(), Params.initializationOptions.fallbackFlags,
Sam McCall2a3ac012020-06-09 22:54:42 +0200508 tooling::ArgumentsAdjuster(std::move(Mangler)));
Kadir Cetinkaya9d662472019-10-15 14:20:52 +0000509 {
510 // Switch caller's context with LSPServer's background context. Since we
511 // rather want to propagate information from LSPServer's context into the
512 // Server, CDB, etc.
513 WithContext MainContext(BackgroundContext.clone());
514 llvm::Optional<WithContextValue> WithOffsetEncoding;
Sam McCall6342b382020-09-30 10:56:43 +0200515 if (Opts.Encoding)
516 WithOffsetEncoding.emplace(kCurrentOffsetEncoding, *Opts.Encoding);
Sam McCall7ba07792020-09-29 10:37:46 +0200517 Server.emplace(*CDB, TFS, Opts,
Sam McCall6ef1cce2020-01-24 14:08:56 +0100518 static_cast<ClangdServer::Callbacks *>(this));
Kadir Cetinkaya9d662472019-10-15 14:20:52 +0000519 }
Sam McCallbc904612018-10-25 04:22:52 +0000520 applyConfiguration(Params.initializationOptions.ConfigSettings);
Simon Marchi88016782018-08-01 11:28:49 +0000521
Sam McCall7ba07792020-09-29 10:37:46 +0200522 Opts.CodeComplete.EnableSnippets = Params.capabilities.CompletionSnippets;
523 Opts.CodeComplete.IncludeFixIts = Params.capabilities.CompletionFixes;
524 if (!Opts.CodeComplete.BundleOverloads.hasValue())
525 Opts.CodeComplete.BundleOverloads = Params.capabilities.HasSignatureHelp;
526 Opts.CodeComplete.DocumentationFormat =
Sam McCalla3a27a72020-04-30 10:49:32 +0200527 Params.capabilities.CompletionDocumentationFormat;
Sam McCallbf6a2fc2018-10-17 07:33:42 +0000528 DiagOpts.EmbedFixesInDiagnostics = Params.capabilities.DiagnosticFixes;
529 DiagOpts.SendDiagnosticCategory = Params.capabilities.DiagnosticCategory;
Sam McCallc9e4ee92019-04-18 15:17:07 +0000530 DiagOpts.EmitRelatedLocations =
531 Params.capabilities.DiagnosticRelatedInformation;
Sam McCallbf6a2fc2018-10-17 07:33:42 +0000532 if (Params.capabilities.WorkspaceSymbolKinds)
533 SupportedSymbolKinds |= *Params.capabilities.WorkspaceSymbolKinds;
534 if (Params.capabilities.CompletionItemKinds)
535 SupportedCompletionItemKinds |= *Params.capabilities.CompletionItemKinds;
536 SupportsCodeAction = Params.capabilities.CodeActionStructure;
Ilya Biryukov19d75602018-11-23 15:21:19 +0000537 SupportsHierarchicalDocumentSymbol =
538 Params.capabilities.HierarchicalDocumentSymbol;
Haojian Wub6188492018-12-20 15:39:12 +0000539 SupportFileStatus = Params.initializationOptions.FileStatus;
Ilya Biryukovf9169d02019-05-29 10:01:00 +0000540 HoverContentFormat = Params.capabilities.HoverContentFormat;
Ilya Biryukov4ef0f822019-06-04 09:36:59 +0000541 SupportsOffsetsInSignatureHelp = Params.capabilities.OffsetsInSignatureHelp;
Sam McCall7d20e802020-01-22 19:41:45 +0100542 if (Params.capabilities.WorkDoneProgress)
543 BackgroundIndexProgressState = BackgroundIndexProgress::Empty;
544 BackgroundIndexSkipCreate = Params.capabilities.ImplicitProgressCreation;
Haojian Wuf429ab62019-07-24 07:49:23 +0000545
546 // Per LSP, renameProvider can be either boolean or RenameOptions.
547 // RenameOptions will be specified if the client states it supports prepare.
548 llvm::json::Value RenameProvider =
549 llvm::json::Object{{"prepareProvider", true}};
550 if (!Params.capabilities.RenamePrepareSupport) // Only boolean allowed per LSP
551 RenameProvider = true;
552
Haojian Wu08d93f12019-08-22 14:53:45 +0000553 // Per LSP, codeActionProvide can be either boolean or CodeActionOptions.
554 // CodeActionOptions is only valid if the client supports action literal
555 // via textDocument.codeAction.codeActionLiteralSupport.
556 llvm::json::Value CodeActionProvider = true;
557 if (Params.capabilities.CodeActionStructure)
558 CodeActionProvider = llvm::json::Object{
559 {"codeActionKinds",
560 {CodeAction::QUICKFIX_KIND, CodeAction::REFACTOR_KIND,
561 CodeAction::INFO_KIND}}};
562
Sam McCalla69698f2019-03-27 17:47:49 +0000563 llvm::json::Object Result{
Sam McCall6f7dca92020-03-03 12:25:46 +0100564 {{"serverInfo",
565 llvm::json::Object{{"name", "clangd"},
566 {"version", getClangToolFullVersion("clangd")}}},
567 {"capabilities",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000568 llvm::json::Object{
Sam McCall596b63a2020-04-10 03:27:37 +0200569 {"textDocumentSync",
570 llvm::json::Object{
571 {"openClose", true},
572 {"change", (int)TextDocumentSyncKind::Incremental},
573 {"save", true},
574 }},
Sam McCall0930ab02017-11-07 15:49:35 +0000575 {"documentFormattingProvider", true},
576 {"documentRangeFormattingProvider", true},
577 {"documentOnTypeFormattingProvider",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000578 llvm::json::Object{
Sam McCall25c62572019-06-10 14:26:21 +0000579 {"firstTriggerCharacter", "\n"},
Sam McCall0930ab02017-11-07 15:49:35 +0000580 {"moreTriggerCharacter", {}},
581 }},
Haojian Wu08d93f12019-08-22 14:53:45 +0000582 {"codeActionProvider", std::move(CodeActionProvider)},
Sam McCall0930ab02017-11-07 15:49:35 +0000583 {"completionProvider",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000584 llvm::json::Object{
Kirill Bobyrev9d11e672020-08-26 17:08:00 +0200585 {"allCommitCharacters",
586 {" ", "\t", "(", ")", "[", "]", "{", "}", "<",
587 ">", ":", ";", ",", "+", "-", "/", "*", "%",
588 "^", "&", "#", "?", ".", "=", "\"", "'", "|"}},
Sam McCall0930ab02017-11-07 15:49:35 +0000589 {"resolveProvider", false},
Sam McCall032727f2020-05-06 01:39:59 +0200590 // We do extra checks, e.g. that > is part of ->.
591 {"triggerCharacters", {".", "<", ">", ":", "\"", "/"}},
Sam McCall0930ab02017-11-07 15:49:35 +0000592 }},
Sam McCall71177ac2020-03-24 02:24:47 +0100593 {"semanticTokensProvider",
594 llvm::json::Object{
Sam McCall5fea54b2020-07-10 16:08:14 +0200595 {"full", llvm::json::Object{{"delta", true}}},
596 {"range", false},
Sam McCall71177ac2020-03-24 02:24:47 +0100597 {"legend",
598 llvm::json::Object{{"tokenTypes", semanticTokenTypes()},
599 {"tokenModifiers", llvm::json::Array()}}},
600 }},
Sam McCall0930ab02017-11-07 15:49:35 +0000601 {"signatureHelpProvider",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000602 llvm::json::Object{
Sam McCall0930ab02017-11-07 15:49:35 +0000603 {"triggerCharacters", {"(", ","}},
604 }},
Sam McCall866ba2c2019-02-01 11:26:13 +0000605 {"declarationProvider", true},
Sam McCall0930ab02017-11-07 15:49:35 +0000606 {"definitionProvider", true},
Utkarsh Saxenab31486a2020-11-18 13:25:09 +0100607 {"implementationProvider", true},
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000608 {"documentHighlightProvider", true},
Sam McCall8d7ecc12019-12-16 19:08:51 +0100609 {"documentLinkProvider",
610 llvm::json::Object{
611 {"resolveProvider", false},
612 }},
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000613 {"hoverProvider", true},
Haojian Wuf429ab62019-07-24 07:49:23 +0000614 {"renameProvider", std::move(RenameProvider)},
Utkarsh Saxena55925da2019-09-24 13:38:33 +0000615 {"selectionRangeProvider", true},
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000616 {"documentSymbolProvider", true},
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000617 {"workspaceSymbolProvider", true},
Sam McCall1ad142f2018-09-05 11:53:07 +0000618 {"referencesProvider", true},
Sam McCall8adc4d12020-10-16 20:03:48 +0200619 {"astProvider", true},
Sam McCall0930ab02017-11-07 15:49:35 +0000620 {"executeCommandProvider",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000621 llvm::json::Object{
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000622 {"commands",
623 {ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND,
624 ExecuteCommandParams::CLANGD_APPLY_TWEAK}},
Sam McCall0930ab02017-11-07 15:49:35 +0000625 }},
Kadir Cetinkaya86658022019-03-19 09:27:04 +0000626 {"typeHierarchyProvider", true},
Kadir Cetinkayad0f28742020-10-13 00:10:04 +0200627 {"memoryUsageProvider", true}, // clangd extension.
Nathan Ridge0a4f99c2020-11-15 22:45:17 -0500628 {"callHierarchyProvider", true},
Sam McCalla69698f2019-03-27 17:47:49 +0000629 }}}};
Sam McCall6342b382020-09-30 10:56:43 +0200630 if (Opts.Encoding)
631 Result["offsetEncoding"] = *Opts.Encoding;
Sam McCall7ba07792020-09-29 10:37:46 +0200632 if (Opts.TheiaSemanticHighlighting)
Johan Vikstroma848dab2019-07-04 07:53:12 +0000633 Result.getObject("capabilities")
634 ->insert(
635 {"semanticHighlighting",
Haojian Wu1ca2ee42019-07-04 12:27:21 +0000636 llvm::json::Object{{"scopes", buildHighlightScopeLookupTable()}}});
Sam McCall7ba07792020-09-29 10:37:46 +0200637 if (Opts.FoldingRanges)
Kirill Bobyrev7a514c92020-07-14 09:28:38 +0200638 Result.getObject("capabilities")->insert({"foldingRangeProvider", true});
Sam McCalla69698f2019-03-27 17:47:49 +0000639 Reply(std::move(Result));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000640}
641
Sam McCall8a2d2942020-03-03 12:12:14 +0100642void ClangdLSPServer::onInitialized(const InitializedParams &Params) {}
643
Sam McCall2c30fbc2018-10-18 12:32:04 +0000644void ClangdLSPServer::onShutdown(const ShutdownParams &Params,
645 Callback<std::nullptr_t> Reply) {
Ilya Biryukov0d9b8a32017-10-25 08:45:41 +0000646 // Do essentially nothing, just say we're ready to exit.
647 ShutdownRequestReceived = true;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000648 Reply(nullptr);
Sam McCall8a5dded2017-10-12 13:29:58 +0000649}
Ilya Biryukovafb55542017-05-16 14:40:30 +0000650
Sam McCall422c8282018-11-26 16:00:11 +0000651// sync is a clangd extension: it blocks until all background work completes.
652// It blocks the calling thread, so no messages are processed until it returns!
653void ClangdLSPServer::onSync(const NoParams &Params,
654 Callback<std::nullptr_t> Reply) {
655 if (Server->blockUntilIdleForTest(/*TimeoutSeconds=*/60))
656 Reply(nullptr);
657 else
Sam McCall30667c92020-07-08 21:49:38 +0200658 Reply(error("Not idle after a minute"));
Sam McCall422c8282018-11-26 16:00:11 +0000659}
660
Sam McCall2c30fbc2018-10-18 12:32:04 +0000661void ClangdLSPServer::onDocumentDidOpen(
662 const DidOpenTextDocumentParams &Params) {
Simon Marchi9569fd52018-03-16 14:30:42 +0000663 PathRef File = Params.textDocument.uri.file();
Ilya Biryukovb10ef472018-06-13 09:20:41 +0000664
Sam McCall2c30fbc2018-10-18 12:32:04 +0000665 const std::string &Contents = Params.textDocument.text;
Simon Marchi9569fd52018-03-16 14:30:42 +0000666
Sam McCall2cd33e62020-03-04 00:33:29 +0100667 auto Version = DraftMgr.addDraft(File, Params.textDocument.version, Contents);
668 Server->addDocument(File, Contents, encodeVersion(Version),
669 WantDiagnostics::Yes);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000670}
671
Sam McCall2c30fbc2018-10-18 12:32:04 +0000672void ClangdLSPServer::onDocumentDidChange(
673 const DidChangeTextDocumentParams &Params) {
Eric Liu51fed182018-02-22 18:40:39 +0000674 auto WantDiags = WantDiagnostics::Auto;
675 if (Params.wantDiagnostics.hasValue())
676 WantDiags = Params.wantDiagnostics.getValue() ? WantDiagnostics::Yes
677 : WantDiagnostics::No;
Simon Marchi9569fd52018-03-16 14:30:42 +0000678
679 PathRef File = Params.textDocument.uri.file();
Sam McCallcaf5a4d2020-03-03 15:57:39 +0100680 llvm::Expected<DraftStore::Draft> Draft = DraftMgr.updateDraft(
681 File, Params.textDocument.version, Params.contentChanges);
682 if (!Draft) {
Simon Marchi98082622018-03-26 14:41:40 +0000683 // If this fails, we are most likely going to be not in sync anymore with
684 // the client. It is better to remove the draft and let further operations
685 // fail rather than giving wrong results.
686 DraftMgr.removeDraft(File);
Ilya Biryukov652364b2018-09-26 05:48:29 +0000687 Server->removeDocument(File);
Sam McCallcaf5a4d2020-03-03 15:57:39 +0100688 elog("Failed to update {0}: {1}", File, Draft.takeError());
Simon Marchi98082622018-03-26 14:41:40 +0000689 return;
690 }
Simon Marchi9569fd52018-03-16 14:30:42 +0000691
Sam McCall2cd33e62020-03-04 00:33:29 +0100692 Server->addDocument(File, Draft->Contents, encodeVersion(Draft->Version),
693 WantDiags, Params.forceRebuild);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000694}
695
Sam McCall596b63a2020-04-10 03:27:37 +0200696void ClangdLSPServer::onDocumentDidSave(
697 const DidSaveTextDocumentParams &Params) {
698 reparseOpenFilesIfNeeded([](llvm::StringRef) { return true; });
699}
700
Sam McCall2c30fbc2018-10-18 12:32:04 +0000701void ClangdLSPServer::onFileEvent(const DidChangeWatchedFilesParams &Params) {
Sam McCall596b63a2020-04-10 03:27:37 +0200702 // We could also reparse all open files here. However:
703 // - this could be frequent, and revalidating all the preambles isn't free
704 // - this is useful e.g. when switching git branches, but we're likely to see
705 // fresh headers but still have the old-branch main-file content
Ilya Biryukov652364b2018-09-26 05:48:29 +0000706 Server->onFileEvent(Params);
Marc-Andre Laperlebf114242017-10-02 18:00:37 +0000707}
708
Sam McCall2c30fbc2018-10-18 12:32:04 +0000709void ClangdLSPServer::onCommand(const ExecuteCommandParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000710 Callback<llvm::json::Value> Reply) {
Ilya Biryukov12864002019-08-16 12:46:41 +0000711 auto ApplyEdit = [this](WorkspaceEdit WE, std::string SuccessMessage,
712 decltype(Reply) Reply) {
Eric Liuc5105f92018-02-16 14:15:55 +0000713 ApplyWorkspaceEditParams Edit;
714 Edit.edit = std::move(WE);
Ilya Biryukov12864002019-08-16 12:46:41 +0000715 call<ApplyWorkspaceEditResponse>(
716 "workspace/applyEdit", std::move(Edit),
717 [Reply = std::move(Reply), SuccessMessage = std::move(SuccessMessage)](
718 llvm::Expected<ApplyWorkspaceEditResponse> Response) mutable {
719 if (!Response)
720 return Reply(Response.takeError());
721 if (!Response->applied) {
722 std::string Reason = Response->failureReason
723 ? *Response->failureReason
724 : "unknown reason";
Sam McCall30667c92020-07-08 21:49:38 +0200725 return Reply(error("edits were not applied: {0}", Reason));
Ilya Biryukov12864002019-08-16 12:46:41 +0000726 }
727 return Reply(SuccessMessage);
728 });
Eric Liuc5105f92018-02-16 14:15:55 +0000729 };
Ilya Biryukov12864002019-08-16 12:46:41 +0000730
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000731 if (Params.command == ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND &&
732 Params.workspaceEdit) {
733 // The flow for "apply-fix" :
734 // 1. We publish a diagnostic, including fixits
735 // 2. The user clicks on the diagnostic, the editor asks us for code actions
736 // 3. We send code actions, with the fixit embedded as context
737 // 4. The user selects the fixit, the editor asks us to apply it
738 // 5. We unwrap the changes and send them back to the editor
Haojian Wuf2516342019-08-05 12:48:09 +0000739 // 6. The editor applies the changes (applyEdit), and sends us a reply
740 // 7. We unwrap the reply and send a reply to the editor.
Ilya Biryukov12864002019-08-16 12:46:41 +0000741 ApplyEdit(*Params.workspaceEdit, "Fix applied.", std::move(Reply));
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000742 } else if (Params.command == ExecuteCommandParams::CLANGD_APPLY_TWEAK &&
743 Params.tweakArgs) {
744 auto Code = DraftMgr.getDraft(Params.tweakArgs->file.file());
745 if (!Code)
Sam McCall30667c92020-07-08 21:49:38 +0200746 return Reply(error("trying to apply a code action for a non-added file"));
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000747
Ilya Biryukov12864002019-08-16 12:46:41 +0000748 auto Action = [this, ApplyEdit, Reply = std::move(Reply),
749 File = Params.tweakArgs->file, Code = std::move(*Code)](
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000750 llvm::Expected<Tweak::Effect> R) mutable {
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000751 if (!R)
752 return Reply(R.takeError());
753
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000754 assert(R->ShowMessage ||
755 (!R->ApplyEdits.empty() && "tweak has no effect"));
Ilya Biryukov12864002019-08-16 12:46:41 +0000756
Sam McCall395fde72019-06-18 13:37:54 +0000757 if (R->ShowMessage) {
758 ShowMessageParams Msg;
759 Msg.message = *R->ShowMessage;
760 Msg.type = MessageType::Info;
761 notify("window/showMessage", Msg);
762 }
Ilya Biryukov12864002019-08-16 12:46:41 +0000763 // When no edit is specified, make sure we Reply().
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000764 if (R->ApplyEdits.empty())
765 return Reply("Tweak applied.");
766
Haojian Wu852bafa2019-10-23 14:40:20 +0200767 if (auto Err = validateEdits(DraftMgr, R->ApplyEdits))
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000768 return Reply(std::move(Err));
769
770 WorkspaceEdit WE;
771 WE.changes.emplace();
772 for (const auto &It : R->ApplyEdits) {
Kadir Cetinkayae95e5162019-10-02 09:12:01 +0000773 (*WE.changes)[URI::createFile(It.first()).toString()] =
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000774 It.second.asTextEdits();
775 }
776 // ApplyEdit will take care of calling Reply().
777 return ApplyEdit(std::move(WE), "Tweak applied.", std::move(Reply));
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000778 };
779 Server->applyTweak(Params.tweakArgs->file.file(),
780 Params.tweakArgs->selection, Params.tweakArgs->tweakID,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000781 std::move(Action));
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000782 } else {
783 // We should not get here because ExecuteCommandParams would not have
784 // parsed in the first place and this handler should not be called. But if
785 // more commands are added, this will be here has a safe guard.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000786 Reply(llvm::make_error<LSPError>(
787 llvm::formatv("Unsupported command \"{0}\".", Params.command).str(),
Sam McCall2c30fbc2018-10-18 12:32:04 +0000788 ErrorCode::InvalidParams));
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000789 }
790}
791
Sam McCall2c30fbc2018-10-18 12:32:04 +0000792void ClangdLSPServer::onWorkspaceSymbol(
793 const WorkspaceSymbolParams &Params,
794 Callback<std::vector<SymbolInformation>> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000795 Server->workspaceSymbols(
Sam McCall7ba07792020-09-29 10:37:46 +0200796 Params.query, Opts.CodeComplete.Limit,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000797 [Reply = std::move(Reply),
798 this](llvm::Expected<std::vector<SymbolInformation>> Items) mutable {
799 if (!Items)
800 return Reply(Items.takeError());
801 for (auto &Sym : *Items)
802 Sym.kind = adjustKindToCapability(Sym.kind, SupportedSymbolKinds);
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000803
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000804 Reply(std::move(*Items));
805 });
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000806}
807
Haojian Wuf429ab62019-07-24 07:49:23 +0000808void ClangdLSPServer::onPrepareRename(const TextDocumentPositionParams &Params,
809 Callback<llvm::Optional<Range>> Reply) {
Haojian Wu0f0cbcc2020-10-02 16:01:25 +0200810 Server->prepareRename(
Haojian Wu9c09e202020-10-07 21:16:45 +0200811 Params.textDocument.uri.file(), Params.position, /*NewName*/ llvm::None,
812 Opts.Rename,
Haojian Wu0f0cbcc2020-10-02 16:01:25 +0200813 [Reply = std::move(Reply)](llvm::Expected<RenameResult> Result) mutable {
814 if (!Result)
815 return Reply(Result.takeError());
816 return Reply(std::move(Result->Target));
817 });
Haojian Wuf429ab62019-07-24 07:49:23 +0000818}
819
Sam McCall2c30fbc2018-10-18 12:32:04 +0000820void ClangdLSPServer::onRename(const RenameParams &Params,
821 Callback<WorkspaceEdit> Reply) {
Benjamin Krameradcd0262020-01-28 20:23:46 +0100822 Path File = std::string(Params.textDocument.uri.file());
Sam McCallcaf5a4d2020-03-03 15:57:39 +0100823 if (!DraftMgr.getDraft(File))
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000824 return Reply(llvm::make_error<LSPError>(
825 "onRename called for non-added file", ErrorCode::InvalidParams));
Haojian Wu852bafa2019-10-23 14:40:20 +0200826 Server->rename(
Sam McCall7ba07792020-09-29 10:37:46 +0200827 File, Params.position, Params.newName, Opts.Rename,
Haojian Wu852bafa2019-10-23 14:40:20 +0200828 [File, Params, Reply = std::move(Reply),
Haojian Wu0f0cbcc2020-10-02 16:01:25 +0200829 this](llvm::Expected<RenameResult> R) mutable {
830 if (!R)
831 return Reply(R.takeError());
832 if (auto Err = validateEdits(DraftMgr, R->GlobalChanges))
Haojian Wu852bafa2019-10-23 14:40:20 +0200833 return Reply(std::move(Err));
834 WorkspaceEdit Result;
835 Result.changes.emplace();
Haojian Wu0f0cbcc2020-10-02 16:01:25 +0200836 for (const auto &Rep : R->GlobalChanges) {
Haojian Wu852bafa2019-10-23 14:40:20 +0200837 (*Result.changes)[URI::createFile(Rep.first()).toString()] =
838 Rep.second.asTextEdits();
839 }
840 Reply(Result);
841 });
Haojian Wu345099c2017-11-09 11:30:04 +0000842}
843
Sam McCall2c30fbc2018-10-18 12:32:04 +0000844void ClangdLSPServer::onDocumentDidClose(
845 const DidCloseTextDocumentParams &Params) {
Simon Marchi9569fd52018-03-16 14:30:42 +0000846 PathRef File = Params.textDocument.uri.file();
847 DraftMgr.removeDraft(File);
Ilya Biryukov652364b2018-09-26 05:48:29 +0000848 Server->removeDocument(File);
Ilya Biryukov49c10712019-03-25 10:15:11 +0000849
850 {
851 std::lock_guard<std::mutex> Lock(FixItsMutex);
852 FixItsMap.erase(File);
853 }
Johan Vikstromc2653ef22019-08-01 08:08:44 +0000854 {
855 std::lock_guard<std::mutex> HLock(HighlightingsMutex);
856 FileToHighlightings.erase(File);
857 }
Sam McCall9e3063e2020-04-01 16:21:44 +0200858 {
859 std::lock_guard<std::mutex> HLock(SemanticTokensMutex);
860 LastSemanticTokens.erase(File);
861 }
Ilya Biryukov49c10712019-03-25 10:15:11 +0000862 // clangd will not send updates for this file anymore, so we empty out the
863 // list of diagnostics shown on the client (e.g. in the "Problems" pane of
864 // VSCode). Note that this cannot race with actual diagnostics responses
865 // because removeDocument() guarantees no diagnostic callbacks will be
866 // executed after it returns.
Sam McCall6525a6b2020-03-03 12:44:40 +0100867 PublishDiagnosticsParams Notification;
868 Notification.uri = URIForFile::canonicalize(File, /*TUPath=*/File);
869 publishDiagnostics(Notification);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000870}
871
Sam McCall4db732a2017-09-30 10:08:52 +0000872void ClangdLSPServer::onDocumentOnTypeFormatting(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000873 const DocumentOnTypeFormattingParams &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 "onDocumentOnTypeFormatting 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->formatOnType(File, Code->Contents, Params.position, Params.ch,
883 std::move(Reply));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000884}
885
Sam McCall4db732a2017-09-30 10:08:52 +0000886void ClangdLSPServer::onDocumentRangeFormatting(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000887 const DocumentRangeFormattingParams &Params,
888 Callback<std::vector<TextEdit>> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000889 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000890 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000891 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000892 return Reply(llvm::make_error<LSPError>(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000893 "onDocumentRangeFormatting called for non-added file",
894 ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000895
Sam McCallffa63dd2020-06-26 12:57:29 +0200896 Server->formatRange(
897 File, Code->Contents, Params.range,
898 [Code = Code->Contents, Reply = std::move(Reply)](
899 llvm::Expected<tooling::Replacements> Result) mutable {
900 if (Result)
901 Reply(replacementsToEdits(Code, Result.get()));
902 else
903 Reply(Result.takeError());
904 });
Ilya Biryukovafb55542017-05-16 14:40:30 +0000905}
906
Sam McCall2c30fbc2018-10-18 12:32:04 +0000907void ClangdLSPServer::onDocumentFormatting(
908 const DocumentFormattingParams &Params,
909 Callback<std::vector<TextEdit>> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000910 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000911 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000912 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000913 return Reply(llvm::make_error<LSPError>(
914 "onDocumentFormatting called for non-added file",
915 ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000916
Sam McCallffa63dd2020-06-26 12:57:29 +0200917 Server->formatFile(File, Code->Contents,
918 [Code = Code->Contents, Reply = std::move(Reply)](
919 llvm::Expected<tooling::Replacements> Result) mutable {
920 if (Result)
921 Reply(replacementsToEdits(Code, Result.get()));
922 else
923 Reply(Result.takeError());
924 });
Sam McCall4db732a2017-09-30 10:08:52 +0000925}
926
Ilya Biryukov19d75602018-11-23 15:21:19 +0000927/// The functions constructs a flattened view of the DocumentSymbol hierarchy.
928/// Used by the clients that do not support the hierarchical view.
929static std::vector<SymbolInformation>
930flattenSymbolHierarchy(llvm::ArrayRef<DocumentSymbol> Symbols,
931 const URIForFile &FileURI) {
Ilya Biryukov19d75602018-11-23 15:21:19 +0000932 std::vector<SymbolInformation> Results;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000933 std::function<void(const DocumentSymbol &, llvm::StringRef)> Process =
934 [&](const DocumentSymbol &S, llvm::Optional<llvm::StringRef> ParentName) {
Ilya Biryukov19d75602018-11-23 15:21:19 +0000935 SymbolInformation SI;
Benjamin Krameradcd0262020-01-28 20:23:46 +0100936 SI.containerName = std::string(ParentName ? "" : *ParentName);
Ilya Biryukov19d75602018-11-23 15:21:19 +0000937 SI.name = S.name;
938 SI.kind = S.kind;
939 SI.location.range = S.range;
940 SI.location.uri = FileURI;
941
942 Results.push_back(std::move(SI));
943 std::string FullName =
944 !ParentName ? S.name : (ParentName->str() + "::" + S.name);
945 for (auto &C : S.children)
946 Process(C, /*ParentName=*/FullName);
947 };
948 for (auto &S : Symbols)
949 Process(S, /*ParentName=*/"");
950 return Results;
951}
952
953void ClangdLSPServer::onDocumentSymbol(const DocumentSymbolParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000954 Callback<llvm::json::Value> Reply) {
Ilya Biryukov19d75602018-11-23 15:21:19 +0000955 URIForFile FileURI = Params.textDocument.uri;
Ilya Biryukov652364b2018-09-26 05:48:29 +0000956 Server->documentSymbols(
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000957 Params.textDocument.uri.file(),
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000958 [this, FileURI, Reply = std::move(Reply)](
959 llvm::Expected<std::vector<DocumentSymbol>> Items) mutable {
960 if (!Items)
961 return Reply(Items.takeError());
962 adjustSymbolKinds(*Items, SupportedSymbolKinds);
963 if (SupportsHierarchicalDocumentSymbol)
964 return Reply(std::move(*Items));
965 else
966 return Reply(flattenSymbolHierarchy(*Items, FileURI));
967 });
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000968}
969
Kirill Bobyrev7a514c92020-07-14 09:28:38 +0200970void ClangdLSPServer::onFoldingRange(
971 const FoldingRangeParams &Params,
972 Callback<std::vector<FoldingRange>> Reply) {
973 Server->foldingRanges(Params.textDocument.uri.file(), std::move(Reply));
974}
975
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000976static llvm::Optional<Command> asCommand(const CodeAction &Action) {
Sam McCall20841d42018-10-16 16:29:41 +0000977 Command Cmd;
978 if (Action.command && Action.edit)
Sam McCallc008af62018-10-20 15:30:37 +0000979 return None; // Not representable. (We never emit these anyway).
Sam McCall20841d42018-10-16 16:29:41 +0000980 if (Action.command) {
981 Cmd = *Action.command;
982 } else if (Action.edit) {
Benjamin Krameradcd0262020-01-28 20:23:46 +0100983 Cmd.command = std::string(Command::CLANGD_APPLY_FIX_COMMAND);
Sam McCall20841d42018-10-16 16:29:41 +0000984 Cmd.workspaceEdit = *Action.edit;
985 } else {
Sam McCallc008af62018-10-20 15:30:37 +0000986 return None;
Sam McCall20841d42018-10-16 16:29:41 +0000987 }
988 Cmd.title = Action.title;
989 if (Action.kind && *Action.kind == CodeAction::QUICKFIX_KIND)
990 Cmd.title = "Apply fix: " + Cmd.title;
991 return Cmd;
992}
993
Sam McCall2c30fbc2018-10-18 12:32:04 +0000994void ClangdLSPServer::onCodeAction(const CodeActionParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000995 Callback<llvm::json::Value> Reply) {
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000996 URIForFile File = Params.textDocument.uri;
997 auto Code = DraftMgr.getDraft(File.file());
Sam McCall2c30fbc2018-10-18 12:32:04 +0000998 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000999 return Reply(llvm::make_error<LSPError>(
1000 "onCodeAction called for non-added file", ErrorCode::InvalidParams));
Sam McCall5627ae62020-10-09 15:17:26 +02001001
1002 // Checks whether a particular CodeActionKind is included in the response.
1003 auto KindAllowed = [Only(Params.context.only)](llvm::StringRef Kind) {
1004 if (Only.empty())
1005 return true;
1006 return llvm::any_of(Only, [&](llvm::StringRef Base) {
1007 return Kind.consume_front(Base) && (Kind.empty() || Kind.startswith("."));
1008 });
1009 };
1010
Sam McCall20841d42018-10-16 16:29:41 +00001011 // We provide a code action for Fixes on the specified diagnostics.
Ilya Biryukovcce67a32019-01-29 14:17:36 +00001012 std::vector<CodeAction> FixIts;
Sam McCall5627ae62020-10-09 15:17:26 +02001013 if (KindAllowed(CodeAction::QUICKFIX_KIND)) {
1014 for (const Diagnostic &D : Params.context.diagnostics) {
1015 for (auto &F : getFixes(File.file(), D)) {
1016 FixIts.push_back(toCodeAction(F, Params.textDocument.uri));
1017 FixIts.back().diagnostics = {D};
1018 }
Sam McCalldd0566b2017-11-06 15:40:30 +00001019 }
Ilya Biryukovafb55542017-05-16 14:40:30 +00001020 }
Sam McCall20841d42018-10-16 16:29:41 +00001021
Ilya Biryukovcce67a32019-01-29 14:17:36 +00001022 // Now enumerate the semantic code actions.
1023 auto ConsumeActions =
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001024 [Reply = std::move(Reply), File, Code = std::move(*Code),
1025 Selection = Params.range, FixIts = std::move(FixIts), this](
1026 llvm::Expected<std::vector<ClangdServer::TweakRef>> Tweaks) mutable {
Ilya Biryukovc6ed7782019-01-30 14:24:17 +00001027 if (!Tweaks)
1028 return Reply(Tweaks.takeError());
Ilya Biryukovcce67a32019-01-29 14:17:36 +00001029
1030 std::vector<CodeAction> Actions = std::move(FixIts);
1031 Actions.reserve(Actions.size() + Tweaks->size());
1032 for (const auto &T : *Tweaks)
1033 Actions.push_back(toCodeAction(T, File, Selection));
1034
Sam McCall83926852020-09-29 16:28:50 +02001035 // If there's exactly one quick-fix, call it "preferred".
1036 // We never consider refactorings etc as preferred.
1037 CodeAction *OnlyFix = nullptr;
1038 for (auto &Action : Actions) {
1039 if (Action.kind && *Action.kind == CodeAction::QUICKFIX_KIND) {
1040 if (OnlyFix) {
1041 OnlyFix->isPreferred = false;
1042 break;
1043 }
1044 Action.isPreferred = true;
1045 OnlyFix = &Action;
1046 }
1047 }
1048
Ilya Biryukovcce67a32019-01-29 14:17:36 +00001049 if (SupportsCodeAction)
1050 return Reply(llvm::json::Array(Actions));
1051 std::vector<Command> Commands;
1052 for (const auto &Action : Actions) {
1053 if (auto Command = asCommand(Action))
1054 Commands.push_back(std::move(*Command));
1055 }
1056 return Reply(llvm::json::Array(Commands));
1057 };
Sam McCall7530b252020-10-02 11:34:40 +02001058 Server->enumerateTweaks(
1059 File.file(), Params.range,
Sam McCall5627ae62020-10-09 15:17:26 +02001060 [this, KindAllowed(std::move(KindAllowed))](const Tweak &T) {
1061 return Opts.TweakFilter(T) && KindAllowed(T.kind());
Sam McCall7530b252020-10-02 11:34:40 +02001062 },
1063 std::move(ConsumeActions));
Ilya Biryukovafb55542017-05-16 14:40:30 +00001064}
1065
Ilya Biryukovb0826bd2019-01-03 13:37:12 +00001066void ClangdLSPServer::onCompletion(const CompletionParams &Params,
Sam McCall2c30fbc2018-10-18 12:32:04 +00001067 Callback<CompletionList> Reply) {
Ilya Biryukova7a11472019-06-07 16:24:38 +00001068 if (!shouldRunCompletion(Params)) {
1069 // Clients sometimes auto-trigger completions in undesired places (e.g.
1070 // 'a >^ '), we return empty results in those cases.
1071 vlog("ignored auto-triggered completion, preceding char did not match");
1072 return Reply(CompletionList());
1073 }
Kadir Cetinkaya94076862020-10-12 14:24:05 +02001074 Server->codeComplete(
1075 Params.textDocument.uri.file(), Params.position, Opts.CodeComplete,
1076 [Reply = std::move(Reply),
1077 this](llvm::Expected<CodeCompleteResult> List) mutable {
1078 if (!List)
1079 return Reply(List.takeError());
1080 CompletionList LSPList;
1081 LSPList.isIncomplete = List->HasMore;
1082 for (const auto &R : List->Completions) {
1083 CompletionItem C = R.render(Opts.CodeComplete);
1084 C.kind = adjustKindToCapability(C.kind, SupportedCompletionItemKinds);
1085 LSPList.items.push_back(std::move(C));
1086 }
1087 return Reply(std::move(LSPList));
1088 });
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +00001089}
1090
Sam McCall2c30fbc2018-10-18 12:32:04 +00001091void ClangdLSPServer::onSignatureHelp(const TextDocumentPositionParams &Params,
1092 Callback<SignatureHelp> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +00001093 Server->signatureHelp(Params.textDocument.uri.file(), Params.position,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001094 [Reply = std::move(Reply), this](
1095 llvm::Expected<SignatureHelp> Signature) mutable {
1096 if (!Signature)
1097 return Reply(Signature.takeError());
1098 if (SupportsOffsetsInSignatureHelp)
1099 return Reply(std::move(*Signature));
1100 // Strip out the offsets from signature help for
1101 // clients that only support string labels.
1102 for (auto &SigInfo : Signature->signatures) {
1103 for (auto &Param : SigInfo.parameters)
1104 Param.labelOffsets.reset();
1105 }
1106 return Reply(std::move(*Signature));
1107 });
Ilya Biryukov652364b2018-09-26 05:48:29 +00001108}
1109
Sam McCall0dbab7f2019-02-02 05:56:00 +00001110// Go to definition has a toggle function: if def and decl are distinct, then
1111// the first press gives you the def, the second gives you the matching def.
1112// getToggle() returns the counterpart location that under the cursor.
1113//
1114// We return the toggled location alone (ignoring other symbols) to encourage
1115// editors to "bounce" quickly between locations, without showing a menu.
1116static Location *getToggle(const TextDocumentPositionParams &Point,
1117 LocatedSymbol &Sym) {
1118 // Toggle only makes sense with two distinct locations.
1119 if (!Sym.Definition || *Sym.Definition == Sym.PreferredDeclaration)
1120 return nullptr;
1121 if (Sym.Definition->uri.file() == Point.textDocument.uri.file() &&
1122 Sym.Definition->range.contains(Point.position))
1123 return &Sym.PreferredDeclaration;
1124 if (Sym.PreferredDeclaration.uri.file() == Point.textDocument.uri.file() &&
1125 Sym.PreferredDeclaration.range.contains(Point.position))
1126 return &*Sym.Definition;
1127 return nullptr;
1128}
1129
Sam McCall2c30fbc2018-10-18 12:32:04 +00001130void ClangdLSPServer::onGoToDefinition(const TextDocumentPositionParams &Params,
1131 Callback<std::vector<Location>> Reply) {
Sam McCall866ba2c2019-02-01 11:26:13 +00001132 Server->locateSymbolAt(
1133 Params.textDocument.uri.file(), Params.position,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001134 [Params, Reply = std::move(Reply)](
1135 llvm::Expected<std::vector<LocatedSymbol>> Symbols) mutable {
1136 if (!Symbols)
1137 return Reply(Symbols.takeError());
1138 std::vector<Location> Defs;
1139 for (auto &S : *Symbols) {
1140 if (Location *Toggle = getToggle(Params, S))
1141 return Reply(std::vector<Location>{std::move(*Toggle)});
1142 Defs.push_back(S.Definition.getValueOr(S.PreferredDeclaration));
1143 }
1144 Reply(std::move(Defs));
1145 });
Sam McCall866ba2c2019-02-01 11:26:13 +00001146}
1147
1148void ClangdLSPServer::onGoToDeclaration(
1149 const TextDocumentPositionParams &Params,
1150 Callback<std::vector<Location>> Reply) {
1151 Server->locateSymbolAt(
1152 Params.textDocument.uri.file(), Params.position,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001153 [Params, Reply = std::move(Reply)](
1154 llvm::Expected<std::vector<LocatedSymbol>> Symbols) mutable {
1155 if (!Symbols)
1156 return Reply(Symbols.takeError());
1157 std::vector<Location> Decls;
1158 for (auto &S : *Symbols) {
1159 if (Location *Toggle = getToggle(Params, S))
1160 return Reply(std::vector<Location>{std::move(*Toggle)});
1161 Decls.push_back(std::move(S.PreferredDeclaration));
1162 }
1163 Reply(std::move(Decls));
1164 });
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +00001165}
1166
Sam McCall111fe842019-05-07 07:55:35 +00001167void ClangdLSPServer::onSwitchSourceHeader(
1168 const TextDocumentIdentifier &Params,
Sam McCallb9ec3e92019-05-07 08:30:32 +00001169 Callback<llvm::Optional<URIForFile>> Reply) {
Haojian Wud6d5edd2019-10-01 10:21:15 +00001170 Server->switchSourceHeader(
1171 Params.uri.file(),
1172 [Reply = std::move(Reply),
1173 Params](llvm::Expected<llvm::Optional<clangd::Path>> Path) mutable {
1174 if (!Path)
1175 return Reply(Path.takeError());
1176 if (*Path)
Haojian Wu77c97002019-10-07 11:37:25 +00001177 return Reply(URIForFile::canonicalize(**Path, Params.uri.file()));
Haojian Wud6d5edd2019-10-01 10:21:15 +00001178 return Reply(llvm::None);
1179 });
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +00001180}
1181
Sam McCall2c30fbc2018-10-18 12:32:04 +00001182void ClangdLSPServer::onDocumentHighlight(
1183 const TextDocumentPositionParams &Params,
1184 Callback<std::vector<DocumentHighlight>> Reply) {
1185 Server->findDocumentHighlights(Params.textDocument.uri.file(),
1186 Params.position, std::move(Reply));
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +00001187}
1188
Sam McCall2c30fbc2018-10-18 12:32:04 +00001189void ClangdLSPServer::onHover(const TextDocumentPositionParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001190 Callback<llvm::Optional<Hover>> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +00001191 Server->findHover(Params.textDocument.uri.file(), Params.position,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001192 [Reply = std::move(Reply), this](
1193 llvm::Expected<llvm::Optional<HoverInfo>> H) mutable {
1194 if (!H)
1195 return Reply(H.takeError());
1196 if (!*H)
1197 return Reply(llvm::None);
Ilya Biryukovf9169d02019-05-29 10:01:00 +00001198
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001199 Hover R;
1200 R.contents.kind = HoverContentFormat;
1201 R.range = (*H)->SymRange;
1202 switch (HoverContentFormat) {
1203 case MarkupKind::PlainText:
Kadir Cetinkaya597c6b62019-12-10 10:28:37 +01001204 R.contents.value = (*H)->present().asPlainText();
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001205 return Reply(std::move(R));
1206 case MarkupKind::Markdown:
Kadir Cetinkaya597c6b62019-12-10 10:28:37 +01001207 R.contents.value = (*H)->present().asMarkdown();
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001208 return Reply(std::move(R));
1209 };
1210 llvm_unreachable("unhandled MarkupKind");
1211 });
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +00001212}
1213
Kadir Cetinkaya86658022019-03-19 09:27:04 +00001214void ClangdLSPServer::onTypeHierarchy(
1215 const TypeHierarchyParams &Params,
1216 Callback<Optional<TypeHierarchyItem>> Reply) {
1217 Server->typeHierarchy(Params.textDocument.uri.file(), Params.position,
1218 Params.resolve, Params.direction, std::move(Reply));
1219}
1220
Nathan Ridge087b0442019-07-13 03:24:48 +00001221void ClangdLSPServer::onResolveTypeHierarchy(
1222 const ResolveTypeHierarchyItemParams &Params,
1223 Callback<Optional<TypeHierarchyItem>> Reply) {
1224 Server->resolveTypeHierarchy(Params.item, Params.resolve, Params.direction,
1225 std::move(Reply));
1226}
1227
Nathan Ridge0a4f99c2020-11-15 22:45:17 -05001228void ClangdLSPServer::onPrepareCallHierarchy(
1229 const CallHierarchyPrepareParams &Params,
1230 Callback<std::vector<CallHierarchyItem>> Reply) {
1231 Server->prepareCallHierarchy(Params.textDocument.uri.file(), Params.position,
1232 std::move(Reply));
1233}
1234
1235void ClangdLSPServer::onCallHierarchyIncomingCalls(
1236 const CallHierarchyIncomingCallsParams &Params,
1237 Callback<std::vector<CallHierarchyIncomingCall>> Reply) {
1238 Server->incomingCalls(Params.item, std::move(Reply));
1239}
1240
1241void ClangdLSPServer::onCallHierarchyOutgoingCalls(
1242 const CallHierarchyOutgoingCallsParams &Params,
1243 Callback<std::vector<CallHierarchyOutgoingCall>> Reply) {
1244 // FIXME: To be implemented.
1245 Reply(std::vector<CallHierarchyOutgoingCall>{});
1246}
1247
Simon Marchi88016782018-08-01 11:28:49 +00001248void ClangdLSPServer::applyConfiguration(
Sam McCallbc904612018-10-25 04:22:52 +00001249 const ConfigurationSettings &Settings) {
Simon Marchiabeed662018-10-16 15:55:03 +00001250 // Per-file update to the compilation database.
David Goldman60249c22020-01-13 17:01:10 -05001251 llvm::StringSet<> ModifiedFiles;
Sam McCallbc904612018-10-25 04:22:52 +00001252 for (auto &Entry : Settings.compilationDatabaseChanges) {
Sam McCallbc904612018-10-25 04:22:52 +00001253 PathRef File = Entry.first;
Sam McCallc55d09a2018-11-02 13:09:36 +00001254 auto Old = CDB->getCompileCommand(File);
1255 auto New =
1256 tooling::CompileCommand(std::move(Entry.second.workingDirectory), File,
1257 std::move(Entry.second.compilationCommand),
1258 /*Output=*/"");
Sam McCall6980edb2018-11-02 14:07:51 +00001259 if (Old != New) {
Sam McCallc55d09a2018-11-02 13:09:36 +00001260 CDB->setCompileCommand(File, std::move(New));
David Goldman60249c22020-01-13 17:01:10 -05001261 ModifiedFiles.insert(File);
Sam McCall6980edb2018-11-02 14:07:51 +00001262 }
Alex Lorenzf8087862018-08-01 17:39:29 +00001263 }
David Goldman60249c22020-01-13 17:01:10 -05001264
Sam McCall596b63a2020-04-10 03:27:37 +02001265 reparseOpenFilesIfNeeded(
1266 [&](llvm::StringRef File) { return ModifiedFiles.count(File) != 0; });
Simon Marchi5178f922018-02-22 14:00:39 +00001267}
1268
Sam McCalledf6a192020-03-24 00:31:14 +01001269void ClangdLSPServer::publishTheiaSemanticHighlighting(
1270 const TheiaSemanticHighlightingParams &Params) {
Johan Vikstroma848dab2019-07-04 07:53:12 +00001271 notify("textDocument/semanticHighlighting", Params);
1272}
1273
Ilya Biryukov49c10712019-03-25 10:15:11 +00001274void ClangdLSPServer::publishDiagnostics(
Sam McCall6525a6b2020-03-03 12:44:40 +01001275 const PublishDiagnosticsParams &Params) {
1276 notify("textDocument/publishDiagnostics", Params);
Ilya Biryukov49c10712019-03-25 10:15:11 +00001277}
1278
Kadir Cetinkaya35871fd2020-09-28 15:09:55 +02001279void ClangdLSPServer::maybeExportMemoryProfile() {
1280 if (!trace::enabled())
1281 return;
1282 // Profiling might be expensive, so we throttle it to happen once every 5
1283 // minutes.
1284 static constexpr auto ProfileInterval = std::chrono::minutes(5);
1285 auto Now = std::chrono::steady_clock::now();
1286 if (Now < NextProfileTime)
1287 return;
1288
1289 static constexpr trace::Metric MemoryUsage(
1290 "memory_usage", trace::Metric::Value, "component_name");
1291 trace::Span Tracer("ProfileBrief");
1292 MemoryTree MT;
1293 profile(MT);
1294 record(MT, "clangd_lsp_server", MemoryUsage);
1295 NextProfileTime = Now + ProfileInterval;
1296}
1297
Simon Marchi88016782018-08-01 11:28:49 +00001298// FIXME: This function needs to be properly tested.
1299void ClangdLSPServer::onChangeConfiguration(
Sam McCall2c30fbc2018-10-18 12:32:04 +00001300 const DidChangeConfigurationParams &Params) {
Simon Marchi88016782018-08-01 11:28:49 +00001301 applyConfiguration(Params.settings);
1302}
1303
Sam McCall2c30fbc2018-10-18 12:32:04 +00001304void ClangdLSPServer::onReference(const ReferenceParams &Params,
1305 Callback<std::vector<Location>> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +00001306 Server->findReferences(Params.textDocument.uri.file(), Params.position,
Sam McCall7ba07792020-09-29 10:37:46 +02001307 Opts.CodeComplete.Limit,
Haojian Wu5181ada2019-11-18 11:35:00 +01001308 [Reply = std::move(Reply)](
1309 llvm::Expected<ReferencesResult> Refs) mutable {
1310 if (!Refs)
1311 return Reply(Refs.takeError());
1312 return Reply(std::move(Refs->References));
1313 });
Sam McCall1ad142f2018-09-05 11:53:07 +00001314}
1315
Utkarsh Saxenab31486a2020-11-18 13:25:09 +01001316void ClangdLSPServer::onGoToImplementation(
1317 const TextDocumentPositionParams &Params,
1318 Callback<std::vector<Location>> Reply) {
1319 Server->findImplementations(
1320 Params.textDocument.uri.file(), Params.position,
1321 [Reply = std::move(Reply)](
1322 llvm::Expected<std::vector<LocatedSymbol>> Overrides) mutable {
1323 if (!Overrides)
1324 return Reply(Overrides.takeError());
1325 std::vector<Location> Impls;
1326 for (const LocatedSymbol &Sym : *Overrides)
1327 Impls.push_back(Sym.PreferredDeclaration);
1328 return Reply(std::move(Impls));
1329 });
1330}
1331
Jan Korousb4067012018-11-27 16:40:46 +00001332void ClangdLSPServer::onSymbolInfo(const TextDocumentPositionParams &Params,
1333 Callback<std::vector<SymbolDetails>> Reply) {
1334 Server->symbolInfo(Params.textDocument.uri.file(), Params.position,
1335 std::move(Reply));
1336}
1337
Utkarsh Saxena55925da2019-09-24 13:38:33 +00001338void ClangdLSPServer::onSelectionRange(
1339 const SelectionRangeParams &Params,
1340 Callback<std::vector<SelectionRange>> Reply) {
Utkarsh Saxena55925da2019-09-24 13:38:33 +00001341 Server->semanticRanges(
Sam McCall8f237f92020-03-25 00:51:50 +01001342 Params.textDocument.uri.file(), Params.positions,
Utkarsh Saxena55925da2019-09-24 13:38:33 +00001343 [Reply = std::move(Reply)](
Sam McCall8f237f92020-03-25 00:51:50 +01001344 llvm::Expected<std::vector<SelectionRange>> Ranges) mutable {
1345 if (!Ranges)
Utkarsh Saxena55925da2019-09-24 13:38:33 +00001346 return Reply(Ranges.takeError());
Sam McCall8f237f92020-03-25 00:51:50 +01001347 return Reply(std::move(*Ranges));
Utkarsh Saxena55925da2019-09-24 13:38:33 +00001348 });
1349}
1350
Sam McCall8d7ecc12019-12-16 19:08:51 +01001351void ClangdLSPServer::onDocumentLink(
1352 const DocumentLinkParams &Params,
1353 Callback<std::vector<DocumentLink>> Reply) {
1354
1355 // TODO(forster): This currently resolves all targets eagerly. This is slow,
1356 // because it blocks on the preamble/AST being built. We could respond to the
1357 // request faster by using string matching or the lexer to find the includes
1358 // and resolving the targets lazily.
1359 Server->documentLinks(
1360 Params.textDocument.uri.file(),
1361 [Reply = std::move(Reply)](
1362 llvm::Expected<std::vector<DocumentLink>> Links) mutable {
1363 if (!Links) {
1364 return Reply(Links.takeError());
1365 }
1366 return Reply(std::move(Links));
1367 });
1368}
1369
Sam McCall9e3063e2020-04-01 16:21:44 +02001370// Increment a numeric string: "" -> 1 -> 2 -> ... -> 9 -> 10 -> 11 ...
1371static void increment(std::string &S) {
1372 for (char &C : llvm::reverse(S)) {
1373 if (C != '9') {
1374 ++C;
1375 return;
1376 }
1377 C = '0';
1378 }
1379 S.insert(S.begin(), '1');
1380}
1381
Sam McCall71177ac2020-03-24 02:24:47 +01001382void ClangdLSPServer::onSemanticTokens(const SemanticTokensParams &Params,
1383 Callback<SemanticTokens> CB) {
1384 Server->semanticHighlights(
1385 Params.textDocument.uri.file(),
Sam McCall9e3063e2020-04-01 16:21:44 +02001386 [this, File(Params.textDocument.uri.file().str()), CB(std::move(CB))](
1387 llvm::Expected<std::vector<HighlightingToken>> HT) mutable {
1388 if (!HT)
1389 return CB(HT.takeError());
Sam McCall71177ac2020-03-24 02:24:47 +01001390 SemanticTokens Result;
Sam McCall9e3063e2020-04-01 16:21:44 +02001391 Result.tokens = toSemanticTokens(*HT);
1392 {
1393 std::lock_guard<std::mutex> Lock(SemanticTokensMutex);
Kadir Cetinkayae64f99c2020-04-16 23:12:09 +02001394 auto &Last = LastSemanticTokens[File];
Sam McCall9e3063e2020-04-01 16:21:44 +02001395
1396 Last.tokens = Result.tokens;
1397 increment(Last.resultId);
1398 Result.resultId = Last.resultId;
1399 }
1400 CB(std::move(Result));
1401 });
1402}
1403
Sam McCall5fea54b2020-07-10 16:08:14 +02001404void ClangdLSPServer::onSemanticTokensDelta(
1405 const SemanticTokensDeltaParams &Params,
1406 Callback<SemanticTokensOrDelta> CB) {
Sam McCall9e3063e2020-04-01 16:21:44 +02001407 Server->semanticHighlights(
1408 Params.textDocument.uri.file(),
1409 [this, PrevResultID(Params.previousResultId),
1410 File(Params.textDocument.uri.file().str()), CB(std::move(CB))](
1411 llvm::Expected<std::vector<HighlightingToken>> HT) mutable {
1412 if (!HT)
1413 return CB(HT.takeError());
1414 std::vector<SemanticToken> Toks = toSemanticTokens(*HT);
1415
Sam McCall5fea54b2020-07-10 16:08:14 +02001416 SemanticTokensOrDelta Result;
Sam McCall9e3063e2020-04-01 16:21:44 +02001417 {
1418 std::lock_guard<std::mutex> Lock(SemanticTokensMutex);
Kadir Cetinkayae64f99c2020-04-16 23:12:09 +02001419 auto &Last = LastSemanticTokens[File];
Sam McCall9e3063e2020-04-01 16:21:44 +02001420
1421 if (PrevResultID == Last.resultId) {
1422 Result.edits = diffTokens(Last.tokens, Toks);
1423 } else {
Sam McCall5fea54b2020-07-10 16:08:14 +02001424 vlog("semanticTokens/full/delta: wanted edits vs {0} but last "
1425 "result had ID {1}. Returning full token list.",
Sam McCall9e3063e2020-04-01 16:21:44 +02001426 PrevResultID, Last.resultId);
1427 Result.tokens = Toks;
1428 }
1429
1430 Last.tokens = std::move(Toks);
1431 increment(Last.resultId);
1432 Result.resultId = Last.resultId;
1433 }
1434
Sam McCall71177ac2020-03-24 02:24:47 +01001435 CB(std::move(Result));
1436 });
1437}
1438
Kadir Cetinkayad0f28742020-10-13 00:10:04 +02001439void ClangdLSPServer::onMemoryUsage(const NoParams &,
1440 Callback<MemoryTree> Reply) {
1441 llvm::BumpPtrAllocator DetailAlloc;
1442 MemoryTree MT(&DetailAlloc);
1443 profile(MT);
1444 Reply(std::move(MT));
1445}
1446
Sam McCall8adc4d12020-10-16 20:03:48 +02001447void ClangdLSPServer::onAST(const ASTParams &Params,
1448 Callback<llvm::Optional<ASTNode>> CB) {
1449 Server->getAST(Params.textDocument.uri.file(), Params.range, std::move(CB));
1450}
1451
Sam McCall7ba07792020-09-29 10:37:46 +02001452ClangdLSPServer::ClangdLSPServer(class Transport &Transp,
1453 const ThreadsafeFS &TFS,
1454 const ClangdLSPServer::Options &Opts)
Kadir Cetinkaya9d662472019-10-15 14:20:52 +00001455 : BackgroundContext(Context::current().clone()), Transp(Transp),
Sam McCall7ba07792020-09-29 10:37:46 +02001456 MsgHandler(new MessageHandler(*this)), TFS(TFS),
1457 SupportedSymbolKinds(defaultSymbolKinds()),
1458 SupportedCompletionItemKinds(defaultCompletionItemKinds()), Opts(Opts) {
Sam McCall2c30fbc2018-10-18 12:32:04 +00001459 // clang-format off
1460 MsgHandler->bind("initialize", &ClangdLSPServer::onInitialize);
Sam McCall8a2d2942020-03-03 12:12:14 +01001461 MsgHandler->bind("initialized", &ClangdLSPServer::onInitialized);
Sam McCall2c30fbc2018-10-18 12:32:04 +00001462 MsgHandler->bind("shutdown", &ClangdLSPServer::onShutdown);
Sam McCall422c8282018-11-26 16:00:11 +00001463 MsgHandler->bind("sync", &ClangdLSPServer::onSync);
Sam McCall2c30fbc2018-10-18 12:32:04 +00001464 MsgHandler->bind("textDocument/rangeFormatting", &ClangdLSPServer::onDocumentRangeFormatting);
1465 MsgHandler->bind("textDocument/onTypeFormatting", &ClangdLSPServer::onDocumentOnTypeFormatting);
1466 MsgHandler->bind("textDocument/formatting", &ClangdLSPServer::onDocumentFormatting);
1467 MsgHandler->bind("textDocument/codeAction", &ClangdLSPServer::onCodeAction);
1468 MsgHandler->bind("textDocument/completion", &ClangdLSPServer::onCompletion);
1469 MsgHandler->bind("textDocument/signatureHelp", &ClangdLSPServer::onSignatureHelp);
1470 MsgHandler->bind("textDocument/definition", &ClangdLSPServer::onGoToDefinition);
Sam McCall866ba2c2019-02-01 11:26:13 +00001471 MsgHandler->bind("textDocument/declaration", &ClangdLSPServer::onGoToDeclaration);
Utkarsh Saxenab31486a2020-11-18 13:25:09 +01001472 MsgHandler->bind("textDocument/implementation", &ClangdLSPServer::onGoToImplementation);
Sam McCall2c30fbc2018-10-18 12:32:04 +00001473 MsgHandler->bind("textDocument/references", &ClangdLSPServer::onReference);
1474 MsgHandler->bind("textDocument/switchSourceHeader", &ClangdLSPServer::onSwitchSourceHeader);
Haojian Wuf429ab62019-07-24 07:49:23 +00001475 MsgHandler->bind("textDocument/prepareRename", &ClangdLSPServer::onPrepareRename);
Sam McCall2c30fbc2018-10-18 12:32:04 +00001476 MsgHandler->bind("textDocument/rename", &ClangdLSPServer::onRename);
1477 MsgHandler->bind("textDocument/hover", &ClangdLSPServer::onHover);
1478 MsgHandler->bind("textDocument/documentSymbol", &ClangdLSPServer::onDocumentSymbol);
1479 MsgHandler->bind("workspace/executeCommand", &ClangdLSPServer::onCommand);
1480 MsgHandler->bind("textDocument/documentHighlight", &ClangdLSPServer::onDocumentHighlight);
1481 MsgHandler->bind("workspace/symbol", &ClangdLSPServer::onWorkspaceSymbol);
Sam McCall8adc4d12020-10-16 20:03:48 +02001482 MsgHandler->bind("textDocument/ast", &ClangdLSPServer::onAST);
Sam McCall2c30fbc2018-10-18 12:32:04 +00001483 MsgHandler->bind("textDocument/didOpen", &ClangdLSPServer::onDocumentDidOpen);
1484 MsgHandler->bind("textDocument/didClose", &ClangdLSPServer::onDocumentDidClose);
1485 MsgHandler->bind("textDocument/didChange", &ClangdLSPServer::onDocumentDidChange);
Sam McCall596b63a2020-04-10 03:27:37 +02001486 MsgHandler->bind("textDocument/didSave", &ClangdLSPServer::onDocumentDidSave);
Sam McCall2c30fbc2018-10-18 12:32:04 +00001487 MsgHandler->bind("workspace/didChangeWatchedFiles", &ClangdLSPServer::onFileEvent);
1488 MsgHandler->bind("workspace/didChangeConfiguration", &ClangdLSPServer::onChangeConfiguration);
Jan Korousb4067012018-11-27 16:40:46 +00001489 MsgHandler->bind("textDocument/symbolInfo", &ClangdLSPServer::onSymbolInfo);
Kadir Cetinkaya86658022019-03-19 09:27:04 +00001490 MsgHandler->bind("textDocument/typeHierarchy", &ClangdLSPServer::onTypeHierarchy);
Nathan Ridge087b0442019-07-13 03:24:48 +00001491 MsgHandler->bind("typeHierarchy/resolve", &ClangdLSPServer::onResolveTypeHierarchy);
Nathan Ridge0a4f99c2020-11-15 22:45:17 -05001492 MsgHandler->bind("textDocument/prepareCallHierarchy", &ClangdLSPServer::onPrepareCallHierarchy);
1493 MsgHandler->bind("callHierarchy/incomingCalls", &ClangdLSPServer::onCallHierarchyIncomingCalls);
1494 MsgHandler->bind("callHierarchy/outgoingCalls", &ClangdLSPServer::onCallHierarchyOutgoingCalls);
Utkarsh Saxena55925da2019-09-24 13:38:33 +00001495 MsgHandler->bind("textDocument/selectionRange", &ClangdLSPServer::onSelectionRange);
Sam McCall8d7ecc12019-12-16 19:08:51 +01001496 MsgHandler->bind("textDocument/documentLink", &ClangdLSPServer::onDocumentLink);
Sam McCall5fea54b2020-07-10 16:08:14 +02001497 MsgHandler->bind("textDocument/semanticTokens/full", &ClangdLSPServer::onSemanticTokens);
1498 MsgHandler->bind("textDocument/semanticTokens/full/delta", &ClangdLSPServer::onSemanticTokensDelta);
Kadir Cetinkayad0f28742020-10-13 00:10:04 +02001499 MsgHandler->bind("$/memoryUsage", &ClangdLSPServer::onMemoryUsage);
Kirill Bobyrev7a514c92020-07-14 09:28:38 +02001500 if (Opts.FoldingRanges)
1501 MsgHandler->bind("textDocument/foldingRange", &ClangdLSPServer::onFoldingRange);
Sam McCall2c30fbc2018-10-18 12:32:04 +00001502 // clang-format on
Kadir Cetinkaya35871fd2020-09-28 15:09:55 +02001503
1504 // Delay first profile until we've finished warming up.
1505 NextProfileTime = std::chrono::steady_clock::now() + std::chrono::minutes(1);
Sam McCall2c30fbc2018-10-18 12:32:04 +00001506}
1507
Kadir Cetinkaya6b850322020-03-17 19:08:23 +01001508ClangdLSPServer::~ClangdLSPServer() {
1509 IsBeingDestroyed = true;
Sam McCall8bda5f22019-10-23 11:11:18 +02001510 // Explicitly destroy ClangdServer first, blocking on threads it owns.
1511 // This ensures they don't access any other members.
1512 Server.reset();
1513}
Ilya Biryukov38d79772017-05-16 09:38:59 +00001514
Sam McCalldc8f3cf2018-10-17 07:32:05 +00001515bool ClangdLSPServer::run() {
Ilya Biryukovafb55542017-05-16 14:40:30 +00001516 // Run the Language Server loop.
Sam McCalldc8f3cf2018-10-17 07:32:05 +00001517 bool CleanExit = true;
Sam McCall2c30fbc2018-10-18 12:32:04 +00001518 if (auto Err = Transp.loop(*MsgHandler)) {
Sam McCalldc8f3cf2018-10-17 07:32:05 +00001519 elog("Transport error: {0}", std::move(Err));
1520 CleanExit = false;
1521 }
Ilya Biryukovafb55542017-05-16 14:40:30 +00001522
Sam McCalldc8f3cf2018-10-17 07:32:05 +00001523 return CleanExit && ShutdownRequestReceived;
Ilya Biryukov38d79772017-05-16 09:38:59 +00001524}
1525
Kadir Cetinkaya35871fd2020-09-28 15:09:55 +02001526void ClangdLSPServer::profile(MemoryTree &MT) const {
1527 if (Server)
1528 Server->profile(MT.child("clangd_server"));
1529}
1530
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001531std::vector<Fix> ClangdLSPServer::getFixes(llvm::StringRef File,
Ilya Biryukov71028b82018-03-12 15:28:22 +00001532 const clangd::Diagnostic &D) {
Ilya Biryukov38d79772017-05-16 09:38:59 +00001533 std::lock_guard<std::mutex> Lock(FixItsMutex);
1534 auto DiagToFixItsIter = FixItsMap.find(File);
1535 if (DiagToFixItsIter == FixItsMap.end())
1536 return {};
1537
1538 const auto &DiagToFixItsMap = DiagToFixItsIter->second;
1539 auto FixItsIter = DiagToFixItsMap.find(D);
1540 if (FixItsIter == DiagToFixItsMap.end())
1541 return {};
1542
1543 return FixItsIter->second;
1544}
1545
Sam McCall032727f2020-05-06 01:39:59 +02001546// A completion request is sent when the user types '>' or ':', but we only
1547// want to trigger on '->' and '::'. We check the preceeding text to make
1548// sure it matches what we expected.
1549// Running the lexer here would be more robust (e.g. we can detect comments
1550// and avoid triggering completion there), but we choose to err on the side
1551// of simplicity here.
Ilya Biryukovb0826bd2019-01-03 13:37:12 +00001552bool ClangdLSPServer::shouldRunCompletion(
1553 const CompletionParams &Params) const {
Sam McCall032727f2020-05-06 01:39:59 +02001554 if (Params.context.triggerKind != CompletionTriggerKind::TriggerCharacter)
Ilya Biryukovb0826bd2019-01-03 13:37:12 +00001555 return true;
Ilya Biryukovb0826bd2019-01-03 13:37:12 +00001556 auto Code = DraftMgr.getDraft(Params.textDocument.uri.file());
1557 if (!Code)
1558 return true; // completion code will log the error for untracked doc.
Sam McCallcaf5a4d2020-03-03 15:57:39 +01001559 auto Offset = positionToOffset(Code->Contents, Params.position,
Ilya Biryukovb0826bd2019-01-03 13:37:12 +00001560 /*AllowColumnsBeyondLineLength=*/false);
1561 if (!Offset) {
1562 vlog("could not convert position '{0}' to offset for file '{1}'",
1563 Params.position, Params.textDocument.uri.file());
1564 return true;
1565 }
Sam McCall032727f2020-05-06 01:39:59 +02001566 return allowImplicitCompletion(Code->Contents, *Offset);
Ilya Biryukovb0826bd2019-01-03 13:37:12 +00001567}
1568
Johan Vikstroma848dab2019-07-04 07:53:12 +00001569void ClangdLSPServer::onHighlightingsReady(
Sam McCall2cd33e62020-03-04 00:33:29 +01001570 PathRef File, llvm::StringRef Version,
1571 std::vector<HighlightingToken> Highlightings) {
Johan Vikstromc2653ef22019-08-01 08:08:44 +00001572 std::vector<HighlightingToken> Old;
1573 std::vector<HighlightingToken> HighlightingsCopy = Highlightings;
1574 {
1575 std::lock_guard<std::mutex> Lock(HighlightingsMutex);
1576 Old = std::move(FileToHighlightings[File]);
1577 FileToHighlightings[File] = std::move(HighlightingsCopy);
1578 }
1579 // LSP allows us to send incremental edits of highlightings. Also need to diff
1580 // to remove highlightings from tokens that should no longer have them.
Haojian Wu0a6000f2019-08-26 08:38:45 +00001581 std::vector<LineHighlightings> Diffed = diffHighlightings(Highlightings, Old);
Sam McCalledf6a192020-03-24 00:31:14 +01001582 TheiaSemanticHighlightingParams Notification;
Sam McCall2cd33e62020-03-04 00:33:29 +01001583 Notification.TextDocument.uri =
1584 URIForFile::canonicalize(File, /*TUPath=*/File);
1585 Notification.TextDocument.version = decodeVersion(Version);
Sam McCalledf6a192020-03-24 00:31:14 +01001586 Notification.Lines = toTheiaSemanticHighlightingInformation(Diffed);
1587 publishTheiaSemanticHighlighting(Notification);
Johan Vikstroma848dab2019-07-04 07:53:12 +00001588}
1589
Sam McCall2cd33e62020-03-04 00:33:29 +01001590void ClangdLSPServer::onDiagnosticsReady(PathRef File, llvm::StringRef Version,
Sam McCalla7bb0cc2018-03-12 23:22:35 +00001591 std::vector<Diag> Diagnostics) {
Sam McCall6525a6b2020-03-03 12:44:40 +01001592 PublishDiagnosticsParams Notification;
Sam McCall2cd33e62020-03-04 00:33:29 +01001593 Notification.version = decodeVersion(Version);
Sam McCall6525a6b2020-03-03 12:44:40 +01001594 Notification.uri = URIForFile::canonicalize(File, /*TUPath=*/File);
Ilya Biryukov38d79772017-05-16 09:38:59 +00001595 DiagnosticToReplacementMap LocalFixIts; // Temporary storage
Sam McCalla7bb0cc2018-03-12 23:22:35 +00001596 for (auto &Diag : Diagnostics) {
Sam McCall6525a6b2020-03-03 12:44:40 +01001597 toLSPDiags(Diag, Notification.uri, DiagOpts,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001598 [&](clangd::Diagnostic Diag, llvm::ArrayRef<Fix> Fixes) {
Sam McCall16e70702018-10-24 07:59:38 +00001599 auto &FixItsForDiagnostic = LocalFixIts[Diag];
1600 llvm::copy(Fixes, std::back_inserter(FixItsForDiagnostic));
Sam McCall6525a6b2020-03-03 12:44:40 +01001601 Notification.diagnostics.push_back(std::move(Diag));
Sam McCall16e70702018-10-24 07:59:38 +00001602 });
Ilya Biryukov38d79772017-05-16 09:38:59 +00001603 }
1604
1605 // Cache FixIts
1606 {
Ilya Biryukov38d79772017-05-16 09:38:59 +00001607 std::lock_guard<std::mutex> Lock(FixItsMutex);
1608 FixItsMap[File] = LocalFixIts;
1609 }
1610
Ilya Biryukov49c10712019-03-25 10:15:11 +00001611 // Send a notification to the LSP client.
Sam McCall6525a6b2020-03-03 12:44:40 +01001612 publishDiagnostics(Notification);
Ilya Biryukov38d79772017-05-16 09:38:59 +00001613}
Simon Marchi9569fd52018-03-16 14:30:42 +00001614
Sam McCall7d20e802020-01-22 19:41:45 +01001615void ClangdLSPServer::onBackgroundIndexProgress(
1616 const BackgroundQueue::Stats &Stats) {
1617 static const char ProgressToken[] = "backgroundIndexProgress";
1618 std::lock_guard<std::mutex> Lock(BackgroundIndexProgressMutex);
1619
1620 auto NotifyProgress = [this](const BackgroundQueue::Stats &Stats) {
1621 if (BackgroundIndexProgressState != BackgroundIndexProgress::Live) {
1622 WorkDoneProgressBegin Begin;
1623 Begin.percentage = true;
1624 Begin.title = "indexing";
1625 progress(ProgressToken, std::move(Begin));
1626 BackgroundIndexProgressState = BackgroundIndexProgress::Live;
1627 }
1628
1629 if (Stats.Completed < Stats.Enqueued) {
1630 assert(Stats.Enqueued > Stats.LastIdle);
1631 WorkDoneProgressReport Report;
1632 Report.percentage = 100.0 * (Stats.Completed - Stats.LastIdle) /
1633 (Stats.Enqueued - Stats.LastIdle);
1634 Report.message =
1635 llvm::formatv("{0}/{1}", Stats.Completed - Stats.LastIdle,
1636 Stats.Enqueued - Stats.LastIdle);
1637 progress(ProgressToken, std::move(Report));
1638 } else {
1639 assert(Stats.Completed == Stats.Enqueued);
1640 progress(ProgressToken, WorkDoneProgressEnd());
1641 BackgroundIndexProgressState = BackgroundIndexProgress::Empty;
1642 }
1643 };
1644
1645 switch (BackgroundIndexProgressState) {
1646 case BackgroundIndexProgress::Unsupported:
1647 return;
1648 case BackgroundIndexProgress::Creating:
1649 // Cache this update for when the progress bar is available.
1650 PendingBackgroundIndexProgress = Stats;
1651 return;
1652 case BackgroundIndexProgress::Empty: {
1653 if (BackgroundIndexSkipCreate) {
1654 NotifyProgress(Stats);
1655 break;
1656 }
1657 // Cache this update for when the progress bar is available.
1658 PendingBackgroundIndexProgress = Stats;
1659 BackgroundIndexProgressState = BackgroundIndexProgress::Creating;
1660 WorkDoneProgressCreateParams CreateRequest;
1661 CreateRequest.token = ProgressToken;
1662 call<std::nullptr_t>(
1663 "window/workDoneProgress/create", CreateRequest,
1664 [this, NotifyProgress](llvm::Expected<std::nullptr_t> E) {
1665 std::lock_guard<std::mutex> Lock(BackgroundIndexProgressMutex);
1666 if (E) {
1667 NotifyProgress(this->PendingBackgroundIndexProgress);
1668 } else {
1669 elog("Failed to create background index progress bar: {0}",
1670 E.takeError());
1671 // give up forever rather than thrashing about
1672 BackgroundIndexProgressState = BackgroundIndexProgress::Unsupported;
1673 }
1674 });
1675 break;
1676 }
1677 case BackgroundIndexProgress::Live:
1678 NotifyProgress(Stats);
1679 break;
1680 }
1681}
1682
Haojian Wub6188492018-12-20 15:39:12 +00001683void ClangdLSPServer::onFileUpdated(PathRef File, const TUStatus &Status) {
1684 if (!SupportFileStatus)
1685 return;
1686 // FIXME: we don't emit "BuildingFile" and `RunningAction`, as these
1687 // two statuses are running faster in practice, which leads the UI constantly
1688 // changing, and doesn't provide much value. We may want to emit status at a
1689 // reasonable time interval (e.g. 0.5s).
Kadir Cetinkaya6b850322020-03-17 19:08:23 +01001690 if (Status.PreambleActivity == PreambleAction::Idle &&
1691 (Status.ASTActivity.K == ASTAction::Building ||
1692 Status.ASTActivity.K == ASTAction::RunningAction))
Haojian Wub6188492018-12-20 15:39:12 +00001693 return;
1694 notify("textDocument/clangd.fileStatus", Status.render(File));
1695}
1696
Sam McCall596b63a2020-04-10 03:27:37 +02001697void ClangdLSPServer::reparseOpenFilesIfNeeded(
1698 llvm::function_ref<bool(llvm::StringRef File)> Filter) {
David Goldman60249c22020-01-13 17:01:10 -05001699 // Reparse only opened files that were modified.
Simon Marchi9569fd52018-03-16 14:30:42 +00001700 for (const Path &FilePath : DraftMgr.getActiveFiles())
Sam McCall596b63a2020-04-10 03:27:37 +02001701 if (Filter(FilePath))
Sam McCall2cd33e62020-03-04 00:33:29 +01001702 if (auto Draft = DraftMgr.getDraft(FilePath)) // else disappeared in race?
1703 Server->addDocument(FilePath, std::move(Draft->Contents),
1704 encodeVersion(Draft->Version),
1705 WantDiagnostics::Auto);
Simon Marchi9569fd52018-03-16 14:30:42 +00001706}
Alex Lorenzf8087862018-08-01 17:39:29 +00001707
Sam McCallc008af62018-10-20 15:30:37 +00001708} // namespace clangd
1709} // namespace clang