blob: 80792eddc69a9b8bba43b69b178193fc326bb105 [file] [log] [blame]
Ilya Biryukov38d79772017-05-16 09:38:59 +00001//===--- ClangdLSPServer.cpp - LSP server ------------------------*- C++-*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
Kirill Bobyrev8e35f1e2018-08-14 16:03:32 +00008//===----------------------------------------------------------------------===//
Ilya Biryukov38d79772017-05-16 09:38:59 +00009
10#include "ClangdLSPServer.h"
Ilya Biryukov71028b82018-03-12 15:28:22 +000011#include "Diagnostics.h"
Sam McCallb536a2a2017-12-19 12:23:48 +000012#include "SourceCode.h"
Sam McCall2c30fbc2018-10-18 12:32:04 +000013#include "Trace.h"
Eric Liu78ed91a72018-01-29 15:37:46 +000014#include "URI.h"
Kadir Cetinkaya689bf932018-08-24 13:09:41 +000015#include "llvm/ADT/ScopeExit.h"
Simon Marchi9569fd52018-03-16 14:30:42 +000016#include "llvm/Support/Errc.h"
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +000017#include "llvm/Support/FormatVariadic.h"
Eric Liu5740ff52018-01-31 16:26:27 +000018#include "llvm/Support/Path.h"
Sam McCall2c30fbc2018-10-18 12:32:04 +000019#include "llvm/Support/ScopedPrinter.h"
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +000020
Sam McCallc008af62018-10-20 15:30:37 +000021namespace clang {
22namespace clangd {
Ilya Biryukovafb55542017-05-16 14:40:30 +000023namespace {
Ilya Biryukovb0826bd2019-01-03 13:37:12 +000024class IgnoreCompletionError : public llvm::ErrorInfo<CancelledError> {
25public:
26 void log(llvm::raw_ostream &OS) const override {
27 OS << "ignored auto-triggered completion, preceding char did not match";
28 }
29 std::error_code convertToErrorCode() const override {
30 return std::make_error_code(std::errc::operation_canceled);
31 }
32};
Ilya Biryukovafb55542017-05-16 14:40:30 +000033
Ilya Biryukov19d75602018-11-23 15:21:19 +000034void adjustSymbolKinds(llvm::MutableArrayRef<DocumentSymbol> Syms,
35 SymbolKindBitset Kinds) {
36 for (auto &S : Syms) {
37 S.kind = adjustKindToCapability(S.kind, Kinds);
38 adjustSymbolKinds(S.children, Kinds);
39 }
40}
41
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +000042SymbolKindBitset defaultSymbolKinds() {
43 SymbolKindBitset Defaults;
44 for (size_t I = SymbolKindMin; I <= static_cast<size_t>(SymbolKind::Array);
45 ++I)
46 Defaults.set(I);
47 return Defaults;
48}
49
Kadir Cetinkaya133d46f2018-09-27 17:13:07 +000050CompletionItemKindBitset defaultCompletionItemKinds() {
51 CompletionItemKindBitset Defaults;
52 for (size_t I = CompletionItemKindMin;
53 I <= static_cast<size_t>(CompletionItemKind::Reference); ++I)
54 Defaults.set(I);
55 return Defaults;
56}
57
Ilya Biryukovafb55542017-05-16 14:40:30 +000058} // namespace
59
Sam McCall2c30fbc2018-10-18 12:32:04 +000060// MessageHandler dispatches incoming LSP messages.
61// It handles cross-cutting concerns:
62// - serializes/deserializes protocol objects to JSON
63// - logging of inbound messages
64// - cancellation handling
65// - basic call tracing
Sam McCall3d0adbe2018-10-18 14:41:50 +000066// MessageHandler ensures that initialize() is called before any other handler.
Sam McCall2c30fbc2018-10-18 12:32:04 +000067class ClangdLSPServer::MessageHandler : public Transport::MessageHandler {
68public:
69 MessageHandler(ClangdLSPServer &Server) : Server(Server) {}
70
Ilya Biryukovf2001aa2019-01-07 15:45:19 +000071 bool onNotify(llvm::StringRef Method, llvm::json::Value Params) override {
Sam McCall2c30fbc2018-10-18 12:32:04 +000072 log("<-- {0}", Method);
73 if (Method == "exit")
74 return false;
Sam McCall3d0adbe2018-10-18 14:41:50 +000075 if (!Server.Server)
76 elog("Notification {0} before initialization", Method);
77 else if (Method == "$/cancelRequest")
Sam McCall2c30fbc2018-10-18 12:32:04 +000078 onCancel(std::move(Params));
79 else if (auto Handler = Notifications.lookup(Method))
80 Handler(std::move(Params));
81 else
82 log("unhandled notification {0}", Method);
83 return true;
84 }
85
Ilya Biryukovf2001aa2019-01-07 15:45:19 +000086 bool onCall(llvm::StringRef Method, llvm::json::Value Params,
87 llvm::json::Value ID) override {
Sam McCalle2f3a732018-10-24 14:26:26 +000088 // Calls can be canceled by the client. Add cancellation context.
89 WithContext WithCancel(cancelableRequestContext(ID));
90 trace::Span Tracer(Method);
91 SPAN_ATTACH(Tracer, "Params", Params);
92 ReplyOnce Reply(ID, Method, &Server, Tracer.Args);
Sam McCall2c30fbc2018-10-18 12:32:04 +000093 log("<-- {0}({1})", Method, ID);
Sam McCall3d0adbe2018-10-18 14:41:50 +000094 if (!Server.Server && Method != "initialize") {
95 elog("Call {0} before initialization.", Method);
Ilya Biryukovf2001aa2019-01-07 15:45:19 +000096 Reply(llvm::make_error<LSPError>("server not initialized",
97 ErrorCode::ServerNotInitialized));
Sam McCall3d0adbe2018-10-18 14:41:50 +000098 } else if (auto Handler = Calls.lookup(Method))
Sam McCalle2f3a732018-10-24 14:26:26 +000099 Handler(std::move(Params), std::move(Reply));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000100 else
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000101 Reply(llvm::make_error<LSPError>("method not found",
102 ErrorCode::MethodNotFound));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000103 return true;
104 }
105
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000106 bool onReply(llvm::json::Value ID,
107 llvm::Expected<llvm::json::Value> Result) override {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000108 // We ignore replies, just log them.
109 if (Result)
110 log("<-- reply({0})", ID);
111 else
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000112 log("<-- reply({0}) error: {1}", ID, llvm::toString(Result.takeError()));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000113 return true;
114 }
115
116 // Bind an LSP method name to a call.
Sam McCalle2f3a732018-10-24 14:26:26 +0000117 template <typename Param, typename Result>
Sam McCall2c30fbc2018-10-18 12:32:04 +0000118 void bind(const char *Method,
Sam McCalle2f3a732018-10-24 14:26:26 +0000119 void (ClangdLSPServer::*Handler)(const Param &, Callback<Result>)) {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000120 Calls[Method] = [Method, Handler, this](llvm::json::Value RawParams,
Sam McCalle2f3a732018-10-24 14:26:26 +0000121 ReplyOnce Reply) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000122 Param P;
Sam McCalle2f3a732018-10-24 14:26:26 +0000123 if (fromJSON(RawParams, P)) {
124 (Server.*Handler)(P, std::move(Reply));
125 } else {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000126 elog("Failed to decode {0} request.", Method);
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000127 Reply(llvm::make_error<LSPError>("failed to decode request",
128 ErrorCode::InvalidRequest));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000129 }
Sam McCall2c30fbc2018-10-18 12:32:04 +0000130 };
131 }
132
133 // Bind an LSP method name to a notification.
134 template <typename Param>
135 void bind(const char *Method,
136 void (ClangdLSPServer::*Handler)(const Param &)) {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000137 Notifications[Method] = [Method, Handler,
138 this](llvm::json::Value RawParams) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000139 Param P;
140 if (!fromJSON(RawParams, P)) {
141 elog("Failed to decode {0} request.", Method);
142 return;
143 }
144 trace::Span Tracer(Method);
145 SPAN_ATTACH(Tracer, "Params", RawParams);
146 (Server.*Handler)(P);
147 };
148 }
149
150private:
Sam McCalle2f3a732018-10-24 14:26:26 +0000151 // Function object to reply to an LSP call.
152 // Each instance must be called exactly once, otherwise:
153 // - the bug is logged, and (in debug mode) an assert will fire
154 // - if there was no reply, an error reply is sent
155 // - if there were multiple replies, only the first is sent
156 class ReplyOnce {
157 std::atomic<bool> Replied = {false};
Sam McCalld7babe42018-10-24 15:18:40 +0000158 std::chrono::steady_clock::time_point Start;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000159 llvm::json::Value ID;
Sam McCalle2f3a732018-10-24 14:26:26 +0000160 std::string Method;
161 ClangdLSPServer *Server; // Null when moved-from.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000162 llvm::json::Object *TraceArgs;
Sam McCalle2f3a732018-10-24 14:26:26 +0000163
164 public:
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000165 ReplyOnce(const llvm::json::Value &ID, llvm::StringRef Method,
166 ClangdLSPServer *Server, llvm::json::Object *TraceArgs)
Sam McCalld7babe42018-10-24 15:18:40 +0000167 : Start(std::chrono::steady_clock::now()), ID(ID), Method(Method),
168 Server(Server), TraceArgs(TraceArgs) {
Sam McCalle2f3a732018-10-24 14:26:26 +0000169 assert(Server);
170 }
171 ReplyOnce(ReplyOnce &&Other)
Sam McCalld7babe42018-10-24 15:18:40 +0000172 : Replied(Other.Replied.load()), Start(Other.Start),
173 ID(std::move(Other.ID)), Method(std::move(Other.Method)),
174 Server(Other.Server), TraceArgs(Other.TraceArgs) {
Sam McCalle2f3a732018-10-24 14:26:26 +0000175 Other.Server = nullptr;
176 }
Ilya Biryukov22fa4652019-01-03 13:28:05 +0000177 ReplyOnce &operator=(ReplyOnce &&) = delete;
Sam McCalle2f3a732018-10-24 14:26:26 +0000178 ReplyOnce(const ReplyOnce &) = delete;
Ilya Biryukov22fa4652019-01-03 13:28:05 +0000179 ReplyOnce &operator=(const ReplyOnce &) = delete;
Sam McCalle2f3a732018-10-24 14:26:26 +0000180
181 ~ReplyOnce() {
182 if (Server && !Replied) {
183 elog("No reply to message {0}({1})", Method, ID);
184 assert(false && "must reply to all calls!");
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000185 (*this)(llvm::make_error<LSPError>("server failed to reply",
186 ErrorCode::InternalError));
Sam McCalle2f3a732018-10-24 14:26:26 +0000187 }
188 }
189
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000190 void operator()(llvm::Expected<llvm::json::Value> Reply) {
Sam McCalle2f3a732018-10-24 14:26:26 +0000191 assert(Server && "moved-from!");
192 if (Replied.exchange(true)) {
193 elog("Replied twice to message {0}({1})", Method, ID);
194 assert(false && "must reply to each call only once!");
195 return;
196 }
Sam McCalld7babe42018-10-24 15:18:40 +0000197 auto Duration = std::chrono::steady_clock::now() - Start;
198 if (Reply) {
199 log("--> reply:{0}({1}) {2:ms}", Method, ID, Duration);
200 if (TraceArgs)
Sam McCalle2f3a732018-10-24 14:26:26 +0000201 (*TraceArgs)["Reply"] = *Reply;
Sam McCalld7babe42018-10-24 15:18:40 +0000202 std::lock_guard<std::mutex> Lock(Server->TranspWriter);
203 Server->Transp.reply(std::move(ID), std::move(Reply));
204 } else {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000205 llvm::Error Err = Reply.takeError();
Sam McCalld7babe42018-10-24 15:18:40 +0000206 log("--> reply:{0}({1}) {2:ms}, error: {3}", Method, ID, Duration, Err);
207 if (TraceArgs)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000208 (*TraceArgs)["Error"] = llvm::to_string(Err);
Sam McCalld7babe42018-10-24 15:18:40 +0000209 std::lock_guard<std::mutex> Lock(Server->TranspWriter);
210 Server->Transp.reply(std::move(ID), std::move(Err));
Sam McCalle2f3a732018-10-24 14:26:26 +0000211 }
Sam McCalle2f3a732018-10-24 14:26:26 +0000212 }
213 };
214
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000215 llvm::StringMap<std::function<void(llvm::json::Value)>> Notifications;
216 llvm::StringMap<std::function<void(llvm::json::Value, ReplyOnce)>> Calls;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000217
218 // Method calls may be cancelled by ID, so keep track of their state.
219 // This needs a mutex: handlers may finish on a different thread, and that's
220 // when we clean up entries in the map.
221 mutable std::mutex RequestCancelersMutex;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000222 llvm::StringMap<std::pair<Canceler, /*Cookie*/ unsigned>> RequestCancelers;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000223 unsigned NextRequestCookie = 0; // To disambiguate reused IDs, see below.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000224 void onCancel(const llvm::json::Value &Params) {
225 const llvm::json::Value *ID = nullptr;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000226 if (auto *O = Params.getAsObject())
227 ID = O->get("id");
228 if (!ID) {
229 elog("Bad cancellation request: {0}", Params);
230 return;
231 }
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000232 auto StrID = llvm::to_string(*ID);
Sam McCall2c30fbc2018-10-18 12:32:04 +0000233 std::lock_guard<std::mutex> Lock(RequestCancelersMutex);
234 auto It = RequestCancelers.find(StrID);
235 if (It != RequestCancelers.end())
236 It->second.first(); // Invoke the canceler.
237 }
238 // We run cancelable requests in a context that does two things:
239 // - allows cancellation using RequestCancelers[ID]
240 // - cleans up the entry in RequestCancelers when it's no longer needed
241 // If a client reuses an ID, the last wins and the first cannot be canceled.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000242 Context cancelableRequestContext(const llvm::json::Value &ID) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000243 auto Task = cancelableTask();
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000244 auto StrID = llvm::to_string(ID); // JSON-serialize ID for map key.
Sam McCall2c30fbc2018-10-18 12:32:04 +0000245 auto Cookie = NextRequestCookie++; // No lock, only called on main thread.
246 {
247 std::lock_guard<std::mutex> Lock(RequestCancelersMutex);
248 RequestCancelers[StrID] = {std::move(Task.second), Cookie};
249 }
250 // When the request ends, we can clean up the entry we just added.
251 // The cookie lets us check that it hasn't been overwritten due to ID
252 // reuse.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000253 return Task.first.derive(llvm::make_scope_exit([this, StrID, Cookie] {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000254 std::lock_guard<std::mutex> Lock(RequestCancelersMutex);
255 auto It = RequestCancelers.find(StrID);
256 if (It != RequestCancelers.end() && It->second.second == Cookie)
257 RequestCancelers.erase(It);
258 }));
259 }
260
261 ClangdLSPServer &Server;
262};
263
264// call(), notify(), and reply() wrap the Transport, adding logging and locking.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000265void ClangdLSPServer::call(llvm::StringRef Method, llvm::json::Value Params) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000266 auto ID = NextCallID++;
267 log("--> {0}({1})", Method, ID);
268 // We currently don't handle responses, so no need to store ID anywhere.
269 std::lock_guard<std::mutex> Lock(TranspWriter);
270 Transp.call(Method, std::move(Params), ID);
271}
272
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000273void ClangdLSPServer::notify(llvm::StringRef Method, llvm::json::Value Params) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000274 log("--> {0}", Method);
275 std::lock_guard<std::mutex> Lock(TranspWriter);
276 Transp.notify(Method, std::move(Params));
277}
278
Sam McCall2c30fbc2018-10-18 12:32:04 +0000279void ClangdLSPServer::onInitialize(const InitializeParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000280 Callback<llvm::json::Value> Reply) {
Sam McCall0d9b40f2018-10-19 15:42:23 +0000281 if (Params.rootUri && *Params.rootUri)
282 ClangdServerOpts.WorkspaceRoot = Params.rootUri->file();
283 else if (Params.rootPath && !Params.rootPath->empty())
284 ClangdServerOpts.WorkspaceRoot = *Params.rootPath;
Sam McCall3d0adbe2018-10-18 14:41:50 +0000285 if (Server)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000286 return Reply(llvm::make_error<LSPError>("server already initialized",
287 ErrorCode::InvalidRequest));
Sam McCallbc904612018-10-25 04:22:52 +0000288 if (const auto &Dir = Params.initializationOptions.compilationDatabasePath)
289 CompileCommandsDir = Dir;
Sam McCallc55d09a2018-11-02 13:09:36 +0000290 if (UseDirBasedCDB)
291 BaseCDB = llvm::make_unique<DirectoryBasedGlobalCompilationDatabase>(
292 CompileCommandsDir);
Sam McCall6980edb2018-11-02 14:07:51 +0000293 CDB.emplace(BaseCDB.get(), Params.initializationOptions.fallbackFlags);
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,
Sam McCalladccab62017-11-23 16:58:22 +0000723 const clangd::CodeCompleteOptions &CCOpts,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000724 llvm::Optional<Path> CompileCommandsDir,
Sam McCallc55d09a2018-11-02 13:09:36 +0000725 bool UseDirBasedCDB,
Sam McCall7363a2f2018-03-05 17:28:54 +0000726 const ClangdServer::Options &Opts)
Sam McCalld1c9d112018-10-23 14:19:54 +0000727 : Transp(Transp), MsgHandler(new MessageHandler(*this)), CCOpts(CCOpts),
728 SupportedSymbolKinds(defaultSymbolKinds()),
Kadir Cetinkaya133d46f2018-09-27 17:13:07 +0000729 SupportedCompletionItemKinds(defaultCompletionItemKinds()),
Sam McCallc55d09a2018-11-02 13:09:36 +0000730 UseDirBasedCDB(UseDirBasedCDB),
Sam McCall4b86bb02018-10-25 02:22:53 +0000731 CompileCommandsDir(std::move(CompileCommandsDir)),
732 ClangdServerOpts(Opts) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000733 // clang-format off
734 MsgHandler->bind("initialize", &ClangdLSPServer::onInitialize);
735 MsgHandler->bind("shutdown", &ClangdLSPServer::onShutdown);
Sam McCall422c8282018-11-26 16:00:11 +0000736 MsgHandler->bind("sync", &ClangdLSPServer::onSync);
Sam McCall2c30fbc2018-10-18 12:32:04 +0000737 MsgHandler->bind("textDocument/rangeFormatting", &ClangdLSPServer::onDocumentRangeFormatting);
738 MsgHandler->bind("textDocument/onTypeFormatting", &ClangdLSPServer::onDocumentOnTypeFormatting);
739 MsgHandler->bind("textDocument/formatting", &ClangdLSPServer::onDocumentFormatting);
740 MsgHandler->bind("textDocument/codeAction", &ClangdLSPServer::onCodeAction);
741 MsgHandler->bind("textDocument/completion", &ClangdLSPServer::onCompletion);
742 MsgHandler->bind("textDocument/signatureHelp", &ClangdLSPServer::onSignatureHelp);
743 MsgHandler->bind("textDocument/definition", &ClangdLSPServer::onGoToDefinition);
744 MsgHandler->bind("textDocument/references", &ClangdLSPServer::onReference);
745 MsgHandler->bind("textDocument/switchSourceHeader", &ClangdLSPServer::onSwitchSourceHeader);
746 MsgHandler->bind("textDocument/rename", &ClangdLSPServer::onRename);
747 MsgHandler->bind("textDocument/hover", &ClangdLSPServer::onHover);
748 MsgHandler->bind("textDocument/documentSymbol", &ClangdLSPServer::onDocumentSymbol);
749 MsgHandler->bind("workspace/executeCommand", &ClangdLSPServer::onCommand);
750 MsgHandler->bind("textDocument/documentHighlight", &ClangdLSPServer::onDocumentHighlight);
751 MsgHandler->bind("workspace/symbol", &ClangdLSPServer::onWorkspaceSymbol);
752 MsgHandler->bind("textDocument/didOpen", &ClangdLSPServer::onDocumentDidOpen);
753 MsgHandler->bind("textDocument/didClose", &ClangdLSPServer::onDocumentDidClose);
754 MsgHandler->bind("textDocument/didChange", &ClangdLSPServer::onDocumentDidChange);
755 MsgHandler->bind("workspace/didChangeWatchedFiles", &ClangdLSPServer::onFileEvent);
756 MsgHandler->bind("workspace/didChangeConfiguration", &ClangdLSPServer::onChangeConfiguration);
Jan Korousb4067012018-11-27 16:40:46 +0000757 MsgHandler->bind("textDocument/symbolInfo", &ClangdLSPServer::onSymbolInfo);
Sam McCall2c30fbc2018-10-18 12:32:04 +0000758 // clang-format on
759}
760
761ClangdLSPServer::~ClangdLSPServer() = default;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000762
Sam McCalldc8f3cf2018-10-17 07:32:05 +0000763bool ClangdLSPServer::run() {
Ilya Biryukovafb55542017-05-16 14:40:30 +0000764 // Run the Language Server loop.
Sam McCalldc8f3cf2018-10-17 07:32:05 +0000765 bool CleanExit = true;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000766 if (auto Err = Transp.loop(*MsgHandler)) {
Sam McCalldc8f3cf2018-10-17 07:32:05 +0000767 elog("Transport error: {0}", std::move(Err));
768 CleanExit = false;
769 }
Ilya Biryukovafb55542017-05-16 14:40:30 +0000770
Ilya Biryukov652364b2018-09-26 05:48:29 +0000771 // Destroy ClangdServer to ensure all worker threads finish.
772 Server.reset();
Sam McCalldc8f3cf2018-10-17 07:32:05 +0000773 return CleanExit && ShutdownRequestReceived;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000774}
775
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000776std::vector<Fix> ClangdLSPServer::getFixes(llvm::StringRef File,
Ilya Biryukov71028b82018-03-12 15:28:22 +0000777 const clangd::Diagnostic &D) {
Ilya Biryukov38d79772017-05-16 09:38:59 +0000778 std::lock_guard<std::mutex> Lock(FixItsMutex);
779 auto DiagToFixItsIter = FixItsMap.find(File);
780 if (DiagToFixItsIter == FixItsMap.end())
781 return {};
782
783 const auto &DiagToFixItsMap = DiagToFixItsIter->second;
784 auto FixItsIter = DiagToFixItsMap.find(D);
785 if (FixItsIter == DiagToFixItsMap.end())
786 return {};
787
788 return FixItsIter->second;
789}
790
Ilya Biryukovb0826bd2019-01-03 13:37:12 +0000791bool ClangdLSPServer::shouldRunCompletion(
792 const CompletionParams &Params) const {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000793 llvm::StringRef Trigger = Params.context.triggerCharacter;
Ilya Biryukovb0826bd2019-01-03 13:37:12 +0000794 if (Params.context.triggerKind != CompletionTriggerKind::TriggerCharacter ||
795 (Trigger != ">" && Trigger != ":"))
796 return true;
797
798 auto Code = DraftMgr.getDraft(Params.textDocument.uri.file());
799 if (!Code)
800 return true; // completion code will log the error for untracked doc.
801
802 // A completion request is sent when the user types '>' or ':', but we only
803 // want to trigger on '->' and '::'. We check the preceeding character to make
804 // sure it matches what we expected.
805 // Running the lexer here would be more robust (e.g. we can detect comments
806 // and avoid triggering completion there), but we choose to err on the side
807 // of simplicity here.
808 auto Offset = positionToOffset(*Code, Params.position,
809 /*AllowColumnsBeyondLineLength=*/false);
810 if (!Offset) {
811 vlog("could not convert position '{0}' to offset for file '{1}'",
812 Params.position, Params.textDocument.uri.file());
813 return true;
814 }
815 if (*Offset < 2)
816 return false;
817
818 if (Trigger == ">")
819 return (*Code)[*Offset - 2] == '-'; // trigger only on '->'.
820 if (Trigger == ":")
821 return (*Code)[*Offset - 2] == ':'; // trigger only on '::'.
822 assert(false && "unhandled trigger character");
823 return true;
824}
825
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000826void ClangdLSPServer::onDiagnosticsReady(PathRef File,
827 std::vector<Diag> Diagnostics) {
Eric Liu4d814a92018-11-28 10:30:42 +0000828 auto URI = URIForFile::canonicalize(File, /*TUPath=*/File);
Sam McCall16e70702018-10-24 07:59:38 +0000829 std::vector<Diagnostic> LSPDiagnostics;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000830 DiagnosticToReplacementMap LocalFixIts; // Temporary storage
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000831 for (auto &Diag : Diagnostics) {
Sam McCall16e70702018-10-24 07:59:38 +0000832 toLSPDiags(Diag, URI, DiagOpts,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000833 [&](clangd::Diagnostic Diag, llvm::ArrayRef<Fix> Fixes) {
Sam McCall16e70702018-10-24 07:59:38 +0000834 auto &FixItsForDiagnostic = LocalFixIts[Diag];
835 llvm::copy(Fixes, std::back_inserter(FixItsForDiagnostic));
836 LSPDiagnostics.push_back(std::move(Diag));
837 });
Ilya Biryukov38d79772017-05-16 09:38:59 +0000838 }
839
840 // Cache FixIts
841 {
842 // FIXME(ibiryukov): should be deleted when documents are removed
843 std::lock_guard<std::mutex> Lock(FixItsMutex);
844 FixItsMap[File] = LocalFixIts;
845 }
846
847 // Publish diagnostics.
Sam McCall2c30fbc2018-10-18 12:32:04 +0000848 notify("textDocument/publishDiagnostics",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000849 llvm::json::Object{
Sam McCall16e70702018-10-24 07:59:38 +0000850 {"uri", URI},
851 {"diagnostics", std::move(LSPDiagnostics)},
Sam McCall2c30fbc2018-10-18 12:32:04 +0000852 });
Ilya Biryukov38d79772017-05-16 09:38:59 +0000853}
Simon Marchi9569fd52018-03-16 14:30:42 +0000854
Haojian Wub6188492018-12-20 15:39:12 +0000855void ClangdLSPServer::onFileUpdated(PathRef File, const TUStatus &Status) {
856 if (!SupportFileStatus)
857 return;
858 // FIXME: we don't emit "BuildingFile" and `RunningAction`, as these
859 // two statuses are running faster in practice, which leads the UI constantly
860 // changing, and doesn't provide much value. We may want to emit status at a
861 // reasonable time interval (e.g. 0.5s).
862 if (Status.Action.S == TUAction::BuildingFile ||
863 Status.Action.S == TUAction::RunningAction)
864 return;
865 notify("textDocument/clangd.fileStatus", Status.render(File));
866}
867
Simon Marchi9569fd52018-03-16 14:30:42 +0000868void ClangdLSPServer::reparseOpenedFiles() {
869 for (const Path &FilePath : DraftMgr.getActiveFiles())
Ilya Biryukov652364b2018-09-26 05:48:29 +0000870 Server->addDocument(FilePath, *DraftMgr.getDraft(FilePath),
871 WantDiagnostics::Auto);
Simon Marchi9569fd52018-03-16 14:30:42 +0000872}
Alex Lorenzf8087862018-08-01 17:39:29 +0000873
Sam McCallc008af62018-10-20 15:30:37 +0000874} // namespace clangd
875} // namespace clang