blob: 6a4d2f3dbfca2114545502a8b0bd7dce174fbacb [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;
Ilya Biryukov4ef0f822019-06-04 09:36:59 +0000363 SupportsOffsetsInSignatureHelp = Params.capabilities.OffsetsInSignatureHelp;
Sam McCalla69698f2019-03-27 17:47:49 +0000364 llvm::json::Object Result{
Sam McCall0930ab02017-11-07 15:49:35 +0000365 {{"capabilities",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000366 llvm::json::Object{
Simon Marchi98082622018-03-26 14:41:40 +0000367 {"textDocumentSync", (int)TextDocumentSyncKind::Incremental},
Sam McCall0930ab02017-11-07 15:49:35 +0000368 {"documentFormattingProvider", true},
369 {"documentRangeFormattingProvider", true},
370 {"documentOnTypeFormattingProvider",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000371 llvm::json::Object{
Sam McCall0930ab02017-11-07 15:49:35 +0000372 {"firstTriggerCharacter", "}"},
373 {"moreTriggerCharacter", {}},
374 }},
375 {"codeActionProvider", true},
376 {"completionProvider",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000377 llvm::json::Object{
Sam McCall0930ab02017-11-07 15:49:35 +0000378 {"resolveProvider", false},
Ilya Biryukovb0826bd2019-01-03 13:37:12 +0000379 // We do extra checks for '>' and ':' in completion to only
380 // trigger on '->' and '::'.
Sam McCall0930ab02017-11-07 15:49:35 +0000381 {"triggerCharacters", {".", ">", ":"}},
382 }},
383 {"signatureHelpProvider",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000384 llvm::json::Object{
Sam McCall0930ab02017-11-07 15:49:35 +0000385 {"triggerCharacters", {"(", ","}},
386 }},
Sam McCall866ba2c2019-02-01 11:26:13 +0000387 {"declarationProvider", true},
Sam McCall0930ab02017-11-07 15:49:35 +0000388 {"definitionProvider", true},
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000389 {"documentHighlightProvider", true},
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000390 {"hoverProvider", true},
Haojian Wu345099c2017-11-09 11:30:04 +0000391 {"renameProvider", true},
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000392 {"documentSymbolProvider", true},
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000393 {"workspaceSymbolProvider", true},
Sam McCall1ad142f2018-09-05 11:53:07 +0000394 {"referencesProvider", true},
Sam McCall0930ab02017-11-07 15:49:35 +0000395 {"executeCommandProvider",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000396 llvm::json::Object{
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000397 {"commands",
398 {ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND,
399 ExecuteCommandParams::CLANGD_APPLY_TWEAK}},
Sam McCall0930ab02017-11-07 15:49:35 +0000400 }},
Kadir Cetinkaya86658022019-03-19 09:27:04 +0000401 {"typeHierarchyProvider", true},
Sam McCalla69698f2019-03-27 17:47:49 +0000402 }}}};
403 if (NegotiatedOffsetEncoding)
404 Result["offsetEncoding"] = *NegotiatedOffsetEncoding;
405 Reply(std::move(Result));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000406}
407
Sam McCall2c30fbc2018-10-18 12:32:04 +0000408void ClangdLSPServer::onShutdown(const ShutdownParams &Params,
409 Callback<std::nullptr_t> Reply) {
Ilya Biryukov0d9b8a32017-10-25 08:45:41 +0000410 // Do essentially nothing, just say we're ready to exit.
411 ShutdownRequestReceived = true;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000412 Reply(nullptr);
Sam McCall8a5dded2017-10-12 13:29:58 +0000413}
Ilya Biryukovafb55542017-05-16 14:40:30 +0000414
Sam McCall422c8282018-11-26 16:00:11 +0000415// sync is a clangd extension: it blocks until all background work completes.
416// It blocks the calling thread, so no messages are processed until it returns!
417void ClangdLSPServer::onSync(const NoParams &Params,
418 Callback<std::nullptr_t> Reply) {
419 if (Server->blockUntilIdleForTest(/*TimeoutSeconds=*/60))
420 Reply(nullptr);
421 else
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000422 Reply(llvm::createStringError(llvm::inconvertibleErrorCode(),
423 "Not idle after a minute"));
Sam McCall422c8282018-11-26 16:00:11 +0000424}
425
Sam McCall2c30fbc2018-10-18 12:32:04 +0000426void ClangdLSPServer::onDocumentDidOpen(
427 const DidOpenTextDocumentParams &Params) {
Simon Marchi9569fd52018-03-16 14:30:42 +0000428 PathRef File = Params.textDocument.uri.file();
Ilya Biryukovb10ef472018-06-13 09:20:41 +0000429
Sam McCall2c30fbc2018-10-18 12:32:04 +0000430 const std::string &Contents = Params.textDocument.text;
Simon Marchi9569fd52018-03-16 14:30:42 +0000431
Simon Marchi98082622018-03-26 14:41:40 +0000432 DraftMgr.addDraft(File, Contents);
Ilya Biryukov652364b2018-09-26 05:48:29 +0000433 Server->addDocument(File, Contents, WantDiagnostics::Yes);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000434}
435
Sam McCall2c30fbc2018-10-18 12:32:04 +0000436void ClangdLSPServer::onDocumentDidChange(
437 const DidChangeTextDocumentParams &Params) {
Eric Liu51fed182018-02-22 18:40:39 +0000438 auto WantDiags = WantDiagnostics::Auto;
439 if (Params.wantDiagnostics.hasValue())
440 WantDiags = Params.wantDiagnostics.getValue() ? WantDiagnostics::Yes
441 : WantDiagnostics::No;
Simon Marchi9569fd52018-03-16 14:30:42 +0000442
443 PathRef File = Params.textDocument.uri.file();
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000444 llvm::Expected<std::string> Contents =
Simon Marchi98082622018-03-26 14:41:40 +0000445 DraftMgr.updateDraft(File, Params.contentChanges);
446 if (!Contents) {
447 // If this fails, we are most likely going to be not in sync anymore with
448 // the client. It is better to remove the draft and let further operations
449 // fail rather than giving wrong results.
450 DraftMgr.removeDraft(File);
Ilya Biryukov652364b2018-09-26 05:48:29 +0000451 Server->removeDocument(File);
Sam McCallbed58852018-07-11 10:35:11 +0000452 elog("Failed to update {0}: {1}", File, Contents.takeError());
Simon Marchi98082622018-03-26 14:41:40 +0000453 return;
454 }
Simon Marchi9569fd52018-03-16 14:30:42 +0000455
Ilya Biryukov652364b2018-09-26 05:48:29 +0000456 Server->addDocument(File, *Contents, WantDiags);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000457}
458
Sam McCall2c30fbc2018-10-18 12:32:04 +0000459void ClangdLSPServer::onFileEvent(const DidChangeWatchedFilesParams &Params) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000460 Server->onFileEvent(Params);
Marc-Andre Laperlebf114242017-10-02 18:00:37 +0000461}
462
Sam McCall2c30fbc2018-10-18 12:32:04 +0000463void ClangdLSPServer::onCommand(const ExecuteCommandParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000464 Callback<llvm::json::Value> Reply) {
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000465 auto ApplyEdit = [this](WorkspaceEdit WE) {
Eric Liuc5105f92018-02-16 14:15:55 +0000466 ApplyWorkspaceEditParams Edit;
467 Edit.edit = std::move(WE);
Eric Liuc5105f92018-02-16 14:15:55 +0000468 // Ideally, we would wait for the response and if there is no error, we
469 // would reply success/failure to the original RPC.
470 call("workspace/applyEdit", Edit);
471 };
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000472 if (Params.command == ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND &&
473 Params.workspaceEdit) {
474 // The flow for "apply-fix" :
475 // 1. We publish a diagnostic, including fixits
476 // 2. The user clicks on the diagnostic, the editor asks us for code actions
477 // 3. We send code actions, with the fixit embedded as context
478 // 4. The user selects the fixit, the editor asks us to apply it
479 // 5. We unwrap the changes and send them back to the editor
480 // 6. The editor applies the changes (applyEdit), and sends us a reply (but
481 // we ignore it)
482
Sam McCall2c30fbc2018-10-18 12:32:04 +0000483 Reply("Fix applied.");
Eric Liuc5105f92018-02-16 14:15:55 +0000484 ApplyEdit(*Params.workspaceEdit);
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000485 } else if (Params.command == ExecuteCommandParams::CLANGD_APPLY_TWEAK &&
486 Params.tweakArgs) {
487 auto Code = DraftMgr.getDraft(Params.tweakArgs->file.file());
488 if (!Code)
489 return Reply(llvm::createStringError(
490 llvm::inconvertibleErrorCode(),
491 "trying to apply a code action for a non-added file"));
492
493 auto Action = [ApplyEdit](decltype(Reply) Reply, URIForFile File,
494 std::string Code,
495 llvm::Expected<tooling::Replacements> R) {
496 if (!R)
497 return Reply(R.takeError());
498
499 WorkspaceEdit WE;
500 WE.changes.emplace();
501 (*WE.changes)[File.uri()] = replacementsToEdits(Code, *R);
502
503 Reply("Fix applied.");
504 ApplyEdit(std::move(WE));
505 };
506 Server->applyTweak(Params.tweakArgs->file.file(),
507 Params.tweakArgs->selection, Params.tweakArgs->tweakID,
508 Bind(Action, std::move(Reply), Params.tweakArgs->file,
509 std::move(*Code)));
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000510 } else {
511 // We should not get here because ExecuteCommandParams would not have
512 // parsed in the first place and this handler should not be called. But if
513 // more commands are added, this will be here has a safe guard.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000514 Reply(llvm::make_error<LSPError>(
515 llvm::formatv("Unsupported command \"{0}\".", Params.command).str(),
Sam McCall2c30fbc2018-10-18 12:32:04 +0000516 ErrorCode::InvalidParams));
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000517 }
518}
519
Sam McCall2c30fbc2018-10-18 12:32:04 +0000520void ClangdLSPServer::onWorkspaceSymbol(
521 const WorkspaceSymbolParams &Params,
522 Callback<std::vector<SymbolInformation>> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000523 Server->workspaceSymbols(
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000524 Params.query, CCOpts.Limit,
Sam McCall2c30fbc2018-10-18 12:32:04 +0000525 Bind(
526 [this](decltype(Reply) Reply,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000527 llvm::Expected<std::vector<SymbolInformation>> Items) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000528 if (!Items)
529 return Reply(Items.takeError());
530 for (auto &Sym : *Items)
531 Sym.kind = adjustKindToCapability(Sym.kind, SupportedSymbolKinds);
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000532
Sam McCall2c30fbc2018-10-18 12:32:04 +0000533 Reply(std::move(*Items));
534 },
535 std::move(Reply)));
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000536}
537
Sam McCall2c30fbc2018-10-18 12:32:04 +0000538void ClangdLSPServer::onRename(const RenameParams &Params,
539 Callback<WorkspaceEdit> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000540 Path File = Params.textDocument.uri.file();
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000541 llvm::Optional<std::string> Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000542 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000543 return Reply(llvm::make_error<LSPError>(
544 "onRename called for non-added file", ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000545
Ilya Biryukov652364b2018-09-26 05:48:29 +0000546 Server->rename(
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000547 File, Params.position, Params.newName,
Sam McCall2c30fbc2018-10-18 12:32:04 +0000548 Bind(
Ilya Biryukovd9c24dc2019-04-03 07:18:43 +0000549 [File, Code, Params](decltype(Reply) Reply,
550 llvm::Expected<std::vector<TextEdit>> Edits) {
551 if (!Edits)
552 return Reply(Edits.takeError());
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000553
Sam McCall2c30fbc2018-10-18 12:32:04 +0000554 WorkspaceEdit WE;
Ilya Biryukovd9c24dc2019-04-03 07:18:43 +0000555 WE.changes = {{Params.textDocument.uri.uri(), *Edits}};
Sam McCall2c30fbc2018-10-18 12:32:04 +0000556 Reply(WE);
557 },
558 std::move(Reply)));
Haojian Wu345099c2017-11-09 11:30:04 +0000559}
560
Sam McCall2c30fbc2018-10-18 12:32:04 +0000561void ClangdLSPServer::onDocumentDidClose(
562 const DidCloseTextDocumentParams &Params) {
Simon Marchi9569fd52018-03-16 14:30:42 +0000563 PathRef File = Params.textDocument.uri.file();
564 DraftMgr.removeDraft(File);
Ilya Biryukov652364b2018-09-26 05:48:29 +0000565 Server->removeDocument(File);
Ilya Biryukov49c10712019-03-25 10:15:11 +0000566
567 {
568 std::lock_guard<std::mutex> Lock(FixItsMutex);
569 FixItsMap.erase(File);
570 }
571 // clangd will not send updates for this file anymore, so we empty out the
572 // list of diagnostics shown on the client (e.g. in the "Problems" pane of
573 // VSCode). Note that this cannot race with actual diagnostics responses
574 // because removeDocument() guarantees no diagnostic callbacks will be
575 // executed after it returns.
576 publishDiagnostics(URIForFile::canonicalize(File, /*TUPath=*/File), {});
Ilya Biryukovafb55542017-05-16 14:40:30 +0000577}
578
Sam McCall4db732a2017-09-30 10:08:52 +0000579void ClangdLSPServer::onDocumentOnTypeFormatting(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000580 const DocumentOnTypeFormattingParams &Params,
581 Callback<std::vector<TextEdit>> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000582 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000583 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000584 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000585 return Reply(llvm::make_error<LSPError>(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000586 "onDocumentOnTypeFormatting called for non-added file",
587 ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000588
Ilya Biryukov652364b2018-09-26 05:48:29 +0000589 auto ReplacementsOrError = Server->formatOnType(*Code, File, Params.position);
Raoul Wols212bcf82017-12-12 20:25:06 +0000590 if (ReplacementsOrError)
Sam McCall2c30fbc2018-10-18 12:32:04 +0000591 Reply(replacementsToEdits(*Code, ReplacementsOrError.get()));
Raoul Wols212bcf82017-12-12 20:25:06 +0000592 else
Sam McCall2c30fbc2018-10-18 12:32:04 +0000593 Reply(ReplacementsOrError.takeError());
Ilya Biryukovafb55542017-05-16 14:40:30 +0000594}
595
Sam McCall4db732a2017-09-30 10:08:52 +0000596void ClangdLSPServer::onDocumentRangeFormatting(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000597 const DocumentRangeFormattingParams &Params,
598 Callback<std::vector<TextEdit>> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000599 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000600 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000601 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000602 return Reply(llvm::make_error<LSPError>(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000603 "onDocumentRangeFormatting called for non-added file",
604 ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000605
Ilya Biryukov652364b2018-09-26 05:48:29 +0000606 auto ReplacementsOrError = Server->formatRange(*Code, File, Params.range);
Raoul Wols212bcf82017-12-12 20:25:06 +0000607 if (ReplacementsOrError)
Sam McCall2c30fbc2018-10-18 12:32:04 +0000608 Reply(replacementsToEdits(*Code, ReplacementsOrError.get()));
Raoul Wols212bcf82017-12-12 20:25:06 +0000609 else
Sam McCall2c30fbc2018-10-18 12:32:04 +0000610 Reply(ReplacementsOrError.takeError());
Ilya Biryukovafb55542017-05-16 14:40:30 +0000611}
612
Sam McCall2c30fbc2018-10-18 12:32:04 +0000613void ClangdLSPServer::onDocumentFormatting(
614 const DocumentFormattingParams &Params,
615 Callback<std::vector<TextEdit>> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000616 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000617 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000618 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000619 return Reply(llvm::make_error<LSPError>(
620 "onDocumentFormatting called for non-added file",
621 ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000622
Ilya Biryukov652364b2018-09-26 05:48:29 +0000623 auto ReplacementsOrError = Server->formatFile(*Code, File);
Raoul Wols212bcf82017-12-12 20:25:06 +0000624 if (ReplacementsOrError)
Sam McCall2c30fbc2018-10-18 12:32:04 +0000625 Reply(replacementsToEdits(*Code, ReplacementsOrError.get()));
Raoul Wols212bcf82017-12-12 20:25:06 +0000626 else
Sam McCall2c30fbc2018-10-18 12:32:04 +0000627 Reply(ReplacementsOrError.takeError());
Sam McCall4db732a2017-09-30 10:08:52 +0000628}
629
Ilya Biryukov19d75602018-11-23 15:21:19 +0000630/// The functions constructs a flattened view of the DocumentSymbol hierarchy.
631/// Used by the clients that do not support the hierarchical view.
632static std::vector<SymbolInformation>
633flattenSymbolHierarchy(llvm::ArrayRef<DocumentSymbol> Symbols,
634 const URIForFile &FileURI) {
635
636 std::vector<SymbolInformation> Results;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000637 std::function<void(const DocumentSymbol &, llvm::StringRef)> Process =
638 [&](const DocumentSymbol &S, llvm::Optional<llvm::StringRef> ParentName) {
Ilya Biryukov19d75602018-11-23 15:21:19 +0000639 SymbolInformation SI;
640 SI.containerName = ParentName ? "" : *ParentName;
641 SI.name = S.name;
642 SI.kind = S.kind;
643 SI.location.range = S.range;
644 SI.location.uri = FileURI;
645
646 Results.push_back(std::move(SI));
647 std::string FullName =
648 !ParentName ? S.name : (ParentName->str() + "::" + S.name);
649 for (auto &C : S.children)
650 Process(C, /*ParentName=*/FullName);
651 };
652 for (auto &S : Symbols)
653 Process(S, /*ParentName=*/"");
654 return Results;
655}
656
657void ClangdLSPServer::onDocumentSymbol(const DocumentSymbolParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000658 Callback<llvm::json::Value> Reply) {
Ilya Biryukov19d75602018-11-23 15:21:19 +0000659 URIForFile FileURI = Params.textDocument.uri;
Ilya Biryukov652364b2018-09-26 05:48:29 +0000660 Server->documentSymbols(
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000661 Params.textDocument.uri.file(),
Sam McCall2c30fbc2018-10-18 12:32:04 +0000662 Bind(
Ilya Biryukov19d75602018-11-23 15:21:19 +0000663 [this, FileURI](decltype(Reply) Reply,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000664 llvm::Expected<std::vector<DocumentSymbol>> Items) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000665 if (!Items)
666 return Reply(Items.takeError());
Ilya Biryukov19d75602018-11-23 15:21:19 +0000667 adjustSymbolKinds(*Items, SupportedSymbolKinds);
668 if (SupportsHierarchicalDocumentSymbol)
669 return Reply(std::move(*Items));
670 else
671 return Reply(flattenSymbolHierarchy(*Items, FileURI));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000672 },
673 std::move(Reply)));
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000674}
675
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000676static llvm::Optional<Command> asCommand(const CodeAction &Action) {
Sam McCall20841d42018-10-16 16:29:41 +0000677 Command Cmd;
678 if (Action.command && Action.edit)
Sam McCallc008af62018-10-20 15:30:37 +0000679 return None; // Not representable. (We never emit these anyway).
Sam McCall20841d42018-10-16 16:29:41 +0000680 if (Action.command) {
681 Cmd = *Action.command;
682 } else if (Action.edit) {
683 Cmd.command = Command::CLANGD_APPLY_FIX_COMMAND;
684 Cmd.workspaceEdit = *Action.edit;
685 } else {
Sam McCallc008af62018-10-20 15:30:37 +0000686 return None;
Sam McCall20841d42018-10-16 16:29:41 +0000687 }
688 Cmd.title = Action.title;
689 if (Action.kind && *Action.kind == CodeAction::QUICKFIX_KIND)
690 Cmd.title = "Apply fix: " + Cmd.title;
691 return Cmd;
692}
693
Sam McCall2c30fbc2018-10-18 12:32:04 +0000694void ClangdLSPServer::onCodeAction(const CodeActionParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000695 Callback<llvm::json::Value> Reply) {
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000696 URIForFile File = Params.textDocument.uri;
697 auto Code = DraftMgr.getDraft(File.file());
Sam McCall2c30fbc2018-10-18 12:32:04 +0000698 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000699 return Reply(llvm::make_error<LSPError>(
700 "onCodeAction called for non-added file", ErrorCode::InvalidParams));
Sam McCall20841d42018-10-16 16:29:41 +0000701 // We provide a code action for Fixes on the specified diagnostics.
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000702 std::vector<CodeAction> FixIts;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000703 for (const Diagnostic &D : Params.context.diagnostics) {
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000704 for (auto &F : getFixes(File.file(), D)) {
705 FixIts.push_back(toCodeAction(F, Params.textDocument.uri));
706 FixIts.back().diagnostics = {D};
Sam McCalldd0566b2017-11-06 15:40:30 +0000707 }
Ilya Biryukovafb55542017-05-16 14:40:30 +0000708 }
Sam McCall20841d42018-10-16 16:29:41 +0000709
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000710 // Now enumerate the semantic code actions.
711 auto ConsumeActions =
712 [this](decltype(Reply) Reply, URIForFile File, std::string Code,
713 Range Selection, std::vector<CodeAction> FixIts,
714 llvm::Expected<std::vector<ClangdServer::TweakRef>> Tweaks) {
Ilya Biryukovc6ed7782019-01-30 14:24:17 +0000715 if (!Tweaks)
716 return Reply(Tweaks.takeError());
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000717
718 std::vector<CodeAction> Actions = std::move(FixIts);
719 Actions.reserve(Actions.size() + Tweaks->size());
720 for (const auto &T : *Tweaks)
721 Actions.push_back(toCodeAction(T, File, Selection));
722
723 if (SupportsCodeAction)
724 return Reply(llvm::json::Array(Actions));
725 std::vector<Command> Commands;
726 for (const auto &Action : Actions) {
727 if (auto Command = asCommand(Action))
728 Commands.push_back(std::move(*Command));
729 }
730 return Reply(llvm::json::Array(Commands));
731 };
732
733 Server->enumerateTweaks(File.file(), Params.range,
Ilya Biryukovc9409c62019-01-30 09:39:01 +0000734 Bind(ConsumeActions, std::move(Reply), File,
735 std::move(*Code), Params.range,
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000736 std::move(FixIts)));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000737}
738
Ilya Biryukovb0826bd2019-01-03 13:37:12 +0000739void ClangdLSPServer::onCompletion(const CompletionParams &Params,
Sam McCall2c30fbc2018-10-18 12:32:04 +0000740 Callback<CompletionList> Reply) {
Ilya Biryukovb0826bd2019-01-03 13:37:12 +0000741 if (!shouldRunCompletion(Params))
742 return Reply(llvm::make_error<IgnoreCompletionError>());
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000743 Server->codeComplete(Params.textDocument.uri.file(), Params.position, CCOpts,
744 Bind(
745 [this](decltype(Reply) Reply,
746 llvm::Expected<CodeCompleteResult> List) {
747 if (!List)
748 return Reply(List.takeError());
749 CompletionList LSPList;
750 LSPList.isIncomplete = List->HasMore;
751 for (const auto &R : List->Completions) {
752 CompletionItem C = R.render(CCOpts);
753 C.kind = adjustKindToCapability(
754 C.kind, SupportedCompletionItemKinds);
755 LSPList.items.push_back(std::move(C));
756 }
757 return Reply(std::move(LSPList));
758 },
759 std::move(Reply)));
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000760}
761
Sam McCall2c30fbc2018-10-18 12:32:04 +0000762void ClangdLSPServer::onSignatureHelp(const TextDocumentPositionParams &Params,
763 Callback<SignatureHelp> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000764 Server->signatureHelp(Params.textDocument.uri.file(), Params.position,
Ilya Biryukov4ef0f822019-06-04 09:36:59 +0000765 Bind(
766 [this](decltype(Reply) Reply,
767 llvm::Expected<SignatureHelp> Signature) {
768 if (!Signature)
769 return Reply(Signature.takeError());
770 if (SupportsOffsetsInSignatureHelp)
771 return Reply(std::move(*Signature));
772 // Strip out the offsets from signature help for
773 // clients that only support string labels.
774 for (auto &Signature : Signature->signatures) {
775 for (auto &Param : Signature.parameters)
776 Param.labelOffsets.reset();
777 }
778 return Reply(std::move(*Signature));
779 },
780 std::move(Reply)));
Ilya Biryukov652364b2018-09-26 05:48:29 +0000781}
782
Sam McCall0dbab7f2019-02-02 05:56:00 +0000783// Go to definition has a toggle function: if def and decl are distinct, then
784// the first press gives you the def, the second gives you the matching def.
785// getToggle() returns the counterpart location that under the cursor.
786//
787// We return the toggled location alone (ignoring other symbols) to encourage
788// editors to "bounce" quickly between locations, without showing a menu.
789static Location *getToggle(const TextDocumentPositionParams &Point,
790 LocatedSymbol &Sym) {
791 // Toggle only makes sense with two distinct locations.
792 if (!Sym.Definition || *Sym.Definition == Sym.PreferredDeclaration)
793 return nullptr;
794 if (Sym.Definition->uri.file() == Point.textDocument.uri.file() &&
795 Sym.Definition->range.contains(Point.position))
796 return &Sym.PreferredDeclaration;
797 if (Sym.PreferredDeclaration.uri.file() == Point.textDocument.uri.file() &&
798 Sym.PreferredDeclaration.range.contains(Point.position))
799 return &*Sym.Definition;
800 return nullptr;
801}
802
Sam McCall2c30fbc2018-10-18 12:32:04 +0000803void ClangdLSPServer::onGoToDefinition(const TextDocumentPositionParams &Params,
804 Callback<std::vector<Location>> Reply) {
Sam McCall866ba2c2019-02-01 11:26:13 +0000805 Server->locateSymbolAt(
806 Params.textDocument.uri.file(), Params.position,
807 Bind(
Sam McCall0dbab7f2019-02-02 05:56:00 +0000808 [&, Params](decltype(Reply) Reply,
809 llvm::Expected<std::vector<LocatedSymbol>> Symbols) {
Sam McCall866ba2c2019-02-01 11:26:13 +0000810 if (!Symbols)
811 return Reply(Symbols.takeError());
812 std::vector<Location> Defs;
Sam McCall0dbab7f2019-02-02 05:56:00 +0000813 for (auto &S : *Symbols) {
814 if (Location *Toggle = getToggle(Params, S))
815 return Reply(std::vector<Location>{std::move(*Toggle)});
Sam McCall866ba2c2019-02-01 11:26:13 +0000816 Defs.push_back(S.Definition.getValueOr(S.PreferredDeclaration));
Sam McCall0dbab7f2019-02-02 05:56:00 +0000817 }
Sam McCall866ba2c2019-02-01 11:26:13 +0000818 Reply(std::move(Defs));
819 },
820 std::move(Reply)));
821}
822
823void ClangdLSPServer::onGoToDeclaration(
824 const TextDocumentPositionParams &Params,
825 Callback<std::vector<Location>> Reply) {
826 Server->locateSymbolAt(
827 Params.textDocument.uri.file(), Params.position,
828 Bind(
Sam McCall0dbab7f2019-02-02 05:56:00 +0000829 [&, Params](decltype(Reply) Reply,
830 llvm::Expected<std::vector<LocatedSymbol>> Symbols) {
Sam McCall866ba2c2019-02-01 11:26:13 +0000831 if (!Symbols)
832 return Reply(Symbols.takeError());
833 std::vector<Location> Decls;
Sam McCall0dbab7f2019-02-02 05:56:00 +0000834 for (auto &S : *Symbols) {
835 if (Location *Toggle = getToggle(Params, S))
836 return Reply(std::vector<Location>{std::move(*Toggle)});
837 Decls.push_back(std::move(S.PreferredDeclaration));
838 }
Sam McCall866ba2c2019-02-01 11:26:13 +0000839 Reply(std::move(Decls));
840 },
841 std::move(Reply)));
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000842}
843
Sam McCall111fe842019-05-07 07:55:35 +0000844void ClangdLSPServer::onSwitchSourceHeader(
845 const TextDocumentIdentifier &Params,
Sam McCallb9ec3e92019-05-07 08:30:32 +0000846 Callback<llvm::Optional<URIForFile>> Reply) {
Sam McCall111fe842019-05-07 07:55:35 +0000847 if (auto Result = Server->switchSourceHeader(Params.uri.file()))
Sam McCallb9ec3e92019-05-07 08:30:32 +0000848 Reply(URIForFile::canonicalize(*Result, Params.uri.file()));
Sam McCall111fe842019-05-07 07:55:35 +0000849 else
850 Reply(llvm::None);
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000851}
852
Sam McCall2c30fbc2018-10-18 12:32:04 +0000853void ClangdLSPServer::onDocumentHighlight(
854 const TextDocumentPositionParams &Params,
855 Callback<std::vector<DocumentHighlight>> Reply) {
856 Server->findDocumentHighlights(Params.textDocument.uri.file(),
857 Params.position, std::move(Reply));
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000858}
859
Sam McCall2c30fbc2018-10-18 12:32:04 +0000860void ClangdLSPServer::onHover(const TextDocumentPositionParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000861 Callback<llvm::Optional<Hover>> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000862 Server->findHover(Params.textDocument.uri.file(), Params.position,
Kadir Cetinkayac6578ee2019-05-28 10:29:58 +0000863 Bind(
Ilya Biryukovf9169d02019-05-29 10:01:00 +0000864 [this](decltype(Reply) Reply,
865 llvm::Expected<llvm::Optional<HoverInfo>> H) {
866 if (!H)
867 return Reply(H.takeError());
868 if (!*H)
Kadir Cetinkayac6578ee2019-05-28 10:29:58 +0000869 return Reply(llvm::None);
Ilya Biryukovf9169d02019-05-29 10:01:00 +0000870
871 Hover R;
872 R.contents.kind = HoverContentFormat;
873 R.range = (*H)->SymRange;
874 switch (HoverContentFormat) {
875 case MarkupKind::PlainText:
876 R.contents.value =
877 (*H)->present().renderAsPlainText();
878 return Reply(std::move(R));
879 case MarkupKind::Markdown:
880 R.contents.value =
881 (*H)->present().renderAsMarkdown();
882 return Reply(std::move(R));
883 };
884 llvm_unreachable("unhandled MarkupKind");
Kadir Cetinkayac6578ee2019-05-28 10:29:58 +0000885 },
886 std::move(Reply)));
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000887}
888
Kadir Cetinkaya86658022019-03-19 09:27:04 +0000889void ClangdLSPServer::onTypeHierarchy(
890 const TypeHierarchyParams &Params,
891 Callback<Optional<TypeHierarchyItem>> Reply) {
892 Server->typeHierarchy(Params.textDocument.uri.file(), Params.position,
893 Params.resolve, Params.direction, std::move(Reply));
894}
895
Simon Marchi88016782018-08-01 11:28:49 +0000896void ClangdLSPServer::applyConfiguration(
Sam McCallbc904612018-10-25 04:22:52 +0000897 const ConfigurationSettings &Settings) {
Simon Marchiabeed662018-10-16 15:55:03 +0000898 // Per-file update to the compilation database.
Sam McCallbc904612018-10-25 04:22:52 +0000899 bool ShouldReparseOpenFiles = false;
900 for (auto &Entry : Settings.compilationDatabaseChanges) {
901 /// The opened files need to be reparsed only when some existing
902 /// entries are changed.
903 PathRef File = Entry.first;
Sam McCallc55d09a2018-11-02 13:09:36 +0000904 auto Old = CDB->getCompileCommand(File);
905 auto New =
906 tooling::CompileCommand(std::move(Entry.second.workingDirectory), File,
907 std::move(Entry.second.compilationCommand),
908 /*Output=*/"");
Sam McCall6980edb2018-11-02 14:07:51 +0000909 if (Old != New) {
Sam McCallc55d09a2018-11-02 13:09:36 +0000910 CDB->setCompileCommand(File, std::move(New));
Sam McCall6980edb2018-11-02 14:07:51 +0000911 ShouldReparseOpenFiles = true;
912 }
Alex Lorenzf8087862018-08-01 17:39:29 +0000913 }
Sam McCallbc904612018-10-25 04:22:52 +0000914 if (ShouldReparseOpenFiles)
915 reparseOpenedFiles();
Simon Marchi5178f922018-02-22 14:00:39 +0000916}
917
Ilya Biryukov49c10712019-03-25 10:15:11 +0000918void ClangdLSPServer::publishDiagnostics(
919 const URIForFile &File, std::vector<clangd::Diagnostic> Diagnostics) {
920 // Publish diagnostics.
921 notify("textDocument/publishDiagnostics",
922 llvm::json::Object{
923 {"uri", File},
924 {"diagnostics", std::move(Diagnostics)},
925 });
926}
927
Simon Marchi88016782018-08-01 11:28:49 +0000928// FIXME: This function needs to be properly tested.
929void ClangdLSPServer::onChangeConfiguration(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000930 const DidChangeConfigurationParams &Params) {
Simon Marchi88016782018-08-01 11:28:49 +0000931 applyConfiguration(Params.settings);
932}
933
Sam McCall2c30fbc2018-10-18 12:32:04 +0000934void ClangdLSPServer::onReference(const ReferenceParams &Params,
935 Callback<std::vector<Location>> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000936 Server->findReferences(Params.textDocument.uri.file(), Params.position,
Haojian Wuc34f0222019-01-14 18:11:09 +0000937 CCOpts.Limit, std::move(Reply));
Sam McCall1ad142f2018-09-05 11:53:07 +0000938}
939
Jan Korousb4067012018-11-27 16:40:46 +0000940void ClangdLSPServer::onSymbolInfo(const TextDocumentPositionParams &Params,
941 Callback<std::vector<SymbolDetails>> Reply) {
942 Server->symbolInfo(Params.textDocument.uri.file(), Params.position,
943 std::move(Reply));
944}
945
Sam McCalla69698f2019-03-27 17:47:49 +0000946ClangdLSPServer::ClangdLSPServer(
947 class Transport &Transp, const FileSystemProvider &FSProvider,
948 const clangd::CodeCompleteOptions &CCOpts,
949 llvm::Optional<Path> CompileCommandsDir, bool UseDirBasedCDB,
950 llvm::Optional<OffsetEncoding> ForcedOffsetEncoding,
951 const ClangdServer::Options &Opts)
Haojian Wu1ca0c582019-01-22 09:39:05 +0000952 : Transp(Transp), MsgHandler(new MessageHandler(*this)),
953 FSProvider(FSProvider), CCOpts(CCOpts),
Sam McCalld1c9d112018-10-23 14:19:54 +0000954 SupportedSymbolKinds(defaultSymbolKinds()),
Kadir Cetinkaya133d46f2018-09-27 17:13:07 +0000955 SupportedCompletionItemKinds(defaultCompletionItemKinds()),
Sam McCallc55d09a2018-11-02 13:09:36 +0000956 UseDirBasedCDB(UseDirBasedCDB),
Sam McCalla69698f2019-03-27 17:47:49 +0000957 CompileCommandsDir(std::move(CompileCommandsDir)), ClangdServerOpts(Opts),
958 NegotiatedOffsetEncoding(ForcedOffsetEncoding) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000959 // clang-format off
960 MsgHandler->bind("initialize", &ClangdLSPServer::onInitialize);
961 MsgHandler->bind("shutdown", &ClangdLSPServer::onShutdown);
Sam McCall422c8282018-11-26 16:00:11 +0000962 MsgHandler->bind("sync", &ClangdLSPServer::onSync);
Sam McCall2c30fbc2018-10-18 12:32:04 +0000963 MsgHandler->bind("textDocument/rangeFormatting", &ClangdLSPServer::onDocumentRangeFormatting);
964 MsgHandler->bind("textDocument/onTypeFormatting", &ClangdLSPServer::onDocumentOnTypeFormatting);
965 MsgHandler->bind("textDocument/formatting", &ClangdLSPServer::onDocumentFormatting);
966 MsgHandler->bind("textDocument/codeAction", &ClangdLSPServer::onCodeAction);
967 MsgHandler->bind("textDocument/completion", &ClangdLSPServer::onCompletion);
968 MsgHandler->bind("textDocument/signatureHelp", &ClangdLSPServer::onSignatureHelp);
969 MsgHandler->bind("textDocument/definition", &ClangdLSPServer::onGoToDefinition);
Sam McCall866ba2c2019-02-01 11:26:13 +0000970 MsgHandler->bind("textDocument/declaration", &ClangdLSPServer::onGoToDeclaration);
Sam McCall2c30fbc2018-10-18 12:32:04 +0000971 MsgHandler->bind("textDocument/references", &ClangdLSPServer::onReference);
972 MsgHandler->bind("textDocument/switchSourceHeader", &ClangdLSPServer::onSwitchSourceHeader);
973 MsgHandler->bind("textDocument/rename", &ClangdLSPServer::onRename);
974 MsgHandler->bind("textDocument/hover", &ClangdLSPServer::onHover);
975 MsgHandler->bind("textDocument/documentSymbol", &ClangdLSPServer::onDocumentSymbol);
976 MsgHandler->bind("workspace/executeCommand", &ClangdLSPServer::onCommand);
977 MsgHandler->bind("textDocument/documentHighlight", &ClangdLSPServer::onDocumentHighlight);
978 MsgHandler->bind("workspace/symbol", &ClangdLSPServer::onWorkspaceSymbol);
979 MsgHandler->bind("textDocument/didOpen", &ClangdLSPServer::onDocumentDidOpen);
980 MsgHandler->bind("textDocument/didClose", &ClangdLSPServer::onDocumentDidClose);
981 MsgHandler->bind("textDocument/didChange", &ClangdLSPServer::onDocumentDidChange);
982 MsgHandler->bind("workspace/didChangeWatchedFiles", &ClangdLSPServer::onFileEvent);
983 MsgHandler->bind("workspace/didChangeConfiguration", &ClangdLSPServer::onChangeConfiguration);
Jan Korousb4067012018-11-27 16:40:46 +0000984 MsgHandler->bind("textDocument/symbolInfo", &ClangdLSPServer::onSymbolInfo);
Kadir Cetinkaya86658022019-03-19 09:27:04 +0000985 MsgHandler->bind("textDocument/typeHierarchy", &ClangdLSPServer::onTypeHierarchy);
Sam McCall2c30fbc2018-10-18 12:32:04 +0000986 // clang-format on
987}
988
989ClangdLSPServer::~ClangdLSPServer() = default;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000990
Sam McCalldc8f3cf2018-10-17 07:32:05 +0000991bool ClangdLSPServer::run() {
Ilya Biryukovafb55542017-05-16 14:40:30 +0000992 // Run the Language Server loop.
Sam McCalldc8f3cf2018-10-17 07:32:05 +0000993 bool CleanExit = true;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000994 if (auto Err = Transp.loop(*MsgHandler)) {
Sam McCalldc8f3cf2018-10-17 07:32:05 +0000995 elog("Transport error: {0}", std::move(Err));
996 CleanExit = false;
997 }
Ilya Biryukovafb55542017-05-16 14:40:30 +0000998
Ilya Biryukov652364b2018-09-26 05:48:29 +0000999 // Destroy ClangdServer to ensure all worker threads finish.
1000 Server.reset();
Sam McCalldc8f3cf2018-10-17 07:32:05 +00001001 return CleanExit && ShutdownRequestReceived;
Ilya Biryukov38d79772017-05-16 09:38:59 +00001002}
1003
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001004std::vector<Fix> ClangdLSPServer::getFixes(llvm::StringRef File,
Ilya Biryukov71028b82018-03-12 15:28:22 +00001005 const clangd::Diagnostic &D) {
Ilya Biryukov38d79772017-05-16 09:38:59 +00001006 std::lock_guard<std::mutex> Lock(FixItsMutex);
1007 auto DiagToFixItsIter = FixItsMap.find(File);
1008 if (DiagToFixItsIter == FixItsMap.end())
1009 return {};
1010
1011 const auto &DiagToFixItsMap = DiagToFixItsIter->second;
1012 auto FixItsIter = DiagToFixItsMap.find(D);
1013 if (FixItsIter == DiagToFixItsMap.end())
1014 return {};
1015
1016 return FixItsIter->second;
1017}
1018
Ilya Biryukovb0826bd2019-01-03 13:37:12 +00001019bool ClangdLSPServer::shouldRunCompletion(
1020 const CompletionParams &Params) const {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001021 llvm::StringRef Trigger = Params.context.triggerCharacter;
Ilya Biryukovb0826bd2019-01-03 13:37:12 +00001022 if (Params.context.triggerKind != CompletionTriggerKind::TriggerCharacter ||
1023 (Trigger != ">" && Trigger != ":"))
1024 return true;
1025
1026 auto Code = DraftMgr.getDraft(Params.textDocument.uri.file());
1027 if (!Code)
1028 return true; // completion code will log the error for untracked doc.
1029
1030 // A completion request is sent when the user types '>' or ':', but we only
1031 // want to trigger on '->' and '::'. We check the preceeding character to make
1032 // sure it matches what we expected.
1033 // Running the lexer here would be more robust (e.g. we can detect comments
1034 // and avoid triggering completion there), but we choose to err on the side
1035 // of simplicity here.
1036 auto Offset = positionToOffset(*Code, Params.position,
1037 /*AllowColumnsBeyondLineLength=*/false);
1038 if (!Offset) {
1039 vlog("could not convert position '{0}' to offset for file '{1}'",
1040 Params.position, Params.textDocument.uri.file());
1041 return true;
1042 }
1043 if (*Offset < 2)
1044 return false;
1045
1046 if (Trigger == ">")
1047 return (*Code)[*Offset - 2] == '-'; // trigger only on '->'.
1048 if (Trigger == ":")
1049 return (*Code)[*Offset - 2] == ':'; // trigger only on '::'.
1050 assert(false && "unhandled trigger character");
1051 return true;
1052}
1053
Sam McCalla7bb0cc2018-03-12 23:22:35 +00001054void ClangdLSPServer::onDiagnosticsReady(PathRef File,
1055 std::vector<Diag> Diagnostics) {
Eric Liu4d814a92018-11-28 10:30:42 +00001056 auto URI = URIForFile::canonicalize(File, /*TUPath=*/File);
Sam McCall16e70702018-10-24 07:59:38 +00001057 std::vector<Diagnostic> LSPDiagnostics;
Ilya Biryukov38d79772017-05-16 09:38:59 +00001058 DiagnosticToReplacementMap LocalFixIts; // Temporary storage
Sam McCalla7bb0cc2018-03-12 23:22:35 +00001059 for (auto &Diag : Diagnostics) {
Sam McCall16e70702018-10-24 07:59:38 +00001060 toLSPDiags(Diag, URI, DiagOpts,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001061 [&](clangd::Diagnostic Diag, llvm::ArrayRef<Fix> Fixes) {
Sam McCall16e70702018-10-24 07:59:38 +00001062 auto &FixItsForDiagnostic = LocalFixIts[Diag];
1063 llvm::copy(Fixes, std::back_inserter(FixItsForDiagnostic));
1064 LSPDiagnostics.push_back(std::move(Diag));
1065 });
Ilya Biryukov38d79772017-05-16 09:38:59 +00001066 }
1067
1068 // Cache FixIts
1069 {
Ilya Biryukov38d79772017-05-16 09:38:59 +00001070 std::lock_guard<std::mutex> Lock(FixItsMutex);
1071 FixItsMap[File] = LocalFixIts;
1072 }
1073
Ilya Biryukov49c10712019-03-25 10:15:11 +00001074 // Send a notification to the LSP client.
1075 publishDiagnostics(URI, std::move(LSPDiagnostics));
Ilya Biryukov38d79772017-05-16 09:38:59 +00001076}
Simon Marchi9569fd52018-03-16 14:30:42 +00001077
Haojian Wub6188492018-12-20 15:39:12 +00001078void ClangdLSPServer::onFileUpdated(PathRef File, const TUStatus &Status) {
1079 if (!SupportFileStatus)
1080 return;
1081 // FIXME: we don't emit "BuildingFile" and `RunningAction`, as these
1082 // two statuses are running faster in practice, which leads the UI constantly
1083 // changing, and doesn't provide much value. We may want to emit status at a
1084 // reasonable time interval (e.g. 0.5s).
1085 if (Status.Action.S == TUAction::BuildingFile ||
1086 Status.Action.S == TUAction::RunningAction)
1087 return;
1088 notify("textDocument/clangd.fileStatus", Status.render(File));
1089}
1090
Simon Marchi9569fd52018-03-16 14:30:42 +00001091void ClangdLSPServer::reparseOpenedFiles() {
1092 for (const Path &FilePath : DraftMgr.getActiveFiles())
Ilya Biryukov652364b2018-09-26 05:48:29 +00001093 Server->addDocument(FilePath, *DraftMgr.getDraft(FilePath),
1094 WantDiagnostics::Auto);
Simon Marchi9569fd52018-03-16 14:30:42 +00001095}
Alex Lorenzf8087862018-08-01 17:39:29 +00001096
Sam McCallc008af62018-10-20 15:30:37 +00001097} // namespace clangd
1098} // namespace clang