blob: 08a0810d17dafa7a175c8416e7e7a72a8f449d35 [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 McCalld20d7982018-07-09 14:25:59 +000021using namespace llvm;
Sam McCallc008af62018-10-20 15:30:37 +000022namespace clang {
23namespace clangd {
Ilya Biryukovafb55542017-05-16 14:40:30 +000024namespace {
Ilya Biryukovb0826bd2019-01-03 13:37:12 +000025class IgnoreCompletionError : public llvm::ErrorInfo<CancelledError> {
26public:
27 void log(llvm::raw_ostream &OS) const override {
28 OS << "ignored auto-triggered completion, preceding char did not match";
29 }
30 std::error_code convertToErrorCode() const override {
31 return std::make_error_code(std::errc::operation_canceled);
32 }
33};
Ilya Biryukovafb55542017-05-16 14:40:30 +000034
Ilya Biryukov19d75602018-11-23 15:21:19 +000035void adjustSymbolKinds(llvm::MutableArrayRef<DocumentSymbol> Syms,
36 SymbolKindBitset Kinds) {
37 for (auto &S : Syms) {
38 S.kind = adjustKindToCapability(S.kind, Kinds);
39 adjustSymbolKinds(S.children, Kinds);
40 }
41}
42
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +000043SymbolKindBitset defaultSymbolKinds() {
44 SymbolKindBitset Defaults;
45 for (size_t I = SymbolKindMin; I <= static_cast<size_t>(SymbolKind::Array);
46 ++I)
47 Defaults.set(I);
48 return Defaults;
49}
50
Kadir Cetinkaya133d46f2018-09-27 17:13:07 +000051CompletionItemKindBitset defaultCompletionItemKinds() {
52 CompletionItemKindBitset Defaults;
53 for (size_t I = CompletionItemKindMin;
54 I <= static_cast<size_t>(CompletionItemKind::Reference); ++I)
55 Defaults.set(I);
56 return Defaults;
57}
58
Ilya Biryukovafb55542017-05-16 14:40:30 +000059} // namespace
60
Sam McCall2c30fbc2018-10-18 12:32:04 +000061// MessageHandler dispatches incoming LSP messages.
62// It handles cross-cutting concerns:
63// - serializes/deserializes protocol objects to JSON
64// - logging of inbound messages
65// - cancellation handling
66// - basic call tracing
Sam McCall3d0adbe2018-10-18 14:41:50 +000067// MessageHandler ensures that initialize() is called before any other handler.
Sam McCall2c30fbc2018-10-18 12:32:04 +000068class ClangdLSPServer::MessageHandler : public Transport::MessageHandler {
69public:
70 MessageHandler(ClangdLSPServer &Server) : Server(Server) {}
71
72 bool onNotify(StringRef Method, json::Value Params) override {
73 log("<-- {0}", Method);
74 if (Method == "exit")
75 return false;
Sam McCall3d0adbe2018-10-18 14:41:50 +000076 if (!Server.Server)
77 elog("Notification {0} before initialization", Method);
78 else if (Method == "$/cancelRequest")
Sam McCall2c30fbc2018-10-18 12:32:04 +000079 onCancel(std::move(Params));
80 else if (auto Handler = Notifications.lookup(Method))
81 Handler(std::move(Params));
82 else
83 log("unhandled notification {0}", Method);
84 return true;
85 }
86
87 bool onCall(StringRef Method, json::Value Params, 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);
Sam McCalle2f3a732018-10-24 14:26:26 +000096 Reply(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
Sam McCalle2f3a732018-10-24 14:26:26 +0000101 Reply(
102 make_error<LSPError>("method not found", ErrorCode::MethodNotFound));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000103 return true;
104 }
105
106 bool onReply(json::Value ID, Expected<json::Value> Result) override {
107 // We ignore replies, just log them.
108 if (Result)
109 log("<-- reply({0})", ID);
110 else
Sam McCallc008af62018-10-20 15:30:37 +0000111 log("<-- reply({0}) error: {1}", ID, toString(Result.takeError()));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000112 return true;
113 }
114
115 // Bind an LSP method name to a call.
Sam McCalle2f3a732018-10-24 14:26:26 +0000116 template <typename Param, typename Result>
Sam McCall2c30fbc2018-10-18 12:32:04 +0000117 void bind(const char *Method,
Sam McCalle2f3a732018-10-24 14:26:26 +0000118 void (ClangdLSPServer::*Handler)(const Param &, Callback<Result>)) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000119 Calls[Method] = [Method, Handler, this](json::Value RawParams,
Sam McCalle2f3a732018-10-24 14:26:26 +0000120 ReplyOnce Reply) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000121 Param P;
Sam McCalle2f3a732018-10-24 14:26:26 +0000122 if (fromJSON(RawParams, P)) {
123 (Server.*Handler)(P, std::move(Reply));
124 } else {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000125 elog("Failed to decode {0} request.", Method);
Sam McCalle2f3a732018-10-24 14:26:26 +0000126 Reply(make_error<LSPError>("failed to decode request",
127 ErrorCode::InvalidRequest));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000128 }
Sam McCall2c30fbc2018-10-18 12:32:04 +0000129 };
130 }
131
132 // Bind an LSP method name to a notification.
133 template <typename Param>
134 void bind(const char *Method,
135 void (ClangdLSPServer::*Handler)(const Param &)) {
136 Notifications[Method] = [Method, Handler, this](json::Value RawParams) {
137 Param P;
138 if (!fromJSON(RawParams, P)) {
139 elog("Failed to decode {0} request.", Method);
140 return;
141 }
142 trace::Span Tracer(Method);
143 SPAN_ATTACH(Tracer, "Params", RawParams);
144 (Server.*Handler)(P);
145 };
146 }
147
148private:
Sam McCalle2f3a732018-10-24 14:26:26 +0000149 // Function object to reply to an LSP call.
150 // Each instance must be called exactly once, otherwise:
151 // - the bug is logged, and (in debug mode) an assert will fire
152 // - if there was no reply, an error reply is sent
153 // - if there were multiple replies, only the first is sent
154 class ReplyOnce {
155 std::atomic<bool> Replied = {false};
Sam McCalld7babe42018-10-24 15:18:40 +0000156 std::chrono::steady_clock::time_point Start;
Sam McCalle2f3a732018-10-24 14:26:26 +0000157 json::Value ID;
158 std::string Method;
159 ClangdLSPServer *Server; // Null when moved-from.
160 json::Object *TraceArgs;
161
162 public:
163 ReplyOnce(const json::Value &ID, StringRef Method, ClangdLSPServer *Server,
164 json::Object *TraceArgs)
Sam McCalld7babe42018-10-24 15:18:40 +0000165 : Start(std::chrono::steady_clock::now()), ID(ID), Method(Method),
166 Server(Server), TraceArgs(TraceArgs) {
Sam McCalle2f3a732018-10-24 14:26:26 +0000167 assert(Server);
168 }
169 ReplyOnce(ReplyOnce &&Other)
Sam McCalld7babe42018-10-24 15:18:40 +0000170 : Replied(Other.Replied.load()), Start(Other.Start),
171 ID(std::move(Other.ID)), Method(std::move(Other.Method)),
172 Server(Other.Server), TraceArgs(Other.TraceArgs) {
Sam McCalle2f3a732018-10-24 14:26:26 +0000173 Other.Server = nullptr;
174 }
Ilya Biryukov22fa4652019-01-03 13:28:05 +0000175 ReplyOnce &operator=(ReplyOnce &&) = delete;
Sam McCalle2f3a732018-10-24 14:26:26 +0000176 ReplyOnce(const ReplyOnce &) = delete;
Ilya Biryukov22fa4652019-01-03 13:28:05 +0000177 ReplyOnce &operator=(const ReplyOnce &) = delete;
Sam McCalle2f3a732018-10-24 14:26:26 +0000178
179 ~ReplyOnce() {
180 if (Server && !Replied) {
181 elog("No reply to message {0}({1})", Method, ID);
182 assert(false && "must reply to all calls!");
183 (*this)(make_error<LSPError>("server failed to reply",
184 ErrorCode::InternalError));
185 }
186 }
187
188 void operator()(Expected<json::Value> Reply) {
189 assert(Server && "moved-from!");
190 if (Replied.exchange(true)) {
191 elog("Replied twice to message {0}({1})", Method, ID);
192 assert(false && "must reply to each call only once!");
193 return;
194 }
Sam McCalld7babe42018-10-24 15:18:40 +0000195 auto Duration = std::chrono::steady_clock::now() - Start;
196 if (Reply) {
197 log("--> reply:{0}({1}) {2:ms}", Method, ID, Duration);
198 if (TraceArgs)
Sam McCalle2f3a732018-10-24 14:26:26 +0000199 (*TraceArgs)["Reply"] = *Reply;
Sam McCalld7babe42018-10-24 15:18:40 +0000200 std::lock_guard<std::mutex> Lock(Server->TranspWriter);
201 Server->Transp.reply(std::move(ID), std::move(Reply));
202 } else {
203 Error Err = Reply.takeError();
204 log("--> reply:{0}({1}) {2:ms}, error: {3}", Method, ID, Duration, Err);
205 if (TraceArgs)
Sam McCalle2f3a732018-10-24 14:26:26 +0000206 (*TraceArgs)["Error"] = to_string(Err);
Sam McCalld7babe42018-10-24 15:18:40 +0000207 std::lock_guard<std::mutex> Lock(Server->TranspWriter);
208 Server->Transp.reply(std::move(ID), std::move(Err));
Sam McCalle2f3a732018-10-24 14:26:26 +0000209 }
Sam McCalle2f3a732018-10-24 14:26:26 +0000210 }
211 };
212
Sam McCallc008af62018-10-20 15:30:37 +0000213 StringMap<std::function<void(json::Value)>> Notifications;
Sam McCalle2f3a732018-10-24 14:26:26 +0000214 StringMap<std::function<void(json::Value, ReplyOnce)>> Calls;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000215
216 // Method calls may be cancelled by ID, so keep track of their state.
217 // This needs a mutex: handlers may finish on a different thread, and that's
218 // when we clean up entries in the map.
219 mutable std::mutex RequestCancelersMutex;
Sam McCallc008af62018-10-20 15:30:37 +0000220 StringMap<std::pair<Canceler, /*Cookie*/ unsigned>> RequestCancelers;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000221 unsigned NextRequestCookie = 0; // To disambiguate reused IDs, see below.
Sam McCallc008af62018-10-20 15:30:37 +0000222 void onCancel(const json::Value &Params) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000223 const json::Value *ID = nullptr;
224 if (auto *O = Params.getAsObject())
225 ID = O->get("id");
226 if (!ID) {
227 elog("Bad cancellation request: {0}", Params);
228 return;
229 }
Sam McCallc008af62018-10-20 15:30:37 +0000230 auto StrID = to_string(*ID);
Sam McCall2c30fbc2018-10-18 12:32:04 +0000231 std::lock_guard<std::mutex> Lock(RequestCancelersMutex);
232 auto It = RequestCancelers.find(StrID);
233 if (It != RequestCancelers.end())
234 It->second.first(); // Invoke the canceler.
235 }
236 // We run cancelable requests in a context that does two things:
237 // - allows cancellation using RequestCancelers[ID]
238 // - cleans up the entry in RequestCancelers when it's no longer needed
239 // If a client reuses an ID, the last wins and the first cannot be canceled.
240 Context cancelableRequestContext(const json::Value &ID) {
241 auto Task = cancelableTask();
Sam McCallc008af62018-10-20 15:30:37 +0000242 auto StrID = to_string(ID); // JSON-serialize ID for map key.
Sam McCall2c30fbc2018-10-18 12:32:04 +0000243 auto Cookie = NextRequestCookie++; // No lock, only called on main thread.
244 {
245 std::lock_guard<std::mutex> Lock(RequestCancelersMutex);
246 RequestCancelers[StrID] = {std::move(Task.second), Cookie};
247 }
248 // When the request ends, we can clean up the entry we just added.
249 // The cookie lets us check that it hasn't been overwritten due to ID
250 // reuse.
251 return Task.first.derive(make_scope_exit([this, StrID, Cookie] {
252 std::lock_guard<std::mutex> Lock(RequestCancelersMutex);
253 auto It = RequestCancelers.find(StrID);
254 if (It != RequestCancelers.end() && It->second.second == Cookie)
255 RequestCancelers.erase(It);
256 }));
257 }
258
259 ClangdLSPServer &Server;
260};
261
262// call(), notify(), and reply() wrap the Transport, adding logging and locking.
263void ClangdLSPServer::call(StringRef Method, json::Value Params) {
264 auto ID = NextCallID++;
265 log("--> {0}({1})", Method, ID);
266 // We currently don't handle responses, so no need to store ID anywhere.
267 std::lock_guard<std::mutex> Lock(TranspWriter);
268 Transp.call(Method, std::move(Params), ID);
269}
270
271void ClangdLSPServer::notify(StringRef Method, json::Value Params) {
272 log("--> {0}", Method);
273 std::lock_guard<std::mutex> Lock(TranspWriter);
274 Transp.notify(Method, std::move(Params));
275}
276
Sam McCall2c30fbc2018-10-18 12:32:04 +0000277void ClangdLSPServer::onInitialize(const InitializeParams &Params,
278 Callback<json::Value> Reply) {
Sam McCall0d9b40f2018-10-19 15:42:23 +0000279 if (Params.rootUri && *Params.rootUri)
280 ClangdServerOpts.WorkspaceRoot = Params.rootUri->file();
281 else if (Params.rootPath && !Params.rootPath->empty())
282 ClangdServerOpts.WorkspaceRoot = *Params.rootPath;
Sam McCall3d0adbe2018-10-18 14:41:50 +0000283 if (Server)
284 return Reply(make_error<LSPError>("server already initialized",
285 ErrorCode::InvalidRequest));
Sam McCallbc904612018-10-25 04:22:52 +0000286 if (const auto &Dir = Params.initializationOptions.compilationDatabasePath)
287 CompileCommandsDir = Dir;
Sam McCallc55d09a2018-11-02 13:09:36 +0000288 if (UseDirBasedCDB)
289 BaseCDB = llvm::make_unique<DirectoryBasedGlobalCompilationDatabase>(
290 CompileCommandsDir);
Sam McCall6980edb2018-11-02 14:07:51 +0000291 CDB.emplace(BaseCDB.get(), Params.initializationOptions.fallbackFlags);
Sam McCallc55d09a2018-11-02 13:09:36 +0000292 Server.emplace(*CDB, FSProvider, static_cast<DiagnosticsConsumer &>(*this),
293 ClangdServerOpts);
Sam McCallbc904612018-10-25 04:22:52 +0000294 applyConfiguration(Params.initializationOptions.ConfigSettings);
Simon Marchi88016782018-08-01 11:28:49 +0000295
Sam McCallbf6a2fc2018-10-17 07:33:42 +0000296 CCOpts.EnableSnippets = Params.capabilities.CompletionSnippets;
297 DiagOpts.EmbedFixesInDiagnostics = Params.capabilities.DiagnosticFixes;
298 DiagOpts.SendDiagnosticCategory = Params.capabilities.DiagnosticCategory;
299 if (Params.capabilities.WorkspaceSymbolKinds)
300 SupportedSymbolKinds |= *Params.capabilities.WorkspaceSymbolKinds;
301 if (Params.capabilities.CompletionItemKinds)
302 SupportedCompletionItemKinds |= *Params.capabilities.CompletionItemKinds;
303 SupportsCodeAction = Params.capabilities.CodeActionStructure;
Ilya Biryukov19d75602018-11-23 15:21:19 +0000304 SupportsHierarchicalDocumentSymbol =
305 Params.capabilities.HierarchicalDocumentSymbol;
Haojian Wub6188492018-12-20 15:39:12 +0000306 SupportFileStatus = Params.initializationOptions.FileStatus;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000307 Reply(json::Object{
Sam McCall0930ab02017-11-07 15:49:35 +0000308 {{"capabilities",
Sam McCalld20d7982018-07-09 14:25:59 +0000309 json::Object{
Simon Marchi98082622018-03-26 14:41:40 +0000310 {"textDocumentSync", (int)TextDocumentSyncKind::Incremental},
Sam McCall0930ab02017-11-07 15:49:35 +0000311 {"documentFormattingProvider", true},
312 {"documentRangeFormattingProvider", true},
313 {"documentOnTypeFormattingProvider",
Sam McCalld20d7982018-07-09 14:25:59 +0000314 json::Object{
Sam McCall0930ab02017-11-07 15:49:35 +0000315 {"firstTriggerCharacter", "}"},
316 {"moreTriggerCharacter", {}},
317 }},
318 {"codeActionProvider", true},
319 {"completionProvider",
Sam McCalld20d7982018-07-09 14:25:59 +0000320 json::Object{
Sam McCall0930ab02017-11-07 15:49:35 +0000321 {"resolveProvider", false},
Ilya Biryukovb0826bd2019-01-03 13:37:12 +0000322 // We do extra checks for '>' and ':' in completion to only
323 // trigger on '->' and '::'.
Sam McCall0930ab02017-11-07 15:49:35 +0000324 {"triggerCharacters", {".", ">", ":"}},
325 }},
326 {"signatureHelpProvider",
Sam McCalld20d7982018-07-09 14:25:59 +0000327 json::Object{
Sam McCall0930ab02017-11-07 15:49:35 +0000328 {"triggerCharacters", {"(", ","}},
329 }},
330 {"definitionProvider", true},
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000331 {"documentHighlightProvider", true},
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000332 {"hoverProvider", true},
Haojian Wu345099c2017-11-09 11:30:04 +0000333 {"renameProvider", true},
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000334 {"documentSymbolProvider", true},
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000335 {"workspaceSymbolProvider", true},
Sam McCall1ad142f2018-09-05 11:53:07 +0000336 {"referencesProvider", true},
Sam McCall0930ab02017-11-07 15:49:35 +0000337 {"executeCommandProvider",
Sam McCalld20d7982018-07-09 14:25:59 +0000338 json::Object{
Eric Liu2c190532018-05-15 15:23:53 +0000339 {"commands", {ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND}},
Sam McCall0930ab02017-11-07 15:49:35 +0000340 }},
341 }}}});
Ilya Biryukovafb55542017-05-16 14:40:30 +0000342}
343
Sam McCall2c30fbc2018-10-18 12:32:04 +0000344void ClangdLSPServer::onShutdown(const ShutdownParams &Params,
345 Callback<std::nullptr_t> Reply) {
Ilya Biryukov0d9b8a32017-10-25 08:45:41 +0000346 // Do essentially nothing, just say we're ready to exit.
347 ShutdownRequestReceived = true;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000348 Reply(nullptr);
Sam McCall8a5dded2017-10-12 13:29:58 +0000349}
Ilya Biryukovafb55542017-05-16 14:40:30 +0000350
Sam McCall422c8282018-11-26 16:00:11 +0000351// sync is a clangd extension: it blocks until all background work completes.
352// It blocks the calling thread, so no messages are processed until it returns!
353void ClangdLSPServer::onSync(const NoParams &Params,
354 Callback<std::nullptr_t> Reply) {
355 if (Server->blockUntilIdleForTest(/*TimeoutSeconds=*/60))
356 Reply(nullptr);
357 else
358 Reply(createStringError(llvm::inconvertibleErrorCode(),
359 "Not idle after a minute"));
360}
361
Sam McCall2c30fbc2018-10-18 12:32:04 +0000362void ClangdLSPServer::onDocumentDidOpen(
363 const DidOpenTextDocumentParams &Params) {
Simon Marchi9569fd52018-03-16 14:30:42 +0000364 PathRef File = Params.textDocument.uri.file();
Ilya Biryukovb10ef472018-06-13 09:20:41 +0000365
Sam McCall2c30fbc2018-10-18 12:32:04 +0000366 const std::string &Contents = Params.textDocument.text;
Simon Marchi9569fd52018-03-16 14:30:42 +0000367
Simon Marchi98082622018-03-26 14:41:40 +0000368 DraftMgr.addDraft(File, Contents);
Ilya Biryukov652364b2018-09-26 05:48:29 +0000369 Server->addDocument(File, Contents, WantDiagnostics::Yes);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000370}
371
Sam McCall2c30fbc2018-10-18 12:32:04 +0000372void ClangdLSPServer::onDocumentDidChange(
373 const DidChangeTextDocumentParams &Params) {
Eric Liu51fed182018-02-22 18:40:39 +0000374 auto WantDiags = WantDiagnostics::Auto;
375 if (Params.wantDiagnostics.hasValue())
376 WantDiags = Params.wantDiagnostics.getValue() ? WantDiagnostics::Yes
377 : WantDiagnostics::No;
Simon Marchi9569fd52018-03-16 14:30:42 +0000378
379 PathRef File = Params.textDocument.uri.file();
Sam McCallc008af62018-10-20 15:30:37 +0000380 Expected<std::string> Contents =
Simon Marchi98082622018-03-26 14:41:40 +0000381 DraftMgr.updateDraft(File, Params.contentChanges);
382 if (!Contents) {
383 // If this fails, we are most likely going to be not in sync anymore with
384 // the client. It is better to remove the draft and let further operations
385 // fail rather than giving wrong results.
386 DraftMgr.removeDraft(File);
Ilya Biryukov652364b2018-09-26 05:48:29 +0000387 Server->removeDocument(File);
Sam McCallbed58852018-07-11 10:35:11 +0000388 elog("Failed to update {0}: {1}", File, Contents.takeError());
Simon Marchi98082622018-03-26 14:41:40 +0000389 return;
390 }
Simon Marchi9569fd52018-03-16 14:30:42 +0000391
Ilya Biryukov652364b2018-09-26 05:48:29 +0000392 Server->addDocument(File, *Contents, WantDiags);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000393}
394
Sam McCall2c30fbc2018-10-18 12:32:04 +0000395void ClangdLSPServer::onFileEvent(const DidChangeWatchedFilesParams &Params) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000396 Server->onFileEvent(Params);
Marc-Andre Laperlebf114242017-10-02 18:00:37 +0000397}
398
Sam McCall2c30fbc2018-10-18 12:32:04 +0000399void ClangdLSPServer::onCommand(const ExecuteCommandParams &Params,
400 Callback<json::Value> Reply) {
401 auto ApplyEdit = [&](WorkspaceEdit WE) {
Eric Liuc5105f92018-02-16 14:15:55 +0000402 ApplyWorkspaceEditParams Edit;
403 Edit.edit = std::move(WE);
Eric Liuc5105f92018-02-16 14:15:55 +0000404 // Ideally, we would wait for the response and if there is no error, we
405 // would reply success/failure to the original RPC.
406 call("workspace/applyEdit", Edit);
407 };
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000408 if (Params.command == ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND &&
409 Params.workspaceEdit) {
410 // The flow for "apply-fix" :
411 // 1. We publish a diagnostic, including fixits
412 // 2. The user clicks on the diagnostic, the editor asks us for code actions
413 // 3. We send code actions, with the fixit embedded as context
414 // 4. The user selects the fixit, the editor asks us to apply it
415 // 5. We unwrap the changes and send them back to the editor
416 // 6. The editor applies the changes (applyEdit), and sends us a reply (but
417 // we ignore it)
418
Sam McCall2c30fbc2018-10-18 12:32:04 +0000419 Reply("Fix applied.");
Eric Liuc5105f92018-02-16 14:15:55 +0000420 ApplyEdit(*Params.workspaceEdit);
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000421 } else {
422 // We should not get here because ExecuteCommandParams would not have
423 // parsed in the first place and this handler should not be called. But if
424 // more commands are added, this will be here has a safe guard.
Sam McCall2c30fbc2018-10-18 12:32:04 +0000425 Reply(make_error<LSPError>(
Sam McCallc008af62018-10-20 15:30:37 +0000426 formatv("Unsupported command \"{0}\".", Params.command).str(),
Sam McCall2c30fbc2018-10-18 12:32:04 +0000427 ErrorCode::InvalidParams));
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000428 }
429}
430
Sam McCall2c30fbc2018-10-18 12:32:04 +0000431void ClangdLSPServer::onWorkspaceSymbol(
432 const WorkspaceSymbolParams &Params,
433 Callback<std::vector<SymbolInformation>> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000434 Server->workspaceSymbols(
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000435 Params.query, CCOpts.Limit,
Sam McCall2c30fbc2018-10-18 12:32:04 +0000436 Bind(
437 [this](decltype(Reply) Reply,
Sam McCallc008af62018-10-20 15:30:37 +0000438 Expected<std::vector<SymbolInformation>> Items) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000439 if (!Items)
440 return Reply(Items.takeError());
441 for (auto &Sym : *Items)
442 Sym.kind = adjustKindToCapability(Sym.kind, SupportedSymbolKinds);
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000443
Sam McCall2c30fbc2018-10-18 12:32:04 +0000444 Reply(std::move(*Items));
445 },
446 std::move(Reply)));
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000447}
448
Sam McCall2c30fbc2018-10-18 12:32:04 +0000449void ClangdLSPServer::onRename(const RenameParams &Params,
450 Callback<WorkspaceEdit> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000451 Path File = Params.textDocument.uri.file();
Sam McCallc008af62018-10-20 15:30:37 +0000452 Optional<std::string> Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000453 if (!Code)
Sam McCall2c30fbc2018-10-18 12:32:04 +0000454 return Reply(make_error<LSPError>("onRename called for non-added file",
455 ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000456
Ilya Biryukov652364b2018-09-26 05:48:29 +0000457 Server->rename(
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000458 File, Params.position, Params.newName,
Sam McCall2c30fbc2018-10-18 12:32:04 +0000459 Bind(
Sam McCallc008af62018-10-20 15:30:37 +0000460 [File, Code,
461 Params](decltype(Reply) Reply,
462 Expected<std::vector<tooling::Replacement>> Replacements) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000463 if (!Replacements)
464 return Reply(Replacements.takeError());
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000465
Sam McCall2c30fbc2018-10-18 12:32:04 +0000466 // Turn the replacements into the format specified by the Language
467 // Server Protocol. Fuse them into one big JSON array.
468 std::vector<TextEdit> Edits;
469 for (const auto &R : *Replacements)
470 Edits.push_back(replacementToEdit(*Code, R));
471 WorkspaceEdit WE;
472 WE.changes = {{Params.textDocument.uri.uri(), Edits}};
473 Reply(WE);
474 },
475 std::move(Reply)));
Haojian Wu345099c2017-11-09 11:30:04 +0000476}
477
Sam McCall2c30fbc2018-10-18 12:32:04 +0000478void ClangdLSPServer::onDocumentDidClose(
479 const DidCloseTextDocumentParams &Params) {
Simon Marchi9569fd52018-03-16 14:30:42 +0000480 PathRef File = Params.textDocument.uri.file();
481 DraftMgr.removeDraft(File);
Ilya Biryukov652364b2018-09-26 05:48:29 +0000482 Server->removeDocument(File);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000483}
484
Sam McCall4db732a2017-09-30 10:08:52 +0000485void ClangdLSPServer::onDocumentOnTypeFormatting(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000486 const DocumentOnTypeFormattingParams &Params,
487 Callback<std::vector<TextEdit>> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000488 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000489 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000490 if (!Code)
Sam McCall2c30fbc2018-10-18 12:32:04 +0000491 return Reply(make_error<LSPError>(
492 "onDocumentOnTypeFormatting called for non-added file",
493 ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000494
Ilya Biryukov652364b2018-09-26 05:48:29 +0000495 auto ReplacementsOrError = Server->formatOnType(*Code, File, Params.position);
Raoul Wols212bcf82017-12-12 20:25:06 +0000496 if (ReplacementsOrError)
Sam McCall2c30fbc2018-10-18 12:32:04 +0000497 Reply(replacementsToEdits(*Code, ReplacementsOrError.get()));
Raoul Wols212bcf82017-12-12 20:25:06 +0000498 else
Sam McCall2c30fbc2018-10-18 12:32:04 +0000499 Reply(ReplacementsOrError.takeError());
Ilya Biryukovafb55542017-05-16 14:40:30 +0000500}
501
Sam McCall4db732a2017-09-30 10:08:52 +0000502void ClangdLSPServer::onDocumentRangeFormatting(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000503 const DocumentRangeFormattingParams &Params,
504 Callback<std::vector<TextEdit>> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000505 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000506 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000507 if (!Code)
Sam McCall2c30fbc2018-10-18 12:32:04 +0000508 return Reply(make_error<LSPError>(
509 "onDocumentRangeFormatting called for non-added file",
510 ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000511
Ilya Biryukov652364b2018-09-26 05:48:29 +0000512 auto ReplacementsOrError = Server->formatRange(*Code, File, Params.range);
Raoul Wols212bcf82017-12-12 20:25:06 +0000513 if (ReplacementsOrError)
Sam McCall2c30fbc2018-10-18 12:32:04 +0000514 Reply(replacementsToEdits(*Code, ReplacementsOrError.get()));
Raoul Wols212bcf82017-12-12 20:25:06 +0000515 else
Sam McCall2c30fbc2018-10-18 12:32:04 +0000516 Reply(ReplacementsOrError.takeError());
Ilya Biryukovafb55542017-05-16 14:40:30 +0000517}
518
Sam McCall2c30fbc2018-10-18 12:32:04 +0000519void ClangdLSPServer::onDocumentFormatting(
520 const DocumentFormattingParams &Params,
521 Callback<std::vector<TextEdit>> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000522 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000523 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000524 if (!Code)
Sam McCall2c30fbc2018-10-18 12:32:04 +0000525 return Reply(
526 make_error<LSPError>("onDocumentFormatting called for non-added file",
527 ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000528
Ilya Biryukov652364b2018-09-26 05:48:29 +0000529 auto ReplacementsOrError = Server->formatFile(*Code, File);
Raoul Wols212bcf82017-12-12 20:25:06 +0000530 if (ReplacementsOrError)
Sam McCall2c30fbc2018-10-18 12:32:04 +0000531 Reply(replacementsToEdits(*Code, ReplacementsOrError.get()));
Raoul Wols212bcf82017-12-12 20:25:06 +0000532 else
Sam McCall2c30fbc2018-10-18 12:32:04 +0000533 Reply(ReplacementsOrError.takeError());
Sam McCall4db732a2017-09-30 10:08:52 +0000534}
535
Ilya Biryukov19d75602018-11-23 15:21:19 +0000536/// The functions constructs a flattened view of the DocumentSymbol hierarchy.
537/// Used by the clients that do not support the hierarchical view.
538static std::vector<SymbolInformation>
539flattenSymbolHierarchy(llvm::ArrayRef<DocumentSymbol> Symbols,
540 const URIForFile &FileURI) {
541
542 std::vector<SymbolInformation> Results;
543 std::function<void(const DocumentSymbol &, StringRef)> Process =
544 [&](const DocumentSymbol &S, Optional<StringRef> ParentName) {
545 SymbolInformation SI;
546 SI.containerName = ParentName ? "" : *ParentName;
547 SI.name = S.name;
548 SI.kind = S.kind;
549 SI.location.range = S.range;
550 SI.location.uri = FileURI;
551
552 Results.push_back(std::move(SI));
553 std::string FullName =
554 !ParentName ? S.name : (ParentName->str() + "::" + S.name);
555 for (auto &C : S.children)
556 Process(C, /*ParentName=*/FullName);
557 };
558 for (auto &S : Symbols)
559 Process(S, /*ParentName=*/"");
560 return Results;
561}
562
563void ClangdLSPServer::onDocumentSymbol(const DocumentSymbolParams &Params,
564 Callback<json::Value> Reply) {
565 URIForFile FileURI = Params.textDocument.uri;
Ilya Biryukov652364b2018-09-26 05:48:29 +0000566 Server->documentSymbols(
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000567 Params.textDocument.uri.file(),
Sam McCall2c30fbc2018-10-18 12:32:04 +0000568 Bind(
Ilya Biryukov19d75602018-11-23 15:21:19 +0000569 [this, FileURI](decltype(Reply) Reply,
570 Expected<std::vector<DocumentSymbol>> Items) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000571 if (!Items)
572 return Reply(Items.takeError());
Ilya Biryukov19d75602018-11-23 15:21:19 +0000573 adjustSymbolKinds(*Items, SupportedSymbolKinds);
574 if (SupportsHierarchicalDocumentSymbol)
575 return Reply(std::move(*Items));
576 else
577 return Reply(flattenSymbolHierarchy(*Items, FileURI));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000578 },
579 std::move(Reply)));
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000580}
581
Sam McCall20841d42018-10-16 16:29:41 +0000582static Optional<Command> asCommand(const CodeAction &Action) {
583 Command Cmd;
584 if (Action.command && Action.edit)
Sam McCallc008af62018-10-20 15:30:37 +0000585 return None; // Not representable. (We never emit these anyway).
Sam McCall20841d42018-10-16 16:29:41 +0000586 if (Action.command) {
587 Cmd = *Action.command;
588 } else if (Action.edit) {
589 Cmd.command = Command::CLANGD_APPLY_FIX_COMMAND;
590 Cmd.workspaceEdit = *Action.edit;
591 } else {
Sam McCallc008af62018-10-20 15:30:37 +0000592 return None;
Sam McCall20841d42018-10-16 16:29:41 +0000593 }
594 Cmd.title = Action.title;
595 if (Action.kind && *Action.kind == CodeAction::QUICKFIX_KIND)
596 Cmd.title = "Apply fix: " + Cmd.title;
597 return Cmd;
598}
599
Sam McCall2c30fbc2018-10-18 12:32:04 +0000600void ClangdLSPServer::onCodeAction(const CodeActionParams &Params,
601 Callback<json::Value> Reply) {
602 auto Code = DraftMgr.getDraft(Params.textDocument.uri.file());
603 if (!Code)
604 return Reply(make_error<LSPError>("onCodeAction called for non-added file",
605 ErrorCode::InvalidParams));
Sam McCall20841d42018-10-16 16:29:41 +0000606 // We provide a code action for Fixes on the specified diagnostics.
Sam McCall20841d42018-10-16 16:29:41 +0000607 std::vector<CodeAction> Actions;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000608 for (const Diagnostic &D : Params.context.diagnostics) {
Ilya Biryukov71028b82018-03-12 15:28:22 +0000609 for (auto &F : getFixes(Params.textDocument.uri.file(), D)) {
Sam McCall16e70702018-10-24 07:59:38 +0000610 Actions.push_back(toCodeAction(F, Params.textDocument.uri));
Sam McCall20841d42018-10-16 16:29:41 +0000611 Actions.back().diagnostics = {D};
Sam McCalldd0566b2017-11-06 15:40:30 +0000612 }
Ilya Biryukovafb55542017-05-16 14:40:30 +0000613 }
Sam McCall20841d42018-10-16 16:29:41 +0000614
615 if (SupportsCodeAction)
Sam McCall2c30fbc2018-10-18 12:32:04 +0000616 Reply(json::Array(Actions));
Sam McCall20841d42018-10-16 16:29:41 +0000617 else {
618 std::vector<Command> Commands;
619 for (const auto &Action : Actions)
620 if (auto Command = asCommand(Action))
621 Commands.push_back(std::move(*Command));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000622 Reply(json::Array(Commands));
Sam McCall20841d42018-10-16 16:29:41 +0000623 }
Ilya Biryukovafb55542017-05-16 14:40:30 +0000624}
625
Ilya Biryukovb0826bd2019-01-03 13:37:12 +0000626void ClangdLSPServer::onCompletion(const CompletionParams &Params,
Sam McCall2c30fbc2018-10-18 12:32:04 +0000627 Callback<CompletionList> Reply) {
Ilya Biryukovb0826bd2019-01-03 13:37:12 +0000628 if (!shouldRunCompletion(Params))
629 return Reply(llvm::make_error<IgnoreCompletionError>());
Ilya Biryukov22fa4652019-01-03 13:28:05 +0000630 Server->codeComplete(
631 Params.textDocument.uri.file(), Params.position, CCOpts,
632 Bind(
633 [this](decltype(Reply) Reply, Expected<CodeCompleteResult> List) {
634 if (!List)
635 return Reply(List.takeError());
636 CompletionList LSPList;
637 LSPList.isIncomplete = List->HasMore;
638 for (const auto &R : List->Completions) {
639 CompletionItem C = R.render(CCOpts);
640 C.kind =
641 adjustKindToCapability(C.kind, SupportedCompletionItemKinds);
642 LSPList.items.push_back(std::move(C));
643 }
644 return Reply(std::move(LSPList));
645 },
646 std::move(Reply)));
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000647}
648
Sam McCall2c30fbc2018-10-18 12:32:04 +0000649void ClangdLSPServer::onSignatureHelp(const TextDocumentPositionParams &Params,
650 Callback<SignatureHelp> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000651 Server->signatureHelp(Params.textDocument.uri.file(), Params.position,
Sam McCall2c30fbc2018-10-18 12:32:04 +0000652 std::move(Reply));
Ilya Biryukov652364b2018-09-26 05:48:29 +0000653}
654
Sam McCall2c30fbc2018-10-18 12:32:04 +0000655void ClangdLSPServer::onGoToDefinition(const TextDocumentPositionParams &Params,
656 Callback<std::vector<Location>> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000657 Server->findDefinitions(Params.textDocument.uri.file(), Params.position,
Sam McCall2c30fbc2018-10-18 12:32:04 +0000658 std::move(Reply));
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000659}
660
Sam McCall2c30fbc2018-10-18 12:32:04 +0000661void ClangdLSPServer::onSwitchSourceHeader(const TextDocumentIdentifier &Params,
662 Callback<std::string> Reply) {
Sam McCallc008af62018-10-20 15:30:37 +0000663 Optional<Path> Result = Server->switchSourceHeader(Params.uri.file());
Sam McCall2c30fbc2018-10-18 12:32:04 +0000664 Reply(Result ? URI::createFile(*Result).toString() : "");
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000665}
666
Sam McCall2c30fbc2018-10-18 12:32:04 +0000667void ClangdLSPServer::onDocumentHighlight(
668 const TextDocumentPositionParams &Params,
669 Callback<std::vector<DocumentHighlight>> Reply) {
670 Server->findDocumentHighlights(Params.textDocument.uri.file(),
671 Params.position, std::move(Reply));
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000672}
673
Sam McCall2c30fbc2018-10-18 12:32:04 +0000674void ClangdLSPServer::onHover(const TextDocumentPositionParams &Params,
Sam McCallc008af62018-10-20 15:30:37 +0000675 Callback<Optional<Hover>> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000676 Server->findHover(Params.textDocument.uri.file(), Params.position,
Sam McCall2c30fbc2018-10-18 12:32:04 +0000677 std::move(Reply));
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000678}
679
Simon Marchi88016782018-08-01 11:28:49 +0000680void ClangdLSPServer::applyConfiguration(
Sam McCallbc904612018-10-25 04:22:52 +0000681 const ConfigurationSettings &Settings) {
Simon Marchiabeed662018-10-16 15:55:03 +0000682 // Per-file update to the compilation database.
Sam McCallbc904612018-10-25 04:22:52 +0000683 bool ShouldReparseOpenFiles = false;
684 for (auto &Entry : Settings.compilationDatabaseChanges) {
685 /// The opened files need to be reparsed only when some existing
686 /// entries are changed.
687 PathRef File = Entry.first;
Sam McCallc55d09a2018-11-02 13:09:36 +0000688 auto Old = CDB->getCompileCommand(File);
689 auto New =
690 tooling::CompileCommand(std::move(Entry.second.workingDirectory), File,
691 std::move(Entry.second.compilationCommand),
692 /*Output=*/"");
Sam McCall6980edb2018-11-02 14:07:51 +0000693 if (Old != New) {
Sam McCallc55d09a2018-11-02 13:09:36 +0000694 CDB->setCompileCommand(File, std::move(New));
Sam McCall6980edb2018-11-02 14:07:51 +0000695 ShouldReparseOpenFiles = true;
696 }
Alex Lorenzf8087862018-08-01 17:39:29 +0000697 }
Sam McCallbc904612018-10-25 04:22:52 +0000698 if (ShouldReparseOpenFiles)
699 reparseOpenedFiles();
Simon Marchi5178f922018-02-22 14:00:39 +0000700}
701
Simon Marchi88016782018-08-01 11:28:49 +0000702// FIXME: This function needs to be properly tested.
703void ClangdLSPServer::onChangeConfiguration(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000704 const DidChangeConfigurationParams &Params) {
Simon Marchi88016782018-08-01 11:28:49 +0000705 applyConfiguration(Params.settings);
706}
707
Sam McCall2c30fbc2018-10-18 12:32:04 +0000708void ClangdLSPServer::onReference(const ReferenceParams &Params,
709 Callback<std::vector<Location>> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000710 Server->findReferences(Params.textDocument.uri.file(), Params.position,
Sam McCall2c30fbc2018-10-18 12:32:04 +0000711 std::move(Reply));
Sam McCall1ad142f2018-09-05 11:53:07 +0000712}
713
Jan Korousb4067012018-11-27 16:40:46 +0000714void ClangdLSPServer::onSymbolInfo(const TextDocumentPositionParams &Params,
715 Callback<std::vector<SymbolDetails>> Reply) {
716 Server->symbolInfo(Params.textDocument.uri.file(), Params.position,
717 std::move(Reply));
718}
719
Sam McCalldc8f3cf2018-10-17 07:32:05 +0000720ClangdLSPServer::ClangdLSPServer(class Transport &Transp,
Sam McCalladccab62017-11-23 16:58:22 +0000721 const clangd::CodeCompleteOptions &CCOpts,
Sam McCallc008af62018-10-20 15:30:37 +0000722 Optional<Path> CompileCommandsDir,
Sam McCallc55d09a2018-11-02 13:09:36 +0000723 bool UseDirBasedCDB,
Sam McCall7363a2f2018-03-05 17:28:54 +0000724 const ClangdServer::Options &Opts)
Sam McCalld1c9d112018-10-23 14:19:54 +0000725 : Transp(Transp), MsgHandler(new MessageHandler(*this)), CCOpts(CCOpts),
726 SupportedSymbolKinds(defaultSymbolKinds()),
Kadir Cetinkaya133d46f2018-09-27 17:13:07 +0000727 SupportedCompletionItemKinds(defaultCompletionItemKinds()),
Sam McCallc55d09a2018-11-02 13:09:36 +0000728 UseDirBasedCDB(UseDirBasedCDB),
Sam McCall4b86bb02018-10-25 02:22:53 +0000729 CompileCommandsDir(std::move(CompileCommandsDir)),
730 ClangdServerOpts(Opts) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000731 // clang-format off
732 MsgHandler->bind("initialize", &ClangdLSPServer::onInitialize);
733 MsgHandler->bind("shutdown", &ClangdLSPServer::onShutdown);
Sam McCall422c8282018-11-26 16:00:11 +0000734 MsgHandler->bind("sync", &ClangdLSPServer::onSync);
Sam McCall2c30fbc2018-10-18 12:32:04 +0000735 MsgHandler->bind("textDocument/rangeFormatting", &ClangdLSPServer::onDocumentRangeFormatting);
736 MsgHandler->bind("textDocument/onTypeFormatting", &ClangdLSPServer::onDocumentOnTypeFormatting);
737 MsgHandler->bind("textDocument/formatting", &ClangdLSPServer::onDocumentFormatting);
738 MsgHandler->bind("textDocument/codeAction", &ClangdLSPServer::onCodeAction);
739 MsgHandler->bind("textDocument/completion", &ClangdLSPServer::onCompletion);
740 MsgHandler->bind("textDocument/signatureHelp", &ClangdLSPServer::onSignatureHelp);
741 MsgHandler->bind("textDocument/definition", &ClangdLSPServer::onGoToDefinition);
742 MsgHandler->bind("textDocument/references", &ClangdLSPServer::onReference);
743 MsgHandler->bind("textDocument/switchSourceHeader", &ClangdLSPServer::onSwitchSourceHeader);
744 MsgHandler->bind("textDocument/rename", &ClangdLSPServer::onRename);
745 MsgHandler->bind("textDocument/hover", &ClangdLSPServer::onHover);
746 MsgHandler->bind("textDocument/documentSymbol", &ClangdLSPServer::onDocumentSymbol);
747 MsgHandler->bind("workspace/executeCommand", &ClangdLSPServer::onCommand);
748 MsgHandler->bind("textDocument/documentHighlight", &ClangdLSPServer::onDocumentHighlight);
749 MsgHandler->bind("workspace/symbol", &ClangdLSPServer::onWorkspaceSymbol);
750 MsgHandler->bind("textDocument/didOpen", &ClangdLSPServer::onDocumentDidOpen);
751 MsgHandler->bind("textDocument/didClose", &ClangdLSPServer::onDocumentDidClose);
752 MsgHandler->bind("textDocument/didChange", &ClangdLSPServer::onDocumentDidChange);
753 MsgHandler->bind("workspace/didChangeWatchedFiles", &ClangdLSPServer::onFileEvent);
754 MsgHandler->bind("workspace/didChangeConfiguration", &ClangdLSPServer::onChangeConfiguration);
Jan Korousb4067012018-11-27 16:40:46 +0000755 MsgHandler->bind("textDocument/symbolInfo", &ClangdLSPServer::onSymbolInfo);
Sam McCall2c30fbc2018-10-18 12:32:04 +0000756 // clang-format on
757}
758
759ClangdLSPServer::~ClangdLSPServer() = default;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000760
Sam McCalldc8f3cf2018-10-17 07:32:05 +0000761bool ClangdLSPServer::run() {
Ilya Biryukovafb55542017-05-16 14:40:30 +0000762 // Run the Language Server loop.
Sam McCalldc8f3cf2018-10-17 07:32:05 +0000763 bool CleanExit = true;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000764 if (auto Err = Transp.loop(*MsgHandler)) {
Sam McCalldc8f3cf2018-10-17 07:32:05 +0000765 elog("Transport error: {0}", std::move(Err));
766 CleanExit = false;
767 }
Ilya Biryukovafb55542017-05-16 14:40:30 +0000768
Ilya Biryukov652364b2018-09-26 05:48:29 +0000769 // Destroy ClangdServer to ensure all worker threads finish.
770 Server.reset();
Sam McCalldc8f3cf2018-10-17 07:32:05 +0000771 return CleanExit && ShutdownRequestReceived;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000772}
773
Ilya Biryukov71028b82018-03-12 15:28:22 +0000774std::vector<Fix> ClangdLSPServer::getFixes(StringRef File,
775 const clangd::Diagnostic &D) {
Ilya Biryukov38d79772017-05-16 09:38:59 +0000776 std::lock_guard<std::mutex> Lock(FixItsMutex);
777 auto DiagToFixItsIter = FixItsMap.find(File);
778 if (DiagToFixItsIter == FixItsMap.end())
779 return {};
780
781 const auto &DiagToFixItsMap = DiagToFixItsIter->second;
782 auto FixItsIter = DiagToFixItsMap.find(D);
783 if (FixItsIter == DiagToFixItsMap.end())
784 return {};
785
786 return FixItsIter->second;
787}
788
Ilya Biryukovb0826bd2019-01-03 13:37:12 +0000789bool ClangdLSPServer::shouldRunCompletion(
790 const CompletionParams &Params) const {
791 StringRef Trigger = Params.context.triggerCharacter;
792 if (Params.context.triggerKind != CompletionTriggerKind::TriggerCharacter ||
793 (Trigger != ">" && Trigger != ":"))
794 return true;
795
796 auto Code = DraftMgr.getDraft(Params.textDocument.uri.file());
797 if (!Code)
798 return true; // completion code will log the error for untracked doc.
799
800 // A completion request is sent when the user types '>' or ':', but we only
801 // want to trigger on '->' and '::'. We check the preceeding character to make
802 // sure it matches what we expected.
803 // Running the lexer here would be more robust (e.g. we can detect comments
804 // and avoid triggering completion there), but we choose to err on the side
805 // of simplicity here.
806 auto Offset = positionToOffset(*Code, Params.position,
807 /*AllowColumnsBeyondLineLength=*/false);
808 if (!Offset) {
809 vlog("could not convert position '{0}' to offset for file '{1}'",
810 Params.position, Params.textDocument.uri.file());
811 return true;
812 }
813 if (*Offset < 2)
814 return false;
815
816 if (Trigger == ">")
817 return (*Code)[*Offset - 2] == '-'; // trigger only on '->'.
818 if (Trigger == ":")
819 return (*Code)[*Offset - 2] == ':'; // trigger only on '::'.
820 assert(false && "unhandled trigger character");
821 return true;
822}
823
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000824void ClangdLSPServer::onDiagnosticsReady(PathRef File,
825 std::vector<Diag> Diagnostics) {
Eric Liu4d814a92018-11-28 10:30:42 +0000826 auto URI = URIForFile::canonicalize(File, /*TUPath=*/File);
Sam McCall16e70702018-10-24 07:59:38 +0000827 std::vector<Diagnostic> LSPDiagnostics;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000828 DiagnosticToReplacementMap LocalFixIts; // Temporary storage
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000829 for (auto &Diag : Diagnostics) {
Sam McCall16e70702018-10-24 07:59:38 +0000830 toLSPDiags(Diag, URI, DiagOpts,
831 [&](clangd::Diagnostic Diag, ArrayRef<Fix> Fixes) {
832 auto &FixItsForDiagnostic = LocalFixIts[Diag];
833 llvm::copy(Fixes, std::back_inserter(FixItsForDiagnostic));
834 LSPDiagnostics.push_back(std::move(Diag));
835 });
Ilya Biryukov38d79772017-05-16 09:38:59 +0000836 }
837
838 // Cache FixIts
839 {
840 // FIXME(ibiryukov): should be deleted when documents are removed
841 std::lock_guard<std::mutex> Lock(FixItsMutex);
842 FixItsMap[File] = LocalFixIts;
843 }
844
845 // Publish diagnostics.
Sam McCall2c30fbc2018-10-18 12:32:04 +0000846 notify("textDocument/publishDiagnostics",
847 json::Object{
Sam McCall16e70702018-10-24 07:59:38 +0000848 {"uri", URI},
849 {"diagnostics", std::move(LSPDiagnostics)},
Sam McCall2c30fbc2018-10-18 12:32:04 +0000850 });
Ilya Biryukov38d79772017-05-16 09:38:59 +0000851}
Simon Marchi9569fd52018-03-16 14:30:42 +0000852
Haojian Wub6188492018-12-20 15:39:12 +0000853void ClangdLSPServer::onFileUpdated(PathRef File, const TUStatus &Status) {
854 if (!SupportFileStatus)
855 return;
856 // FIXME: we don't emit "BuildingFile" and `RunningAction`, as these
857 // two statuses are running faster in practice, which leads the UI constantly
858 // changing, and doesn't provide much value. We may want to emit status at a
859 // reasonable time interval (e.g. 0.5s).
860 if (Status.Action.S == TUAction::BuildingFile ||
861 Status.Action.S == TUAction::RunningAction)
862 return;
863 notify("textDocument/clangd.fileStatus", Status.render(File));
864}
865
Simon Marchi9569fd52018-03-16 14:30:42 +0000866void ClangdLSPServer::reparseOpenedFiles() {
867 for (const Path &FilePath : DraftMgr.getActiveFiles())
Ilya Biryukov652364b2018-09-26 05:48:29 +0000868 Server->addDocument(FilePath, *DraftMgr.getDraft(FilePath),
869 WantDiagnostics::Auto);
Simon Marchi9569fd52018-03-16 14:30:42 +0000870}
Alex Lorenzf8087862018-08-01 17:39:29 +0000871
Sam McCallc008af62018-10-20 15:30:37 +0000872} // namespace clangd
873} // namespace clang