blob: a65aab0a0827251eeb09223f27beb0d961211a4e [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 Biryukovf9169d02019-05-29 10:01:00 +000011#include "FormattedString.h"
Kadir Cetinkaya256247c2019-06-26 07:45:27 +000012#include "GlobalCompilationDatabase.h"
Ilya Biryukovcce67a32019-01-29 14:17:36 +000013#include "Protocol.h"
Sam McCallb536a2a2017-12-19 12:23:48 +000014#include "SourceCode.h"
Sam McCall2c30fbc2018-10-18 12:32:04 +000015#include "Trace.h"
Eric Liu78ed91a72018-01-29 15:37:46 +000016#include "URI.h"
Sam McCall395fde72019-06-18 13:37:54 +000017#include "refactor/Tweak.h"
Ilya Biryukovcce67a32019-01-29 14:17:36 +000018#include "clang/Tooling/Core/Replacement.h"
Kadir Cetinkaya256247c2019-06-26 07:45:27 +000019#include "llvm/ADT/ArrayRef.h"
Sam McCalla69698f2019-03-27 17:47:49 +000020#include "llvm/ADT/Optional.h"
Kadir Cetinkaya689bf932018-08-24 13:09:41 +000021#include "llvm/ADT/ScopeExit.h"
Simon Marchi9569fd52018-03-16 14:30:42 +000022#include "llvm/Support/Errc.h"
Ilya Biryukovcce67a32019-01-29 14:17:36 +000023#include "llvm/Support/Error.h"
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +000024#include "llvm/Support/FormatVariadic.h"
Eric Liu5740ff52018-01-31 16:26:27 +000025#include "llvm/Support/Path.h"
Sam McCall2c30fbc2018-10-18 12:32:04 +000026#include "llvm/Support/ScopedPrinter.h"
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +000027
Sam McCallc008af62018-10-20 15:30:37 +000028namespace clang {
29namespace clangd {
Ilya Biryukovafb55542017-05-16 14:40:30 +000030namespace {
Ilya Biryukovcce67a32019-01-29 14:17:36 +000031/// Transforms a tweak into a code action that would apply it if executed.
32/// EXPECTS: T.prepare() was called and returned true.
33CodeAction toCodeAction(const ClangdServer::TweakRef &T, const URIForFile &File,
34 Range Selection) {
35 CodeAction CA;
36 CA.title = T.Title;
Sam McCall395fde72019-06-18 13:37:54 +000037 switch (T.Intent) {
38 case Tweak::Refactor:
39 CA.kind = CodeAction::REFACTOR_KIND;
40 break;
41 case Tweak::Info:
42 CA.kind = CodeAction::INFO_KIND;
43 break;
44 }
Ilya Biryukovcce67a32019-01-29 14:17:36 +000045 // This tweak may have an expensive second stage, we only run it if the user
46 // actually chooses it in the UI. We reply with a command that would run the
47 // corresponding tweak.
48 // FIXME: for some tweaks, computing the edits is cheap and we could send them
49 // directly.
50 CA.command.emplace();
51 CA.command->title = T.Title;
52 CA.command->command = Command::CLANGD_APPLY_TWEAK;
53 CA.command->tweakArgs.emplace();
54 CA.command->tweakArgs->file = File;
55 CA.command->tweakArgs->tweakID = T.ID;
56 CA.command->tweakArgs->selection = Selection;
57 return CA;
Simon Pilgrime9a136b2019-02-03 14:08:30 +000058}
Ilya Biryukovcce67a32019-01-29 14:17:36 +000059
Ilya Biryukov19d75602018-11-23 15:21:19 +000060void adjustSymbolKinds(llvm::MutableArrayRef<DocumentSymbol> Syms,
61 SymbolKindBitset Kinds) {
62 for (auto &S : Syms) {
63 S.kind = adjustKindToCapability(S.kind, Kinds);
64 adjustSymbolKinds(S.children, Kinds);
65 }
66}
67
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +000068SymbolKindBitset defaultSymbolKinds() {
69 SymbolKindBitset Defaults;
70 for (size_t I = SymbolKindMin; I <= static_cast<size_t>(SymbolKind::Array);
71 ++I)
72 Defaults.set(I);
73 return Defaults;
74}
75
Kadir Cetinkaya133d46f2018-09-27 17:13:07 +000076CompletionItemKindBitset defaultCompletionItemKinds() {
77 CompletionItemKindBitset Defaults;
78 for (size_t I = CompletionItemKindMin;
79 I <= static_cast<size_t>(CompletionItemKind::Reference); ++I)
80 Defaults.set(I);
81 return Defaults;
82}
83
Ilya Biryukovafb55542017-05-16 14:40:30 +000084} // namespace
85
Sam McCall2c30fbc2018-10-18 12:32:04 +000086// MessageHandler dispatches incoming LSP messages.
87// It handles cross-cutting concerns:
88// - serializes/deserializes protocol objects to JSON
89// - logging of inbound messages
90// - cancellation handling
91// - basic call tracing
Sam McCall3d0adbe2018-10-18 14:41:50 +000092// MessageHandler ensures that initialize() is called before any other handler.
Sam McCall2c30fbc2018-10-18 12:32:04 +000093class ClangdLSPServer::MessageHandler : public Transport::MessageHandler {
94public:
95 MessageHandler(ClangdLSPServer &Server) : Server(Server) {}
96
Ilya Biryukovf2001aa2019-01-07 15:45:19 +000097 bool onNotify(llvm::StringRef Method, llvm::json::Value Params) override {
Sam McCalla69698f2019-03-27 17:47:49 +000098 WithContext HandlerContext(handlerContext());
Sam McCall2c30fbc2018-10-18 12:32:04 +000099 log("<-- {0}", Method);
100 if (Method == "exit")
101 return false;
Sam McCall3d0adbe2018-10-18 14:41:50 +0000102 if (!Server.Server)
103 elog("Notification {0} before initialization", Method);
104 else if (Method == "$/cancelRequest")
Sam McCall2c30fbc2018-10-18 12:32:04 +0000105 onCancel(std::move(Params));
106 else if (auto Handler = Notifications.lookup(Method))
107 Handler(std::move(Params));
108 else
109 log("unhandled notification {0}", Method);
110 return true;
111 }
112
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000113 bool onCall(llvm::StringRef Method, llvm::json::Value Params,
114 llvm::json::Value ID) override {
Sam McCalla69698f2019-03-27 17:47:49 +0000115 WithContext HandlerContext(handlerContext());
Sam McCalle2f3a732018-10-24 14:26:26 +0000116 // Calls can be canceled by the client. Add cancellation context.
117 WithContext WithCancel(cancelableRequestContext(ID));
118 trace::Span Tracer(Method);
119 SPAN_ATTACH(Tracer, "Params", Params);
120 ReplyOnce Reply(ID, Method, &Server, Tracer.Args);
Sam McCall2c30fbc2018-10-18 12:32:04 +0000121 log("<-- {0}({1})", Method, ID);
Sam McCall3d0adbe2018-10-18 14:41:50 +0000122 if (!Server.Server && Method != "initialize") {
123 elog("Call {0} before initialization.", Method);
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000124 Reply(llvm::make_error<LSPError>("server not initialized",
125 ErrorCode::ServerNotInitialized));
Sam McCall3d0adbe2018-10-18 14:41:50 +0000126 } else if (auto Handler = Calls.lookup(Method))
Sam McCalle2f3a732018-10-24 14:26:26 +0000127 Handler(std::move(Params), std::move(Reply));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000128 else
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000129 Reply(llvm::make_error<LSPError>("method not found",
130 ErrorCode::MethodNotFound));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000131 return true;
132 }
133
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000134 bool onReply(llvm::json::Value ID,
135 llvm::Expected<llvm::json::Value> Result) override {
Sam McCalla69698f2019-03-27 17:47:49 +0000136 WithContext HandlerContext(handlerContext());
Sam McCall2c30fbc2018-10-18 12:32:04 +0000137 // We ignore replies, just log them.
138 if (Result)
139 log("<-- reply({0})", ID);
140 else
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000141 log("<-- reply({0}) error: {1}", ID, llvm::toString(Result.takeError()));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000142 return true;
143 }
144
145 // Bind an LSP method name to a call.
Sam McCalle2f3a732018-10-24 14:26:26 +0000146 template <typename Param, typename Result>
Sam McCall2c30fbc2018-10-18 12:32:04 +0000147 void bind(const char *Method,
Sam McCalle2f3a732018-10-24 14:26:26 +0000148 void (ClangdLSPServer::*Handler)(const Param &, Callback<Result>)) {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000149 Calls[Method] = [Method, Handler, this](llvm::json::Value RawParams,
Sam McCalle2f3a732018-10-24 14:26:26 +0000150 ReplyOnce Reply) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000151 Param P;
Sam McCalle2f3a732018-10-24 14:26:26 +0000152 if (fromJSON(RawParams, P)) {
153 (Server.*Handler)(P, std::move(Reply));
154 } else {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000155 elog("Failed to decode {0} request.", Method);
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000156 Reply(llvm::make_error<LSPError>("failed to decode request",
157 ErrorCode::InvalidRequest));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000158 }
Sam McCall2c30fbc2018-10-18 12:32:04 +0000159 };
160 }
161
162 // Bind an LSP method name to a notification.
163 template <typename Param>
164 void bind(const char *Method,
165 void (ClangdLSPServer::*Handler)(const Param &)) {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000166 Notifications[Method] = [Method, Handler,
167 this](llvm::json::Value RawParams) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000168 Param P;
169 if (!fromJSON(RawParams, P)) {
170 elog("Failed to decode {0} request.", Method);
171 return;
172 }
173 trace::Span Tracer(Method);
174 SPAN_ATTACH(Tracer, "Params", RawParams);
175 (Server.*Handler)(P);
176 };
177 }
178
179private:
Sam McCalle2f3a732018-10-24 14:26:26 +0000180 // Function object to reply to an LSP call.
181 // Each instance must be called exactly once, otherwise:
182 // - the bug is logged, and (in debug mode) an assert will fire
183 // - if there was no reply, an error reply is sent
184 // - if there were multiple replies, only the first is sent
185 class ReplyOnce {
186 std::atomic<bool> Replied = {false};
Sam McCalld7babe42018-10-24 15:18:40 +0000187 std::chrono::steady_clock::time_point Start;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000188 llvm::json::Value ID;
Sam McCalle2f3a732018-10-24 14:26:26 +0000189 std::string Method;
190 ClangdLSPServer *Server; // Null when moved-from.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000191 llvm::json::Object *TraceArgs;
Sam McCalle2f3a732018-10-24 14:26:26 +0000192
193 public:
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000194 ReplyOnce(const llvm::json::Value &ID, llvm::StringRef Method,
195 ClangdLSPServer *Server, llvm::json::Object *TraceArgs)
Sam McCalld7babe42018-10-24 15:18:40 +0000196 : Start(std::chrono::steady_clock::now()), ID(ID), Method(Method),
197 Server(Server), TraceArgs(TraceArgs) {
Sam McCalle2f3a732018-10-24 14:26:26 +0000198 assert(Server);
199 }
200 ReplyOnce(ReplyOnce &&Other)
Sam McCalld7babe42018-10-24 15:18:40 +0000201 : Replied(Other.Replied.load()), Start(Other.Start),
202 ID(std::move(Other.ID)), Method(std::move(Other.Method)),
203 Server(Other.Server), TraceArgs(Other.TraceArgs) {
Sam McCalle2f3a732018-10-24 14:26:26 +0000204 Other.Server = nullptr;
205 }
Ilya Biryukov22fa4652019-01-03 13:28:05 +0000206 ReplyOnce &operator=(ReplyOnce &&) = delete;
Sam McCalle2f3a732018-10-24 14:26:26 +0000207 ReplyOnce(const ReplyOnce &) = delete;
Ilya Biryukov22fa4652019-01-03 13:28:05 +0000208 ReplyOnce &operator=(const ReplyOnce &) = delete;
Sam McCalle2f3a732018-10-24 14:26:26 +0000209
210 ~ReplyOnce() {
211 if (Server && !Replied) {
212 elog("No reply to message {0}({1})", Method, ID);
213 assert(false && "must reply to all calls!");
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000214 (*this)(llvm::make_error<LSPError>("server failed to reply",
215 ErrorCode::InternalError));
Sam McCalle2f3a732018-10-24 14:26:26 +0000216 }
217 }
218
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000219 void operator()(llvm::Expected<llvm::json::Value> Reply) {
Sam McCalle2f3a732018-10-24 14:26:26 +0000220 assert(Server && "moved-from!");
221 if (Replied.exchange(true)) {
222 elog("Replied twice to message {0}({1})", Method, ID);
223 assert(false && "must reply to each call only once!");
224 return;
225 }
Sam McCalld7babe42018-10-24 15:18:40 +0000226 auto Duration = std::chrono::steady_clock::now() - Start;
227 if (Reply) {
228 log("--> reply:{0}({1}) {2:ms}", Method, ID, Duration);
229 if (TraceArgs)
Sam McCalle2f3a732018-10-24 14:26:26 +0000230 (*TraceArgs)["Reply"] = *Reply;
Sam McCalld7babe42018-10-24 15:18:40 +0000231 std::lock_guard<std::mutex> Lock(Server->TranspWriter);
232 Server->Transp.reply(std::move(ID), std::move(Reply));
233 } else {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000234 llvm::Error Err = Reply.takeError();
Sam McCalld7babe42018-10-24 15:18:40 +0000235 log("--> reply:{0}({1}) {2:ms}, error: {3}", Method, ID, Duration, Err);
236 if (TraceArgs)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000237 (*TraceArgs)["Error"] = llvm::to_string(Err);
Sam McCalld7babe42018-10-24 15:18:40 +0000238 std::lock_guard<std::mutex> Lock(Server->TranspWriter);
239 Server->Transp.reply(std::move(ID), std::move(Err));
Sam McCalle2f3a732018-10-24 14:26:26 +0000240 }
Sam McCalle2f3a732018-10-24 14:26:26 +0000241 }
242 };
243
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000244 llvm::StringMap<std::function<void(llvm::json::Value)>> Notifications;
245 llvm::StringMap<std::function<void(llvm::json::Value, ReplyOnce)>> Calls;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000246
247 // Method calls may be cancelled by ID, so keep track of their state.
248 // This needs a mutex: handlers may finish on a different thread, and that's
249 // when we clean up entries in the map.
250 mutable std::mutex RequestCancelersMutex;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000251 llvm::StringMap<std::pair<Canceler, /*Cookie*/ unsigned>> RequestCancelers;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000252 unsigned NextRequestCookie = 0; // To disambiguate reused IDs, see below.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000253 void onCancel(const llvm::json::Value &Params) {
254 const llvm::json::Value *ID = nullptr;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000255 if (auto *O = Params.getAsObject())
256 ID = O->get("id");
257 if (!ID) {
258 elog("Bad cancellation request: {0}", Params);
259 return;
260 }
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000261 auto StrID = llvm::to_string(*ID);
Sam McCall2c30fbc2018-10-18 12:32:04 +0000262 std::lock_guard<std::mutex> Lock(RequestCancelersMutex);
263 auto It = RequestCancelers.find(StrID);
264 if (It != RequestCancelers.end())
265 It->second.first(); // Invoke the canceler.
266 }
Sam McCalla69698f2019-03-27 17:47:49 +0000267
268 Context handlerContext() const {
269 return Context::current().derive(
270 kCurrentOffsetEncoding,
271 Server.NegotiatedOffsetEncoding.getValueOr(OffsetEncoding::UTF16));
272 }
273
Sam McCall2c30fbc2018-10-18 12:32:04 +0000274 // We run cancelable requests in a context that does two things:
275 // - allows cancellation using RequestCancelers[ID]
276 // - cleans up the entry in RequestCancelers when it's no longer needed
277 // If a client reuses an ID, the last wins and the first cannot be canceled.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000278 Context cancelableRequestContext(const llvm::json::Value &ID) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000279 auto Task = cancelableTask();
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000280 auto StrID = llvm::to_string(ID); // JSON-serialize ID for map key.
Sam McCall2c30fbc2018-10-18 12:32:04 +0000281 auto Cookie = NextRequestCookie++; // No lock, only called on main thread.
282 {
283 std::lock_guard<std::mutex> Lock(RequestCancelersMutex);
284 RequestCancelers[StrID] = {std::move(Task.second), Cookie};
285 }
286 // When the request ends, we can clean up the entry we just added.
287 // The cookie lets us check that it hasn't been overwritten due to ID
288 // reuse.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000289 return Task.first.derive(llvm::make_scope_exit([this, StrID, Cookie] {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000290 std::lock_guard<std::mutex> Lock(RequestCancelersMutex);
291 auto It = RequestCancelers.find(StrID);
292 if (It != RequestCancelers.end() && It->second.second == Cookie)
293 RequestCancelers.erase(It);
294 }));
295 }
296
297 ClangdLSPServer &Server;
298};
299
300// call(), notify(), and reply() wrap the Transport, adding logging and locking.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000301void ClangdLSPServer::call(llvm::StringRef Method, llvm::json::Value Params) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000302 auto ID = NextCallID++;
303 log("--> {0}({1})", Method, ID);
304 // We currently don't handle responses, so no need to store ID anywhere.
305 std::lock_guard<std::mutex> Lock(TranspWriter);
306 Transp.call(Method, std::move(Params), ID);
307}
308
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000309void ClangdLSPServer::notify(llvm::StringRef Method, llvm::json::Value Params) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000310 log("--> {0}", Method);
311 std::lock_guard<std::mutex> Lock(TranspWriter);
312 Transp.notify(Method, std::move(Params));
313}
314
Sam McCall2c30fbc2018-10-18 12:32:04 +0000315void ClangdLSPServer::onInitialize(const InitializeParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000316 Callback<llvm::json::Value> Reply) {
Sam McCalla69698f2019-03-27 17:47:49 +0000317 // Determine character encoding first as it affects constructed ClangdServer.
318 if (Params.capabilities.offsetEncoding && !NegotiatedOffsetEncoding) {
319 NegotiatedOffsetEncoding = OffsetEncoding::UTF16; // fallback
320 for (OffsetEncoding Supported : *Params.capabilities.offsetEncoding)
321 if (Supported != OffsetEncoding::UnsupportedEncoding) {
322 NegotiatedOffsetEncoding = Supported;
323 break;
324 }
325 }
326 llvm::Optional<WithContextValue> WithOffsetEncoding;
327 if (NegotiatedOffsetEncoding)
328 WithOffsetEncoding.emplace(kCurrentOffsetEncoding,
329 *NegotiatedOffsetEncoding);
330
Sam McCall0d9b40f2018-10-19 15:42:23 +0000331 if (Params.rootUri && *Params.rootUri)
332 ClangdServerOpts.WorkspaceRoot = Params.rootUri->file();
333 else if (Params.rootPath && !Params.rootPath->empty())
334 ClangdServerOpts.WorkspaceRoot = *Params.rootPath;
Sam McCall3d0adbe2018-10-18 14:41:50 +0000335 if (Server)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000336 return Reply(llvm::make_error<LSPError>("server already initialized",
337 ErrorCode::InvalidRequest));
Sam McCallbc904612018-10-25 04:22:52 +0000338 if (const auto &Dir = Params.initializationOptions.compilationDatabasePath)
339 CompileCommandsDir = Dir;
Kadir Cetinkaya256247c2019-06-26 07:45:27 +0000340 if (UseDirBasedCDB) {
Sam McCallc55d09a2018-11-02 13:09:36 +0000341 BaseCDB = llvm::make_unique<DirectoryBasedGlobalCompilationDatabase>(
342 CompileCommandsDir);
Kadir Cetinkaya256247c2019-06-26 07:45:27 +0000343 BaseCDB = getQueryDriverDatabase(
344 llvm::makeArrayRef(ClangdServerOpts.QueryDriverGlobs),
345 std::move(BaseCDB));
346 }
Kadir Cetinkayabe6b35d2019-01-22 09:10:20 +0000347 CDB.emplace(BaseCDB.get(), Params.initializationOptions.fallbackFlags,
348 ClangdServerOpts.ResourceDir);
Sam McCallc55d09a2018-11-02 13:09:36 +0000349 Server.emplace(*CDB, FSProvider, static_cast<DiagnosticsConsumer &>(*this),
350 ClangdServerOpts);
Sam McCallbc904612018-10-25 04:22:52 +0000351 applyConfiguration(Params.initializationOptions.ConfigSettings);
Simon Marchi88016782018-08-01 11:28:49 +0000352
Sam McCallbf6a2fc2018-10-17 07:33:42 +0000353 CCOpts.EnableSnippets = Params.capabilities.CompletionSnippets;
Sam McCall8d412942019-06-18 11:57:26 +0000354 CCOpts.IncludeFixIts = Params.capabilities.CompletionFixes;
Sam McCallbf6a2fc2018-10-17 07:33:42 +0000355 DiagOpts.EmbedFixesInDiagnostics = Params.capabilities.DiagnosticFixes;
356 DiagOpts.SendDiagnosticCategory = Params.capabilities.DiagnosticCategory;
Sam McCallc9e4ee92019-04-18 15:17:07 +0000357 DiagOpts.EmitRelatedLocations =
358 Params.capabilities.DiagnosticRelatedInformation;
Sam McCallbf6a2fc2018-10-17 07:33:42 +0000359 if (Params.capabilities.WorkspaceSymbolKinds)
360 SupportedSymbolKinds |= *Params.capabilities.WorkspaceSymbolKinds;
361 if (Params.capabilities.CompletionItemKinds)
362 SupportedCompletionItemKinds |= *Params.capabilities.CompletionItemKinds;
363 SupportsCodeAction = Params.capabilities.CodeActionStructure;
Ilya Biryukov19d75602018-11-23 15:21:19 +0000364 SupportsHierarchicalDocumentSymbol =
365 Params.capabilities.HierarchicalDocumentSymbol;
Haojian Wub6188492018-12-20 15:39:12 +0000366 SupportFileStatus = Params.initializationOptions.FileStatus;
Ilya Biryukovf9169d02019-05-29 10:01:00 +0000367 HoverContentFormat = Params.capabilities.HoverContentFormat;
Ilya Biryukov4ef0f822019-06-04 09:36:59 +0000368 SupportsOffsetsInSignatureHelp = Params.capabilities.OffsetsInSignatureHelp;
Sam McCalla69698f2019-03-27 17:47:49 +0000369 llvm::json::Object Result{
Sam McCall0930ab02017-11-07 15:49:35 +0000370 {{"capabilities",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000371 llvm::json::Object{
Simon Marchi98082622018-03-26 14:41:40 +0000372 {"textDocumentSync", (int)TextDocumentSyncKind::Incremental},
Sam McCall0930ab02017-11-07 15:49:35 +0000373 {"documentFormattingProvider", true},
374 {"documentRangeFormattingProvider", true},
375 {"documentOnTypeFormattingProvider",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000376 llvm::json::Object{
Sam McCall25c62572019-06-10 14:26:21 +0000377 {"firstTriggerCharacter", "\n"},
Sam McCall0930ab02017-11-07 15:49:35 +0000378 {"moreTriggerCharacter", {}},
379 }},
380 {"codeActionProvider", true},
381 {"completionProvider",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000382 llvm::json::Object{
Sam McCall0930ab02017-11-07 15:49:35 +0000383 {"resolveProvider", false},
Ilya Biryukovb0826bd2019-01-03 13:37:12 +0000384 // We do extra checks for '>' and ':' in completion to only
385 // trigger on '->' and '::'.
Sam McCall0930ab02017-11-07 15:49:35 +0000386 {"triggerCharacters", {".", ">", ":"}},
387 }},
388 {"signatureHelpProvider",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000389 llvm::json::Object{
Sam McCall0930ab02017-11-07 15:49:35 +0000390 {"triggerCharacters", {"(", ","}},
391 }},
Sam McCall866ba2c2019-02-01 11:26:13 +0000392 {"declarationProvider", true},
Sam McCall0930ab02017-11-07 15:49:35 +0000393 {"definitionProvider", true},
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000394 {"documentHighlightProvider", true},
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000395 {"hoverProvider", true},
Haojian Wu345099c2017-11-09 11:30:04 +0000396 {"renameProvider", true},
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000397 {"documentSymbolProvider", true},
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000398 {"workspaceSymbolProvider", true},
Sam McCall1ad142f2018-09-05 11:53:07 +0000399 {"referencesProvider", true},
Sam McCall0930ab02017-11-07 15:49:35 +0000400 {"executeCommandProvider",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000401 llvm::json::Object{
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000402 {"commands",
403 {ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND,
404 ExecuteCommandParams::CLANGD_APPLY_TWEAK}},
Sam McCall0930ab02017-11-07 15:49:35 +0000405 }},
Kadir Cetinkaya86658022019-03-19 09:27:04 +0000406 {"typeHierarchyProvider", true},
Sam McCalla69698f2019-03-27 17:47:49 +0000407 }}}};
408 if (NegotiatedOffsetEncoding)
409 Result["offsetEncoding"] = *NegotiatedOffsetEncoding;
410 Reply(std::move(Result));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000411}
412
Sam McCall2c30fbc2018-10-18 12:32:04 +0000413void ClangdLSPServer::onShutdown(const ShutdownParams &Params,
414 Callback<std::nullptr_t> Reply) {
Ilya Biryukov0d9b8a32017-10-25 08:45:41 +0000415 // Do essentially nothing, just say we're ready to exit.
416 ShutdownRequestReceived = true;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000417 Reply(nullptr);
Sam McCall8a5dded2017-10-12 13:29:58 +0000418}
Ilya Biryukovafb55542017-05-16 14:40:30 +0000419
Sam McCall422c8282018-11-26 16:00:11 +0000420// sync is a clangd extension: it blocks until all background work completes.
421// It blocks the calling thread, so no messages are processed until it returns!
422void ClangdLSPServer::onSync(const NoParams &Params,
423 Callback<std::nullptr_t> Reply) {
424 if (Server->blockUntilIdleForTest(/*TimeoutSeconds=*/60))
425 Reply(nullptr);
426 else
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000427 Reply(llvm::createStringError(llvm::inconvertibleErrorCode(),
428 "Not idle after a minute"));
Sam McCall422c8282018-11-26 16:00:11 +0000429}
430
Sam McCall2c30fbc2018-10-18 12:32:04 +0000431void ClangdLSPServer::onDocumentDidOpen(
432 const DidOpenTextDocumentParams &Params) {
Simon Marchi9569fd52018-03-16 14:30:42 +0000433 PathRef File = Params.textDocument.uri.file();
Ilya Biryukovb10ef472018-06-13 09:20:41 +0000434
Sam McCall2c30fbc2018-10-18 12:32:04 +0000435 const std::string &Contents = Params.textDocument.text;
Simon Marchi9569fd52018-03-16 14:30:42 +0000436
Simon Marchi98082622018-03-26 14:41:40 +0000437 DraftMgr.addDraft(File, Contents);
Ilya Biryukov652364b2018-09-26 05:48:29 +0000438 Server->addDocument(File, Contents, WantDiagnostics::Yes);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000439}
440
Sam McCall2c30fbc2018-10-18 12:32:04 +0000441void ClangdLSPServer::onDocumentDidChange(
442 const DidChangeTextDocumentParams &Params) {
Eric Liu51fed182018-02-22 18:40:39 +0000443 auto WantDiags = WantDiagnostics::Auto;
444 if (Params.wantDiagnostics.hasValue())
445 WantDiags = Params.wantDiagnostics.getValue() ? WantDiagnostics::Yes
446 : WantDiagnostics::No;
Simon Marchi9569fd52018-03-16 14:30:42 +0000447
448 PathRef File = Params.textDocument.uri.file();
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000449 llvm::Expected<std::string> Contents =
Simon Marchi98082622018-03-26 14:41:40 +0000450 DraftMgr.updateDraft(File, Params.contentChanges);
451 if (!Contents) {
452 // If this fails, we are most likely going to be not in sync anymore with
453 // the client. It is better to remove the draft and let further operations
454 // fail rather than giving wrong results.
455 DraftMgr.removeDraft(File);
Ilya Biryukov652364b2018-09-26 05:48:29 +0000456 Server->removeDocument(File);
Sam McCallbed58852018-07-11 10:35:11 +0000457 elog("Failed to update {0}: {1}", File, Contents.takeError());
Simon Marchi98082622018-03-26 14:41:40 +0000458 return;
459 }
Simon Marchi9569fd52018-03-16 14:30:42 +0000460
Ilya Biryukov652364b2018-09-26 05:48:29 +0000461 Server->addDocument(File, *Contents, WantDiags);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000462}
463
Sam McCall2c30fbc2018-10-18 12:32:04 +0000464void ClangdLSPServer::onFileEvent(const DidChangeWatchedFilesParams &Params) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000465 Server->onFileEvent(Params);
Marc-Andre Laperlebf114242017-10-02 18:00:37 +0000466}
467
Sam McCall2c30fbc2018-10-18 12:32:04 +0000468void ClangdLSPServer::onCommand(const ExecuteCommandParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000469 Callback<llvm::json::Value> Reply) {
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000470 auto ApplyEdit = [this](WorkspaceEdit WE) {
Eric Liuc5105f92018-02-16 14:15:55 +0000471 ApplyWorkspaceEditParams Edit;
472 Edit.edit = std::move(WE);
Eric Liuc5105f92018-02-16 14:15:55 +0000473 // Ideally, we would wait for the response and if there is no error, we
474 // would reply success/failure to the original RPC.
475 call("workspace/applyEdit", Edit);
476 };
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000477 if (Params.command == ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND &&
478 Params.workspaceEdit) {
479 // The flow for "apply-fix" :
480 // 1. We publish a diagnostic, including fixits
481 // 2. The user clicks on the diagnostic, the editor asks us for code actions
482 // 3. We send code actions, with the fixit embedded as context
483 // 4. The user selects the fixit, the editor asks us to apply it
484 // 5. We unwrap the changes and send them back to the editor
485 // 6. The editor applies the changes (applyEdit), and sends us a reply (but
486 // we ignore it)
487
Sam McCall2c30fbc2018-10-18 12:32:04 +0000488 Reply("Fix applied.");
Eric Liuc5105f92018-02-16 14:15:55 +0000489 ApplyEdit(*Params.workspaceEdit);
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000490 } else if (Params.command == ExecuteCommandParams::CLANGD_APPLY_TWEAK &&
491 Params.tweakArgs) {
492 auto Code = DraftMgr.getDraft(Params.tweakArgs->file.file());
493 if (!Code)
494 return Reply(llvm::createStringError(
495 llvm::inconvertibleErrorCode(),
496 "trying to apply a code action for a non-added file"));
497
Sam McCall395fde72019-06-18 13:37:54 +0000498 auto Action = [this, ApplyEdit](decltype(Reply) Reply, URIForFile File,
499 std::string Code,
Sam McCall08372eb2019-06-19 07:29:10 +0000500 llvm::Expected<Tweak::Effect> R) {
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000501 if (!R)
502 return Reply(R.takeError());
503
Sam McCall395fde72019-06-18 13:37:54 +0000504 if (R->ApplyEdit) {
505 WorkspaceEdit WE;
506 WE.changes.emplace();
Sam McCall08372eb2019-06-19 07:29:10 +0000507 (*WE.changes)[File.uri()] = replacementsToEdits(Code, *R->ApplyEdit);
Sam McCall395fde72019-06-18 13:37:54 +0000508 ApplyEdit(std::move(WE));
509 }
510 if (R->ShowMessage) {
511 ShowMessageParams Msg;
512 Msg.message = *R->ShowMessage;
513 Msg.type = MessageType::Info;
514 notify("window/showMessage", Msg);
515 }
516 Reply("Tweak applied.");
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000517 };
518 Server->applyTweak(Params.tweakArgs->file.file(),
519 Params.tweakArgs->selection, Params.tweakArgs->tweakID,
520 Bind(Action, std::move(Reply), Params.tweakArgs->file,
521 std::move(*Code)));
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000522 } else {
523 // We should not get here because ExecuteCommandParams would not have
524 // parsed in the first place and this handler should not be called. But if
525 // more commands are added, this will be here has a safe guard.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000526 Reply(llvm::make_error<LSPError>(
527 llvm::formatv("Unsupported command \"{0}\".", Params.command).str(),
Sam McCall2c30fbc2018-10-18 12:32:04 +0000528 ErrorCode::InvalidParams));
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000529 }
530}
531
Sam McCall2c30fbc2018-10-18 12:32:04 +0000532void ClangdLSPServer::onWorkspaceSymbol(
533 const WorkspaceSymbolParams &Params,
534 Callback<std::vector<SymbolInformation>> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000535 Server->workspaceSymbols(
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000536 Params.query, CCOpts.Limit,
Sam McCall2c30fbc2018-10-18 12:32:04 +0000537 Bind(
538 [this](decltype(Reply) Reply,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000539 llvm::Expected<std::vector<SymbolInformation>> Items) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000540 if (!Items)
541 return Reply(Items.takeError());
542 for (auto &Sym : *Items)
543 Sym.kind = adjustKindToCapability(Sym.kind, SupportedSymbolKinds);
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000544
Sam McCall2c30fbc2018-10-18 12:32:04 +0000545 Reply(std::move(*Items));
546 },
547 std::move(Reply)));
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000548}
549
Sam McCall2c30fbc2018-10-18 12:32:04 +0000550void ClangdLSPServer::onRename(const RenameParams &Params,
551 Callback<WorkspaceEdit> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000552 Path File = Params.textDocument.uri.file();
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000553 llvm::Optional<std::string> Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000554 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000555 return Reply(llvm::make_error<LSPError>(
556 "onRename called for non-added file", ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000557
Ilya Biryukov652364b2018-09-26 05:48:29 +0000558 Server->rename(
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000559 File, Params.position, Params.newName,
Sam McCall2c30fbc2018-10-18 12:32:04 +0000560 Bind(
Ilya Biryukovd9c24dc2019-04-03 07:18:43 +0000561 [File, Code, Params](decltype(Reply) Reply,
562 llvm::Expected<std::vector<TextEdit>> Edits) {
563 if (!Edits)
564 return Reply(Edits.takeError());
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000565
Sam McCall2c30fbc2018-10-18 12:32:04 +0000566 WorkspaceEdit WE;
Ilya Biryukovd9c24dc2019-04-03 07:18:43 +0000567 WE.changes = {{Params.textDocument.uri.uri(), *Edits}};
Sam McCall2c30fbc2018-10-18 12:32:04 +0000568 Reply(WE);
569 },
570 std::move(Reply)));
Haojian Wu345099c2017-11-09 11:30:04 +0000571}
572
Sam McCall2c30fbc2018-10-18 12:32:04 +0000573void ClangdLSPServer::onDocumentDidClose(
574 const DidCloseTextDocumentParams &Params) {
Simon Marchi9569fd52018-03-16 14:30:42 +0000575 PathRef File = Params.textDocument.uri.file();
576 DraftMgr.removeDraft(File);
Ilya Biryukov652364b2018-09-26 05:48:29 +0000577 Server->removeDocument(File);
Ilya Biryukov49c10712019-03-25 10:15:11 +0000578
579 {
580 std::lock_guard<std::mutex> Lock(FixItsMutex);
581 FixItsMap.erase(File);
582 }
583 // clangd will not send updates for this file anymore, so we empty out the
584 // list of diagnostics shown on the client (e.g. in the "Problems" pane of
585 // VSCode). Note that this cannot race with actual diagnostics responses
586 // because removeDocument() guarantees no diagnostic callbacks will be
587 // executed after it returns.
588 publishDiagnostics(URIForFile::canonicalize(File, /*TUPath=*/File), {});
Ilya Biryukovafb55542017-05-16 14:40:30 +0000589}
590
Sam McCall4db732a2017-09-30 10:08:52 +0000591void ClangdLSPServer::onDocumentOnTypeFormatting(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000592 const DocumentOnTypeFormattingParams &Params,
593 Callback<std::vector<TextEdit>> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000594 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000595 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000596 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000597 return Reply(llvm::make_error<LSPError>(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000598 "onDocumentOnTypeFormatting called for non-added file",
599 ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000600
Sam McCall25c62572019-06-10 14:26:21 +0000601 Reply(Server->formatOnType(*Code, File, Params.position, Params.ch));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000602}
603
Sam McCall4db732a2017-09-30 10:08:52 +0000604void ClangdLSPServer::onDocumentRangeFormatting(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000605 const DocumentRangeFormattingParams &Params,
606 Callback<std::vector<TextEdit>> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000607 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000608 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000609 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000610 return Reply(llvm::make_error<LSPError>(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000611 "onDocumentRangeFormatting called for non-added file",
612 ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000613
Ilya Biryukov652364b2018-09-26 05:48:29 +0000614 auto ReplacementsOrError = Server->formatRange(*Code, File, Params.range);
Raoul Wols212bcf82017-12-12 20:25:06 +0000615 if (ReplacementsOrError)
Sam McCall2c30fbc2018-10-18 12:32:04 +0000616 Reply(replacementsToEdits(*Code, ReplacementsOrError.get()));
Raoul Wols212bcf82017-12-12 20:25:06 +0000617 else
Sam McCall2c30fbc2018-10-18 12:32:04 +0000618 Reply(ReplacementsOrError.takeError());
Ilya Biryukovafb55542017-05-16 14:40:30 +0000619}
620
Sam McCall2c30fbc2018-10-18 12:32:04 +0000621void ClangdLSPServer::onDocumentFormatting(
622 const DocumentFormattingParams &Params,
623 Callback<std::vector<TextEdit>> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000624 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000625 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000626 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000627 return Reply(llvm::make_error<LSPError>(
628 "onDocumentFormatting called for non-added file",
629 ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000630
Ilya Biryukov652364b2018-09-26 05:48:29 +0000631 auto ReplacementsOrError = Server->formatFile(*Code, File);
Raoul Wols212bcf82017-12-12 20:25:06 +0000632 if (ReplacementsOrError)
Sam McCall2c30fbc2018-10-18 12:32:04 +0000633 Reply(replacementsToEdits(*Code, ReplacementsOrError.get()));
Raoul Wols212bcf82017-12-12 20:25:06 +0000634 else
Sam McCall2c30fbc2018-10-18 12:32:04 +0000635 Reply(ReplacementsOrError.takeError());
Sam McCall4db732a2017-09-30 10:08:52 +0000636}
637
Ilya Biryukov19d75602018-11-23 15:21:19 +0000638/// The functions constructs a flattened view of the DocumentSymbol hierarchy.
639/// Used by the clients that do not support the hierarchical view.
640static std::vector<SymbolInformation>
641flattenSymbolHierarchy(llvm::ArrayRef<DocumentSymbol> Symbols,
642 const URIForFile &FileURI) {
643
644 std::vector<SymbolInformation> Results;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000645 std::function<void(const DocumentSymbol &, llvm::StringRef)> Process =
646 [&](const DocumentSymbol &S, llvm::Optional<llvm::StringRef> ParentName) {
Ilya Biryukov19d75602018-11-23 15:21:19 +0000647 SymbolInformation SI;
648 SI.containerName = ParentName ? "" : *ParentName;
649 SI.name = S.name;
650 SI.kind = S.kind;
651 SI.location.range = S.range;
652 SI.location.uri = FileURI;
653
654 Results.push_back(std::move(SI));
655 std::string FullName =
656 !ParentName ? S.name : (ParentName->str() + "::" + S.name);
657 for (auto &C : S.children)
658 Process(C, /*ParentName=*/FullName);
659 };
660 for (auto &S : Symbols)
661 Process(S, /*ParentName=*/"");
662 return Results;
663}
664
665void ClangdLSPServer::onDocumentSymbol(const DocumentSymbolParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000666 Callback<llvm::json::Value> Reply) {
Ilya Biryukov19d75602018-11-23 15:21:19 +0000667 URIForFile FileURI = Params.textDocument.uri;
Ilya Biryukov652364b2018-09-26 05:48:29 +0000668 Server->documentSymbols(
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000669 Params.textDocument.uri.file(),
Sam McCall2c30fbc2018-10-18 12:32:04 +0000670 Bind(
Ilya Biryukov19d75602018-11-23 15:21:19 +0000671 [this, FileURI](decltype(Reply) Reply,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000672 llvm::Expected<std::vector<DocumentSymbol>> Items) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000673 if (!Items)
674 return Reply(Items.takeError());
Ilya Biryukov19d75602018-11-23 15:21:19 +0000675 adjustSymbolKinds(*Items, SupportedSymbolKinds);
676 if (SupportsHierarchicalDocumentSymbol)
677 return Reply(std::move(*Items));
678 else
679 return Reply(flattenSymbolHierarchy(*Items, FileURI));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000680 },
681 std::move(Reply)));
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000682}
683
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000684static llvm::Optional<Command> asCommand(const CodeAction &Action) {
Sam McCall20841d42018-10-16 16:29:41 +0000685 Command Cmd;
686 if (Action.command && Action.edit)
Sam McCallc008af62018-10-20 15:30:37 +0000687 return None; // Not representable. (We never emit these anyway).
Sam McCall20841d42018-10-16 16:29:41 +0000688 if (Action.command) {
689 Cmd = *Action.command;
690 } else if (Action.edit) {
691 Cmd.command = Command::CLANGD_APPLY_FIX_COMMAND;
692 Cmd.workspaceEdit = *Action.edit;
693 } else {
Sam McCallc008af62018-10-20 15:30:37 +0000694 return None;
Sam McCall20841d42018-10-16 16:29:41 +0000695 }
696 Cmd.title = Action.title;
697 if (Action.kind && *Action.kind == CodeAction::QUICKFIX_KIND)
698 Cmd.title = "Apply fix: " + Cmd.title;
699 return Cmd;
700}
701
Sam McCall2c30fbc2018-10-18 12:32:04 +0000702void ClangdLSPServer::onCodeAction(const CodeActionParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000703 Callback<llvm::json::Value> Reply) {
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000704 URIForFile File = Params.textDocument.uri;
705 auto Code = DraftMgr.getDraft(File.file());
Sam McCall2c30fbc2018-10-18 12:32:04 +0000706 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000707 return Reply(llvm::make_error<LSPError>(
708 "onCodeAction called for non-added file", ErrorCode::InvalidParams));
Sam McCall20841d42018-10-16 16:29:41 +0000709 // We provide a code action for Fixes on the specified diagnostics.
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000710 std::vector<CodeAction> FixIts;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000711 for (const Diagnostic &D : Params.context.diagnostics) {
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000712 for (auto &F : getFixes(File.file(), D)) {
713 FixIts.push_back(toCodeAction(F, Params.textDocument.uri));
714 FixIts.back().diagnostics = {D};
Sam McCalldd0566b2017-11-06 15:40:30 +0000715 }
Ilya Biryukovafb55542017-05-16 14:40:30 +0000716 }
Sam McCall20841d42018-10-16 16:29:41 +0000717
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000718 // Now enumerate the semantic code actions.
719 auto ConsumeActions =
720 [this](decltype(Reply) Reply, URIForFile File, std::string Code,
721 Range Selection, std::vector<CodeAction> FixIts,
722 llvm::Expected<std::vector<ClangdServer::TweakRef>> Tweaks) {
Ilya Biryukovc6ed7782019-01-30 14:24:17 +0000723 if (!Tweaks)
724 return Reply(Tweaks.takeError());
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000725
726 std::vector<CodeAction> Actions = std::move(FixIts);
727 Actions.reserve(Actions.size() + Tweaks->size());
728 for (const auto &T : *Tweaks)
729 Actions.push_back(toCodeAction(T, File, Selection));
730
731 if (SupportsCodeAction)
732 return Reply(llvm::json::Array(Actions));
733 std::vector<Command> Commands;
734 for (const auto &Action : Actions) {
735 if (auto Command = asCommand(Action))
736 Commands.push_back(std::move(*Command));
737 }
738 return Reply(llvm::json::Array(Commands));
739 };
740
741 Server->enumerateTweaks(File.file(), Params.range,
Ilya Biryukovc9409c62019-01-30 09:39:01 +0000742 Bind(ConsumeActions, std::move(Reply), File,
743 std::move(*Code), Params.range,
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000744 std::move(FixIts)));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000745}
746
Ilya Biryukovb0826bd2019-01-03 13:37:12 +0000747void ClangdLSPServer::onCompletion(const CompletionParams &Params,
Sam McCall2c30fbc2018-10-18 12:32:04 +0000748 Callback<CompletionList> Reply) {
Ilya Biryukova7a11472019-06-07 16:24:38 +0000749 if (!shouldRunCompletion(Params)) {
750 // Clients sometimes auto-trigger completions in undesired places (e.g.
751 // 'a >^ '), we return empty results in those cases.
752 vlog("ignored auto-triggered completion, preceding char did not match");
753 return Reply(CompletionList());
754 }
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000755 Server->codeComplete(Params.textDocument.uri.file(), Params.position, CCOpts,
756 Bind(
757 [this](decltype(Reply) Reply,
758 llvm::Expected<CodeCompleteResult> List) {
759 if (!List)
760 return Reply(List.takeError());
761 CompletionList LSPList;
762 LSPList.isIncomplete = List->HasMore;
763 for (const auto &R : List->Completions) {
764 CompletionItem C = R.render(CCOpts);
765 C.kind = adjustKindToCapability(
766 C.kind, SupportedCompletionItemKinds);
767 LSPList.items.push_back(std::move(C));
768 }
769 return Reply(std::move(LSPList));
770 },
771 std::move(Reply)));
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000772}
773
Sam McCall2c30fbc2018-10-18 12:32:04 +0000774void ClangdLSPServer::onSignatureHelp(const TextDocumentPositionParams &Params,
775 Callback<SignatureHelp> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000776 Server->signatureHelp(Params.textDocument.uri.file(), Params.position,
Ilya Biryukov4ef0f822019-06-04 09:36:59 +0000777 Bind(
778 [this](decltype(Reply) Reply,
779 llvm::Expected<SignatureHelp> Signature) {
780 if (!Signature)
781 return Reply(Signature.takeError());
782 if (SupportsOffsetsInSignatureHelp)
783 return Reply(std::move(*Signature));
784 // Strip out the offsets from signature help for
785 // clients that only support string labels.
Simon Pilgrim5f7c20e2019-06-04 11:11:51 +0000786 for (auto &SigInfo : Signature->signatures) {
787 for (auto &Param : SigInfo.parameters)
Ilya Biryukov4ef0f822019-06-04 09:36:59 +0000788 Param.labelOffsets.reset();
789 }
790 return Reply(std::move(*Signature));
791 },
792 std::move(Reply)));
Ilya Biryukov652364b2018-09-26 05:48:29 +0000793}
794
Sam McCall0dbab7f2019-02-02 05:56:00 +0000795// Go to definition has a toggle function: if def and decl are distinct, then
796// the first press gives you the def, the second gives you the matching def.
797// getToggle() returns the counterpart location that under the cursor.
798//
799// We return the toggled location alone (ignoring other symbols) to encourage
800// editors to "bounce" quickly between locations, without showing a menu.
801static Location *getToggle(const TextDocumentPositionParams &Point,
802 LocatedSymbol &Sym) {
803 // Toggle only makes sense with two distinct locations.
804 if (!Sym.Definition || *Sym.Definition == Sym.PreferredDeclaration)
805 return nullptr;
806 if (Sym.Definition->uri.file() == Point.textDocument.uri.file() &&
807 Sym.Definition->range.contains(Point.position))
808 return &Sym.PreferredDeclaration;
809 if (Sym.PreferredDeclaration.uri.file() == Point.textDocument.uri.file() &&
810 Sym.PreferredDeclaration.range.contains(Point.position))
811 return &*Sym.Definition;
812 return nullptr;
813}
814
Sam McCall2c30fbc2018-10-18 12:32:04 +0000815void ClangdLSPServer::onGoToDefinition(const TextDocumentPositionParams &Params,
816 Callback<std::vector<Location>> Reply) {
Sam McCall866ba2c2019-02-01 11:26:13 +0000817 Server->locateSymbolAt(
818 Params.textDocument.uri.file(), Params.position,
819 Bind(
Sam McCall0dbab7f2019-02-02 05:56:00 +0000820 [&, Params](decltype(Reply) Reply,
821 llvm::Expected<std::vector<LocatedSymbol>> Symbols) {
Sam McCall866ba2c2019-02-01 11:26:13 +0000822 if (!Symbols)
823 return Reply(Symbols.takeError());
824 std::vector<Location> Defs;
Sam McCall0dbab7f2019-02-02 05:56:00 +0000825 for (auto &S : *Symbols) {
826 if (Location *Toggle = getToggle(Params, S))
827 return Reply(std::vector<Location>{std::move(*Toggle)});
Sam McCall866ba2c2019-02-01 11:26:13 +0000828 Defs.push_back(S.Definition.getValueOr(S.PreferredDeclaration));
Sam McCall0dbab7f2019-02-02 05:56:00 +0000829 }
Sam McCall866ba2c2019-02-01 11:26:13 +0000830 Reply(std::move(Defs));
831 },
832 std::move(Reply)));
833}
834
835void ClangdLSPServer::onGoToDeclaration(
836 const TextDocumentPositionParams &Params,
837 Callback<std::vector<Location>> Reply) {
838 Server->locateSymbolAt(
839 Params.textDocument.uri.file(), Params.position,
840 Bind(
Sam McCall0dbab7f2019-02-02 05:56:00 +0000841 [&, Params](decltype(Reply) Reply,
842 llvm::Expected<std::vector<LocatedSymbol>> Symbols) {
Sam McCall866ba2c2019-02-01 11:26:13 +0000843 if (!Symbols)
844 return Reply(Symbols.takeError());
845 std::vector<Location> Decls;
Sam McCall0dbab7f2019-02-02 05:56:00 +0000846 for (auto &S : *Symbols) {
847 if (Location *Toggle = getToggle(Params, S))
848 return Reply(std::vector<Location>{std::move(*Toggle)});
849 Decls.push_back(std::move(S.PreferredDeclaration));
850 }
Sam McCall866ba2c2019-02-01 11:26:13 +0000851 Reply(std::move(Decls));
852 },
853 std::move(Reply)));
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000854}
855
Sam McCall111fe842019-05-07 07:55:35 +0000856void ClangdLSPServer::onSwitchSourceHeader(
857 const TextDocumentIdentifier &Params,
Sam McCallb9ec3e92019-05-07 08:30:32 +0000858 Callback<llvm::Optional<URIForFile>> Reply) {
Sam McCall111fe842019-05-07 07:55:35 +0000859 if (auto Result = Server->switchSourceHeader(Params.uri.file()))
Sam McCallb9ec3e92019-05-07 08:30:32 +0000860 Reply(URIForFile::canonicalize(*Result, Params.uri.file()));
Sam McCall111fe842019-05-07 07:55:35 +0000861 else
862 Reply(llvm::None);
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000863}
864
Sam McCall2c30fbc2018-10-18 12:32:04 +0000865void ClangdLSPServer::onDocumentHighlight(
866 const TextDocumentPositionParams &Params,
867 Callback<std::vector<DocumentHighlight>> Reply) {
868 Server->findDocumentHighlights(Params.textDocument.uri.file(),
869 Params.position, std::move(Reply));
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000870}
871
Sam McCall2c30fbc2018-10-18 12:32:04 +0000872void ClangdLSPServer::onHover(const TextDocumentPositionParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000873 Callback<llvm::Optional<Hover>> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000874 Server->findHover(Params.textDocument.uri.file(), Params.position,
Kadir Cetinkayac6578ee2019-05-28 10:29:58 +0000875 Bind(
Ilya Biryukovf9169d02019-05-29 10:01:00 +0000876 [this](decltype(Reply) Reply,
877 llvm::Expected<llvm::Optional<HoverInfo>> H) {
878 if (!H)
879 return Reply(H.takeError());
880 if (!*H)
Kadir Cetinkayac6578ee2019-05-28 10:29:58 +0000881 return Reply(llvm::None);
Ilya Biryukovf9169d02019-05-29 10:01:00 +0000882
883 Hover R;
884 R.contents.kind = HoverContentFormat;
885 R.range = (*H)->SymRange;
886 switch (HoverContentFormat) {
887 case MarkupKind::PlainText:
888 R.contents.value =
889 (*H)->present().renderAsPlainText();
890 return Reply(std::move(R));
891 case MarkupKind::Markdown:
892 R.contents.value =
893 (*H)->present().renderAsMarkdown();
894 return Reply(std::move(R));
895 };
896 llvm_unreachable("unhandled MarkupKind");
Kadir Cetinkayac6578ee2019-05-28 10:29:58 +0000897 },
898 std::move(Reply)));
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000899}
900
Kadir Cetinkaya86658022019-03-19 09:27:04 +0000901void ClangdLSPServer::onTypeHierarchy(
902 const TypeHierarchyParams &Params,
903 Callback<Optional<TypeHierarchyItem>> Reply) {
904 Server->typeHierarchy(Params.textDocument.uri.file(), Params.position,
905 Params.resolve, Params.direction, std::move(Reply));
906}
907
Simon Marchi88016782018-08-01 11:28:49 +0000908void ClangdLSPServer::applyConfiguration(
Sam McCallbc904612018-10-25 04:22:52 +0000909 const ConfigurationSettings &Settings) {
Simon Marchiabeed662018-10-16 15:55:03 +0000910 // Per-file update to the compilation database.
Sam McCallbc904612018-10-25 04:22:52 +0000911 bool ShouldReparseOpenFiles = false;
912 for (auto &Entry : Settings.compilationDatabaseChanges) {
913 /// The opened files need to be reparsed only when some existing
914 /// entries are changed.
915 PathRef File = Entry.first;
Sam McCallc55d09a2018-11-02 13:09:36 +0000916 auto Old = CDB->getCompileCommand(File);
917 auto New =
918 tooling::CompileCommand(std::move(Entry.second.workingDirectory), File,
919 std::move(Entry.second.compilationCommand),
920 /*Output=*/"");
Sam McCall6980edb2018-11-02 14:07:51 +0000921 if (Old != New) {
Sam McCallc55d09a2018-11-02 13:09:36 +0000922 CDB->setCompileCommand(File, std::move(New));
Sam McCall6980edb2018-11-02 14:07:51 +0000923 ShouldReparseOpenFiles = true;
924 }
Alex Lorenzf8087862018-08-01 17:39:29 +0000925 }
Sam McCallbc904612018-10-25 04:22:52 +0000926 if (ShouldReparseOpenFiles)
927 reparseOpenedFiles();
Simon Marchi5178f922018-02-22 14:00:39 +0000928}
929
Ilya Biryukov49c10712019-03-25 10:15:11 +0000930void ClangdLSPServer::publishDiagnostics(
931 const URIForFile &File, std::vector<clangd::Diagnostic> Diagnostics) {
932 // Publish diagnostics.
933 notify("textDocument/publishDiagnostics",
934 llvm::json::Object{
935 {"uri", File},
936 {"diagnostics", std::move(Diagnostics)},
937 });
938}
939
Simon Marchi88016782018-08-01 11:28:49 +0000940// FIXME: This function needs to be properly tested.
941void ClangdLSPServer::onChangeConfiguration(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000942 const DidChangeConfigurationParams &Params) {
Simon Marchi88016782018-08-01 11:28:49 +0000943 applyConfiguration(Params.settings);
944}
945
Sam McCall2c30fbc2018-10-18 12:32:04 +0000946void ClangdLSPServer::onReference(const ReferenceParams &Params,
947 Callback<std::vector<Location>> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000948 Server->findReferences(Params.textDocument.uri.file(), Params.position,
Haojian Wuc34f0222019-01-14 18:11:09 +0000949 CCOpts.Limit, std::move(Reply));
Sam McCall1ad142f2018-09-05 11:53:07 +0000950}
951
Jan Korousb4067012018-11-27 16:40:46 +0000952void ClangdLSPServer::onSymbolInfo(const TextDocumentPositionParams &Params,
953 Callback<std::vector<SymbolDetails>> Reply) {
954 Server->symbolInfo(Params.textDocument.uri.file(), Params.position,
955 std::move(Reply));
956}
957
Sam McCalla69698f2019-03-27 17:47:49 +0000958ClangdLSPServer::ClangdLSPServer(
959 class Transport &Transp, const FileSystemProvider &FSProvider,
960 const clangd::CodeCompleteOptions &CCOpts,
961 llvm::Optional<Path> CompileCommandsDir, bool UseDirBasedCDB,
962 llvm::Optional<OffsetEncoding> ForcedOffsetEncoding,
963 const ClangdServer::Options &Opts)
Haojian Wu1ca0c582019-01-22 09:39:05 +0000964 : Transp(Transp), MsgHandler(new MessageHandler(*this)),
965 FSProvider(FSProvider), CCOpts(CCOpts),
Sam McCalld1c9d112018-10-23 14:19:54 +0000966 SupportedSymbolKinds(defaultSymbolKinds()),
Kadir Cetinkaya133d46f2018-09-27 17:13:07 +0000967 SupportedCompletionItemKinds(defaultCompletionItemKinds()),
Sam McCallc55d09a2018-11-02 13:09:36 +0000968 UseDirBasedCDB(UseDirBasedCDB),
Sam McCalla69698f2019-03-27 17:47:49 +0000969 CompileCommandsDir(std::move(CompileCommandsDir)), ClangdServerOpts(Opts),
970 NegotiatedOffsetEncoding(ForcedOffsetEncoding) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000971 // clang-format off
972 MsgHandler->bind("initialize", &ClangdLSPServer::onInitialize);
973 MsgHandler->bind("shutdown", &ClangdLSPServer::onShutdown);
Sam McCall422c8282018-11-26 16:00:11 +0000974 MsgHandler->bind("sync", &ClangdLSPServer::onSync);
Sam McCall2c30fbc2018-10-18 12:32:04 +0000975 MsgHandler->bind("textDocument/rangeFormatting", &ClangdLSPServer::onDocumentRangeFormatting);
976 MsgHandler->bind("textDocument/onTypeFormatting", &ClangdLSPServer::onDocumentOnTypeFormatting);
977 MsgHandler->bind("textDocument/formatting", &ClangdLSPServer::onDocumentFormatting);
978 MsgHandler->bind("textDocument/codeAction", &ClangdLSPServer::onCodeAction);
979 MsgHandler->bind("textDocument/completion", &ClangdLSPServer::onCompletion);
980 MsgHandler->bind("textDocument/signatureHelp", &ClangdLSPServer::onSignatureHelp);
981 MsgHandler->bind("textDocument/definition", &ClangdLSPServer::onGoToDefinition);
Sam McCall866ba2c2019-02-01 11:26:13 +0000982 MsgHandler->bind("textDocument/declaration", &ClangdLSPServer::onGoToDeclaration);
Sam McCall2c30fbc2018-10-18 12:32:04 +0000983 MsgHandler->bind("textDocument/references", &ClangdLSPServer::onReference);
984 MsgHandler->bind("textDocument/switchSourceHeader", &ClangdLSPServer::onSwitchSourceHeader);
985 MsgHandler->bind("textDocument/rename", &ClangdLSPServer::onRename);
986 MsgHandler->bind("textDocument/hover", &ClangdLSPServer::onHover);
987 MsgHandler->bind("textDocument/documentSymbol", &ClangdLSPServer::onDocumentSymbol);
988 MsgHandler->bind("workspace/executeCommand", &ClangdLSPServer::onCommand);
989 MsgHandler->bind("textDocument/documentHighlight", &ClangdLSPServer::onDocumentHighlight);
990 MsgHandler->bind("workspace/symbol", &ClangdLSPServer::onWorkspaceSymbol);
991 MsgHandler->bind("textDocument/didOpen", &ClangdLSPServer::onDocumentDidOpen);
992 MsgHandler->bind("textDocument/didClose", &ClangdLSPServer::onDocumentDidClose);
993 MsgHandler->bind("textDocument/didChange", &ClangdLSPServer::onDocumentDidChange);
994 MsgHandler->bind("workspace/didChangeWatchedFiles", &ClangdLSPServer::onFileEvent);
995 MsgHandler->bind("workspace/didChangeConfiguration", &ClangdLSPServer::onChangeConfiguration);
Jan Korousb4067012018-11-27 16:40:46 +0000996 MsgHandler->bind("textDocument/symbolInfo", &ClangdLSPServer::onSymbolInfo);
Kadir Cetinkaya86658022019-03-19 09:27:04 +0000997 MsgHandler->bind("textDocument/typeHierarchy", &ClangdLSPServer::onTypeHierarchy);
Sam McCall2c30fbc2018-10-18 12:32:04 +0000998 // clang-format on
999}
1000
1001ClangdLSPServer::~ClangdLSPServer() = default;
Ilya Biryukov38d79772017-05-16 09:38:59 +00001002
Sam McCalldc8f3cf2018-10-17 07:32:05 +00001003bool ClangdLSPServer::run() {
Ilya Biryukovafb55542017-05-16 14:40:30 +00001004 // Run the Language Server loop.
Sam McCalldc8f3cf2018-10-17 07:32:05 +00001005 bool CleanExit = true;
Sam McCall2c30fbc2018-10-18 12:32:04 +00001006 if (auto Err = Transp.loop(*MsgHandler)) {
Sam McCalldc8f3cf2018-10-17 07:32:05 +00001007 elog("Transport error: {0}", std::move(Err));
1008 CleanExit = false;
1009 }
Ilya Biryukovafb55542017-05-16 14:40:30 +00001010
Ilya Biryukov652364b2018-09-26 05:48:29 +00001011 // Destroy ClangdServer to ensure all worker threads finish.
1012 Server.reset();
Sam McCalldc8f3cf2018-10-17 07:32:05 +00001013 return CleanExit && ShutdownRequestReceived;
Ilya Biryukov38d79772017-05-16 09:38:59 +00001014}
1015
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001016std::vector<Fix> ClangdLSPServer::getFixes(llvm::StringRef File,
Ilya Biryukov71028b82018-03-12 15:28:22 +00001017 const clangd::Diagnostic &D) {
Ilya Biryukov38d79772017-05-16 09:38:59 +00001018 std::lock_guard<std::mutex> Lock(FixItsMutex);
1019 auto DiagToFixItsIter = FixItsMap.find(File);
1020 if (DiagToFixItsIter == FixItsMap.end())
1021 return {};
1022
1023 const auto &DiagToFixItsMap = DiagToFixItsIter->second;
1024 auto FixItsIter = DiagToFixItsMap.find(D);
1025 if (FixItsIter == DiagToFixItsMap.end())
1026 return {};
1027
1028 return FixItsIter->second;
1029}
1030
Ilya Biryukovb0826bd2019-01-03 13:37:12 +00001031bool ClangdLSPServer::shouldRunCompletion(
1032 const CompletionParams &Params) const {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001033 llvm::StringRef Trigger = Params.context.triggerCharacter;
Ilya Biryukovb0826bd2019-01-03 13:37:12 +00001034 if (Params.context.triggerKind != CompletionTriggerKind::TriggerCharacter ||
1035 (Trigger != ">" && Trigger != ":"))
1036 return true;
1037
1038 auto Code = DraftMgr.getDraft(Params.textDocument.uri.file());
1039 if (!Code)
1040 return true; // completion code will log the error for untracked doc.
1041
1042 // A completion request is sent when the user types '>' or ':', but we only
1043 // want to trigger on '->' and '::'. We check the preceeding character to make
1044 // sure it matches what we expected.
1045 // Running the lexer here would be more robust (e.g. we can detect comments
1046 // and avoid triggering completion there), but we choose to err on the side
1047 // of simplicity here.
1048 auto Offset = positionToOffset(*Code, Params.position,
1049 /*AllowColumnsBeyondLineLength=*/false);
1050 if (!Offset) {
1051 vlog("could not convert position '{0}' to offset for file '{1}'",
1052 Params.position, Params.textDocument.uri.file());
1053 return true;
1054 }
1055 if (*Offset < 2)
1056 return false;
1057
1058 if (Trigger == ">")
1059 return (*Code)[*Offset - 2] == '-'; // trigger only on '->'.
1060 if (Trigger == ":")
1061 return (*Code)[*Offset - 2] == ':'; // trigger only on '::'.
1062 assert(false && "unhandled trigger character");
1063 return true;
1064}
1065
Sam McCalla7bb0cc2018-03-12 23:22:35 +00001066void ClangdLSPServer::onDiagnosticsReady(PathRef File,
1067 std::vector<Diag> Diagnostics) {
Eric Liu4d814a92018-11-28 10:30:42 +00001068 auto URI = URIForFile::canonicalize(File, /*TUPath=*/File);
Sam McCall16e70702018-10-24 07:59:38 +00001069 std::vector<Diagnostic> LSPDiagnostics;
Ilya Biryukov38d79772017-05-16 09:38:59 +00001070 DiagnosticToReplacementMap LocalFixIts; // Temporary storage
Sam McCalla7bb0cc2018-03-12 23:22:35 +00001071 for (auto &Diag : Diagnostics) {
Sam McCall16e70702018-10-24 07:59:38 +00001072 toLSPDiags(Diag, URI, DiagOpts,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001073 [&](clangd::Diagnostic Diag, llvm::ArrayRef<Fix> Fixes) {
Sam McCall16e70702018-10-24 07:59:38 +00001074 auto &FixItsForDiagnostic = LocalFixIts[Diag];
1075 llvm::copy(Fixes, std::back_inserter(FixItsForDiagnostic));
1076 LSPDiagnostics.push_back(std::move(Diag));
1077 });
Ilya Biryukov38d79772017-05-16 09:38:59 +00001078 }
1079
1080 // Cache FixIts
1081 {
Ilya Biryukov38d79772017-05-16 09:38:59 +00001082 std::lock_guard<std::mutex> Lock(FixItsMutex);
1083 FixItsMap[File] = LocalFixIts;
1084 }
1085
Ilya Biryukov49c10712019-03-25 10:15:11 +00001086 // Send a notification to the LSP client.
1087 publishDiagnostics(URI, std::move(LSPDiagnostics));
Ilya Biryukov38d79772017-05-16 09:38:59 +00001088}
Simon Marchi9569fd52018-03-16 14:30:42 +00001089
Haojian Wub6188492018-12-20 15:39:12 +00001090void ClangdLSPServer::onFileUpdated(PathRef File, const TUStatus &Status) {
1091 if (!SupportFileStatus)
1092 return;
1093 // FIXME: we don't emit "BuildingFile" and `RunningAction`, as these
1094 // two statuses are running faster in practice, which leads the UI constantly
1095 // changing, and doesn't provide much value. We may want to emit status at a
1096 // reasonable time interval (e.g. 0.5s).
1097 if (Status.Action.S == TUAction::BuildingFile ||
1098 Status.Action.S == TUAction::RunningAction)
1099 return;
1100 notify("textDocument/clangd.fileStatus", Status.render(File));
1101}
1102
Simon Marchi9569fd52018-03-16 14:30:42 +00001103void ClangdLSPServer::reparseOpenedFiles() {
1104 for (const Path &FilePath : DraftMgr.getActiveFiles())
Ilya Biryukov652364b2018-09-26 05:48:29 +00001105 Server->addDocument(FilePath, *DraftMgr.getDraft(FilePath),
1106 WantDiagnostics::Auto);
Simon Marchi9569fd52018-03-16 14:30:42 +00001107}
Alex Lorenzf8087862018-08-01 17:39:29 +00001108
Sam McCallc008af62018-10-20 15:30:37 +00001109} // namespace clangd
1110} // namespace clang