blob: f6796e1e792f4949b3a6f6f18d6704cc989c8670 [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 Biryukovcce67a32019-01-29 14:17:36 +000028/// Transforms a tweak into a code action that would apply it if executed.
29/// EXPECTS: T.prepare() was called and returned true.
30CodeAction toCodeAction(const ClangdServer::TweakRef &T, const URIForFile &File,
31 Range Selection) {
32 CodeAction CA;
33 CA.title = T.Title;
34 CA.kind = CodeAction::REFACTOR_KIND;
35 // This tweak may have an expensive second stage, we only run it if the user
36 // actually chooses it in the UI. We reply with a command that would run the
37 // corresponding tweak.
38 // FIXME: for some tweaks, computing the edits is cheap and we could send them
39 // directly.
40 CA.command.emplace();
41 CA.command->title = T.Title;
42 CA.command->command = Command::CLANGD_APPLY_TWEAK;
43 CA.command->tweakArgs.emplace();
44 CA.command->tweakArgs->file = File;
45 CA.command->tweakArgs->tweakID = T.ID;
46 CA.command->tweakArgs->selection = Selection;
47 return CA;
Simon Pilgrime9a136b2019-02-03 14:08:30 +000048}
Ilya Biryukovcce67a32019-01-29 14:17:36 +000049
Ilya Biryukov19d75602018-11-23 15:21:19 +000050void adjustSymbolKinds(llvm::MutableArrayRef<DocumentSymbol> Syms,
51 SymbolKindBitset Kinds) {
52 for (auto &S : Syms) {
53 S.kind = adjustKindToCapability(S.kind, Kinds);
54 adjustSymbolKinds(S.children, Kinds);
55 }
56}
57
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +000058SymbolKindBitset defaultSymbolKinds() {
59 SymbolKindBitset Defaults;
60 for (size_t I = SymbolKindMin; I <= static_cast<size_t>(SymbolKind::Array);
61 ++I)
62 Defaults.set(I);
63 return Defaults;
64}
65
Kadir Cetinkaya133d46f2018-09-27 17:13:07 +000066CompletionItemKindBitset defaultCompletionItemKinds() {
67 CompletionItemKindBitset Defaults;
68 for (size_t I = CompletionItemKindMin;
69 I <= static_cast<size_t>(CompletionItemKind::Reference); ++I)
70 Defaults.set(I);
71 return Defaults;
72}
73
Ilya Biryukovafb55542017-05-16 14:40:30 +000074} // namespace
75
Sam McCall2c30fbc2018-10-18 12:32:04 +000076// MessageHandler dispatches incoming LSP messages.
77// It handles cross-cutting concerns:
78// - serializes/deserializes protocol objects to JSON
79// - logging of inbound messages
80// - cancellation handling
81// - basic call tracing
Sam McCall3d0adbe2018-10-18 14:41:50 +000082// MessageHandler ensures that initialize() is called before any other handler.
Sam McCall2c30fbc2018-10-18 12:32:04 +000083class ClangdLSPServer::MessageHandler : public Transport::MessageHandler {
84public:
85 MessageHandler(ClangdLSPServer &Server) : Server(Server) {}
86
Ilya Biryukovf2001aa2019-01-07 15:45:19 +000087 bool onNotify(llvm::StringRef Method, llvm::json::Value Params) override {
Sam McCalla69698f2019-03-27 17:47:49 +000088 WithContext HandlerContext(handlerContext());
Sam McCall2c30fbc2018-10-18 12:32:04 +000089 log("<-- {0}", Method);
90 if (Method == "exit")
91 return false;
Sam McCall3d0adbe2018-10-18 14:41:50 +000092 if (!Server.Server)
93 elog("Notification {0} before initialization", Method);
94 else if (Method == "$/cancelRequest")
Sam McCall2c30fbc2018-10-18 12:32:04 +000095 onCancel(std::move(Params));
96 else if (auto Handler = Notifications.lookup(Method))
97 Handler(std::move(Params));
98 else
99 log("unhandled notification {0}", Method);
100 return true;
101 }
102
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000103 bool onCall(llvm::StringRef Method, llvm::json::Value Params,
104 llvm::json::Value ID) override {
Sam McCalla69698f2019-03-27 17:47:49 +0000105 WithContext HandlerContext(handlerContext());
Sam McCalle2f3a732018-10-24 14:26:26 +0000106 // Calls can be canceled by the client. Add cancellation context.
107 WithContext WithCancel(cancelableRequestContext(ID));
108 trace::Span Tracer(Method);
109 SPAN_ATTACH(Tracer, "Params", Params);
110 ReplyOnce Reply(ID, Method, &Server, Tracer.Args);
Sam McCall2c30fbc2018-10-18 12:32:04 +0000111 log("<-- {0}({1})", Method, ID);
Sam McCall3d0adbe2018-10-18 14:41:50 +0000112 if (!Server.Server && Method != "initialize") {
113 elog("Call {0} before initialization.", Method);
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000114 Reply(llvm::make_error<LSPError>("server not initialized",
115 ErrorCode::ServerNotInitialized));
Sam McCall3d0adbe2018-10-18 14:41:50 +0000116 } else if (auto Handler = Calls.lookup(Method))
Sam McCalle2f3a732018-10-24 14:26:26 +0000117 Handler(std::move(Params), std::move(Reply));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000118 else
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000119 Reply(llvm::make_error<LSPError>("method not found",
120 ErrorCode::MethodNotFound));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000121 return true;
122 }
123
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000124 bool onReply(llvm::json::Value ID,
125 llvm::Expected<llvm::json::Value> Result) override {
Sam McCalla69698f2019-03-27 17:47:49 +0000126 WithContext HandlerContext(handlerContext());
Sam McCall2c30fbc2018-10-18 12:32:04 +0000127 // We ignore replies, just log them.
128 if (Result)
129 log("<-- reply({0})", ID);
130 else
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000131 log("<-- reply({0}) error: {1}", ID, llvm::toString(Result.takeError()));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000132 return true;
133 }
134
135 // Bind an LSP method name to a call.
Sam McCalle2f3a732018-10-24 14:26:26 +0000136 template <typename Param, typename Result>
Sam McCall2c30fbc2018-10-18 12:32:04 +0000137 void bind(const char *Method,
Sam McCalle2f3a732018-10-24 14:26:26 +0000138 void (ClangdLSPServer::*Handler)(const Param &, Callback<Result>)) {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000139 Calls[Method] = [Method, Handler, this](llvm::json::Value RawParams,
Sam McCalle2f3a732018-10-24 14:26:26 +0000140 ReplyOnce Reply) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000141 Param P;
Sam McCalle2f3a732018-10-24 14:26:26 +0000142 if (fromJSON(RawParams, P)) {
143 (Server.*Handler)(P, std::move(Reply));
144 } else {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000145 elog("Failed to decode {0} request.", Method);
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000146 Reply(llvm::make_error<LSPError>("failed to decode request",
147 ErrorCode::InvalidRequest));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000148 }
Sam McCall2c30fbc2018-10-18 12:32:04 +0000149 };
150 }
151
152 // Bind an LSP method name to a notification.
153 template <typename Param>
154 void bind(const char *Method,
155 void (ClangdLSPServer::*Handler)(const Param &)) {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000156 Notifications[Method] = [Method, Handler,
157 this](llvm::json::Value RawParams) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000158 Param P;
159 if (!fromJSON(RawParams, P)) {
160 elog("Failed to decode {0} request.", Method);
161 return;
162 }
163 trace::Span Tracer(Method);
164 SPAN_ATTACH(Tracer, "Params", RawParams);
165 (Server.*Handler)(P);
166 };
167 }
168
169private:
Sam McCalle2f3a732018-10-24 14:26:26 +0000170 // Function object to reply to an LSP call.
171 // Each instance must be called exactly once, otherwise:
172 // - the bug is logged, and (in debug mode) an assert will fire
173 // - if there was no reply, an error reply is sent
174 // - if there were multiple replies, only the first is sent
175 class ReplyOnce {
176 std::atomic<bool> Replied = {false};
Sam McCalld7babe42018-10-24 15:18:40 +0000177 std::chrono::steady_clock::time_point Start;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000178 llvm::json::Value ID;
Sam McCalle2f3a732018-10-24 14:26:26 +0000179 std::string Method;
180 ClangdLSPServer *Server; // Null when moved-from.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000181 llvm::json::Object *TraceArgs;
Sam McCalle2f3a732018-10-24 14:26:26 +0000182
183 public:
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000184 ReplyOnce(const llvm::json::Value &ID, llvm::StringRef Method,
185 ClangdLSPServer *Server, llvm::json::Object *TraceArgs)
Sam McCalld7babe42018-10-24 15:18:40 +0000186 : Start(std::chrono::steady_clock::now()), ID(ID), Method(Method),
187 Server(Server), TraceArgs(TraceArgs) {
Sam McCalle2f3a732018-10-24 14:26:26 +0000188 assert(Server);
189 }
190 ReplyOnce(ReplyOnce &&Other)
Sam McCalld7babe42018-10-24 15:18:40 +0000191 : Replied(Other.Replied.load()), Start(Other.Start),
192 ID(std::move(Other.ID)), Method(std::move(Other.Method)),
193 Server(Other.Server), TraceArgs(Other.TraceArgs) {
Sam McCalle2f3a732018-10-24 14:26:26 +0000194 Other.Server = nullptr;
195 }
Ilya Biryukov22fa4652019-01-03 13:28:05 +0000196 ReplyOnce &operator=(ReplyOnce &&) = delete;
Sam McCalle2f3a732018-10-24 14:26:26 +0000197 ReplyOnce(const ReplyOnce &) = delete;
Ilya Biryukov22fa4652019-01-03 13:28:05 +0000198 ReplyOnce &operator=(const ReplyOnce &) = delete;
Sam McCalle2f3a732018-10-24 14:26:26 +0000199
200 ~ReplyOnce() {
201 if (Server && !Replied) {
202 elog("No reply to message {0}({1})", Method, ID);
203 assert(false && "must reply to all calls!");
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000204 (*this)(llvm::make_error<LSPError>("server failed to reply",
205 ErrorCode::InternalError));
Sam McCalle2f3a732018-10-24 14:26:26 +0000206 }
207 }
208
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000209 void operator()(llvm::Expected<llvm::json::Value> Reply) {
Sam McCalle2f3a732018-10-24 14:26:26 +0000210 assert(Server && "moved-from!");
211 if (Replied.exchange(true)) {
212 elog("Replied twice to message {0}({1})", Method, ID);
213 assert(false && "must reply to each call only once!");
214 return;
215 }
Sam McCalld7babe42018-10-24 15:18:40 +0000216 auto Duration = std::chrono::steady_clock::now() - Start;
217 if (Reply) {
218 log("--> reply:{0}({1}) {2:ms}", Method, ID, Duration);
219 if (TraceArgs)
Sam McCalle2f3a732018-10-24 14:26:26 +0000220 (*TraceArgs)["Reply"] = *Reply;
Sam McCalld7babe42018-10-24 15:18:40 +0000221 std::lock_guard<std::mutex> Lock(Server->TranspWriter);
222 Server->Transp.reply(std::move(ID), std::move(Reply));
223 } else {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000224 llvm::Error Err = Reply.takeError();
Sam McCalld7babe42018-10-24 15:18:40 +0000225 log("--> reply:{0}({1}) {2:ms}, error: {3}", Method, ID, Duration, Err);
226 if (TraceArgs)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000227 (*TraceArgs)["Error"] = llvm::to_string(Err);
Sam McCalld7babe42018-10-24 15:18:40 +0000228 std::lock_guard<std::mutex> Lock(Server->TranspWriter);
229 Server->Transp.reply(std::move(ID), std::move(Err));
Sam McCalle2f3a732018-10-24 14:26:26 +0000230 }
Sam McCalle2f3a732018-10-24 14:26:26 +0000231 }
232 };
233
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000234 llvm::StringMap<std::function<void(llvm::json::Value)>> Notifications;
235 llvm::StringMap<std::function<void(llvm::json::Value, ReplyOnce)>> Calls;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000236
237 // Method calls may be cancelled by ID, so keep track of their state.
238 // This needs a mutex: handlers may finish on a different thread, and that's
239 // when we clean up entries in the map.
240 mutable std::mutex RequestCancelersMutex;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000241 llvm::StringMap<std::pair<Canceler, /*Cookie*/ unsigned>> RequestCancelers;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000242 unsigned NextRequestCookie = 0; // To disambiguate reused IDs, see below.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000243 void onCancel(const llvm::json::Value &Params) {
244 const llvm::json::Value *ID = nullptr;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000245 if (auto *O = Params.getAsObject())
246 ID = O->get("id");
247 if (!ID) {
248 elog("Bad cancellation request: {0}", Params);
249 return;
250 }
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000251 auto StrID = llvm::to_string(*ID);
Sam McCall2c30fbc2018-10-18 12:32:04 +0000252 std::lock_guard<std::mutex> Lock(RequestCancelersMutex);
253 auto It = RequestCancelers.find(StrID);
254 if (It != RequestCancelers.end())
255 It->second.first(); // Invoke the canceler.
256 }
Sam McCalla69698f2019-03-27 17:47:49 +0000257
258 Context handlerContext() const {
259 return Context::current().derive(
260 kCurrentOffsetEncoding,
261 Server.NegotiatedOffsetEncoding.getValueOr(OffsetEncoding::UTF16));
262 }
263
Sam McCall2c30fbc2018-10-18 12:32:04 +0000264 // We run cancelable requests in a context that does two things:
265 // - allows cancellation using RequestCancelers[ID]
266 // - cleans up the entry in RequestCancelers when it's no longer needed
267 // If a client reuses an ID, the last wins and the first cannot be canceled.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000268 Context cancelableRequestContext(const llvm::json::Value &ID) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000269 auto Task = cancelableTask();
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000270 auto StrID = llvm::to_string(ID); // JSON-serialize ID for map key.
Sam McCall2c30fbc2018-10-18 12:32:04 +0000271 auto Cookie = NextRequestCookie++; // No lock, only called on main thread.
272 {
273 std::lock_guard<std::mutex> Lock(RequestCancelersMutex);
274 RequestCancelers[StrID] = {std::move(Task.second), Cookie};
275 }
276 // When the request ends, we can clean up the entry we just added.
277 // The cookie lets us check that it hasn't been overwritten due to ID
278 // reuse.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000279 return Task.first.derive(llvm::make_scope_exit([this, StrID, Cookie] {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000280 std::lock_guard<std::mutex> Lock(RequestCancelersMutex);
281 auto It = RequestCancelers.find(StrID);
282 if (It != RequestCancelers.end() && It->second.second == Cookie)
283 RequestCancelers.erase(It);
284 }));
285 }
286
287 ClangdLSPServer &Server;
288};
289
290// call(), notify(), and reply() wrap the Transport, adding logging and locking.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000291void ClangdLSPServer::call(llvm::StringRef Method, llvm::json::Value Params) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000292 auto ID = NextCallID++;
293 log("--> {0}({1})", Method, ID);
294 // We currently don't handle responses, so no need to store ID anywhere.
295 std::lock_guard<std::mutex> Lock(TranspWriter);
296 Transp.call(Method, std::move(Params), ID);
297}
298
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000299void ClangdLSPServer::notify(llvm::StringRef Method, llvm::json::Value Params) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000300 log("--> {0}", Method);
301 std::lock_guard<std::mutex> Lock(TranspWriter);
302 Transp.notify(Method, std::move(Params));
303}
304
Sam McCall2c30fbc2018-10-18 12:32:04 +0000305void ClangdLSPServer::onInitialize(const InitializeParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000306 Callback<llvm::json::Value> Reply) {
Sam McCalla69698f2019-03-27 17:47:49 +0000307 // Determine character encoding first as it affects constructed ClangdServer.
308 if (Params.capabilities.offsetEncoding && !NegotiatedOffsetEncoding) {
309 NegotiatedOffsetEncoding = OffsetEncoding::UTF16; // fallback
310 for (OffsetEncoding Supported : *Params.capabilities.offsetEncoding)
311 if (Supported != OffsetEncoding::UnsupportedEncoding) {
312 NegotiatedOffsetEncoding = Supported;
313 break;
314 }
315 }
316 llvm::Optional<WithContextValue> WithOffsetEncoding;
317 if (NegotiatedOffsetEncoding)
318 WithOffsetEncoding.emplace(kCurrentOffsetEncoding,
319 *NegotiatedOffsetEncoding);
320
Sam McCall0d9b40f2018-10-19 15:42:23 +0000321 if (Params.rootUri && *Params.rootUri)
322 ClangdServerOpts.WorkspaceRoot = Params.rootUri->file();
323 else if (Params.rootPath && !Params.rootPath->empty())
324 ClangdServerOpts.WorkspaceRoot = *Params.rootPath;
Sam McCall3d0adbe2018-10-18 14:41:50 +0000325 if (Server)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000326 return Reply(llvm::make_error<LSPError>("server already initialized",
327 ErrorCode::InvalidRequest));
Sam McCallbc904612018-10-25 04:22:52 +0000328 if (const auto &Dir = Params.initializationOptions.compilationDatabasePath)
329 CompileCommandsDir = Dir;
Sam McCallc55d09a2018-11-02 13:09:36 +0000330 if (UseDirBasedCDB)
331 BaseCDB = llvm::make_unique<DirectoryBasedGlobalCompilationDatabase>(
332 CompileCommandsDir);
Kadir Cetinkayabe6b35d2019-01-22 09:10:20 +0000333 CDB.emplace(BaseCDB.get(), Params.initializationOptions.fallbackFlags,
334 ClangdServerOpts.ResourceDir);
Sam McCallc55d09a2018-11-02 13:09:36 +0000335 Server.emplace(*CDB, FSProvider, static_cast<DiagnosticsConsumer &>(*this),
336 ClangdServerOpts);
Sam McCallbc904612018-10-25 04:22:52 +0000337 applyConfiguration(Params.initializationOptions.ConfigSettings);
Simon Marchi88016782018-08-01 11:28:49 +0000338
Sam McCallbf6a2fc2018-10-17 07:33:42 +0000339 CCOpts.EnableSnippets = Params.capabilities.CompletionSnippets;
Sam McCall8d412942019-06-18 11:57:26 +0000340 CCOpts.IncludeFixIts = Params.capabilities.CompletionFixes;
Sam McCallbf6a2fc2018-10-17 07:33:42 +0000341 DiagOpts.EmbedFixesInDiagnostics = Params.capabilities.DiagnosticFixes;
342 DiagOpts.SendDiagnosticCategory = Params.capabilities.DiagnosticCategory;
Sam McCallc9e4ee92019-04-18 15:17:07 +0000343 DiagOpts.EmitRelatedLocations =
344 Params.capabilities.DiagnosticRelatedInformation;
Sam McCallbf6a2fc2018-10-17 07:33:42 +0000345 if (Params.capabilities.WorkspaceSymbolKinds)
346 SupportedSymbolKinds |= *Params.capabilities.WorkspaceSymbolKinds;
347 if (Params.capabilities.CompletionItemKinds)
348 SupportedCompletionItemKinds |= *Params.capabilities.CompletionItemKinds;
349 SupportsCodeAction = Params.capabilities.CodeActionStructure;
Ilya Biryukov19d75602018-11-23 15:21:19 +0000350 SupportsHierarchicalDocumentSymbol =
351 Params.capabilities.HierarchicalDocumentSymbol;
Haojian Wub6188492018-12-20 15:39:12 +0000352 SupportFileStatus = Params.initializationOptions.FileStatus;
Ilya Biryukovf9169d02019-05-29 10:01:00 +0000353 HoverContentFormat = Params.capabilities.HoverContentFormat;
Ilya Biryukov4ef0f822019-06-04 09:36:59 +0000354 SupportsOffsetsInSignatureHelp = Params.capabilities.OffsetsInSignatureHelp;
Sam McCalla69698f2019-03-27 17:47:49 +0000355 llvm::json::Object Result{
Sam McCall0930ab02017-11-07 15:49:35 +0000356 {{"capabilities",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000357 llvm::json::Object{
Simon Marchi98082622018-03-26 14:41:40 +0000358 {"textDocumentSync", (int)TextDocumentSyncKind::Incremental},
Sam McCall0930ab02017-11-07 15:49:35 +0000359 {"documentFormattingProvider", true},
360 {"documentRangeFormattingProvider", true},
361 {"documentOnTypeFormattingProvider",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000362 llvm::json::Object{
Sam McCall25c62572019-06-10 14:26:21 +0000363 {"firstTriggerCharacter", "\n"},
Sam McCall0930ab02017-11-07 15:49:35 +0000364 {"moreTriggerCharacter", {}},
365 }},
366 {"codeActionProvider", true},
367 {"completionProvider",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000368 llvm::json::Object{
Sam McCall0930ab02017-11-07 15:49:35 +0000369 {"resolveProvider", false},
Ilya Biryukovb0826bd2019-01-03 13:37:12 +0000370 // We do extra checks for '>' and ':' in completion to only
371 // trigger on '->' and '::'.
Sam McCall0930ab02017-11-07 15:49:35 +0000372 {"triggerCharacters", {".", ">", ":"}},
373 }},
374 {"signatureHelpProvider",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000375 llvm::json::Object{
Sam McCall0930ab02017-11-07 15:49:35 +0000376 {"triggerCharacters", {"(", ","}},
377 }},
Sam McCall866ba2c2019-02-01 11:26:13 +0000378 {"declarationProvider", true},
Sam McCall0930ab02017-11-07 15:49:35 +0000379 {"definitionProvider", true},
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000380 {"documentHighlightProvider", true},
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000381 {"hoverProvider", true},
Haojian Wu345099c2017-11-09 11:30:04 +0000382 {"renameProvider", true},
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000383 {"documentSymbolProvider", true},
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000384 {"workspaceSymbolProvider", true},
Sam McCall1ad142f2018-09-05 11:53:07 +0000385 {"referencesProvider", true},
Sam McCall0930ab02017-11-07 15:49:35 +0000386 {"executeCommandProvider",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000387 llvm::json::Object{
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000388 {"commands",
389 {ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND,
390 ExecuteCommandParams::CLANGD_APPLY_TWEAK}},
Sam McCall0930ab02017-11-07 15:49:35 +0000391 }},
Kadir Cetinkaya86658022019-03-19 09:27:04 +0000392 {"typeHierarchyProvider", true},
Sam McCalla69698f2019-03-27 17:47:49 +0000393 }}}};
394 if (NegotiatedOffsetEncoding)
395 Result["offsetEncoding"] = *NegotiatedOffsetEncoding;
396 Reply(std::move(Result));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000397}
398
Sam McCall2c30fbc2018-10-18 12:32:04 +0000399void ClangdLSPServer::onShutdown(const ShutdownParams &Params,
400 Callback<std::nullptr_t> Reply) {
Ilya Biryukov0d9b8a32017-10-25 08:45:41 +0000401 // Do essentially nothing, just say we're ready to exit.
402 ShutdownRequestReceived = true;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000403 Reply(nullptr);
Sam McCall8a5dded2017-10-12 13:29:58 +0000404}
Ilya Biryukovafb55542017-05-16 14:40:30 +0000405
Sam McCall422c8282018-11-26 16:00:11 +0000406// sync is a clangd extension: it blocks until all background work completes.
407// It blocks the calling thread, so no messages are processed until it returns!
408void ClangdLSPServer::onSync(const NoParams &Params,
409 Callback<std::nullptr_t> Reply) {
410 if (Server->blockUntilIdleForTest(/*TimeoutSeconds=*/60))
411 Reply(nullptr);
412 else
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000413 Reply(llvm::createStringError(llvm::inconvertibleErrorCode(),
414 "Not idle after a minute"));
Sam McCall422c8282018-11-26 16:00:11 +0000415}
416
Sam McCall2c30fbc2018-10-18 12:32:04 +0000417void ClangdLSPServer::onDocumentDidOpen(
418 const DidOpenTextDocumentParams &Params) {
Simon Marchi9569fd52018-03-16 14:30:42 +0000419 PathRef File = Params.textDocument.uri.file();
Ilya Biryukovb10ef472018-06-13 09:20:41 +0000420
Sam McCall2c30fbc2018-10-18 12:32:04 +0000421 const std::string &Contents = Params.textDocument.text;
Simon Marchi9569fd52018-03-16 14:30:42 +0000422
Simon Marchi98082622018-03-26 14:41:40 +0000423 DraftMgr.addDraft(File, Contents);
Ilya Biryukov652364b2018-09-26 05:48:29 +0000424 Server->addDocument(File, Contents, WantDiagnostics::Yes);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000425}
426
Sam McCall2c30fbc2018-10-18 12:32:04 +0000427void ClangdLSPServer::onDocumentDidChange(
428 const DidChangeTextDocumentParams &Params) {
Eric Liu51fed182018-02-22 18:40:39 +0000429 auto WantDiags = WantDiagnostics::Auto;
430 if (Params.wantDiagnostics.hasValue())
431 WantDiags = Params.wantDiagnostics.getValue() ? WantDiagnostics::Yes
432 : WantDiagnostics::No;
Simon Marchi9569fd52018-03-16 14:30:42 +0000433
434 PathRef File = Params.textDocument.uri.file();
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000435 llvm::Expected<std::string> Contents =
Simon Marchi98082622018-03-26 14:41:40 +0000436 DraftMgr.updateDraft(File, Params.contentChanges);
437 if (!Contents) {
438 // If this fails, we are most likely going to be not in sync anymore with
439 // the client. It is better to remove the draft and let further operations
440 // fail rather than giving wrong results.
441 DraftMgr.removeDraft(File);
Ilya Biryukov652364b2018-09-26 05:48:29 +0000442 Server->removeDocument(File);
Sam McCallbed58852018-07-11 10:35:11 +0000443 elog("Failed to update {0}: {1}", File, Contents.takeError());
Simon Marchi98082622018-03-26 14:41:40 +0000444 return;
445 }
Simon Marchi9569fd52018-03-16 14:30:42 +0000446
Ilya Biryukov652364b2018-09-26 05:48:29 +0000447 Server->addDocument(File, *Contents, WantDiags);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000448}
449
Sam McCall2c30fbc2018-10-18 12:32:04 +0000450void ClangdLSPServer::onFileEvent(const DidChangeWatchedFilesParams &Params) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000451 Server->onFileEvent(Params);
Marc-Andre Laperlebf114242017-10-02 18:00:37 +0000452}
453
Sam McCall2c30fbc2018-10-18 12:32:04 +0000454void ClangdLSPServer::onCommand(const ExecuteCommandParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000455 Callback<llvm::json::Value> Reply) {
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000456 auto ApplyEdit = [this](WorkspaceEdit WE) {
Eric Liuc5105f92018-02-16 14:15:55 +0000457 ApplyWorkspaceEditParams Edit;
458 Edit.edit = std::move(WE);
Eric Liuc5105f92018-02-16 14:15:55 +0000459 // Ideally, we would wait for the response and if there is no error, we
460 // would reply success/failure to the original RPC.
461 call("workspace/applyEdit", Edit);
462 };
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000463 if (Params.command == ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND &&
464 Params.workspaceEdit) {
465 // The flow for "apply-fix" :
466 // 1. We publish a diagnostic, including fixits
467 // 2. The user clicks on the diagnostic, the editor asks us for code actions
468 // 3. We send code actions, with the fixit embedded as context
469 // 4. The user selects the fixit, the editor asks us to apply it
470 // 5. We unwrap the changes and send them back to the editor
471 // 6. The editor applies the changes (applyEdit), and sends us a reply (but
472 // we ignore it)
473
Sam McCall2c30fbc2018-10-18 12:32:04 +0000474 Reply("Fix applied.");
Eric Liuc5105f92018-02-16 14:15:55 +0000475 ApplyEdit(*Params.workspaceEdit);
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000476 } else if (Params.command == ExecuteCommandParams::CLANGD_APPLY_TWEAK &&
477 Params.tweakArgs) {
478 auto Code = DraftMgr.getDraft(Params.tweakArgs->file.file());
479 if (!Code)
480 return Reply(llvm::createStringError(
481 llvm::inconvertibleErrorCode(),
482 "trying to apply a code action for a non-added file"));
483
484 auto Action = [ApplyEdit](decltype(Reply) Reply, URIForFile File,
485 std::string Code,
Ilya Biryukov04112ec2019-06-12 12:03:24 +0000486 llvm::Expected<std::vector<TextEdit>> R) {
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000487 if (!R)
488 return Reply(R.takeError());
489
490 WorkspaceEdit WE;
491 WE.changes.emplace();
Ilya Biryukov04112ec2019-06-12 12:03:24 +0000492 (*WE.changes)[File.uri()] = std::move(*R);
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000493
494 Reply("Fix applied.");
495 ApplyEdit(std::move(WE));
496 };
497 Server->applyTweak(Params.tweakArgs->file.file(),
498 Params.tweakArgs->selection, Params.tweakArgs->tweakID,
499 Bind(Action, std::move(Reply), Params.tweakArgs->file,
500 std::move(*Code)));
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000501 } else {
502 // We should not get here because ExecuteCommandParams would not have
503 // parsed in the first place and this handler should not be called. But if
504 // more commands are added, this will be here has a safe guard.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000505 Reply(llvm::make_error<LSPError>(
506 llvm::formatv("Unsupported command \"{0}\".", Params.command).str(),
Sam McCall2c30fbc2018-10-18 12:32:04 +0000507 ErrorCode::InvalidParams));
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000508 }
509}
510
Sam McCall2c30fbc2018-10-18 12:32:04 +0000511void ClangdLSPServer::onWorkspaceSymbol(
512 const WorkspaceSymbolParams &Params,
513 Callback<std::vector<SymbolInformation>> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000514 Server->workspaceSymbols(
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000515 Params.query, CCOpts.Limit,
Sam McCall2c30fbc2018-10-18 12:32:04 +0000516 Bind(
517 [this](decltype(Reply) Reply,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000518 llvm::Expected<std::vector<SymbolInformation>> Items) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000519 if (!Items)
520 return Reply(Items.takeError());
521 for (auto &Sym : *Items)
522 Sym.kind = adjustKindToCapability(Sym.kind, SupportedSymbolKinds);
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000523
Sam McCall2c30fbc2018-10-18 12:32:04 +0000524 Reply(std::move(*Items));
525 },
526 std::move(Reply)));
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000527}
528
Sam McCall2c30fbc2018-10-18 12:32:04 +0000529void ClangdLSPServer::onRename(const RenameParams &Params,
530 Callback<WorkspaceEdit> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000531 Path File = Params.textDocument.uri.file();
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000532 llvm::Optional<std::string> Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000533 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000534 return Reply(llvm::make_error<LSPError>(
535 "onRename called for non-added file", ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000536
Ilya Biryukov652364b2018-09-26 05:48:29 +0000537 Server->rename(
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000538 File, Params.position, Params.newName,
Sam McCall2c30fbc2018-10-18 12:32:04 +0000539 Bind(
Ilya Biryukovd9c24dc2019-04-03 07:18:43 +0000540 [File, Code, Params](decltype(Reply) Reply,
541 llvm::Expected<std::vector<TextEdit>> Edits) {
542 if (!Edits)
543 return Reply(Edits.takeError());
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000544
Sam McCall2c30fbc2018-10-18 12:32:04 +0000545 WorkspaceEdit WE;
Ilya Biryukovd9c24dc2019-04-03 07:18:43 +0000546 WE.changes = {{Params.textDocument.uri.uri(), *Edits}};
Sam McCall2c30fbc2018-10-18 12:32:04 +0000547 Reply(WE);
548 },
549 std::move(Reply)));
Haojian Wu345099c2017-11-09 11:30:04 +0000550}
551
Sam McCall2c30fbc2018-10-18 12:32:04 +0000552void ClangdLSPServer::onDocumentDidClose(
553 const DidCloseTextDocumentParams &Params) {
Simon Marchi9569fd52018-03-16 14:30:42 +0000554 PathRef File = Params.textDocument.uri.file();
555 DraftMgr.removeDraft(File);
Ilya Biryukov652364b2018-09-26 05:48:29 +0000556 Server->removeDocument(File);
Ilya Biryukov49c10712019-03-25 10:15:11 +0000557
558 {
559 std::lock_guard<std::mutex> Lock(FixItsMutex);
560 FixItsMap.erase(File);
561 }
562 // clangd will not send updates for this file anymore, so we empty out the
563 // list of diagnostics shown on the client (e.g. in the "Problems" pane of
564 // VSCode). Note that this cannot race with actual diagnostics responses
565 // because removeDocument() guarantees no diagnostic callbacks will be
566 // executed after it returns.
567 publishDiagnostics(URIForFile::canonicalize(File, /*TUPath=*/File), {});
Ilya Biryukovafb55542017-05-16 14:40:30 +0000568}
569
Sam McCall4db732a2017-09-30 10:08:52 +0000570void ClangdLSPServer::onDocumentOnTypeFormatting(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000571 const DocumentOnTypeFormattingParams &Params,
572 Callback<std::vector<TextEdit>> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000573 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000574 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000575 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000576 return Reply(llvm::make_error<LSPError>(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000577 "onDocumentOnTypeFormatting called for non-added file",
578 ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000579
Sam McCall25c62572019-06-10 14:26:21 +0000580 Reply(Server->formatOnType(*Code, File, Params.position, Params.ch));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000581}
582
Sam McCall4db732a2017-09-30 10:08:52 +0000583void ClangdLSPServer::onDocumentRangeFormatting(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000584 const DocumentRangeFormattingParams &Params,
585 Callback<std::vector<TextEdit>> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000586 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000587 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000588 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000589 return Reply(llvm::make_error<LSPError>(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000590 "onDocumentRangeFormatting called for non-added file",
591 ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000592
Ilya Biryukov652364b2018-09-26 05:48:29 +0000593 auto ReplacementsOrError = Server->formatRange(*Code, File, Params.range);
Raoul Wols212bcf82017-12-12 20:25:06 +0000594 if (ReplacementsOrError)
Sam McCall2c30fbc2018-10-18 12:32:04 +0000595 Reply(replacementsToEdits(*Code, ReplacementsOrError.get()));
Raoul Wols212bcf82017-12-12 20:25:06 +0000596 else
Sam McCall2c30fbc2018-10-18 12:32:04 +0000597 Reply(ReplacementsOrError.takeError());
Ilya Biryukovafb55542017-05-16 14:40:30 +0000598}
599
Sam McCall2c30fbc2018-10-18 12:32:04 +0000600void ClangdLSPServer::onDocumentFormatting(
601 const DocumentFormattingParams &Params,
602 Callback<std::vector<TextEdit>> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000603 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000604 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000605 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000606 return Reply(llvm::make_error<LSPError>(
607 "onDocumentFormatting called for non-added file",
608 ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000609
Ilya Biryukov652364b2018-09-26 05:48:29 +0000610 auto ReplacementsOrError = Server->formatFile(*Code, File);
Raoul Wols212bcf82017-12-12 20:25:06 +0000611 if (ReplacementsOrError)
Sam McCall2c30fbc2018-10-18 12:32:04 +0000612 Reply(replacementsToEdits(*Code, ReplacementsOrError.get()));
Raoul Wols212bcf82017-12-12 20:25:06 +0000613 else
Sam McCall2c30fbc2018-10-18 12:32:04 +0000614 Reply(ReplacementsOrError.takeError());
Sam McCall4db732a2017-09-30 10:08:52 +0000615}
616
Ilya Biryukov19d75602018-11-23 15:21:19 +0000617/// The functions constructs a flattened view of the DocumentSymbol hierarchy.
618/// Used by the clients that do not support the hierarchical view.
619static std::vector<SymbolInformation>
620flattenSymbolHierarchy(llvm::ArrayRef<DocumentSymbol> Symbols,
621 const URIForFile &FileURI) {
622
623 std::vector<SymbolInformation> Results;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000624 std::function<void(const DocumentSymbol &, llvm::StringRef)> Process =
625 [&](const DocumentSymbol &S, llvm::Optional<llvm::StringRef> ParentName) {
Ilya Biryukov19d75602018-11-23 15:21:19 +0000626 SymbolInformation SI;
627 SI.containerName = ParentName ? "" : *ParentName;
628 SI.name = S.name;
629 SI.kind = S.kind;
630 SI.location.range = S.range;
631 SI.location.uri = FileURI;
632
633 Results.push_back(std::move(SI));
634 std::string FullName =
635 !ParentName ? S.name : (ParentName->str() + "::" + S.name);
636 for (auto &C : S.children)
637 Process(C, /*ParentName=*/FullName);
638 };
639 for (auto &S : Symbols)
640 Process(S, /*ParentName=*/"");
641 return Results;
642}
643
644void ClangdLSPServer::onDocumentSymbol(const DocumentSymbolParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000645 Callback<llvm::json::Value> Reply) {
Ilya Biryukov19d75602018-11-23 15:21:19 +0000646 URIForFile FileURI = Params.textDocument.uri;
Ilya Biryukov652364b2018-09-26 05:48:29 +0000647 Server->documentSymbols(
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000648 Params.textDocument.uri.file(),
Sam McCall2c30fbc2018-10-18 12:32:04 +0000649 Bind(
Ilya Biryukov19d75602018-11-23 15:21:19 +0000650 [this, FileURI](decltype(Reply) Reply,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000651 llvm::Expected<std::vector<DocumentSymbol>> Items) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000652 if (!Items)
653 return Reply(Items.takeError());
Ilya Biryukov19d75602018-11-23 15:21:19 +0000654 adjustSymbolKinds(*Items, SupportedSymbolKinds);
655 if (SupportsHierarchicalDocumentSymbol)
656 return Reply(std::move(*Items));
657 else
658 return Reply(flattenSymbolHierarchy(*Items, FileURI));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000659 },
660 std::move(Reply)));
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000661}
662
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000663static llvm::Optional<Command> asCommand(const CodeAction &Action) {
Sam McCall20841d42018-10-16 16:29:41 +0000664 Command Cmd;
665 if (Action.command && Action.edit)
Sam McCallc008af62018-10-20 15:30:37 +0000666 return None; // Not representable. (We never emit these anyway).
Sam McCall20841d42018-10-16 16:29:41 +0000667 if (Action.command) {
668 Cmd = *Action.command;
669 } else if (Action.edit) {
670 Cmd.command = Command::CLANGD_APPLY_FIX_COMMAND;
671 Cmd.workspaceEdit = *Action.edit;
672 } else {
Sam McCallc008af62018-10-20 15:30:37 +0000673 return None;
Sam McCall20841d42018-10-16 16:29:41 +0000674 }
675 Cmd.title = Action.title;
676 if (Action.kind && *Action.kind == CodeAction::QUICKFIX_KIND)
677 Cmd.title = "Apply fix: " + Cmd.title;
678 return Cmd;
679}
680
Sam McCall2c30fbc2018-10-18 12:32:04 +0000681void ClangdLSPServer::onCodeAction(const CodeActionParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000682 Callback<llvm::json::Value> Reply) {
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000683 URIForFile File = Params.textDocument.uri;
684 auto Code = DraftMgr.getDraft(File.file());
Sam McCall2c30fbc2018-10-18 12:32:04 +0000685 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000686 return Reply(llvm::make_error<LSPError>(
687 "onCodeAction called for non-added file", ErrorCode::InvalidParams));
Sam McCall20841d42018-10-16 16:29:41 +0000688 // We provide a code action for Fixes on the specified diagnostics.
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000689 std::vector<CodeAction> FixIts;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000690 for (const Diagnostic &D : Params.context.diagnostics) {
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000691 for (auto &F : getFixes(File.file(), D)) {
692 FixIts.push_back(toCodeAction(F, Params.textDocument.uri));
693 FixIts.back().diagnostics = {D};
Sam McCalldd0566b2017-11-06 15:40:30 +0000694 }
Ilya Biryukovafb55542017-05-16 14:40:30 +0000695 }
Sam McCall20841d42018-10-16 16:29:41 +0000696
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000697 // Now enumerate the semantic code actions.
698 auto ConsumeActions =
699 [this](decltype(Reply) Reply, URIForFile File, std::string Code,
700 Range Selection, std::vector<CodeAction> FixIts,
701 llvm::Expected<std::vector<ClangdServer::TweakRef>> Tweaks) {
Ilya Biryukovc6ed7782019-01-30 14:24:17 +0000702 if (!Tweaks)
703 return Reply(Tweaks.takeError());
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000704
705 std::vector<CodeAction> Actions = std::move(FixIts);
706 Actions.reserve(Actions.size() + Tweaks->size());
707 for (const auto &T : *Tweaks)
708 Actions.push_back(toCodeAction(T, File, Selection));
709
710 if (SupportsCodeAction)
711 return Reply(llvm::json::Array(Actions));
712 std::vector<Command> Commands;
713 for (const auto &Action : Actions) {
714 if (auto Command = asCommand(Action))
715 Commands.push_back(std::move(*Command));
716 }
717 return Reply(llvm::json::Array(Commands));
718 };
719
720 Server->enumerateTweaks(File.file(), Params.range,
Ilya Biryukovc9409c62019-01-30 09:39:01 +0000721 Bind(ConsumeActions, std::move(Reply), File,
722 std::move(*Code), Params.range,
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000723 std::move(FixIts)));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000724}
725
Ilya Biryukovb0826bd2019-01-03 13:37:12 +0000726void ClangdLSPServer::onCompletion(const CompletionParams &Params,
Sam McCall2c30fbc2018-10-18 12:32:04 +0000727 Callback<CompletionList> Reply) {
Ilya Biryukova7a11472019-06-07 16:24:38 +0000728 if (!shouldRunCompletion(Params)) {
729 // Clients sometimes auto-trigger completions in undesired places (e.g.
730 // 'a >^ '), we return empty results in those cases.
731 vlog("ignored auto-triggered completion, preceding char did not match");
732 return Reply(CompletionList());
733 }
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000734 Server->codeComplete(Params.textDocument.uri.file(), Params.position, CCOpts,
735 Bind(
736 [this](decltype(Reply) Reply,
737 llvm::Expected<CodeCompleteResult> List) {
738 if (!List)
739 return Reply(List.takeError());
740 CompletionList LSPList;
741 LSPList.isIncomplete = List->HasMore;
742 for (const auto &R : List->Completions) {
743 CompletionItem C = R.render(CCOpts);
744 C.kind = adjustKindToCapability(
745 C.kind, SupportedCompletionItemKinds);
746 LSPList.items.push_back(std::move(C));
747 }
748 return Reply(std::move(LSPList));
749 },
750 std::move(Reply)));
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000751}
752
Sam McCall2c30fbc2018-10-18 12:32:04 +0000753void ClangdLSPServer::onSignatureHelp(const TextDocumentPositionParams &Params,
754 Callback<SignatureHelp> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000755 Server->signatureHelp(Params.textDocument.uri.file(), Params.position,
Ilya Biryukov4ef0f822019-06-04 09:36:59 +0000756 Bind(
757 [this](decltype(Reply) Reply,
758 llvm::Expected<SignatureHelp> Signature) {
759 if (!Signature)
760 return Reply(Signature.takeError());
761 if (SupportsOffsetsInSignatureHelp)
762 return Reply(std::move(*Signature));
763 // Strip out the offsets from signature help for
764 // clients that only support string labels.
Simon Pilgrim5f7c20e2019-06-04 11:11:51 +0000765 for (auto &SigInfo : Signature->signatures) {
766 for (auto &Param : SigInfo.parameters)
Ilya Biryukov4ef0f822019-06-04 09:36:59 +0000767 Param.labelOffsets.reset();
768 }
769 return Reply(std::move(*Signature));
770 },
771 std::move(Reply)));
Ilya Biryukov652364b2018-09-26 05:48:29 +0000772}
773
Sam McCall0dbab7f2019-02-02 05:56:00 +0000774// Go to definition has a toggle function: if def and decl are distinct, then
775// the first press gives you the def, the second gives you the matching def.
776// getToggle() returns the counterpart location that under the cursor.
777//
778// We return the toggled location alone (ignoring other symbols) to encourage
779// editors to "bounce" quickly between locations, without showing a menu.
780static Location *getToggle(const TextDocumentPositionParams &Point,
781 LocatedSymbol &Sym) {
782 // Toggle only makes sense with two distinct locations.
783 if (!Sym.Definition || *Sym.Definition == Sym.PreferredDeclaration)
784 return nullptr;
785 if (Sym.Definition->uri.file() == Point.textDocument.uri.file() &&
786 Sym.Definition->range.contains(Point.position))
787 return &Sym.PreferredDeclaration;
788 if (Sym.PreferredDeclaration.uri.file() == Point.textDocument.uri.file() &&
789 Sym.PreferredDeclaration.range.contains(Point.position))
790 return &*Sym.Definition;
791 return nullptr;
792}
793
Sam McCall2c30fbc2018-10-18 12:32:04 +0000794void ClangdLSPServer::onGoToDefinition(const TextDocumentPositionParams &Params,
795 Callback<std::vector<Location>> Reply) {
Sam McCall866ba2c2019-02-01 11:26:13 +0000796 Server->locateSymbolAt(
797 Params.textDocument.uri.file(), Params.position,
798 Bind(
Sam McCall0dbab7f2019-02-02 05:56:00 +0000799 [&, Params](decltype(Reply) Reply,
800 llvm::Expected<std::vector<LocatedSymbol>> Symbols) {
Sam McCall866ba2c2019-02-01 11:26:13 +0000801 if (!Symbols)
802 return Reply(Symbols.takeError());
803 std::vector<Location> Defs;
Sam McCall0dbab7f2019-02-02 05:56:00 +0000804 for (auto &S : *Symbols) {
805 if (Location *Toggle = getToggle(Params, S))
806 return Reply(std::vector<Location>{std::move(*Toggle)});
Sam McCall866ba2c2019-02-01 11:26:13 +0000807 Defs.push_back(S.Definition.getValueOr(S.PreferredDeclaration));
Sam McCall0dbab7f2019-02-02 05:56:00 +0000808 }
Sam McCall866ba2c2019-02-01 11:26:13 +0000809 Reply(std::move(Defs));
810 },
811 std::move(Reply)));
812}
813
814void ClangdLSPServer::onGoToDeclaration(
815 const TextDocumentPositionParams &Params,
816 Callback<std::vector<Location>> Reply) {
817 Server->locateSymbolAt(
818 Params.textDocument.uri.file(), Params.position,
819 Bind(
Sam McCall0dbab7f2019-02-02 05:56:00 +0000820 [&, Params](decltype(Reply) Reply,
821 llvm::Expected<std::vector<LocatedSymbol>> Symbols) {
Sam McCall866ba2c2019-02-01 11:26:13 +0000822 if (!Symbols)
823 return Reply(Symbols.takeError());
824 std::vector<Location> Decls;
Sam McCall0dbab7f2019-02-02 05:56:00 +0000825 for (auto &S : *Symbols) {
826 if (Location *Toggle = getToggle(Params, S))
827 return Reply(std::vector<Location>{std::move(*Toggle)});
828 Decls.push_back(std::move(S.PreferredDeclaration));
829 }
Sam McCall866ba2c2019-02-01 11:26:13 +0000830 Reply(std::move(Decls));
831 },
832 std::move(Reply)));
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000833}
834
Sam McCall111fe842019-05-07 07:55:35 +0000835void ClangdLSPServer::onSwitchSourceHeader(
836 const TextDocumentIdentifier &Params,
Sam McCallb9ec3e92019-05-07 08:30:32 +0000837 Callback<llvm::Optional<URIForFile>> Reply) {
Sam McCall111fe842019-05-07 07:55:35 +0000838 if (auto Result = Server->switchSourceHeader(Params.uri.file()))
Sam McCallb9ec3e92019-05-07 08:30:32 +0000839 Reply(URIForFile::canonicalize(*Result, Params.uri.file()));
Sam McCall111fe842019-05-07 07:55:35 +0000840 else
841 Reply(llvm::None);
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000842}
843
Sam McCall2c30fbc2018-10-18 12:32:04 +0000844void ClangdLSPServer::onDocumentHighlight(
845 const TextDocumentPositionParams &Params,
846 Callback<std::vector<DocumentHighlight>> Reply) {
847 Server->findDocumentHighlights(Params.textDocument.uri.file(),
848 Params.position, std::move(Reply));
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000849}
850
Sam McCall2c30fbc2018-10-18 12:32:04 +0000851void ClangdLSPServer::onHover(const TextDocumentPositionParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000852 Callback<llvm::Optional<Hover>> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000853 Server->findHover(Params.textDocument.uri.file(), Params.position,
Kadir Cetinkayac6578ee2019-05-28 10:29:58 +0000854 Bind(
Ilya Biryukovf9169d02019-05-29 10:01:00 +0000855 [this](decltype(Reply) Reply,
856 llvm::Expected<llvm::Optional<HoverInfo>> H) {
857 if (!H)
858 return Reply(H.takeError());
859 if (!*H)
Kadir Cetinkayac6578ee2019-05-28 10:29:58 +0000860 return Reply(llvm::None);
Ilya Biryukovf9169d02019-05-29 10:01:00 +0000861
862 Hover R;
863 R.contents.kind = HoverContentFormat;
864 R.range = (*H)->SymRange;
865 switch (HoverContentFormat) {
866 case MarkupKind::PlainText:
867 R.contents.value =
868 (*H)->present().renderAsPlainText();
869 return Reply(std::move(R));
870 case MarkupKind::Markdown:
871 R.contents.value =
872 (*H)->present().renderAsMarkdown();
873 return Reply(std::move(R));
874 };
875 llvm_unreachable("unhandled MarkupKind");
Kadir Cetinkayac6578ee2019-05-28 10:29:58 +0000876 },
877 std::move(Reply)));
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000878}
879
Kadir Cetinkaya86658022019-03-19 09:27:04 +0000880void ClangdLSPServer::onTypeHierarchy(
881 const TypeHierarchyParams &Params,
882 Callback<Optional<TypeHierarchyItem>> Reply) {
883 Server->typeHierarchy(Params.textDocument.uri.file(), Params.position,
884 Params.resolve, Params.direction, std::move(Reply));
885}
886
Simon Marchi88016782018-08-01 11:28:49 +0000887void ClangdLSPServer::applyConfiguration(
Sam McCallbc904612018-10-25 04:22:52 +0000888 const ConfigurationSettings &Settings) {
Simon Marchiabeed662018-10-16 15:55:03 +0000889 // Per-file update to the compilation database.
Sam McCallbc904612018-10-25 04:22:52 +0000890 bool ShouldReparseOpenFiles = false;
891 for (auto &Entry : Settings.compilationDatabaseChanges) {
892 /// The opened files need to be reparsed only when some existing
893 /// entries are changed.
894 PathRef File = Entry.first;
Sam McCallc55d09a2018-11-02 13:09:36 +0000895 auto Old = CDB->getCompileCommand(File);
896 auto New =
897 tooling::CompileCommand(std::move(Entry.second.workingDirectory), File,
898 std::move(Entry.second.compilationCommand),
899 /*Output=*/"");
Sam McCall6980edb2018-11-02 14:07:51 +0000900 if (Old != New) {
Sam McCallc55d09a2018-11-02 13:09:36 +0000901 CDB->setCompileCommand(File, std::move(New));
Sam McCall6980edb2018-11-02 14:07:51 +0000902 ShouldReparseOpenFiles = true;
903 }
Alex Lorenzf8087862018-08-01 17:39:29 +0000904 }
Sam McCallbc904612018-10-25 04:22:52 +0000905 if (ShouldReparseOpenFiles)
906 reparseOpenedFiles();
Simon Marchi5178f922018-02-22 14:00:39 +0000907}
908
Ilya Biryukov49c10712019-03-25 10:15:11 +0000909void ClangdLSPServer::publishDiagnostics(
910 const URIForFile &File, std::vector<clangd::Diagnostic> Diagnostics) {
911 // Publish diagnostics.
912 notify("textDocument/publishDiagnostics",
913 llvm::json::Object{
914 {"uri", File},
915 {"diagnostics", std::move(Diagnostics)},
916 });
917}
918
Simon Marchi88016782018-08-01 11:28:49 +0000919// FIXME: This function needs to be properly tested.
920void ClangdLSPServer::onChangeConfiguration(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000921 const DidChangeConfigurationParams &Params) {
Simon Marchi88016782018-08-01 11:28:49 +0000922 applyConfiguration(Params.settings);
923}
924
Sam McCall2c30fbc2018-10-18 12:32:04 +0000925void ClangdLSPServer::onReference(const ReferenceParams &Params,
926 Callback<std::vector<Location>> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000927 Server->findReferences(Params.textDocument.uri.file(), Params.position,
Haojian Wuc34f0222019-01-14 18:11:09 +0000928 CCOpts.Limit, std::move(Reply));
Sam McCall1ad142f2018-09-05 11:53:07 +0000929}
930
Jan Korousb4067012018-11-27 16:40:46 +0000931void ClangdLSPServer::onSymbolInfo(const TextDocumentPositionParams &Params,
932 Callback<std::vector<SymbolDetails>> Reply) {
933 Server->symbolInfo(Params.textDocument.uri.file(), Params.position,
934 std::move(Reply));
935}
936
Sam McCalla69698f2019-03-27 17:47:49 +0000937ClangdLSPServer::ClangdLSPServer(
938 class Transport &Transp, const FileSystemProvider &FSProvider,
939 const clangd::CodeCompleteOptions &CCOpts,
940 llvm::Optional<Path> CompileCommandsDir, bool UseDirBasedCDB,
941 llvm::Optional<OffsetEncoding> ForcedOffsetEncoding,
942 const ClangdServer::Options &Opts)
Haojian Wu1ca0c582019-01-22 09:39:05 +0000943 : Transp(Transp), MsgHandler(new MessageHandler(*this)),
944 FSProvider(FSProvider), CCOpts(CCOpts),
Sam McCalld1c9d112018-10-23 14:19:54 +0000945 SupportedSymbolKinds(defaultSymbolKinds()),
Kadir Cetinkaya133d46f2018-09-27 17:13:07 +0000946 SupportedCompletionItemKinds(defaultCompletionItemKinds()),
Sam McCallc55d09a2018-11-02 13:09:36 +0000947 UseDirBasedCDB(UseDirBasedCDB),
Sam McCalla69698f2019-03-27 17:47:49 +0000948 CompileCommandsDir(std::move(CompileCommandsDir)), ClangdServerOpts(Opts),
949 NegotiatedOffsetEncoding(ForcedOffsetEncoding) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000950 // clang-format off
951 MsgHandler->bind("initialize", &ClangdLSPServer::onInitialize);
952 MsgHandler->bind("shutdown", &ClangdLSPServer::onShutdown);
Sam McCall422c8282018-11-26 16:00:11 +0000953 MsgHandler->bind("sync", &ClangdLSPServer::onSync);
Sam McCall2c30fbc2018-10-18 12:32:04 +0000954 MsgHandler->bind("textDocument/rangeFormatting", &ClangdLSPServer::onDocumentRangeFormatting);
955 MsgHandler->bind("textDocument/onTypeFormatting", &ClangdLSPServer::onDocumentOnTypeFormatting);
956 MsgHandler->bind("textDocument/formatting", &ClangdLSPServer::onDocumentFormatting);
957 MsgHandler->bind("textDocument/codeAction", &ClangdLSPServer::onCodeAction);
958 MsgHandler->bind("textDocument/completion", &ClangdLSPServer::onCompletion);
959 MsgHandler->bind("textDocument/signatureHelp", &ClangdLSPServer::onSignatureHelp);
960 MsgHandler->bind("textDocument/definition", &ClangdLSPServer::onGoToDefinition);
Sam McCall866ba2c2019-02-01 11:26:13 +0000961 MsgHandler->bind("textDocument/declaration", &ClangdLSPServer::onGoToDeclaration);
Sam McCall2c30fbc2018-10-18 12:32:04 +0000962 MsgHandler->bind("textDocument/references", &ClangdLSPServer::onReference);
963 MsgHandler->bind("textDocument/switchSourceHeader", &ClangdLSPServer::onSwitchSourceHeader);
964 MsgHandler->bind("textDocument/rename", &ClangdLSPServer::onRename);
965 MsgHandler->bind("textDocument/hover", &ClangdLSPServer::onHover);
966 MsgHandler->bind("textDocument/documentSymbol", &ClangdLSPServer::onDocumentSymbol);
967 MsgHandler->bind("workspace/executeCommand", &ClangdLSPServer::onCommand);
968 MsgHandler->bind("textDocument/documentHighlight", &ClangdLSPServer::onDocumentHighlight);
969 MsgHandler->bind("workspace/symbol", &ClangdLSPServer::onWorkspaceSymbol);
970 MsgHandler->bind("textDocument/didOpen", &ClangdLSPServer::onDocumentDidOpen);
971 MsgHandler->bind("textDocument/didClose", &ClangdLSPServer::onDocumentDidClose);
972 MsgHandler->bind("textDocument/didChange", &ClangdLSPServer::onDocumentDidChange);
973 MsgHandler->bind("workspace/didChangeWatchedFiles", &ClangdLSPServer::onFileEvent);
974 MsgHandler->bind("workspace/didChangeConfiguration", &ClangdLSPServer::onChangeConfiguration);
Jan Korousb4067012018-11-27 16:40:46 +0000975 MsgHandler->bind("textDocument/symbolInfo", &ClangdLSPServer::onSymbolInfo);
Kadir Cetinkaya86658022019-03-19 09:27:04 +0000976 MsgHandler->bind("textDocument/typeHierarchy", &ClangdLSPServer::onTypeHierarchy);
Sam McCall2c30fbc2018-10-18 12:32:04 +0000977 // clang-format on
978}
979
980ClangdLSPServer::~ClangdLSPServer() = default;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000981
Sam McCalldc8f3cf2018-10-17 07:32:05 +0000982bool ClangdLSPServer::run() {
Ilya Biryukovafb55542017-05-16 14:40:30 +0000983 // Run the Language Server loop.
Sam McCalldc8f3cf2018-10-17 07:32:05 +0000984 bool CleanExit = true;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000985 if (auto Err = Transp.loop(*MsgHandler)) {
Sam McCalldc8f3cf2018-10-17 07:32:05 +0000986 elog("Transport error: {0}", std::move(Err));
987 CleanExit = false;
988 }
Ilya Biryukovafb55542017-05-16 14:40:30 +0000989
Ilya Biryukov652364b2018-09-26 05:48:29 +0000990 // Destroy ClangdServer to ensure all worker threads finish.
991 Server.reset();
Sam McCalldc8f3cf2018-10-17 07:32:05 +0000992 return CleanExit && ShutdownRequestReceived;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000993}
994
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000995std::vector<Fix> ClangdLSPServer::getFixes(llvm::StringRef File,
Ilya Biryukov71028b82018-03-12 15:28:22 +0000996 const clangd::Diagnostic &D) {
Ilya Biryukov38d79772017-05-16 09:38:59 +0000997 std::lock_guard<std::mutex> Lock(FixItsMutex);
998 auto DiagToFixItsIter = FixItsMap.find(File);
999 if (DiagToFixItsIter == FixItsMap.end())
1000 return {};
1001
1002 const auto &DiagToFixItsMap = DiagToFixItsIter->second;
1003 auto FixItsIter = DiagToFixItsMap.find(D);
1004 if (FixItsIter == DiagToFixItsMap.end())
1005 return {};
1006
1007 return FixItsIter->second;
1008}
1009
Ilya Biryukovb0826bd2019-01-03 13:37:12 +00001010bool ClangdLSPServer::shouldRunCompletion(
1011 const CompletionParams &Params) const {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001012 llvm::StringRef Trigger = Params.context.triggerCharacter;
Ilya Biryukovb0826bd2019-01-03 13:37:12 +00001013 if (Params.context.triggerKind != CompletionTriggerKind::TriggerCharacter ||
1014 (Trigger != ">" && Trigger != ":"))
1015 return true;
1016
1017 auto Code = DraftMgr.getDraft(Params.textDocument.uri.file());
1018 if (!Code)
1019 return true; // completion code will log the error for untracked doc.
1020
1021 // A completion request is sent when the user types '>' or ':', but we only
1022 // want to trigger on '->' and '::'. We check the preceeding character to make
1023 // sure it matches what we expected.
1024 // Running the lexer here would be more robust (e.g. we can detect comments
1025 // and avoid triggering completion there), but we choose to err on the side
1026 // of simplicity here.
1027 auto Offset = positionToOffset(*Code, Params.position,
1028 /*AllowColumnsBeyondLineLength=*/false);
1029 if (!Offset) {
1030 vlog("could not convert position '{0}' to offset for file '{1}'",
1031 Params.position, Params.textDocument.uri.file());
1032 return true;
1033 }
1034 if (*Offset < 2)
1035 return false;
1036
1037 if (Trigger == ">")
1038 return (*Code)[*Offset - 2] == '-'; // trigger only on '->'.
1039 if (Trigger == ":")
1040 return (*Code)[*Offset - 2] == ':'; // trigger only on '::'.
1041 assert(false && "unhandled trigger character");
1042 return true;
1043}
1044
Sam McCalla7bb0cc2018-03-12 23:22:35 +00001045void ClangdLSPServer::onDiagnosticsReady(PathRef File,
1046 std::vector<Diag> Diagnostics) {
Eric Liu4d814a92018-11-28 10:30:42 +00001047 auto URI = URIForFile::canonicalize(File, /*TUPath=*/File);
Sam McCall16e70702018-10-24 07:59:38 +00001048 std::vector<Diagnostic> LSPDiagnostics;
Ilya Biryukov38d79772017-05-16 09:38:59 +00001049 DiagnosticToReplacementMap LocalFixIts; // Temporary storage
Sam McCalla7bb0cc2018-03-12 23:22:35 +00001050 for (auto &Diag : Diagnostics) {
Sam McCall16e70702018-10-24 07:59:38 +00001051 toLSPDiags(Diag, URI, DiagOpts,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001052 [&](clangd::Diagnostic Diag, llvm::ArrayRef<Fix> Fixes) {
Sam McCall16e70702018-10-24 07:59:38 +00001053 auto &FixItsForDiagnostic = LocalFixIts[Diag];
1054 llvm::copy(Fixes, std::back_inserter(FixItsForDiagnostic));
1055 LSPDiagnostics.push_back(std::move(Diag));
1056 });
Ilya Biryukov38d79772017-05-16 09:38:59 +00001057 }
1058
1059 // Cache FixIts
1060 {
Ilya Biryukov38d79772017-05-16 09:38:59 +00001061 std::lock_guard<std::mutex> Lock(FixItsMutex);
1062 FixItsMap[File] = LocalFixIts;
1063 }
1064
Ilya Biryukov49c10712019-03-25 10:15:11 +00001065 // Send a notification to the LSP client.
1066 publishDiagnostics(URI, std::move(LSPDiagnostics));
Ilya Biryukov38d79772017-05-16 09:38:59 +00001067}
Simon Marchi9569fd52018-03-16 14:30:42 +00001068
Haojian Wub6188492018-12-20 15:39:12 +00001069void ClangdLSPServer::onFileUpdated(PathRef File, const TUStatus &Status) {
1070 if (!SupportFileStatus)
1071 return;
1072 // FIXME: we don't emit "BuildingFile" and `RunningAction`, as these
1073 // two statuses are running faster in practice, which leads the UI constantly
1074 // changing, and doesn't provide much value. We may want to emit status at a
1075 // reasonable time interval (e.g. 0.5s).
1076 if (Status.Action.S == TUAction::BuildingFile ||
1077 Status.Action.S == TUAction::RunningAction)
1078 return;
1079 notify("textDocument/clangd.fileStatus", Status.render(File));
1080}
1081
Simon Marchi9569fd52018-03-16 14:30:42 +00001082void ClangdLSPServer::reparseOpenedFiles() {
1083 for (const Path &FilePath : DraftMgr.getActiveFiles())
Ilya Biryukov652364b2018-09-26 05:48:29 +00001084 Server->addDocument(FilePath, *DraftMgr.getDraft(FilePath),
1085 WantDiagnostics::Auto);
Simon Marchi9569fd52018-03-16 14:30:42 +00001086}
Alex Lorenzf8087862018-08-01 17:39:29 +00001087
Sam McCallc008af62018-10-20 15:30:37 +00001088} // namespace clangd
1089} // namespace clang