blob: 7eaacd26e551acbfdea1bbb44efc883b78cf605d [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"
Sam McCall395fde72019-06-18 13:37:54 +000016#include "refactor/Tweak.h"
Ilya Biryukovcce67a32019-01-29 14:17:36 +000017#include "clang/Tooling/Core/Replacement.h"
Sam McCalla69698f2019-03-27 17:47:49 +000018#include "llvm/ADT/Optional.h"
Kadir Cetinkaya689bf932018-08-24 13:09:41 +000019#include "llvm/ADT/ScopeExit.h"
Simon Marchi9569fd52018-03-16 14:30:42 +000020#include "llvm/Support/Errc.h"
Ilya Biryukovcce67a32019-01-29 14:17:36 +000021#include "llvm/Support/Error.h"
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +000022#include "llvm/Support/FormatVariadic.h"
Eric Liu5740ff52018-01-31 16:26:27 +000023#include "llvm/Support/Path.h"
Sam McCall2c30fbc2018-10-18 12:32:04 +000024#include "llvm/Support/ScopedPrinter.h"
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +000025
Sam McCallc008af62018-10-20 15:30:37 +000026namespace clang {
27namespace clangd {
Ilya Biryukovafb55542017-05-16 14:40:30 +000028namespace {
Ilya Biryukovcce67a32019-01-29 14:17:36 +000029/// Transforms a tweak into a code action that would apply it if executed.
30/// EXPECTS: T.prepare() was called and returned true.
31CodeAction toCodeAction(const ClangdServer::TweakRef &T, const URIForFile &File,
32 Range Selection) {
33 CodeAction CA;
34 CA.title = T.Title;
Sam McCall395fde72019-06-18 13:37:54 +000035 switch (T.Intent) {
36 case Tweak::Refactor:
37 CA.kind = CodeAction::REFACTOR_KIND;
38 break;
39 case Tweak::Info:
40 CA.kind = CodeAction::INFO_KIND;
41 break;
42 }
Ilya Biryukovcce67a32019-01-29 14:17:36 +000043 // This tweak may have an expensive second stage, we only run it if the user
44 // actually chooses it in the UI. We reply with a command that would run the
45 // corresponding tweak.
46 // FIXME: for some tweaks, computing the edits is cheap and we could send them
47 // directly.
48 CA.command.emplace();
49 CA.command->title = T.Title;
50 CA.command->command = Command::CLANGD_APPLY_TWEAK;
51 CA.command->tweakArgs.emplace();
52 CA.command->tweakArgs->file = File;
53 CA.command->tweakArgs->tweakID = T.ID;
54 CA.command->tweakArgs->selection = Selection;
55 return CA;
Simon Pilgrime9a136b2019-02-03 14:08:30 +000056}
Ilya Biryukovcce67a32019-01-29 14:17:36 +000057
Ilya Biryukov19d75602018-11-23 15:21:19 +000058void adjustSymbolKinds(llvm::MutableArrayRef<DocumentSymbol> Syms,
59 SymbolKindBitset Kinds) {
60 for (auto &S : Syms) {
61 S.kind = adjustKindToCapability(S.kind, Kinds);
62 adjustSymbolKinds(S.children, Kinds);
63 }
64}
65
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +000066SymbolKindBitset defaultSymbolKinds() {
67 SymbolKindBitset Defaults;
68 for (size_t I = SymbolKindMin; I <= static_cast<size_t>(SymbolKind::Array);
69 ++I)
70 Defaults.set(I);
71 return Defaults;
72}
73
Kadir Cetinkaya133d46f2018-09-27 17:13:07 +000074CompletionItemKindBitset defaultCompletionItemKinds() {
75 CompletionItemKindBitset Defaults;
76 for (size_t I = CompletionItemKindMin;
77 I <= static_cast<size_t>(CompletionItemKind::Reference); ++I)
78 Defaults.set(I);
79 return Defaults;
80}
81
Ilya Biryukovafb55542017-05-16 14:40:30 +000082} // namespace
83
Sam McCall2c30fbc2018-10-18 12:32:04 +000084// MessageHandler dispatches incoming LSP messages.
85// It handles cross-cutting concerns:
86// - serializes/deserializes protocol objects to JSON
87// - logging of inbound messages
88// - cancellation handling
89// - basic call tracing
Sam McCall3d0adbe2018-10-18 14:41:50 +000090// MessageHandler ensures that initialize() is called before any other handler.
Sam McCall2c30fbc2018-10-18 12:32:04 +000091class ClangdLSPServer::MessageHandler : public Transport::MessageHandler {
92public:
93 MessageHandler(ClangdLSPServer &Server) : Server(Server) {}
94
Ilya Biryukovf2001aa2019-01-07 15:45:19 +000095 bool onNotify(llvm::StringRef Method, llvm::json::Value Params) override {
Sam McCalla69698f2019-03-27 17:47:49 +000096 WithContext HandlerContext(handlerContext());
Sam McCall2c30fbc2018-10-18 12:32:04 +000097 log("<-- {0}", Method);
98 if (Method == "exit")
99 return false;
Sam McCall3d0adbe2018-10-18 14:41:50 +0000100 if (!Server.Server)
101 elog("Notification {0} before initialization", Method);
102 else if (Method == "$/cancelRequest")
Sam McCall2c30fbc2018-10-18 12:32:04 +0000103 onCancel(std::move(Params));
104 else if (auto Handler = Notifications.lookup(Method))
105 Handler(std::move(Params));
106 else
107 log("unhandled notification {0}", Method);
108 return true;
109 }
110
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000111 bool onCall(llvm::StringRef Method, llvm::json::Value Params,
112 llvm::json::Value ID) override {
Sam McCalla69698f2019-03-27 17:47:49 +0000113 WithContext HandlerContext(handlerContext());
Sam McCalle2f3a732018-10-24 14:26:26 +0000114 // Calls can be canceled by the client. Add cancellation context.
115 WithContext WithCancel(cancelableRequestContext(ID));
116 trace::Span Tracer(Method);
117 SPAN_ATTACH(Tracer, "Params", Params);
118 ReplyOnce Reply(ID, Method, &Server, Tracer.Args);
Sam McCall2c30fbc2018-10-18 12:32:04 +0000119 log("<-- {0}({1})", Method, ID);
Sam McCall3d0adbe2018-10-18 14:41:50 +0000120 if (!Server.Server && Method != "initialize") {
121 elog("Call {0} before initialization.", Method);
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000122 Reply(llvm::make_error<LSPError>("server not initialized",
123 ErrorCode::ServerNotInitialized));
Sam McCall3d0adbe2018-10-18 14:41:50 +0000124 } else if (auto Handler = Calls.lookup(Method))
Sam McCalle2f3a732018-10-24 14:26:26 +0000125 Handler(std::move(Params), std::move(Reply));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000126 else
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000127 Reply(llvm::make_error<LSPError>("method not found",
128 ErrorCode::MethodNotFound));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000129 return true;
130 }
131
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000132 bool onReply(llvm::json::Value ID,
133 llvm::Expected<llvm::json::Value> Result) override {
Sam McCalla69698f2019-03-27 17:47:49 +0000134 WithContext HandlerContext(handlerContext());
Sam McCall2c30fbc2018-10-18 12:32:04 +0000135 // We ignore replies, just log them.
136 if (Result)
137 log("<-- reply({0})", ID);
138 else
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000139 log("<-- reply({0}) error: {1}", ID, llvm::toString(Result.takeError()));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000140 return true;
141 }
142
143 // Bind an LSP method name to a call.
Sam McCalle2f3a732018-10-24 14:26:26 +0000144 template <typename Param, typename Result>
Sam McCall2c30fbc2018-10-18 12:32:04 +0000145 void bind(const char *Method,
Sam McCalle2f3a732018-10-24 14:26:26 +0000146 void (ClangdLSPServer::*Handler)(const Param &, Callback<Result>)) {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000147 Calls[Method] = [Method, Handler, this](llvm::json::Value RawParams,
Sam McCalle2f3a732018-10-24 14:26:26 +0000148 ReplyOnce Reply) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000149 Param P;
Sam McCalle2f3a732018-10-24 14:26:26 +0000150 if (fromJSON(RawParams, P)) {
151 (Server.*Handler)(P, std::move(Reply));
152 } else {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000153 elog("Failed to decode {0} request.", Method);
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000154 Reply(llvm::make_error<LSPError>("failed to decode request",
155 ErrorCode::InvalidRequest));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000156 }
Sam McCall2c30fbc2018-10-18 12:32:04 +0000157 };
158 }
159
160 // Bind an LSP method name to a notification.
161 template <typename Param>
162 void bind(const char *Method,
163 void (ClangdLSPServer::*Handler)(const Param &)) {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000164 Notifications[Method] = [Method, Handler,
165 this](llvm::json::Value RawParams) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000166 Param P;
167 if (!fromJSON(RawParams, P)) {
168 elog("Failed to decode {0} request.", Method);
169 return;
170 }
171 trace::Span Tracer(Method);
172 SPAN_ATTACH(Tracer, "Params", RawParams);
173 (Server.*Handler)(P);
174 };
175 }
176
177private:
Sam McCalle2f3a732018-10-24 14:26:26 +0000178 // Function object to reply to an LSP call.
179 // Each instance must be called exactly once, otherwise:
180 // - the bug is logged, and (in debug mode) an assert will fire
181 // - if there was no reply, an error reply is sent
182 // - if there were multiple replies, only the first is sent
183 class ReplyOnce {
184 std::atomic<bool> Replied = {false};
Sam McCalld7babe42018-10-24 15:18:40 +0000185 std::chrono::steady_clock::time_point Start;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000186 llvm::json::Value ID;
Sam McCalle2f3a732018-10-24 14:26:26 +0000187 std::string Method;
188 ClangdLSPServer *Server; // Null when moved-from.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000189 llvm::json::Object *TraceArgs;
Sam McCalle2f3a732018-10-24 14:26:26 +0000190
191 public:
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000192 ReplyOnce(const llvm::json::Value &ID, llvm::StringRef Method,
193 ClangdLSPServer *Server, llvm::json::Object *TraceArgs)
Sam McCalld7babe42018-10-24 15:18:40 +0000194 : Start(std::chrono::steady_clock::now()), ID(ID), Method(Method),
195 Server(Server), TraceArgs(TraceArgs) {
Sam McCalle2f3a732018-10-24 14:26:26 +0000196 assert(Server);
197 }
198 ReplyOnce(ReplyOnce &&Other)
Sam McCalld7babe42018-10-24 15:18:40 +0000199 : Replied(Other.Replied.load()), Start(Other.Start),
200 ID(std::move(Other.ID)), Method(std::move(Other.Method)),
201 Server(Other.Server), TraceArgs(Other.TraceArgs) {
Sam McCalle2f3a732018-10-24 14:26:26 +0000202 Other.Server = nullptr;
203 }
Ilya Biryukov22fa4652019-01-03 13:28:05 +0000204 ReplyOnce &operator=(ReplyOnce &&) = delete;
Sam McCalle2f3a732018-10-24 14:26:26 +0000205 ReplyOnce(const ReplyOnce &) = delete;
Ilya Biryukov22fa4652019-01-03 13:28:05 +0000206 ReplyOnce &operator=(const ReplyOnce &) = delete;
Sam McCalle2f3a732018-10-24 14:26:26 +0000207
208 ~ReplyOnce() {
209 if (Server && !Replied) {
210 elog("No reply to message {0}({1})", Method, ID);
211 assert(false && "must reply to all calls!");
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000212 (*this)(llvm::make_error<LSPError>("server failed to reply",
213 ErrorCode::InternalError));
Sam McCalle2f3a732018-10-24 14:26:26 +0000214 }
215 }
216
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000217 void operator()(llvm::Expected<llvm::json::Value> Reply) {
Sam McCalle2f3a732018-10-24 14:26:26 +0000218 assert(Server && "moved-from!");
219 if (Replied.exchange(true)) {
220 elog("Replied twice to message {0}({1})", Method, ID);
221 assert(false && "must reply to each call only once!");
222 return;
223 }
Sam McCalld7babe42018-10-24 15:18:40 +0000224 auto Duration = std::chrono::steady_clock::now() - Start;
225 if (Reply) {
226 log("--> reply:{0}({1}) {2:ms}", Method, ID, Duration);
227 if (TraceArgs)
Sam McCalle2f3a732018-10-24 14:26:26 +0000228 (*TraceArgs)["Reply"] = *Reply;
Sam McCalld7babe42018-10-24 15:18:40 +0000229 std::lock_guard<std::mutex> Lock(Server->TranspWriter);
230 Server->Transp.reply(std::move(ID), std::move(Reply));
231 } else {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000232 llvm::Error Err = Reply.takeError();
Sam McCalld7babe42018-10-24 15:18:40 +0000233 log("--> reply:{0}({1}) {2:ms}, error: {3}", Method, ID, Duration, Err);
234 if (TraceArgs)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000235 (*TraceArgs)["Error"] = llvm::to_string(Err);
Sam McCalld7babe42018-10-24 15:18:40 +0000236 std::lock_guard<std::mutex> Lock(Server->TranspWriter);
237 Server->Transp.reply(std::move(ID), std::move(Err));
Sam McCalle2f3a732018-10-24 14:26:26 +0000238 }
Sam McCalle2f3a732018-10-24 14:26:26 +0000239 }
240 };
241
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000242 llvm::StringMap<std::function<void(llvm::json::Value)>> Notifications;
243 llvm::StringMap<std::function<void(llvm::json::Value, ReplyOnce)>> Calls;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000244
245 // Method calls may be cancelled by ID, so keep track of their state.
246 // This needs a mutex: handlers may finish on a different thread, and that's
247 // when we clean up entries in the map.
248 mutable std::mutex RequestCancelersMutex;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000249 llvm::StringMap<std::pair<Canceler, /*Cookie*/ unsigned>> RequestCancelers;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000250 unsigned NextRequestCookie = 0; // To disambiguate reused IDs, see below.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000251 void onCancel(const llvm::json::Value &Params) {
252 const llvm::json::Value *ID = nullptr;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000253 if (auto *O = Params.getAsObject())
254 ID = O->get("id");
255 if (!ID) {
256 elog("Bad cancellation request: {0}", Params);
257 return;
258 }
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000259 auto StrID = llvm::to_string(*ID);
Sam McCall2c30fbc2018-10-18 12:32:04 +0000260 std::lock_guard<std::mutex> Lock(RequestCancelersMutex);
261 auto It = RequestCancelers.find(StrID);
262 if (It != RequestCancelers.end())
263 It->second.first(); // Invoke the canceler.
264 }
Sam McCalla69698f2019-03-27 17:47:49 +0000265
266 Context handlerContext() const {
267 return Context::current().derive(
268 kCurrentOffsetEncoding,
269 Server.NegotiatedOffsetEncoding.getValueOr(OffsetEncoding::UTF16));
270 }
271
Sam McCall2c30fbc2018-10-18 12:32:04 +0000272 // We run cancelable requests in a context that does two things:
273 // - allows cancellation using RequestCancelers[ID]
274 // - cleans up the entry in RequestCancelers when it's no longer needed
275 // If a client reuses an ID, the last wins and the first cannot be canceled.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000276 Context cancelableRequestContext(const llvm::json::Value &ID) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000277 auto Task = cancelableTask();
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000278 auto StrID = llvm::to_string(ID); // JSON-serialize ID for map key.
Sam McCall2c30fbc2018-10-18 12:32:04 +0000279 auto Cookie = NextRequestCookie++; // No lock, only called on main thread.
280 {
281 std::lock_guard<std::mutex> Lock(RequestCancelersMutex);
282 RequestCancelers[StrID] = {std::move(Task.second), Cookie};
283 }
284 // When the request ends, we can clean up the entry we just added.
285 // The cookie lets us check that it hasn't been overwritten due to ID
286 // reuse.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000287 return Task.first.derive(llvm::make_scope_exit([this, StrID, Cookie] {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000288 std::lock_guard<std::mutex> Lock(RequestCancelersMutex);
289 auto It = RequestCancelers.find(StrID);
290 if (It != RequestCancelers.end() && It->second.second == Cookie)
291 RequestCancelers.erase(It);
292 }));
293 }
294
295 ClangdLSPServer &Server;
296};
297
298// call(), notify(), and reply() wrap the Transport, adding logging and locking.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000299void ClangdLSPServer::call(llvm::StringRef Method, llvm::json::Value Params) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000300 auto ID = NextCallID++;
301 log("--> {0}({1})", Method, ID);
302 // We currently don't handle responses, so no need to store ID anywhere.
303 std::lock_guard<std::mutex> Lock(TranspWriter);
304 Transp.call(Method, std::move(Params), ID);
305}
306
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000307void ClangdLSPServer::notify(llvm::StringRef Method, llvm::json::Value Params) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000308 log("--> {0}", Method);
309 std::lock_guard<std::mutex> Lock(TranspWriter);
310 Transp.notify(Method, std::move(Params));
311}
312
Sam McCall2c30fbc2018-10-18 12:32:04 +0000313void ClangdLSPServer::onInitialize(const InitializeParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000314 Callback<llvm::json::Value> Reply) {
Sam McCalla69698f2019-03-27 17:47:49 +0000315 // Determine character encoding first as it affects constructed ClangdServer.
316 if (Params.capabilities.offsetEncoding && !NegotiatedOffsetEncoding) {
317 NegotiatedOffsetEncoding = OffsetEncoding::UTF16; // fallback
318 for (OffsetEncoding Supported : *Params.capabilities.offsetEncoding)
319 if (Supported != OffsetEncoding::UnsupportedEncoding) {
320 NegotiatedOffsetEncoding = Supported;
321 break;
322 }
323 }
324 llvm::Optional<WithContextValue> WithOffsetEncoding;
325 if (NegotiatedOffsetEncoding)
326 WithOffsetEncoding.emplace(kCurrentOffsetEncoding,
327 *NegotiatedOffsetEncoding);
328
Sam McCall0d9b40f2018-10-19 15:42:23 +0000329 if (Params.rootUri && *Params.rootUri)
330 ClangdServerOpts.WorkspaceRoot = Params.rootUri->file();
331 else if (Params.rootPath && !Params.rootPath->empty())
332 ClangdServerOpts.WorkspaceRoot = *Params.rootPath;
Sam McCall3d0adbe2018-10-18 14:41:50 +0000333 if (Server)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000334 return Reply(llvm::make_error<LSPError>("server already initialized",
335 ErrorCode::InvalidRequest));
Sam McCallbc904612018-10-25 04:22:52 +0000336 if (const auto &Dir = Params.initializationOptions.compilationDatabasePath)
337 CompileCommandsDir = Dir;
Sam McCallc55d09a2018-11-02 13:09:36 +0000338 if (UseDirBasedCDB)
339 BaseCDB = llvm::make_unique<DirectoryBasedGlobalCompilationDatabase>(
340 CompileCommandsDir);
Kadir Cetinkayabe6b35d2019-01-22 09:10:20 +0000341 CDB.emplace(BaseCDB.get(), Params.initializationOptions.fallbackFlags,
342 ClangdServerOpts.ResourceDir);
Sam McCallc55d09a2018-11-02 13:09:36 +0000343 Server.emplace(*CDB, FSProvider, static_cast<DiagnosticsConsumer &>(*this),
344 ClangdServerOpts);
Sam McCallbc904612018-10-25 04:22:52 +0000345 applyConfiguration(Params.initializationOptions.ConfigSettings);
Simon Marchi88016782018-08-01 11:28:49 +0000346
Sam McCallbf6a2fc2018-10-17 07:33:42 +0000347 CCOpts.EnableSnippets = Params.capabilities.CompletionSnippets;
Sam McCall8d412942019-06-18 11:57:26 +0000348 CCOpts.IncludeFixIts = Params.capabilities.CompletionFixes;
Sam McCallbf6a2fc2018-10-17 07:33:42 +0000349 DiagOpts.EmbedFixesInDiagnostics = Params.capabilities.DiagnosticFixes;
350 DiagOpts.SendDiagnosticCategory = Params.capabilities.DiagnosticCategory;
Sam McCallc9e4ee92019-04-18 15:17:07 +0000351 DiagOpts.EmitRelatedLocations =
352 Params.capabilities.DiagnosticRelatedInformation;
Sam McCallbf6a2fc2018-10-17 07:33:42 +0000353 if (Params.capabilities.WorkspaceSymbolKinds)
354 SupportedSymbolKinds |= *Params.capabilities.WorkspaceSymbolKinds;
355 if (Params.capabilities.CompletionItemKinds)
356 SupportedCompletionItemKinds |= *Params.capabilities.CompletionItemKinds;
357 SupportsCodeAction = Params.capabilities.CodeActionStructure;
Ilya Biryukov19d75602018-11-23 15:21:19 +0000358 SupportsHierarchicalDocumentSymbol =
359 Params.capabilities.HierarchicalDocumentSymbol;
Haojian Wub6188492018-12-20 15:39:12 +0000360 SupportFileStatus = Params.initializationOptions.FileStatus;
Ilya Biryukovf9169d02019-05-29 10:01:00 +0000361 HoverContentFormat = Params.capabilities.HoverContentFormat;
Ilya Biryukov4ef0f822019-06-04 09:36:59 +0000362 SupportsOffsetsInSignatureHelp = Params.capabilities.OffsetsInSignatureHelp;
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 McCall25c62572019-06-10 14:26:21 +0000371 {"firstTriggerCharacter", "\n"},
Sam McCall0930ab02017-11-07 15:49:35 +0000372 {"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
Sam McCall395fde72019-06-18 13:37:54 +0000492 auto Action = [this, ApplyEdit](decltype(Reply) Reply, URIForFile File,
493 std::string Code,
Ilya Biryukovdf9ee082019-06-18 15:15:41 +0000494 llvm::Expected<ResolvedEffect> R) {
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000495 if (!R)
496 return Reply(R.takeError());
497
Sam McCall395fde72019-06-18 13:37:54 +0000498 if (R->ApplyEdit) {
499 WorkspaceEdit WE;
500 WE.changes.emplace();
Ilya Biryukovdf9ee082019-06-18 15:15:41 +0000501 (*WE.changes)[File.uri()] = *R->ApplyEdit;
Sam McCall395fde72019-06-18 13:37:54 +0000502 ApplyEdit(std::move(WE));
503 }
504 if (R->ShowMessage) {
505 ShowMessageParams Msg;
506 Msg.message = *R->ShowMessage;
507 Msg.type = MessageType::Info;
508 notify("window/showMessage", Msg);
509 }
510 Reply("Tweak applied.");
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000511 };
512 Server->applyTweak(Params.tweakArgs->file.file(),
513 Params.tweakArgs->selection, Params.tweakArgs->tweakID,
514 Bind(Action, std::move(Reply), Params.tweakArgs->file,
515 std::move(*Code)));
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000516 } else {
517 // We should not get here because ExecuteCommandParams would not have
518 // parsed in the first place and this handler should not be called. But if
519 // more commands are added, this will be here has a safe guard.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000520 Reply(llvm::make_error<LSPError>(
521 llvm::formatv("Unsupported command \"{0}\".", Params.command).str(),
Sam McCall2c30fbc2018-10-18 12:32:04 +0000522 ErrorCode::InvalidParams));
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000523 }
524}
525
Sam McCall2c30fbc2018-10-18 12:32:04 +0000526void ClangdLSPServer::onWorkspaceSymbol(
527 const WorkspaceSymbolParams &Params,
528 Callback<std::vector<SymbolInformation>> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000529 Server->workspaceSymbols(
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000530 Params.query, CCOpts.Limit,
Sam McCall2c30fbc2018-10-18 12:32:04 +0000531 Bind(
532 [this](decltype(Reply) Reply,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000533 llvm::Expected<std::vector<SymbolInformation>> Items) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000534 if (!Items)
535 return Reply(Items.takeError());
536 for (auto &Sym : *Items)
537 Sym.kind = adjustKindToCapability(Sym.kind, SupportedSymbolKinds);
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000538
Sam McCall2c30fbc2018-10-18 12:32:04 +0000539 Reply(std::move(*Items));
540 },
541 std::move(Reply)));
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000542}
543
Sam McCall2c30fbc2018-10-18 12:32:04 +0000544void ClangdLSPServer::onRename(const RenameParams &Params,
545 Callback<WorkspaceEdit> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000546 Path File = Params.textDocument.uri.file();
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000547 llvm::Optional<std::string> Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000548 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000549 return Reply(llvm::make_error<LSPError>(
550 "onRename called for non-added file", ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000551
Ilya Biryukov652364b2018-09-26 05:48:29 +0000552 Server->rename(
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000553 File, Params.position, Params.newName,
Sam McCall2c30fbc2018-10-18 12:32:04 +0000554 Bind(
Ilya Biryukovd9c24dc2019-04-03 07:18:43 +0000555 [File, Code, Params](decltype(Reply) Reply,
556 llvm::Expected<std::vector<TextEdit>> Edits) {
557 if (!Edits)
558 return Reply(Edits.takeError());
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000559
Sam McCall2c30fbc2018-10-18 12:32:04 +0000560 WorkspaceEdit WE;
Ilya Biryukovd9c24dc2019-04-03 07:18:43 +0000561 WE.changes = {{Params.textDocument.uri.uri(), *Edits}};
Sam McCall2c30fbc2018-10-18 12:32:04 +0000562 Reply(WE);
563 },
564 std::move(Reply)));
Haojian Wu345099c2017-11-09 11:30:04 +0000565}
566
Sam McCall2c30fbc2018-10-18 12:32:04 +0000567void ClangdLSPServer::onDocumentDidClose(
568 const DidCloseTextDocumentParams &Params) {
Simon Marchi9569fd52018-03-16 14:30:42 +0000569 PathRef File = Params.textDocument.uri.file();
570 DraftMgr.removeDraft(File);
Ilya Biryukov652364b2018-09-26 05:48:29 +0000571 Server->removeDocument(File);
Ilya Biryukov49c10712019-03-25 10:15:11 +0000572
573 {
574 std::lock_guard<std::mutex> Lock(FixItsMutex);
575 FixItsMap.erase(File);
576 }
577 // clangd will not send updates for this file anymore, so we empty out the
578 // list of diagnostics shown on the client (e.g. in the "Problems" pane of
579 // VSCode). Note that this cannot race with actual diagnostics responses
580 // because removeDocument() guarantees no diagnostic callbacks will be
581 // executed after it returns.
582 publishDiagnostics(URIForFile::canonicalize(File, /*TUPath=*/File), {});
Ilya Biryukovafb55542017-05-16 14:40:30 +0000583}
584
Sam McCall4db732a2017-09-30 10:08:52 +0000585void ClangdLSPServer::onDocumentOnTypeFormatting(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000586 const DocumentOnTypeFormattingParams &Params,
587 Callback<std::vector<TextEdit>> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000588 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000589 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000590 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000591 return Reply(llvm::make_error<LSPError>(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000592 "onDocumentOnTypeFormatting called for non-added file",
593 ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000594
Sam McCall25c62572019-06-10 14:26:21 +0000595 Reply(Server->formatOnType(*Code, File, Params.position, Params.ch));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000596}
597
Sam McCall4db732a2017-09-30 10:08:52 +0000598void ClangdLSPServer::onDocumentRangeFormatting(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000599 const DocumentRangeFormattingParams &Params,
600 Callback<std::vector<TextEdit>> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000601 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000602 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000603 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000604 return Reply(llvm::make_error<LSPError>(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000605 "onDocumentRangeFormatting called for non-added file",
606 ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000607
Ilya Biryukov652364b2018-09-26 05:48:29 +0000608 auto ReplacementsOrError = Server->formatRange(*Code, File, Params.range);
Raoul Wols212bcf82017-12-12 20:25:06 +0000609 if (ReplacementsOrError)
Sam McCall2c30fbc2018-10-18 12:32:04 +0000610 Reply(replacementsToEdits(*Code, ReplacementsOrError.get()));
Raoul Wols212bcf82017-12-12 20:25:06 +0000611 else
Sam McCall2c30fbc2018-10-18 12:32:04 +0000612 Reply(ReplacementsOrError.takeError());
Ilya Biryukovafb55542017-05-16 14:40:30 +0000613}
614
Sam McCall2c30fbc2018-10-18 12:32:04 +0000615void ClangdLSPServer::onDocumentFormatting(
616 const DocumentFormattingParams &Params,
617 Callback<std::vector<TextEdit>> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000618 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000619 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000620 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000621 return Reply(llvm::make_error<LSPError>(
622 "onDocumentFormatting called for non-added file",
623 ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000624
Ilya Biryukov652364b2018-09-26 05:48:29 +0000625 auto ReplacementsOrError = Server->formatFile(*Code, File);
Raoul Wols212bcf82017-12-12 20:25:06 +0000626 if (ReplacementsOrError)
Sam McCall2c30fbc2018-10-18 12:32:04 +0000627 Reply(replacementsToEdits(*Code, ReplacementsOrError.get()));
Raoul Wols212bcf82017-12-12 20:25:06 +0000628 else
Sam McCall2c30fbc2018-10-18 12:32:04 +0000629 Reply(ReplacementsOrError.takeError());
Sam McCall4db732a2017-09-30 10:08:52 +0000630}
631
Ilya Biryukov19d75602018-11-23 15:21:19 +0000632/// The functions constructs a flattened view of the DocumentSymbol hierarchy.
633/// Used by the clients that do not support the hierarchical view.
634static std::vector<SymbolInformation>
635flattenSymbolHierarchy(llvm::ArrayRef<DocumentSymbol> Symbols,
636 const URIForFile &FileURI) {
637
638 std::vector<SymbolInformation> Results;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000639 std::function<void(const DocumentSymbol &, llvm::StringRef)> Process =
640 [&](const DocumentSymbol &S, llvm::Optional<llvm::StringRef> ParentName) {
Ilya Biryukov19d75602018-11-23 15:21:19 +0000641 SymbolInformation SI;
642 SI.containerName = ParentName ? "" : *ParentName;
643 SI.name = S.name;
644 SI.kind = S.kind;
645 SI.location.range = S.range;
646 SI.location.uri = FileURI;
647
648 Results.push_back(std::move(SI));
649 std::string FullName =
650 !ParentName ? S.name : (ParentName->str() + "::" + S.name);
651 for (auto &C : S.children)
652 Process(C, /*ParentName=*/FullName);
653 };
654 for (auto &S : Symbols)
655 Process(S, /*ParentName=*/"");
656 return Results;
657}
658
659void ClangdLSPServer::onDocumentSymbol(const DocumentSymbolParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000660 Callback<llvm::json::Value> Reply) {
Ilya Biryukov19d75602018-11-23 15:21:19 +0000661 URIForFile FileURI = Params.textDocument.uri;
Ilya Biryukov652364b2018-09-26 05:48:29 +0000662 Server->documentSymbols(
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000663 Params.textDocument.uri.file(),
Sam McCall2c30fbc2018-10-18 12:32:04 +0000664 Bind(
Ilya Biryukov19d75602018-11-23 15:21:19 +0000665 [this, FileURI](decltype(Reply) Reply,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000666 llvm::Expected<std::vector<DocumentSymbol>> Items) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000667 if (!Items)
668 return Reply(Items.takeError());
Ilya Biryukov19d75602018-11-23 15:21:19 +0000669 adjustSymbolKinds(*Items, SupportedSymbolKinds);
670 if (SupportsHierarchicalDocumentSymbol)
671 return Reply(std::move(*Items));
672 else
673 return Reply(flattenSymbolHierarchy(*Items, FileURI));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000674 },
675 std::move(Reply)));
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000676}
677
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000678static llvm::Optional<Command> asCommand(const CodeAction &Action) {
Sam McCall20841d42018-10-16 16:29:41 +0000679 Command Cmd;
680 if (Action.command && Action.edit)
Sam McCallc008af62018-10-20 15:30:37 +0000681 return None; // Not representable. (We never emit these anyway).
Sam McCall20841d42018-10-16 16:29:41 +0000682 if (Action.command) {
683 Cmd = *Action.command;
684 } else if (Action.edit) {
685 Cmd.command = Command::CLANGD_APPLY_FIX_COMMAND;
686 Cmd.workspaceEdit = *Action.edit;
687 } else {
Sam McCallc008af62018-10-20 15:30:37 +0000688 return None;
Sam McCall20841d42018-10-16 16:29:41 +0000689 }
690 Cmd.title = Action.title;
691 if (Action.kind && *Action.kind == CodeAction::QUICKFIX_KIND)
692 Cmd.title = "Apply fix: " + Cmd.title;
693 return Cmd;
694}
695
Sam McCall2c30fbc2018-10-18 12:32:04 +0000696void ClangdLSPServer::onCodeAction(const CodeActionParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000697 Callback<llvm::json::Value> Reply) {
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000698 URIForFile File = Params.textDocument.uri;
699 auto Code = DraftMgr.getDraft(File.file());
Sam McCall2c30fbc2018-10-18 12:32:04 +0000700 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000701 return Reply(llvm::make_error<LSPError>(
702 "onCodeAction called for non-added file", ErrorCode::InvalidParams));
Sam McCall20841d42018-10-16 16:29:41 +0000703 // We provide a code action for Fixes on the specified diagnostics.
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000704 std::vector<CodeAction> FixIts;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000705 for (const Diagnostic &D : Params.context.diagnostics) {
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000706 for (auto &F : getFixes(File.file(), D)) {
707 FixIts.push_back(toCodeAction(F, Params.textDocument.uri));
708 FixIts.back().diagnostics = {D};
Sam McCalldd0566b2017-11-06 15:40:30 +0000709 }
Ilya Biryukovafb55542017-05-16 14:40:30 +0000710 }
Sam McCall20841d42018-10-16 16:29:41 +0000711
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000712 // Now enumerate the semantic code actions.
713 auto ConsumeActions =
714 [this](decltype(Reply) Reply, URIForFile File, std::string Code,
715 Range Selection, std::vector<CodeAction> FixIts,
716 llvm::Expected<std::vector<ClangdServer::TweakRef>> Tweaks) {
Ilya Biryukovc6ed7782019-01-30 14:24:17 +0000717 if (!Tweaks)
718 return Reply(Tweaks.takeError());
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000719
720 std::vector<CodeAction> Actions = std::move(FixIts);
721 Actions.reserve(Actions.size() + Tweaks->size());
722 for (const auto &T : *Tweaks)
723 Actions.push_back(toCodeAction(T, File, Selection));
724
725 if (SupportsCodeAction)
726 return Reply(llvm::json::Array(Actions));
727 std::vector<Command> Commands;
728 for (const auto &Action : Actions) {
729 if (auto Command = asCommand(Action))
730 Commands.push_back(std::move(*Command));
731 }
732 return Reply(llvm::json::Array(Commands));
733 };
734
735 Server->enumerateTweaks(File.file(), Params.range,
Ilya Biryukovc9409c62019-01-30 09:39:01 +0000736 Bind(ConsumeActions, std::move(Reply), File,
737 std::move(*Code), Params.range,
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000738 std::move(FixIts)));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000739}
740
Ilya Biryukovb0826bd2019-01-03 13:37:12 +0000741void ClangdLSPServer::onCompletion(const CompletionParams &Params,
Sam McCall2c30fbc2018-10-18 12:32:04 +0000742 Callback<CompletionList> Reply) {
Ilya Biryukova7a11472019-06-07 16:24:38 +0000743 if (!shouldRunCompletion(Params)) {
744 // Clients sometimes auto-trigger completions in undesired places (e.g.
745 // 'a >^ '), we return empty results in those cases.
746 vlog("ignored auto-triggered completion, preceding char did not match");
747 return Reply(CompletionList());
748 }
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000749 Server->codeComplete(Params.textDocument.uri.file(), Params.position, CCOpts,
750 Bind(
751 [this](decltype(Reply) Reply,
752 llvm::Expected<CodeCompleteResult> List) {
753 if (!List)
754 return Reply(List.takeError());
755 CompletionList LSPList;
756 LSPList.isIncomplete = List->HasMore;
757 for (const auto &R : List->Completions) {
758 CompletionItem C = R.render(CCOpts);
759 C.kind = adjustKindToCapability(
760 C.kind, SupportedCompletionItemKinds);
761 LSPList.items.push_back(std::move(C));
762 }
763 return Reply(std::move(LSPList));
764 },
765 std::move(Reply)));
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000766}
767
Sam McCall2c30fbc2018-10-18 12:32:04 +0000768void ClangdLSPServer::onSignatureHelp(const TextDocumentPositionParams &Params,
769 Callback<SignatureHelp> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000770 Server->signatureHelp(Params.textDocument.uri.file(), Params.position,
Ilya Biryukov4ef0f822019-06-04 09:36:59 +0000771 Bind(
772 [this](decltype(Reply) Reply,
773 llvm::Expected<SignatureHelp> Signature) {
774 if (!Signature)
775 return Reply(Signature.takeError());
776 if (SupportsOffsetsInSignatureHelp)
777 return Reply(std::move(*Signature));
778 // Strip out the offsets from signature help for
779 // clients that only support string labels.
Simon Pilgrim5f7c20e2019-06-04 11:11:51 +0000780 for (auto &SigInfo : Signature->signatures) {
781 for (auto &Param : SigInfo.parameters)
Ilya Biryukov4ef0f822019-06-04 09:36:59 +0000782 Param.labelOffsets.reset();
783 }
784 return Reply(std::move(*Signature));
785 },
786 std::move(Reply)));
Ilya Biryukov652364b2018-09-26 05:48:29 +0000787}
788
Sam McCall0dbab7f2019-02-02 05:56:00 +0000789// Go to definition has a toggle function: if def and decl are distinct, then
790// the first press gives you the def, the second gives you the matching def.
791// getToggle() returns the counterpart location that under the cursor.
792//
793// We return the toggled location alone (ignoring other symbols) to encourage
794// editors to "bounce" quickly between locations, without showing a menu.
795static Location *getToggle(const TextDocumentPositionParams &Point,
796 LocatedSymbol &Sym) {
797 // Toggle only makes sense with two distinct locations.
798 if (!Sym.Definition || *Sym.Definition == Sym.PreferredDeclaration)
799 return nullptr;
800 if (Sym.Definition->uri.file() == Point.textDocument.uri.file() &&
801 Sym.Definition->range.contains(Point.position))
802 return &Sym.PreferredDeclaration;
803 if (Sym.PreferredDeclaration.uri.file() == Point.textDocument.uri.file() &&
804 Sym.PreferredDeclaration.range.contains(Point.position))
805 return &*Sym.Definition;
806 return nullptr;
807}
808
Sam McCall2c30fbc2018-10-18 12:32:04 +0000809void ClangdLSPServer::onGoToDefinition(const TextDocumentPositionParams &Params,
810 Callback<std::vector<Location>> Reply) {
Sam McCall866ba2c2019-02-01 11:26:13 +0000811 Server->locateSymbolAt(
812 Params.textDocument.uri.file(), Params.position,
813 Bind(
Sam McCall0dbab7f2019-02-02 05:56:00 +0000814 [&, Params](decltype(Reply) Reply,
815 llvm::Expected<std::vector<LocatedSymbol>> Symbols) {
Sam McCall866ba2c2019-02-01 11:26:13 +0000816 if (!Symbols)
817 return Reply(Symbols.takeError());
818 std::vector<Location> Defs;
Sam McCall0dbab7f2019-02-02 05:56:00 +0000819 for (auto &S : *Symbols) {
820 if (Location *Toggle = getToggle(Params, S))
821 return Reply(std::vector<Location>{std::move(*Toggle)});
Sam McCall866ba2c2019-02-01 11:26:13 +0000822 Defs.push_back(S.Definition.getValueOr(S.PreferredDeclaration));
Sam McCall0dbab7f2019-02-02 05:56:00 +0000823 }
Sam McCall866ba2c2019-02-01 11:26:13 +0000824 Reply(std::move(Defs));
825 },
826 std::move(Reply)));
827}
828
829void ClangdLSPServer::onGoToDeclaration(
830 const TextDocumentPositionParams &Params,
831 Callback<std::vector<Location>> Reply) {
832 Server->locateSymbolAt(
833 Params.textDocument.uri.file(), Params.position,
834 Bind(
Sam McCall0dbab7f2019-02-02 05:56:00 +0000835 [&, Params](decltype(Reply) Reply,
836 llvm::Expected<std::vector<LocatedSymbol>> Symbols) {
Sam McCall866ba2c2019-02-01 11:26:13 +0000837 if (!Symbols)
838 return Reply(Symbols.takeError());
839 std::vector<Location> Decls;
Sam McCall0dbab7f2019-02-02 05:56:00 +0000840 for (auto &S : *Symbols) {
841 if (Location *Toggle = getToggle(Params, S))
842 return Reply(std::vector<Location>{std::move(*Toggle)});
843 Decls.push_back(std::move(S.PreferredDeclaration));
844 }
Sam McCall866ba2c2019-02-01 11:26:13 +0000845 Reply(std::move(Decls));
846 },
847 std::move(Reply)));
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000848}
849
Sam McCall111fe842019-05-07 07:55:35 +0000850void ClangdLSPServer::onSwitchSourceHeader(
851 const TextDocumentIdentifier &Params,
Sam McCallb9ec3e92019-05-07 08:30:32 +0000852 Callback<llvm::Optional<URIForFile>> Reply) {
Sam McCall111fe842019-05-07 07:55:35 +0000853 if (auto Result = Server->switchSourceHeader(Params.uri.file()))
Sam McCallb9ec3e92019-05-07 08:30:32 +0000854 Reply(URIForFile::canonicalize(*Result, Params.uri.file()));
Sam McCall111fe842019-05-07 07:55:35 +0000855 else
856 Reply(llvm::None);
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000857}
858
Sam McCall2c30fbc2018-10-18 12:32:04 +0000859void ClangdLSPServer::onDocumentHighlight(
860 const TextDocumentPositionParams &Params,
861 Callback<std::vector<DocumentHighlight>> Reply) {
862 Server->findDocumentHighlights(Params.textDocument.uri.file(),
863 Params.position, std::move(Reply));
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000864}
865
Sam McCall2c30fbc2018-10-18 12:32:04 +0000866void ClangdLSPServer::onHover(const TextDocumentPositionParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000867 Callback<llvm::Optional<Hover>> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000868 Server->findHover(Params.textDocument.uri.file(), Params.position,
Kadir Cetinkayac6578ee2019-05-28 10:29:58 +0000869 Bind(
Ilya Biryukovf9169d02019-05-29 10:01:00 +0000870 [this](decltype(Reply) Reply,
871 llvm::Expected<llvm::Optional<HoverInfo>> H) {
872 if (!H)
873 return Reply(H.takeError());
874 if (!*H)
Kadir Cetinkayac6578ee2019-05-28 10:29:58 +0000875 return Reply(llvm::None);
Ilya Biryukovf9169d02019-05-29 10:01:00 +0000876
877 Hover R;
878 R.contents.kind = HoverContentFormat;
879 R.range = (*H)->SymRange;
880 switch (HoverContentFormat) {
881 case MarkupKind::PlainText:
882 R.contents.value =
883 (*H)->present().renderAsPlainText();
884 return Reply(std::move(R));
885 case MarkupKind::Markdown:
886 R.contents.value =
887 (*H)->present().renderAsMarkdown();
888 return Reply(std::move(R));
889 };
890 llvm_unreachable("unhandled MarkupKind");
Kadir Cetinkayac6578ee2019-05-28 10:29:58 +0000891 },
892 std::move(Reply)));
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000893}
894
Kadir Cetinkaya86658022019-03-19 09:27:04 +0000895void ClangdLSPServer::onTypeHierarchy(
896 const TypeHierarchyParams &Params,
897 Callback<Optional<TypeHierarchyItem>> Reply) {
898 Server->typeHierarchy(Params.textDocument.uri.file(), Params.position,
899 Params.resolve, Params.direction, std::move(Reply));
900}
901
Simon Marchi88016782018-08-01 11:28:49 +0000902void ClangdLSPServer::applyConfiguration(
Sam McCallbc904612018-10-25 04:22:52 +0000903 const ConfigurationSettings &Settings) {
Simon Marchiabeed662018-10-16 15:55:03 +0000904 // Per-file update to the compilation database.
Sam McCallbc904612018-10-25 04:22:52 +0000905 bool ShouldReparseOpenFiles = false;
906 for (auto &Entry : Settings.compilationDatabaseChanges) {
907 /// The opened files need to be reparsed only when some existing
908 /// entries are changed.
909 PathRef File = Entry.first;
Sam McCallc55d09a2018-11-02 13:09:36 +0000910 auto Old = CDB->getCompileCommand(File);
911 auto New =
912 tooling::CompileCommand(std::move(Entry.second.workingDirectory), File,
913 std::move(Entry.second.compilationCommand),
914 /*Output=*/"");
Sam McCall6980edb2018-11-02 14:07:51 +0000915 if (Old != New) {
Sam McCallc55d09a2018-11-02 13:09:36 +0000916 CDB->setCompileCommand(File, std::move(New));
Sam McCall6980edb2018-11-02 14:07:51 +0000917 ShouldReparseOpenFiles = true;
918 }
Alex Lorenzf8087862018-08-01 17:39:29 +0000919 }
Sam McCallbc904612018-10-25 04:22:52 +0000920 if (ShouldReparseOpenFiles)
921 reparseOpenedFiles();
Simon Marchi5178f922018-02-22 14:00:39 +0000922}
923
Ilya Biryukov49c10712019-03-25 10:15:11 +0000924void ClangdLSPServer::publishDiagnostics(
925 const URIForFile &File, std::vector<clangd::Diagnostic> Diagnostics) {
926 // Publish diagnostics.
927 notify("textDocument/publishDiagnostics",
928 llvm::json::Object{
929 {"uri", File},
930 {"diagnostics", std::move(Diagnostics)},
931 });
932}
933
Simon Marchi88016782018-08-01 11:28:49 +0000934// FIXME: This function needs to be properly tested.
935void ClangdLSPServer::onChangeConfiguration(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000936 const DidChangeConfigurationParams &Params) {
Simon Marchi88016782018-08-01 11:28:49 +0000937 applyConfiguration(Params.settings);
938}
939
Sam McCall2c30fbc2018-10-18 12:32:04 +0000940void ClangdLSPServer::onReference(const ReferenceParams &Params,
941 Callback<std::vector<Location>> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000942 Server->findReferences(Params.textDocument.uri.file(), Params.position,
Haojian Wuc34f0222019-01-14 18:11:09 +0000943 CCOpts.Limit, std::move(Reply));
Sam McCall1ad142f2018-09-05 11:53:07 +0000944}
945
Jan Korousb4067012018-11-27 16:40:46 +0000946void ClangdLSPServer::onSymbolInfo(const TextDocumentPositionParams &Params,
947 Callback<std::vector<SymbolDetails>> Reply) {
948 Server->symbolInfo(Params.textDocument.uri.file(), Params.position,
949 std::move(Reply));
950}
951
Sam McCalla69698f2019-03-27 17:47:49 +0000952ClangdLSPServer::ClangdLSPServer(
953 class Transport &Transp, const FileSystemProvider &FSProvider,
954 const clangd::CodeCompleteOptions &CCOpts,
955 llvm::Optional<Path> CompileCommandsDir, bool UseDirBasedCDB,
956 llvm::Optional<OffsetEncoding> ForcedOffsetEncoding,
957 const ClangdServer::Options &Opts)
Haojian Wu1ca0c582019-01-22 09:39:05 +0000958 : Transp(Transp), MsgHandler(new MessageHandler(*this)),
959 FSProvider(FSProvider), CCOpts(CCOpts),
Sam McCalld1c9d112018-10-23 14:19:54 +0000960 SupportedSymbolKinds(defaultSymbolKinds()),
Kadir Cetinkaya133d46f2018-09-27 17:13:07 +0000961 SupportedCompletionItemKinds(defaultCompletionItemKinds()),
Sam McCallc55d09a2018-11-02 13:09:36 +0000962 UseDirBasedCDB(UseDirBasedCDB),
Sam McCalla69698f2019-03-27 17:47:49 +0000963 CompileCommandsDir(std::move(CompileCommandsDir)), ClangdServerOpts(Opts),
964 NegotiatedOffsetEncoding(ForcedOffsetEncoding) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000965 // clang-format off
966 MsgHandler->bind("initialize", &ClangdLSPServer::onInitialize);
967 MsgHandler->bind("shutdown", &ClangdLSPServer::onShutdown);
Sam McCall422c8282018-11-26 16:00:11 +0000968 MsgHandler->bind("sync", &ClangdLSPServer::onSync);
Sam McCall2c30fbc2018-10-18 12:32:04 +0000969 MsgHandler->bind("textDocument/rangeFormatting", &ClangdLSPServer::onDocumentRangeFormatting);
970 MsgHandler->bind("textDocument/onTypeFormatting", &ClangdLSPServer::onDocumentOnTypeFormatting);
971 MsgHandler->bind("textDocument/formatting", &ClangdLSPServer::onDocumentFormatting);
972 MsgHandler->bind("textDocument/codeAction", &ClangdLSPServer::onCodeAction);
973 MsgHandler->bind("textDocument/completion", &ClangdLSPServer::onCompletion);
974 MsgHandler->bind("textDocument/signatureHelp", &ClangdLSPServer::onSignatureHelp);
975 MsgHandler->bind("textDocument/definition", &ClangdLSPServer::onGoToDefinition);
Sam McCall866ba2c2019-02-01 11:26:13 +0000976 MsgHandler->bind("textDocument/declaration", &ClangdLSPServer::onGoToDeclaration);
Sam McCall2c30fbc2018-10-18 12:32:04 +0000977 MsgHandler->bind("textDocument/references", &ClangdLSPServer::onReference);
978 MsgHandler->bind("textDocument/switchSourceHeader", &ClangdLSPServer::onSwitchSourceHeader);
979 MsgHandler->bind("textDocument/rename", &ClangdLSPServer::onRename);
980 MsgHandler->bind("textDocument/hover", &ClangdLSPServer::onHover);
981 MsgHandler->bind("textDocument/documentSymbol", &ClangdLSPServer::onDocumentSymbol);
982 MsgHandler->bind("workspace/executeCommand", &ClangdLSPServer::onCommand);
983 MsgHandler->bind("textDocument/documentHighlight", &ClangdLSPServer::onDocumentHighlight);
984 MsgHandler->bind("workspace/symbol", &ClangdLSPServer::onWorkspaceSymbol);
985 MsgHandler->bind("textDocument/didOpen", &ClangdLSPServer::onDocumentDidOpen);
986 MsgHandler->bind("textDocument/didClose", &ClangdLSPServer::onDocumentDidClose);
987 MsgHandler->bind("textDocument/didChange", &ClangdLSPServer::onDocumentDidChange);
988 MsgHandler->bind("workspace/didChangeWatchedFiles", &ClangdLSPServer::onFileEvent);
989 MsgHandler->bind("workspace/didChangeConfiguration", &ClangdLSPServer::onChangeConfiguration);
Jan Korousb4067012018-11-27 16:40:46 +0000990 MsgHandler->bind("textDocument/symbolInfo", &ClangdLSPServer::onSymbolInfo);
Kadir Cetinkaya86658022019-03-19 09:27:04 +0000991 MsgHandler->bind("textDocument/typeHierarchy", &ClangdLSPServer::onTypeHierarchy);
Sam McCall2c30fbc2018-10-18 12:32:04 +0000992 // clang-format on
993}
994
995ClangdLSPServer::~ClangdLSPServer() = default;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000996
Sam McCalldc8f3cf2018-10-17 07:32:05 +0000997bool ClangdLSPServer::run() {
Ilya Biryukovafb55542017-05-16 14:40:30 +0000998 // Run the Language Server loop.
Sam McCalldc8f3cf2018-10-17 07:32:05 +0000999 bool CleanExit = true;
Sam McCall2c30fbc2018-10-18 12:32:04 +00001000 if (auto Err = Transp.loop(*MsgHandler)) {
Sam McCalldc8f3cf2018-10-17 07:32:05 +00001001 elog("Transport error: {0}", std::move(Err));
1002 CleanExit = false;
1003 }
Ilya Biryukovafb55542017-05-16 14:40:30 +00001004
Ilya Biryukov652364b2018-09-26 05:48:29 +00001005 // Destroy ClangdServer to ensure all worker threads finish.
1006 Server.reset();
Sam McCalldc8f3cf2018-10-17 07:32:05 +00001007 return CleanExit && ShutdownRequestReceived;
Ilya Biryukov38d79772017-05-16 09:38:59 +00001008}
1009
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001010std::vector<Fix> ClangdLSPServer::getFixes(llvm::StringRef File,
Ilya Biryukov71028b82018-03-12 15:28:22 +00001011 const clangd::Diagnostic &D) {
Ilya Biryukov38d79772017-05-16 09:38:59 +00001012 std::lock_guard<std::mutex> Lock(FixItsMutex);
1013 auto DiagToFixItsIter = FixItsMap.find(File);
1014 if (DiagToFixItsIter == FixItsMap.end())
1015 return {};
1016
1017 const auto &DiagToFixItsMap = DiagToFixItsIter->second;
1018 auto FixItsIter = DiagToFixItsMap.find(D);
1019 if (FixItsIter == DiagToFixItsMap.end())
1020 return {};
1021
1022 return FixItsIter->second;
1023}
1024
Ilya Biryukovb0826bd2019-01-03 13:37:12 +00001025bool ClangdLSPServer::shouldRunCompletion(
1026 const CompletionParams &Params) const {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001027 llvm::StringRef Trigger = Params.context.triggerCharacter;
Ilya Biryukovb0826bd2019-01-03 13:37:12 +00001028 if (Params.context.triggerKind != CompletionTriggerKind::TriggerCharacter ||
1029 (Trigger != ">" && Trigger != ":"))
1030 return true;
1031
1032 auto Code = DraftMgr.getDraft(Params.textDocument.uri.file());
1033 if (!Code)
1034 return true; // completion code will log the error for untracked doc.
1035
1036 // A completion request is sent when the user types '>' or ':', but we only
1037 // want to trigger on '->' and '::'. We check the preceeding character to make
1038 // sure it matches what we expected.
1039 // Running the lexer here would be more robust (e.g. we can detect comments
1040 // and avoid triggering completion there), but we choose to err on the side
1041 // of simplicity here.
1042 auto Offset = positionToOffset(*Code, Params.position,
1043 /*AllowColumnsBeyondLineLength=*/false);
1044 if (!Offset) {
1045 vlog("could not convert position '{0}' to offset for file '{1}'",
1046 Params.position, Params.textDocument.uri.file());
1047 return true;
1048 }
1049 if (*Offset < 2)
1050 return false;
1051
1052 if (Trigger == ">")
1053 return (*Code)[*Offset - 2] == '-'; // trigger only on '->'.
1054 if (Trigger == ":")
1055 return (*Code)[*Offset - 2] == ':'; // trigger only on '::'.
1056 assert(false && "unhandled trigger character");
1057 return true;
1058}
1059
Sam McCalla7bb0cc2018-03-12 23:22:35 +00001060void ClangdLSPServer::onDiagnosticsReady(PathRef File,
1061 std::vector<Diag> Diagnostics) {
Eric Liu4d814a92018-11-28 10:30:42 +00001062 auto URI = URIForFile::canonicalize(File, /*TUPath=*/File);
Sam McCall16e70702018-10-24 07:59:38 +00001063 std::vector<Diagnostic> LSPDiagnostics;
Ilya Biryukov38d79772017-05-16 09:38:59 +00001064 DiagnosticToReplacementMap LocalFixIts; // Temporary storage
Sam McCalla7bb0cc2018-03-12 23:22:35 +00001065 for (auto &Diag : Diagnostics) {
Sam McCall16e70702018-10-24 07:59:38 +00001066 toLSPDiags(Diag, URI, DiagOpts,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001067 [&](clangd::Diagnostic Diag, llvm::ArrayRef<Fix> Fixes) {
Sam McCall16e70702018-10-24 07:59:38 +00001068 auto &FixItsForDiagnostic = LocalFixIts[Diag];
1069 llvm::copy(Fixes, std::back_inserter(FixItsForDiagnostic));
1070 LSPDiagnostics.push_back(std::move(Diag));
1071 });
Ilya Biryukov38d79772017-05-16 09:38:59 +00001072 }
1073
1074 // Cache FixIts
1075 {
Ilya Biryukov38d79772017-05-16 09:38:59 +00001076 std::lock_guard<std::mutex> Lock(FixItsMutex);
1077 FixItsMap[File] = LocalFixIts;
1078 }
1079
Ilya Biryukov49c10712019-03-25 10:15:11 +00001080 // Send a notification to the LSP client.
1081 publishDiagnostics(URI, std::move(LSPDiagnostics));
Ilya Biryukov38d79772017-05-16 09:38:59 +00001082}
Simon Marchi9569fd52018-03-16 14:30:42 +00001083
Haojian Wub6188492018-12-20 15:39:12 +00001084void ClangdLSPServer::onFileUpdated(PathRef File, const TUStatus &Status) {
1085 if (!SupportFileStatus)
1086 return;
1087 // FIXME: we don't emit "BuildingFile" and `RunningAction`, as these
1088 // two statuses are running faster in practice, which leads the UI constantly
1089 // changing, and doesn't provide much value. We may want to emit status at a
1090 // reasonable time interval (e.g. 0.5s).
1091 if (Status.Action.S == TUAction::BuildingFile ||
1092 Status.Action.S == TUAction::RunningAction)
1093 return;
1094 notify("textDocument/clangd.fileStatus", Status.render(File));
1095}
1096
Simon Marchi9569fd52018-03-16 14:30:42 +00001097void ClangdLSPServer::reparseOpenedFiles() {
1098 for (const Path &FilePath : DraftMgr.getActiveFiles())
Ilya Biryukov652364b2018-09-26 05:48:29 +00001099 Server->addDocument(FilePath, *DraftMgr.getDraft(FilePath),
1100 WantDiagnostics::Auto);
Simon Marchi9569fd52018-03-16 14:30:42 +00001101}
Alex Lorenzf8087862018-08-01 17:39:29 +00001102
Sam McCallc008af62018-10-20 15:30:37 +00001103} // namespace clangd
1104} // namespace clang