blob: 3f0b9c0956cd6d18da704d93ba5b8bb2760a2692 [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;
340 DiagOpts.EmbedFixesInDiagnostics = Params.capabilities.DiagnosticFixes;
341 DiagOpts.SendDiagnosticCategory = Params.capabilities.DiagnosticCategory;
Sam McCallc9e4ee92019-04-18 15:17:07 +0000342 DiagOpts.EmitRelatedLocations =
343 Params.capabilities.DiagnosticRelatedInformation;
Sam McCallbf6a2fc2018-10-17 07:33:42 +0000344 if (Params.capabilities.WorkspaceSymbolKinds)
345 SupportedSymbolKinds |= *Params.capabilities.WorkspaceSymbolKinds;
346 if (Params.capabilities.CompletionItemKinds)
347 SupportedCompletionItemKinds |= *Params.capabilities.CompletionItemKinds;
348 SupportsCodeAction = Params.capabilities.CodeActionStructure;
Ilya Biryukov19d75602018-11-23 15:21:19 +0000349 SupportsHierarchicalDocumentSymbol =
350 Params.capabilities.HierarchicalDocumentSymbol;
Haojian Wub6188492018-12-20 15:39:12 +0000351 SupportFileStatus = Params.initializationOptions.FileStatus;
Ilya Biryukovf9169d02019-05-29 10:01:00 +0000352 HoverContentFormat = Params.capabilities.HoverContentFormat;
Ilya Biryukov4ef0f822019-06-04 09:36:59 +0000353 SupportsOffsetsInSignatureHelp = Params.capabilities.OffsetsInSignatureHelp;
Sam McCalla69698f2019-03-27 17:47:49 +0000354 llvm::json::Object Result{
Sam McCall0930ab02017-11-07 15:49:35 +0000355 {{"capabilities",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000356 llvm::json::Object{
Simon Marchi98082622018-03-26 14:41:40 +0000357 {"textDocumentSync", (int)TextDocumentSyncKind::Incremental},
Sam McCall0930ab02017-11-07 15:49:35 +0000358 {"documentFormattingProvider", true},
359 {"documentRangeFormattingProvider", true},
360 {"documentOnTypeFormattingProvider",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000361 llvm::json::Object{
Sam McCall25c62572019-06-10 14:26:21 +0000362 {"firstTriggerCharacter", "\n"},
Sam McCall0930ab02017-11-07 15:49:35 +0000363 {"moreTriggerCharacter", {}},
364 }},
365 {"codeActionProvider", true},
366 {"completionProvider",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000367 llvm::json::Object{
Sam McCall0930ab02017-11-07 15:49:35 +0000368 {"resolveProvider", false},
Ilya Biryukovb0826bd2019-01-03 13:37:12 +0000369 // We do extra checks for '>' and ':' in completion to only
370 // trigger on '->' and '::'.
Sam McCall0930ab02017-11-07 15:49:35 +0000371 {"triggerCharacters", {".", ">", ":"}},
372 }},
373 {"signatureHelpProvider",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000374 llvm::json::Object{
Sam McCall0930ab02017-11-07 15:49:35 +0000375 {"triggerCharacters", {"(", ","}},
376 }},
Sam McCall866ba2c2019-02-01 11:26:13 +0000377 {"declarationProvider", true},
Sam McCall0930ab02017-11-07 15:49:35 +0000378 {"definitionProvider", true},
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000379 {"documentHighlightProvider", true},
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000380 {"hoverProvider", true},
Haojian Wu345099c2017-11-09 11:30:04 +0000381 {"renameProvider", true},
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000382 {"documentSymbolProvider", true},
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000383 {"workspaceSymbolProvider", true},
Sam McCall1ad142f2018-09-05 11:53:07 +0000384 {"referencesProvider", true},
Sam McCall0930ab02017-11-07 15:49:35 +0000385 {"executeCommandProvider",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000386 llvm::json::Object{
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000387 {"commands",
388 {ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND,
389 ExecuteCommandParams::CLANGD_APPLY_TWEAK}},
Sam McCall0930ab02017-11-07 15:49:35 +0000390 }},
Kadir Cetinkaya86658022019-03-19 09:27:04 +0000391 {"typeHierarchyProvider", true},
Sam McCalla69698f2019-03-27 17:47:49 +0000392 }}}};
393 if (NegotiatedOffsetEncoding)
394 Result["offsetEncoding"] = *NegotiatedOffsetEncoding;
395 Reply(std::move(Result));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000396}
397
Sam McCall2c30fbc2018-10-18 12:32:04 +0000398void ClangdLSPServer::onShutdown(const ShutdownParams &Params,
399 Callback<std::nullptr_t> Reply) {
Ilya Biryukov0d9b8a32017-10-25 08:45:41 +0000400 // Do essentially nothing, just say we're ready to exit.
401 ShutdownRequestReceived = true;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000402 Reply(nullptr);
Sam McCall8a5dded2017-10-12 13:29:58 +0000403}
Ilya Biryukovafb55542017-05-16 14:40:30 +0000404
Sam McCall422c8282018-11-26 16:00:11 +0000405// sync is a clangd extension: it blocks until all background work completes.
406// It blocks the calling thread, so no messages are processed until it returns!
407void ClangdLSPServer::onSync(const NoParams &Params,
408 Callback<std::nullptr_t> Reply) {
409 if (Server->blockUntilIdleForTest(/*TimeoutSeconds=*/60))
410 Reply(nullptr);
411 else
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000412 Reply(llvm::createStringError(llvm::inconvertibleErrorCode(),
413 "Not idle after a minute"));
Sam McCall422c8282018-11-26 16:00:11 +0000414}
415
Sam McCall2c30fbc2018-10-18 12:32:04 +0000416void ClangdLSPServer::onDocumentDidOpen(
417 const DidOpenTextDocumentParams &Params) {
Simon Marchi9569fd52018-03-16 14:30:42 +0000418 PathRef File = Params.textDocument.uri.file();
Ilya Biryukovb10ef472018-06-13 09:20:41 +0000419
Sam McCall2c30fbc2018-10-18 12:32:04 +0000420 const std::string &Contents = Params.textDocument.text;
Simon Marchi9569fd52018-03-16 14:30:42 +0000421
Simon Marchi98082622018-03-26 14:41:40 +0000422 DraftMgr.addDraft(File, Contents);
Ilya Biryukov652364b2018-09-26 05:48:29 +0000423 Server->addDocument(File, Contents, WantDiagnostics::Yes);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000424}
425
Sam McCall2c30fbc2018-10-18 12:32:04 +0000426void ClangdLSPServer::onDocumentDidChange(
427 const DidChangeTextDocumentParams &Params) {
Eric Liu51fed182018-02-22 18:40:39 +0000428 auto WantDiags = WantDiagnostics::Auto;
429 if (Params.wantDiagnostics.hasValue())
430 WantDiags = Params.wantDiagnostics.getValue() ? WantDiagnostics::Yes
431 : WantDiagnostics::No;
Simon Marchi9569fd52018-03-16 14:30:42 +0000432
433 PathRef File = Params.textDocument.uri.file();
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000434 llvm::Expected<std::string> Contents =
Simon Marchi98082622018-03-26 14:41:40 +0000435 DraftMgr.updateDraft(File, Params.contentChanges);
436 if (!Contents) {
437 // If this fails, we are most likely going to be not in sync anymore with
438 // the client. It is better to remove the draft and let further operations
439 // fail rather than giving wrong results.
440 DraftMgr.removeDraft(File);
Ilya Biryukov652364b2018-09-26 05:48:29 +0000441 Server->removeDocument(File);
Sam McCallbed58852018-07-11 10:35:11 +0000442 elog("Failed to update {0}: {1}", File, Contents.takeError());
Simon Marchi98082622018-03-26 14:41:40 +0000443 return;
444 }
Simon Marchi9569fd52018-03-16 14:30:42 +0000445
Ilya Biryukov652364b2018-09-26 05:48:29 +0000446 Server->addDocument(File, *Contents, WantDiags);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000447}
448
Sam McCall2c30fbc2018-10-18 12:32:04 +0000449void ClangdLSPServer::onFileEvent(const DidChangeWatchedFilesParams &Params) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000450 Server->onFileEvent(Params);
Marc-Andre Laperlebf114242017-10-02 18:00:37 +0000451}
452
Sam McCall2c30fbc2018-10-18 12:32:04 +0000453void ClangdLSPServer::onCommand(const ExecuteCommandParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000454 Callback<llvm::json::Value> Reply) {
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000455 auto ApplyEdit = [this](WorkspaceEdit WE) {
Eric Liuc5105f92018-02-16 14:15:55 +0000456 ApplyWorkspaceEditParams Edit;
457 Edit.edit = std::move(WE);
Eric Liuc5105f92018-02-16 14:15:55 +0000458 // Ideally, we would wait for the response and if there is no error, we
459 // would reply success/failure to the original RPC.
460 call("workspace/applyEdit", Edit);
461 };
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000462 if (Params.command == ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND &&
463 Params.workspaceEdit) {
464 // The flow for "apply-fix" :
465 // 1. We publish a diagnostic, including fixits
466 // 2. The user clicks on the diagnostic, the editor asks us for code actions
467 // 3. We send code actions, with the fixit embedded as context
468 // 4. The user selects the fixit, the editor asks us to apply it
469 // 5. We unwrap the changes and send them back to the editor
470 // 6. The editor applies the changes (applyEdit), and sends us a reply (but
471 // we ignore it)
472
Sam McCall2c30fbc2018-10-18 12:32:04 +0000473 Reply("Fix applied.");
Eric Liuc5105f92018-02-16 14:15:55 +0000474 ApplyEdit(*Params.workspaceEdit);
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000475 } else if (Params.command == ExecuteCommandParams::CLANGD_APPLY_TWEAK &&
476 Params.tweakArgs) {
477 auto Code = DraftMgr.getDraft(Params.tweakArgs->file.file());
478 if (!Code)
479 return Reply(llvm::createStringError(
480 llvm::inconvertibleErrorCode(),
481 "trying to apply a code action for a non-added file"));
482
483 auto Action = [ApplyEdit](decltype(Reply) Reply, URIForFile File,
484 std::string Code,
485 llvm::Expected<tooling::Replacements> R) {
486 if (!R)
487 return Reply(R.takeError());
488
489 WorkspaceEdit WE;
490 WE.changes.emplace();
491 (*WE.changes)[File.uri()] = replacementsToEdits(Code, *R);
492
493 Reply("Fix applied.");
494 ApplyEdit(std::move(WE));
495 };
496 Server->applyTweak(Params.tweakArgs->file.file(),
497 Params.tweakArgs->selection, Params.tweakArgs->tweakID,
498 Bind(Action, std::move(Reply), Params.tweakArgs->file,
499 std::move(*Code)));
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000500 } else {
501 // We should not get here because ExecuteCommandParams would not have
502 // parsed in the first place and this handler should not be called. But if
503 // more commands are added, this will be here has a safe guard.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000504 Reply(llvm::make_error<LSPError>(
505 llvm::formatv("Unsupported command \"{0}\".", Params.command).str(),
Sam McCall2c30fbc2018-10-18 12:32:04 +0000506 ErrorCode::InvalidParams));
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000507 }
508}
509
Sam McCall2c30fbc2018-10-18 12:32:04 +0000510void ClangdLSPServer::onWorkspaceSymbol(
511 const WorkspaceSymbolParams &Params,
512 Callback<std::vector<SymbolInformation>> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000513 Server->workspaceSymbols(
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000514 Params.query, CCOpts.Limit,
Sam McCall2c30fbc2018-10-18 12:32:04 +0000515 Bind(
516 [this](decltype(Reply) Reply,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000517 llvm::Expected<std::vector<SymbolInformation>> Items) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000518 if (!Items)
519 return Reply(Items.takeError());
520 for (auto &Sym : *Items)
521 Sym.kind = adjustKindToCapability(Sym.kind, SupportedSymbolKinds);
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000522
Sam McCall2c30fbc2018-10-18 12:32:04 +0000523 Reply(std::move(*Items));
524 },
525 std::move(Reply)));
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000526}
527
Sam McCall2c30fbc2018-10-18 12:32:04 +0000528void ClangdLSPServer::onRename(const RenameParams &Params,
529 Callback<WorkspaceEdit> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000530 Path File = Params.textDocument.uri.file();
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000531 llvm::Optional<std::string> Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000532 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000533 return Reply(llvm::make_error<LSPError>(
534 "onRename called for non-added file", ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000535
Ilya Biryukov652364b2018-09-26 05:48:29 +0000536 Server->rename(
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000537 File, Params.position, Params.newName,
Sam McCall2c30fbc2018-10-18 12:32:04 +0000538 Bind(
Ilya Biryukovd9c24dc2019-04-03 07:18:43 +0000539 [File, Code, Params](decltype(Reply) Reply,
540 llvm::Expected<std::vector<TextEdit>> Edits) {
541 if (!Edits)
542 return Reply(Edits.takeError());
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000543
Sam McCall2c30fbc2018-10-18 12:32:04 +0000544 WorkspaceEdit WE;
Ilya Biryukovd9c24dc2019-04-03 07:18:43 +0000545 WE.changes = {{Params.textDocument.uri.uri(), *Edits}};
Sam McCall2c30fbc2018-10-18 12:32:04 +0000546 Reply(WE);
547 },
548 std::move(Reply)));
Haojian Wu345099c2017-11-09 11:30:04 +0000549}
550
Sam McCall2c30fbc2018-10-18 12:32:04 +0000551void ClangdLSPServer::onDocumentDidClose(
552 const DidCloseTextDocumentParams &Params) {
Simon Marchi9569fd52018-03-16 14:30:42 +0000553 PathRef File = Params.textDocument.uri.file();
554 DraftMgr.removeDraft(File);
Ilya Biryukov652364b2018-09-26 05:48:29 +0000555 Server->removeDocument(File);
Ilya Biryukov49c10712019-03-25 10:15:11 +0000556
557 {
558 std::lock_guard<std::mutex> Lock(FixItsMutex);
559 FixItsMap.erase(File);
560 }
561 // clangd will not send updates for this file anymore, so we empty out the
562 // list of diagnostics shown on the client (e.g. in the "Problems" pane of
563 // VSCode). Note that this cannot race with actual diagnostics responses
564 // because removeDocument() guarantees no diagnostic callbacks will be
565 // executed after it returns.
566 publishDiagnostics(URIForFile::canonicalize(File, /*TUPath=*/File), {});
Ilya Biryukovafb55542017-05-16 14:40:30 +0000567}
568
Sam McCall4db732a2017-09-30 10:08:52 +0000569void ClangdLSPServer::onDocumentOnTypeFormatting(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000570 const DocumentOnTypeFormattingParams &Params,
571 Callback<std::vector<TextEdit>> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000572 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000573 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000574 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000575 return Reply(llvm::make_error<LSPError>(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000576 "onDocumentOnTypeFormatting called for non-added file",
577 ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000578
Sam McCall25c62572019-06-10 14:26:21 +0000579 Reply(Server->formatOnType(*Code, File, Params.position, Params.ch));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000580}
581
Sam McCall4db732a2017-09-30 10:08:52 +0000582void ClangdLSPServer::onDocumentRangeFormatting(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000583 const DocumentRangeFormattingParams &Params,
584 Callback<std::vector<TextEdit>> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000585 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000586 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000587 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000588 return Reply(llvm::make_error<LSPError>(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000589 "onDocumentRangeFormatting called for non-added file",
590 ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000591
Ilya Biryukov652364b2018-09-26 05:48:29 +0000592 auto ReplacementsOrError = Server->formatRange(*Code, File, Params.range);
Raoul Wols212bcf82017-12-12 20:25:06 +0000593 if (ReplacementsOrError)
Sam McCall2c30fbc2018-10-18 12:32:04 +0000594 Reply(replacementsToEdits(*Code, ReplacementsOrError.get()));
Raoul Wols212bcf82017-12-12 20:25:06 +0000595 else
Sam McCall2c30fbc2018-10-18 12:32:04 +0000596 Reply(ReplacementsOrError.takeError());
Ilya Biryukovafb55542017-05-16 14:40:30 +0000597}
598
Sam McCall2c30fbc2018-10-18 12:32:04 +0000599void ClangdLSPServer::onDocumentFormatting(
600 const DocumentFormattingParams &Params,
601 Callback<std::vector<TextEdit>> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000602 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000603 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000604 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000605 return Reply(llvm::make_error<LSPError>(
606 "onDocumentFormatting called for non-added file",
607 ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000608
Ilya Biryukov652364b2018-09-26 05:48:29 +0000609 auto ReplacementsOrError = Server->formatFile(*Code, File);
Raoul Wols212bcf82017-12-12 20:25:06 +0000610 if (ReplacementsOrError)
Sam McCall2c30fbc2018-10-18 12:32:04 +0000611 Reply(replacementsToEdits(*Code, ReplacementsOrError.get()));
Raoul Wols212bcf82017-12-12 20:25:06 +0000612 else
Sam McCall2c30fbc2018-10-18 12:32:04 +0000613 Reply(ReplacementsOrError.takeError());
Sam McCall4db732a2017-09-30 10:08:52 +0000614}
615
Ilya Biryukov19d75602018-11-23 15:21:19 +0000616/// The functions constructs a flattened view of the DocumentSymbol hierarchy.
617/// Used by the clients that do not support the hierarchical view.
618static std::vector<SymbolInformation>
619flattenSymbolHierarchy(llvm::ArrayRef<DocumentSymbol> Symbols,
620 const URIForFile &FileURI) {
621
622 std::vector<SymbolInformation> Results;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000623 std::function<void(const DocumentSymbol &, llvm::StringRef)> Process =
624 [&](const DocumentSymbol &S, llvm::Optional<llvm::StringRef> ParentName) {
Ilya Biryukov19d75602018-11-23 15:21:19 +0000625 SymbolInformation SI;
626 SI.containerName = ParentName ? "" : *ParentName;
627 SI.name = S.name;
628 SI.kind = S.kind;
629 SI.location.range = S.range;
630 SI.location.uri = FileURI;
631
632 Results.push_back(std::move(SI));
633 std::string FullName =
634 !ParentName ? S.name : (ParentName->str() + "::" + S.name);
635 for (auto &C : S.children)
636 Process(C, /*ParentName=*/FullName);
637 };
638 for (auto &S : Symbols)
639 Process(S, /*ParentName=*/"");
640 return Results;
641}
642
643void ClangdLSPServer::onDocumentSymbol(const DocumentSymbolParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000644 Callback<llvm::json::Value> Reply) {
Ilya Biryukov19d75602018-11-23 15:21:19 +0000645 URIForFile FileURI = Params.textDocument.uri;
Ilya Biryukov652364b2018-09-26 05:48:29 +0000646 Server->documentSymbols(
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000647 Params.textDocument.uri.file(),
Sam McCall2c30fbc2018-10-18 12:32:04 +0000648 Bind(
Ilya Biryukov19d75602018-11-23 15:21:19 +0000649 [this, FileURI](decltype(Reply) Reply,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000650 llvm::Expected<std::vector<DocumentSymbol>> Items) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000651 if (!Items)
652 return Reply(Items.takeError());
Ilya Biryukov19d75602018-11-23 15:21:19 +0000653 adjustSymbolKinds(*Items, SupportedSymbolKinds);
654 if (SupportsHierarchicalDocumentSymbol)
655 return Reply(std::move(*Items));
656 else
657 return Reply(flattenSymbolHierarchy(*Items, FileURI));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000658 },
659 std::move(Reply)));
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000660}
661
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000662static llvm::Optional<Command> asCommand(const CodeAction &Action) {
Sam McCall20841d42018-10-16 16:29:41 +0000663 Command Cmd;
664 if (Action.command && Action.edit)
Sam McCallc008af62018-10-20 15:30:37 +0000665 return None; // Not representable. (We never emit these anyway).
Sam McCall20841d42018-10-16 16:29:41 +0000666 if (Action.command) {
667 Cmd = *Action.command;
668 } else if (Action.edit) {
669 Cmd.command = Command::CLANGD_APPLY_FIX_COMMAND;
670 Cmd.workspaceEdit = *Action.edit;
671 } else {
Sam McCallc008af62018-10-20 15:30:37 +0000672 return None;
Sam McCall20841d42018-10-16 16:29:41 +0000673 }
674 Cmd.title = Action.title;
675 if (Action.kind && *Action.kind == CodeAction::QUICKFIX_KIND)
676 Cmd.title = "Apply fix: " + Cmd.title;
677 return Cmd;
678}
679
Sam McCall2c30fbc2018-10-18 12:32:04 +0000680void ClangdLSPServer::onCodeAction(const CodeActionParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000681 Callback<llvm::json::Value> Reply) {
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000682 URIForFile File = Params.textDocument.uri;
683 auto Code = DraftMgr.getDraft(File.file());
Sam McCall2c30fbc2018-10-18 12:32:04 +0000684 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000685 return Reply(llvm::make_error<LSPError>(
686 "onCodeAction called for non-added file", ErrorCode::InvalidParams));
Sam McCall20841d42018-10-16 16:29:41 +0000687 // We provide a code action for Fixes on the specified diagnostics.
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000688 std::vector<CodeAction> FixIts;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000689 for (const Diagnostic &D : Params.context.diagnostics) {
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000690 for (auto &F : getFixes(File.file(), D)) {
691 FixIts.push_back(toCodeAction(F, Params.textDocument.uri));
692 FixIts.back().diagnostics = {D};
Sam McCalldd0566b2017-11-06 15:40:30 +0000693 }
Ilya Biryukovafb55542017-05-16 14:40:30 +0000694 }
Sam McCall20841d42018-10-16 16:29:41 +0000695
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000696 // Now enumerate the semantic code actions.
697 auto ConsumeActions =
698 [this](decltype(Reply) Reply, URIForFile File, std::string Code,
699 Range Selection, std::vector<CodeAction> FixIts,
700 llvm::Expected<std::vector<ClangdServer::TweakRef>> Tweaks) {
Ilya Biryukovc6ed7782019-01-30 14:24:17 +0000701 if (!Tweaks)
702 return Reply(Tweaks.takeError());
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000703
704 std::vector<CodeAction> Actions = std::move(FixIts);
705 Actions.reserve(Actions.size() + Tweaks->size());
706 for (const auto &T : *Tweaks)
707 Actions.push_back(toCodeAction(T, File, Selection));
708
709 if (SupportsCodeAction)
710 return Reply(llvm::json::Array(Actions));
711 std::vector<Command> Commands;
712 for (const auto &Action : Actions) {
713 if (auto Command = asCommand(Action))
714 Commands.push_back(std::move(*Command));
715 }
716 return Reply(llvm::json::Array(Commands));
717 };
718
719 Server->enumerateTweaks(File.file(), Params.range,
Ilya Biryukovc9409c62019-01-30 09:39:01 +0000720 Bind(ConsumeActions, std::move(Reply), File,
721 std::move(*Code), Params.range,
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000722 std::move(FixIts)));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000723}
724
Ilya Biryukovb0826bd2019-01-03 13:37:12 +0000725void ClangdLSPServer::onCompletion(const CompletionParams &Params,
Sam McCall2c30fbc2018-10-18 12:32:04 +0000726 Callback<CompletionList> Reply) {
Ilya Biryukova7a11472019-06-07 16:24:38 +0000727 if (!shouldRunCompletion(Params)) {
728 // Clients sometimes auto-trigger completions in undesired places (e.g.
729 // 'a >^ '), we return empty results in those cases.
730 vlog("ignored auto-triggered completion, preceding char did not match");
731 return Reply(CompletionList());
732 }
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000733 Server->codeComplete(Params.textDocument.uri.file(), Params.position, CCOpts,
734 Bind(
735 [this](decltype(Reply) Reply,
736 llvm::Expected<CodeCompleteResult> List) {
737 if (!List)
738 return Reply(List.takeError());
739 CompletionList LSPList;
740 LSPList.isIncomplete = List->HasMore;
741 for (const auto &R : List->Completions) {
742 CompletionItem C = R.render(CCOpts);
743 C.kind = adjustKindToCapability(
744 C.kind, SupportedCompletionItemKinds);
745 LSPList.items.push_back(std::move(C));
746 }
747 return Reply(std::move(LSPList));
748 },
749 std::move(Reply)));
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000750}
751
Sam McCall2c30fbc2018-10-18 12:32:04 +0000752void ClangdLSPServer::onSignatureHelp(const TextDocumentPositionParams &Params,
753 Callback<SignatureHelp> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000754 Server->signatureHelp(Params.textDocument.uri.file(), Params.position,
Ilya Biryukov4ef0f822019-06-04 09:36:59 +0000755 Bind(
756 [this](decltype(Reply) Reply,
757 llvm::Expected<SignatureHelp> Signature) {
758 if (!Signature)
759 return Reply(Signature.takeError());
760 if (SupportsOffsetsInSignatureHelp)
761 return Reply(std::move(*Signature));
762 // Strip out the offsets from signature help for
763 // clients that only support string labels.
Simon Pilgrim5f7c20e2019-06-04 11:11:51 +0000764 for (auto &SigInfo : Signature->signatures) {
765 for (auto &Param : SigInfo.parameters)
Ilya Biryukov4ef0f822019-06-04 09:36:59 +0000766 Param.labelOffsets.reset();
767 }
768 return Reply(std::move(*Signature));
769 },
770 std::move(Reply)));
Ilya Biryukov652364b2018-09-26 05:48:29 +0000771}
772
Sam McCall0dbab7f2019-02-02 05:56:00 +0000773// Go to definition has a toggle function: if def and decl are distinct, then
774// the first press gives you the def, the second gives you the matching def.
775// getToggle() returns the counterpart location that under the cursor.
776//
777// We return the toggled location alone (ignoring other symbols) to encourage
778// editors to "bounce" quickly between locations, without showing a menu.
779static Location *getToggle(const TextDocumentPositionParams &Point,
780 LocatedSymbol &Sym) {
781 // Toggle only makes sense with two distinct locations.
782 if (!Sym.Definition || *Sym.Definition == Sym.PreferredDeclaration)
783 return nullptr;
784 if (Sym.Definition->uri.file() == Point.textDocument.uri.file() &&
785 Sym.Definition->range.contains(Point.position))
786 return &Sym.PreferredDeclaration;
787 if (Sym.PreferredDeclaration.uri.file() == Point.textDocument.uri.file() &&
788 Sym.PreferredDeclaration.range.contains(Point.position))
789 return &*Sym.Definition;
790 return nullptr;
791}
792
Sam McCall2c30fbc2018-10-18 12:32:04 +0000793void ClangdLSPServer::onGoToDefinition(const TextDocumentPositionParams &Params,
794 Callback<std::vector<Location>> Reply) {
Sam McCall866ba2c2019-02-01 11:26:13 +0000795 Server->locateSymbolAt(
796 Params.textDocument.uri.file(), Params.position,
797 Bind(
Sam McCall0dbab7f2019-02-02 05:56:00 +0000798 [&, Params](decltype(Reply) Reply,
799 llvm::Expected<std::vector<LocatedSymbol>> Symbols) {
Sam McCall866ba2c2019-02-01 11:26:13 +0000800 if (!Symbols)
801 return Reply(Symbols.takeError());
802 std::vector<Location> Defs;
Sam McCall0dbab7f2019-02-02 05:56:00 +0000803 for (auto &S : *Symbols) {
804 if (Location *Toggle = getToggle(Params, S))
805 return Reply(std::vector<Location>{std::move(*Toggle)});
Sam McCall866ba2c2019-02-01 11:26:13 +0000806 Defs.push_back(S.Definition.getValueOr(S.PreferredDeclaration));
Sam McCall0dbab7f2019-02-02 05:56:00 +0000807 }
Sam McCall866ba2c2019-02-01 11:26:13 +0000808 Reply(std::move(Defs));
809 },
810 std::move(Reply)));
811}
812
813void ClangdLSPServer::onGoToDeclaration(
814 const TextDocumentPositionParams &Params,
815 Callback<std::vector<Location>> Reply) {
816 Server->locateSymbolAt(
817 Params.textDocument.uri.file(), Params.position,
818 Bind(
Sam McCall0dbab7f2019-02-02 05:56:00 +0000819 [&, Params](decltype(Reply) Reply,
820 llvm::Expected<std::vector<LocatedSymbol>> Symbols) {
Sam McCall866ba2c2019-02-01 11:26:13 +0000821 if (!Symbols)
822 return Reply(Symbols.takeError());
823 std::vector<Location> Decls;
Sam McCall0dbab7f2019-02-02 05:56:00 +0000824 for (auto &S : *Symbols) {
825 if (Location *Toggle = getToggle(Params, S))
826 return Reply(std::vector<Location>{std::move(*Toggle)});
827 Decls.push_back(std::move(S.PreferredDeclaration));
828 }
Sam McCall866ba2c2019-02-01 11:26:13 +0000829 Reply(std::move(Decls));
830 },
831 std::move(Reply)));
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000832}
833
Sam McCall111fe842019-05-07 07:55:35 +0000834void ClangdLSPServer::onSwitchSourceHeader(
835 const TextDocumentIdentifier &Params,
Sam McCallb9ec3e92019-05-07 08:30:32 +0000836 Callback<llvm::Optional<URIForFile>> Reply) {
Sam McCall111fe842019-05-07 07:55:35 +0000837 if (auto Result = Server->switchSourceHeader(Params.uri.file()))
Sam McCallb9ec3e92019-05-07 08:30:32 +0000838 Reply(URIForFile::canonicalize(*Result, Params.uri.file()));
Sam McCall111fe842019-05-07 07:55:35 +0000839 else
840 Reply(llvm::None);
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000841}
842
Sam McCall2c30fbc2018-10-18 12:32:04 +0000843void ClangdLSPServer::onDocumentHighlight(
844 const TextDocumentPositionParams &Params,
845 Callback<std::vector<DocumentHighlight>> Reply) {
846 Server->findDocumentHighlights(Params.textDocument.uri.file(),
847 Params.position, std::move(Reply));
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000848}
849
Sam McCall2c30fbc2018-10-18 12:32:04 +0000850void ClangdLSPServer::onHover(const TextDocumentPositionParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000851 Callback<llvm::Optional<Hover>> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000852 Server->findHover(Params.textDocument.uri.file(), Params.position,
Kadir Cetinkayac6578ee2019-05-28 10:29:58 +0000853 Bind(
Ilya Biryukovf9169d02019-05-29 10:01:00 +0000854 [this](decltype(Reply) Reply,
855 llvm::Expected<llvm::Optional<HoverInfo>> H) {
856 if (!H)
857 return Reply(H.takeError());
858 if (!*H)
Kadir Cetinkayac6578ee2019-05-28 10:29:58 +0000859 return Reply(llvm::None);
Ilya Biryukovf9169d02019-05-29 10:01:00 +0000860
861 Hover R;
862 R.contents.kind = HoverContentFormat;
863 R.range = (*H)->SymRange;
864 switch (HoverContentFormat) {
865 case MarkupKind::PlainText:
866 R.contents.value =
867 (*H)->present().renderAsPlainText();
868 return Reply(std::move(R));
869 case MarkupKind::Markdown:
870 R.contents.value =
871 (*H)->present().renderAsMarkdown();
872 return Reply(std::move(R));
873 };
874 llvm_unreachable("unhandled MarkupKind");
Kadir Cetinkayac6578ee2019-05-28 10:29:58 +0000875 },
876 std::move(Reply)));
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000877}
878
Kadir Cetinkaya86658022019-03-19 09:27:04 +0000879void ClangdLSPServer::onTypeHierarchy(
880 const TypeHierarchyParams &Params,
881 Callback<Optional<TypeHierarchyItem>> Reply) {
882 Server->typeHierarchy(Params.textDocument.uri.file(), Params.position,
883 Params.resolve, Params.direction, std::move(Reply));
884}
885
Simon Marchi88016782018-08-01 11:28:49 +0000886void ClangdLSPServer::applyConfiguration(
Sam McCallbc904612018-10-25 04:22:52 +0000887 const ConfigurationSettings &Settings) {
Simon Marchiabeed662018-10-16 15:55:03 +0000888 // Per-file update to the compilation database.
Sam McCallbc904612018-10-25 04:22:52 +0000889 bool ShouldReparseOpenFiles = false;
890 for (auto &Entry : Settings.compilationDatabaseChanges) {
891 /// The opened files need to be reparsed only when some existing
892 /// entries are changed.
893 PathRef File = Entry.first;
Sam McCallc55d09a2018-11-02 13:09:36 +0000894 auto Old = CDB->getCompileCommand(File);
895 auto New =
896 tooling::CompileCommand(std::move(Entry.second.workingDirectory), File,
897 std::move(Entry.second.compilationCommand),
898 /*Output=*/"");
Sam McCall6980edb2018-11-02 14:07:51 +0000899 if (Old != New) {
Sam McCallc55d09a2018-11-02 13:09:36 +0000900 CDB->setCompileCommand(File, std::move(New));
Sam McCall6980edb2018-11-02 14:07:51 +0000901 ShouldReparseOpenFiles = true;
902 }
Alex Lorenzf8087862018-08-01 17:39:29 +0000903 }
Sam McCallbc904612018-10-25 04:22:52 +0000904 if (ShouldReparseOpenFiles)
905 reparseOpenedFiles();
Simon Marchi5178f922018-02-22 14:00:39 +0000906}
907
Ilya Biryukov49c10712019-03-25 10:15:11 +0000908void ClangdLSPServer::publishDiagnostics(
909 const URIForFile &File, std::vector<clangd::Diagnostic> Diagnostics) {
910 // Publish diagnostics.
911 notify("textDocument/publishDiagnostics",
912 llvm::json::Object{
913 {"uri", File},
914 {"diagnostics", std::move(Diagnostics)},
915 });
916}
917
Simon Marchi88016782018-08-01 11:28:49 +0000918// FIXME: This function needs to be properly tested.
919void ClangdLSPServer::onChangeConfiguration(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000920 const DidChangeConfigurationParams &Params) {
Simon Marchi88016782018-08-01 11:28:49 +0000921 applyConfiguration(Params.settings);
922}
923
Sam McCall2c30fbc2018-10-18 12:32:04 +0000924void ClangdLSPServer::onReference(const ReferenceParams &Params,
925 Callback<std::vector<Location>> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000926 Server->findReferences(Params.textDocument.uri.file(), Params.position,
Haojian Wuc34f0222019-01-14 18:11:09 +0000927 CCOpts.Limit, std::move(Reply));
Sam McCall1ad142f2018-09-05 11:53:07 +0000928}
929
Jan Korousb4067012018-11-27 16:40:46 +0000930void ClangdLSPServer::onSymbolInfo(const TextDocumentPositionParams &Params,
931 Callback<std::vector<SymbolDetails>> Reply) {
932 Server->symbolInfo(Params.textDocument.uri.file(), Params.position,
933 std::move(Reply));
934}
935
Sam McCalla69698f2019-03-27 17:47:49 +0000936ClangdLSPServer::ClangdLSPServer(
937 class Transport &Transp, const FileSystemProvider &FSProvider,
938 const clangd::CodeCompleteOptions &CCOpts,
939 llvm::Optional<Path> CompileCommandsDir, bool UseDirBasedCDB,
940 llvm::Optional<OffsetEncoding> ForcedOffsetEncoding,
941 const ClangdServer::Options &Opts)
Haojian Wu1ca0c582019-01-22 09:39:05 +0000942 : Transp(Transp), MsgHandler(new MessageHandler(*this)),
943 FSProvider(FSProvider), CCOpts(CCOpts),
Sam McCalld1c9d112018-10-23 14:19:54 +0000944 SupportedSymbolKinds(defaultSymbolKinds()),
Kadir Cetinkaya133d46f2018-09-27 17:13:07 +0000945 SupportedCompletionItemKinds(defaultCompletionItemKinds()),
Sam McCallc55d09a2018-11-02 13:09:36 +0000946 UseDirBasedCDB(UseDirBasedCDB),
Sam McCalla69698f2019-03-27 17:47:49 +0000947 CompileCommandsDir(std::move(CompileCommandsDir)), ClangdServerOpts(Opts),
948 NegotiatedOffsetEncoding(ForcedOffsetEncoding) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000949 // clang-format off
950 MsgHandler->bind("initialize", &ClangdLSPServer::onInitialize);
951 MsgHandler->bind("shutdown", &ClangdLSPServer::onShutdown);
Sam McCall422c8282018-11-26 16:00:11 +0000952 MsgHandler->bind("sync", &ClangdLSPServer::onSync);
Sam McCall2c30fbc2018-10-18 12:32:04 +0000953 MsgHandler->bind("textDocument/rangeFormatting", &ClangdLSPServer::onDocumentRangeFormatting);
954 MsgHandler->bind("textDocument/onTypeFormatting", &ClangdLSPServer::onDocumentOnTypeFormatting);
955 MsgHandler->bind("textDocument/formatting", &ClangdLSPServer::onDocumentFormatting);
956 MsgHandler->bind("textDocument/codeAction", &ClangdLSPServer::onCodeAction);
957 MsgHandler->bind("textDocument/completion", &ClangdLSPServer::onCompletion);
958 MsgHandler->bind("textDocument/signatureHelp", &ClangdLSPServer::onSignatureHelp);
959 MsgHandler->bind("textDocument/definition", &ClangdLSPServer::onGoToDefinition);
Sam McCall866ba2c2019-02-01 11:26:13 +0000960 MsgHandler->bind("textDocument/declaration", &ClangdLSPServer::onGoToDeclaration);
Sam McCall2c30fbc2018-10-18 12:32:04 +0000961 MsgHandler->bind("textDocument/references", &ClangdLSPServer::onReference);
962 MsgHandler->bind("textDocument/switchSourceHeader", &ClangdLSPServer::onSwitchSourceHeader);
963 MsgHandler->bind("textDocument/rename", &ClangdLSPServer::onRename);
964 MsgHandler->bind("textDocument/hover", &ClangdLSPServer::onHover);
965 MsgHandler->bind("textDocument/documentSymbol", &ClangdLSPServer::onDocumentSymbol);
966 MsgHandler->bind("workspace/executeCommand", &ClangdLSPServer::onCommand);
967 MsgHandler->bind("textDocument/documentHighlight", &ClangdLSPServer::onDocumentHighlight);
968 MsgHandler->bind("workspace/symbol", &ClangdLSPServer::onWorkspaceSymbol);
969 MsgHandler->bind("textDocument/didOpen", &ClangdLSPServer::onDocumentDidOpen);
970 MsgHandler->bind("textDocument/didClose", &ClangdLSPServer::onDocumentDidClose);
971 MsgHandler->bind("textDocument/didChange", &ClangdLSPServer::onDocumentDidChange);
972 MsgHandler->bind("workspace/didChangeWatchedFiles", &ClangdLSPServer::onFileEvent);
973 MsgHandler->bind("workspace/didChangeConfiguration", &ClangdLSPServer::onChangeConfiguration);
Jan Korousb4067012018-11-27 16:40:46 +0000974 MsgHandler->bind("textDocument/symbolInfo", &ClangdLSPServer::onSymbolInfo);
Kadir Cetinkaya86658022019-03-19 09:27:04 +0000975 MsgHandler->bind("textDocument/typeHierarchy", &ClangdLSPServer::onTypeHierarchy);
Sam McCall2c30fbc2018-10-18 12:32:04 +0000976 // clang-format on
977}
978
979ClangdLSPServer::~ClangdLSPServer() = default;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000980
Sam McCalldc8f3cf2018-10-17 07:32:05 +0000981bool ClangdLSPServer::run() {
Ilya Biryukovafb55542017-05-16 14:40:30 +0000982 // Run the Language Server loop.
Sam McCalldc8f3cf2018-10-17 07:32:05 +0000983 bool CleanExit = true;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000984 if (auto Err = Transp.loop(*MsgHandler)) {
Sam McCalldc8f3cf2018-10-17 07:32:05 +0000985 elog("Transport error: {0}", std::move(Err));
986 CleanExit = false;
987 }
Ilya Biryukovafb55542017-05-16 14:40:30 +0000988
Ilya Biryukov652364b2018-09-26 05:48:29 +0000989 // Destroy ClangdServer to ensure all worker threads finish.
990 Server.reset();
Sam McCalldc8f3cf2018-10-17 07:32:05 +0000991 return CleanExit && ShutdownRequestReceived;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000992}
993
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000994std::vector<Fix> ClangdLSPServer::getFixes(llvm::StringRef File,
Ilya Biryukov71028b82018-03-12 15:28:22 +0000995 const clangd::Diagnostic &D) {
Ilya Biryukov38d79772017-05-16 09:38:59 +0000996 std::lock_guard<std::mutex> Lock(FixItsMutex);
997 auto DiagToFixItsIter = FixItsMap.find(File);
998 if (DiagToFixItsIter == FixItsMap.end())
999 return {};
1000
1001 const auto &DiagToFixItsMap = DiagToFixItsIter->second;
1002 auto FixItsIter = DiagToFixItsMap.find(D);
1003 if (FixItsIter == DiagToFixItsMap.end())
1004 return {};
1005
1006 return FixItsIter->second;
1007}
1008
Ilya Biryukovb0826bd2019-01-03 13:37:12 +00001009bool ClangdLSPServer::shouldRunCompletion(
1010 const CompletionParams &Params) const {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001011 llvm::StringRef Trigger = Params.context.triggerCharacter;
Ilya Biryukovb0826bd2019-01-03 13:37:12 +00001012 if (Params.context.triggerKind != CompletionTriggerKind::TriggerCharacter ||
1013 (Trigger != ">" && Trigger != ":"))
1014 return true;
1015
1016 auto Code = DraftMgr.getDraft(Params.textDocument.uri.file());
1017 if (!Code)
1018 return true; // completion code will log the error for untracked doc.
1019
1020 // A completion request is sent when the user types '>' or ':', but we only
1021 // want to trigger on '->' and '::'. We check the preceeding character to make
1022 // sure it matches what we expected.
1023 // Running the lexer here would be more robust (e.g. we can detect comments
1024 // and avoid triggering completion there), but we choose to err on the side
1025 // of simplicity here.
1026 auto Offset = positionToOffset(*Code, Params.position,
1027 /*AllowColumnsBeyondLineLength=*/false);
1028 if (!Offset) {
1029 vlog("could not convert position '{0}' to offset for file '{1}'",
1030 Params.position, Params.textDocument.uri.file());
1031 return true;
1032 }
1033 if (*Offset < 2)
1034 return false;
1035
1036 if (Trigger == ">")
1037 return (*Code)[*Offset - 2] == '-'; // trigger only on '->'.
1038 if (Trigger == ":")
1039 return (*Code)[*Offset - 2] == ':'; // trigger only on '::'.
1040 assert(false && "unhandled trigger character");
1041 return true;
1042}
1043
Sam McCalla7bb0cc2018-03-12 23:22:35 +00001044void ClangdLSPServer::onDiagnosticsReady(PathRef File,
1045 std::vector<Diag> Diagnostics) {
Eric Liu4d814a92018-11-28 10:30:42 +00001046 auto URI = URIForFile::canonicalize(File, /*TUPath=*/File);
Sam McCall16e70702018-10-24 07:59:38 +00001047 std::vector<Diagnostic> LSPDiagnostics;
Ilya Biryukov38d79772017-05-16 09:38:59 +00001048 DiagnosticToReplacementMap LocalFixIts; // Temporary storage
Sam McCalla7bb0cc2018-03-12 23:22:35 +00001049 for (auto &Diag : Diagnostics) {
Sam McCall16e70702018-10-24 07:59:38 +00001050 toLSPDiags(Diag, URI, DiagOpts,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001051 [&](clangd::Diagnostic Diag, llvm::ArrayRef<Fix> Fixes) {
Sam McCall16e70702018-10-24 07:59:38 +00001052 auto &FixItsForDiagnostic = LocalFixIts[Diag];
1053 llvm::copy(Fixes, std::back_inserter(FixItsForDiagnostic));
1054 LSPDiagnostics.push_back(std::move(Diag));
1055 });
Ilya Biryukov38d79772017-05-16 09:38:59 +00001056 }
1057
1058 // Cache FixIts
1059 {
Ilya Biryukov38d79772017-05-16 09:38:59 +00001060 std::lock_guard<std::mutex> Lock(FixItsMutex);
1061 FixItsMap[File] = LocalFixIts;
1062 }
1063
Ilya Biryukov49c10712019-03-25 10:15:11 +00001064 // Send a notification to the LSP client.
1065 publishDiagnostics(URI, std::move(LSPDiagnostics));
Ilya Biryukov38d79772017-05-16 09:38:59 +00001066}
Simon Marchi9569fd52018-03-16 14:30:42 +00001067
Haojian Wub6188492018-12-20 15:39:12 +00001068void ClangdLSPServer::onFileUpdated(PathRef File, const TUStatus &Status) {
1069 if (!SupportFileStatus)
1070 return;
1071 // FIXME: we don't emit "BuildingFile" and `RunningAction`, as these
1072 // two statuses are running faster in practice, which leads the UI constantly
1073 // changing, and doesn't provide much value. We may want to emit status at a
1074 // reasonable time interval (e.g. 0.5s).
1075 if (Status.Action.S == TUAction::BuildingFile ||
1076 Status.Action.S == TUAction::RunningAction)
1077 return;
1078 notify("textDocument/clangd.fileStatus", Status.render(File));
1079}
1080
Simon Marchi9569fd52018-03-16 14:30:42 +00001081void ClangdLSPServer::reparseOpenedFiles() {
1082 for (const Path &FilePath : DraftMgr.getActiveFiles())
Ilya Biryukov652364b2018-09-26 05:48:29 +00001083 Server->addDocument(FilePath, *DraftMgr.getDraft(FilePath),
1084 WantDiagnostics::Auto);
Simon Marchi9569fd52018-03-16 14:30:42 +00001085}
Alex Lorenzf8087862018-08-01 17:39:29 +00001086
Sam McCallc008af62018-10-20 15:30:37 +00001087} // namespace clangd
1088} // namespace clang