blob: bddea9047c43177beb992d0f00e187656db079e5 [file] [log] [blame]
Ilya Biryukov38d79772017-05-16 09:38:59 +00001//===--- ClangdLSPServer.cpp - LSP server ------------------------*- C++-*-===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Ilya Biryukov38d79772017-05-16 09:38:59 +00006//
Kirill Bobyrev8e35f1e2018-08-14 16:03:32 +00007//===----------------------------------------------------------------------===//
Ilya Biryukov38d79772017-05-16 09:38:59 +00008
9#include "ClangdLSPServer.h"
Ilya Biryukov71028b82018-03-12 15:28:22 +000010#include "Diagnostics.h"
Ilya Biryukovcce67a32019-01-29 14:17:36 +000011#include "Protocol.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"
Ilya Biryukovcce67a32019-01-29 14:17:36 +000015#include "clang/Tooling/Core/Replacement.h"
Kadir Cetinkaya689bf932018-08-24 13:09:41 +000016#include "llvm/ADT/ScopeExit.h"
Simon Marchi9569fd52018-03-16 14:30:42 +000017#include "llvm/Support/Errc.h"
Ilya Biryukovcce67a32019-01-29 14:17:36 +000018#include "llvm/Support/Error.h"
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +000019#include "llvm/Support/FormatVariadic.h"
Eric Liu5740ff52018-01-31 16:26:27 +000020#include "llvm/Support/Path.h"
Sam McCall2c30fbc2018-10-18 12:32:04 +000021#include "llvm/Support/ScopedPrinter.h"
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +000022
Sam McCallc008af62018-10-20 15:30:37 +000023namespace clang {
24namespace clangd {
Ilya Biryukovafb55542017-05-16 14:40:30 +000025namespace {
Ilya Biryukovb0826bd2019-01-03 13:37:12 +000026class IgnoreCompletionError : public llvm::ErrorInfo<CancelledError> {
27public:
28 void log(llvm::raw_ostream &OS) const override {
29 OS << "ignored auto-triggered completion, preceding char did not match";
30 }
31 std::error_code convertToErrorCode() const override {
32 return std::make_error_code(std::errc::operation_canceled);
33 }
34};
Ilya Biryukovafb55542017-05-16 14:40:30 +000035
Ilya Biryukovcce67a32019-01-29 14:17:36 +000036/// Transforms a tweak into a code action that would apply it if executed.
37/// EXPECTS: T.prepare() was called and returned true.
38CodeAction toCodeAction(const ClangdServer::TweakRef &T, const URIForFile &File,
39 Range Selection) {
40 CodeAction CA;
41 CA.title = T.Title;
42 CA.kind = CodeAction::REFACTOR_KIND;
43 // This tweak may have an expensive second stage, we only run it if the user
44 // actually chooses it in the UI. We reply with a command that would run the
45 // corresponding tweak.
46 // FIXME: for some tweaks, computing the edits is cheap and we could send them
47 // directly.
48 CA.command.emplace();
49 CA.command->title = T.Title;
50 CA.command->command = Command::CLANGD_APPLY_TWEAK;
51 CA.command->tweakArgs.emplace();
52 CA.command->tweakArgs->file = File;
53 CA.command->tweakArgs->tweakID = T.ID;
54 CA.command->tweakArgs->selection = Selection;
55 return CA;
Simon Pilgrime9a136b2019-02-03 14:08:30 +000056}
Ilya Biryukovcce67a32019-01-29 14:17:36 +000057
Ilya Biryukov19d75602018-11-23 15:21:19 +000058void adjustSymbolKinds(llvm::MutableArrayRef<DocumentSymbol> Syms,
59 SymbolKindBitset Kinds) {
60 for (auto &S : Syms) {
61 S.kind = adjustKindToCapability(S.kind, Kinds);
62 adjustSymbolKinds(S.children, Kinds);
63 }
64}
65
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +000066SymbolKindBitset defaultSymbolKinds() {
67 SymbolKindBitset Defaults;
68 for (size_t I = SymbolKindMin; I <= static_cast<size_t>(SymbolKind::Array);
69 ++I)
70 Defaults.set(I);
71 return Defaults;
72}
73
Kadir Cetinkaya133d46f2018-09-27 17:13:07 +000074CompletionItemKindBitset defaultCompletionItemKinds() {
75 CompletionItemKindBitset Defaults;
76 for (size_t I = CompletionItemKindMin;
77 I <= static_cast<size_t>(CompletionItemKind::Reference); ++I)
78 Defaults.set(I);
79 return Defaults;
80}
81
Ilya Biryukovafb55542017-05-16 14:40:30 +000082} // namespace
83
Sam McCall2c30fbc2018-10-18 12:32:04 +000084// MessageHandler dispatches incoming LSP messages.
85// It handles cross-cutting concerns:
86// - serializes/deserializes protocol objects to JSON
87// - logging of inbound messages
88// - cancellation handling
89// - basic call tracing
Sam McCall3d0adbe2018-10-18 14:41:50 +000090// MessageHandler ensures that initialize() is called before any other handler.
Sam McCall2c30fbc2018-10-18 12:32:04 +000091class ClangdLSPServer::MessageHandler : public Transport::MessageHandler {
92public:
93 MessageHandler(ClangdLSPServer &Server) : Server(Server) {}
94
Ilya Biryukovf2001aa2019-01-07 15:45:19 +000095 bool onNotify(llvm::StringRef Method, llvm::json::Value Params) override {
Sam McCall2c30fbc2018-10-18 12:32:04 +000096 log("<-- {0}", Method);
97 if (Method == "exit")
98 return false;
Sam McCall3d0adbe2018-10-18 14:41:50 +000099 if (!Server.Server)
100 elog("Notification {0} before initialization", Method);
101 else if (Method == "$/cancelRequest")
Sam McCall2c30fbc2018-10-18 12:32:04 +0000102 onCancel(std::move(Params));
103 else if (auto Handler = Notifications.lookup(Method))
104 Handler(std::move(Params));
105 else
106 log("unhandled notification {0}", Method);
107 return true;
108 }
109
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000110 bool onCall(llvm::StringRef Method, llvm::json::Value Params,
111 llvm::json::Value ID) override {
Sam McCalle2f3a732018-10-24 14:26:26 +0000112 // Calls can be canceled by the client. Add cancellation context.
113 WithContext WithCancel(cancelableRequestContext(ID));
114 trace::Span Tracer(Method);
115 SPAN_ATTACH(Tracer, "Params", Params);
116 ReplyOnce Reply(ID, Method, &Server, Tracer.Args);
Sam McCall2c30fbc2018-10-18 12:32:04 +0000117 log("<-- {0}({1})", Method, ID);
Sam McCall3d0adbe2018-10-18 14:41:50 +0000118 if (!Server.Server && Method != "initialize") {
119 elog("Call {0} before initialization.", Method);
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000120 Reply(llvm::make_error<LSPError>("server not initialized",
121 ErrorCode::ServerNotInitialized));
Sam McCall3d0adbe2018-10-18 14:41:50 +0000122 } else if (auto Handler = Calls.lookup(Method))
Sam McCalle2f3a732018-10-24 14:26:26 +0000123 Handler(std::move(Params), std::move(Reply));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000124 else
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000125 Reply(llvm::make_error<LSPError>("method not found",
126 ErrorCode::MethodNotFound));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000127 return true;
128 }
129
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000130 bool onReply(llvm::json::Value ID,
131 llvm::Expected<llvm::json::Value> Result) override {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000132 // We ignore replies, just log them.
133 if (Result)
134 log("<-- reply({0})", ID);
135 else
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000136 log("<-- reply({0}) error: {1}", ID, llvm::toString(Result.takeError()));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000137 return true;
138 }
139
140 // Bind an LSP method name to a call.
Sam McCalle2f3a732018-10-24 14:26:26 +0000141 template <typename Param, typename Result>
Sam McCall2c30fbc2018-10-18 12:32:04 +0000142 void bind(const char *Method,
Sam McCalle2f3a732018-10-24 14:26:26 +0000143 void (ClangdLSPServer::*Handler)(const Param &, Callback<Result>)) {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000144 Calls[Method] = [Method, Handler, this](llvm::json::Value RawParams,
Sam McCalle2f3a732018-10-24 14:26:26 +0000145 ReplyOnce Reply) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000146 Param P;
Sam McCalle2f3a732018-10-24 14:26:26 +0000147 if (fromJSON(RawParams, P)) {
148 (Server.*Handler)(P, std::move(Reply));
149 } else {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000150 elog("Failed to decode {0} request.", Method);
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000151 Reply(llvm::make_error<LSPError>("failed to decode request",
152 ErrorCode::InvalidRequest));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000153 }
Sam McCall2c30fbc2018-10-18 12:32:04 +0000154 };
155 }
156
157 // Bind an LSP method name to a notification.
158 template <typename Param>
159 void bind(const char *Method,
160 void (ClangdLSPServer::*Handler)(const Param &)) {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000161 Notifications[Method] = [Method, Handler,
162 this](llvm::json::Value RawParams) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000163 Param P;
164 if (!fromJSON(RawParams, P)) {
165 elog("Failed to decode {0} request.", Method);
166 return;
167 }
168 trace::Span Tracer(Method);
169 SPAN_ATTACH(Tracer, "Params", RawParams);
170 (Server.*Handler)(P);
171 };
172 }
173
174private:
Sam McCalle2f3a732018-10-24 14:26:26 +0000175 // Function object to reply to an LSP call.
176 // Each instance must be called exactly once, otherwise:
177 // - the bug is logged, and (in debug mode) an assert will fire
178 // - if there was no reply, an error reply is sent
179 // - if there were multiple replies, only the first is sent
180 class ReplyOnce {
181 std::atomic<bool> Replied = {false};
Sam McCalld7babe42018-10-24 15:18:40 +0000182 std::chrono::steady_clock::time_point Start;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000183 llvm::json::Value ID;
Sam McCalle2f3a732018-10-24 14:26:26 +0000184 std::string Method;
185 ClangdLSPServer *Server; // Null when moved-from.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000186 llvm::json::Object *TraceArgs;
Sam McCalle2f3a732018-10-24 14:26:26 +0000187
188 public:
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000189 ReplyOnce(const llvm::json::Value &ID, llvm::StringRef Method,
190 ClangdLSPServer *Server, llvm::json::Object *TraceArgs)
Sam McCalld7babe42018-10-24 15:18:40 +0000191 : Start(std::chrono::steady_clock::now()), ID(ID), Method(Method),
192 Server(Server), TraceArgs(TraceArgs) {
Sam McCalle2f3a732018-10-24 14:26:26 +0000193 assert(Server);
194 }
195 ReplyOnce(ReplyOnce &&Other)
Sam McCalld7babe42018-10-24 15:18:40 +0000196 : Replied(Other.Replied.load()), Start(Other.Start),
197 ID(std::move(Other.ID)), Method(std::move(Other.Method)),
198 Server(Other.Server), TraceArgs(Other.TraceArgs) {
Sam McCalle2f3a732018-10-24 14:26:26 +0000199 Other.Server = nullptr;
200 }
Ilya Biryukov22fa4652019-01-03 13:28:05 +0000201 ReplyOnce &operator=(ReplyOnce &&) = delete;
Sam McCalle2f3a732018-10-24 14:26:26 +0000202 ReplyOnce(const ReplyOnce &) = delete;
Ilya Biryukov22fa4652019-01-03 13:28:05 +0000203 ReplyOnce &operator=(const ReplyOnce &) = delete;
Sam McCalle2f3a732018-10-24 14:26:26 +0000204
205 ~ReplyOnce() {
206 if (Server && !Replied) {
207 elog("No reply to message {0}({1})", Method, ID);
208 assert(false && "must reply to all calls!");
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000209 (*this)(llvm::make_error<LSPError>("server failed to reply",
210 ErrorCode::InternalError));
Sam McCalle2f3a732018-10-24 14:26:26 +0000211 }
212 }
213
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000214 void operator()(llvm::Expected<llvm::json::Value> Reply) {
Sam McCalle2f3a732018-10-24 14:26:26 +0000215 assert(Server && "moved-from!");
216 if (Replied.exchange(true)) {
217 elog("Replied twice to message {0}({1})", Method, ID);
218 assert(false && "must reply to each call only once!");
219 return;
220 }
Sam McCalld7babe42018-10-24 15:18:40 +0000221 auto Duration = std::chrono::steady_clock::now() - Start;
222 if (Reply) {
223 log("--> reply:{0}({1}) {2:ms}", Method, ID, Duration);
224 if (TraceArgs)
Sam McCalle2f3a732018-10-24 14:26:26 +0000225 (*TraceArgs)["Reply"] = *Reply;
Sam McCalld7babe42018-10-24 15:18:40 +0000226 std::lock_guard<std::mutex> Lock(Server->TranspWriter);
227 Server->Transp.reply(std::move(ID), std::move(Reply));
228 } else {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000229 llvm::Error Err = Reply.takeError();
Sam McCalld7babe42018-10-24 15:18:40 +0000230 log("--> reply:{0}({1}) {2:ms}, error: {3}", Method, ID, Duration, Err);
231 if (TraceArgs)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000232 (*TraceArgs)["Error"] = llvm::to_string(Err);
Sam McCalld7babe42018-10-24 15:18:40 +0000233 std::lock_guard<std::mutex> Lock(Server->TranspWriter);
234 Server->Transp.reply(std::move(ID), std::move(Err));
Sam McCalle2f3a732018-10-24 14:26:26 +0000235 }
Sam McCalle2f3a732018-10-24 14:26:26 +0000236 }
237 };
238
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000239 llvm::StringMap<std::function<void(llvm::json::Value)>> Notifications;
240 llvm::StringMap<std::function<void(llvm::json::Value, ReplyOnce)>> Calls;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000241
242 // Method calls may be cancelled by ID, so keep track of their state.
243 // This needs a mutex: handlers may finish on a different thread, and that's
244 // when we clean up entries in the map.
245 mutable std::mutex RequestCancelersMutex;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000246 llvm::StringMap<std::pair<Canceler, /*Cookie*/ unsigned>> RequestCancelers;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000247 unsigned NextRequestCookie = 0; // To disambiguate reused IDs, see below.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000248 void onCancel(const llvm::json::Value &Params) {
249 const llvm::json::Value *ID = nullptr;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000250 if (auto *O = Params.getAsObject())
251 ID = O->get("id");
252 if (!ID) {
253 elog("Bad cancellation request: {0}", Params);
254 return;
255 }
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000256 auto StrID = llvm::to_string(*ID);
Sam McCall2c30fbc2018-10-18 12:32:04 +0000257 std::lock_guard<std::mutex> Lock(RequestCancelersMutex);
258 auto It = RequestCancelers.find(StrID);
259 if (It != RequestCancelers.end())
260 It->second.first(); // Invoke the canceler.
261 }
262 // We run cancelable requests in a context that does two things:
263 // - allows cancellation using RequestCancelers[ID]
264 // - cleans up the entry in RequestCancelers when it's no longer needed
265 // If a client reuses an ID, the last wins and the first cannot be canceled.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000266 Context cancelableRequestContext(const llvm::json::Value &ID) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000267 auto Task = cancelableTask();
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000268 auto StrID = llvm::to_string(ID); // JSON-serialize ID for map key.
Sam McCall2c30fbc2018-10-18 12:32:04 +0000269 auto Cookie = NextRequestCookie++; // No lock, only called on main thread.
270 {
271 std::lock_guard<std::mutex> Lock(RequestCancelersMutex);
272 RequestCancelers[StrID] = {std::move(Task.second), Cookie};
273 }
274 // When the request ends, we can clean up the entry we just added.
275 // The cookie lets us check that it hasn't been overwritten due to ID
276 // reuse.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000277 return Task.first.derive(llvm::make_scope_exit([this, StrID, Cookie] {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000278 std::lock_guard<std::mutex> Lock(RequestCancelersMutex);
279 auto It = RequestCancelers.find(StrID);
280 if (It != RequestCancelers.end() && It->second.second == Cookie)
281 RequestCancelers.erase(It);
282 }));
283 }
284
285 ClangdLSPServer &Server;
286};
287
288// call(), notify(), and reply() wrap the Transport, adding logging and locking.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000289void ClangdLSPServer::call(llvm::StringRef Method, llvm::json::Value Params) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000290 auto ID = NextCallID++;
291 log("--> {0}({1})", Method, ID);
292 // We currently don't handle responses, so no need to store ID anywhere.
293 std::lock_guard<std::mutex> Lock(TranspWriter);
294 Transp.call(Method, std::move(Params), ID);
295}
296
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000297void ClangdLSPServer::notify(llvm::StringRef Method, llvm::json::Value Params) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000298 log("--> {0}", Method);
299 std::lock_guard<std::mutex> Lock(TranspWriter);
300 Transp.notify(Method, std::move(Params));
301}
302
Sam McCall2c30fbc2018-10-18 12:32:04 +0000303void ClangdLSPServer::onInitialize(const InitializeParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000304 Callback<llvm::json::Value> Reply) {
Sam McCall0d9b40f2018-10-19 15:42:23 +0000305 if (Params.rootUri && *Params.rootUri)
306 ClangdServerOpts.WorkspaceRoot = Params.rootUri->file();
307 else if (Params.rootPath && !Params.rootPath->empty())
308 ClangdServerOpts.WorkspaceRoot = *Params.rootPath;
Sam McCall3d0adbe2018-10-18 14:41:50 +0000309 if (Server)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000310 return Reply(llvm::make_error<LSPError>("server already initialized",
311 ErrorCode::InvalidRequest));
Sam McCallbc904612018-10-25 04:22:52 +0000312 if (const auto &Dir = Params.initializationOptions.compilationDatabasePath)
313 CompileCommandsDir = Dir;
Sam McCallc55d09a2018-11-02 13:09:36 +0000314 if (UseDirBasedCDB)
315 BaseCDB = llvm::make_unique<DirectoryBasedGlobalCompilationDatabase>(
316 CompileCommandsDir);
Kadir Cetinkayabe6b35d2019-01-22 09:10:20 +0000317 CDB.emplace(BaseCDB.get(), Params.initializationOptions.fallbackFlags,
318 ClangdServerOpts.ResourceDir);
Sam McCallc55d09a2018-11-02 13:09:36 +0000319 Server.emplace(*CDB, FSProvider, static_cast<DiagnosticsConsumer &>(*this),
320 ClangdServerOpts);
Sam McCallbc904612018-10-25 04:22:52 +0000321 applyConfiguration(Params.initializationOptions.ConfigSettings);
Simon Marchi88016782018-08-01 11:28:49 +0000322
Sam McCallbf6a2fc2018-10-17 07:33:42 +0000323 CCOpts.EnableSnippets = Params.capabilities.CompletionSnippets;
324 DiagOpts.EmbedFixesInDiagnostics = Params.capabilities.DiagnosticFixes;
325 DiagOpts.SendDiagnosticCategory = Params.capabilities.DiagnosticCategory;
326 if (Params.capabilities.WorkspaceSymbolKinds)
327 SupportedSymbolKinds |= *Params.capabilities.WorkspaceSymbolKinds;
328 if (Params.capabilities.CompletionItemKinds)
329 SupportedCompletionItemKinds |= *Params.capabilities.CompletionItemKinds;
330 SupportsCodeAction = Params.capabilities.CodeActionStructure;
Ilya Biryukov19d75602018-11-23 15:21:19 +0000331 SupportsHierarchicalDocumentSymbol =
332 Params.capabilities.HierarchicalDocumentSymbol;
Haojian Wub6188492018-12-20 15:39:12 +0000333 SupportFileStatus = Params.initializationOptions.FileStatus;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000334 Reply(llvm::json::Object{
Sam McCall0930ab02017-11-07 15:49:35 +0000335 {{"capabilities",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000336 llvm::json::Object{
Simon Marchi98082622018-03-26 14:41:40 +0000337 {"textDocumentSync", (int)TextDocumentSyncKind::Incremental},
Sam McCall0930ab02017-11-07 15:49:35 +0000338 {"documentFormattingProvider", true},
339 {"documentRangeFormattingProvider", true},
340 {"documentOnTypeFormattingProvider",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000341 llvm::json::Object{
Sam McCall0930ab02017-11-07 15:49:35 +0000342 {"firstTriggerCharacter", "}"},
343 {"moreTriggerCharacter", {}},
344 }},
345 {"codeActionProvider", true},
346 {"completionProvider",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000347 llvm::json::Object{
Sam McCall0930ab02017-11-07 15:49:35 +0000348 {"resolveProvider", false},
Ilya Biryukovb0826bd2019-01-03 13:37:12 +0000349 // We do extra checks for '>' and ':' in completion to only
350 // trigger on '->' and '::'.
Sam McCall0930ab02017-11-07 15:49:35 +0000351 {"triggerCharacters", {".", ">", ":"}},
352 }},
353 {"signatureHelpProvider",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000354 llvm::json::Object{
Sam McCall0930ab02017-11-07 15:49:35 +0000355 {"triggerCharacters", {"(", ","}},
356 }},
Sam McCall866ba2c2019-02-01 11:26:13 +0000357 {"declarationProvider", true},
Sam McCall0930ab02017-11-07 15:49:35 +0000358 {"definitionProvider", true},
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000359 {"documentHighlightProvider", true},
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000360 {"hoverProvider", true},
Haojian Wu345099c2017-11-09 11:30:04 +0000361 {"renameProvider", true},
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000362 {"documentSymbolProvider", true},
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000363 {"workspaceSymbolProvider", true},
Sam McCall1ad142f2018-09-05 11:53:07 +0000364 {"referencesProvider", true},
Sam McCall0930ab02017-11-07 15:49:35 +0000365 {"executeCommandProvider",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000366 llvm::json::Object{
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000367 {"commands",
368 {ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND,
369 ExecuteCommandParams::CLANGD_APPLY_TWEAK}},
Sam McCall0930ab02017-11-07 15:49:35 +0000370 }},
Kadir Cetinkaya86658022019-03-19 09:27:04 +0000371 {"typeHierarchyProvider", true},
Sam McCall0930ab02017-11-07 15:49:35 +0000372 }}}});
Ilya Biryukovafb55542017-05-16 14:40:30 +0000373}
374
Sam McCall2c30fbc2018-10-18 12:32:04 +0000375void ClangdLSPServer::onShutdown(const ShutdownParams &Params,
376 Callback<std::nullptr_t> Reply) {
Ilya Biryukov0d9b8a32017-10-25 08:45:41 +0000377 // Do essentially nothing, just say we're ready to exit.
378 ShutdownRequestReceived = true;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000379 Reply(nullptr);
Sam McCall8a5dded2017-10-12 13:29:58 +0000380}
Ilya Biryukovafb55542017-05-16 14:40:30 +0000381
Sam McCall422c8282018-11-26 16:00:11 +0000382// sync is a clangd extension: it blocks until all background work completes.
383// It blocks the calling thread, so no messages are processed until it returns!
384void ClangdLSPServer::onSync(const NoParams &Params,
385 Callback<std::nullptr_t> Reply) {
386 if (Server->blockUntilIdleForTest(/*TimeoutSeconds=*/60))
387 Reply(nullptr);
388 else
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000389 Reply(llvm::createStringError(llvm::inconvertibleErrorCode(),
390 "Not idle after a minute"));
Sam McCall422c8282018-11-26 16:00:11 +0000391}
392
Sam McCall2c30fbc2018-10-18 12:32:04 +0000393void ClangdLSPServer::onDocumentDidOpen(
394 const DidOpenTextDocumentParams &Params) {
Simon Marchi9569fd52018-03-16 14:30:42 +0000395 PathRef File = Params.textDocument.uri.file();
Ilya Biryukovb10ef472018-06-13 09:20:41 +0000396
Sam McCall2c30fbc2018-10-18 12:32:04 +0000397 const std::string &Contents = Params.textDocument.text;
Simon Marchi9569fd52018-03-16 14:30:42 +0000398
Simon Marchi98082622018-03-26 14:41:40 +0000399 DraftMgr.addDraft(File, Contents);
Ilya Biryukov652364b2018-09-26 05:48:29 +0000400 Server->addDocument(File, Contents, WantDiagnostics::Yes);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000401}
402
Sam McCall2c30fbc2018-10-18 12:32:04 +0000403void ClangdLSPServer::onDocumentDidChange(
404 const DidChangeTextDocumentParams &Params) {
Eric Liu51fed182018-02-22 18:40:39 +0000405 auto WantDiags = WantDiagnostics::Auto;
406 if (Params.wantDiagnostics.hasValue())
407 WantDiags = Params.wantDiagnostics.getValue() ? WantDiagnostics::Yes
408 : WantDiagnostics::No;
Simon Marchi9569fd52018-03-16 14:30:42 +0000409
410 PathRef File = Params.textDocument.uri.file();
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000411 llvm::Expected<std::string> Contents =
Simon Marchi98082622018-03-26 14:41:40 +0000412 DraftMgr.updateDraft(File, Params.contentChanges);
413 if (!Contents) {
414 // If this fails, we are most likely going to be not in sync anymore with
415 // the client. It is better to remove the draft and let further operations
416 // fail rather than giving wrong results.
417 DraftMgr.removeDraft(File);
Ilya Biryukov652364b2018-09-26 05:48:29 +0000418 Server->removeDocument(File);
Sam McCallbed58852018-07-11 10:35:11 +0000419 elog("Failed to update {0}: {1}", File, Contents.takeError());
Simon Marchi98082622018-03-26 14:41:40 +0000420 return;
421 }
Simon Marchi9569fd52018-03-16 14:30:42 +0000422
Ilya Biryukov652364b2018-09-26 05:48:29 +0000423 Server->addDocument(File, *Contents, WantDiags);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000424}
425
Sam McCall2c30fbc2018-10-18 12:32:04 +0000426void ClangdLSPServer::onFileEvent(const DidChangeWatchedFilesParams &Params) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000427 Server->onFileEvent(Params);
Marc-Andre Laperlebf114242017-10-02 18:00:37 +0000428}
429
Sam McCall2c30fbc2018-10-18 12:32:04 +0000430void ClangdLSPServer::onCommand(const ExecuteCommandParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000431 Callback<llvm::json::Value> Reply) {
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000432 auto ApplyEdit = [this](WorkspaceEdit WE) {
Eric Liuc5105f92018-02-16 14:15:55 +0000433 ApplyWorkspaceEditParams Edit;
434 Edit.edit = std::move(WE);
Eric Liuc5105f92018-02-16 14:15:55 +0000435 // Ideally, we would wait for the response and if there is no error, we
436 // would reply success/failure to the original RPC.
437 call("workspace/applyEdit", Edit);
438 };
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000439 if (Params.command == ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND &&
440 Params.workspaceEdit) {
441 // The flow for "apply-fix" :
442 // 1. We publish a diagnostic, including fixits
443 // 2. The user clicks on the diagnostic, the editor asks us for code actions
444 // 3. We send code actions, with the fixit embedded as context
445 // 4. The user selects the fixit, the editor asks us to apply it
446 // 5. We unwrap the changes and send them back to the editor
447 // 6. The editor applies the changes (applyEdit), and sends us a reply (but
448 // we ignore it)
449
Sam McCall2c30fbc2018-10-18 12:32:04 +0000450 Reply("Fix applied.");
Eric Liuc5105f92018-02-16 14:15:55 +0000451 ApplyEdit(*Params.workspaceEdit);
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000452 } else if (Params.command == ExecuteCommandParams::CLANGD_APPLY_TWEAK &&
453 Params.tweakArgs) {
454 auto Code = DraftMgr.getDraft(Params.tweakArgs->file.file());
455 if (!Code)
456 return Reply(llvm::createStringError(
457 llvm::inconvertibleErrorCode(),
458 "trying to apply a code action for a non-added file"));
459
460 auto Action = [ApplyEdit](decltype(Reply) Reply, URIForFile File,
461 std::string Code,
462 llvm::Expected<tooling::Replacements> R) {
463 if (!R)
464 return Reply(R.takeError());
465
466 WorkspaceEdit WE;
467 WE.changes.emplace();
468 (*WE.changes)[File.uri()] = replacementsToEdits(Code, *R);
469
470 Reply("Fix applied.");
471 ApplyEdit(std::move(WE));
472 };
473 Server->applyTweak(Params.tweakArgs->file.file(),
474 Params.tweakArgs->selection, Params.tweakArgs->tweakID,
475 Bind(Action, std::move(Reply), Params.tweakArgs->file,
476 std::move(*Code)));
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000477 } else {
478 // We should not get here because ExecuteCommandParams would not have
479 // parsed in the first place and this handler should not be called. But if
480 // more commands are added, this will be here has a safe guard.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000481 Reply(llvm::make_error<LSPError>(
482 llvm::formatv("Unsupported command \"{0}\".", Params.command).str(),
Sam McCall2c30fbc2018-10-18 12:32:04 +0000483 ErrorCode::InvalidParams));
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000484 }
485}
486
Sam McCall2c30fbc2018-10-18 12:32:04 +0000487void ClangdLSPServer::onWorkspaceSymbol(
488 const WorkspaceSymbolParams &Params,
489 Callback<std::vector<SymbolInformation>> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000490 Server->workspaceSymbols(
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000491 Params.query, CCOpts.Limit,
Sam McCall2c30fbc2018-10-18 12:32:04 +0000492 Bind(
493 [this](decltype(Reply) Reply,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000494 llvm::Expected<std::vector<SymbolInformation>> Items) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000495 if (!Items)
496 return Reply(Items.takeError());
497 for (auto &Sym : *Items)
498 Sym.kind = adjustKindToCapability(Sym.kind, SupportedSymbolKinds);
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000499
Sam McCall2c30fbc2018-10-18 12:32:04 +0000500 Reply(std::move(*Items));
501 },
502 std::move(Reply)));
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000503}
504
Sam McCall2c30fbc2018-10-18 12:32:04 +0000505void ClangdLSPServer::onRename(const RenameParams &Params,
506 Callback<WorkspaceEdit> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000507 Path File = Params.textDocument.uri.file();
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000508 llvm::Optional<std::string> 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>(
511 "onRename called for non-added file", ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000512
Ilya Biryukov652364b2018-09-26 05:48:29 +0000513 Server->rename(
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000514 File, Params.position, Params.newName,
Sam McCall2c30fbc2018-10-18 12:32:04 +0000515 Bind(
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000516 [File, Code, Params](
517 decltype(Reply) Reply,
518 llvm::Expected<std::vector<tooling::Replacement>> Replacements) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000519 if (!Replacements)
520 return Reply(Replacements.takeError());
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000521
Sam McCall2c30fbc2018-10-18 12:32:04 +0000522 // Turn the replacements into the format specified by the Language
523 // Server Protocol. Fuse them into one big JSON array.
524 std::vector<TextEdit> Edits;
525 for (const auto &R : *Replacements)
526 Edits.push_back(replacementToEdit(*Code, R));
527 WorkspaceEdit WE;
528 WE.changes = {{Params.textDocument.uri.uri(), Edits}};
529 Reply(WE);
530 },
531 std::move(Reply)));
Haojian Wu345099c2017-11-09 11:30:04 +0000532}
533
Sam McCall2c30fbc2018-10-18 12:32:04 +0000534void ClangdLSPServer::onDocumentDidClose(
535 const DidCloseTextDocumentParams &Params) {
Simon Marchi9569fd52018-03-16 14:30:42 +0000536 PathRef File = Params.textDocument.uri.file();
537 DraftMgr.removeDraft(File);
Ilya Biryukov652364b2018-09-26 05:48:29 +0000538 Server->removeDocument(File);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000539}
540
Sam McCall4db732a2017-09-30 10:08:52 +0000541void ClangdLSPServer::onDocumentOnTypeFormatting(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000542 const DocumentOnTypeFormattingParams &Params,
543 Callback<std::vector<TextEdit>> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000544 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000545 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000546 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000547 return Reply(llvm::make_error<LSPError>(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000548 "onDocumentOnTypeFormatting called for non-added file",
549 ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000550
Ilya Biryukov652364b2018-09-26 05:48:29 +0000551 auto ReplacementsOrError = Server->formatOnType(*Code, File, Params.position);
Raoul Wols212bcf82017-12-12 20:25:06 +0000552 if (ReplacementsOrError)
Sam McCall2c30fbc2018-10-18 12:32:04 +0000553 Reply(replacementsToEdits(*Code, ReplacementsOrError.get()));
Raoul Wols212bcf82017-12-12 20:25:06 +0000554 else
Sam McCall2c30fbc2018-10-18 12:32:04 +0000555 Reply(ReplacementsOrError.takeError());
Ilya Biryukovafb55542017-05-16 14:40:30 +0000556}
557
Sam McCall4db732a2017-09-30 10:08:52 +0000558void ClangdLSPServer::onDocumentRangeFormatting(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000559 const DocumentRangeFormattingParams &Params,
560 Callback<std::vector<TextEdit>> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000561 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000562 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000563 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000564 return Reply(llvm::make_error<LSPError>(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000565 "onDocumentRangeFormatting called for non-added file",
566 ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000567
Ilya Biryukov652364b2018-09-26 05:48:29 +0000568 auto ReplacementsOrError = Server->formatRange(*Code, File, Params.range);
Raoul Wols212bcf82017-12-12 20:25:06 +0000569 if (ReplacementsOrError)
Sam McCall2c30fbc2018-10-18 12:32:04 +0000570 Reply(replacementsToEdits(*Code, ReplacementsOrError.get()));
Raoul Wols212bcf82017-12-12 20:25:06 +0000571 else
Sam McCall2c30fbc2018-10-18 12:32:04 +0000572 Reply(ReplacementsOrError.takeError());
Ilya Biryukovafb55542017-05-16 14:40:30 +0000573}
574
Sam McCall2c30fbc2018-10-18 12:32:04 +0000575void ClangdLSPServer::onDocumentFormatting(
576 const DocumentFormattingParams &Params,
577 Callback<std::vector<TextEdit>> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000578 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000579 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000580 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000581 return Reply(llvm::make_error<LSPError>(
582 "onDocumentFormatting called for non-added file",
583 ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000584
Ilya Biryukov652364b2018-09-26 05:48:29 +0000585 auto ReplacementsOrError = Server->formatFile(*Code, File);
Raoul Wols212bcf82017-12-12 20:25:06 +0000586 if (ReplacementsOrError)
Sam McCall2c30fbc2018-10-18 12:32:04 +0000587 Reply(replacementsToEdits(*Code, ReplacementsOrError.get()));
Raoul Wols212bcf82017-12-12 20:25:06 +0000588 else
Sam McCall2c30fbc2018-10-18 12:32:04 +0000589 Reply(ReplacementsOrError.takeError());
Sam McCall4db732a2017-09-30 10:08:52 +0000590}
591
Ilya Biryukov19d75602018-11-23 15:21:19 +0000592/// The functions constructs a flattened view of the DocumentSymbol hierarchy.
593/// Used by the clients that do not support the hierarchical view.
594static std::vector<SymbolInformation>
595flattenSymbolHierarchy(llvm::ArrayRef<DocumentSymbol> Symbols,
596 const URIForFile &FileURI) {
597
598 std::vector<SymbolInformation> Results;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000599 std::function<void(const DocumentSymbol &, llvm::StringRef)> Process =
600 [&](const DocumentSymbol &S, llvm::Optional<llvm::StringRef> ParentName) {
Ilya Biryukov19d75602018-11-23 15:21:19 +0000601 SymbolInformation SI;
602 SI.containerName = ParentName ? "" : *ParentName;
603 SI.name = S.name;
604 SI.kind = S.kind;
605 SI.location.range = S.range;
606 SI.location.uri = FileURI;
607
608 Results.push_back(std::move(SI));
609 std::string FullName =
610 !ParentName ? S.name : (ParentName->str() + "::" + S.name);
611 for (auto &C : S.children)
612 Process(C, /*ParentName=*/FullName);
613 };
614 for (auto &S : Symbols)
615 Process(S, /*ParentName=*/"");
616 return Results;
617}
618
619void ClangdLSPServer::onDocumentSymbol(const DocumentSymbolParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000620 Callback<llvm::json::Value> Reply) {
Ilya Biryukov19d75602018-11-23 15:21:19 +0000621 URIForFile FileURI = Params.textDocument.uri;
Ilya Biryukov652364b2018-09-26 05:48:29 +0000622 Server->documentSymbols(
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000623 Params.textDocument.uri.file(),
Sam McCall2c30fbc2018-10-18 12:32:04 +0000624 Bind(
Ilya Biryukov19d75602018-11-23 15:21:19 +0000625 [this, FileURI](decltype(Reply) Reply,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000626 llvm::Expected<std::vector<DocumentSymbol>> Items) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000627 if (!Items)
628 return Reply(Items.takeError());
Ilya Biryukov19d75602018-11-23 15:21:19 +0000629 adjustSymbolKinds(*Items, SupportedSymbolKinds);
630 if (SupportsHierarchicalDocumentSymbol)
631 return Reply(std::move(*Items));
632 else
633 return Reply(flattenSymbolHierarchy(*Items, FileURI));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000634 },
635 std::move(Reply)));
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000636}
637
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000638static llvm::Optional<Command> asCommand(const CodeAction &Action) {
Sam McCall20841d42018-10-16 16:29:41 +0000639 Command Cmd;
640 if (Action.command && Action.edit)
Sam McCallc008af62018-10-20 15:30:37 +0000641 return None; // Not representable. (We never emit these anyway).
Sam McCall20841d42018-10-16 16:29:41 +0000642 if (Action.command) {
643 Cmd = *Action.command;
644 } else if (Action.edit) {
645 Cmd.command = Command::CLANGD_APPLY_FIX_COMMAND;
646 Cmd.workspaceEdit = *Action.edit;
647 } else {
Sam McCallc008af62018-10-20 15:30:37 +0000648 return None;
Sam McCall20841d42018-10-16 16:29:41 +0000649 }
650 Cmd.title = Action.title;
651 if (Action.kind && *Action.kind == CodeAction::QUICKFIX_KIND)
652 Cmd.title = "Apply fix: " + Cmd.title;
653 return Cmd;
654}
655
Sam McCall2c30fbc2018-10-18 12:32:04 +0000656void ClangdLSPServer::onCodeAction(const CodeActionParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000657 Callback<llvm::json::Value> Reply) {
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000658 URIForFile File = Params.textDocument.uri;
659 auto Code = DraftMgr.getDraft(File.file());
Sam McCall2c30fbc2018-10-18 12:32:04 +0000660 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000661 return Reply(llvm::make_error<LSPError>(
662 "onCodeAction called for non-added file", ErrorCode::InvalidParams));
Sam McCall20841d42018-10-16 16:29:41 +0000663 // We provide a code action for Fixes on the specified diagnostics.
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000664 std::vector<CodeAction> FixIts;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000665 for (const Diagnostic &D : Params.context.diagnostics) {
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000666 for (auto &F : getFixes(File.file(), D)) {
667 FixIts.push_back(toCodeAction(F, Params.textDocument.uri));
668 FixIts.back().diagnostics = {D};
Sam McCalldd0566b2017-11-06 15:40:30 +0000669 }
Ilya Biryukovafb55542017-05-16 14:40:30 +0000670 }
Sam McCall20841d42018-10-16 16:29:41 +0000671
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000672 // Now enumerate the semantic code actions.
673 auto ConsumeActions =
674 [this](decltype(Reply) Reply, URIForFile File, std::string Code,
675 Range Selection, std::vector<CodeAction> FixIts,
676 llvm::Expected<std::vector<ClangdServer::TweakRef>> Tweaks) {
Ilya Biryukovc6ed7782019-01-30 14:24:17 +0000677 if (!Tweaks)
678 return Reply(Tweaks.takeError());
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000679
680 std::vector<CodeAction> Actions = std::move(FixIts);
681 Actions.reserve(Actions.size() + Tweaks->size());
682 for (const auto &T : *Tweaks)
683 Actions.push_back(toCodeAction(T, File, Selection));
684
685 if (SupportsCodeAction)
686 return Reply(llvm::json::Array(Actions));
687 std::vector<Command> Commands;
688 for (const auto &Action : Actions) {
689 if (auto Command = asCommand(Action))
690 Commands.push_back(std::move(*Command));
691 }
692 return Reply(llvm::json::Array(Commands));
693 };
694
695 Server->enumerateTweaks(File.file(), Params.range,
Ilya Biryukovc9409c62019-01-30 09:39:01 +0000696 Bind(ConsumeActions, std::move(Reply), File,
697 std::move(*Code), Params.range,
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000698 std::move(FixIts)));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000699}
700
Ilya Biryukovb0826bd2019-01-03 13:37:12 +0000701void ClangdLSPServer::onCompletion(const CompletionParams &Params,
Sam McCall2c30fbc2018-10-18 12:32:04 +0000702 Callback<CompletionList> Reply) {
Ilya Biryukovb0826bd2019-01-03 13:37:12 +0000703 if (!shouldRunCompletion(Params))
704 return Reply(llvm::make_error<IgnoreCompletionError>());
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000705 Server->codeComplete(Params.textDocument.uri.file(), Params.position, CCOpts,
706 Bind(
707 [this](decltype(Reply) Reply,
708 llvm::Expected<CodeCompleteResult> List) {
709 if (!List)
710 return Reply(List.takeError());
711 CompletionList LSPList;
712 LSPList.isIncomplete = List->HasMore;
713 for (const auto &R : List->Completions) {
714 CompletionItem C = R.render(CCOpts);
715 C.kind = adjustKindToCapability(
716 C.kind, SupportedCompletionItemKinds);
717 LSPList.items.push_back(std::move(C));
718 }
719 return Reply(std::move(LSPList));
720 },
721 std::move(Reply)));
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000722}
723
Sam McCall2c30fbc2018-10-18 12:32:04 +0000724void ClangdLSPServer::onSignatureHelp(const TextDocumentPositionParams &Params,
725 Callback<SignatureHelp> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000726 Server->signatureHelp(Params.textDocument.uri.file(), Params.position,
Sam McCall2c30fbc2018-10-18 12:32:04 +0000727 std::move(Reply));
Ilya Biryukov652364b2018-09-26 05:48:29 +0000728}
729
Sam McCall0dbab7f2019-02-02 05:56:00 +0000730// Go to definition has a toggle function: if def and decl are distinct, then
731// the first press gives you the def, the second gives you the matching def.
732// getToggle() returns the counterpart location that under the cursor.
733//
734// We return the toggled location alone (ignoring other symbols) to encourage
735// editors to "bounce" quickly between locations, without showing a menu.
736static Location *getToggle(const TextDocumentPositionParams &Point,
737 LocatedSymbol &Sym) {
738 // Toggle only makes sense with two distinct locations.
739 if (!Sym.Definition || *Sym.Definition == Sym.PreferredDeclaration)
740 return nullptr;
741 if (Sym.Definition->uri.file() == Point.textDocument.uri.file() &&
742 Sym.Definition->range.contains(Point.position))
743 return &Sym.PreferredDeclaration;
744 if (Sym.PreferredDeclaration.uri.file() == Point.textDocument.uri.file() &&
745 Sym.PreferredDeclaration.range.contains(Point.position))
746 return &*Sym.Definition;
747 return nullptr;
748}
749
Sam McCall2c30fbc2018-10-18 12:32:04 +0000750void ClangdLSPServer::onGoToDefinition(const TextDocumentPositionParams &Params,
751 Callback<std::vector<Location>> Reply) {
Sam McCall866ba2c2019-02-01 11:26:13 +0000752 Server->locateSymbolAt(
753 Params.textDocument.uri.file(), Params.position,
754 Bind(
Sam McCall0dbab7f2019-02-02 05:56:00 +0000755 [&, Params](decltype(Reply) Reply,
756 llvm::Expected<std::vector<LocatedSymbol>> Symbols) {
Sam McCall866ba2c2019-02-01 11:26:13 +0000757 if (!Symbols)
758 return Reply(Symbols.takeError());
759 std::vector<Location> Defs;
Sam McCall0dbab7f2019-02-02 05:56:00 +0000760 for (auto &S : *Symbols) {
761 if (Location *Toggle = getToggle(Params, S))
762 return Reply(std::vector<Location>{std::move(*Toggle)});
Sam McCall866ba2c2019-02-01 11:26:13 +0000763 Defs.push_back(S.Definition.getValueOr(S.PreferredDeclaration));
Sam McCall0dbab7f2019-02-02 05:56:00 +0000764 }
Sam McCall866ba2c2019-02-01 11:26:13 +0000765 Reply(std::move(Defs));
766 },
767 std::move(Reply)));
768}
769
770void ClangdLSPServer::onGoToDeclaration(
771 const TextDocumentPositionParams &Params,
772 Callback<std::vector<Location>> Reply) {
773 Server->locateSymbolAt(
774 Params.textDocument.uri.file(), Params.position,
775 Bind(
Sam McCall0dbab7f2019-02-02 05:56:00 +0000776 [&, Params](decltype(Reply) Reply,
777 llvm::Expected<std::vector<LocatedSymbol>> Symbols) {
Sam McCall866ba2c2019-02-01 11:26:13 +0000778 if (!Symbols)
779 return Reply(Symbols.takeError());
780 std::vector<Location> Decls;
Sam McCall0dbab7f2019-02-02 05:56:00 +0000781 for (auto &S : *Symbols) {
782 if (Location *Toggle = getToggle(Params, S))
783 return Reply(std::vector<Location>{std::move(*Toggle)});
784 Decls.push_back(std::move(S.PreferredDeclaration));
785 }
Sam McCall866ba2c2019-02-01 11:26:13 +0000786 Reply(std::move(Decls));
787 },
788 std::move(Reply)));
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000789}
790
Sam McCall2c30fbc2018-10-18 12:32:04 +0000791void ClangdLSPServer::onSwitchSourceHeader(const TextDocumentIdentifier &Params,
792 Callback<std::string> Reply) {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000793 llvm::Optional<Path> Result = Server->switchSourceHeader(Params.uri.file());
Sam McCall2c30fbc2018-10-18 12:32:04 +0000794 Reply(Result ? URI::createFile(*Result).toString() : "");
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000795}
796
Sam McCall2c30fbc2018-10-18 12:32:04 +0000797void ClangdLSPServer::onDocumentHighlight(
798 const TextDocumentPositionParams &Params,
799 Callback<std::vector<DocumentHighlight>> Reply) {
800 Server->findDocumentHighlights(Params.textDocument.uri.file(),
801 Params.position, std::move(Reply));
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000802}
803
Sam McCall2c30fbc2018-10-18 12:32:04 +0000804void ClangdLSPServer::onHover(const TextDocumentPositionParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000805 Callback<llvm::Optional<Hover>> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000806 Server->findHover(Params.textDocument.uri.file(), Params.position,
Sam McCall2c30fbc2018-10-18 12:32:04 +0000807 std::move(Reply));
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000808}
809
Kadir Cetinkaya86658022019-03-19 09:27:04 +0000810void ClangdLSPServer::onTypeHierarchy(
811 const TypeHierarchyParams &Params,
812 Callback<Optional<TypeHierarchyItem>> Reply) {
813 Server->typeHierarchy(Params.textDocument.uri.file(), Params.position,
814 Params.resolve, Params.direction, std::move(Reply));
815}
816
Simon Marchi88016782018-08-01 11:28:49 +0000817void ClangdLSPServer::applyConfiguration(
Sam McCallbc904612018-10-25 04:22:52 +0000818 const ConfigurationSettings &Settings) {
Simon Marchiabeed662018-10-16 15:55:03 +0000819 // Per-file update to the compilation database.
Sam McCallbc904612018-10-25 04:22:52 +0000820 bool ShouldReparseOpenFiles = false;
821 for (auto &Entry : Settings.compilationDatabaseChanges) {
822 /// The opened files need to be reparsed only when some existing
823 /// entries are changed.
824 PathRef File = Entry.first;
Sam McCallc55d09a2018-11-02 13:09:36 +0000825 auto Old = CDB->getCompileCommand(File);
826 auto New =
827 tooling::CompileCommand(std::move(Entry.second.workingDirectory), File,
828 std::move(Entry.second.compilationCommand),
829 /*Output=*/"");
Sam McCall6980edb2018-11-02 14:07:51 +0000830 if (Old != New) {
Sam McCallc55d09a2018-11-02 13:09:36 +0000831 CDB->setCompileCommand(File, std::move(New));
Sam McCall6980edb2018-11-02 14:07:51 +0000832 ShouldReparseOpenFiles = true;
833 }
Alex Lorenzf8087862018-08-01 17:39:29 +0000834 }
Sam McCallbc904612018-10-25 04:22:52 +0000835 if (ShouldReparseOpenFiles)
836 reparseOpenedFiles();
Simon Marchi5178f922018-02-22 14:00:39 +0000837}
838
Simon Marchi88016782018-08-01 11:28:49 +0000839// FIXME: This function needs to be properly tested.
840void ClangdLSPServer::onChangeConfiguration(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000841 const DidChangeConfigurationParams &Params) {
Simon Marchi88016782018-08-01 11:28:49 +0000842 applyConfiguration(Params.settings);
843}
844
Sam McCall2c30fbc2018-10-18 12:32:04 +0000845void ClangdLSPServer::onReference(const ReferenceParams &Params,
846 Callback<std::vector<Location>> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000847 Server->findReferences(Params.textDocument.uri.file(), Params.position,
Haojian Wuc34f0222019-01-14 18:11:09 +0000848 CCOpts.Limit, std::move(Reply));
Sam McCall1ad142f2018-09-05 11:53:07 +0000849}
850
Jan Korousb4067012018-11-27 16:40:46 +0000851void ClangdLSPServer::onSymbolInfo(const TextDocumentPositionParams &Params,
852 Callback<std::vector<SymbolDetails>> Reply) {
853 Server->symbolInfo(Params.textDocument.uri.file(), Params.position,
854 std::move(Reply));
855}
856
Sam McCalldc8f3cf2018-10-17 07:32:05 +0000857ClangdLSPServer::ClangdLSPServer(class Transport &Transp,
Haojian Wu1ca0c582019-01-22 09:39:05 +0000858 const FileSystemProvider &FSProvider,
Sam McCalladccab62017-11-23 16:58:22 +0000859 const clangd::CodeCompleteOptions &CCOpts,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000860 llvm::Optional<Path> CompileCommandsDir,
Sam McCallc55d09a2018-11-02 13:09:36 +0000861 bool UseDirBasedCDB,
Sam McCall7363a2f2018-03-05 17:28:54 +0000862 const ClangdServer::Options &Opts)
Haojian Wu1ca0c582019-01-22 09:39:05 +0000863 : Transp(Transp), MsgHandler(new MessageHandler(*this)),
864 FSProvider(FSProvider), CCOpts(CCOpts),
Sam McCalld1c9d112018-10-23 14:19:54 +0000865 SupportedSymbolKinds(defaultSymbolKinds()),
Kadir Cetinkaya133d46f2018-09-27 17:13:07 +0000866 SupportedCompletionItemKinds(defaultCompletionItemKinds()),
Sam McCallc55d09a2018-11-02 13:09:36 +0000867 UseDirBasedCDB(UseDirBasedCDB),
Sam McCall4b86bb02018-10-25 02:22:53 +0000868 CompileCommandsDir(std::move(CompileCommandsDir)),
869 ClangdServerOpts(Opts) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000870 // clang-format off
871 MsgHandler->bind("initialize", &ClangdLSPServer::onInitialize);
872 MsgHandler->bind("shutdown", &ClangdLSPServer::onShutdown);
Sam McCall422c8282018-11-26 16:00:11 +0000873 MsgHandler->bind("sync", &ClangdLSPServer::onSync);
Sam McCall2c30fbc2018-10-18 12:32:04 +0000874 MsgHandler->bind("textDocument/rangeFormatting", &ClangdLSPServer::onDocumentRangeFormatting);
875 MsgHandler->bind("textDocument/onTypeFormatting", &ClangdLSPServer::onDocumentOnTypeFormatting);
876 MsgHandler->bind("textDocument/formatting", &ClangdLSPServer::onDocumentFormatting);
877 MsgHandler->bind("textDocument/codeAction", &ClangdLSPServer::onCodeAction);
878 MsgHandler->bind("textDocument/completion", &ClangdLSPServer::onCompletion);
879 MsgHandler->bind("textDocument/signatureHelp", &ClangdLSPServer::onSignatureHelp);
880 MsgHandler->bind("textDocument/definition", &ClangdLSPServer::onGoToDefinition);
Sam McCall866ba2c2019-02-01 11:26:13 +0000881 MsgHandler->bind("textDocument/declaration", &ClangdLSPServer::onGoToDeclaration);
Sam McCall2c30fbc2018-10-18 12:32:04 +0000882 MsgHandler->bind("textDocument/references", &ClangdLSPServer::onReference);
883 MsgHandler->bind("textDocument/switchSourceHeader", &ClangdLSPServer::onSwitchSourceHeader);
884 MsgHandler->bind("textDocument/rename", &ClangdLSPServer::onRename);
885 MsgHandler->bind("textDocument/hover", &ClangdLSPServer::onHover);
886 MsgHandler->bind("textDocument/documentSymbol", &ClangdLSPServer::onDocumentSymbol);
887 MsgHandler->bind("workspace/executeCommand", &ClangdLSPServer::onCommand);
888 MsgHandler->bind("textDocument/documentHighlight", &ClangdLSPServer::onDocumentHighlight);
889 MsgHandler->bind("workspace/symbol", &ClangdLSPServer::onWorkspaceSymbol);
890 MsgHandler->bind("textDocument/didOpen", &ClangdLSPServer::onDocumentDidOpen);
891 MsgHandler->bind("textDocument/didClose", &ClangdLSPServer::onDocumentDidClose);
892 MsgHandler->bind("textDocument/didChange", &ClangdLSPServer::onDocumentDidChange);
893 MsgHandler->bind("workspace/didChangeWatchedFiles", &ClangdLSPServer::onFileEvent);
894 MsgHandler->bind("workspace/didChangeConfiguration", &ClangdLSPServer::onChangeConfiguration);
Jan Korousb4067012018-11-27 16:40:46 +0000895 MsgHandler->bind("textDocument/symbolInfo", &ClangdLSPServer::onSymbolInfo);
Kadir Cetinkaya86658022019-03-19 09:27:04 +0000896 MsgHandler->bind("textDocument/typeHierarchy", &ClangdLSPServer::onTypeHierarchy);
Sam McCall2c30fbc2018-10-18 12:32:04 +0000897 // clang-format on
898}
899
900ClangdLSPServer::~ClangdLSPServer() = default;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000901
Sam McCalldc8f3cf2018-10-17 07:32:05 +0000902bool ClangdLSPServer::run() {
Ilya Biryukovafb55542017-05-16 14:40:30 +0000903 // Run the Language Server loop.
Sam McCalldc8f3cf2018-10-17 07:32:05 +0000904 bool CleanExit = true;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000905 if (auto Err = Transp.loop(*MsgHandler)) {
Sam McCalldc8f3cf2018-10-17 07:32:05 +0000906 elog("Transport error: {0}", std::move(Err));
907 CleanExit = false;
908 }
Ilya Biryukovafb55542017-05-16 14:40:30 +0000909
Ilya Biryukov652364b2018-09-26 05:48:29 +0000910 // Destroy ClangdServer to ensure all worker threads finish.
911 Server.reset();
Sam McCalldc8f3cf2018-10-17 07:32:05 +0000912 return CleanExit && ShutdownRequestReceived;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000913}
914
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000915std::vector<Fix> ClangdLSPServer::getFixes(llvm::StringRef File,
Ilya Biryukov71028b82018-03-12 15:28:22 +0000916 const clangd::Diagnostic &D) {
Ilya Biryukov38d79772017-05-16 09:38:59 +0000917 std::lock_guard<std::mutex> Lock(FixItsMutex);
918 auto DiagToFixItsIter = FixItsMap.find(File);
919 if (DiagToFixItsIter == FixItsMap.end())
920 return {};
921
922 const auto &DiagToFixItsMap = DiagToFixItsIter->second;
923 auto FixItsIter = DiagToFixItsMap.find(D);
924 if (FixItsIter == DiagToFixItsMap.end())
925 return {};
926
927 return FixItsIter->second;
928}
929
Ilya Biryukovb0826bd2019-01-03 13:37:12 +0000930bool ClangdLSPServer::shouldRunCompletion(
931 const CompletionParams &Params) const {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000932 llvm::StringRef Trigger = Params.context.triggerCharacter;
Ilya Biryukovb0826bd2019-01-03 13:37:12 +0000933 if (Params.context.triggerKind != CompletionTriggerKind::TriggerCharacter ||
934 (Trigger != ">" && Trigger != ":"))
935 return true;
936
937 auto Code = DraftMgr.getDraft(Params.textDocument.uri.file());
938 if (!Code)
939 return true; // completion code will log the error for untracked doc.
940
941 // A completion request is sent when the user types '>' or ':', but we only
942 // want to trigger on '->' and '::'. We check the preceeding character to make
943 // sure it matches what we expected.
944 // Running the lexer here would be more robust (e.g. we can detect comments
945 // and avoid triggering completion there), but we choose to err on the side
946 // of simplicity here.
947 auto Offset = positionToOffset(*Code, Params.position,
948 /*AllowColumnsBeyondLineLength=*/false);
949 if (!Offset) {
950 vlog("could not convert position '{0}' to offset for file '{1}'",
951 Params.position, Params.textDocument.uri.file());
952 return true;
953 }
954 if (*Offset < 2)
955 return false;
956
957 if (Trigger == ">")
958 return (*Code)[*Offset - 2] == '-'; // trigger only on '->'.
959 if (Trigger == ":")
960 return (*Code)[*Offset - 2] == ':'; // trigger only on '::'.
961 assert(false && "unhandled trigger character");
962 return true;
963}
964
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000965void ClangdLSPServer::onDiagnosticsReady(PathRef File,
966 std::vector<Diag> Diagnostics) {
Eric Liu4d814a92018-11-28 10:30:42 +0000967 auto URI = URIForFile::canonicalize(File, /*TUPath=*/File);
Sam McCall16e70702018-10-24 07:59:38 +0000968 std::vector<Diagnostic> LSPDiagnostics;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000969 DiagnosticToReplacementMap LocalFixIts; // Temporary storage
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000970 for (auto &Diag : Diagnostics) {
Sam McCall16e70702018-10-24 07:59:38 +0000971 toLSPDiags(Diag, URI, DiagOpts,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000972 [&](clangd::Diagnostic Diag, llvm::ArrayRef<Fix> Fixes) {
Sam McCall16e70702018-10-24 07:59:38 +0000973 auto &FixItsForDiagnostic = LocalFixIts[Diag];
974 llvm::copy(Fixes, std::back_inserter(FixItsForDiagnostic));
975 LSPDiagnostics.push_back(std::move(Diag));
976 });
Ilya Biryukov38d79772017-05-16 09:38:59 +0000977 }
978
979 // Cache FixIts
980 {
981 // FIXME(ibiryukov): should be deleted when documents are removed
982 std::lock_guard<std::mutex> Lock(FixItsMutex);
983 FixItsMap[File] = LocalFixIts;
984 }
985
986 // Publish diagnostics.
Sam McCall2c30fbc2018-10-18 12:32:04 +0000987 notify("textDocument/publishDiagnostics",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000988 llvm::json::Object{
Sam McCall16e70702018-10-24 07:59:38 +0000989 {"uri", URI},
990 {"diagnostics", std::move(LSPDiagnostics)},
Sam McCall2c30fbc2018-10-18 12:32:04 +0000991 });
Ilya Biryukov38d79772017-05-16 09:38:59 +0000992}
Simon Marchi9569fd52018-03-16 14:30:42 +0000993
Haojian Wub6188492018-12-20 15:39:12 +0000994void ClangdLSPServer::onFileUpdated(PathRef File, const TUStatus &Status) {
995 if (!SupportFileStatus)
996 return;
997 // FIXME: we don't emit "BuildingFile" and `RunningAction`, as these
998 // two statuses are running faster in practice, which leads the UI constantly
999 // changing, and doesn't provide much value. We may want to emit status at a
1000 // reasonable time interval (e.g. 0.5s).
1001 if (Status.Action.S == TUAction::BuildingFile ||
1002 Status.Action.S == TUAction::RunningAction)
1003 return;
1004 notify("textDocument/clangd.fileStatus", Status.render(File));
1005}
1006
Simon Marchi9569fd52018-03-16 14:30:42 +00001007void ClangdLSPServer::reparseOpenedFiles() {
1008 for (const Path &FilePath : DraftMgr.getActiveFiles())
Ilya Biryukov652364b2018-09-26 05:48:29 +00001009 Server->addDocument(FilePath, *DraftMgr.getDraft(FilePath),
1010 WantDiagnostics::Auto);
Simon Marchi9569fd52018-03-16 14:30:42 +00001011}
Alex Lorenzf8087862018-08-01 17:39:29 +00001012
Sam McCallc008af62018-10-20 15:30:37 +00001013} // namespace clangd
1014} // namespace clang