blob: 53326296a6810aea2877ed5d6ed3de7a5d4e907e [file] [log] [blame]
Ilya Biryukov38d79772017-05-16 09:38:59 +00001//===--- ClangdLSPServer.cpp - LSP server ------------------------*- C++-*-===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Ilya Biryukov38d79772017-05-16 09:38:59 +00006//
Kirill Bobyrev8e35f1e2018-08-14 16:03:32 +00007//===----------------------------------------------------------------------===//
Ilya Biryukov38d79772017-05-16 09:38:59 +00008
9#include "ClangdLSPServer.h"
Ilya Biryukov71028b82018-03-12 15:28:22 +000010#include "Diagnostics.h"
Ilya Biryukovf9169d02019-05-29 10:01:00 +000011#include "FormattedString.h"
Ilya Biryukovcce67a32019-01-29 14:17:36 +000012#include "Protocol.h"
Sam McCallb536a2a2017-12-19 12:23:48 +000013#include "SourceCode.h"
Sam McCall2c30fbc2018-10-18 12:32:04 +000014#include "Trace.h"
Eric Liu78ed91a72018-01-29 15:37:46 +000015#include "URI.h"
Ilya Biryukovcce67a32019-01-29 14:17:36 +000016#include "clang/Tooling/Core/Replacement.h"
Sam McCalla69698f2019-03-27 17:47:49 +000017#include "llvm/ADT/Optional.h"
Kadir Cetinkaya689bf932018-08-24 13:09:41 +000018#include "llvm/ADT/ScopeExit.h"
Simon Marchi9569fd52018-03-16 14:30:42 +000019#include "llvm/Support/Errc.h"
Ilya Biryukovcce67a32019-01-29 14:17:36 +000020#include "llvm/Support/Error.h"
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +000021#include "llvm/Support/FormatVariadic.h"
Eric Liu5740ff52018-01-31 16:26:27 +000022#include "llvm/Support/Path.h"
Sam McCall2c30fbc2018-10-18 12:32:04 +000023#include "llvm/Support/ScopedPrinter.h"
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +000024
Sam McCallc008af62018-10-20 15:30:37 +000025namespace clang {
26namespace clangd {
Ilya Biryukovafb55542017-05-16 14:40:30 +000027namespace {
Ilya Biryukovb0826bd2019-01-03 13:37:12 +000028class IgnoreCompletionError : public llvm::ErrorInfo<CancelledError> {
29public:
30 void log(llvm::raw_ostream &OS) const override {
31 OS << "ignored auto-triggered completion, preceding char did not match";
32 }
33 std::error_code convertToErrorCode() const override {
34 return std::make_error_code(std::errc::operation_canceled);
35 }
36};
Ilya Biryukovafb55542017-05-16 14:40:30 +000037
Ilya Biryukovcce67a32019-01-29 14:17:36 +000038/// Transforms a tweak into a code action that would apply it if executed.
39/// EXPECTS: T.prepare() was called and returned true.
40CodeAction toCodeAction(const ClangdServer::TweakRef &T, const URIForFile &File,
41 Range Selection) {
42 CodeAction CA;
43 CA.title = T.Title;
44 CA.kind = CodeAction::REFACTOR_KIND;
45 // This tweak may have an expensive second stage, we only run it if the user
46 // actually chooses it in the UI. We reply with a command that would run the
47 // corresponding tweak.
48 // FIXME: for some tweaks, computing the edits is cheap and we could send them
49 // directly.
50 CA.command.emplace();
51 CA.command->title = T.Title;
52 CA.command->command = Command::CLANGD_APPLY_TWEAK;
53 CA.command->tweakArgs.emplace();
54 CA.command->tweakArgs->file = File;
55 CA.command->tweakArgs->tweakID = T.ID;
56 CA.command->tweakArgs->selection = Selection;
57 return CA;
Simon Pilgrime9a136b2019-02-03 14:08:30 +000058}
Ilya Biryukovcce67a32019-01-29 14:17:36 +000059
Ilya Biryukov19d75602018-11-23 15:21:19 +000060void adjustSymbolKinds(llvm::MutableArrayRef<DocumentSymbol> Syms,
61 SymbolKindBitset Kinds) {
62 for (auto &S : Syms) {
63 S.kind = adjustKindToCapability(S.kind, Kinds);
64 adjustSymbolKinds(S.children, Kinds);
65 }
66}
67
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +000068SymbolKindBitset defaultSymbolKinds() {
69 SymbolKindBitset Defaults;
70 for (size_t I = SymbolKindMin; I <= static_cast<size_t>(SymbolKind::Array);
71 ++I)
72 Defaults.set(I);
73 return Defaults;
74}
75
Kadir Cetinkaya133d46f2018-09-27 17:13:07 +000076CompletionItemKindBitset defaultCompletionItemKinds() {
77 CompletionItemKindBitset Defaults;
78 for (size_t I = CompletionItemKindMin;
79 I <= static_cast<size_t>(CompletionItemKind::Reference); ++I)
80 Defaults.set(I);
81 return Defaults;
82}
83
Ilya Biryukovafb55542017-05-16 14:40:30 +000084} // namespace
85
Sam McCall2c30fbc2018-10-18 12:32:04 +000086// MessageHandler dispatches incoming LSP messages.
87// It handles cross-cutting concerns:
88// - serializes/deserializes protocol objects to JSON
89// - logging of inbound messages
90// - cancellation handling
91// - basic call tracing
Sam McCall3d0adbe2018-10-18 14:41:50 +000092// MessageHandler ensures that initialize() is called before any other handler.
Sam McCall2c30fbc2018-10-18 12:32:04 +000093class ClangdLSPServer::MessageHandler : public Transport::MessageHandler {
94public:
95 MessageHandler(ClangdLSPServer &Server) : Server(Server) {}
96
Ilya Biryukovf2001aa2019-01-07 15:45:19 +000097 bool onNotify(llvm::StringRef Method, llvm::json::Value Params) override {
Sam McCalla69698f2019-03-27 17:47:49 +000098 WithContext HandlerContext(handlerContext());
Sam McCall2c30fbc2018-10-18 12:32:04 +000099 log("<-- {0}", Method);
100 if (Method == "exit")
101 return false;
Sam McCall3d0adbe2018-10-18 14:41:50 +0000102 if (!Server.Server)
103 elog("Notification {0} before initialization", Method);
104 else if (Method == "$/cancelRequest")
Sam McCall2c30fbc2018-10-18 12:32:04 +0000105 onCancel(std::move(Params));
106 else if (auto Handler = Notifications.lookup(Method))
107 Handler(std::move(Params));
108 else
109 log("unhandled notification {0}", Method);
110 return true;
111 }
112
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000113 bool onCall(llvm::StringRef Method, llvm::json::Value Params,
114 llvm::json::Value ID) override {
Sam McCalla69698f2019-03-27 17:47:49 +0000115 WithContext HandlerContext(handlerContext());
Sam McCalle2f3a732018-10-24 14:26:26 +0000116 // Calls can be canceled by the client. Add cancellation context.
117 WithContext WithCancel(cancelableRequestContext(ID));
118 trace::Span Tracer(Method);
119 SPAN_ATTACH(Tracer, "Params", Params);
120 ReplyOnce Reply(ID, Method, &Server, Tracer.Args);
Sam McCall2c30fbc2018-10-18 12:32:04 +0000121 log("<-- {0}({1})", Method, ID);
Sam McCall3d0adbe2018-10-18 14:41:50 +0000122 if (!Server.Server && Method != "initialize") {
123 elog("Call {0} before initialization.", Method);
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000124 Reply(llvm::make_error<LSPError>("server not initialized",
125 ErrorCode::ServerNotInitialized));
Sam McCall3d0adbe2018-10-18 14:41:50 +0000126 } else if (auto Handler = Calls.lookup(Method))
Sam McCalle2f3a732018-10-24 14:26:26 +0000127 Handler(std::move(Params), std::move(Reply));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000128 else
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000129 Reply(llvm::make_error<LSPError>("method not found",
130 ErrorCode::MethodNotFound));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000131 return true;
132 }
133
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000134 bool onReply(llvm::json::Value ID,
135 llvm::Expected<llvm::json::Value> Result) override {
Sam McCalla69698f2019-03-27 17:47:49 +0000136 WithContext HandlerContext(handlerContext());
Sam McCall2c30fbc2018-10-18 12:32:04 +0000137 // We ignore replies, just log them.
138 if (Result)
139 log("<-- reply({0})", ID);
140 else
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000141 log("<-- reply({0}) error: {1}", ID, llvm::toString(Result.takeError()));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000142 return true;
143 }
144
145 // Bind an LSP method name to a call.
Sam McCalle2f3a732018-10-24 14:26:26 +0000146 template <typename Param, typename Result>
Sam McCall2c30fbc2018-10-18 12:32:04 +0000147 void bind(const char *Method,
Sam McCalle2f3a732018-10-24 14:26:26 +0000148 void (ClangdLSPServer::*Handler)(const Param &, Callback<Result>)) {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000149 Calls[Method] = [Method, Handler, this](llvm::json::Value RawParams,
Sam McCalle2f3a732018-10-24 14:26:26 +0000150 ReplyOnce Reply) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000151 Param P;
Sam McCalle2f3a732018-10-24 14:26:26 +0000152 if (fromJSON(RawParams, P)) {
153 (Server.*Handler)(P, std::move(Reply));
154 } else {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000155 elog("Failed to decode {0} request.", Method);
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000156 Reply(llvm::make_error<LSPError>("failed to decode request",
157 ErrorCode::InvalidRequest));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000158 }
Sam McCall2c30fbc2018-10-18 12:32:04 +0000159 };
160 }
161
162 // Bind an LSP method name to a notification.
163 template <typename Param>
164 void bind(const char *Method,
165 void (ClangdLSPServer::*Handler)(const Param &)) {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000166 Notifications[Method] = [Method, Handler,
167 this](llvm::json::Value RawParams) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000168 Param P;
169 if (!fromJSON(RawParams, P)) {
170 elog("Failed to decode {0} request.", Method);
171 return;
172 }
173 trace::Span Tracer(Method);
174 SPAN_ATTACH(Tracer, "Params", RawParams);
175 (Server.*Handler)(P);
176 };
177 }
178
179private:
Sam McCalle2f3a732018-10-24 14:26:26 +0000180 // Function object to reply to an LSP call.
181 // Each instance must be called exactly once, otherwise:
182 // - the bug is logged, and (in debug mode) an assert will fire
183 // - if there was no reply, an error reply is sent
184 // - if there were multiple replies, only the first is sent
185 class ReplyOnce {
186 std::atomic<bool> Replied = {false};
Sam McCalld7babe42018-10-24 15:18:40 +0000187 std::chrono::steady_clock::time_point Start;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000188 llvm::json::Value ID;
Sam McCalle2f3a732018-10-24 14:26:26 +0000189 std::string Method;
190 ClangdLSPServer *Server; // Null when moved-from.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000191 llvm::json::Object *TraceArgs;
Sam McCalle2f3a732018-10-24 14:26:26 +0000192
193 public:
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000194 ReplyOnce(const llvm::json::Value &ID, llvm::StringRef Method,
195 ClangdLSPServer *Server, llvm::json::Object *TraceArgs)
Sam McCalld7babe42018-10-24 15:18:40 +0000196 : Start(std::chrono::steady_clock::now()), ID(ID), Method(Method),
197 Server(Server), TraceArgs(TraceArgs) {
Sam McCalle2f3a732018-10-24 14:26:26 +0000198 assert(Server);
199 }
200 ReplyOnce(ReplyOnce &&Other)
Sam McCalld7babe42018-10-24 15:18:40 +0000201 : Replied(Other.Replied.load()), Start(Other.Start),
202 ID(std::move(Other.ID)), Method(std::move(Other.Method)),
203 Server(Other.Server), TraceArgs(Other.TraceArgs) {
Sam McCalle2f3a732018-10-24 14:26:26 +0000204 Other.Server = nullptr;
205 }
Ilya Biryukov22fa4652019-01-03 13:28:05 +0000206 ReplyOnce &operator=(ReplyOnce &&) = delete;
Sam McCalle2f3a732018-10-24 14:26:26 +0000207 ReplyOnce(const ReplyOnce &) = delete;
Ilya Biryukov22fa4652019-01-03 13:28:05 +0000208 ReplyOnce &operator=(const ReplyOnce &) = delete;
Sam McCalle2f3a732018-10-24 14:26:26 +0000209
210 ~ReplyOnce() {
211 if (Server && !Replied) {
212 elog("No reply to message {0}({1})", Method, ID);
213 assert(false && "must reply to all calls!");
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000214 (*this)(llvm::make_error<LSPError>("server failed to reply",
215 ErrorCode::InternalError));
Sam McCalle2f3a732018-10-24 14:26:26 +0000216 }
217 }
218
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000219 void operator()(llvm::Expected<llvm::json::Value> Reply) {
Sam McCalle2f3a732018-10-24 14:26:26 +0000220 assert(Server && "moved-from!");
221 if (Replied.exchange(true)) {
222 elog("Replied twice to message {0}({1})", Method, ID);
223 assert(false && "must reply to each call only once!");
224 return;
225 }
Sam McCalld7babe42018-10-24 15:18:40 +0000226 auto Duration = std::chrono::steady_clock::now() - Start;
227 if (Reply) {
228 log("--> reply:{0}({1}) {2:ms}", Method, ID, Duration);
229 if (TraceArgs)
Sam McCalle2f3a732018-10-24 14:26:26 +0000230 (*TraceArgs)["Reply"] = *Reply;
Sam McCalld7babe42018-10-24 15:18:40 +0000231 std::lock_guard<std::mutex> Lock(Server->TranspWriter);
232 Server->Transp.reply(std::move(ID), std::move(Reply));
233 } else {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000234 llvm::Error Err = Reply.takeError();
Sam McCalld7babe42018-10-24 15:18:40 +0000235 log("--> reply:{0}({1}) {2:ms}, error: {3}", Method, ID, Duration, Err);
236 if (TraceArgs)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000237 (*TraceArgs)["Error"] = llvm::to_string(Err);
Sam McCalld7babe42018-10-24 15:18:40 +0000238 std::lock_guard<std::mutex> Lock(Server->TranspWriter);
239 Server->Transp.reply(std::move(ID), std::move(Err));
Sam McCalle2f3a732018-10-24 14:26:26 +0000240 }
Sam McCalle2f3a732018-10-24 14:26:26 +0000241 }
242 };
243
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000244 llvm::StringMap<std::function<void(llvm::json::Value)>> Notifications;
245 llvm::StringMap<std::function<void(llvm::json::Value, ReplyOnce)>> Calls;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000246
247 // Method calls may be cancelled by ID, so keep track of their state.
248 // This needs a mutex: handlers may finish on a different thread, and that's
249 // when we clean up entries in the map.
250 mutable std::mutex RequestCancelersMutex;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000251 llvm::StringMap<std::pair<Canceler, /*Cookie*/ unsigned>> RequestCancelers;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000252 unsigned NextRequestCookie = 0; // To disambiguate reused IDs, see below.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000253 void onCancel(const llvm::json::Value &Params) {
254 const llvm::json::Value *ID = nullptr;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000255 if (auto *O = Params.getAsObject())
256 ID = O->get("id");
257 if (!ID) {
258 elog("Bad cancellation request: {0}", Params);
259 return;
260 }
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000261 auto StrID = llvm::to_string(*ID);
Sam McCall2c30fbc2018-10-18 12:32:04 +0000262 std::lock_guard<std::mutex> Lock(RequestCancelersMutex);
263 auto It = RequestCancelers.find(StrID);
264 if (It != RequestCancelers.end())
265 It->second.first(); // Invoke the canceler.
266 }
Sam McCalla69698f2019-03-27 17:47:49 +0000267
268 Context handlerContext() const {
269 return Context::current().derive(
270 kCurrentOffsetEncoding,
271 Server.NegotiatedOffsetEncoding.getValueOr(OffsetEncoding::UTF16));
272 }
273
Sam McCall2c30fbc2018-10-18 12:32:04 +0000274 // We run cancelable requests in a context that does two things:
275 // - allows cancellation using RequestCancelers[ID]
276 // - cleans up the entry in RequestCancelers when it's no longer needed
277 // If a client reuses an ID, the last wins and the first cannot be canceled.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000278 Context cancelableRequestContext(const llvm::json::Value &ID) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000279 auto Task = cancelableTask();
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000280 auto StrID = llvm::to_string(ID); // JSON-serialize ID for map key.
Sam McCall2c30fbc2018-10-18 12:32:04 +0000281 auto Cookie = NextRequestCookie++; // No lock, only called on main thread.
282 {
283 std::lock_guard<std::mutex> Lock(RequestCancelersMutex);
284 RequestCancelers[StrID] = {std::move(Task.second), Cookie};
285 }
286 // When the request ends, we can clean up the entry we just added.
287 // The cookie lets us check that it hasn't been overwritten due to ID
288 // reuse.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000289 return Task.first.derive(llvm::make_scope_exit([this, StrID, Cookie] {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000290 std::lock_guard<std::mutex> Lock(RequestCancelersMutex);
291 auto It = RequestCancelers.find(StrID);
292 if (It != RequestCancelers.end() && It->second.second == Cookie)
293 RequestCancelers.erase(It);
294 }));
295 }
296
297 ClangdLSPServer &Server;
298};
299
300// call(), notify(), and reply() wrap the Transport, adding logging and locking.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000301void ClangdLSPServer::call(llvm::StringRef Method, llvm::json::Value Params) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000302 auto ID = NextCallID++;
303 log("--> {0}({1})", Method, ID);
304 // We currently don't handle responses, so no need to store ID anywhere.
305 std::lock_guard<std::mutex> Lock(TranspWriter);
306 Transp.call(Method, std::move(Params), ID);
307}
308
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000309void ClangdLSPServer::notify(llvm::StringRef Method, llvm::json::Value Params) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000310 log("--> {0}", Method);
311 std::lock_guard<std::mutex> Lock(TranspWriter);
312 Transp.notify(Method, std::move(Params));
313}
314
Sam McCall2c30fbc2018-10-18 12:32:04 +0000315void ClangdLSPServer::onInitialize(const InitializeParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000316 Callback<llvm::json::Value> Reply) {
Sam McCalla69698f2019-03-27 17:47:49 +0000317 // Determine character encoding first as it affects constructed ClangdServer.
318 if (Params.capabilities.offsetEncoding && !NegotiatedOffsetEncoding) {
319 NegotiatedOffsetEncoding = OffsetEncoding::UTF16; // fallback
320 for (OffsetEncoding Supported : *Params.capabilities.offsetEncoding)
321 if (Supported != OffsetEncoding::UnsupportedEncoding) {
322 NegotiatedOffsetEncoding = Supported;
323 break;
324 }
325 }
326 llvm::Optional<WithContextValue> WithOffsetEncoding;
327 if (NegotiatedOffsetEncoding)
328 WithOffsetEncoding.emplace(kCurrentOffsetEncoding,
329 *NegotiatedOffsetEncoding);
330
Sam McCall0d9b40f2018-10-19 15:42:23 +0000331 if (Params.rootUri && *Params.rootUri)
332 ClangdServerOpts.WorkspaceRoot = Params.rootUri->file();
333 else if (Params.rootPath && !Params.rootPath->empty())
334 ClangdServerOpts.WorkspaceRoot = *Params.rootPath;
Sam McCall3d0adbe2018-10-18 14:41:50 +0000335 if (Server)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000336 return Reply(llvm::make_error<LSPError>("server already initialized",
337 ErrorCode::InvalidRequest));
Sam McCallbc904612018-10-25 04:22:52 +0000338 if (const auto &Dir = Params.initializationOptions.compilationDatabasePath)
339 CompileCommandsDir = Dir;
Sam McCallc55d09a2018-11-02 13:09:36 +0000340 if (UseDirBasedCDB)
341 BaseCDB = llvm::make_unique<DirectoryBasedGlobalCompilationDatabase>(
342 CompileCommandsDir);
Kadir Cetinkayabe6b35d2019-01-22 09:10:20 +0000343 CDB.emplace(BaseCDB.get(), Params.initializationOptions.fallbackFlags,
344 ClangdServerOpts.ResourceDir);
Sam McCallc55d09a2018-11-02 13:09:36 +0000345 Server.emplace(*CDB, FSProvider, static_cast<DiagnosticsConsumer &>(*this),
346 ClangdServerOpts);
Sam McCallbc904612018-10-25 04:22:52 +0000347 applyConfiguration(Params.initializationOptions.ConfigSettings);
Simon Marchi88016782018-08-01 11:28:49 +0000348
Sam McCallbf6a2fc2018-10-17 07:33:42 +0000349 CCOpts.EnableSnippets = Params.capabilities.CompletionSnippets;
350 DiagOpts.EmbedFixesInDiagnostics = Params.capabilities.DiagnosticFixes;
351 DiagOpts.SendDiagnosticCategory = Params.capabilities.DiagnosticCategory;
Sam McCallc9e4ee92019-04-18 15:17:07 +0000352 DiagOpts.EmitRelatedLocations =
353 Params.capabilities.DiagnosticRelatedInformation;
Sam McCallbf6a2fc2018-10-17 07:33:42 +0000354 if (Params.capabilities.WorkspaceSymbolKinds)
355 SupportedSymbolKinds |= *Params.capabilities.WorkspaceSymbolKinds;
356 if (Params.capabilities.CompletionItemKinds)
357 SupportedCompletionItemKinds |= *Params.capabilities.CompletionItemKinds;
358 SupportsCodeAction = Params.capabilities.CodeActionStructure;
Ilya Biryukov19d75602018-11-23 15:21:19 +0000359 SupportsHierarchicalDocumentSymbol =
360 Params.capabilities.HierarchicalDocumentSymbol;
Haojian Wub6188492018-12-20 15:39:12 +0000361 SupportFileStatus = Params.initializationOptions.FileStatus;
Ilya Biryukovf9169d02019-05-29 10:01:00 +0000362 HoverContentFormat = Params.capabilities.HoverContentFormat;
Sam McCalla69698f2019-03-27 17:47:49 +0000363 llvm::json::Object Result{
Sam McCall0930ab02017-11-07 15:49:35 +0000364 {{"capabilities",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000365 llvm::json::Object{
Simon Marchi98082622018-03-26 14:41:40 +0000366 {"textDocumentSync", (int)TextDocumentSyncKind::Incremental},
Sam McCall0930ab02017-11-07 15:49:35 +0000367 {"documentFormattingProvider", true},
368 {"documentRangeFormattingProvider", true},
369 {"documentOnTypeFormattingProvider",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000370 llvm::json::Object{
Sam McCall0930ab02017-11-07 15:49:35 +0000371 {"firstTriggerCharacter", "}"},
372 {"moreTriggerCharacter", {}},
373 }},
374 {"codeActionProvider", true},
375 {"completionProvider",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000376 llvm::json::Object{
Sam McCall0930ab02017-11-07 15:49:35 +0000377 {"resolveProvider", false},
Ilya Biryukovb0826bd2019-01-03 13:37:12 +0000378 // We do extra checks for '>' and ':' in completion to only
379 // trigger on '->' and '::'.
Sam McCall0930ab02017-11-07 15:49:35 +0000380 {"triggerCharacters", {".", ">", ":"}},
381 }},
382 {"signatureHelpProvider",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000383 llvm::json::Object{
Sam McCall0930ab02017-11-07 15:49:35 +0000384 {"triggerCharacters", {"(", ","}},
385 }},
Sam McCall866ba2c2019-02-01 11:26:13 +0000386 {"declarationProvider", true},
Sam McCall0930ab02017-11-07 15:49:35 +0000387 {"definitionProvider", true},
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000388 {"documentHighlightProvider", true},
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000389 {"hoverProvider", true},
Haojian Wu345099c2017-11-09 11:30:04 +0000390 {"renameProvider", true},
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000391 {"documentSymbolProvider", true},
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000392 {"workspaceSymbolProvider", true},
Sam McCall1ad142f2018-09-05 11:53:07 +0000393 {"referencesProvider", true},
Sam McCall0930ab02017-11-07 15:49:35 +0000394 {"executeCommandProvider",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000395 llvm::json::Object{
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000396 {"commands",
397 {ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND,
398 ExecuteCommandParams::CLANGD_APPLY_TWEAK}},
Sam McCall0930ab02017-11-07 15:49:35 +0000399 }},
Kadir Cetinkaya86658022019-03-19 09:27:04 +0000400 {"typeHierarchyProvider", true},
Sam McCalla69698f2019-03-27 17:47:49 +0000401 }}}};
402 if (NegotiatedOffsetEncoding)
403 Result["offsetEncoding"] = *NegotiatedOffsetEncoding;
404 Reply(std::move(Result));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000405}
406
Sam McCall2c30fbc2018-10-18 12:32:04 +0000407void ClangdLSPServer::onShutdown(const ShutdownParams &Params,
408 Callback<std::nullptr_t> Reply) {
Ilya Biryukov0d9b8a32017-10-25 08:45:41 +0000409 // Do essentially nothing, just say we're ready to exit.
410 ShutdownRequestReceived = true;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000411 Reply(nullptr);
Sam McCall8a5dded2017-10-12 13:29:58 +0000412}
Ilya Biryukovafb55542017-05-16 14:40:30 +0000413
Sam McCall422c8282018-11-26 16:00:11 +0000414// sync is a clangd extension: it blocks until all background work completes.
415// It blocks the calling thread, so no messages are processed until it returns!
416void ClangdLSPServer::onSync(const NoParams &Params,
417 Callback<std::nullptr_t> Reply) {
418 if (Server->blockUntilIdleForTest(/*TimeoutSeconds=*/60))
419 Reply(nullptr);
420 else
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000421 Reply(llvm::createStringError(llvm::inconvertibleErrorCode(),
422 "Not idle after a minute"));
Sam McCall422c8282018-11-26 16:00:11 +0000423}
424
Sam McCall2c30fbc2018-10-18 12:32:04 +0000425void ClangdLSPServer::onDocumentDidOpen(
426 const DidOpenTextDocumentParams &Params) {
Simon Marchi9569fd52018-03-16 14:30:42 +0000427 PathRef File = Params.textDocument.uri.file();
Ilya Biryukovb10ef472018-06-13 09:20:41 +0000428
Sam McCall2c30fbc2018-10-18 12:32:04 +0000429 const std::string &Contents = Params.textDocument.text;
Simon Marchi9569fd52018-03-16 14:30:42 +0000430
Simon Marchi98082622018-03-26 14:41:40 +0000431 DraftMgr.addDraft(File, Contents);
Ilya Biryukov652364b2018-09-26 05:48:29 +0000432 Server->addDocument(File, Contents, WantDiagnostics::Yes);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000433}
434
Sam McCall2c30fbc2018-10-18 12:32:04 +0000435void ClangdLSPServer::onDocumentDidChange(
436 const DidChangeTextDocumentParams &Params) {
Eric Liu51fed182018-02-22 18:40:39 +0000437 auto WantDiags = WantDiagnostics::Auto;
438 if (Params.wantDiagnostics.hasValue())
439 WantDiags = Params.wantDiagnostics.getValue() ? WantDiagnostics::Yes
440 : WantDiagnostics::No;
Simon Marchi9569fd52018-03-16 14:30:42 +0000441
442 PathRef File = Params.textDocument.uri.file();
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000443 llvm::Expected<std::string> Contents =
Simon Marchi98082622018-03-26 14:41:40 +0000444 DraftMgr.updateDraft(File, Params.contentChanges);
445 if (!Contents) {
446 // If this fails, we are most likely going to be not in sync anymore with
447 // the client. It is better to remove the draft and let further operations
448 // fail rather than giving wrong results.
449 DraftMgr.removeDraft(File);
Ilya Biryukov652364b2018-09-26 05:48:29 +0000450 Server->removeDocument(File);
Sam McCallbed58852018-07-11 10:35:11 +0000451 elog("Failed to update {0}: {1}", File, Contents.takeError());
Simon Marchi98082622018-03-26 14:41:40 +0000452 return;
453 }
Simon Marchi9569fd52018-03-16 14:30:42 +0000454
Ilya Biryukov652364b2018-09-26 05:48:29 +0000455 Server->addDocument(File, *Contents, WantDiags);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000456}
457
Sam McCall2c30fbc2018-10-18 12:32:04 +0000458void ClangdLSPServer::onFileEvent(const DidChangeWatchedFilesParams &Params) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000459 Server->onFileEvent(Params);
Marc-Andre Laperlebf114242017-10-02 18:00:37 +0000460}
461
Sam McCall2c30fbc2018-10-18 12:32:04 +0000462void ClangdLSPServer::onCommand(const ExecuteCommandParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000463 Callback<llvm::json::Value> Reply) {
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000464 auto ApplyEdit = [this](WorkspaceEdit WE) {
Eric Liuc5105f92018-02-16 14:15:55 +0000465 ApplyWorkspaceEditParams Edit;
466 Edit.edit = std::move(WE);
Eric Liuc5105f92018-02-16 14:15:55 +0000467 // Ideally, we would wait for the response and if there is no error, we
468 // would reply success/failure to the original RPC.
469 call("workspace/applyEdit", Edit);
470 };
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000471 if (Params.command == ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND &&
472 Params.workspaceEdit) {
473 // The flow for "apply-fix" :
474 // 1. We publish a diagnostic, including fixits
475 // 2. The user clicks on the diagnostic, the editor asks us for code actions
476 // 3. We send code actions, with the fixit embedded as context
477 // 4. The user selects the fixit, the editor asks us to apply it
478 // 5. We unwrap the changes and send them back to the editor
479 // 6. The editor applies the changes (applyEdit), and sends us a reply (but
480 // we ignore it)
481
Sam McCall2c30fbc2018-10-18 12:32:04 +0000482 Reply("Fix applied.");
Eric Liuc5105f92018-02-16 14:15:55 +0000483 ApplyEdit(*Params.workspaceEdit);
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000484 } else if (Params.command == ExecuteCommandParams::CLANGD_APPLY_TWEAK &&
485 Params.tweakArgs) {
486 auto Code = DraftMgr.getDraft(Params.tweakArgs->file.file());
487 if (!Code)
488 return Reply(llvm::createStringError(
489 llvm::inconvertibleErrorCode(),
490 "trying to apply a code action for a non-added file"));
491
492 auto Action = [ApplyEdit](decltype(Reply) Reply, URIForFile File,
493 std::string Code,
494 llvm::Expected<tooling::Replacements> R) {
495 if (!R)
496 return Reply(R.takeError());
497
498 WorkspaceEdit WE;
499 WE.changes.emplace();
500 (*WE.changes)[File.uri()] = replacementsToEdits(Code, *R);
501
502 Reply("Fix applied.");
503 ApplyEdit(std::move(WE));
504 };
505 Server->applyTweak(Params.tweakArgs->file.file(),
506 Params.tweakArgs->selection, Params.tweakArgs->tweakID,
507 Bind(Action, std::move(Reply), Params.tweakArgs->file,
508 std::move(*Code)));
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000509 } else {
510 // We should not get here because ExecuteCommandParams would not have
511 // parsed in the first place and this handler should not be called. But if
512 // more commands are added, this will be here has a safe guard.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000513 Reply(llvm::make_error<LSPError>(
514 llvm::formatv("Unsupported command \"{0}\".", Params.command).str(),
Sam McCall2c30fbc2018-10-18 12:32:04 +0000515 ErrorCode::InvalidParams));
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000516 }
517}
518
Sam McCall2c30fbc2018-10-18 12:32:04 +0000519void ClangdLSPServer::onWorkspaceSymbol(
520 const WorkspaceSymbolParams &Params,
521 Callback<std::vector<SymbolInformation>> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000522 Server->workspaceSymbols(
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000523 Params.query, CCOpts.Limit,
Sam McCall2c30fbc2018-10-18 12:32:04 +0000524 Bind(
525 [this](decltype(Reply) Reply,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000526 llvm::Expected<std::vector<SymbolInformation>> Items) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000527 if (!Items)
528 return Reply(Items.takeError());
529 for (auto &Sym : *Items)
530 Sym.kind = adjustKindToCapability(Sym.kind, SupportedSymbolKinds);
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000531
Sam McCall2c30fbc2018-10-18 12:32:04 +0000532 Reply(std::move(*Items));
533 },
534 std::move(Reply)));
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000535}
536
Sam McCall2c30fbc2018-10-18 12:32:04 +0000537void ClangdLSPServer::onRename(const RenameParams &Params,
538 Callback<WorkspaceEdit> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000539 Path File = Params.textDocument.uri.file();
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000540 llvm::Optional<std::string> Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000541 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000542 return Reply(llvm::make_error<LSPError>(
543 "onRename called for non-added file", ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000544
Ilya Biryukov652364b2018-09-26 05:48:29 +0000545 Server->rename(
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000546 File, Params.position, Params.newName,
Sam McCall2c30fbc2018-10-18 12:32:04 +0000547 Bind(
Ilya Biryukovd9c24dc2019-04-03 07:18:43 +0000548 [File, Code, Params](decltype(Reply) Reply,
549 llvm::Expected<std::vector<TextEdit>> Edits) {
550 if (!Edits)
551 return Reply(Edits.takeError());
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000552
Sam McCall2c30fbc2018-10-18 12:32:04 +0000553 WorkspaceEdit WE;
Ilya Biryukovd9c24dc2019-04-03 07:18:43 +0000554 WE.changes = {{Params.textDocument.uri.uri(), *Edits}};
Sam McCall2c30fbc2018-10-18 12:32:04 +0000555 Reply(WE);
556 },
557 std::move(Reply)));
Haojian Wu345099c2017-11-09 11:30:04 +0000558}
559
Sam McCall2c30fbc2018-10-18 12:32:04 +0000560void ClangdLSPServer::onDocumentDidClose(
561 const DidCloseTextDocumentParams &Params) {
Simon Marchi9569fd52018-03-16 14:30:42 +0000562 PathRef File = Params.textDocument.uri.file();
563 DraftMgr.removeDraft(File);
Ilya Biryukov652364b2018-09-26 05:48:29 +0000564 Server->removeDocument(File);
Ilya Biryukov49c10712019-03-25 10:15:11 +0000565
566 {
567 std::lock_guard<std::mutex> Lock(FixItsMutex);
568 FixItsMap.erase(File);
569 }
570 // clangd will not send updates for this file anymore, so we empty out the
571 // list of diagnostics shown on the client (e.g. in the "Problems" pane of
572 // VSCode). Note that this cannot race with actual diagnostics responses
573 // because removeDocument() guarantees no diagnostic callbacks will be
574 // executed after it returns.
575 publishDiagnostics(URIForFile::canonicalize(File, /*TUPath=*/File), {});
Ilya Biryukovafb55542017-05-16 14:40:30 +0000576}
577
Sam McCall4db732a2017-09-30 10:08:52 +0000578void ClangdLSPServer::onDocumentOnTypeFormatting(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000579 const DocumentOnTypeFormattingParams &Params,
580 Callback<std::vector<TextEdit>> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000581 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000582 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000583 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000584 return Reply(llvm::make_error<LSPError>(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000585 "onDocumentOnTypeFormatting called for non-added file",
586 ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000587
Ilya Biryukov652364b2018-09-26 05:48:29 +0000588 auto ReplacementsOrError = Server->formatOnType(*Code, File, Params.position);
Raoul Wols212bcf82017-12-12 20:25:06 +0000589 if (ReplacementsOrError)
Sam McCall2c30fbc2018-10-18 12:32:04 +0000590 Reply(replacementsToEdits(*Code, ReplacementsOrError.get()));
Raoul Wols212bcf82017-12-12 20:25:06 +0000591 else
Sam McCall2c30fbc2018-10-18 12:32:04 +0000592 Reply(ReplacementsOrError.takeError());
Ilya Biryukovafb55542017-05-16 14:40:30 +0000593}
594
Sam McCall4db732a2017-09-30 10:08:52 +0000595void ClangdLSPServer::onDocumentRangeFormatting(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000596 const DocumentRangeFormattingParams &Params,
597 Callback<std::vector<TextEdit>> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000598 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000599 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000600 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000601 return Reply(llvm::make_error<LSPError>(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000602 "onDocumentRangeFormatting called for non-added file",
603 ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000604
Ilya Biryukov652364b2018-09-26 05:48:29 +0000605 auto ReplacementsOrError = Server->formatRange(*Code, File, Params.range);
Raoul Wols212bcf82017-12-12 20:25:06 +0000606 if (ReplacementsOrError)
Sam McCall2c30fbc2018-10-18 12:32:04 +0000607 Reply(replacementsToEdits(*Code, ReplacementsOrError.get()));
Raoul Wols212bcf82017-12-12 20:25:06 +0000608 else
Sam McCall2c30fbc2018-10-18 12:32:04 +0000609 Reply(ReplacementsOrError.takeError());
Ilya Biryukovafb55542017-05-16 14:40:30 +0000610}
611
Sam McCall2c30fbc2018-10-18 12:32:04 +0000612void ClangdLSPServer::onDocumentFormatting(
613 const DocumentFormattingParams &Params,
614 Callback<std::vector<TextEdit>> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000615 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000616 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000617 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000618 return Reply(llvm::make_error<LSPError>(
619 "onDocumentFormatting called for non-added file",
620 ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000621
Ilya Biryukov652364b2018-09-26 05:48:29 +0000622 auto ReplacementsOrError = Server->formatFile(*Code, File);
Raoul Wols212bcf82017-12-12 20:25:06 +0000623 if (ReplacementsOrError)
Sam McCall2c30fbc2018-10-18 12:32:04 +0000624 Reply(replacementsToEdits(*Code, ReplacementsOrError.get()));
Raoul Wols212bcf82017-12-12 20:25:06 +0000625 else
Sam McCall2c30fbc2018-10-18 12:32:04 +0000626 Reply(ReplacementsOrError.takeError());
Sam McCall4db732a2017-09-30 10:08:52 +0000627}
628
Ilya Biryukov19d75602018-11-23 15:21:19 +0000629/// The functions constructs a flattened view of the DocumentSymbol hierarchy.
630/// Used by the clients that do not support the hierarchical view.
631static std::vector<SymbolInformation>
632flattenSymbolHierarchy(llvm::ArrayRef<DocumentSymbol> Symbols,
633 const URIForFile &FileURI) {
634
635 std::vector<SymbolInformation> Results;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000636 std::function<void(const DocumentSymbol &, llvm::StringRef)> Process =
637 [&](const DocumentSymbol &S, llvm::Optional<llvm::StringRef> ParentName) {
Ilya Biryukov19d75602018-11-23 15:21:19 +0000638 SymbolInformation SI;
639 SI.containerName = ParentName ? "" : *ParentName;
640 SI.name = S.name;
641 SI.kind = S.kind;
642 SI.location.range = S.range;
643 SI.location.uri = FileURI;
644
645 Results.push_back(std::move(SI));
646 std::string FullName =
647 !ParentName ? S.name : (ParentName->str() + "::" + S.name);
648 for (auto &C : S.children)
649 Process(C, /*ParentName=*/FullName);
650 };
651 for (auto &S : Symbols)
652 Process(S, /*ParentName=*/"");
653 return Results;
654}
655
656void ClangdLSPServer::onDocumentSymbol(const DocumentSymbolParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000657 Callback<llvm::json::Value> Reply) {
Ilya Biryukov19d75602018-11-23 15:21:19 +0000658 URIForFile FileURI = Params.textDocument.uri;
Ilya Biryukov652364b2018-09-26 05:48:29 +0000659 Server->documentSymbols(
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000660 Params.textDocument.uri.file(),
Sam McCall2c30fbc2018-10-18 12:32:04 +0000661 Bind(
Ilya Biryukov19d75602018-11-23 15:21:19 +0000662 [this, FileURI](decltype(Reply) Reply,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000663 llvm::Expected<std::vector<DocumentSymbol>> Items) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000664 if (!Items)
665 return Reply(Items.takeError());
Ilya Biryukov19d75602018-11-23 15:21:19 +0000666 adjustSymbolKinds(*Items, SupportedSymbolKinds);
667 if (SupportsHierarchicalDocumentSymbol)
668 return Reply(std::move(*Items));
669 else
670 return Reply(flattenSymbolHierarchy(*Items, FileURI));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000671 },
672 std::move(Reply)));
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000673}
674
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000675static llvm::Optional<Command> asCommand(const CodeAction &Action) {
Sam McCall20841d42018-10-16 16:29:41 +0000676 Command Cmd;
677 if (Action.command && Action.edit)
Sam McCallc008af62018-10-20 15:30:37 +0000678 return None; // Not representable. (We never emit these anyway).
Sam McCall20841d42018-10-16 16:29:41 +0000679 if (Action.command) {
680 Cmd = *Action.command;
681 } else if (Action.edit) {
682 Cmd.command = Command::CLANGD_APPLY_FIX_COMMAND;
683 Cmd.workspaceEdit = *Action.edit;
684 } else {
Sam McCallc008af62018-10-20 15:30:37 +0000685 return None;
Sam McCall20841d42018-10-16 16:29:41 +0000686 }
687 Cmd.title = Action.title;
688 if (Action.kind && *Action.kind == CodeAction::QUICKFIX_KIND)
689 Cmd.title = "Apply fix: " + Cmd.title;
690 return Cmd;
691}
692
Sam McCall2c30fbc2018-10-18 12:32:04 +0000693void ClangdLSPServer::onCodeAction(const CodeActionParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000694 Callback<llvm::json::Value> Reply) {
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000695 URIForFile File = Params.textDocument.uri;
696 auto Code = DraftMgr.getDraft(File.file());
Sam McCall2c30fbc2018-10-18 12:32:04 +0000697 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000698 return Reply(llvm::make_error<LSPError>(
699 "onCodeAction called for non-added file", ErrorCode::InvalidParams));
Sam McCall20841d42018-10-16 16:29:41 +0000700 // We provide a code action for Fixes on the specified diagnostics.
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000701 std::vector<CodeAction> FixIts;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000702 for (const Diagnostic &D : Params.context.diagnostics) {
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000703 for (auto &F : getFixes(File.file(), D)) {
704 FixIts.push_back(toCodeAction(F, Params.textDocument.uri));
705 FixIts.back().diagnostics = {D};
Sam McCalldd0566b2017-11-06 15:40:30 +0000706 }
Ilya Biryukovafb55542017-05-16 14:40:30 +0000707 }
Sam McCall20841d42018-10-16 16:29:41 +0000708
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000709 // Now enumerate the semantic code actions.
710 auto ConsumeActions =
711 [this](decltype(Reply) Reply, URIForFile File, std::string Code,
712 Range Selection, std::vector<CodeAction> FixIts,
713 llvm::Expected<std::vector<ClangdServer::TweakRef>> Tweaks) {
Ilya Biryukovc6ed7782019-01-30 14:24:17 +0000714 if (!Tweaks)
715 return Reply(Tweaks.takeError());
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000716
717 std::vector<CodeAction> Actions = std::move(FixIts);
718 Actions.reserve(Actions.size() + Tweaks->size());
719 for (const auto &T : *Tweaks)
720 Actions.push_back(toCodeAction(T, File, Selection));
721
722 if (SupportsCodeAction)
723 return Reply(llvm::json::Array(Actions));
724 std::vector<Command> Commands;
725 for (const auto &Action : Actions) {
726 if (auto Command = asCommand(Action))
727 Commands.push_back(std::move(*Command));
728 }
729 return Reply(llvm::json::Array(Commands));
730 };
731
732 Server->enumerateTweaks(File.file(), Params.range,
Ilya Biryukovc9409c62019-01-30 09:39:01 +0000733 Bind(ConsumeActions, std::move(Reply), File,
734 std::move(*Code), Params.range,
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000735 std::move(FixIts)));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000736}
737
Ilya Biryukovb0826bd2019-01-03 13:37:12 +0000738void ClangdLSPServer::onCompletion(const CompletionParams &Params,
Sam McCall2c30fbc2018-10-18 12:32:04 +0000739 Callback<CompletionList> Reply) {
Ilya Biryukovb0826bd2019-01-03 13:37:12 +0000740 if (!shouldRunCompletion(Params))
741 return Reply(llvm::make_error<IgnoreCompletionError>());
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000742 Server->codeComplete(Params.textDocument.uri.file(), Params.position, CCOpts,
743 Bind(
744 [this](decltype(Reply) Reply,
745 llvm::Expected<CodeCompleteResult> List) {
746 if (!List)
747 return Reply(List.takeError());
748 CompletionList LSPList;
749 LSPList.isIncomplete = List->HasMore;
750 for (const auto &R : List->Completions) {
751 CompletionItem C = R.render(CCOpts);
752 C.kind = adjustKindToCapability(
753 C.kind, SupportedCompletionItemKinds);
754 LSPList.items.push_back(std::move(C));
755 }
756 return Reply(std::move(LSPList));
757 },
758 std::move(Reply)));
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000759}
760
Sam McCall2c30fbc2018-10-18 12:32:04 +0000761void ClangdLSPServer::onSignatureHelp(const TextDocumentPositionParams &Params,
762 Callback<SignatureHelp> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000763 Server->signatureHelp(Params.textDocument.uri.file(), Params.position,
Sam McCall2c30fbc2018-10-18 12:32:04 +0000764 std::move(Reply));
Ilya Biryukov652364b2018-09-26 05:48:29 +0000765}
766
Sam McCall0dbab7f2019-02-02 05:56:00 +0000767// Go to definition has a toggle function: if def and decl are distinct, then
768// the first press gives you the def, the second gives you the matching def.
769// getToggle() returns the counterpart location that under the cursor.
770//
771// We return the toggled location alone (ignoring other symbols) to encourage
772// editors to "bounce" quickly between locations, without showing a menu.
773static Location *getToggle(const TextDocumentPositionParams &Point,
774 LocatedSymbol &Sym) {
775 // Toggle only makes sense with two distinct locations.
776 if (!Sym.Definition || *Sym.Definition == Sym.PreferredDeclaration)
777 return nullptr;
778 if (Sym.Definition->uri.file() == Point.textDocument.uri.file() &&
779 Sym.Definition->range.contains(Point.position))
780 return &Sym.PreferredDeclaration;
781 if (Sym.PreferredDeclaration.uri.file() == Point.textDocument.uri.file() &&
782 Sym.PreferredDeclaration.range.contains(Point.position))
783 return &*Sym.Definition;
784 return nullptr;
785}
786
Sam McCall2c30fbc2018-10-18 12:32:04 +0000787void ClangdLSPServer::onGoToDefinition(const TextDocumentPositionParams &Params,
788 Callback<std::vector<Location>> Reply) {
Sam McCall866ba2c2019-02-01 11:26:13 +0000789 Server->locateSymbolAt(
790 Params.textDocument.uri.file(), Params.position,
791 Bind(
Sam McCall0dbab7f2019-02-02 05:56:00 +0000792 [&, Params](decltype(Reply) Reply,
793 llvm::Expected<std::vector<LocatedSymbol>> Symbols) {
Sam McCall866ba2c2019-02-01 11:26:13 +0000794 if (!Symbols)
795 return Reply(Symbols.takeError());
796 std::vector<Location> Defs;
Sam McCall0dbab7f2019-02-02 05:56:00 +0000797 for (auto &S : *Symbols) {
798 if (Location *Toggle = getToggle(Params, S))
799 return Reply(std::vector<Location>{std::move(*Toggle)});
Sam McCall866ba2c2019-02-01 11:26:13 +0000800 Defs.push_back(S.Definition.getValueOr(S.PreferredDeclaration));
Sam McCall0dbab7f2019-02-02 05:56:00 +0000801 }
Sam McCall866ba2c2019-02-01 11:26:13 +0000802 Reply(std::move(Defs));
803 },
804 std::move(Reply)));
805}
806
807void ClangdLSPServer::onGoToDeclaration(
808 const TextDocumentPositionParams &Params,
809 Callback<std::vector<Location>> Reply) {
810 Server->locateSymbolAt(
811 Params.textDocument.uri.file(), Params.position,
812 Bind(
Sam McCall0dbab7f2019-02-02 05:56:00 +0000813 [&, Params](decltype(Reply) Reply,
814 llvm::Expected<std::vector<LocatedSymbol>> Symbols) {
Sam McCall866ba2c2019-02-01 11:26:13 +0000815 if (!Symbols)
816 return Reply(Symbols.takeError());
817 std::vector<Location> Decls;
Sam McCall0dbab7f2019-02-02 05:56:00 +0000818 for (auto &S : *Symbols) {
819 if (Location *Toggle = getToggle(Params, S))
820 return Reply(std::vector<Location>{std::move(*Toggle)});
821 Decls.push_back(std::move(S.PreferredDeclaration));
822 }
Sam McCall866ba2c2019-02-01 11:26:13 +0000823 Reply(std::move(Decls));
824 },
825 std::move(Reply)));
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000826}
827
Sam McCall111fe842019-05-07 07:55:35 +0000828void ClangdLSPServer::onSwitchSourceHeader(
829 const TextDocumentIdentifier &Params,
Sam McCallb9ec3e92019-05-07 08:30:32 +0000830 Callback<llvm::Optional<URIForFile>> Reply) {
Sam McCall111fe842019-05-07 07:55:35 +0000831 if (auto Result = Server->switchSourceHeader(Params.uri.file()))
Sam McCallb9ec3e92019-05-07 08:30:32 +0000832 Reply(URIForFile::canonicalize(*Result, Params.uri.file()));
Sam McCall111fe842019-05-07 07:55:35 +0000833 else
834 Reply(llvm::None);
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000835}
836
Sam McCall2c30fbc2018-10-18 12:32:04 +0000837void ClangdLSPServer::onDocumentHighlight(
838 const TextDocumentPositionParams &Params,
839 Callback<std::vector<DocumentHighlight>> Reply) {
840 Server->findDocumentHighlights(Params.textDocument.uri.file(),
841 Params.position, std::move(Reply));
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000842}
843
Sam McCall2c30fbc2018-10-18 12:32:04 +0000844void ClangdLSPServer::onHover(const TextDocumentPositionParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000845 Callback<llvm::Optional<Hover>> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000846 Server->findHover(Params.textDocument.uri.file(), Params.position,
Kadir Cetinkayac6578ee2019-05-28 10:29:58 +0000847 Bind(
Ilya Biryukovf9169d02019-05-29 10:01:00 +0000848 [this](decltype(Reply) Reply,
849 llvm::Expected<llvm::Optional<HoverInfo>> H) {
850 if (!H)
851 return Reply(H.takeError());
852 if (!*H)
Kadir Cetinkayac6578ee2019-05-28 10:29:58 +0000853 return Reply(llvm::None);
Ilya Biryukovf9169d02019-05-29 10:01:00 +0000854
855 Hover R;
856 R.contents.kind = HoverContentFormat;
857 R.range = (*H)->SymRange;
858 switch (HoverContentFormat) {
859 case MarkupKind::PlainText:
860 R.contents.value =
861 (*H)->present().renderAsPlainText();
862 return Reply(std::move(R));
863 case MarkupKind::Markdown:
864 R.contents.value =
865 (*H)->present().renderAsMarkdown();
866 return Reply(std::move(R));
867 };
868 llvm_unreachable("unhandled MarkupKind");
Kadir Cetinkayac6578ee2019-05-28 10:29:58 +0000869 },
870 std::move(Reply)));
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000871}
872
Kadir Cetinkaya86658022019-03-19 09:27:04 +0000873void ClangdLSPServer::onTypeHierarchy(
874 const TypeHierarchyParams &Params,
875 Callback<Optional<TypeHierarchyItem>> Reply) {
876 Server->typeHierarchy(Params.textDocument.uri.file(), Params.position,
877 Params.resolve, Params.direction, std::move(Reply));
878}
879
Simon Marchi88016782018-08-01 11:28:49 +0000880void ClangdLSPServer::applyConfiguration(
Sam McCallbc904612018-10-25 04:22:52 +0000881 const ConfigurationSettings &Settings) {
Simon Marchiabeed662018-10-16 15:55:03 +0000882 // Per-file update to the compilation database.
Sam McCallbc904612018-10-25 04:22:52 +0000883 bool ShouldReparseOpenFiles = false;
884 for (auto &Entry : Settings.compilationDatabaseChanges) {
885 /// The opened files need to be reparsed only when some existing
886 /// entries are changed.
887 PathRef File = Entry.first;
Sam McCallc55d09a2018-11-02 13:09:36 +0000888 auto Old = CDB->getCompileCommand(File);
889 auto New =
890 tooling::CompileCommand(std::move(Entry.second.workingDirectory), File,
891 std::move(Entry.second.compilationCommand),
892 /*Output=*/"");
Sam McCall6980edb2018-11-02 14:07:51 +0000893 if (Old != New) {
Sam McCallc55d09a2018-11-02 13:09:36 +0000894 CDB->setCompileCommand(File, std::move(New));
Sam McCall6980edb2018-11-02 14:07:51 +0000895 ShouldReparseOpenFiles = true;
896 }
Alex Lorenzf8087862018-08-01 17:39:29 +0000897 }
Sam McCallbc904612018-10-25 04:22:52 +0000898 if (ShouldReparseOpenFiles)
899 reparseOpenedFiles();
Simon Marchi5178f922018-02-22 14:00:39 +0000900}
901
Ilya Biryukov49c10712019-03-25 10:15:11 +0000902void ClangdLSPServer::publishDiagnostics(
903 const URIForFile &File, std::vector<clangd::Diagnostic> Diagnostics) {
904 // Publish diagnostics.
905 notify("textDocument/publishDiagnostics",
906 llvm::json::Object{
907 {"uri", File},
908 {"diagnostics", std::move(Diagnostics)},
909 });
910}
911
Simon Marchi88016782018-08-01 11:28:49 +0000912// FIXME: This function needs to be properly tested.
913void ClangdLSPServer::onChangeConfiguration(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000914 const DidChangeConfigurationParams &Params) {
Simon Marchi88016782018-08-01 11:28:49 +0000915 applyConfiguration(Params.settings);
916}
917
Sam McCall2c30fbc2018-10-18 12:32:04 +0000918void ClangdLSPServer::onReference(const ReferenceParams &Params,
919 Callback<std::vector<Location>> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000920 Server->findReferences(Params.textDocument.uri.file(), Params.position,
Haojian Wuc34f0222019-01-14 18:11:09 +0000921 CCOpts.Limit, std::move(Reply));
Sam McCall1ad142f2018-09-05 11:53:07 +0000922}
923
Jan Korousb4067012018-11-27 16:40:46 +0000924void ClangdLSPServer::onSymbolInfo(const TextDocumentPositionParams &Params,
925 Callback<std::vector<SymbolDetails>> Reply) {
926 Server->symbolInfo(Params.textDocument.uri.file(), Params.position,
927 std::move(Reply));
928}
929
Sam McCalla69698f2019-03-27 17:47:49 +0000930ClangdLSPServer::ClangdLSPServer(
931 class Transport &Transp, const FileSystemProvider &FSProvider,
932 const clangd::CodeCompleteOptions &CCOpts,
933 llvm::Optional<Path> CompileCommandsDir, bool UseDirBasedCDB,
934 llvm::Optional<OffsetEncoding> ForcedOffsetEncoding,
935 const ClangdServer::Options &Opts)
Haojian Wu1ca0c582019-01-22 09:39:05 +0000936 : Transp(Transp), MsgHandler(new MessageHandler(*this)),
937 FSProvider(FSProvider), CCOpts(CCOpts),
Sam McCalld1c9d112018-10-23 14:19:54 +0000938 SupportedSymbolKinds(defaultSymbolKinds()),
Kadir Cetinkaya133d46f2018-09-27 17:13:07 +0000939 SupportedCompletionItemKinds(defaultCompletionItemKinds()),
Sam McCallc55d09a2018-11-02 13:09:36 +0000940 UseDirBasedCDB(UseDirBasedCDB),
Sam McCalla69698f2019-03-27 17:47:49 +0000941 CompileCommandsDir(std::move(CompileCommandsDir)), ClangdServerOpts(Opts),
942 NegotiatedOffsetEncoding(ForcedOffsetEncoding) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000943 // clang-format off
944 MsgHandler->bind("initialize", &ClangdLSPServer::onInitialize);
945 MsgHandler->bind("shutdown", &ClangdLSPServer::onShutdown);
Sam McCall422c8282018-11-26 16:00:11 +0000946 MsgHandler->bind("sync", &ClangdLSPServer::onSync);
Sam McCall2c30fbc2018-10-18 12:32:04 +0000947 MsgHandler->bind("textDocument/rangeFormatting", &ClangdLSPServer::onDocumentRangeFormatting);
948 MsgHandler->bind("textDocument/onTypeFormatting", &ClangdLSPServer::onDocumentOnTypeFormatting);
949 MsgHandler->bind("textDocument/formatting", &ClangdLSPServer::onDocumentFormatting);
950 MsgHandler->bind("textDocument/codeAction", &ClangdLSPServer::onCodeAction);
951 MsgHandler->bind("textDocument/completion", &ClangdLSPServer::onCompletion);
952 MsgHandler->bind("textDocument/signatureHelp", &ClangdLSPServer::onSignatureHelp);
953 MsgHandler->bind("textDocument/definition", &ClangdLSPServer::onGoToDefinition);
Sam McCall866ba2c2019-02-01 11:26:13 +0000954 MsgHandler->bind("textDocument/declaration", &ClangdLSPServer::onGoToDeclaration);
Sam McCall2c30fbc2018-10-18 12:32:04 +0000955 MsgHandler->bind("textDocument/references", &ClangdLSPServer::onReference);
956 MsgHandler->bind("textDocument/switchSourceHeader", &ClangdLSPServer::onSwitchSourceHeader);
957 MsgHandler->bind("textDocument/rename", &ClangdLSPServer::onRename);
958 MsgHandler->bind("textDocument/hover", &ClangdLSPServer::onHover);
959 MsgHandler->bind("textDocument/documentSymbol", &ClangdLSPServer::onDocumentSymbol);
960 MsgHandler->bind("workspace/executeCommand", &ClangdLSPServer::onCommand);
961 MsgHandler->bind("textDocument/documentHighlight", &ClangdLSPServer::onDocumentHighlight);
962 MsgHandler->bind("workspace/symbol", &ClangdLSPServer::onWorkspaceSymbol);
963 MsgHandler->bind("textDocument/didOpen", &ClangdLSPServer::onDocumentDidOpen);
964 MsgHandler->bind("textDocument/didClose", &ClangdLSPServer::onDocumentDidClose);
965 MsgHandler->bind("textDocument/didChange", &ClangdLSPServer::onDocumentDidChange);
966 MsgHandler->bind("workspace/didChangeWatchedFiles", &ClangdLSPServer::onFileEvent);
967 MsgHandler->bind("workspace/didChangeConfiguration", &ClangdLSPServer::onChangeConfiguration);
Jan Korousb4067012018-11-27 16:40:46 +0000968 MsgHandler->bind("textDocument/symbolInfo", &ClangdLSPServer::onSymbolInfo);
Kadir Cetinkaya86658022019-03-19 09:27:04 +0000969 MsgHandler->bind("textDocument/typeHierarchy", &ClangdLSPServer::onTypeHierarchy);
Sam McCall2c30fbc2018-10-18 12:32:04 +0000970 // clang-format on
971}
972
973ClangdLSPServer::~ClangdLSPServer() = default;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000974
Sam McCalldc8f3cf2018-10-17 07:32:05 +0000975bool ClangdLSPServer::run() {
Ilya Biryukovafb55542017-05-16 14:40:30 +0000976 // Run the Language Server loop.
Sam McCalldc8f3cf2018-10-17 07:32:05 +0000977 bool CleanExit = true;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000978 if (auto Err = Transp.loop(*MsgHandler)) {
Sam McCalldc8f3cf2018-10-17 07:32:05 +0000979 elog("Transport error: {0}", std::move(Err));
980 CleanExit = false;
981 }
Ilya Biryukovafb55542017-05-16 14:40:30 +0000982
Ilya Biryukov652364b2018-09-26 05:48:29 +0000983 // Destroy ClangdServer to ensure all worker threads finish.
984 Server.reset();
Sam McCalldc8f3cf2018-10-17 07:32:05 +0000985 return CleanExit && ShutdownRequestReceived;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000986}
987
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000988std::vector<Fix> ClangdLSPServer::getFixes(llvm::StringRef File,
Ilya Biryukov71028b82018-03-12 15:28:22 +0000989 const clangd::Diagnostic &D) {
Ilya Biryukov38d79772017-05-16 09:38:59 +0000990 std::lock_guard<std::mutex> Lock(FixItsMutex);
991 auto DiagToFixItsIter = FixItsMap.find(File);
992 if (DiagToFixItsIter == FixItsMap.end())
993 return {};
994
995 const auto &DiagToFixItsMap = DiagToFixItsIter->second;
996 auto FixItsIter = DiagToFixItsMap.find(D);
997 if (FixItsIter == DiagToFixItsMap.end())
998 return {};
999
1000 return FixItsIter->second;
1001}
1002
Ilya Biryukovb0826bd2019-01-03 13:37:12 +00001003bool ClangdLSPServer::shouldRunCompletion(
1004 const CompletionParams &Params) const {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001005 llvm::StringRef Trigger = Params.context.triggerCharacter;
Ilya Biryukovb0826bd2019-01-03 13:37:12 +00001006 if (Params.context.triggerKind != CompletionTriggerKind::TriggerCharacter ||
1007 (Trigger != ">" && Trigger != ":"))
1008 return true;
1009
1010 auto Code = DraftMgr.getDraft(Params.textDocument.uri.file());
1011 if (!Code)
1012 return true; // completion code will log the error for untracked doc.
1013
1014 // A completion request is sent when the user types '>' or ':', but we only
1015 // want to trigger on '->' and '::'. We check the preceeding character to make
1016 // sure it matches what we expected.
1017 // Running the lexer here would be more robust (e.g. we can detect comments
1018 // and avoid triggering completion there), but we choose to err on the side
1019 // of simplicity here.
1020 auto Offset = positionToOffset(*Code, Params.position,
1021 /*AllowColumnsBeyondLineLength=*/false);
1022 if (!Offset) {
1023 vlog("could not convert position '{0}' to offset for file '{1}'",
1024 Params.position, Params.textDocument.uri.file());
1025 return true;
1026 }
1027 if (*Offset < 2)
1028 return false;
1029
1030 if (Trigger == ">")
1031 return (*Code)[*Offset - 2] == '-'; // trigger only on '->'.
1032 if (Trigger == ":")
1033 return (*Code)[*Offset - 2] == ':'; // trigger only on '::'.
1034 assert(false && "unhandled trigger character");
1035 return true;
1036}
1037
Sam McCalla7bb0cc2018-03-12 23:22:35 +00001038void ClangdLSPServer::onDiagnosticsReady(PathRef File,
1039 std::vector<Diag> Diagnostics) {
Eric Liu4d814a92018-11-28 10:30:42 +00001040 auto URI = URIForFile::canonicalize(File, /*TUPath=*/File);
Sam McCall16e70702018-10-24 07:59:38 +00001041 std::vector<Diagnostic> LSPDiagnostics;
Ilya Biryukov38d79772017-05-16 09:38:59 +00001042 DiagnosticToReplacementMap LocalFixIts; // Temporary storage
Sam McCalla7bb0cc2018-03-12 23:22:35 +00001043 for (auto &Diag : Diagnostics) {
Sam McCall16e70702018-10-24 07:59:38 +00001044 toLSPDiags(Diag, URI, DiagOpts,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001045 [&](clangd::Diagnostic Diag, llvm::ArrayRef<Fix> Fixes) {
Sam McCall16e70702018-10-24 07:59:38 +00001046 auto &FixItsForDiagnostic = LocalFixIts[Diag];
1047 llvm::copy(Fixes, std::back_inserter(FixItsForDiagnostic));
1048 LSPDiagnostics.push_back(std::move(Diag));
1049 });
Ilya Biryukov38d79772017-05-16 09:38:59 +00001050 }
1051
1052 // Cache FixIts
1053 {
Ilya Biryukov38d79772017-05-16 09:38:59 +00001054 std::lock_guard<std::mutex> Lock(FixItsMutex);
1055 FixItsMap[File] = LocalFixIts;
1056 }
1057
Ilya Biryukov49c10712019-03-25 10:15:11 +00001058 // Send a notification to the LSP client.
1059 publishDiagnostics(URI, std::move(LSPDiagnostics));
Ilya Biryukov38d79772017-05-16 09:38:59 +00001060}
Simon Marchi9569fd52018-03-16 14:30:42 +00001061
Haojian Wub6188492018-12-20 15:39:12 +00001062void ClangdLSPServer::onFileUpdated(PathRef File, const TUStatus &Status) {
1063 if (!SupportFileStatus)
1064 return;
1065 // FIXME: we don't emit "BuildingFile" and `RunningAction`, as these
1066 // two statuses are running faster in practice, which leads the UI constantly
1067 // changing, and doesn't provide much value. We may want to emit status at a
1068 // reasonable time interval (e.g. 0.5s).
1069 if (Status.Action.S == TUAction::BuildingFile ||
1070 Status.Action.S == TUAction::RunningAction)
1071 return;
1072 notify("textDocument/clangd.fileStatus", Status.render(File));
1073}
1074
Simon Marchi9569fd52018-03-16 14:30:42 +00001075void ClangdLSPServer::reparseOpenedFiles() {
1076 for (const Path &FilePath : DraftMgr.getActiveFiles())
Ilya Biryukov652364b2018-09-26 05:48:29 +00001077 Server->addDocument(FilePath, *DraftMgr.getDraft(FilePath),
1078 WantDiagnostics::Auto);
Simon Marchi9569fd52018-03-16 14:30:42 +00001079}
Alex Lorenzf8087862018-08-01 17:39:29 +00001080
Sam McCallc008af62018-10-20 15:30:37 +00001081} // namespace clangd
1082} // namespace clang