@@ -1,19 +1,44 @@
2− collections::HashMap,
1+use std::collections::HashMap;
3− process::{ChildStderr, ChildStdin, ChildStdout, Command, Stdio},
3+use jsonrpc_core as jsonrpc;
6+use serde::{Deserialize, Serialize};
9+use smol::channel::{Receiver, Sender};
6use smol::io::{BufReader, BufWriter};
10use smol::io::{BufReader, BufWriter};
7use smol::prelude::*;
11use smol::prelude::*;
8−use smol::Unblock;
12+use smol::process::{Child, ChildStderr, ChildStdin, ChildStdout, Command, Stdio};
15+use futures_util::{select, FutureExt};
17+/// A type representing all possible values sent from the server to the client.
18+#[derive(Debug, PartialEq, Clone, Deserialize, Serialize)]
19+#[serde(deny_unknown_fields)]
22+ /// A regular JSON-RPC request output (single response).
23+ Output(jsonrpc::Output),
25+ Notification(jsonrpc::Notification),
26+ /// A JSON-RPC request
32+ stderr: BufReader<ChildStderr>,
33+ outgoing: Sender<Payload>,
35+ pub request_counter: u64,
10−struct Client {
37+ capabilities: Option<lsp::ServerCapabilities>,
12− reader: BufReader<Unblock<ChildStdout>>,
15impl Client {
40impl Client {
16− fn start(cmd: &str, args: &[String]) -> Self {
41+ pub fn start(ex: &Executor, cmd: &str, args: &[String]) -> Self {
17 let mut process = Command::new(cmd)
42 let mut process = Command::new(cmd)
18 .args(args)
43 .args(args)
19 .stdin(Stdio::piped())
44 .stdin(Stdio::piped())
@@ -21,51 +46,332 @@ impl Client {
21 .stderr(Stdio::piped())
46 .stderr(Stdio::piped())
23 .expect("Failed to start language server");
48 .expect("Failed to start language server");
24− // TODO: impl drop that kills the process
49+ // smol makes sure the process is reaped on drop, but using kill_on_drop(true) maybe?
26 // TODO: do we need bufreader/writer here? or do we use async wrappers on unblock?
51 // TODO: do we need bufreader/writer here? or do we use async wrappers on unblock?
27− let writer = BufWriter::new(Unblock::new(
28− process.stdin.take().expect("Failed to open stdin"),
52+ let writer = BufWriter::new(process.stdin.take().expect("Failed to open stdin"));
30− let reader = BufReader::new(Unblock::new(
31− process.stdout.take().expect("Failed to open stdout"),
53+ let reader = BufReader::new(process.stdout.take().expect("Failed to open stdout"));
33− let stderr = BufReader::new(Unblock::new(
34− process.stderr.take().expect("Failed to open stderr"),
54+ let stderr = BufReader::new(process.stderr.take().expect("Failed to open stderr"));
56+ let (incoming, outgoing) = Transport::start(ex, reader, writer);
69+ fn next_request_id(&mut self) -> jsonrpc::Id {
70+ let id = jsonrpc::Id::Num(self.request_counter);
71+ self.request_counter += 1;
75+ fn to_params(value: Value) -> anyhow::Result<jsonrpc::Params> {
78+ let params = match value {
79+ Value::Null => Params::None,
80+ Value::Bool(_) | Value::Number(_) | Value::String(_) => Params::Array(vec![value]),
81+ Value::Array(vec) => Params::Array(vec),
82+ Value::Object(map) => Params::Map(map),
88+ pub async fn request<R: lsp::request::Request>(
91+ ) -> anyhow::Result<R::Result>
93+ R::Params: serde::Serialize,
94+ R::Result: core::fmt::Debug, // TODO: temporary
96+ let params = serde_json::to_value(params)?;
98+ let request = jsonrpc::MethodCall {
99+ jsonrpc: Some(jsonrpc::Version::V2),
100+ id: self.next_request_id(),
101+ method: R::METHOD.to_string(),
102+ params: Self::to_params(params)?,
105+ let (tx, rx) = smol::channel::bounded::<anyhow::Result<Value>>(1);
108+ .send(Payload::Request {
114+ let response = rx.recv().await??;
116+ let response = serde_json::from_value(response)?;
118+ // TODO: we should pass request to a sender thread via a channel
119+ // so it can't be interleaved
121+ // TODO: responses can be out of order, we need to register a single shot response channel
126+ pub async fn notify<R: lsp::notification::Notification>(
129+ ) -> anyhow::Result<()>
131+ R::Params: serde::Serialize,
133+ let params = serde_json::to_value(params)?;
135+ let notification = jsonrpc::Notification {
136+ jsonrpc: Some(jsonrpc::Version::V2),
137+ method: R::METHOD.to_string(),
138+ params: Self::to_params(params)?,
142+ .send(Payload::Notification(notification))
148+ // -------------------------------------------------------------------------------------------
150+ // -------------------------------------------------------------------------------------------
152+ pub async fn initialize(&mut self) -> anyhow::Result<()> {
153+ // TODO: delay any requests that are triggered prior to initialize
155+ #[allow(deprecated)]
156+ let params = lsp::InitializeParams {
157+ process_id: Some(u64::from(std::process::id())),
159+ // root_uri: Some(lsp_types::Url::parse("file://localhost/")?),
160+ root_uri: None, // set to project root in the future
161+ initialization_options: None,
162+ capabilities: lsp::ClientCapabilities::default(),
164+ workspace_folders: None,
168+ let response = self.request::<lsp::request::Initialize>(params).await?;
169+ self.capabilities = Some(response.capabilities);
171+ // next up, notify<initialized>
172+ self.notify::<lsp::notification::Initialized>(lsp::InitializedParams {})
178+ pub async fn shutdown(&mut self) -> anyhow::Result<()> {
179+ self.request::<lsp::request::Shutdown>(()).await
182+ pub async fn exit(&mut self) -> anyhow::Result<()> {
183+ self.notify::<lsp::notification::Exit>(()).await
186+ // -------------------------------------------------------------------------------------------
188+ // -------------------------------------------------------------------------------------------
190+ pub async fn text_document_did_open(&mut self) -> anyhow::Result<()> {
191+ self.notify::<lsp::notification::DidOpenTextDocument>(lsp::DidOpenTextDocumentParams {
192+ text_document: lsp::TextDocumentItem {
193+ uri: lsp::Url::parse(".")?,
194+ language_id: "rust".to_string(),
196+ text: "".to_string(),
37− Client { reader }
202+ pub async fn text_document_did_change(&mut self) -> anyhow::Result<()> {
206+ // will_save / will_save_wait_until
208+ pub async fn text_document_did_save(&mut self) -> anyhow::Result<()> {
40− async fn receiver(&mut self) -> Result<(), std::io::Error> {
212+ pub async fn text_document_did_close(&mut self) -> anyhow::Result<()> {
41− let mut headers: HashMap<String, String> = HashMap::default();
213+ unimplemented!()
219+ chan: Sender<anyhow::Result<Value>>,
220+ value: jsonrpc::MethodCall,
222+ Notification(jsonrpc::Notification),
226+ incoming: Sender<Message>,
227+ outgoing: Receiver<Payload>,
229+ pending_requests: HashMap<jsonrpc::Id, Sender<anyhow::Result<Value>>>,
230+ headers: HashMap<String, String>,
232+ writer: BufWriter<ChildStdin>,
233+ reader: BufReader<ChildStdout>,
239+ reader: BufReader<ChildStdout>,
240+ writer: BufWriter<ChildStdin>,
241+ ) -> (Receiver<Message>, Sender<Payload>) {
242+ let (incoming, rx) = smol::channel::unbounded();
243+ let (tx, outgoing) = smol::channel::unbounded();
245+ let transport = Self {
250+ pending_requests: Default::default(),
251+ headers: Default::default(),
254+ ex.spawn(transport.duplex()).detach();
260+ reader: &mut (impl AsyncBufRead + Unpin),
261+ headers: &mut HashMap<String, String>,
262+ ) -> Result<Message, std::io::Error> {
45− let mut header = String::new();
265+ let mut header = String::new();
46− // detect pipe closed if 0
266+ // detect pipe closed if 0
47− self.reader.read_line(&mut header).await?;
267+ reader.read_line(&mut header).await?;
48− let header = header.trim();
268+ let header = header.trim();
50− if header.is_empty() {
54− let parts: Vec<&str> = header.split(": ").collect();
270+ if header.is_empty() {
55− if parts.len() != 2 {
271+ break;
56− // return Err(Error::new(ErrorKind::Other, "Failed to parse header"));
59− headers.insert(parts[0].to_string(), parts[1].to_string());
274+ let parts: Vec<&str> = header.split(": ").collect();
275+ if parts.len() != 2 {
276+ // return Err(Error::new(ErrorKind::Other, "Failed to parse header"));
279+ headers.insert(parts[0].to_string(), parts[1].to_string());
62− // find content-length
282+ // find content-length
283+ let content_length = headers.get("Content-Length").unwrap().parse().unwrap();
285+ let mut content = vec![0; content_length];
286+ reader.read_exact(&mut content).await?;
287+ let msg = String::from_utf8(content).unwrap();
291+ // try parsing as output (server response) or call (server request)
292+ let output: serde_json::Result<Message> = serde_json::from_str(&msg);
64− // read data
294+ Ok(output?)
65− // decode via serde_json decoding into jsonrpc_core Output
295+ }
297+ pub async fn send_payload(&mut self, payload: Payload) -> anyhow::Result<()> {
299+ Payload::Request { chan, value } => {
300+ self.pending_requests.insert(value.id.clone(), chan);
302+ let json = serde_json::to_string(&value)?;
303+ self.send(json).await
305+ Payload::Notification(value) => {
306+ let json = serde_json::to_string(&value)?;
307+ self.send(json).await
312+ pub async fn send(&mut self, request: String) -> anyhow::Result<()> {
313+ println!("-> {}", request);
317+ .write_all(format!("Content-Length: {}\r\n\r\n", request.len()).as_bytes())
321+ self.writer.write_all(request.as_bytes()).await?;
323+ self.writer.flush().await?;
328+ pub async fn recv_response(&mut self, output: jsonrpc::Output) -> anyhow::Result<()> {
330+ jsonrpc::Output::Success(jsonrpc::Success { id, result, .. }) => {
331+ println!("<- {}", result);
336+ .expect("pending_request with id not found!");
337+ tx.send(Ok(result)).await?;
339+ jsonrpc::Output::Failure(_) => panic!("recv fail"),
340+ msg => unimplemented!("{:?}", msg),
345+ pub async fn duplex(mut self) {
349+ msg = self.outgoing.next().fuse() => {
353+ let msg = msg.unwrap();
355+ self.send_payload(msg).await.unwrap();
358+ msg = Self::recv(&mut self.reader, &mut self.headers).fuse() => {
362+ let msg = msg.unwrap();
365+ Message::Output(output) => self.recv_response(output).await.unwrap(),
366+ Message::Notification(_) => {
369+ Message::Call(_) => {