blob: 057426fd63eb523044b6f47968e7f7fdb5df6788 [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"
Sam McCallb536a2a2017-12-19 12:23:48 +000011#include "SourceCode.h"
Sam McCall2c30fbc2018-10-18 12:32:04 +000012#include "Trace.h"
Eric Liu78ed91a72018-01-29 15:37:46 +000013#include "URI.h"
Kadir Cetinkaya689bf932018-08-24 13:09:41 +000014#include "llvm/ADT/ScopeExit.h"
Simon Marchi9569fd52018-03-16 14:30:42 +000015#include "llvm/Support/Errc.h"
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +000016#include "llvm/Support/FormatVariadic.h"
Eric Liu5740ff52018-01-31 16:26:27 +000017#include "llvm/Support/Path.h"
Sam McCall2c30fbc2018-10-18 12:32:04 +000018#include "llvm/Support/ScopedPrinter.h"
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +000019
Sam McCallc008af62018-10-20 15:30:37 +000020namespace clang {
21namespace clangd {
Ilya Biryukovafb55542017-05-16 14:40:30 +000022namespace {
Ilya Biryukovb0826bd2019-01-03 13:37:12 +000023class IgnoreCompletionError : public llvm::ErrorInfo<CancelledError> {
24public:
25 void log(llvm::raw_ostream &OS) const override {
26 OS << "ignored auto-triggered completion, preceding char did not match";
27 }
28 std::error_code convertToErrorCode() const override {
29 return std::make_error_code(std::errc::operation_canceled);
30 }
31};
Ilya Biryukovafb55542017-05-16 14:40:30 +000032
Ilya Biryukov19d75602018-11-23 15:21:19 +000033void adjustSymbolKinds(llvm::MutableArrayRef<DocumentSymbol> Syms,
34 SymbolKindBitset Kinds) {
35 for (auto &S : Syms) {
36 S.kind = adjustKindToCapability(S.kind, Kinds);
37 adjustSymbolKinds(S.children, Kinds);
38 }
39}
40
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +000041SymbolKindBitset defaultSymbolKinds() {
42 SymbolKindBitset Defaults;
43 for (size_t I = SymbolKindMin; I <= static_cast<size_t>(SymbolKind::Array);
44 ++I)
45 Defaults.set(I);
46 return Defaults;
47}
48
Kadir Cetinkaya133d46f2018-09-27 17:13:07 +000049CompletionItemKindBitset defaultCompletionItemKinds() {
50 CompletionItemKindBitset Defaults;
51 for (size_t I = CompletionItemKindMin;
52 I <= static_cast<size_t>(CompletionItemKind::Reference); ++I)
53 Defaults.set(I);
54 return Defaults;
55}
56
Ilya Biryukovafb55542017-05-16 14:40:30 +000057} // namespace
58
Sam McCall2c30fbc2018-10-18 12:32:04 +000059// MessageHandler dispatches incoming LSP messages.
60// It handles cross-cutting concerns:
61// - serializes/deserializes protocol objects to JSON
62// - logging of inbound messages
63// - cancellation handling
64// - basic call tracing
Sam McCall3d0adbe2018-10-18 14:41:50 +000065// MessageHandler ensures that initialize() is called before any other handler.
Sam McCall2c30fbc2018-10-18 12:32:04 +000066class ClangdLSPServer::MessageHandler : public Transport::MessageHandler {
67public:
68 MessageHandler(ClangdLSPServer &Server) : Server(Server) {}
69
Ilya Biryukovf2001aa2019-01-07 15:45:19 +000070 bool onNotify(llvm::StringRef Method, llvm::json::Value Params) override {
Sam McCall2c30fbc2018-10-18 12:32:04 +000071 log("<-- {0}", Method);
72 if (Method == "exit")
73 return false;
Sam McCall3d0adbe2018-10-18 14:41:50 +000074 if (!Server.Server)
75 elog("Notification {0} before initialization", Method);
76 else if (Method == "$/cancelRequest")
Sam McCall2c30fbc2018-10-18 12:32:04 +000077 onCancel(std::move(Params));
78 else if (auto Handler = Notifications.lookup(Method))
79 Handler(std::move(Params));
80 else
81 log("unhandled notification {0}", Method);
82 return true;
83 }
84
Ilya Biryukovf2001aa2019-01-07 15:45:19 +000085 bool onCall(llvm::StringRef Method, llvm::json::Value Params,
86 llvm::json::Value ID) override {
Sam McCalle2f3a732018-10-24 14:26:26 +000087 // Calls can be canceled by the client. Add cancellation context.
88 WithContext WithCancel(cancelableRequestContext(ID));
89 trace::Span Tracer(Method);
90 SPAN_ATTACH(Tracer, "Params", Params);
91 ReplyOnce Reply(ID, Method, &Server, Tracer.Args);
Sam McCall2c30fbc2018-10-18 12:32:04 +000092 log("<-- {0}({1})", Method, ID);
Sam McCall3d0adbe2018-10-18 14:41:50 +000093 if (!Server.Server && Method != "initialize") {
94 elog("Call {0} before initialization.", Method);
Ilya Biryukovf2001aa2019-01-07 15:45:19 +000095 Reply(llvm::make_error<LSPError>("server not initialized",
96 ErrorCode::ServerNotInitialized));
Sam McCall3d0adbe2018-10-18 14:41:50 +000097 } else if (auto Handler = Calls.lookup(Method))
Sam McCalle2f3a732018-10-24 14:26:26 +000098 Handler(std::move(Params), std::move(Reply));
Sam McCall2c30fbc2018-10-18 12:32:04 +000099 else
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000100 Reply(llvm::make_error<LSPError>("method not found",
101 ErrorCode::MethodNotFound));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000102 return true;
103 }
104
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000105 bool onReply(llvm::json::Value ID,
106 llvm::Expected<llvm::json::Value> Result) override {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000107 // We ignore replies, just log them.
108 if (Result)
109 log("<-- reply({0})", ID);
110 else
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000111 log("<-- reply({0}) error: {1}", ID, llvm::toString(Result.takeError()));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000112 return true;
113 }
114
115 // Bind an LSP method name to a call.
Sam McCalle2f3a732018-10-24 14:26:26 +0000116 template <typename Param, typename Result>
Sam McCall2c30fbc2018-10-18 12:32:04 +0000117 void bind(const char *Method,
Sam McCalle2f3a732018-10-24 14:26:26 +0000118 void (ClangdLSPServer::*Handler)(const Param &, Callback<Result>)) {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000119 Calls[Method] = [Method, Handler, this](llvm::json::Value RawParams,
Sam McCalle2f3a732018-10-24 14:26:26 +0000120 ReplyOnce Reply) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000121 Param P;
Sam McCalle2f3a732018-10-24 14:26:26 +0000122 if (fromJSON(RawParams, P)) {
123 (Server.*Handler)(P, std::move(Reply));
124 } else {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000125 elog("Failed to decode {0} request.", Method);
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000126 Reply(llvm::make_error<LSPError>("failed to decode request",
127 ErrorCode::InvalidRequest));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000128 }
Sam McCall2c30fbc2018-10-18 12:32:04 +0000129 };
130 }
131
132 // Bind an LSP method name to a notification.
133 template <typename Param>
134 void bind(const char *Method,
135 void (ClangdLSPServer::*Handler)(const Param &)) {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000136 Notifications[Method] = [Method, Handler,
137 this](llvm::json::Value RawParams) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000138 Param P;
139 if (!fromJSON(RawParams, P)) {
140 elog("Failed to decode {0} request.", Method);
141 return;
142 }
143 trace::Span Tracer(Method);
144 SPAN_ATTACH(Tracer, "Params", RawParams);
145 (Server.*Handler)(P);
146 };
147 }
148
149private:
Sam McCalle2f3a732018-10-24 14:26:26 +0000150 // Function object to reply to an LSP call.
151 // Each instance must be called exactly once, otherwise:
152 // - the bug is logged, and (in debug mode) an assert will fire
153 // - if there was no reply, an error reply is sent
154 // - if there were multiple replies, only the first is sent
155 class ReplyOnce {
156 std::atomic<bool> Replied = {false};
Sam McCalld7babe42018-10-24 15:18:40 +0000157 std::chrono::steady_clock::time_point Start;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000158 llvm::json::Value ID;
Sam McCalle2f3a732018-10-24 14:26:26 +0000159 std::string Method;
160 ClangdLSPServer *Server; // Null when moved-from.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000161 llvm::json::Object *TraceArgs;
Sam McCalle2f3a732018-10-24 14:26:26 +0000162
163 public:
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000164 ReplyOnce(const llvm::json::Value &ID, llvm::StringRef Method,
165 ClangdLSPServer *Server, llvm::json::Object *TraceArgs)
Sam McCalld7babe42018-10-24 15:18:40 +0000166 : Start(std::chrono::steady_clock::now()), ID(ID), Method(Method),
167 Server(Server), TraceArgs(TraceArgs) {
Sam McCalle2f3a732018-10-24 14:26:26 +0000168 assert(Server);
169 }
170 ReplyOnce(ReplyOnce &&Other)
Sam McCalld7babe42018-10-24 15:18:40 +0000171 : Replied(Other.Replied.load()), Start(Other.Start),
172 ID(std::move(Other.ID)), Method(std::move(Other.Method)),
173 Server(Other.Server), TraceArgs(Other.TraceArgs) {
Sam McCalle2f3a732018-10-24 14:26:26 +0000174 Other.Server = nullptr;
175 }
Ilya Biryukov22fa4652019-01-03 13:28:05 +0000176 ReplyOnce &operator=(ReplyOnce &&) = delete;
Sam McCalle2f3a732018-10-24 14:26:26 +0000177 ReplyOnce(const ReplyOnce &) = delete;
Ilya Biryukov22fa4652019-01-03 13:28:05 +0000178 ReplyOnce &operator=(const ReplyOnce &) = delete;
Sam McCalle2f3a732018-10-24 14:26:26 +0000179
180 ~ReplyOnce() {
181 if (Server && !Replied) {
182 elog("No reply to message {0}({1})", Method, ID);
183 assert(false && "must reply to all calls!");
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000184 (*this)(llvm::make_error<LSPError>("server failed to reply",
185 ErrorCode::InternalError));
Sam McCalle2f3a732018-10-24 14:26:26 +0000186 }
187 }
188
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000189 void operator()(llvm::Expected<llvm::json::Value> Reply) {
Sam McCalle2f3a732018-10-24 14:26:26 +0000190 assert(Server && "moved-from!");
191 if (Replied.exchange(true)) {
192 elog("Replied twice to message {0}({1})", Method, ID);
193 assert(false && "must reply to each call only once!");
194 return;
195 }
Sam McCalld7babe42018-10-24 15:18:40 +0000196 auto Duration = std::chrono::steady_clock::now() - Start;
197 if (Reply) {
198 log("--> reply:{0}({1}) {2:ms}", Method, ID, Duration);
199 if (TraceArgs)
Sam McCalle2f3a732018-10-24 14:26:26 +0000200 (*TraceArgs)["Reply"] = *Reply;
Sam McCalld7babe42018-10-24 15:18:40 +0000201 std::lock_guard<std::mutex> Lock(Server->TranspWriter);
202 Server->Transp.reply(std::move(ID), std::move(Reply));
203 } else {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000204 llvm::Error Err = Reply.takeError();
Sam McCalld7babe42018-10-24 15:18:40 +0000205 log("--> reply:{0}({1}) {2:ms}, error: {3}", Method, ID, Duration, Err);
206 if (TraceArgs)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000207 (*TraceArgs)["Error"] = llvm::to_string(Err);
Sam McCalld7babe42018-10-24 15:18:40 +0000208 std::lock_guard<std::mutex> Lock(Server->TranspWriter);
209 Server->Transp.reply(std::move(ID), std::move(Err));
Sam McCalle2f3a732018-10-24 14:26:26 +0000210 }
Sam McCalle2f3a732018-10-24 14:26:26 +0000211 }
212 };
213
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000214 llvm::StringMap<std::function<void(llvm::json::Value)>> Notifications;
215 llvm::StringMap<std::function<void(llvm::json::Value, ReplyOnce)>> Calls;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000216
217 // Method calls may be cancelled by ID, so keep track of their state.
218 // This needs a mutex: handlers may finish on a different thread, and that's
219 // when we clean up entries in the map.
220 mutable std::mutex RequestCancelersMutex;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000221 llvm::StringMap<std::pair<Canceler, /*Cookie*/ unsigned>> RequestCancelers;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000222 unsigned NextRequestCookie = 0; // To disambiguate reused IDs, see below.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000223 void onCancel(const llvm::json::Value &Params) {
224 const llvm::json::Value *ID = nullptr;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000225 if (auto *O = Params.getAsObject())
226 ID = O->get("id");
227 if (!ID) {
228 elog("Bad cancellation request: {0}", Params);
229 return;
230 }
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000231 auto StrID = llvm::to_string(*ID);
Sam McCall2c30fbc2018-10-18 12:32:04 +0000232 std::lock_guard<std::mutex> Lock(RequestCancelersMutex);
233 auto It = RequestCancelers.find(StrID);
234 if (It != RequestCancelers.end())
235 It->second.first(); // Invoke the canceler.
236 }
237 // We run cancelable requests in a context that does two things:
238 // - allows cancellation using RequestCancelers[ID]
239 // - cleans up the entry in RequestCancelers when it's no longer needed
240 // If a client reuses an ID, the last wins and the first cannot be canceled.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000241 Context cancelableRequestContext(const llvm::json::Value &ID) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000242 auto Task = cancelableTask();
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000243 auto StrID = llvm::to_string(ID); // JSON-serialize ID for map key.
Sam McCall2c30fbc2018-10-18 12:32:04 +0000244 auto Cookie = NextRequestCookie++; // No lock, only called on main thread.
245 {
246 std::lock_guard<std::mutex> Lock(RequestCancelersMutex);
247 RequestCancelers[StrID] = {std::move(Task.second), Cookie};
248 }
249 // When the request ends, we can clean up the entry we just added.
250 // The cookie lets us check that it hasn't been overwritten due to ID
251 // reuse.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000252 return Task.first.derive(llvm::make_scope_exit([this, StrID, Cookie] {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000253 std::lock_guard<std::mutex> Lock(RequestCancelersMutex);
254 auto It = RequestCancelers.find(StrID);
255 if (It != RequestCancelers.end() && It->second.second == Cookie)
256 RequestCancelers.erase(It);
257 }));
258 }
259
260 ClangdLSPServer &Server;
261};
262
263// call(), notify(), and reply() wrap the Transport, adding logging and locking.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000264void ClangdLSPServer::call(llvm::StringRef Method, llvm::json::Value Params) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000265 auto ID = NextCallID++;
266 log("--> {0}({1})", Method, ID);
267 // We currently don't handle responses, so no need to store ID anywhere.
268 std::lock_guard<std::mutex> Lock(TranspWriter);
269 Transp.call(Method, std::move(Params), ID);
270}
271
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000272void ClangdLSPServer::notify(llvm::StringRef Method, llvm::json::Value Params) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000273 log("--> {0}", Method);
274 std::lock_guard<std::mutex> Lock(TranspWriter);
275 Transp.notify(Method, std::move(Params));
276}
277
Sam McCall2c30fbc2018-10-18 12:32:04 +0000278void ClangdLSPServer::onInitialize(const InitializeParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000279 Callback<llvm::json::Value> Reply) {
Sam McCall0d9b40f2018-10-19 15:42:23 +0000280 if (Params.rootUri && *Params.rootUri)
281 ClangdServerOpts.WorkspaceRoot = Params.rootUri->file();
282 else if (Params.rootPath && !Params.rootPath->empty())
283 ClangdServerOpts.WorkspaceRoot = *Params.rootPath;
Sam McCall3d0adbe2018-10-18 14:41:50 +0000284 if (Server)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000285 return Reply(llvm::make_error<LSPError>("server already initialized",
286 ErrorCode::InvalidRequest));
Sam McCallbc904612018-10-25 04:22:52 +0000287 if (const auto &Dir = Params.initializationOptions.compilationDatabasePath)
288 CompileCommandsDir = Dir;
Sam McCallc55d09a2018-11-02 13:09:36 +0000289 if (UseDirBasedCDB)
290 BaseCDB = llvm::make_unique<DirectoryBasedGlobalCompilationDatabase>(
291 CompileCommandsDir);
Sam McCall6980edb2018-11-02 14:07:51 +0000292 CDB.emplace(BaseCDB.get(), Params.initializationOptions.fallbackFlags);
Sam McCallc55d09a2018-11-02 13:09:36 +0000293 Server.emplace(*CDB, FSProvider, static_cast<DiagnosticsConsumer &>(*this),
294 ClangdServerOpts);
Sam McCallbc904612018-10-25 04:22:52 +0000295 applyConfiguration(Params.initializationOptions.ConfigSettings);
Simon Marchi88016782018-08-01 11:28:49 +0000296
Sam McCallbf6a2fc2018-10-17 07:33:42 +0000297 CCOpts.EnableSnippets = Params.capabilities.CompletionSnippets;
298 DiagOpts.EmbedFixesInDiagnostics = Params.capabilities.DiagnosticFixes;
299 DiagOpts.SendDiagnosticCategory = Params.capabilities.DiagnosticCategory;
300 if (Params.capabilities.WorkspaceSymbolKinds)
301 SupportedSymbolKinds |= *Params.capabilities.WorkspaceSymbolKinds;
302 if (Params.capabilities.CompletionItemKinds)
303 SupportedCompletionItemKinds |= *Params.capabilities.CompletionItemKinds;
304 SupportsCodeAction = Params.capabilities.CodeActionStructure;
Ilya Biryukov19d75602018-11-23 15:21:19 +0000305 SupportsHierarchicalDocumentSymbol =
306 Params.capabilities.HierarchicalDocumentSymbol;
Haojian Wub6188492018-12-20 15:39:12 +0000307 SupportFileStatus = Params.initializationOptions.FileStatus;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000308 Reply(llvm::json::Object{
Sam McCall0930ab02017-11-07 15:49:35 +0000309 {{"capabilities",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000310 llvm::json::Object{
Simon Marchi98082622018-03-26 14:41:40 +0000311 {"textDocumentSync", (int)TextDocumentSyncKind::Incremental},
Sam McCall0930ab02017-11-07 15:49:35 +0000312 {"documentFormattingProvider", true},
313 {"documentRangeFormattingProvider", true},
314 {"documentOnTypeFormattingProvider",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000315 llvm::json::Object{
Sam McCall0930ab02017-11-07 15:49:35 +0000316 {"firstTriggerCharacter", "}"},
317 {"moreTriggerCharacter", {}},
318 }},
319 {"codeActionProvider", true},
320 {"completionProvider",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000321 llvm::json::Object{
Sam McCall0930ab02017-11-07 15:49:35 +0000322 {"resolveProvider", false},
Ilya Biryukovb0826bd2019-01-03 13:37:12 +0000323 // We do extra checks for '>' and ':' in completion to only
324 // trigger on '->' and '::'.
Sam McCall0930ab02017-11-07 15:49:35 +0000325 {"triggerCharacters", {".", ">", ":"}},
326 }},
327 {"signatureHelpProvider",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000328 llvm::json::Object{
Sam McCall0930ab02017-11-07 15:49:35 +0000329 {"triggerCharacters", {"(", ","}},
330 }},
331 {"definitionProvider", true},
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000332 {"documentHighlightProvider", true},
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000333 {"hoverProvider", true},
Haojian Wu345099c2017-11-09 11:30:04 +0000334 {"renameProvider", true},
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000335 {"documentSymbolProvider", true},
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000336 {"workspaceSymbolProvider", true},
Sam McCall1ad142f2018-09-05 11:53:07 +0000337 {"referencesProvider", true},
Sam McCall0930ab02017-11-07 15:49:35 +0000338 {"executeCommandProvider",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000339 llvm::json::Object{
Eric Liu2c190532018-05-15 15:23:53 +0000340 {"commands", {ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND}},
Sam McCall0930ab02017-11-07 15:49:35 +0000341 }},
342 }}}});
Ilya Biryukovafb55542017-05-16 14:40:30 +0000343}
344
Sam McCall2c30fbc2018-10-18 12:32:04 +0000345void ClangdLSPServer::onShutdown(const ShutdownParams &Params,
346 Callback<std::nullptr_t> Reply) {
Ilya Biryukov0d9b8a32017-10-25 08:45:41 +0000347 // Do essentially nothing, just say we're ready to exit.
348 ShutdownRequestReceived = true;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000349 Reply(nullptr);
Sam McCall8a5dded2017-10-12 13:29:58 +0000350}
Ilya Biryukovafb55542017-05-16 14:40:30 +0000351
Sam McCall422c8282018-11-26 16:00:11 +0000352// sync is a clangd extension: it blocks until all background work completes.
353// It blocks the calling thread, so no messages are processed until it returns!
354void ClangdLSPServer::onSync(const NoParams &Params,
355 Callback<std::nullptr_t> Reply) {
356 if (Server->blockUntilIdleForTest(/*TimeoutSeconds=*/60))
357 Reply(nullptr);
358 else
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000359 Reply(llvm::createStringError(llvm::inconvertibleErrorCode(),
360 "Not idle after a minute"));
Sam McCall422c8282018-11-26 16:00:11 +0000361}
362
Sam McCall2c30fbc2018-10-18 12:32:04 +0000363void ClangdLSPServer::onDocumentDidOpen(
364 const DidOpenTextDocumentParams &Params) {
Simon Marchi9569fd52018-03-16 14:30:42 +0000365 PathRef File = Params.textDocument.uri.file();
Ilya Biryukovb10ef472018-06-13 09:20:41 +0000366
Sam McCall2c30fbc2018-10-18 12:32:04 +0000367 const std::string &Contents = Params.textDocument.text;
Simon Marchi9569fd52018-03-16 14:30:42 +0000368
Simon Marchi98082622018-03-26 14:41:40 +0000369 DraftMgr.addDraft(File, Contents);
Ilya Biryukov652364b2018-09-26 05:48:29 +0000370 Server->addDocument(File, Contents, WantDiagnostics::Yes);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000371}
372
Sam McCall2c30fbc2018-10-18 12:32:04 +0000373void ClangdLSPServer::onDocumentDidChange(
374 const DidChangeTextDocumentParams &Params) {
Eric Liu51fed182018-02-22 18:40:39 +0000375 auto WantDiags = WantDiagnostics::Auto;
376 if (Params.wantDiagnostics.hasValue())
377 WantDiags = Params.wantDiagnostics.getValue() ? WantDiagnostics::Yes
378 : WantDiagnostics::No;
Simon Marchi9569fd52018-03-16 14:30:42 +0000379
380 PathRef File = Params.textDocument.uri.file();
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000381 llvm::Expected<std::string> Contents =
Simon Marchi98082622018-03-26 14:41:40 +0000382 DraftMgr.updateDraft(File, Params.contentChanges);
383 if (!Contents) {
384 // If this fails, we are most likely going to be not in sync anymore with
385 // the client. It is better to remove the draft and let further operations
386 // fail rather than giving wrong results.
387 DraftMgr.removeDraft(File);
Ilya Biryukov652364b2018-09-26 05:48:29 +0000388 Server->removeDocument(File);
Sam McCallbed58852018-07-11 10:35:11 +0000389 elog("Failed to update {0}: {1}", File, Contents.takeError());
Simon Marchi98082622018-03-26 14:41:40 +0000390 return;
391 }
Simon Marchi9569fd52018-03-16 14:30:42 +0000392
Ilya Biryukov652364b2018-09-26 05:48:29 +0000393 Server->addDocument(File, *Contents, WantDiags);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000394}
395
Sam McCall2c30fbc2018-10-18 12:32:04 +0000396void ClangdLSPServer::onFileEvent(const DidChangeWatchedFilesParams &Params) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000397 Server->onFileEvent(Params);
Marc-Andre Laperlebf114242017-10-02 18:00:37 +0000398}
399
Sam McCall2c30fbc2018-10-18 12:32:04 +0000400void ClangdLSPServer::onCommand(const ExecuteCommandParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000401 Callback<llvm::json::Value> Reply) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000402 auto ApplyEdit = [&](WorkspaceEdit WE) {
Eric Liuc5105f92018-02-16 14:15:55 +0000403 ApplyWorkspaceEditParams Edit;
404 Edit.edit = std::move(WE);
Eric Liuc5105f92018-02-16 14:15:55 +0000405 // Ideally, we would wait for the response and if there is no error, we
406 // would reply success/failure to the original RPC.
407 call("workspace/applyEdit", Edit);
408 };
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000409 if (Params.command == ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND &&
410 Params.workspaceEdit) {
411 // The flow for "apply-fix" :
412 // 1. We publish a diagnostic, including fixits
413 // 2. The user clicks on the diagnostic, the editor asks us for code actions
414 // 3. We send code actions, with the fixit embedded as context
415 // 4. The user selects the fixit, the editor asks us to apply it
416 // 5. We unwrap the changes and send them back to the editor
417 // 6. The editor applies the changes (applyEdit), and sends us a reply (but
418 // we ignore it)
419
Sam McCall2c30fbc2018-10-18 12:32:04 +0000420 Reply("Fix applied.");
Eric Liuc5105f92018-02-16 14:15:55 +0000421 ApplyEdit(*Params.workspaceEdit);
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000422 } else {
423 // We should not get here because ExecuteCommandParams would not have
424 // parsed in the first place and this handler should not be called. But if
425 // more commands are added, this will be here has a safe guard.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000426 Reply(llvm::make_error<LSPError>(
427 llvm::formatv("Unsupported command \"{0}\".", Params.command).str(),
Sam McCall2c30fbc2018-10-18 12:32:04 +0000428 ErrorCode::InvalidParams));
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000429 }
430}
431
Sam McCall2c30fbc2018-10-18 12:32:04 +0000432void ClangdLSPServer::onWorkspaceSymbol(
433 const WorkspaceSymbolParams &Params,
434 Callback<std::vector<SymbolInformation>> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000435 Server->workspaceSymbols(
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000436 Params.query, CCOpts.Limit,
Sam McCall2c30fbc2018-10-18 12:32:04 +0000437 Bind(
438 [this](decltype(Reply) Reply,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000439 llvm::Expected<std::vector<SymbolInformation>> Items) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000440 if (!Items)
441 return Reply(Items.takeError());
442 for (auto &Sym : *Items)
443 Sym.kind = adjustKindToCapability(Sym.kind, SupportedSymbolKinds);
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000444
Sam McCall2c30fbc2018-10-18 12:32:04 +0000445 Reply(std::move(*Items));
446 },
447 std::move(Reply)));
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000448}
449
Sam McCall2c30fbc2018-10-18 12:32:04 +0000450void ClangdLSPServer::onRename(const RenameParams &Params,
451 Callback<WorkspaceEdit> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000452 Path File = Params.textDocument.uri.file();
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000453 llvm::Optional<std::string> Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000454 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000455 return Reply(llvm::make_error<LSPError>(
456 "onRename called for non-added file", ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000457
Ilya Biryukov652364b2018-09-26 05:48:29 +0000458 Server->rename(
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000459 File, Params.position, Params.newName,
Sam McCall2c30fbc2018-10-18 12:32:04 +0000460 Bind(
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000461 [File, Code, Params](
462 decltype(Reply) Reply,
463 llvm::Expected<std::vector<tooling::Replacement>> Replacements) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000464 if (!Replacements)
465 return Reply(Replacements.takeError());
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000466
Sam McCall2c30fbc2018-10-18 12:32:04 +0000467 // Turn the replacements into the format specified by the Language
468 // Server Protocol. Fuse them into one big JSON array.
469 std::vector<TextEdit> Edits;
470 for (const auto &R : *Replacements)
471 Edits.push_back(replacementToEdit(*Code, R));
472 WorkspaceEdit WE;
473 WE.changes = {{Params.textDocument.uri.uri(), Edits}};
474 Reply(WE);
475 },
476 std::move(Reply)));
Haojian Wu345099c2017-11-09 11:30:04 +0000477}
478
Sam McCall2c30fbc2018-10-18 12:32:04 +0000479void ClangdLSPServer::onDocumentDidClose(
480 const DidCloseTextDocumentParams &Params) {
Simon Marchi9569fd52018-03-16 14:30:42 +0000481 PathRef File = Params.textDocument.uri.file();
482 DraftMgr.removeDraft(File);
Ilya Biryukov652364b2018-09-26 05:48:29 +0000483 Server->removeDocument(File);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000484}
485
Sam McCall4db732a2017-09-30 10:08:52 +0000486void ClangdLSPServer::onDocumentOnTypeFormatting(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000487 const DocumentOnTypeFormattingParams &Params,
488 Callback<std::vector<TextEdit>> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000489 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000490 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000491 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000492 return Reply(llvm::make_error<LSPError>(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000493 "onDocumentOnTypeFormatting called for non-added file",
494 ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000495
Ilya Biryukov652364b2018-09-26 05:48:29 +0000496 auto ReplacementsOrError = Server->formatOnType(*Code, File, Params.position);
Raoul Wols212bcf82017-12-12 20:25:06 +0000497 if (ReplacementsOrError)
Sam McCall2c30fbc2018-10-18 12:32:04 +0000498 Reply(replacementsToEdits(*Code, ReplacementsOrError.get()));
Raoul Wols212bcf82017-12-12 20:25:06 +0000499 else
Sam McCall2c30fbc2018-10-18 12:32:04 +0000500 Reply(ReplacementsOrError.takeError());
Ilya Biryukovafb55542017-05-16 14:40:30 +0000501}
502
Sam McCall4db732a2017-09-30 10:08:52 +0000503void ClangdLSPServer::onDocumentRangeFormatting(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000504 const DocumentRangeFormattingParams &Params,
505 Callback<std::vector<TextEdit>> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000506 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000507 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000508 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000509 return Reply(llvm::make_error<LSPError>(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000510 "onDocumentRangeFormatting called for non-added file",
511 ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000512
Ilya Biryukov652364b2018-09-26 05:48:29 +0000513 auto ReplacementsOrError = Server->formatRange(*Code, File, Params.range);
Raoul Wols212bcf82017-12-12 20:25:06 +0000514 if (ReplacementsOrError)
Sam McCall2c30fbc2018-10-18 12:32:04 +0000515 Reply(replacementsToEdits(*Code, ReplacementsOrError.get()));
Raoul Wols212bcf82017-12-12 20:25:06 +0000516 else
Sam McCall2c30fbc2018-10-18 12:32:04 +0000517 Reply(ReplacementsOrError.takeError());
Ilya Biryukovafb55542017-05-16 14:40:30 +0000518}
519
Sam McCall2c30fbc2018-10-18 12:32:04 +0000520void ClangdLSPServer::onDocumentFormatting(
521 const DocumentFormattingParams &Params,
522 Callback<std::vector<TextEdit>> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000523 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000524 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000525 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000526 return Reply(llvm::make_error<LSPError>(
527 "onDocumentFormatting called for non-added file",
528 ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000529
Ilya Biryukov652364b2018-09-26 05:48:29 +0000530 auto ReplacementsOrError = Server->formatFile(*Code, File);
Raoul Wols212bcf82017-12-12 20:25:06 +0000531 if (ReplacementsOrError)
Sam McCall2c30fbc2018-10-18 12:32:04 +0000532 Reply(replacementsToEdits(*Code, ReplacementsOrError.get()));
Raoul Wols212bcf82017-12-12 20:25:06 +0000533 else
Sam McCall2c30fbc2018-10-18 12:32:04 +0000534 Reply(ReplacementsOrError.takeError());
Sam McCall4db732a2017-09-30 10:08:52 +0000535}
536
Ilya Biryukov19d75602018-11-23 15:21:19 +0000537/// The functions constructs a flattened view of the DocumentSymbol hierarchy.
538/// Used by the clients that do not support the hierarchical view.
539static std::vector<SymbolInformation>
540flattenSymbolHierarchy(llvm::ArrayRef<DocumentSymbol> Symbols,
541 const URIForFile &FileURI) {
542
543 std::vector<SymbolInformation> Results;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000544 std::function<void(const DocumentSymbol &, llvm::StringRef)> Process =
545 [&](const DocumentSymbol &S, llvm::Optional<llvm::StringRef> ParentName) {
Ilya Biryukov19d75602018-11-23 15:21:19 +0000546 SymbolInformation SI;
547 SI.containerName = ParentName ? "" : *ParentName;
548 SI.name = S.name;
549 SI.kind = S.kind;
550 SI.location.range = S.range;
551 SI.location.uri = FileURI;
552
553 Results.push_back(std::move(SI));
554 std::string FullName =
555 !ParentName ? S.name : (ParentName->str() + "::" + S.name);
556 for (auto &C : S.children)
557 Process(C, /*ParentName=*/FullName);
558 };
559 for (auto &S : Symbols)
560 Process(S, /*ParentName=*/"");
561 return Results;
562}
563
564void ClangdLSPServer::onDocumentSymbol(const DocumentSymbolParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000565 Callback<llvm::json::Value> Reply) {
Ilya Biryukov19d75602018-11-23 15:21:19 +0000566 URIForFile FileURI = Params.textDocument.uri;
Ilya Biryukov652364b2018-09-26 05:48:29 +0000567 Server->documentSymbols(
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000568 Params.textDocument.uri.file(),
Sam McCall2c30fbc2018-10-18 12:32:04 +0000569 Bind(
Ilya Biryukov19d75602018-11-23 15:21:19 +0000570 [this, FileURI](decltype(Reply) Reply,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000571 llvm::Expected<std::vector<DocumentSymbol>> Items) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000572 if (!Items)
573 return Reply(Items.takeError());
Ilya Biryukov19d75602018-11-23 15:21:19 +0000574 adjustSymbolKinds(*Items, SupportedSymbolKinds);
575 if (SupportsHierarchicalDocumentSymbol)
576 return Reply(std::move(*Items));
577 else
578 return Reply(flattenSymbolHierarchy(*Items, FileURI));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000579 },
580 std::move(Reply)));
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000581}
582
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000583static llvm::Optional<Command> asCommand(const CodeAction &Action) {
Sam McCall20841d42018-10-16 16:29:41 +0000584 Command Cmd;
585 if (Action.command && Action.edit)
Sam McCallc008af62018-10-20 15:30:37 +0000586 return None; // Not representable. (We never emit these anyway).
Sam McCall20841d42018-10-16 16:29:41 +0000587 if (Action.command) {
588 Cmd = *Action.command;
589 } else if (Action.edit) {
590 Cmd.command = Command::CLANGD_APPLY_FIX_COMMAND;
591 Cmd.workspaceEdit = *Action.edit;
592 } else {
Sam McCallc008af62018-10-20 15:30:37 +0000593 return None;
Sam McCall20841d42018-10-16 16:29:41 +0000594 }
595 Cmd.title = Action.title;
596 if (Action.kind && *Action.kind == CodeAction::QUICKFIX_KIND)
597 Cmd.title = "Apply fix: " + Cmd.title;
598 return Cmd;
599}
600
Sam McCall2c30fbc2018-10-18 12:32:04 +0000601void ClangdLSPServer::onCodeAction(const CodeActionParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000602 Callback<llvm::json::Value> Reply) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000603 auto Code = DraftMgr.getDraft(Params.textDocument.uri.file());
604 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000605 return Reply(llvm::make_error<LSPError>(
606 "onCodeAction called for non-added file", ErrorCode::InvalidParams));
Sam McCall20841d42018-10-16 16:29:41 +0000607 // We provide a code action for Fixes on the specified diagnostics.
Sam McCall20841d42018-10-16 16:29:41 +0000608 std::vector<CodeAction> Actions;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000609 for (const Diagnostic &D : Params.context.diagnostics) {
Ilya Biryukov71028b82018-03-12 15:28:22 +0000610 for (auto &F : getFixes(Params.textDocument.uri.file(), D)) {
Sam McCall16e70702018-10-24 07:59:38 +0000611 Actions.push_back(toCodeAction(F, Params.textDocument.uri));
Sam McCall20841d42018-10-16 16:29:41 +0000612 Actions.back().diagnostics = {D};
Sam McCalldd0566b2017-11-06 15:40:30 +0000613 }
Ilya Biryukovafb55542017-05-16 14:40:30 +0000614 }
Sam McCall20841d42018-10-16 16:29:41 +0000615
616 if (SupportsCodeAction)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000617 Reply(llvm::json::Array(Actions));
Sam McCall20841d42018-10-16 16:29:41 +0000618 else {
619 std::vector<Command> Commands;
620 for (const auto &Action : Actions)
621 if (auto Command = asCommand(Action))
622 Commands.push_back(std::move(*Command));
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000623 Reply(llvm::json::Array(Commands));
Sam McCall20841d42018-10-16 16:29:41 +0000624 }
Ilya Biryukovafb55542017-05-16 14:40:30 +0000625}
626
Ilya Biryukovb0826bd2019-01-03 13:37:12 +0000627void ClangdLSPServer::onCompletion(const CompletionParams &Params,
Sam McCall2c30fbc2018-10-18 12:32:04 +0000628 Callback<CompletionList> Reply) {
Ilya Biryukovb0826bd2019-01-03 13:37:12 +0000629 if (!shouldRunCompletion(Params))
630 return Reply(llvm::make_error<IgnoreCompletionError>());
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000631 Server->codeComplete(Params.textDocument.uri.file(), Params.position, CCOpts,
632 Bind(
633 [this](decltype(Reply) Reply,
634 llvm::Expected<CodeCompleteResult> List) {
635 if (!List)
636 return Reply(List.takeError());
637 CompletionList LSPList;
638 LSPList.isIncomplete = List->HasMore;
639 for (const auto &R : List->Completions) {
640 CompletionItem C = R.render(CCOpts);
641 C.kind = adjustKindToCapability(
642 C.kind, SupportedCompletionItemKinds);
643 LSPList.items.push_back(std::move(C));
644 }
645 return Reply(std::move(LSPList));
646 },
647 std::move(Reply)));
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000648}
649
Sam McCall2c30fbc2018-10-18 12:32:04 +0000650void ClangdLSPServer::onSignatureHelp(const TextDocumentPositionParams &Params,
651 Callback<SignatureHelp> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000652 Server->signatureHelp(Params.textDocument.uri.file(), Params.position,
Sam McCall2c30fbc2018-10-18 12:32:04 +0000653 std::move(Reply));
Ilya Biryukov652364b2018-09-26 05:48:29 +0000654}
655
Sam McCall2c30fbc2018-10-18 12:32:04 +0000656void ClangdLSPServer::onGoToDefinition(const TextDocumentPositionParams &Params,
657 Callback<std::vector<Location>> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000658 Server->findDefinitions(Params.textDocument.uri.file(), Params.position,
Sam McCall2c30fbc2018-10-18 12:32:04 +0000659 std::move(Reply));
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000660}
661
Sam McCall2c30fbc2018-10-18 12:32:04 +0000662void ClangdLSPServer::onSwitchSourceHeader(const TextDocumentIdentifier &Params,
663 Callback<std::string> Reply) {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000664 llvm::Optional<Path> Result = Server->switchSourceHeader(Params.uri.file());
Sam McCall2c30fbc2018-10-18 12:32:04 +0000665 Reply(Result ? URI::createFile(*Result).toString() : "");
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000666}
667
Sam McCall2c30fbc2018-10-18 12:32:04 +0000668void ClangdLSPServer::onDocumentHighlight(
669 const TextDocumentPositionParams &Params,
670 Callback<std::vector<DocumentHighlight>> Reply) {
671 Server->findDocumentHighlights(Params.textDocument.uri.file(),
672 Params.position, std::move(Reply));
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000673}
674
Sam McCall2c30fbc2018-10-18 12:32:04 +0000675void ClangdLSPServer::onHover(const TextDocumentPositionParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000676 Callback<llvm::Optional<Hover>> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000677 Server->findHover(Params.textDocument.uri.file(), Params.position,
Sam McCall2c30fbc2018-10-18 12:32:04 +0000678 std::move(Reply));
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000679}
680
Simon Marchi88016782018-08-01 11:28:49 +0000681void ClangdLSPServer::applyConfiguration(
Sam McCallbc904612018-10-25 04:22:52 +0000682 const ConfigurationSettings &Settings) {
Simon Marchiabeed662018-10-16 15:55:03 +0000683 // Per-file update to the compilation database.
Sam McCallbc904612018-10-25 04:22:52 +0000684 bool ShouldReparseOpenFiles = false;
685 for (auto &Entry : Settings.compilationDatabaseChanges) {
686 /// The opened files need to be reparsed only when some existing
687 /// entries are changed.
688 PathRef File = Entry.first;
Sam McCallc55d09a2018-11-02 13:09:36 +0000689 auto Old = CDB->getCompileCommand(File);
690 auto New =
691 tooling::CompileCommand(std::move(Entry.second.workingDirectory), File,
692 std::move(Entry.second.compilationCommand),
693 /*Output=*/"");
Sam McCall6980edb2018-11-02 14:07:51 +0000694 if (Old != New) {
Sam McCallc55d09a2018-11-02 13:09:36 +0000695 CDB->setCompileCommand(File, std::move(New));
Sam McCall6980edb2018-11-02 14:07:51 +0000696 ShouldReparseOpenFiles = true;
697 }
Alex Lorenzf8087862018-08-01 17:39:29 +0000698 }
Sam McCallbc904612018-10-25 04:22:52 +0000699 if (ShouldReparseOpenFiles)
700 reparseOpenedFiles();
Simon Marchi5178f922018-02-22 14:00:39 +0000701}
702
Simon Marchi88016782018-08-01 11:28:49 +0000703// FIXME: This function needs to be properly tested.
704void ClangdLSPServer::onChangeConfiguration(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000705 const DidChangeConfigurationParams &Params) {
Simon Marchi88016782018-08-01 11:28:49 +0000706 applyConfiguration(Params.settings);
707}
708
Sam McCall2c30fbc2018-10-18 12:32:04 +0000709void ClangdLSPServer::onReference(const ReferenceParams &Params,
710 Callback<std::vector<Location>> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000711 Server->findReferences(Params.textDocument.uri.file(), Params.position,
Haojian Wuc34f0222019-01-14 18:11:09 +0000712 CCOpts.Limit, std::move(Reply));
Sam McCall1ad142f2018-09-05 11:53:07 +0000713}
714
Jan Korousb4067012018-11-27 16:40:46 +0000715void ClangdLSPServer::onSymbolInfo(const TextDocumentPositionParams &Params,
716 Callback<std::vector<SymbolDetails>> Reply) {
717 Server->symbolInfo(Params.textDocument.uri.file(), Params.position,
718 std::move(Reply));
719}
720
Sam McCalldc8f3cf2018-10-17 07:32:05 +0000721ClangdLSPServer::ClangdLSPServer(class Transport &Transp,
Sam McCalladccab62017-11-23 16:58:22 +0000722 const clangd::CodeCompleteOptions &CCOpts,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000723 llvm::Optional<Path> CompileCommandsDir,
Sam McCallc55d09a2018-11-02 13:09:36 +0000724 bool UseDirBasedCDB,
Sam McCall7363a2f2018-03-05 17:28:54 +0000725 const ClangdServer::Options &Opts)
Sam McCalld1c9d112018-10-23 14:19:54 +0000726 : Transp(Transp), MsgHandler(new MessageHandler(*this)), CCOpts(CCOpts),
727 SupportedSymbolKinds(defaultSymbolKinds()),
Kadir Cetinkaya133d46f2018-09-27 17:13:07 +0000728 SupportedCompletionItemKinds(defaultCompletionItemKinds()),
Sam McCallc55d09a2018-11-02 13:09:36 +0000729 UseDirBasedCDB(UseDirBasedCDB),
Sam McCall4b86bb02018-10-25 02:22:53 +0000730 CompileCommandsDir(std::move(CompileCommandsDir)),
731 ClangdServerOpts(Opts) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000732 // clang-format off
733 MsgHandler->bind("initialize", &ClangdLSPServer::onInitialize);
734 MsgHandler->bind("shutdown", &ClangdLSPServer::onShutdown);
Sam McCall422c8282018-11-26 16:00:11 +0000735 MsgHandler->bind("sync", &ClangdLSPServer::onSync);
Sam McCall2c30fbc2018-10-18 12:32:04 +0000736 MsgHandler->bind("textDocument/rangeFormatting", &ClangdLSPServer::onDocumentRangeFormatting);
737 MsgHandler->bind("textDocument/onTypeFormatting", &ClangdLSPServer::onDocumentOnTypeFormatting);
738 MsgHandler->bind("textDocument/formatting", &ClangdLSPServer::onDocumentFormatting);
739 MsgHandler->bind("textDocument/codeAction", &ClangdLSPServer::onCodeAction);
740 MsgHandler->bind("textDocument/completion", &ClangdLSPServer::onCompletion);
741 MsgHandler->bind("textDocument/signatureHelp", &ClangdLSPServer::onSignatureHelp);
742 MsgHandler->bind("textDocument/definition", &ClangdLSPServer::onGoToDefinition);
743 MsgHandler->bind("textDocument/references", &ClangdLSPServer::onReference);
744 MsgHandler->bind("textDocument/switchSourceHeader", &ClangdLSPServer::onSwitchSourceHeader);
745 MsgHandler->bind("textDocument/rename", &ClangdLSPServer::onRename);
746 MsgHandler->bind("textDocument/hover", &ClangdLSPServer::onHover);
747 MsgHandler->bind("textDocument/documentSymbol", &ClangdLSPServer::onDocumentSymbol);
748 MsgHandler->bind("workspace/executeCommand", &ClangdLSPServer::onCommand);
749 MsgHandler->bind("textDocument/documentHighlight", &ClangdLSPServer::onDocumentHighlight);
750 MsgHandler->bind("workspace/symbol", &ClangdLSPServer::onWorkspaceSymbol);
751 MsgHandler->bind("textDocument/didOpen", &ClangdLSPServer::onDocumentDidOpen);
752 MsgHandler->bind("textDocument/didClose", &ClangdLSPServer::onDocumentDidClose);
753 MsgHandler->bind("textDocument/didChange", &ClangdLSPServer::onDocumentDidChange);
754 MsgHandler->bind("workspace/didChangeWatchedFiles", &ClangdLSPServer::onFileEvent);
755 MsgHandler->bind("workspace/didChangeConfiguration", &ClangdLSPServer::onChangeConfiguration);
Jan Korousb4067012018-11-27 16:40:46 +0000756 MsgHandler->bind("textDocument/symbolInfo", &ClangdLSPServer::onSymbolInfo);
Sam McCall2c30fbc2018-10-18 12:32:04 +0000757 // clang-format on
758}
759
760ClangdLSPServer::~ClangdLSPServer() = default;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000761
Sam McCalldc8f3cf2018-10-17 07:32:05 +0000762bool ClangdLSPServer::run() {
Ilya Biryukovafb55542017-05-16 14:40:30 +0000763 // Run the Language Server loop.
Sam McCalldc8f3cf2018-10-17 07:32:05 +0000764 bool CleanExit = true;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000765 if (auto Err = Transp.loop(*MsgHandler)) {
Sam McCalldc8f3cf2018-10-17 07:32:05 +0000766 elog("Transport error: {0}", std::move(Err));
767 CleanExit = false;
768 }
Ilya Biryukovafb55542017-05-16 14:40:30 +0000769
Ilya Biryukov652364b2018-09-26 05:48:29 +0000770 // Destroy ClangdServer to ensure all worker threads finish.
771 Server.reset();
Sam McCalldc8f3cf2018-10-17 07:32:05 +0000772 return CleanExit && ShutdownRequestReceived;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000773}
774
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000775std::vector<Fix> ClangdLSPServer::getFixes(llvm::StringRef File,
Ilya Biryukov71028b82018-03-12 15:28:22 +0000776 const clangd::Diagnostic &D) {
Ilya Biryukov38d79772017-05-16 09:38:59 +0000777 std::lock_guard<std::mutex> Lock(FixItsMutex);
778 auto DiagToFixItsIter = FixItsMap.find(File);
779 if (DiagToFixItsIter == FixItsMap.end())
780 return {};
781
782 const auto &DiagToFixItsMap = DiagToFixItsIter->second;
783 auto FixItsIter = DiagToFixItsMap.find(D);
784 if (FixItsIter == DiagToFixItsMap.end())
785 return {};
786
787 return FixItsIter->second;
788}
789
Ilya Biryukovb0826bd2019-01-03 13:37:12 +0000790bool ClangdLSPServer::shouldRunCompletion(
791 const CompletionParams &Params) const {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000792 llvm::StringRef Trigger = Params.context.triggerCharacter;
Ilya Biryukovb0826bd2019-01-03 13:37:12 +0000793 if (Params.context.triggerKind != CompletionTriggerKind::TriggerCharacter ||
794 (Trigger != ">" && Trigger != ":"))
795 return true;
796
797 auto Code = DraftMgr.getDraft(Params.textDocument.uri.file());
798 if (!Code)
799 return true; // completion code will log the error for untracked doc.
800
801 // A completion request is sent when the user types '>' or ':', but we only
802 // want to trigger on '->' and '::'. We check the preceeding character to make
803 // sure it matches what we expected.
804 // Running the lexer here would be more robust (e.g. we can detect comments
805 // and avoid triggering completion there), but we choose to err on the side
806 // of simplicity here.
807 auto Offset = positionToOffset(*Code, Params.position,
808 /*AllowColumnsBeyondLineLength=*/false);
809 if (!Offset) {
810 vlog("could not convert position '{0}' to offset for file '{1}'",
811 Params.position, Params.textDocument.uri.file());
812 return true;
813 }
814 if (*Offset < 2)
815 return false;
816
817 if (Trigger == ">")
818 return (*Code)[*Offset - 2] == '-'; // trigger only on '->'.
819 if (Trigger == ":")
820 return (*Code)[*Offset - 2] == ':'; // trigger only on '::'.
821 assert(false && "unhandled trigger character");
822 return true;
823}
824
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000825void ClangdLSPServer::onDiagnosticsReady(PathRef File,
826 std::vector<Diag> Diagnostics) {
Eric Liu4d814a92018-11-28 10:30:42 +0000827 auto URI = URIForFile::canonicalize(File, /*TUPath=*/File);
Sam McCall16e70702018-10-24 07:59:38 +0000828 std::vector<Diagnostic> LSPDiagnostics;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000829 DiagnosticToReplacementMap LocalFixIts; // Temporary storage
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000830 for (auto &Diag : Diagnostics) {
Sam McCall16e70702018-10-24 07:59:38 +0000831 toLSPDiags(Diag, URI, DiagOpts,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000832 [&](clangd::Diagnostic Diag, llvm::ArrayRef<Fix> Fixes) {
Sam McCall16e70702018-10-24 07:59:38 +0000833 auto &FixItsForDiagnostic = LocalFixIts[Diag];
834 llvm::copy(Fixes, std::back_inserter(FixItsForDiagnostic));
835 LSPDiagnostics.push_back(std::move(Diag));
836 });
Ilya Biryukov38d79772017-05-16 09:38:59 +0000837 }
838
839 // Cache FixIts
840 {
841 // FIXME(ibiryukov): should be deleted when documents are removed
842 std::lock_guard<std::mutex> Lock(FixItsMutex);
843 FixItsMap[File] = LocalFixIts;
844 }
845
846 // Publish diagnostics.
Sam McCall2c30fbc2018-10-18 12:32:04 +0000847 notify("textDocument/publishDiagnostics",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000848 llvm::json::Object{
Sam McCall16e70702018-10-24 07:59:38 +0000849 {"uri", URI},
850 {"diagnostics", std::move(LSPDiagnostics)},
Sam McCall2c30fbc2018-10-18 12:32:04 +0000851 });
Ilya Biryukov38d79772017-05-16 09:38:59 +0000852}
Simon Marchi9569fd52018-03-16 14:30:42 +0000853
Haojian Wub6188492018-12-20 15:39:12 +0000854void ClangdLSPServer::onFileUpdated(PathRef File, const TUStatus &Status) {
855 if (!SupportFileStatus)
856 return;
857 // FIXME: we don't emit "BuildingFile" and `RunningAction`, as these
858 // two statuses are running faster in practice, which leads the UI constantly
859 // changing, and doesn't provide much value. We may want to emit status at a
860 // reasonable time interval (e.g. 0.5s).
861 if (Status.Action.S == TUAction::BuildingFile ||
862 Status.Action.S == TUAction::RunningAction)
863 return;
864 notify("textDocument/clangd.fileStatus", Status.render(File));
865}
866
Simon Marchi9569fd52018-03-16 14:30:42 +0000867void ClangdLSPServer::reparseOpenedFiles() {
868 for (const Path &FilePath : DraftMgr.getActiveFiles())
Ilya Biryukov652364b2018-09-26 05:48:29 +0000869 Server->addDocument(FilePath, *DraftMgr.getDraft(FilePath),
870 WantDiagnostics::Auto);
Simon Marchi9569fd52018-03-16 14:30:42 +0000871}
Alex Lorenzf8087862018-08-01 17:39:29 +0000872
Sam McCallc008af62018-10-20 15:30:37 +0000873} // namespace clangd
874} // namespace clang