LLVM 24.0.0git
Transport.h
Go to the documentation of this file.
1//===--- Transport.h - Sending and Receiving LSP messages -------*- C++ -*-===//
2//
3// 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
6//
7//===----------------------------------------------------------------------===//
8//
9// The language server protocol is usually implemented by writing messages as
10// JSON-RPC over the stdin/stdout of a subprocess. This file contains a JSON
11// transport interface that handles this communication.
12//
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_SUPPORT_LSP_TRANSPORT_H
16#define LLVM_SUPPORT_LSP_TRANSPORT_H
17
19#include "llvm/ADT/StringMap.h"
20#include "llvm/ADT/StringRef.h"
23#include "llvm/Support/JSON.h"
27#include <memory>
28
29namespace llvm {
30namespace lsp {
31class MessageHandler;
32
33//===----------------------------------------------------------------------===//
34// JSONTransport
35//===----------------------------------------------------------------------===//
36
37/// The encoding style of the JSON-RPC messages (both input and output).
39 /// Encoding per the LSP specification, with mandatory Content-Length header.
41 /// Messages are delimited by a '// -----' line. Comment lines start with //.
43};
44
45/// An abstract class used by the JSONTransport to read JSON message.
47public:
49 : Style(Style) {}
50 virtual ~JSONTransportInput() = default;
51
52 virtual bool hasError() const = 0;
53 virtual bool isEndOfInput() const = 0;
54
55 /// Read in a message from the input stream.
56 LogicalResult readMessage(std::string &Json) {
58 : readStandardMessage(Json);
59 }
60 virtual LogicalResult readDelimitedMessage(std::string &Json) = 0;
61 virtual LogicalResult readStandardMessage(std::string &Json) = 0;
62
63private:
64 /// The JSON stream style to use.
65 JSONStreamStyle Style;
66};
67
68/// Concrete implementation of the JSONTransportInput that reads from a file.
70public:
72 std::FILE *In, JSONStreamStyle Style = JSONStreamStyle::Standard)
73 : JSONTransportInput(Style), In(In) {}
74
75 bool hasError() const final { return ferror(In); }
76 bool isEndOfInput() const final { return feof(In); }
77
78 LogicalResult readDelimitedMessage(std::string &Json) final;
79 LogicalResult readStandardMessage(std::string &Json) final;
80
81private:
82 std::FILE *In;
83};
84
85/// A transport class that performs the JSON-RPC communication with the LSP
86/// client.
88public:
89 JSONTransport(std::unique_ptr<JSONTransportInput> In, raw_ostream &Out,
90 bool PrettyOutput = false)
91 : In(std::move(In)), Out(Out), PrettyOutput(PrettyOutput) {}
92
93 JSONTransport(std::FILE *In, raw_ostream &Out,
95 bool PrettyOutput = false)
96 : In(std::make_unique<JSONTransportInputOverFile>(In, Style)), Out(Out),
97 PrettyOutput(PrettyOutput) {}
98
99 /// The following methods are used to send a message to the LSP client.
105
106 /// Start executing the JSON-RPC transport.
108
109private:
110 /// Dispatches the given incoming json message to the message handler.
111 bool handleMessage(llvm::json::Value Msg, MessageHandler &Handler);
112 /// Writes the given message to the output stream.
113 void sendMessage(llvm::json::Value Msg);
114
115private:
116 /// The input to read a message from.
117 std::unique_ptr<JSONTransportInput> In;
119 /// The output file stream.
120 raw_ostream &Out;
121 /// If the output JSON should be formatted for easier readability.
122 bool PrettyOutput;
123};
124
125//===----------------------------------------------------------------------===//
126// MessageHandler
127//===----------------------------------------------------------------------===//
128
129/// A Callback<T> is a void function that accepts Expected<T>. This is
130/// accepted by functions that logically return T.
131template <typename T>
133
134/// An OutgoingNotification<T> is a function used for outgoing notifications
135/// send to the client.
136template <typename T>
138
139/// An OutgoingRequest<T> is a function used for outgoing requests to send to
140/// the client.
141template <typename T>
143 llvm::unique_function<void(const T &, llvm::json::Value Id)>;
144
145/// An `OutgoingRequestCallback` is invoked when an outgoing request to the
146/// client receives a response in turn. It is passed the original request's ID,
147/// as well as the response result.
148template <typename T>
150 std::function<void(llvm::json::Value, llvm::Expected<T>)>;
151
152/// A handler used to process the incoming transport messages.
154public:
155 MessageHandler(JSONTransport &Transport) : Transport(Transport) {}
156
162
163 template <typename T>
165 StringRef PayloadName, StringRef PayloadKind) {
166 T Result;
168 if (!fromJSON(Raw, Result, Root))
169 return handleParseError(Raw, PayloadName, PayloadKind, Root);
170 return std::move(Result);
171 }
172
173 template <typename Param, typename Result, typename ThisT>
174 void method(llvm::StringLiteral Method, ThisT *ThisPtr,
175 void (ThisT::*Handler)(const Param &, Callback<Result>)) {
176 MethodHandlers[Method] = [Method, Handler,
177 ThisPtr](llvm::json::Value RawParams,
180 parse<Param>(RawParams, Method, "request");
181 if (!Parameter)
182 return Reply(Parameter.takeError());
183 (ThisPtr->*Handler)(*Parameter, std::move(Reply));
184 };
185 }
186
187 template <typename Param, typename ThisT>
189 void (ThisT::*Handler)(const Param &)) {
190 NotificationHandlers[Method] = [Method, Handler,
191 ThisPtr](llvm::json::Value RawParams) {
193 parse<Param>(RawParams, Method, "notification");
194 if (!Parameter) {
196 Parameter.takeError(), [](const LSPError &LspError) {
197 Logger::error("JSON parsing error: {0}",
198 LspError.message.c_str());
199 }));
200 }
201 (ThisPtr->*Handler)(*Parameter);
202 };
203 }
204
205 /// Create an OutgoingNotification object used for the given method.
206 template <typename T>
208 return [&, Method](const T &Params) {
209 std::lock_guard<std::mutex> TransportLock(TransportOutputMutex);
210 Logger::info("--> {0}", Method);
211 Transport.notify(Method, llvm::json::Value(Params));
212 };
213 }
214
215 // Simple helper function that returns a string as printed from a op.
216 template <typename T> static std::string debugString(T &&Op) {
217 std::string InstrStr;
218 llvm::raw_string_ostream Os(InstrStr);
219 Os << Op;
220 return Os.str();
221 }
222
223 /// Create an OutgoingRequest function that, when called, sends a request with
224 /// the given method via the transport. Should the outgoing request be
225 /// met with a response, the result JSON is parsed and the response callback
226 /// is invoked.
227 template <typename Param, typename Result>
231 return [&, Method, Callback](const Param &Parameter, llvm::json::Value Id) {
232 auto CallbackWrapper = [Method, Callback = std::move(Callback)](
235 if (!Value)
236 return Callback(std::move(Id), Value.takeError());
237
238 std::string ResponseName = llvm::formatv("reply:{0}({1})", Method, Id);
240 parse<Result>(*Value, ResponseName, "response");
241 if (!ParseResult)
242 return Callback(std::move(Id), ParseResult.takeError());
243
244 return Callback(std::move(Id), *ParseResult);
245 };
246
247 {
248 std::lock_guard<std::mutex> Lock(ResponseHandlersMutex);
249 ResponseHandlers.insert(
250 {debugString(Id), std::make_pair(Method.str(), CallbackWrapper)});
251 }
252
253 std::lock_guard<std::mutex> TransportLock(TransportOutputMutex);
254 Logger::info("--> {0}({1})", Method, Id);
255 Transport.call(Method, llvm::json::Value(Parameter), Id);
256 };
257 }
258
259private:
260 LLVM_ABI static llvm::Error
261 handleParseError(const llvm::json::Value &Raw, StringRef PayloadName,
262 StringRef PayloadKind, const llvm::json::Path::Root &Root);
263
264 template <typename HandlerT>
266
267 HandlerMap<void(llvm::json::Value)> NotificationHandlers;
269 MethodHandlers;
270
271 /// A pair of (1) the original request's method name, and (2) the callback
272 /// function to be invoked for responses.
273 using ResponseHandlerTy =
274 std::pair<std::string, OutgoingRequestCallback<llvm::json::Value>>;
275 /// A mapping from request/response ID to response handler.
276 llvm::StringMap<ResponseHandlerTy> ResponseHandlers;
277 /// Mutex to guard insertion into the response handler map.
278 std::mutex ResponseHandlersMutex;
279
280 JSONTransport &Transport;
281
282 /// Mutex to guard sending output messages to the transport.
283 std::mutex TransportOutputMutex;
284};
285
286} // namespace lsp
287} // namespace llvm
288
289#endif
aarch64 promote const
This file defines the StringMap class.
#define LLVM_ABI
Definition Compiler.h:215
This file provides a collection of function (or more generally, callable) type erasure utilities supp...
This file supports working with JSON data.
#define T
const char * Msg
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
Tagged union holding either a T or a Error.
Definition Error.h:485
This class represents success/failure for parsing-like operations that find it important to chain tog...
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
A wrapper around a string literal that serves as a proxy for constructing global tables of StringRefs...
Definition StringRef.h:888
StringMap - This is an unconventional map that is specialized for handling keys that are "strings",...
Definition StringMap.h:129
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
The root is the trivial Path to the root value.
Definition JSON.h:700
A Value is an JSON value of unknown type.
Definition JSON.h:291
Concrete implementation of the JSONTransportInput that reads from a file.
Definition Transport.h:69
JSONTransportInputOverFile(std::FILE *In, JSONStreamStyle Style=JSONStreamStyle::Standard)
Definition Transport.h:71
virtual bool hasError() const =0
virtual bool isEndOfInput() const =0
virtual LogicalResult readDelimitedMessage(std::string &Json)=0
LogicalResult readMessage(std::string &Json)
Read in a message from the input stream.
Definition Transport.h:56
virtual ~JSONTransportInput()=default
virtual LogicalResult readStandardMessage(std::string &Json)=0
JSONTransportInput(JSONStreamStyle Style=JSONStreamStyle::Standard)
Definition Transport.h:48
A transport class that performs the JSON-RPC communication with the LSP client.
Definition Transport.h:87
LLVM_ABI void reply(llvm::json::Value Id, llvm::Expected< llvm::json::Value > Result)
LLVM_ABI llvm::Error run(MessageHandler &Handler)
Start executing the JSON-RPC transport.
LLVM_ABI void notify(StringRef Method, llvm::json::Value Params)
The following methods are used to send a message to the LSP client.
JSONTransport(std::unique_ptr< JSONTransportInput > In, raw_ostream &Out, bool PrettyOutput=false)
Definition Transport.h:89
LLVM_ABI void call(StringRef Method, llvm::json::Value Params, llvm::json::Value Id)
JSONTransport(std::FILE *In, raw_ostream &Out, JSONStreamStyle Style=JSONStreamStyle::Standard, bool PrettyOutput=false)
Definition Transport.h:93
This class models an LSP error as an llvm::Error.
Definition Protocol.h:80
static void info(const char *Fmt, Ts &&...Vals)
Definition Logging.h:34
A handler used to process the incoming transport messages.
Definition Transport.h:153
OutgoingRequest< Param > outgoingRequest(llvm::StringLiteral Method, OutgoingRequestCallback< Result > Callback)
Create an OutgoingRequest function that, when called, sends a request with the given method via the t...
Definition Transport.h:229
void notification(llvm::StringLiteral Method, ThisT *ThisPtr, void(ThisT::*Handler)(const Param &))
Definition Transport.h:188
OutgoingNotification< T > outgoingNotification(llvm::StringLiteral Method)
Create an OutgoingNotification object used for the given method.
Definition Transport.h:207
LLVM_ABI bool onNotify(StringRef Method, llvm::json::Value Value)
void method(llvm::StringLiteral Method, ThisT *ThisPtr, void(ThisT::*Handler)(const Param &, Callback< Result >))
Definition Transport.h:174
MessageHandler(JSONTransport &Transport)
Definition Transport.h:155
static llvm::Expected< T > parse(const llvm::json::Value &Raw, StringRef PayloadName, StringRef PayloadKind)
Definition Transport.h:164
static std::string debugString(T &&Op)
Definition Transport.h:216
LLVM_ABI bool onCall(StringRef Method, llvm::json::Value Params, llvm::json::Value Id)
LLVM_ABI bool onReply(llvm::json::Value Id, llvm::Expected< llvm::json::Value > Result)
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
A raw_ostream that writes to an std::string.
std::string & str()
Returns the string's reference.
unique_function is a type-erasing functor similar to std::function.
llvm::unique_function< void(llvm::Expected< T >)> Callback
A Callback<T> is a void function that accepts Expected<T>.
Definition Transport.h:132
llvm::unique_function< void(const T &, llvm::json::Value Id)> OutgoingRequest
An OutgoingRequest<T> is a function used for outgoing requests to send to the client.
Definition Transport.h:142
@ Parameter
An inlay hint that is for a parameter.
Definition Protocol.h:1134
std::function< void(llvm::json::Value, llvm::Expected< T >)> OutgoingRequestCallback
An OutgoingRequestCallback is invoked when an outgoing request to the client receives a response in t...
Definition Transport.h:149
LLVM_ABI bool fromJSON(const llvm::json::Value &value, URIForFile &result, llvm::json::Path path)
Definition Protocol.cpp:238
JSONStreamStyle
The encoding style of the JSON-RPC messages (both input and output).
Definition Transport.h:38
@ Standard
Encoding per the LSP specification, with mandatory Content-Length header.
Definition Transport.h:40
@ Delimited
Messages are delimited by a '// --—' line. Comment lines start with //.
Definition Transport.h:42
llvm::unique_function< void(const T &)> OutgoingNotification
An OutgoingNotification<T> is a function used for outgoing notifications send to the client.
Definition Transport.h:137
This is an optimization pass for GlobalISel generic memory operations.
Error handleErrors(Error E, HandlerTs &&... Hs)
Pass the ErrorInfo(s) contained in E to their respective handlers.
Definition Error.h:990
auto formatv(bool Validate, const char *Fmt, Ts &&...Vals)
DWARFExpression::Operation Op
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1917
void consumeError(Error Err)
Consume a Error without doing anything.
Definition Error.h:1106
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:878
This class represents an efficient way to signal success or failure.