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 {
30// Simple helper function that returns a string as printed from a op.
31template <typename T> static std::string debugString(T &&Op) {
32 std::string InstrStr;
33 llvm::raw_string_ostream Os(InstrStr);
34 Os << Op;
35 return Os.str();
36}
37namespace lsp {
38class MessageHandler;
39
40//===----------------------------------------------------------------------===//
41// JSONTransport
42//===----------------------------------------------------------------------===//
43
44/// The encoding style of the JSON-RPC messages (both input and output).
46 /// Encoding per the LSP specification, with mandatory Content-Length header.
48 /// Messages are delimited by a '// -----' line. Comment lines start with //.
50};
51
52/// An abstract class used by the JSONTransport to read JSON message.
54public:
56 : Style(Style) {}
57 virtual ~JSONTransportInput() = default;
58
59 virtual bool hasError() const = 0;
60 virtual bool isEndOfInput() const = 0;
61
62 /// Read in a message from the input stream.
63 LogicalResult readMessage(std::string &Json) {
65 : readStandardMessage(Json);
66 }
67 virtual LogicalResult readDelimitedMessage(std::string &Json) = 0;
68 virtual LogicalResult readStandardMessage(std::string &Json) = 0;
69
70private:
71 /// The JSON stream style to use.
72 JSONStreamStyle Style;
73};
74
75/// Concrete implementation of the JSONTransportInput that reads from a file.
77public:
79 std::FILE *In, JSONStreamStyle Style = JSONStreamStyle::Standard)
80 : JSONTransportInput(Style), In(In) {}
81
82 bool hasError() const final { return ferror(In); }
83 bool isEndOfInput() const final { return feof(In); }
84
85 LogicalResult readDelimitedMessage(std::string &Json) final;
86 LogicalResult readStandardMessage(std::string &Json) final;
87
88private:
89 std::FILE *In;
90};
91
92/// A transport class that performs the JSON-RPC communication with the LSP
93/// client.
95public:
96 JSONTransport(std::unique_ptr<JSONTransportInput> In, raw_ostream &Out,
97 bool PrettyOutput = false)
98 : In(std::move(In)), Out(Out), PrettyOutput(PrettyOutput) {}
99
100 JSONTransport(std::FILE *In, raw_ostream &Out,
102 bool PrettyOutput = false)
103 : In(std::make_unique<JSONTransportInputOverFile>(In, Style)), Out(Out),
104 PrettyOutput(PrettyOutput) {}
105
106 /// The following methods are used to send a message to the LSP client.
112
113 /// Start executing the JSON-RPC transport.
115
116private:
117 /// Dispatches the given incoming json message to the message handler.
118 bool handleMessage(llvm::json::Value Msg, MessageHandler &Handler);
119 /// Writes the given message to the output stream.
120 void sendMessage(llvm::json::Value Msg);
121
122private:
123 /// The input to read a message from.
124 std::unique_ptr<JSONTransportInput> In;
126 /// The output file stream.
127 raw_ostream &Out;
128 /// If the output JSON should be formatted for easier readability.
129 bool PrettyOutput;
130};
131
132//===----------------------------------------------------------------------===//
133// MessageHandler
134//===----------------------------------------------------------------------===//
135
136/// A Callback<T> is a void function that accepts Expected<T>. This is
137/// accepted by functions that logically return T.
138template <typename T>
140
141/// An OutgoingNotification<T> is a function used for outgoing notifications
142/// send to the client.
143template <typename T>
145
146/// An OutgoingRequest<T> is a function used for outgoing requests to send to
147/// the client.
148template <typename T>
150 llvm::unique_function<void(const T &, llvm::json::Value Id)>;
151
152/// An `OutgoingRequestCallback` is invoked when an outgoing request to the
153/// client receives a response in turn. It is passed the original request's ID,
154/// as well as the response result.
155template <typename T>
157 std::function<void(llvm::json::Value, llvm::Expected<T>)>;
158
159/// A handler used to process the incoming transport messages.
161public:
162 MessageHandler(JSONTransport &Transport) : Transport(Transport) {}
163
169
170 template <typename T>
172 StringRef PayloadName, StringRef PayloadKind) {
173 T Result;
175 if (!fromJSON(Raw, Result, Root))
176 return handleParseError(Raw, PayloadName, PayloadKind, Root);
177 return std::move(Result);
178 }
179
180 template <typename Param, typename Result, typename ThisT>
181 void method(llvm::StringLiteral Method, ThisT *ThisPtr,
182 void (ThisT::*Handler)(const Param &, Callback<Result>)) {
183 MethodHandlers[Method] = [Method, Handler,
184 ThisPtr](llvm::json::Value RawParams,
187 parse<Param>(RawParams, Method, "request");
188 if (!Parameter)
189 return Reply(Parameter.takeError());
190 (ThisPtr->*Handler)(*Parameter, std::move(Reply));
191 };
192 }
193
194 template <typename Param, typename ThisT>
196 void (ThisT::*Handler)(const Param &)) {
197 NotificationHandlers[Method] = [Method, Handler,
198 ThisPtr](llvm::json::Value RawParams) {
200 parse<Param>(RawParams, Method, "notification");
201 if (!Parameter) {
203 Parameter.takeError(), [](const LSPError &LspError) {
204 Logger::error("JSON parsing error: {0}",
205 LspError.message.c_str());
206 }));
207 }
208 (ThisPtr->*Handler)(*Parameter);
209 };
210 }
211
212 /// Create an OutgoingNotification object used for the given method.
213 template <typename T>
215 return [&, Method](const T &Params) {
216 std::lock_guard<std::mutex> TransportLock(TransportOutputMutex);
217 Logger::info("--> {0}", Method);
218 Transport.notify(Method, llvm::json::Value(Params));
219 };
220 }
221
222 /// Create an OutgoingRequest function that, when called, sends a request with
223 /// the given method via the transport. Should the outgoing request be
224 /// met with a response, the result JSON is parsed and the response callback
225 /// is invoked.
226 template <typename Param, typename Result>
230 return [&, Method, Callback](const Param &Parameter, llvm::json::Value Id) {
231 auto CallbackWrapper = [Method, Callback = std::move(Callback)](
234 if (!Value)
235 return Callback(std::move(Id), Value.takeError());
236
237 std::string ResponseName = llvm::formatv("reply:{0}({1})", Method, Id);
239 parse<Result>(*Value, ResponseName, "response");
240 if (!ParseResult)
241 return Callback(std::move(Id), ParseResult.takeError());
242
243 return Callback(std::move(Id), *ParseResult);
244 };
245
246 {
247 std::lock_guard<std::mutex> Lock(ResponseHandlersMutex);
248 ResponseHandlers.insert(
249 {debugString(Id), std::make_pair(Method.str(), CallbackWrapper)});
250 }
251
252 std::lock_guard<std::mutex> TransportLock(TransportOutputMutex);
253 Logger::info("--> {0}({1})", Method, Id);
254 Transport.call(Method, llvm::json::Value(Parameter), Id);
255 };
256 }
257
258private:
259 LLVM_ABI static llvm::Error
260 handleParseError(const llvm::json::Value &Raw, StringRef PayloadName,
261 StringRef PayloadKind, const llvm::json::Path::Root &Root);
262
263 template <typename HandlerT>
265
266 HandlerMap<void(llvm::json::Value)> NotificationHandlers;
268 MethodHandlers;
269
270 /// A pair of (1) the original request's method name, and (2) the callback
271 /// function to be invoked for responses.
272 using ResponseHandlerTy =
273 std::pair<std::string, OutgoingRequestCallback<llvm::json::Value>>;
274 /// A mapping from request/response ID to response handler.
275 llvm::StringMap<ResponseHandlerTy> ResponseHandlers;
276 /// Mutex to guard insertion into the response handler map.
277 std::mutex ResponseHandlersMutex;
278
279 JSONTransport &Transport;
280
281 /// Mutex to guard sending output messages to the transport.
282 std::mutex TransportOutputMutex;
283};
284
285} // namespace lsp
286} // namespace llvm
287
288#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:128
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:76
JSONTransportInputOverFile(std::FILE *In, JSONStreamStyle Style=JSONStreamStyle::Standard)
Definition Transport.h:78
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:63
virtual ~JSONTransportInput()=default
virtual LogicalResult readStandardMessage(std::string &Json)=0
JSONTransportInput(JSONStreamStyle Style=JSONStreamStyle::Standard)
Definition Transport.h:55
A transport class that performs the JSON-RPC communication with the LSP client.
Definition Transport.h:94
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:96
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:100
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:160
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:228
void notification(llvm::StringLiteral Method, ThisT *ThisPtr, void(ThisT::*Handler)(const Param &))
Definition Transport.h:195
OutgoingNotification< T > outgoingNotification(llvm::StringLiteral Method)
Create an OutgoingNotification object used for the given method.
Definition Transport.h:214
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:181
MessageHandler(JSONTransport &Transport)
Definition Transport.h:162
static llvm::Expected< T > parse(const llvm::json::Value &Raw, StringRef PayloadName, StringRef PayloadKind)
Definition Transport.h:171
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:139
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:149
@ 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:156
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:45
@ Standard
Encoding per the LSP specification, with mandatory Content-Length header.
Definition Transport.h:47
@ Delimited
Messages are delimited by a '// --—' line. Comment lines start with //.
Definition Transport.h:49
llvm::unique_function< void(const T &)> OutgoingNotification
An OutgoingNotification<T> is a function used for outgoing notifications send to the client.
Definition Transport.h:144
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)
static std::string debugString(T &&Op)
Definition Transport.h:31
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.