1 //! A language server scaffold, exposing a synchronous crossbeam-channel based API.
2 //! This crate handles protocol handshaking and parsing messages, while you
3 //! control the message dispatch loop yourself.
5 //! Run with `RUST_LOG=lsp_server=debug` to see all the messages.
14 net::{TcpListener, TcpStream, ToSocketAddrs},
17 use crossbeam_channel::{Receiver, Sender};
20 error::{ExtractError, ProtocolError},
21 msg::{ErrorCode, Message, Notification, Request, RequestId, Response, ResponseError},
22 req_queue::{Incoming, Outgoing, ReqQueue},
26 /// Connection is just a pair of channels of LSP messages.
27 pub struct Connection {
28 pub sender: Sender<Message>,
29 pub receiver: Receiver<Message>,
33 /// Create connection over standard in/standard out.
35 /// Use this to create a real language server.
36 pub fn stdio() -> (Connection, IoThreads) {
37 let (sender, receiver, io_threads) = stdio::stdio_transport();
38 (Connection { sender, receiver }, io_threads)
41 /// Open a connection over tcp.
42 /// This call blocks until a connection is established.
44 /// Use this to create a real language server.
45 pub fn connect<A: ToSocketAddrs>(addr: A) -> io::Result<(Connection, IoThreads)> {
46 let stream = TcpStream::connect(addr)?;
47 let (sender, receiver, io_threads) = socket::socket_transport(stream);
48 Ok((Connection { sender, receiver }, io_threads))
51 /// Listen for a connection over tcp.
52 /// This call blocks until a connection is established.
54 /// Use this to create a real language server.
55 pub fn listen<A: ToSocketAddrs>(addr: A) -> io::Result<(Connection, IoThreads)> {
56 let listener = TcpListener::bind(addr)?;
57 let (stream, _) = listener.accept()?;
58 let (sender, receiver, io_threads) = socket::socket_transport(stream);
59 Ok((Connection { sender, receiver }, io_threads))
62 /// Creates a pair of connected connections.
64 /// Use this for testing.
65 pub fn memory() -> (Connection, Connection) {
66 let (s1, r1) = crossbeam_channel::unbounded();
67 let (s2, r2) = crossbeam_channel::unbounded();
68 (Connection { sender: s1, receiver: r2 }, Connection { sender: s2, receiver: r1 })
71 /// Starts the initialization process by waiting for an initialize
72 /// request from the client. Use this for more advanced customization than
73 /// `initialize` can provide.
75 /// Returns the request id and serialized `InitializeParams` from the client.
80 /// use std::error::Error;
81 /// use lsp_types::{ClientCapabilities, InitializeParams, ServerCapabilities};
83 /// use lsp_server::{Connection, Message, Request, RequestId, Response};
85 /// fn main() -> Result<(), Box<dyn Error + Sync + Send>> {
86 /// // Create the transport. Includes the stdio (stdin and stdout) versions but this could
87 /// // also be implemented to use sockets or HTTP.
88 /// let (connection, io_threads) = Connection::stdio();
91 /// let (id, params) = connection.initialize_start()?;
93 /// let init_params: InitializeParams = serde_json::from_value(params).unwrap();
94 /// let client_capabilities: ClientCapabilities = init_params.capabilities;
95 /// let server_capabilities = ServerCapabilities::default();
97 /// let initialize_data = serde_json::json!({
98 /// "capabilities": server_capabilities,
100 /// "name": "lsp-server-test",
105 /// connection.initialize_finish(id, initialize_data)?;
107 /// // ... Run main loop ...
112 pub fn initialize_start(&self) -> Result<(RequestId, serde_json::Value), ProtocolError> {
114 match self.receiver.recv() {
115 Ok(Message::Request(req)) if req.is_initialize() => {
116 return Ok((req.id, req.params))
118 // Respond to non-initialize requests with ServerNotInitialized
119 Ok(Message::Request(req)) => {
120 let resp = Response::new_err(
122 ErrorCode::ServerNotInitialized as i32,
123 format!("expected initialize request, got {:?}", req),
125 self.sender.send(resp.into()).unwrap();
128 return Err(ProtocolError(format!(
129 "expected initialize request, got {:?}",
134 return Err(ProtocolError(format!(
135 "expected initialize request, got error: {}",
143 /// Finishes the initialization process by sending an `InitializeResult` to the client
144 pub fn initialize_finish(
146 initialize_id: RequestId,
147 initialize_result: serde_json::Value,
148 ) -> Result<(), ProtocolError> {
149 let resp = Response::new_ok(initialize_id, initialize_result);
150 self.sender.send(resp.into()).unwrap();
151 match &self.receiver.recv() {
152 Ok(Message::Notification(n)) if n.is_initialized() => (),
154 return Err(ProtocolError(format!(
155 "expected Message::Notification, got: {:?}",
160 return Err(ProtocolError(format!(
161 "expected initialized notification, got error: {}",
169 /// Initialize the connection. Sends the server capabilities
170 /// to the client and returns the serialized client capabilities
171 /// on success. If more fine-grained initialization is required use
172 /// `initialize_start`/`initialize_finish`.
177 /// use std::error::Error;
178 /// use lsp_types::ServerCapabilities;
180 /// use lsp_server::{Connection, Message, Request, RequestId, Response};
182 /// fn main() -> Result<(), Box<dyn Error + Sync + Send>> {
183 /// // Create the transport. Includes the stdio (stdin and stdout) versions but this could
184 /// // also be implemented to use sockets or HTTP.
185 /// let (connection, io_threads) = Connection::stdio();
187 /// // Run the server
188 /// let server_capabilities = serde_json::to_value(&ServerCapabilities::default()).unwrap();
189 /// let initialization_params = connection.initialize(server_capabilities)?;
191 /// // ... Run main loop ...
198 server_capabilities: serde_json::Value,
199 ) -> Result<serde_json::Value, ProtocolError> {
200 let (id, params) = self.initialize_start()?;
202 let initialize_data = serde_json::json!({
203 "capabilities": server_capabilities,
206 self.initialize_finish(id, initialize_data)?;
211 /// If `req` is `Shutdown`, respond to it and return `true`, otherwise return `false`
212 pub fn handle_shutdown(&self, req: &Request) -> Result<bool, ProtocolError> {
213 if !req.is_shutdown() {
216 let resp = Response::new_ok(req.id.clone(), ());
217 let _ = self.sender.send(resp.into());
218 match &self.receiver.recv_timeout(std::time::Duration::from_secs(30)) {
219 Ok(Message::Notification(n)) if n.is_exit() => (),
221 return Err(ProtocolError(format!("unexpected message during shutdown: {:?}", msg)))
224 return Err(ProtocolError(format!("unexpected error during shutdown: {}", e)))