blob: e59da26a982f9e50f58248079cecdc2162e627c7 [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"
Johan Vikstroma848dab2019-07-04 07:53:12 +000014#include "SemanticHighlighting.h"
Sam McCallb536a2a2017-12-19 12:23:48 +000015#include "SourceCode.h"
Sam McCall2c30fbc2018-10-18 12:32:04 +000016#include "Trace.h"
Eric Liu78ed91a72018-01-29 15:37:46 +000017#include "URI.h"
Sam McCall395fde72019-06-18 13:37:54 +000018#include "refactor/Tweak.h"
Ilya Biryukovcce67a32019-01-29 14:17:36 +000019#include "clang/Tooling/Core/Replacement.h"
Kadir Cetinkaya256247c2019-06-26 07:45:27 +000020#include "llvm/ADT/ArrayRef.h"
Sam McCalla69698f2019-03-27 17:47:49 +000021#include "llvm/ADT/Optional.h"
Kadir Cetinkaya689bf932018-08-24 13:09:41 +000022#include "llvm/ADT/ScopeExit.h"
Simon Marchi9569fd52018-03-16 14:30:42 +000023#include "llvm/Support/Errc.h"
Ilya Biryukovcce67a32019-01-29 14:17:36 +000024#include "llvm/Support/Error.h"
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +000025#include "llvm/Support/FormatVariadic.h"
Eric Liu5740ff52018-01-31 16:26:27 +000026#include "llvm/Support/Path.h"
Sam McCall2c30fbc2018-10-18 12:32:04 +000027#include "llvm/Support/ScopedPrinter.h"
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +000028
Sam McCallc008af62018-10-20 15:30:37 +000029namespace clang {
30namespace clangd {
Ilya Biryukovafb55542017-05-16 14:40:30 +000031namespace {
Ilya Biryukovcce67a32019-01-29 14:17:36 +000032/// Transforms a tweak into a code action that would apply it if executed.
33/// EXPECTS: T.prepare() was called and returned true.
34CodeAction toCodeAction(const ClangdServer::TweakRef &T, const URIForFile &File,
35 Range Selection) {
36 CodeAction CA;
37 CA.title = T.Title;
Sam McCall395fde72019-06-18 13:37:54 +000038 switch (T.Intent) {
39 case Tweak::Refactor:
40 CA.kind = CodeAction::REFACTOR_KIND;
41 break;
42 case Tweak::Info:
43 CA.kind = CodeAction::INFO_KIND;
44 break;
45 }
Ilya Biryukovcce67a32019-01-29 14:17:36 +000046 // This tweak may have an expensive second stage, we only run it if the user
47 // actually chooses it in the UI. We reply with a command that would run the
48 // corresponding tweak.
49 // FIXME: for some tweaks, computing the edits is cheap and we could send them
50 // directly.
51 CA.command.emplace();
52 CA.command->title = T.Title;
53 CA.command->command = Command::CLANGD_APPLY_TWEAK;
54 CA.command->tweakArgs.emplace();
55 CA.command->tweakArgs->file = File;
56 CA.command->tweakArgs->tweakID = T.ID;
57 CA.command->tweakArgs->selection = Selection;
58 return CA;
Simon Pilgrime9a136b2019-02-03 14:08:30 +000059}
Ilya Biryukovcce67a32019-01-29 14:17:36 +000060
Ilya Biryukov19d75602018-11-23 15:21:19 +000061void adjustSymbolKinds(llvm::MutableArrayRef<DocumentSymbol> Syms,
62 SymbolKindBitset Kinds) {
63 for (auto &S : Syms) {
64 S.kind = adjustKindToCapability(S.kind, Kinds);
65 adjustSymbolKinds(S.children, Kinds);
66 }
67}
68
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +000069SymbolKindBitset defaultSymbolKinds() {
70 SymbolKindBitset Defaults;
71 for (size_t I = SymbolKindMin; I <= static_cast<size_t>(SymbolKind::Array);
72 ++I)
73 Defaults.set(I);
74 return Defaults;
75}
76
Kadir Cetinkaya133d46f2018-09-27 17:13:07 +000077CompletionItemKindBitset defaultCompletionItemKinds() {
78 CompletionItemKindBitset Defaults;
79 for (size_t I = CompletionItemKindMin;
80 I <= static_cast<size_t>(CompletionItemKind::Reference); ++I)
81 Defaults.set(I);
82 return Defaults;
83}
84
Haojian Wu1ca2ee42019-07-04 12:27:21 +000085// Build a lookup table (HighlightingKind => {TextMate Scopes}), which is sent
86// to the LSP client.
87std::vector<std::vector<std::string>> buildHighlightScopeLookupTable() {
88 std::vector<std::vector<std::string>> LookupTable;
89 // HighlightingKind is using as the index.
90 for (int KindValue = 0; KindValue < (int)HighlightingKind::NumKinds;
91 ++KindValue)
92 LookupTable.push_back({toTextMateScope((HighlightingKind)(KindValue))});
93 return LookupTable;
94}
95
Ilya Biryukovafb55542017-05-16 14:40:30 +000096} // namespace
97
Sam McCall2c30fbc2018-10-18 12:32:04 +000098// MessageHandler dispatches incoming LSP messages.
99// It handles cross-cutting concerns:
100// - serializes/deserializes protocol objects to JSON
101// - logging of inbound messages
102// - cancellation handling
103// - basic call tracing
Sam McCall3d0adbe2018-10-18 14:41:50 +0000104// MessageHandler ensures that initialize() is called before any other handler.
Sam McCall2c30fbc2018-10-18 12:32:04 +0000105class ClangdLSPServer::MessageHandler : public Transport::MessageHandler {
106public:
107 MessageHandler(ClangdLSPServer &Server) : Server(Server) {}
108
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000109 bool onNotify(llvm::StringRef Method, llvm::json::Value Params) override {
Sam McCalla69698f2019-03-27 17:47:49 +0000110 WithContext HandlerContext(handlerContext());
Sam McCall2c30fbc2018-10-18 12:32:04 +0000111 log("<-- {0}", Method);
112 if (Method == "exit")
113 return false;
Sam McCall3d0adbe2018-10-18 14:41:50 +0000114 if (!Server.Server)
115 elog("Notification {0} before initialization", Method);
116 else if (Method == "$/cancelRequest")
Sam McCall2c30fbc2018-10-18 12:32:04 +0000117 onCancel(std::move(Params));
118 else if (auto Handler = Notifications.lookup(Method))
119 Handler(std::move(Params));
120 else
121 log("unhandled notification {0}", Method);
122 return true;
123 }
124
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000125 bool onCall(llvm::StringRef Method, llvm::json::Value Params,
126 llvm::json::Value ID) override {
Sam McCalla69698f2019-03-27 17:47:49 +0000127 WithContext HandlerContext(handlerContext());
Sam McCalle2f3a732018-10-24 14:26:26 +0000128 // Calls can be canceled by the client. Add cancellation context.
129 WithContext WithCancel(cancelableRequestContext(ID));
130 trace::Span Tracer(Method);
131 SPAN_ATTACH(Tracer, "Params", Params);
132 ReplyOnce Reply(ID, Method, &Server, Tracer.Args);
Sam McCall2c30fbc2018-10-18 12:32:04 +0000133 log("<-- {0}({1})", Method, ID);
Sam McCall3d0adbe2018-10-18 14:41:50 +0000134 if (!Server.Server && Method != "initialize") {
135 elog("Call {0} before initialization.", Method);
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000136 Reply(llvm::make_error<LSPError>("server not initialized",
137 ErrorCode::ServerNotInitialized));
Sam McCall3d0adbe2018-10-18 14:41:50 +0000138 } else if (auto Handler = Calls.lookup(Method))
Sam McCalle2f3a732018-10-24 14:26:26 +0000139 Handler(std::move(Params), std::move(Reply));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000140 else
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000141 Reply(llvm::make_error<LSPError>("method not found",
142 ErrorCode::MethodNotFound));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000143 return true;
144 }
145
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000146 bool onReply(llvm::json::Value ID,
147 llvm::Expected<llvm::json::Value> Result) override {
Sam McCalla69698f2019-03-27 17:47:49 +0000148 WithContext HandlerContext(handlerContext());
Sam McCall2c30fbc2018-10-18 12:32:04 +0000149 // We ignore replies, just log them.
150 if (Result)
151 log("<-- reply({0})", ID);
152 else
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000153 log("<-- reply({0}) error: {1}", ID, llvm::toString(Result.takeError()));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000154 return true;
155 }
156
157 // Bind an LSP method name to a call.
Sam McCalle2f3a732018-10-24 14:26:26 +0000158 template <typename Param, typename Result>
Sam McCall2c30fbc2018-10-18 12:32:04 +0000159 void bind(const char *Method,
Sam McCalle2f3a732018-10-24 14:26:26 +0000160 void (ClangdLSPServer::*Handler)(const Param &, Callback<Result>)) {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000161 Calls[Method] = [Method, Handler, this](llvm::json::Value RawParams,
Sam McCalle2f3a732018-10-24 14:26:26 +0000162 ReplyOnce Reply) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000163 Param P;
Sam McCalle2f3a732018-10-24 14:26:26 +0000164 if (fromJSON(RawParams, P)) {
165 (Server.*Handler)(P, std::move(Reply));
166 } else {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000167 elog("Failed to decode {0} request.", Method);
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000168 Reply(llvm::make_error<LSPError>("failed to decode request",
169 ErrorCode::InvalidRequest));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000170 }
Sam McCall2c30fbc2018-10-18 12:32:04 +0000171 };
172 }
173
174 // Bind an LSP method name to a notification.
175 template <typename Param>
176 void bind(const char *Method,
177 void (ClangdLSPServer::*Handler)(const Param &)) {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000178 Notifications[Method] = [Method, Handler,
179 this](llvm::json::Value RawParams) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000180 Param P;
181 if (!fromJSON(RawParams, P)) {
182 elog("Failed to decode {0} request.", Method);
183 return;
184 }
185 trace::Span Tracer(Method);
186 SPAN_ATTACH(Tracer, "Params", RawParams);
187 (Server.*Handler)(P);
188 };
189 }
190
191private:
Sam McCalle2f3a732018-10-24 14:26:26 +0000192 // Function object to reply to an LSP call.
193 // Each instance must be called exactly once, otherwise:
194 // - the bug is logged, and (in debug mode) an assert will fire
195 // - if there was no reply, an error reply is sent
196 // - if there were multiple replies, only the first is sent
197 class ReplyOnce {
198 std::atomic<bool> Replied = {false};
Sam McCalld7babe42018-10-24 15:18:40 +0000199 std::chrono::steady_clock::time_point Start;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000200 llvm::json::Value ID;
Sam McCalle2f3a732018-10-24 14:26:26 +0000201 std::string Method;
202 ClangdLSPServer *Server; // Null when moved-from.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000203 llvm::json::Object *TraceArgs;
Sam McCalle2f3a732018-10-24 14:26:26 +0000204
205 public:
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000206 ReplyOnce(const llvm::json::Value &ID, llvm::StringRef Method,
207 ClangdLSPServer *Server, llvm::json::Object *TraceArgs)
Sam McCalld7babe42018-10-24 15:18:40 +0000208 : Start(std::chrono::steady_clock::now()), ID(ID), Method(Method),
209 Server(Server), TraceArgs(TraceArgs) {
Sam McCalle2f3a732018-10-24 14:26:26 +0000210 assert(Server);
211 }
212 ReplyOnce(ReplyOnce &&Other)
Sam McCalld7babe42018-10-24 15:18:40 +0000213 : Replied(Other.Replied.load()), Start(Other.Start),
214 ID(std::move(Other.ID)), Method(std::move(Other.Method)),
215 Server(Other.Server), TraceArgs(Other.TraceArgs) {
Sam McCalle2f3a732018-10-24 14:26:26 +0000216 Other.Server = nullptr;
217 }
Ilya Biryukov22fa4652019-01-03 13:28:05 +0000218 ReplyOnce &operator=(ReplyOnce &&) = delete;
Sam McCalle2f3a732018-10-24 14:26:26 +0000219 ReplyOnce(const ReplyOnce &) = delete;
Ilya Biryukov22fa4652019-01-03 13:28:05 +0000220 ReplyOnce &operator=(const ReplyOnce &) = delete;
Sam McCalle2f3a732018-10-24 14:26:26 +0000221
222 ~ReplyOnce() {
223 if (Server && !Replied) {
224 elog("No reply to message {0}({1})", Method, ID);
225 assert(false && "must reply to all calls!");
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000226 (*this)(llvm::make_error<LSPError>("server failed to reply",
227 ErrorCode::InternalError));
Sam McCalle2f3a732018-10-24 14:26:26 +0000228 }
229 }
230
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000231 void operator()(llvm::Expected<llvm::json::Value> Reply) {
Sam McCalle2f3a732018-10-24 14:26:26 +0000232 assert(Server && "moved-from!");
233 if (Replied.exchange(true)) {
234 elog("Replied twice to message {0}({1})", Method, ID);
235 assert(false && "must reply to each call only once!");
236 return;
237 }
Sam McCalld7babe42018-10-24 15:18:40 +0000238 auto Duration = std::chrono::steady_clock::now() - Start;
239 if (Reply) {
240 log("--> reply:{0}({1}) {2:ms}", Method, ID, Duration);
241 if (TraceArgs)
Sam McCalle2f3a732018-10-24 14:26:26 +0000242 (*TraceArgs)["Reply"] = *Reply;
Sam McCalld7babe42018-10-24 15:18:40 +0000243 std::lock_guard<std::mutex> Lock(Server->TranspWriter);
244 Server->Transp.reply(std::move(ID), std::move(Reply));
245 } else {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000246 llvm::Error Err = Reply.takeError();
Sam McCalld7babe42018-10-24 15:18:40 +0000247 log("--> reply:{0}({1}) {2:ms}, error: {3}", Method, ID, Duration, Err);
248 if (TraceArgs)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000249 (*TraceArgs)["Error"] = llvm::to_string(Err);
Sam McCalld7babe42018-10-24 15:18:40 +0000250 std::lock_guard<std::mutex> Lock(Server->TranspWriter);
251 Server->Transp.reply(std::move(ID), std::move(Err));
Sam McCalle2f3a732018-10-24 14:26:26 +0000252 }
Sam McCalle2f3a732018-10-24 14:26:26 +0000253 }
254 };
255
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000256 llvm::StringMap<std::function<void(llvm::json::Value)>> Notifications;
257 llvm::StringMap<std::function<void(llvm::json::Value, ReplyOnce)>> Calls;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000258
259 // Method calls may be cancelled by ID, so keep track of their state.
260 // This needs a mutex: handlers may finish on a different thread, and that's
261 // when we clean up entries in the map.
262 mutable std::mutex RequestCancelersMutex;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000263 llvm::StringMap<std::pair<Canceler, /*Cookie*/ unsigned>> RequestCancelers;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000264 unsigned NextRequestCookie = 0; // To disambiguate reused IDs, see below.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000265 void onCancel(const llvm::json::Value &Params) {
266 const llvm::json::Value *ID = nullptr;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000267 if (auto *O = Params.getAsObject())
268 ID = O->get("id");
269 if (!ID) {
270 elog("Bad cancellation request: {0}", Params);
271 return;
272 }
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000273 auto StrID = llvm::to_string(*ID);
Sam McCall2c30fbc2018-10-18 12:32:04 +0000274 std::lock_guard<std::mutex> Lock(RequestCancelersMutex);
275 auto It = RequestCancelers.find(StrID);
276 if (It != RequestCancelers.end())
277 It->second.first(); // Invoke the canceler.
278 }
Sam McCalla69698f2019-03-27 17:47:49 +0000279
280 Context handlerContext() const {
281 return Context::current().derive(
282 kCurrentOffsetEncoding,
283 Server.NegotiatedOffsetEncoding.getValueOr(OffsetEncoding::UTF16));
284 }
285
Sam McCall2c30fbc2018-10-18 12:32:04 +0000286 // We run cancelable requests in a context that does two things:
287 // - allows cancellation using RequestCancelers[ID]
288 // - cleans up the entry in RequestCancelers when it's no longer needed
289 // If a client reuses an ID, the last wins and the first cannot be canceled.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000290 Context cancelableRequestContext(const llvm::json::Value &ID) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000291 auto Task = cancelableTask();
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000292 auto StrID = llvm::to_string(ID); // JSON-serialize ID for map key.
Sam McCall2c30fbc2018-10-18 12:32:04 +0000293 auto Cookie = NextRequestCookie++; // No lock, only called on main thread.
294 {
295 std::lock_guard<std::mutex> Lock(RequestCancelersMutex);
296 RequestCancelers[StrID] = {std::move(Task.second), Cookie};
297 }
298 // When the request ends, we can clean up the entry we just added.
299 // The cookie lets us check that it hasn't been overwritten due to ID
300 // reuse.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000301 return Task.first.derive(llvm::make_scope_exit([this, StrID, Cookie] {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000302 std::lock_guard<std::mutex> Lock(RequestCancelersMutex);
303 auto It = RequestCancelers.find(StrID);
304 if (It != RequestCancelers.end() && It->second.second == Cookie)
305 RequestCancelers.erase(It);
306 }));
307 }
308
309 ClangdLSPServer &Server;
310};
311
312// call(), notify(), and reply() wrap the Transport, adding logging and locking.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000313void ClangdLSPServer::call(llvm::StringRef Method, llvm::json::Value Params) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000314 auto ID = NextCallID++;
315 log("--> {0}({1})", Method, ID);
316 // We currently don't handle responses, so no need to store ID anywhere.
317 std::lock_guard<std::mutex> Lock(TranspWriter);
318 Transp.call(Method, std::move(Params), ID);
319}
320
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000321void ClangdLSPServer::notify(llvm::StringRef Method, llvm::json::Value Params) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000322 log("--> {0}", Method);
323 std::lock_guard<std::mutex> Lock(TranspWriter);
324 Transp.notify(Method, std::move(Params));
325}
326
Sam McCall2c30fbc2018-10-18 12:32:04 +0000327void ClangdLSPServer::onInitialize(const InitializeParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000328 Callback<llvm::json::Value> Reply) {
Sam McCalla69698f2019-03-27 17:47:49 +0000329 // Determine character encoding first as it affects constructed ClangdServer.
330 if (Params.capabilities.offsetEncoding && !NegotiatedOffsetEncoding) {
331 NegotiatedOffsetEncoding = OffsetEncoding::UTF16; // fallback
332 for (OffsetEncoding Supported : *Params.capabilities.offsetEncoding)
333 if (Supported != OffsetEncoding::UnsupportedEncoding) {
334 NegotiatedOffsetEncoding = Supported;
335 break;
336 }
337 }
338 llvm::Optional<WithContextValue> WithOffsetEncoding;
339 if (NegotiatedOffsetEncoding)
340 WithOffsetEncoding.emplace(kCurrentOffsetEncoding,
341 *NegotiatedOffsetEncoding);
342
Johan Vikstroma848dab2019-07-04 07:53:12 +0000343 ClangdServerOpts.SemanticHighlighting =
344 Params.capabilities.SemanticHighlighting;
Sam McCall0d9b40f2018-10-19 15:42:23 +0000345 if (Params.rootUri && *Params.rootUri)
346 ClangdServerOpts.WorkspaceRoot = Params.rootUri->file();
347 else if (Params.rootPath && !Params.rootPath->empty())
348 ClangdServerOpts.WorkspaceRoot = *Params.rootPath;
Sam McCall3d0adbe2018-10-18 14:41:50 +0000349 if (Server)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000350 return Reply(llvm::make_error<LSPError>("server already initialized",
351 ErrorCode::InvalidRequest));
Sam McCallbc904612018-10-25 04:22:52 +0000352 if (const auto &Dir = Params.initializationOptions.compilationDatabasePath)
353 CompileCommandsDir = Dir;
Kadir Cetinkaya256247c2019-06-26 07:45:27 +0000354 if (UseDirBasedCDB) {
Sam McCallc55d09a2018-11-02 13:09:36 +0000355 BaseCDB = llvm::make_unique<DirectoryBasedGlobalCompilationDatabase>(
356 CompileCommandsDir);
Kadir Cetinkaya256247c2019-06-26 07:45:27 +0000357 BaseCDB = getQueryDriverDatabase(
358 llvm::makeArrayRef(ClangdServerOpts.QueryDriverGlobs),
359 std::move(BaseCDB));
360 }
Kadir Cetinkayabe6b35d2019-01-22 09:10:20 +0000361 CDB.emplace(BaseCDB.get(), Params.initializationOptions.fallbackFlags,
362 ClangdServerOpts.ResourceDir);
Sam McCallc55d09a2018-11-02 13:09:36 +0000363 Server.emplace(*CDB, FSProvider, static_cast<DiagnosticsConsumer &>(*this),
364 ClangdServerOpts);
Sam McCallbc904612018-10-25 04:22:52 +0000365 applyConfiguration(Params.initializationOptions.ConfigSettings);
Simon Marchi88016782018-08-01 11:28:49 +0000366
Sam McCallbf6a2fc2018-10-17 07:33:42 +0000367 CCOpts.EnableSnippets = Params.capabilities.CompletionSnippets;
Sam McCall8d412942019-06-18 11:57:26 +0000368 CCOpts.IncludeFixIts = Params.capabilities.CompletionFixes;
Sam McCall5f092e32019-07-08 17:27:15 +0000369 if (!CCOpts.BundleOverloads.hasValue())
370 CCOpts.BundleOverloads = Params.capabilities.HasSignatureHelp;
Sam McCallbf6a2fc2018-10-17 07:33:42 +0000371 DiagOpts.EmbedFixesInDiagnostics = Params.capabilities.DiagnosticFixes;
372 DiagOpts.SendDiagnosticCategory = Params.capabilities.DiagnosticCategory;
Sam McCallc9e4ee92019-04-18 15:17:07 +0000373 DiagOpts.EmitRelatedLocations =
374 Params.capabilities.DiagnosticRelatedInformation;
Sam McCallbf6a2fc2018-10-17 07:33:42 +0000375 if (Params.capabilities.WorkspaceSymbolKinds)
376 SupportedSymbolKinds |= *Params.capabilities.WorkspaceSymbolKinds;
377 if (Params.capabilities.CompletionItemKinds)
378 SupportedCompletionItemKinds |= *Params.capabilities.CompletionItemKinds;
379 SupportsCodeAction = Params.capabilities.CodeActionStructure;
Ilya Biryukov19d75602018-11-23 15:21:19 +0000380 SupportsHierarchicalDocumentSymbol =
381 Params.capabilities.HierarchicalDocumentSymbol;
Haojian Wub6188492018-12-20 15:39:12 +0000382 SupportFileStatus = Params.initializationOptions.FileStatus;
Ilya Biryukovf9169d02019-05-29 10:01:00 +0000383 HoverContentFormat = Params.capabilities.HoverContentFormat;
Ilya Biryukov4ef0f822019-06-04 09:36:59 +0000384 SupportsOffsetsInSignatureHelp = Params.capabilities.OffsetsInSignatureHelp;
Sam McCalla69698f2019-03-27 17:47:49 +0000385 llvm::json::Object Result{
Sam McCall0930ab02017-11-07 15:49:35 +0000386 {{"capabilities",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000387 llvm::json::Object{
Simon Marchi98082622018-03-26 14:41:40 +0000388 {"textDocumentSync", (int)TextDocumentSyncKind::Incremental},
Sam McCall0930ab02017-11-07 15:49:35 +0000389 {"documentFormattingProvider", true},
390 {"documentRangeFormattingProvider", true},
391 {"documentOnTypeFormattingProvider",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000392 llvm::json::Object{
Sam McCall25c62572019-06-10 14:26:21 +0000393 {"firstTriggerCharacter", "\n"},
Sam McCall0930ab02017-11-07 15:49:35 +0000394 {"moreTriggerCharacter", {}},
395 }},
396 {"codeActionProvider", true},
397 {"completionProvider",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000398 llvm::json::Object{
Sam McCall0930ab02017-11-07 15:49:35 +0000399 {"resolveProvider", false},
Ilya Biryukovb0826bd2019-01-03 13:37:12 +0000400 // We do extra checks for '>' and ':' in completion to only
401 // trigger on '->' and '::'.
Sam McCall0930ab02017-11-07 15:49:35 +0000402 {"triggerCharacters", {".", ">", ":"}},
403 }},
404 {"signatureHelpProvider",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000405 llvm::json::Object{
Sam McCall0930ab02017-11-07 15:49:35 +0000406 {"triggerCharacters", {"(", ","}},
407 }},
Sam McCall866ba2c2019-02-01 11:26:13 +0000408 {"declarationProvider", true},
Sam McCall0930ab02017-11-07 15:49:35 +0000409 {"definitionProvider", true},
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000410 {"documentHighlightProvider", true},
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000411 {"hoverProvider", true},
Haojian Wu345099c2017-11-09 11:30:04 +0000412 {"renameProvider", true},
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000413 {"documentSymbolProvider", true},
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000414 {"workspaceSymbolProvider", true},
Sam McCall1ad142f2018-09-05 11:53:07 +0000415 {"referencesProvider", true},
Sam McCall0930ab02017-11-07 15:49:35 +0000416 {"executeCommandProvider",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000417 llvm::json::Object{
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000418 {"commands",
419 {ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND,
420 ExecuteCommandParams::CLANGD_APPLY_TWEAK}},
Sam McCall0930ab02017-11-07 15:49:35 +0000421 }},
Kadir Cetinkaya86658022019-03-19 09:27:04 +0000422 {"typeHierarchyProvider", true},
Sam McCalla69698f2019-03-27 17:47:49 +0000423 }}}};
424 if (NegotiatedOffsetEncoding)
425 Result["offsetEncoding"] = *NegotiatedOffsetEncoding;
Johan Vikstroma848dab2019-07-04 07:53:12 +0000426 if (Params.capabilities.SemanticHighlighting)
427 Result.getObject("capabilities")
428 ->insert(
429 {"semanticHighlighting",
Haojian Wu1ca2ee42019-07-04 12:27:21 +0000430 llvm::json::Object{{"scopes", buildHighlightScopeLookupTable()}}});
Sam McCalla69698f2019-03-27 17:47:49 +0000431 Reply(std::move(Result));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000432}
433
Sam McCall2c30fbc2018-10-18 12:32:04 +0000434void ClangdLSPServer::onShutdown(const ShutdownParams &Params,
435 Callback<std::nullptr_t> Reply) {
Ilya Biryukov0d9b8a32017-10-25 08:45:41 +0000436 // Do essentially nothing, just say we're ready to exit.
437 ShutdownRequestReceived = true;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000438 Reply(nullptr);
Sam McCall8a5dded2017-10-12 13:29:58 +0000439}
Ilya Biryukovafb55542017-05-16 14:40:30 +0000440
Sam McCall422c8282018-11-26 16:00:11 +0000441// sync is a clangd extension: it blocks until all background work completes.
442// It blocks the calling thread, so no messages are processed until it returns!
443void ClangdLSPServer::onSync(const NoParams &Params,
444 Callback<std::nullptr_t> Reply) {
445 if (Server->blockUntilIdleForTest(/*TimeoutSeconds=*/60))
446 Reply(nullptr);
447 else
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000448 Reply(llvm::createStringError(llvm::inconvertibleErrorCode(),
449 "Not idle after a minute"));
Sam McCall422c8282018-11-26 16:00:11 +0000450}
451
Sam McCall2c30fbc2018-10-18 12:32:04 +0000452void ClangdLSPServer::onDocumentDidOpen(
453 const DidOpenTextDocumentParams &Params) {
Simon Marchi9569fd52018-03-16 14:30:42 +0000454 PathRef File = Params.textDocument.uri.file();
Ilya Biryukovb10ef472018-06-13 09:20:41 +0000455
Sam McCall2c30fbc2018-10-18 12:32:04 +0000456 const std::string &Contents = Params.textDocument.text;
Simon Marchi9569fd52018-03-16 14:30:42 +0000457
Simon Marchi98082622018-03-26 14:41:40 +0000458 DraftMgr.addDraft(File, Contents);
Ilya Biryukov652364b2018-09-26 05:48:29 +0000459 Server->addDocument(File, Contents, WantDiagnostics::Yes);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000460}
461
Sam McCall2c30fbc2018-10-18 12:32:04 +0000462void ClangdLSPServer::onDocumentDidChange(
463 const DidChangeTextDocumentParams &Params) {
Eric Liu51fed182018-02-22 18:40:39 +0000464 auto WantDiags = WantDiagnostics::Auto;
465 if (Params.wantDiagnostics.hasValue())
466 WantDiags = Params.wantDiagnostics.getValue() ? WantDiagnostics::Yes
467 : WantDiagnostics::No;
Simon Marchi9569fd52018-03-16 14:30:42 +0000468
469 PathRef File = Params.textDocument.uri.file();
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000470 llvm::Expected<std::string> Contents =
Simon Marchi98082622018-03-26 14:41:40 +0000471 DraftMgr.updateDraft(File, Params.contentChanges);
472 if (!Contents) {
473 // If this fails, we are most likely going to be not in sync anymore with
474 // the client. It is better to remove the draft and let further operations
475 // fail rather than giving wrong results.
476 DraftMgr.removeDraft(File);
Ilya Biryukov652364b2018-09-26 05:48:29 +0000477 Server->removeDocument(File);
Sam McCallbed58852018-07-11 10:35:11 +0000478 elog("Failed to update {0}: {1}", File, Contents.takeError());
Simon Marchi98082622018-03-26 14:41:40 +0000479 return;
480 }
Simon Marchi9569fd52018-03-16 14:30:42 +0000481
Ilya Biryukov652364b2018-09-26 05:48:29 +0000482 Server->addDocument(File, *Contents, WantDiags);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000483}
484
Sam McCall2c30fbc2018-10-18 12:32:04 +0000485void ClangdLSPServer::onFileEvent(const DidChangeWatchedFilesParams &Params) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000486 Server->onFileEvent(Params);
Marc-Andre Laperlebf114242017-10-02 18:00:37 +0000487}
488
Sam McCall2c30fbc2018-10-18 12:32:04 +0000489void ClangdLSPServer::onCommand(const ExecuteCommandParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000490 Callback<llvm::json::Value> Reply) {
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000491 auto ApplyEdit = [this](WorkspaceEdit WE) {
Eric Liuc5105f92018-02-16 14:15:55 +0000492 ApplyWorkspaceEditParams Edit;
493 Edit.edit = std::move(WE);
Eric Liuc5105f92018-02-16 14:15:55 +0000494 // Ideally, we would wait for the response and if there is no error, we
495 // would reply success/failure to the original RPC.
496 call("workspace/applyEdit", Edit);
497 };
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000498 if (Params.command == ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND &&
499 Params.workspaceEdit) {
500 // The flow for "apply-fix" :
501 // 1. We publish a diagnostic, including fixits
502 // 2. The user clicks on the diagnostic, the editor asks us for code actions
503 // 3. We send code actions, with the fixit embedded as context
504 // 4. The user selects the fixit, the editor asks us to apply it
505 // 5. We unwrap the changes and send them back to the editor
506 // 6. The editor applies the changes (applyEdit), and sends us a reply (but
507 // we ignore it)
508
Sam McCall2c30fbc2018-10-18 12:32:04 +0000509 Reply("Fix applied.");
Eric Liuc5105f92018-02-16 14:15:55 +0000510 ApplyEdit(*Params.workspaceEdit);
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000511 } else if (Params.command == ExecuteCommandParams::CLANGD_APPLY_TWEAK &&
512 Params.tweakArgs) {
513 auto Code = DraftMgr.getDraft(Params.tweakArgs->file.file());
514 if (!Code)
515 return Reply(llvm::createStringError(
516 llvm::inconvertibleErrorCode(),
517 "trying to apply a code action for a non-added file"));
518
Sam McCall395fde72019-06-18 13:37:54 +0000519 auto Action = [this, ApplyEdit](decltype(Reply) Reply, URIForFile File,
520 std::string Code,
Sam McCall08372eb2019-06-19 07:29:10 +0000521 llvm::Expected<Tweak::Effect> R) {
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000522 if (!R)
523 return Reply(R.takeError());
524
Sam McCall395fde72019-06-18 13:37:54 +0000525 if (R->ApplyEdit) {
526 WorkspaceEdit WE;
527 WE.changes.emplace();
Sam McCall08372eb2019-06-19 07:29:10 +0000528 (*WE.changes)[File.uri()] = replacementsToEdits(Code, *R->ApplyEdit);
Sam McCall395fde72019-06-18 13:37:54 +0000529 ApplyEdit(std::move(WE));
530 }
531 if (R->ShowMessage) {
532 ShowMessageParams Msg;
533 Msg.message = *R->ShowMessage;
534 Msg.type = MessageType::Info;
535 notify("window/showMessage", Msg);
536 }
537 Reply("Tweak applied.");
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000538 };
539 Server->applyTweak(Params.tweakArgs->file.file(),
540 Params.tweakArgs->selection, Params.tweakArgs->tweakID,
541 Bind(Action, std::move(Reply), Params.tweakArgs->file,
542 std::move(*Code)));
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000543 } else {
544 // We should not get here because ExecuteCommandParams would not have
545 // parsed in the first place and this handler should not be called. But if
546 // more commands are added, this will be here has a safe guard.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000547 Reply(llvm::make_error<LSPError>(
548 llvm::formatv("Unsupported command \"{0}\".", Params.command).str(),
Sam McCall2c30fbc2018-10-18 12:32:04 +0000549 ErrorCode::InvalidParams));
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000550 }
551}
552
Sam McCall2c30fbc2018-10-18 12:32:04 +0000553void ClangdLSPServer::onWorkspaceSymbol(
554 const WorkspaceSymbolParams &Params,
555 Callback<std::vector<SymbolInformation>> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000556 Server->workspaceSymbols(
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000557 Params.query, CCOpts.Limit,
Sam McCall2c30fbc2018-10-18 12:32:04 +0000558 Bind(
559 [this](decltype(Reply) Reply,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000560 llvm::Expected<std::vector<SymbolInformation>> Items) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000561 if (!Items)
562 return Reply(Items.takeError());
563 for (auto &Sym : *Items)
564 Sym.kind = adjustKindToCapability(Sym.kind, SupportedSymbolKinds);
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000565
Sam McCall2c30fbc2018-10-18 12:32:04 +0000566 Reply(std::move(*Items));
567 },
568 std::move(Reply)));
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000569}
570
Sam McCall2c30fbc2018-10-18 12:32:04 +0000571void ClangdLSPServer::onRename(const RenameParams &Params,
572 Callback<WorkspaceEdit> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000573 Path File = Params.textDocument.uri.file();
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000574 llvm::Optional<std::string> Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000575 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000576 return Reply(llvm::make_error<LSPError>(
577 "onRename called for non-added file", ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000578
Ilya Biryukov652364b2018-09-26 05:48:29 +0000579 Server->rename(
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000580 File, Params.position, Params.newName,
Sam McCall2c30fbc2018-10-18 12:32:04 +0000581 Bind(
Ilya Biryukovd9c24dc2019-04-03 07:18:43 +0000582 [File, Code, Params](decltype(Reply) Reply,
583 llvm::Expected<std::vector<TextEdit>> Edits) {
584 if (!Edits)
585 return Reply(Edits.takeError());
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000586
Sam McCall2c30fbc2018-10-18 12:32:04 +0000587 WorkspaceEdit WE;
Ilya Biryukovd9c24dc2019-04-03 07:18:43 +0000588 WE.changes = {{Params.textDocument.uri.uri(), *Edits}};
Sam McCall2c30fbc2018-10-18 12:32:04 +0000589 Reply(WE);
590 },
591 std::move(Reply)));
Haojian Wu345099c2017-11-09 11:30:04 +0000592}
593
Sam McCall2c30fbc2018-10-18 12:32:04 +0000594void ClangdLSPServer::onDocumentDidClose(
595 const DidCloseTextDocumentParams &Params) {
Simon Marchi9569fd52018-03-16 14:30:42 +0000596 PathRef File = Params.textDocument.uri.file();
597 DraftMgr.removeDraft(File);
Ilya Biryukov652364b2018-09-26 05:48:29 +0000598 Server->removeDocument(File);
Ilya Biryukov49c10712019-03-25 10:15:11 +0000599
600 {
601 std::lock_guard<std::mutex> Lock(FixItsMutex);
602 FixItsMap.erase(File);
603 }
604 // clangd will not send updates for this file anymore, so we empty out the
605 // list of diagnostics shown on the client (e.g. in the "Problems" pane of
606 // VSCode). Note that this cannot race with actual diagnostics responses
607 // because removeDocument() guarantees no diagnostic callbacks will be
608 // executed after it returns.
609 publishDiagnostics(URIForFile::canonicalize(File, /*TUPath=*/File), {});
Ilya Biryukovafb55542017-05-16 14:40:30 +0000610}
611
Sam McCall4db732a2017-09-30 10:08:52 +0000612void ClangdLSPServer::onDocumentOnTypeFormatting(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000613 const DocumentOnTypeFormattingParams &Params,
614 Callback<std::vector<TextEdit>> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000615 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000616 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000617 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000618 return Reply(llvm::make_error<LSPError>(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000619 "onDocumentOnTypeFormatting called for non-added file",
620 ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000621
Sam McCall25c62572019-06-10 14:26:21 +0000622 Reply(Server->formatOnType(*Code, File, Params.position, Params.ch));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000623}
624
Sam McCall4db732a2017-09-30 10:08:52 +0000625void ClangdLSPServer::onDocumentRangeFormatting(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000626 const DocumentRangeFormattingParams &Params,
627 Callback<std::vector<TextEdit>> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000628 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000629 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000630 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000631 return Reply(llvm::make_error<LSPError>(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000632 "onDocumentRangeFormatting called for non-added file",
633 ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000634
Ilya Biryukov652364b2018-09-26 05:48:29 +0000635 auto ReplacementsOrError = Server->formatRange(*Code, File, Params.range);
Raoul Wols212bcf82017-12-12 20:25:06 +0000636 if (ReplacementsOrError)
Sam McCall2c30fbc2018-10-18 12:32:04 +0000637 Reply(replacementsToEdits(*Code, ReplacementsOrError.get()));
Raoul Wols212bcf82017-12-12 20:25:06 +0000638 else
Sam McCall2c30fbc2018-10-18 12:32:04 +0000639 Reply(ReplacementsOrError.takeError());
Ilya Biryukovafb55542017-05-16 14:40:30 +0000640}
641
Sam McCall2c30fbc2018-10-18 12:32:04 +0000642void ClangdLSPServer::onDocumentFormatting(
643 const DocumentFormattingParams &Params,
644 Callback<std::vector<TextEdit>> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000645 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000646 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000647 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000648 return Reply(llvm::make_error<LSPError>(
649 "onDocumentFormatting called for non-added file",
650 ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000651
Ilya Biryukov652364b2018-09-26 05:48:29 +0000652 auto ReplacementsOrError = Server->formatFile(*Code, File);
Raoul Wols212bcf82017-12-12 20:25:06 +0000653 if (ReplacementsOrError)
Sam McCall2c30fbc2018-10-18 12:32:04 +0000654 Reply(replacementsToEdits(*Code, ReplacementsOrError.get()));
Raoul Wols212bcf82017-12-12 20:25:06 +0000655 else
Sam McCall2c30fbc2018-10-18 12:32:04 +0000656 Reply(ReplacementsOrError.takeError());
Sam McCall4db732a2017-09-30 10:08:52 +0000657}
658
Ilya Biryukov19d75602018-11-23 15:21:19 +0000659/// The functions constructs a flattened view of the DocumentSymbol hierarchy.
660/// Used by the clients that do not support the hierarchical view.
661static std::vector<SymbolInformation>
662flattenSymbolHierarchy(llvm::ArrayRef<DocumentSymbol> Symbols,
663 const URIForFile &FileURI) {
664
665 std::vector<SymbolInformation> Results;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000666 std::function<void(const DocumentSymbol &, llvm::StringRef)> Process =
667 [&](const DocumentSymbol &S, llvm::Optional<llvm::StringRef> ParentName) {
Ilya Biryukov19d75602018-11-23 15:21:19 +0000668 SymbolInformation SI;
669 SI.containerName = ParentName ? "" : *ParentName;
670 SI.name = S.name;
671 SI.kind = S.kind;
672 SI.location.range = S.range;
673 SI.location.uri = FileURI;
674
675 Results.push_back(std::move(SI));
676 std::string FullName =
677 !ParentName ? S.name : (ParentName->str() + "::" + S.name);
678 for (auto &C : S.children)
679 Process(C, /*ParentName=*/FullName);
680 };
681 for (auto &S : Symbols)
682 Process(S, /*ParentName=*/"");
683 return Results;
684}
685
686void ClangdLSPServer::onDocumentSymbol(const DocumentSymbolParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000687 Callback<llvm::json::Value> Reply) {
Ilya Biryukov19d75602018-11-23 15:21:19 +0000688 URIForFile FileURI = Params.textDocument.uri;
Ilya Biryukov652364b2018-09-26 05:48:29 +0000689 Server->documentSymbols(
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000690 Params.textDocument.uri.file(),
Sam McCall2c30fbc2018-10-18 12:32:04 +0000691 Bind(
Ilya Biryukov19d75602018-11-23 15:21:19 +0000692 [this, FileURI](decltype(Reply) Reply,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000693 llvm::Expected<std::vector<DocumentSymbol>> Items) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000694 if (!Items)
695 return Reply(Items.takeError());
Ilya Biryukov19d75602018-11-23 15:21:19 +0000696 adjustSymbolKinds(*Items, SupportedSymbolKinds);
697 if (SupportsHierarchicalDocumentSymbol)
698 return Reply(std::move(*Items));
699 else
700 return Reply(flattenSymbolHierarchy(*Items, FileURI));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000701 },
702 std::move(Reply)));
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000703}
704
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000705static llvm::Optional<Command> asCommand(const CodeAction &Action) {
Sam McCall20841d42018-10-16 16:29:41 +0000706 Command Cmd;
707 if (Action.command && Action.edit)
Sam McCallc008af62018-10-20 15:30:37 +0000708 return None; // Not representable. (We never emit these anyway).
Sam McCall20841d42018-10-16 16:29:41 +0000709 if (Action.command) {
710 Cmd = *Action.command;
711 } else if (Action.edit) {
712 Cmd.command = Command::CLANGD_APPLY_FIX_COMMAND;
713 Cmd.workspaceEdit = *Action.edit;
714 } else {
Sam McCallc008af62018-10-20 15:30:37 +0000715 return None;
Sam McCall20841d42018-10-16 16:29:41 +0000716 }
717 Cmd.title = Action.title;
718 if (Action.kind && *Action.kind == CodeAction::QUICKFIX_KIND)
719 Cmd.title = "Apply fix: " + Cmd.title;
720 return Cmd;
721}
722
Sam McCall2c30fbc2018-10-18 12:32:04 +0000723void ClangdLSPServer::onCodeAction(const CodeActionParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000724 Callback<llvm::json::Value> Reply) {
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000725 URIForFile File = Params.textDocument.uri;
726 auto Code = DraftMgr.getDraft(File.file());
Sam McCall2c30fbc2018-10-18 12:32:04 +0000727 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000728 return Reply(llvm::make_error<LSPError>(
729 "onCodeAction called for non-added file", ErrorCode::InvalidParams));
Sam McCall20841d42018-10-16 16:29:41 +0000730 // We provide a code action for Fixes on the specified diagnostics.
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000731 std::vector<CodeAction> FixIts;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000732 for (const Diagnostic &D : Params.context.diagnostics) {
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000733 for (auto &F : getFixes(File.file(), D)) {
734 FixIts.push_back(toCodeAction(F, Params.textDocument.uri));
735 FixIts.back().diagnostics = {D};
Sam McCalldd0566b2017-11-06 15:40:30 +0000736 }
Ilya Biryukovafb55542017-05-16 14:40:30 +0000737 }
Sam McCall20841d42018-10-16 16:29:41 +0000738
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000739 // Now enumerate the semantic code actions.
740 auto ConsumeActions =
741 [this](decltype(Reply) Reply, URIForFile File, std::string Code,
742 Range Selection, std::vector<CodeAction> FixIts,
743 llvm::Expected<std::vector<ClangdServer::TweakRef>> Tweaks) {
Ilya Biryukovc6ed7782019-01-30 14:24:17 +0000744 if (!Tweaks)
745 return Reply(Tweaks.takeError());
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000746
747 std::vector<CodeAction> Actions = std::move(FixIts);
748 Actions.reserve(Actions.size() + Tweaks->size());
749 for (const auto &T : *Tweaks)
750 Actions.push_back(toCodeAction(T, File, Selection));
751
752 if (SupportsCodeAction)
753 return Reply(llvm::json::Array(Actions));
754 std::vector<Command> Commands;
755 for (const auto &Action : Actions) {
756 if (auto Command = asCommand(Action))
757 Commands.push_back(std::move(*Command));
758 }
759 return Reply(llvm::json::Array(Commands));
760 };
761
762 Server->enumerateTweaks(File.file(), Params.range,
Ilya Biryukovc9409c62019-01-30 09:39:01 +0000763 Bind(ConsumeActions, std::move(Reply), File,
764 std::move(*Code), Params.range,
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000765 std::move(FixIts)));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000766}
767
Ilya Biryukovb0826bd2019-01-03 13:37:12 +0000768void ClangdLSPServer::onCompletion(const CompletionParams &Params,
Sam McCall2c30fbc2018-10-18 12:32:04 +0000769 Callback<CompletionList> Reply) {
Ilya Biryukova7a11472019-06-07 16:24:38 +0000770 if (!shouldRunCompletion(Params)) {
771 // Clients sometimes auto-trigger completions in undesired places (e.g.
772 // 'a >^ '), we return empty results in those cases.
773 vlog("ignored auto-triggered completion, preceding char did not match");
774 return Reply(CompletionList());
775 }
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000776 Server->codeComplete(Params.textDocument.uri.file(), Params.position, CCOpts,
777 Bind(
778 [this](decltype(Reply) Reply,
779 llvm::Expected<CodeCompleteResult> List) {
780 if (!List)
781 return Reply(List.takeError());
782 CompletionList LSPList;
783 LSPList.isIncomplete = List->HasMore;
784 for (const auto &R : List->Completions) {
785 CompletionItem C = R.render(CCOpts);
786 C.kind = adjustKindToCapability(
787 C.kind, SupportedCompletionItemKinds);
788 LSPList.items.push_back(std::move(C));
789 }
790 return Reply(std::move(LSPList));
791 },
792 std::move(Reply)));
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000793}
794
Sam McCall2c30fbc2018-10-18 12:32:04 +0000795void ClangdLSPServer::onSignatureHelp(const TextDocumentPositionParams &Params,
796 Callback<SignatureHelp> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000797 Server->signatureHelp(Params.textDocument.uri.file(), Params.position,
Ilya Biryukov4ef0f822019-06-04 09:36:59 +0000798 Bind(
799 [this](decltype(Reply) Reply,
800 llvm::Expected<SignatureHelp> Signature) {
801 if (!Signature)
802 return Reply(Signature.takeError());
803 if (SupportsOffsetsInSignatureHelp)
804 return Reply(std::move(*Signature));
805 // Strip out the offsets from signature help for
806 // clients that only support string labels.
Simon Pilgrim5f7c20e2019-06-04 11:11:51 +0000807 for (auto &SigInfo : Signature->signatures) {
808 for (auto &Param : SigInfo.parameters)
Ilya Biryukov4ef0f822019-06-04 09:36:59 +0000809 Param.labelOffsets.reset();
810 }
811 return Reply(std::move(*Signature));
812 },
813 std::move(Reply)));
Ilya Biryukov652364b2018-09-26 05:48:29 +0000814}
815
Sam McCall0dbab7f2019-02-02 05:56:00 +0000816// Go to definition has a toggle function: if def and decl are distinct, then
817// the first press gives you the def, the second gives you the matching def.
818// getToggle() returns the counterpart location that under the cursor.
819//
820// We return the toggled location alone (ignoring other symbols) to encourage
821// editors to "bounce" quickly between locations, without showing a menu.
822static Location *getToggle(const TextDocumentPositionParams &Point,
823 LocatedSymbol &Sym) {
824 // Toggle only makes sense with two distinct locations.
825 if (!Sym.Definition || *Sym.Definition == Sym.PreferredDeclaration)
826 return nullptr;
827 if (Sym.Definition->uri.file() == Point.textDocument.uri.file() &&
828 Sym.Definition->range.contains(Point.position))
829 return &Sym.PreferredDeclaration;
830 if (Sym.PreferredDeclaration.uri.file() == Point.textDocument.uri.file() &&
831 Sym.PreferredDeclaration.range.contains(Point.position))
832 return &*Sym.Definition;
833 return nullptr;
834}
835
Sam McCall2c30fbc2018-10-18 12:32:04 +0000836void ClangdLSPServer::onGoToDefinition(const TextDocumentPositionParams &Params,
837 Callback<std::vector<Location>> Reply) {
Sam McCall866ba2c2019-02-01 11:26:13 +0000838 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> Defs;
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)});
Sam McCall866ba2c2019-02-01 11:26:13 +0000849 Defs.push_back(S.Definition.getValueOr(S.PreferredDeclaration));
Sam McCall0dbab7f2019-02-02 05:56:00 +0000850 }
Sam McCall866ba2c2019-02-01 11:26:13 +0000851 Reply(std::move(Defs));
852 },
853 std::move(Reply)));
854}
855
856void ClangdLSPServer::onGoToDeclaration(
857 const TextDocumentPositionParams &Params,
858 Callback<std::vector<Location>> Reply) {
859 Server->locateSymbolAt(
860 Params.textDocument.uri.file(), Params.position,
861 Bind(
Sam McCall0dbab7f2019-02-02 05:56:00 +0000862 [&, Params](decltype(Reply) Reply,
863 llvm::Expected<std::vector<LocatedSymbol>> Symbols) {
Sam McCall866ba2c2019-02-01 11:26:13 +0000864 if (!Symbols)
865 return Reply(Symbols.takeError());
866 std::vector<Location> Decls;
Sam McCall0dbab7f2019-02-02 05:56:00 +0000867 for (auto &S : *Symbols) {
868 if (Location *Toggle = getToggle(Params, S))
869 return Reply(std::vector<Location>{std::move(*Toggle)});
870 Decls.push_back(std::move(S.PreferredDeclaration));
871 }
Sam McCall866ba2c2019-02-01 11:26:13 +0000872 Reply(std::move(Decls));
873 },
874 std::move(Reply)));
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000875}
876
Sam McCall111fe842019-05-07 07:55:35 +0000877void ClangdLSPServer::onSwitchSourceHeader(
878 const TextDocumentIdentifier &Params,
Sam McCallb9ec3e92019-05-07 08:30:32 +0000879 Callback<llvm::Optional<URIForFile>> Reply) {
Sam McCall111fe842019-05-07 07:55:35 +0000880 if (auto Result = Server->switchSourceHeader(Params.uri.file()))
Sam McCallb9ec3e92019-05-07 08:30:32 +0000881 Reply(URIForFile::canonicalize(*Result, Params.uri.file()));
Sam McCall111fe842019-05-07 07:55:35 +0000882 else
883 Reply(llvm::None);
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000884}
885
Sam McCall2c30fbc2018-10-18 12:32:04 +0000886void ClangdLSPServer::onDocumentHighlight(
887 const TextDocumentPositionParams &Params,
888 Callback<std::vector<DocumentHighlight>> Reply) {
889 Server->findDocumentHighlights(Params.textDocument.uri.file(),
890 Params.position, std::move(Reply));
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000891}
892
Sam McCall2c30fbc2018-10-18 12:32:04 +0000893void ClangdLSPServer::onHover(const TextDocumentPositionParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000894 Callback<llvm::Optional<Hover>> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000895 Server->findHover(Params.textDocument.uri.file(), Params.position,
Kadir Cetinkayac6578ee2019-05-28 10:29:58 +0000896 Bind(
Ilya Biryukovf9169d02019-05-29 10:01:00 +0000897 [this](decltype(Reply) Reply,
898 llvm::Expected<llvm::Optional<HoverInfo>> H) {
899 if (!H)
900 return Reply(H.takeError());
901 if (!*H)
Kadir Cetinkayac6578ee2019-05-28 10:29:58 +0000902 return Reply(llvm::None);
Ilya Biryukovf9169d02019-05-29 10:01:00 +0000903
904 Hover R;
905 R.contents.kind = HoverContentFormat;
906 R.range = (*H)->SymRange;
907 switch (HoverContentFormat) {
908 case MarkupKind::PlainText:
909 R.contents.value =
910 (*H)->present().renderAsPlainText();
911 return Reply(std::move(R));
912 case MarkupKind::Markdown:
913 R.contents.value =
914 (*H)->present().renderAsMarkdown();
915 return Reply(std::move(R));
916 };
917 llvm_unreachable("unhandled MarkupKind");
Kadir Cetinkayac6578ee2019-05-28 10:29:58 +0000918 },
919 std::move(Reply)));
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000920}
921
Kadir Cetinkaya86658022019-03-19 09:27:04 +0000922void ClangdLSPServer::onTypeHierarchy(
923 const TypeHierarchyParams &Params,
924 Callback<Optional<TypeHierarchyItem>> Reply) {
925 Server->typeHierarchy(Params.textDocument.uri.file(), Params.position,
926 Params.resolve, Params.direction, std::move(Reply));
927}
928
Simon Marchi88016782018-08-01 11:28:49 +0000929void ClangdLSPServer::applyConfiguration(
Sam McCallbc904612018-10-25 04:22:52 +0000930 const ConfigurationSettings &Settings) {
Simon Marchiabeed662018-10-16 15:55:03 +0000931 // Per-file update to the compilation database.
Sam McCallbc904612018-10-25 04:22:52 +0000932 bool ShouldReparseOpenFiles = false;
933 for (auto &Entry : Settings.compilationDatabaseChanges) {
934 /// The opened files need to be reparsed only when some existing
935 /// entries are changed.
936 PathRef File = Entry.first;
Sam McCallc55d09a2018-11-02 13:09:36 +0000937 auto Old = CDB->getCompileCommand(File);
938 auto New =
939 tooling::CompileCommand(std::move(Entry.second.workingDirectory), File,
940 std::move(Entry.second.compilationCommand),
941 /*Output=*/"");
Sam McCall6980edb2018-11-02 14:07:51 +0000942 if (Old != New) {
Sam McCallc55d09a2018-11-02 13:09:36 +0000943 CDB->setCompileCommand(File, std::move(New));
Sam McCall6980edb2018-11-02 14:07:51 +0000944 ShouldReparseOpenFiles = true;
945 }
Alex Lorenzf8087862018-08-01 17:39:29 +0000946 }
Sam McCallbc904612018-10-25 04:22:52 +0000947 if (ShouldReparseOpenFiles)
948 reparseOpenedFiles();
Simon Marchi5178f922018-02-22 14:00:39 +0000949}
950
Johan Vikstroma848dab2019-07-04 07:53:12 +0000951void ClangdLSPServer::publishSemanticHighlighting(
952 SemanticHighlightingParams Params) {
953 notify("textDocument/semanticHighlighting", Params);
954}
955
Ilya Biryukov49c10712019-03-25 10:15:11 +0000956void ClangdLSPServer::publishDiagnostics(
957 const URIForFile &File, std::vector<clangd::Diagnostic> Diagnostics) {
958 // Publish diagnostics.
959 notify("textDocument/publishDiagnostics",
960 llvm::json::Object{
961 {"uri", File},
962 {"diagnostics", std::move(Diagnostics)},
963 });
964}
965
Simon Marchi88016782018-08-01 11:28:49 +0000966// FIXME: This function needs to be properly tested.
967void ClangdLSPServer::onChangeConfiguration(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000968 const DidChangeConfigurationParams &Params) {
Simon Marchi88016782018-08-01 11:28:49 +0000969 applyConfiguration(Params.settings);
970}
971
Sam McCall2c30fbc2018-10-18 12:32:04 +0000972void ClangdLSPServer::onReference(const ReferenceParams &Params,
973 Callback<std::vector<Location>> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000974 Server->findReferences(Params.textDocument.uri.file(), Params.position,
Haojian Wuc34f0222019-01-14 18:11:09 +0000975 CCOpts.Limit, std::move(Reply));
Sam McCall1ad142f2018-09-05 11:53:07 +0000976}
977
Jan Korousb4067012018-11-27 16:40:46 +0000978void ClangdLSPServer::onSymbolInfo(const TextDocumentPositionParams &Params,
979 Callback<std::vector<SymbolDetails>> Reply) {
980 Server->symbolInfo(Params.textDocument.uri.file(), Params.position,
981 std::move(Reply));
982}
983
Sam McCalla69698f2019-03-27 17:47:49 +0000984ClangdLSPServer::ClangdLSPServer(
985 class Transport &Transp, const FileSystemProvider &FSProvider,
986 const clangd::CodeCompleteOptions &CCOpts,
987 llvm::Optional<Path> CompileCommandsDir, bool UseDirBasedCDB,
988 llvm::Optional<OffsetEncoding> ForcedOffsetEncoding,
989 const ClangdServer::Options &Opts)
Haojian Wu1ca0c582019-01-22 09:39:05 +0000990 : Transp(Transp), MsgHandler(new MessageHandler(*this)),
991 FSProvider(FSProvider), CCOpts(CCOpts),
Sam McCalld1c9d112018-10-23 14:19:54 +0000992 SupportedSymbolKinds(defaultSymbolKinds()),
Kadir Cetinkaya133d46f2018-09-27 17:13:07 +0000993 SupportedCompletionItemKinds(defaultCompletionItemKinds()),
Sam McCallc55d09a2018-11-02 13:09:36 +0000994 UseDirBasedCDB(UseDirBasedCDB),
Sam McCalla69698f2019-03-27 17:47:49 +0000995 CompileCommandsDir(std::move(CompileCommandsDir)), ClangdServerOpts(Opts),
996 NegotiatedOffsetEncoding(ForcedOffsetEncoding) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000997 // clang-format off
998 MsgHandler->bind("initialize", &ClangdLSPServer::onInitialize);
999 MsgHandler->bind("shutdown", &ClangdLSPServer::onShutdown);
Sam McCall422c8282018-11-26 16:00:11 +00001000 MsgHandler->bind("sync", &ClangdLSPServer::onSync);
Sam McCall2c30fbc2018-10-18 12:32:04 +00001001 MsgHandler->bind("textDocument/rangeFormatting", &ClangdLSPServer::onDocumentRangeFormatting);
1002 MsgHandler->bind("textDocument/onTypeFormatting", &ClangdLSPServer::onDocumentOnTypeFormatting);
1003 MsgHandler->bind("textDocument/formatting", &ClangdLSPServer::onDocumentFormatting);
1004 MsgHandler->bind("textDocument/codeAction", &ClangdLSPServer::onCodeAction);
1005 MsgHandler->bind("textDocument/completion", &ClangdLSPServer::onCompletion);
1006 MsgHandler->bind("textDocument/signatureHelp", &ClangdLSPServer::onSignatureHelp);
1007 MsgHandler->bind("textDocument/definition", &ClangdLSPServer::onGoToDefinition);
Sam McCall866ba2c2019-02-01 11:26:13 +00001008 MsgHandler->bind("textDocument/declaration", &ClangdLSPServer::onGoToDeclaration);
Sam McCall2c30fbc2018-10-18 12:32:04 +00001009 MsgHandler->bind("textDocument/references", &ClangdLSPServer::onReference);
1010 MsgHandler->bind("textDocument/switchSourceHeader", &ClangdLSPServer::onSwitchSourceHeader);
1011 MsgHandler->bind("textDocument/rename", &ClangdLSPServer::onRename);
1012 MsgHandler->bind("textDocument/hover", &ClangdLSPServer::onHover);
1013 MsgHandler->bind("textDocument/documentSymbol", &ClangdLSPServer::onDocumentSymbol);
1014 MsgHandler->bind("workspace/executeCommand", &ClangdLSPServer::onCommand);
1015 MsgHandler->bind("textDocument/documentHighlight", &ClangdLSPServer::onDocumentHighlight);
1016 MsgHandler->bind("workspace/symbol", &ClangdLSPServer::onWorkspaceSymbol);
1017 MsgHandler->bind("textDocument/didOpen", &ClangdLSPServer::onDocumentDidOpen);
1018 MsgHandler->bind("textDocument/didClose", &ClangdLSPServer::onDocumentDidClose);
1019 MsgHandler->bind("textDocument/didChange", &ClangdLSPServer::onDocumentDidChange);
1020 MsgHandler->bind("workspace/didChangeWatchedFiles", &ClangdLSPServer::onFileEvent);
1021 MsgHandler->bind("workspace/didChangeConfiguration", &ClangdLSPServer::onChangeConfiguration);
Jan Korousb4067012018-11-27 16:40:46 +00001022 MsgHandler->bind("textDocument/symbolInfo", &ClangdLSPServer::onSymbolInfo);
Kadir Cetinkaya86658022019-03-19 09:27:04 +00001023 MsgHandler->bind("textDocument/typeHierarchy", &ClangdLSPServer::onTypeHierarchy);
Sam McCall2c30fbc2018-10-18 12:32:04 +00001024 // clang-format on
1025}
1026
1027ClangdLSPServer::~ClangdLSPServer() = default;
Ilya Biryukov38d79772017-05-16 09:38:59 +00001028
Sam McCalldc8f3cf2018-10-17 07:32:05 +00001029bool ClangdLSPServer::run() {
Ilya Biryukovafb55542017-05-16 14:40:30 +00001030 // Run the Language Server loop.
Sam McCalldc8f3cf2018-10-17 07:32:05 +00001031 bool CleanExit = true;
Sam McCall2c30fbc2018-10-18 12:32:04 +00001032 if (auto Err = Transp.loop(*MsgHandler)) {
Sam McCalldc8f3cf2018-10-17 07:32:05 +00001033 elog("Transport error: {0}", std::move(Err));
1034 CleanExit = false;
1035 }
Ilya Biryukovafb55542017-05-16 14:40:30 +00001036
Ilya Biryukov652364b2018-09-26 05:48:29 +00001037 // Destroy ClangdServer to ensure all worker threads finish.
1038 Server.reset();
Sam McCalldc8f3cf2018-10-17 07:32:05 +00001039 return CleanExit && ShutdownRequestReceived;
Ilya Biryukov38d79772017-05-16 09:38:59 +00001040}
1041
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001042std::vector<Fix> ClangdLSPServer::getFixes(llvm::StringRef File,
Ilya Biryukov71028b82018-03-12 15:28:22 +00001043 const clangd::Diagnostic &D) {
Ilya Biryukov38d79772017-05-16 09:38:59 +00001044 std::lock_guard<std::mutex> Lock(FixItsMutex);
1045 auto DiagToFixItsIter = FixItsMap.find(File);
1046 if (DiagToFixItsIter == FixItsMap.end())
1047 return {};
1048
1049 const auto &DiagToFixItsMap = DiagToFixItsIter->second;
1050 auto FixItsIter = DiagToFixItsMap.find(D);
1051 if (FixItsIter == DiagToFixItsMap.end())
1052 return {};
1053
1054 return FixItsIter->second;
1055}
1056
Ilya Biryukovb0826bd2019-01-03 13:37:12 +00001057bool ClangdLSPServer::shouldRunCompletion(
1058 const CompletionParams &Params) const {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001059 llvm::StringRef Trigger = Params.context.triggerCharacter;
Ilya Biryukovb0826bd2019-01-03 13:37:12 +00001060 if (Params.context.triggerKind != CompletionTriggerKind::TriggerCharacter ||
1061 (Trigger != ">" && Trigger != ":"))
1062 return true;
1063
1064 auto Code = DraftMgr.getDraft(Params.textDocument.uri.file());
1065 if (!Code)
1066 return true; // completion code will log the error for untracked doc.
1067
1068 // A completion request is sent when the user types '>' or ':', but we only
1069 // want to trigger on '->' and '::'. We check the preceeding character to make
1070 // sure it matches what we expected.
1071 // Running the lexer here would be more robust (e.g. we can detect comments
1072 // and avoid triggering completion there), but we choose to err on the side
1073 // of simplicity here.
1074 auto Offset = positionToOffset(*Code, Params.position,
1075 /*AllowColumnsBeyondLineLength=*/false);
1076 if (!Offset) {
1077 vlog("could not convert position '{0}' to offset for file '{1}'",
1078 Params.position, Params.textDocument.uri.file());
1079 return true;
1080 }
1081 if (*Offset < 2)
1082 return false;
1083
1084 if (Trigger == ">")
1085 return (*Code)[*Offset - 2] == '-'; // trigger only on '->'.
1086 if (Trigger == ":")
1087 return (*Code)[*Offset - 2] == ':'; // trigger only on '::'.
1088 assert(false && "unhandled trigger character");
1089 return true;
1090}
1091
Johan Vikstroma848dab2019-07-04 07:53:12 +00001092void ClangdLSPServer::onHighlightingsReady(
1093 PathRef File, std::vector<HighlightingToken> Highlightings) {
1094 publishSemanticHighlighting(
1095 {{URIForFile::canonicalize(File, /*TUPath=*/File)},
1096 toSemanticHighlightingInformation(Highlightings)});
1097}
1098
Sam McCalla7bb0cc2018-03-12 23:22:35 +00001099void ClangdLSPServer::onDiagnosticsReady(PathRef File,
1100 std::vector<Diag> Diagnostics) {
Eric Liu4d814a92018-11-28 10:30:42 +00001101 auto URI = URIForFile::canonicalize(File, /*TUPath=*/File);
Sam McCall16e70702018-10-24 07:59:38 +00001102 std::vector<Diagnostic> LSPDiagnostics;
Ilya Biryukov38d79772017-05-16 09:38:59 +00001103 DiagnosticToReplacementMap LocalFixIts; // Temporary storage
Sam McCalla7bb0cc2018-03-12 23:22:35 +00001104 for (auto &Diag : Diagnostics) {
Sam McCall16e70702018-10-24 07:59:38 +00001105 toLSPDiags(Diag, URI, DiagOpts,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001106 [&](clangd::Diagnostic Diag, llvm::ArrayRef<Fix> Fixes) {
Sam McCall16e70702018-10-24 07:59:38 +00001107 auto &FixItsForDiagnostic = LocalFixIts[Diag];
1108 llvm::copy(Fixes, std::back_inserter(FixItsForDiagnostic));
1109 LSPDiagnostics.push_back(std::move(Diag));
1110 });
Ilya Biryukov38d79772017-05-16 09:38:59 +00001111 }
1112
1113 // Cache FixIts
1114 {
Ilya Biryukov38d79772017-05-16 09:38:59 +00001115 std::lock_guard<std::mutex> Lock(FixItsMutex);
1116 FixItsMap[File] = LocalFixIts;
1117 }
1118
Ilya Biryukov49c10712019-03-25 10:15:11 +00001119 // Send a notification to the LSP client.
1120 publishDiagnostics(URI, std::move(LSPDiagnostics));
Ilya Biryukov38d79772017-05-16 09:38:59 +00001121}
Simon Marchi9569fd52018-03-16 14:30:42 +00001122
Haojian Wub6188492018-12-20 15:39:12 +00001123void ClangdLSPServer::onFileUpdated(PathRef File, const TUStatus &Status) {
1124 if (!SupportFileStatus)
1125 return;
1126 // FIXME: we don't emit "BuildingFile" and `RunningAction`, as these
1127 // two statuses are running faster in practice, which leads the UI constantly
1128 // changing, and doesn't provide much value. We may want to emit status at a
1129 // reasonable time interval (e.g. 0.5s).
1130 if (Status.Action.S == TUAction::BuildingFile ||
1131 Status.Action.S == TUAction::RunningAction)
1132 return;
1133 notify("textDocument/clangd.fileStatus", Status.render(File));
1134}
1135
Simon Marchi9569fd52018-03-16 14:30:42 +00001136void ClangdLSPServer::reparseOpenedFiles() {
1137 for (const Path &FilePath : DraftMgr.getActiveFiles())
Ilya Biryukov652364b2018-09-26 05:48:29 +00001138 Server->addDocument(FilePath, *DraftMgr.getDraft(FilePath),
1139 WantDiagnostics::Auto);
Simon Marchi9569fd52018-03-16 14:30:42 +00001140}
Alex Lorenzf8087862018-08-01 17:39:29 +00001141
Sam McCallc008af62018-10-20 15:30:37 +00001142} // namespace clangd
1143} // namespace clang