blob: e90ee916184bc78ad0c81d23ad6816a5fd8e79c5 [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);
Kadir Cetinkayabe6b35d2019-01-22 09:10:20 +0000292 CDB.emplace(BaseCDB.get(), Params.initializationOptions.fallbackFlags,
293 ClangdServerOpts.ResourceDir);
Sam McCallc55d09a2018-11-02 13:09:36 +0000294 Server.emplace(*CDB, FSProvider, static_cast<DiagnosticsConsumer &>(*this),
295 ClangdServerOpts);
Sam McCallbc904612018-10-25 04:22:52 +0000296 applyConfiguration(Params.initializationOptions.ConfigSettings);
Simon Marchi88016782018-08-01 11:28:49 +0000297
Sam McCallbf6a2fc2018-10-17 07:33:42 +0000298 CCOpts.EnableSnippets = Params.capabilities.CompletionSnippets;
299 DiagOpts.EmbedFixesInDiagnostics = Params.capabilities.DiagnosticFixes;
300 DiagOpts.SendDiagnosticCategory = Params.capabilities.DiagnosticCategory;
301 if (Params.capabilities.WorkspaceSymbolKinds)
302 SupportedSymbolKinds |= *Params.capabilities.WorkspaceSymbolKinds;
303 if (Params.capabilities.CompletionItemKinds)
304 SupportedCompletionItemKinds |= *Params.capabilities.CompletionItemKinds;
305 SupportsCodeAction = Params.capabilities.CodeActionStructure;
Ilya Biryukov19d75602018-11-23 15:21:19 +0000306 SupportsHierarchicalDocumentSymbol =
307 Params.capabilities.HierarchicalDocumentSymbol;
Haojian Wub6188492018-12-20 15:39:12 +0000308 SupportFileStatus = Params.initializationOptions.FileStatus;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000309 Reply(llvm::json::Object{
Sam McCall0930ab02017-11-07 15:49:35 +0000310 {{"capabilities",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000311 llvm::json::Object{
Simon Marchi98082622018-03-26 14:41:40 +0000312 {"textDocumentSync", (int)TextDocumentSyncKind::Incremental},
Sam McCall0930ab02017-11-07 15:49:35 +0000313 {"documentFormattingProvider", true},
314 {"documentRangeFormattingProvider", true},
315 {"documentOnTypeFormattingProvider",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000316 llvm::json::Object{
Sam McCall0930ab02017-11-07 15:49:35 +0000317 {"firstTriggerCharacter", "}"},
318 {"moreTriggerCharacter", {}},
319 }},
320 {"codeActionProvider", true},
321 {"completionProvider",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000322 llvm::json::Object{
Sam McCall0930ab02017-11-07 15:49:35 +0000323 {"resolveProvider", false},
Ilya Biryukovb0826bd2019-01-03 13:37:12 +0000324 // We do extra checks for '>' and ':' in completion to only
325 // trigger on '->' and '::'.
Sam McCall0930ab02017-11-07 15:49:35 +0000326 {"triggerCharacters", {".", ">", ":"}},
327 }},
328 {"signatureHelpProvider",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000329 llvm::json::Object{
Sam McCall0930ab02017-11-07 15:49:35 +0000330 {"triggerCharacters", {"(", ","}},
331 }},
332 {"definitionProvider", true},
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000333 {"documentHighlightProvider", true},
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000334 {"hoverProvider", true},
Haojian Wu345099c2017-11-09 11:30:04 +0000335 {"renameProvider", true},
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000336 {"documentSymbolProvider", true},
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000337 {"workspaceSymbolProvider", true},
Sam McCall1ad142f2018-09-05 11:53:07 +0000338 {"referencesProvider", true},
Sam McCall0930ab02017-11-07 15:49:35 +0000339 {"executeCommandProvider",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000340 llvm::json::Object{
Eric Liu2c190532018-05-15 15:23:53 +0000341 {"commands", {ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND}},
Sam McCall0930ab02017-11-07 15:49:35 +0000342 }},
343 }}}});
Ilya Biryukovafb55542017-05-16 14:40:30 +0000344}
345
Sam McCall2c30fbc2018-10-18 12:32:04 +0000346void ClangdLSPServer::onShutdown(const ShutdownParams &Params,
347 Callback<std::nullptr_t> Reply) {
Ilya Biryukov0d9b8a32017-10-25 08:45:41 +0000348 // Do essentially nothing, just say we're ready to exit.
349 ShutdownRequestReceived = true;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000350 Reply(nullptr);
Sam McCall8a5dded2017-10-12 13:29:58 +0000351}
Ilya Biryukovafb55542017-05-16 14:40:30 +0000352
Sam McCall422c8282018-11-26 16:00:11 +0000353// sync is a clangd extension: it blocks until all background work completes.
354// It blocks the calling thread, so no messages are processed until it returns!
355void ClangdLSPServer::onSync(const NoParams &Params,
356 Callback<std::nullptr_t> Reply) {
357 if (Server->blockUntilIdleForTest(/*TimeoutSeconds=*/60))
358 Reply(nullptr);
359 else
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000360 Reply(llvm::createStringError(llvm::inconvertibleErrorCode(),
361 "Not idle after a minute"));
Sam McCall422c8282018-11-26 16:00:11 +0000362}
363
Sam McCall2c30fbc2018-10-18 12:32:04 +0000364void ClangdLSPServer::onDocumentDidOpen(
365 const DidOpenTextDocumentParams &Params) {
Simon Marchi9569fd52018-03-16 14:30:42 +0000366 PathRef File = Params.textDocument.uri.file();
Ilya Biryukovb10ef472018-06-13 09:20:41 +0000367
Sam McCall2c30fbc2018-10-18 12:32:04 +0000368 const std::string &Contents = Params.textDocument.text;
Simon Marchi9569fd52018-03-16 14:30:42 +0000369
Simon Marchi98082622018-03-26 14:41:40 +0000370 DraftMgr.addDraft(File, Contents);
Ilya Biryukov652364b2018-09-26 05:48:29 +0000371 Server->addDocument(File, Contents, WantDiagnostics::Yes);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000372}
373
Sam McCall2c30fbc2018-10-18 12:32:04 +0000374void ClangdLSPServer::onDocumentDidChange(
375 const DidChangeTextDocumentParams &Params) {
Eric Liu51fed182018-02-22 18:40:39 +0000376 auto WantDiags = WantDiagnostics::Auto;
377 if (Params.wantDiagnostics.hasValue())
378 WantDiags = Params.wantDiagnostics.getValue() ? WantDiagnostics::Yes
379 : WantDiagnostics::No;
Simon Marchi9569fd52018-03-16 14:30:42 +0000380
381 PathRef File = Params.textDocument.uri.file();
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000382 llvm::Expected<std::string> Contents =
Simon Marchi98082622018-03-26 14:41:40 +0000383 DraftMgr.updateDraft(File, Params.contentChanges);
384 if (!Contents) {
385 // If this fails, we are most likely going to be not in sync anymore with
386 // the client. It is better to remove the draft and let further operations
387 // fail rather than giving wrong results.
388 DraftMgr.removeDraft(File);
Ilya Biryukov652364b2018-09-26 05:48:29 +0000389 Server->removeDocument(File);
Sam McCallbed58852018-07-11 10:35:11 +0000390 elog("Failed to update {0}: {1}", File, Contents.takeError());
Simon Marchi98082622018-03-26 14:41:40 +0000391 return;
392 }
Simon Marchi9569fd52018-03-16 14:30:42 +0000393
Ilya Biryukov652364b2018-09-26 05:48:29 +0000394 Server->addDocument(File, *Contents, WantDiags);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000395}
396
Sam McCall2c30fbc2018-10-18 12:32:04 +0000397void ClangdLSPServer::onFileEvent(const DidChangeWatchedFilesParams &Params) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000398 Server->onFileEvent(Params);
Marc-Andre Laperlebf114242017-10-02 18:00:37 +0000399}
400
Sam McCall2c30fbc2018-10-18 12:32:04 +0000401void ClangdLSPServer::onCommand(const ExecuteCommandParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000402 Callback<llvm::json::Value> Reply) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000403 auto ApplyEdit = [&](WorkspaceEdit WE) {
Eric Liuc5105f92018-02-16 14:15:55 +0000404 ApplyWorkspaceEditParams Edit;
405 Edit.edit = std::move(WE);
Eric Liuc5105f92018-02-16 14:15:55 +0000406 // Ideally, we would wait for the response and if there is no error, we
407 // would reply success/failure to the original RPC.
408 call("workspace/applyEdit", Edit);
409 };
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000410 if (Params.command == ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND &&
411 Params.workspaceEdit) {
412 // The flow for "apply-fix" :
413 // 1. We publish a diagnostic, including fixits
414 // 2. The user clicks on the diagnostic, the editor asks us for code actions
415 // 3. We send code actions, with the fixit embedded as context
416 // 4. The user selects the fixit, the editor asks us to apply it
417 // 5. We unwrap the changes and send them back to the editor
418 // 6. The editor applies the changes (applyEdit), and sends us a reply (but
419 // we ignore it)
420
Sam McCall2c30fbc2018-10-18 12:32:04 +0000421 Reply("Fix applied.");
Eric Liuc5105f92018-02-16 14:15:55 +0000422 ApplyEdit(*Params.workspaceEdit);
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000423 } else {
424 // We should not get here because ExecuteCommandParams would not have
425 // parsed in the first place and this handler should not be called. But if
426 // more commands are added, this will be here has a safe guard.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000427 Reply(llvm::make_error<LSPError>(
428 llvm::formatv("Unsupported command \"{0}\".", Params.command).str(),
Sam McCall2c30fbc2018-10-18 12:32:04 +0000429 ErrorCode::InvalidParams));
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000430 }
431}
432
Sam McCall2c30fbc2018-10-18 12:32:04 +0000433void ClangdLSPServer::onWorkspaceSymbol(
434 const WorkspaceSymbolParams &Params,
435 Callback<std::vector<SymbolInformation>> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000436 Server->workspaceSymbols(
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000437 Params.query, CCOpts.Limit,
Sam McCall2c30fbc2018-10-18 12:32:04 +0000438 Bind(
439 [this](decltype(Reply) Reply,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000440 llvm::Expected<std::vector<SymbolInformation>> Items) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000441 if (!Items)
442 return Reply(Items.takeError());
443 for (auto &Sym : *Items)
444 Sym.kind = adjustKindToCapability(Sym.kind, SupportedSymbolKinds);
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000445
Sam McCall2c30fbc2018-10-18 12:32:04 +0000446 Reply(std::move(*Items));
447 },
448 std::move(Reply)));
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000449}
450
Sam McCall2c30fbc2018-10-18 12:32:04 +0000451void ClangdLSPServer::onRename(const RenameParams &Params,
452 Callback<WorkspaceEdit> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000453 Path File = Params.textDocument.uri.file();
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000454 llvm::Optional<std::string> Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000455 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000456 return Reply(llvm::make_error<LSPError>(
457 "onRename called for non-added file", ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000458
Ilya Biryukov652364b2018-09-26 05:48:29 +0000459 Server->rename(
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000460 File, Params.position, Params.newName,
Sam McCall2c30fbc2018-10-18 12:32:04 +0000461 Bind(
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000462 [File, Code, Params](
463 decltype(Reply) Reply,
464 llvm::Expected<std::vector<tooling::Replacement>> Replacements) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000465 if (!Replacements)
466 return Reply(Replacements.takeError());
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000467
Sam McCall2c30fbc2018-10-18 12:32:04 +0000468 // Turn the replacements into the format specified by the Language
469 // Server Protocol. Fuse them into one big JSON array.
470 std::vector<TextEdit> Edits;
471 for (const auto &R : *Replacements)
472 Edits.push_back(replacementToEdit(*Code, R));
473 WorkspaceEdit WE;
474 WE.changes = {{Params.textDocument.uri.uri(), Edits}};
475 Reply(WE);
476 },
477 std::move(Reply)));
Haojian Wu345099c2017-11-09 11:30:04 +0000478}
479
Sam McCall2c30fbc2018-10-18 12:32:04 +0000480void ClangdLSPServer::onDocumentDidClose(
481 const DidCloseTextDocumentParams &Params) {
Simon Marchi9569fd52018-03-16 14:30:42 +0000482 PathRef File = Params.textDocument.uri.file();
483 DraftMgr.removeDraft(File);
Ilya Biryukov652364b2018-09-26 05:48:29 +0000484 Server->removeDocument(File);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000485}
486
Sam McCall4db732a2017-09-30 10:08:52 +0000487void ClangdLSPServer::onDocumentOnTypeFormatting(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000488 const DocumentOnTypeFormattingParams &Params,
489 Callback<std::vector<TextEdit>> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000490 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000491 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000492 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000493 return Reply(llvm::make_error<LSPError>(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000494 "onDocumentOnTypeFormatting called for non-added file",
495 ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000496
Ilya Biryukov652364b2018-09-26 05:48:29 +0000497 auto ReplacementsOrError = Server->formatOnType(*Code, File, Params.position);
Raoul Wols212bcf82017-12-12 20:25:06 +0000498 if (ReplacementsOrError)
Sam McCall2c30fbc2018-10-18 12:32:04 +0000499 Reply(replacementsToEdits(*Code, ReplacementsOrError.get()));
Raoul Wols212bcf82017-12-12 20:25:06 +0000500 else
Sam McCall2c30fbc2018-10-18 12:32:04 +0000501 Reply(ReplacementsOrError.takeError());
Ilya Biryukovafb55542017-05-16 14:40:30 +0000502}
503
Sam McCall4db732a2017-09-30 10:08:52 +0000504void ClangdLSPServer::onDocumentRangeFormatting(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000505 const DocumentRangeFormattingParams &Params,
506 Callback<std::vector<TextEdit>> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000507 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000508 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000509 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000510 return Reply(llvm::make_error<LSPError>(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000511 "onDocumentRangeFormatting called for non-added file",
512 ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000513
Ilya Biryukov652364b2018-09-26 05:48:29 +0000514 auto ReplacementsOrError = Server->formatRange(*Code, File, Params.range);
Raoul Wols212bcf82017-12-12 20:25:06 +0000515 if (ReplacementsOrError)
Sam McCall2c30fbc2018-10-18 12:32:04 +0000516 Reply(replacementsToEdits(*Code, ReplacementsOrError.get()));
Raoul Wols212bcf82017-12-12 20:25:06 +0000517 else
Sam McCall2c30fbc2018-10-18 12:32:04 +0000518 Reply(ReplacementsOrError.takeError());
Ilya Biryukovafb55542017-05-16 14:40:30 +0000519}
520
Sam McCall2c30fbc2018-10-18 12:32:04 +0000521void ClangdLSPServer::onDocumentFormatting(
522 const DocumentFormattingParams &Params,
523 Callback<std::vector<TextEdit>> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000524 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000525 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000526 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000527 return Reply(llvm::make_error<LSPError>(
528 "onDocumentFormatting called for non-added file",
529 ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000530
Ilya Biryukov652364b2018-09-26 05:48:29 +0000531 auto ReplacementsOrError = Server->formatFile(*Code, File);
Raoul Wols212bcf82017-12-12 20:25:06 +0000532 if (ReplacementsOrError)
Sam McCall2c30fbc2018-10-18 12:32:04 +0000533 Reply(replacementsToEdits(*Code, ReplacementsOrError.get()));
Raoul Wols212bcf82017-12-12 20:25:06 +0000534 else
Sam McCall2c30fbc2018-10-18 12:32:04 +0000535 Reply(ReplacementsOrError.takeError());
Sam McCall4db732a2017-09-30 10:08:52 +0000536}
537
Ilya Biryukov19d75602018-11-23 15:21:19 +0000538/// The functions constructs a flattened view of the DocumentSymbol hierarchy.
539/// Used by the clients that do not support the hierarchical view.
540static std::vector<SymbolInformation>
541flattenSymbolHierarchy(llvm::ArrayRef<DocumentSymbol> Symbols,
542 const URIForFile &FileURI) {
543
544 std::vector<SymbolInformation> Results;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000545 std::function<void(const DocumentSymbol &, llvm::StringRef)> Process =
546 [&](const DocumentSymbol &S, llvm::Optional<llvm::StringRef> ParentName) {
Ilya Biryukov19d75602018-11-23 15:21:19 +0000547 SymbolInformation SI;
548 SI.containerName = ParentName ? "" : *ParentName;
549 SI.name = S.name;
550 SI.kind = S.kind;
551 SI.location.range = S.range;
552 SI.location.uri = FileURI;
553
554 Results.push_back(std::move(SI));
555 std::string FullName =
556 !ParentName ? S.name : (ParentName->str() + "::" + S.name);
557 for (auto &C : S.children)
558 Process(C, /*ParentName=*/FullName);
559 };
560 for (auto &S : Symbols)
561 Process(S, /*ParentName=*/"");
562 return Results;
563}
564
565void ClangdLSPServer::onDocumentSymbol(const DocumentSymbolParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000566 Callback<llvm::json::Value> Reply) {
Ilya Biryukov19d75602018-11-23 15:21:19 +0000567 URIForFile FileURI = Params.textDocument.uri;
Ilya Biryukov652364b2018-09-26 05:48:29 +0000568 Server->documentSymbols(
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000569 Params.textDocument.uri.file(),
Sam McCall2c30fbc2018-10-18 12:32:04 +0000570 Bind(
Ilya Biryukov19d75602018-11-23 15:21:19 +0000571 [this, FileURI](decltype(Reply) Reply,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000572 llvm::Expected<std::vector<DocumentSymbol>> Items) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000573 if (!Items)
574 return Reply(Items.takeError());
Ilya Biryukov19d75602018-11-23 15:21:19 +0000575 adjustSymbolKinds(*Items, SupportedSymbolKinds);
576 if (SupportsHierarchicalDocumentSymbol)
577 return Reply(std::move(*Items));
578 else
579 return Reply(flattenSymbolHierarchy(*Items, FileURI));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000580 },
581 std::move(Reply)));
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000582}
583
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000584static llvm::Optional<Command> asCommand(const CodeAction &Action) {
Sam McCall20841d42018-10-16 16:29:41 +0000585 Command Cmd;
586 if (Action.command && Action.edit)
Sam McCallc008af62018-10-20 15:30:37 +0000587 return None; // Not representable. (We never emit these anyway).
Sam McCall20841d42018-10-16 16:29:41 +0000588 if (Action.command) {
589 Cmd = *Action.command;
590 } else if (Action.edit) {
591 Cmd.command = Command::CLANGD_APPLY_FIX_COMMAND;
592 Cmd.workspaceEdit = *Action.edit;
593 } else {
Sam McCallc008af62018-10-20 15:30:37 +0000594 return None;
Sam McCall20841d42018-10-16 16:29:41 +0000595 }
596 Cmd.title = Action.title;
597 if (Action.kind && *Action.kind == CodeAction::QUICKFIX_KIND)
598 Cmd.title = "Apply fix: " + Cmd.title;
599 return Cmd;
600}
601
Sam McCall2c30fbc2018-10-18 12:32:04 +0000602void ClangdLSPServer::onCodeAction(const CodeActionParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000603 Callback<llvm::json::Value> Reply) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000604 auto Code = DraftMgr.getDraft(Params.textDocument.uri.file());
605 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000606 return Reply(llvm::make_error<LSPError>(
607 "onCodeAction called for non-added file", ErrorCode::InvalidParams));
Sam McCall20841d42018-10-16 16:29:41 +0000608 // We provide a code action for Fixes on the specified diagnostics.
Sam McCall20841d42018-10-16 16:29:41 +0000609 std::vector<CodeAction> Actions;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000610 for (const Diagnostic &D : Params.context.diagnostics) {
Ilya Biryukov71028b82018-03-12 15:28:22 +0000611 for (auto &F : getFixes(Params.textDocument.uri.file(), D)) {
Sam McCall16e70702018-10-24 07:59:38 +0000612 Actions.push_back(toCodeAction(F, Params.textDocument.uri));
Sam McCall20841d42018-10-16 16:29:41 +0000613 Actions.back().diagnostics = {D};
Sam McCalldd0566b2017-11-06 15:40:30 +0000614 }
Ilya Biryukovafb55542017-05-16 14:40:30 +0000615 }
Sam McCall20841d42018-10-16 16:29:41 +0000616
617 if (SupportsCodeAction)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000618 Reply(llvm::json::Array(Actions));
Sam McCall20841d42018-10-16 16:29:41 +0000619 else {
620 std::vector<Command> Commands;
621 for (const auto &Action : Actions)
622 if (auto Command = asCommand(Action))
623 Commands.push_back(std::move(*Command));
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000624 Reply(llvm::json::Array(Commands));
Sam McCall20841d42018-10-16 16:29:41 +0000625 }
Ilya Biryukovafb55542017-05-16 14:40:30 +0000626}
627
Ilya Biryukovb0826bd2019-01-03 13:37:12 +0000628void ClangdLSPServer::onCompletion(const CompletionParams &Params,
Sam McCall2c30fbc2018-10-18 12:32:04 +0000629 Callback<CompletionList> Reply) {
Ilya Biryukovb0826bd2019-01-03 13:37:12 +0000630 if (!shouldRunCompletion(Params))
631 return Reply(llvm::make_error<IgnoreCompletionError>());
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000632 Server->codeComplete(Params.textDocument.uri.file(), Params.position, CCOpts,
633 Bind(
634 [this](decltype(Reply) Reply,
635 llvm::Expected<CodeCompleteResult> List) {
636 if (!List)
637 return Reply(List.takeError());
638 CompletionList LSPList;
639 LSPList.isIncomplete = List->HasMore;
640 for (const auto &R : List->Completions) {
641 CompletionItem C = R.render(CCOpts);
642 C.kind = adjustKindToCapability(
643 C.kind, SupportedCompletionItemKinds);
644 LSPList.items.push_back(std::move(C));
645 }
646 return Reply(std::move(LSPList));
647 },
648 std::move(Reply)));
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000649}
650
Sam McCall2c30fbc2018-10-18 12:32:04 +0000651void ClangdLSPServer::onSignatureHelp(const TextDocumentPositionParams &Params,
652 Callback<SignatureHelp> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000653 Server->signatureHelp(Params.textDocument.uri.file(), Params.position,
Sam McCall2c30fbc2018-10-18 12:32:04 +0000654 std::move(Reply));
Ilya Biryukov652364b2018-09-26 05:48:29 +0000655}
656
Sam McCall2c30fbc2018-10-18 12:32:04 +0000657void ClangdLSPServer::onGoToDefinition(const TextDocumentPositionParams &Params,
658 Callback<std::vector<Location>> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000659 Server->findDefinitions(Params.textDocument.uri.file(), Params.position,
Sam McCall2c30fbc2018-10-18 12:32:04 +0000660 std::move(Reply));
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000661}
662
Sam McCall2c30fbc2018-10-18 12:32:04 +0000663void ClangdLSPServer::onSwitchSourceHeader(const TextDocumentIdentifier &Params,
664 Callback<std::string> Reply) {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000665 llvm::Optional<Path> Result = Server->switchSourceHeader(Params.uri.file());
Sam McCall2c30fbc2018-10-18 12:32:04 +0000666 Reply(Result ? URI::createFile(*Result).toString() : "");
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000667}
668
Sam McCall2c30fbc2018-10-18 12:32:04 +0000669void ClangdLSPServer::onDocumentHighlight(
670 const TextDocumentPositionParams &Params,
671 Callback<std::vector<DocumentHighlight>> Reply) {
672 Server->findDocumentHighlights(Params.textDocument.uri.file(),
673 Params.position, std::move(Reply));
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000674}
675
Sam McCall2c30fbc2018-10-18 12:32:04 +0000676void ClangdLSPServer::onHover(const TextDocumentPositionParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000677 Callback<llvm::Optional<Hover>> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000678 Server->findHover(Params.textDocument.uri.file(), Params.position,
Sam McCall2c30fbc2018-10-18 12:32:04 +0000679 std::move(Reply));
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000680}
681
Simon Marchi88016782018-08-01 11:28:49 +0000682void ClangdLSPServer::applyConfiguration(
Sam McCallbc904612018-10-25 04:22:52 +0000683 const ConfigurationSettings &Settings) {
Simon Marchiabeed662018-10-16 15:55:03 +0000684 // Per-file update to the compilation database.
Sam McCallbc904612018-10-25 04:22:52 +0000685 bool ShouldReparseOpenFiles = false;
686 for (auto &Entry : Settings.compilationDatabaseChanges) {
687 /// The opened files need to be reparsed only when some existing
688 /// entries are changed.
689 PathRef File = Entry.first;
Sam McCallc55d09a2018-11-02 13:09:36 +0000690 auto Old = CDB->getCompileCommand(File);
691 auto New =
692 tooling::CompileCommand(std::move(Entry.second.workingDirectory), File,
693 std::move(Entry.second.compilationCommand),
694 /*Output=*/"");
Sam McCall6980edb2018-11-02 14:07:51 +0000695 if (Old != New) {
Sam McCallc55d09a2018-11-02 13:09:36 +0000696 CDB->setCompileCommand(File, std::move(New));
Sam McCall6980edb2018-11-02 14:07:51 +0000697 ShouldReparseOpenFiles = true;
698 }
Alex Lorenzf8087862018-08-01 17:39:29 +0000699 }
Sam McCallbc904612018-10-25 04:22:52 +0000700 if (ShouldReparseOpenFiles)
701 reparseOpenedFiles();
Simon Marchi5178f922018-02-22 14:00:39 +0000702}
703
Simon Marchi88016782018-08-01 11:28:49 +0000704// FIXME: This function needs to be properly tested.
705void ClangdLSPServer::onChangeConfiguration(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000706 const DidChangeConfigurationParams &Params) {
Simon Marchi88016782018-08-01 11:28:49 +0000707 applyConfiguration(Params.settings);
708}
709
Sam McCall2c30fbc2018-10-18 12:32:04 +0000710void ClangdLSPServer::onReference(const ReferenceParams &Params,
711 Callback<std::vector<Location>> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000712 Server->findReferences(Params.textDocument.uri.file(), Params.position,
Haojian Wuc34f0222019-01-14 18:11:09 +0000713 CCOpts.Limit, std::move(Reply));
Sam McCall1ad142f2018-09-05 11:53:07 +0000714}
715
Jan Korousb4067012018-11-27 16:40:46 +0000716void ClangdLSPServer::onSymbolInfo(const TextDocumentPositionParams &Params,
717 Callback<std::vector<SymbolDetails>> Reply) {
718 Server->symbolInfo(Params.textDocument.uri.file(), Params.position,
719 std::move(Reply));
720}
721
Sam McCalldc8f3cf2018-10-17 07:32:05 +0000722ClangdLSPServer::ClangdLSPServer(class Transport &Transp,
Haojian Wu1ca0c582019-01-22 09:39:05 +0000723 const FileSystemProvider &FSProvider,
Sam McCalladccab62017-11-23 16:58:22 +0000724 const clangd::CodeCompleteOptions &CCOpts,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000725 llvm::Optional<Path> CompileCommandsDir,
Sam McCallc55d09a2018-11-02 13:09:36 +0000726 bool UseDirBasedCDB,
Sam McCall7363a2f2018-03-05 17:28:54 +0000727 const ClangdServer::Options &Opts)
Haojian Wu1ca0c582019-01-22 09:39:05 +0000728 : Transp(Transp), MsgHandler(new MessageHandler(*this)),
729 FSProvider(FSProvider), CCOpts(CCOpts),
Sam McCalld1c9d112018-10-23 14:19:54 +0000730 SupportedSymbolKinds(defaultSymbolKinds()),
Kadir Cetinkaya133d46f2018-09-27 17:13:07 +0000731 SupportedCompletionItemKinds(defaultCompletionItemKinds()),
Sam McCallc55d09a2018-11-02 13:09:36 +0000732 UseDirBasedCDB(UseDirBasedCDB),
Sam McCall4b86bb02018-10-25 02:22:53 +0000733 CompileCommandsDir(std::move(CompileCommandsDir)),
734 ClangdServerOpts(Opts) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000735 // clang-format off
736 MsgHandler->bind("initialize", &ClangdLSPServer::onInitialize);
737 MsgHandler->bind("shutdown", &ClangdLSPServer::onShutdown);
Sam McCall422c8282018-11-26 16:00:11 +0000738 MsgHandler->bind("sync", &ClangdLSPServer::onSync);
Sam McCall2c30fbc2018-10-18 12:32:04 +0000739 MsgHandler->bind("textDocument/rangeFormatting", &ClangdLSPServer::onDocumentRangeFormatting);
740 MsgHandler->bind("textDocument/onTypeFormatting", &ClangdLSPServer::onDocumentOnTypeFormatting);
741 MsgHandler->bind("textDocument/formatting", &ClangdLSPServer::onDocumentFormatting);
742 MsgHandler->bind("textDocument/codeAction", &ClangdLSPServer::onCodeAction);
743 MsgHandler->bind("textDocument/completion", &ClangdLSPServer::onCompletion);
744 MsgHandler->bind("textDocument/signatureHelp", &ClangdLSPServer::onSignatureHelp);
745 MsgHandler->bind("textDocument/definition", &ClangdLSPServer::onGoToDefinition);
746 MsgHandler->bind("textDocument/references", &ClangdLSPServer::onReference);
747 MsgHandler->bind("textDocument/switchSourceHeader", &ClangdLSPServer::onSwitchSourceHeader);
748 MsgHandler->bind("textDocument/rename", &ClangdLSPServer::onRename);
749 MsgHandler->bind("textDocument/hover", &ClangdLSPServer::onHover);
750 MsgHandler->bind("textDocument/documentSymbol", &ClangdLSPServer::onDocumentSymbol);
751 MsgHandler->bind("workspace/executeCommand", &ClangdLSPServer::onCommand);
752 MsgHandler->bind("textDocument/documentHighlight", &ClangdLSPServer::onDocumentHighlight);
753 MsgHandler->bind("workspace/symbol", &ClangdLSPServer::onWorkspaceSymbol);
754 MsgHandler->bind("textDocument/didOpen", &ClangdLSPServer::onDocumentDidOpen);
755 MsgHandler->bind("textDocument/didClose", &ClangdLSPServer::onDocumentDidClose);
756 MsgHandler->bind("textDocument/didChange", &ClangdLSPServer::onDocumentDidChange);
757 MsgHandler->bind("workspace/didChangeWatchedFiles", &ClangdLSPServer::onFileEvent);
758 MsgHandler->bind("workspace/didChangeConfiguration", &ClangdLSPServer::onChangeConfiguration);
Jan Korousb4067012018-11-27 16:40:46 +0000759 MsgHandler->bind("textDocument/symbolInfo", &ClangdLSPServer::onSymbolInfo);
Sam McCall2c30fbc2018-10-18 12:32:04 +0000760 // clang-format on
761}
762
763ClangdLSPServer::~ClangdLSPServer() = default;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000764
Sam McCalldc8f3cf2018-10-17 07:32:05 +0000765bool ClangdLSPServer::run() {
Ilya Biryukovafb55542017-05-16 14:40:30 +0000766 // Run the Language Server loop.
Sam McCalldc8f3cf2018-10-17 07:32:05 +0000767 bool CleanExit = true;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000768 if (auto Err = Transp.loop(*MsgHandler)) {
Sam McCalldc8f3cf2018-10-17 07:32:05 +0000769 elog("Transport error: {0}", std::move(Err));
770 CleanExit = false;
771 }
Ilya Biryukovafb55542017-05-16 14:40:30 +0000772
Ilya Biryukov652364b2018-09-26 05:48:29 +0000773 // Destroy ClangdServer to ensure all worker threads finish.
774 Server.reset();
Sam McCalldc8f3cf2018-10-17 07:32:05 +0000775 return CleanExit && ShutdownRequestReceived;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000776}
777
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000778std::vector<Fix> ClangdLSPServer::getFixes(llvm::StringRef File,
Ilya Biryukov71028b82018-03-12 15:28:22 +0000779 const clangd::Diagnostic &D) {
Ilya Biryukov38d79772017-05-16 09:38:59 +0000780 std::lock_guard<std::mutex> Lock(FixItsMutex);
781 auto DiagToFixItsIter = FixItsMap.find(File);
782 if (DiagToFixItsIter == FixItsMap.end())
783 return {};
784
785 const auto &DiagToFixItsMap = DiagToFixItsIter->second;
786 auto FixItsIter = DiagToFixItsMap.find(D);
787 if (FixItsIter == DiagToFixItsMap.end())
788 return {};
789
790 return FixItsIter->second;
791}
792
Ilya Biryukovb0826bd2019-01-03 13:37:12 +0000793bool ClangdLSPServer::shouldRunCompletion(
794 const CompletionParams &Params) const {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000795 llvm::StringRef Trigger = Params.context.triggerCharacter;
Ilya Biryukovb0826bd2019-01-03 13:37:12 +0000796 if (Params.context.triggerKind != CompletionTriggerKind::TriggerCharacter ||
797 (Trigger != ">" && Trigger != ":"))
798 return true;
799
800 auto Code = DraftMgr.getDraft(Params.textDocument.uri.file());
801 if (!Code)
802 return true; // completion code will log the error for untracked doc.
803
804 // A completion request is sent when the user types '>' or ':', but we only
805 // want to trigger on '->' and '::'. We check the preceeding character to make
806 // sure it matches what we expected.
807 // Running the lexer here would be more robust (e.g. we can detect comments
808 // and avoid triggering completion there), but we choose to err on the side
809 // of simplicity here.
810 auto Offset = positionToOffset(*Code, Params.position,
811 /*AllowColumnsBeyondLineLength=*/false);
812 if (!Offset) {
813 vlog("could not convert position '{0}' to offset for file '{1}'",
814 Params.position, Params.textDocument.uri.file());
815 return true;
816 }
817 if (*Offset < 2)
818 return false;
819
820 if (Trigger == ">")
821 return (*Code)[*Offset - 2] == '-'; // trigger only on '->'.
822 if (Trigger == ":")
823 return (*Code)[*Offset - 2] == ':'; // trigger only on '::'.
824 assert(false && "unhandled trigger character");
825 return true;
826}
827
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000828void ClangdLSPServer::onDiagnosticsReady(PathRef File,
829 std::vector<Diag> Diagnostics) {
Eric Liu4d814a92018-11-28 10:30:42 +0000830 auto URI = URIForFile::canonicalize(File, /*TUPath=*/File);
Sam McCall16e70702018-10-24 07:59:38 +0000831 std::vector<Diagnostic> LSPDiagnostics;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000832 DiagnosticToReplacementMap LocalFixIts; // Temporary storage
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000833 for (auto &Diag : Diagnostics) {
Sam McCall16e70702018-10-24 07:59:38 +0000834 toLSPDiags(Diag, URI, DiagOpts,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000835 [&](clangd::Diagnostic Diag, llvm::ArrayRef<Fix> Fixes) {
Sam McCall16e70702018-10-24 07:59:38 +0000836 auto &FixItsForDiagnostic = LocalFixIts[Diag];
837 llvm::copy(Fixes, std::back_inserter(FixItsForDiagnostic));
838 LSPDiagnostics.push_back(std::move(Diag));
839 });
Ilya Biryukov38d79772017-05-16 09:38:59 +0000840 }
841
842 // Cache FixIts
843 {
844 // FIXME(ibiryukov): should be deleted when documents are removed
845 std::lock_guard<std::mutex> Lock(FixItsMutex);
846 FixItsMap[File] = LocalFixIts;
847 }
848
849 // Publish diagnostics.
Sam McCall2c30fbc2018-10-18 12:32:04 +0000850 notify("textDocument/publishDiagnostics",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000851 llvm::json::Object{
Sam McCall16e70702018-10-24 07:59:38 +0000852 {"uri", URI},
853 {"diagnostics", std::move(LSPDiagnostics)},
Sam McCall2c30fbc2018-10-18 12:32:04 +0000854 });
Ilya Biryukov38d79772017-05-16 09:38:59 +0000855}
Simon Marchi9569fd52018-03-16 14:30:42 +0000856
Haojian Wub6188492018-12-20 15:39:12 +0000857void ClangdLSPServer::onFileUpdated(PathRef File, const TUStatus &Status) {
858 if (!SupportFileStatus)
859 return;
860 // FIXME: we don't emit "BuildingFile" and `RunningAction`, as these
861 // two statuses are running faster in practice, which leads the UI constantly
862 // changing, and doesn't provide much value. We may want to emit status at a
863 // reasonable time interval (e.g. 0.5s).
864 if (Status.Action.S == TUAction::BuildingFile ||
865 Status.Action.S == TUAction::RunningAction)
866 return;
867 notify("textDocument/clangd.fileStatus", Status.render(File));
868}
869
Simon Marchi9569fd52018-03-16 14:30:42 +0000870void ClangdLSPServer::reparseOpenedFiles() {
871 for (const Path &FilePath : DraftMgr.getActiveFiles())
Ilya Biryukov652364b2018-09-26 05:48:29 +0000872 Server->addDocument(FilePath, *DraftMgr.getDraft(FilePath),
873 WantDiagnostics::Auto);
Simon Marchi9569fd52018-03-16 14:30:42 +0000874}
Alex Lorenzf8087862018-08-01 17:39:29 +0000875
Sam McCallc008af62018-10-20 15:30:37 +0000876} // namespace clangd
877} // namespace clang