@@ -1,19 +1,44 @@
1−use std::{
2− collections::HashMap,
3− process::{ChildStderr, ChildStdin, ChildStdout, Command, Stdio},
4−};
1+use std::collections::HashMap;
52
3+use jsonrpc_core as jsonrpc;
4+use lsp_types as lsp;
5+
6+use serde::{Deserialize, Serialize};
7+use serde_json::Value;
8+
9+use smol::channel::{Receiver, Sender};
610use smol::io::{BufReader, BufWriter};
711use smol::prelude::*;
8−use smol::Unblock;
12+use smol::process::{Child, ChildStderr, ChildStdin, ChildStdout, Command, Stdio};
13+use smol::Executor;
14+
15+use futures_util::{select, FutureExt};
16+
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)]
20+#[serde(untagged)]
21+enum Message {
22+ /// A regular JSON-RPC request output (single response).
23+ Output(jsonrpc::Output),
24+ /// A notification.
25+ Notification(jsonrpc::Notification),
26+ /// A JSON-RPC request
27+ Call(jsonrpc::Call),
28+}
29+
30+pub struct Client {
31+ process: Child,
32+ stderr: BufReader<ChildStderr>,
33+ outgoing: Sender<Payload>,
34+
35+ pub request_counter: u64,
936
10−struct Client {
11− // process: Command,
12− reader: BufReader<Unblock<ChildStdout>>,
37+ capabilities: Option<lsp::ServerCapabilities>,
1338}
1439
1540impl Client {
16− fn start(cmd: &str, args: &[String]) -> Self {
41+ pub fn start(ex: &Executor, cmd: &str, args: &[String]) -> Self {
1742 let mut process = Command::new(cmd)
1843 .args(args)
1944 .stdin(Stdio::piped())
@@ -21,51 +46,332 @@ impl Client {
2146 .stderr(Stdio::piped())
2247 .spawn()
2348 .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?
2550
2651 // 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"),
29− ));
30− let reader = BufReader::new(Unblock::new(
31− process.stdout.take().expect("Failed to open stdout"),
32− ));
33− let stderr = BufReader::new(Unblock::new(
34− process.stderr.take().expect("Failed to open stderr"),
35− ));
52+ let writer = BufWriter::new(process.stdin.take().expect("Failed to open stdin"));
53+ let reader = BufReader::new(process.stdout.take().expect("Failed to open stdout"));
54+ let stderr = BufReader::new(process.stderr.take().expect("Failed to open stderr"));
55+
56+ let (incoming, outgoing) = Transport::start(ex, reader, writer);
57+
58+ Client {
59+ process,
60+ stderr,
61+ outgoing,
62+
63+ request_counter: 0,
64+
65+ capabilities: None,
66+ }
67+ }
68+
69+ fn next_request_id(&mut self) -> jsonrpc::Id {
70+ let id = jsonrpc::Id::Num(self.request_counter);
71+ self.request_counter += 1;
72+ id
73+ }
74+
75+ fn to_params(value: Value) -> anyhow::Result<jsonrpc::Params> {
76+ use jsonrpc::Params;
77+
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),
83+ };
84+
85+ Ok(params)
86+ }
87+
88+ pub async fn request<R: lsp::request::Request>(
89+ &mut self,
90+ params: R::Params,
91+ ) -> anyhow::Result<R::Result>
92+ where
93+ R::Params: serde::Serialize,
94+ R::Result: core::fmt::Debug, // TODO: temporary
95+ {
96+ let params = serde_json::to_value(params)?;
97+
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)?,
103+ };
104+
105+ let (tx, rx) = smol::channel::bounded::<anyhow::Result<Value>>(1);
106+
107+ self.outgoing
108+ .send(Payload::Request {
109+ chan: tx,
110+ value: request,
111+ })
112+ .await?;
113+
114+ let response = rx.recv().await??;
115+
116+ let response = serde_json::from_value(response)?;
117+
118+ // TODO: we should pass request to a sender thread via a channel
119+ // so it can't be interleaved
120+
121+ // TODO: responses can be out of order, we need to register a single shot response channel
122+
123+ Ok(response)
124+ }
125+
126+ pub async fn notify<R: lsp::notification::Notification>(
127+ &mut self,
128+ params: R::Params,
129+ ) -> anyhow::Result<()>
130+ where
131+ R::Params: serde::Serialize,
132+ {
133+ let params = serde_json::to_value(params)?;
134+
135+ let notification = jsonrpc::Notification {
136+ jsonrpc: Some(jsonrpc::Version::V2),
137+ method: R::METHOD.to_string(),
138+ params: Self::to_params(params)?,
139+ };
140+
141+ self.outgoing
142+ .send(Payload::Notification(notification))
143+ .await?;
144+
145+ Ok(())
146+ }
147+
148+ // -------------------------------------------------------------------------------------------
149+ // General messages
150+ // -------------------------------------------------------------------------------------------
151+
152+ pub async fn initialize(&mut self) -> anyhow::Result<()> {
153+ // TODO: delay any requests that are triggered prior to initialize
154+
155+ #[allow(deprecated)]
156+ let params = lsp::InitializeParams {
157+ process_id: Some(u64::from(std::process::id())),
158+ root_path: None,
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(),
163+ trace: None,
164+ workspace_folders: None,
165+ client_info: None,
166+ };
167+
168+ let response = self.request::<lsp::request::Initialize>(params).await?;
169+ self.capabilities = Some(response.capabilities);
170+
171+ // next up, notify<initialized>
172+ self.notify::<lsp::notification::Initialized>(lsp::InitializedParams {})
173+ .await?;
174+
175+ Ok(())
176+ }
177+
178+ pub async fn shutdown(&mut self) -> anyhow::Result<()> {
179+ self.request::<lsp::request::Shutdown>(()).await
180+ }
181+
182+ pub async fn exit(&mut self) -> anyhow::Result<()> {
183+ self.notify::<lsp::notification::Exit>(()).await
184+ }
185+
186+ // -------------------------------------------------------------------------------------------
187+ // Text document
188+ // -------------------------------------------------------------------------------------------
189+
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(),
195+ version: 0,
196+ text: "".to_string(),
197+ },
198+ })
199+ .await
200+ }
36201
37− Client { reader }
202+ pub async fn text_document_did_change(&mut self) -> anyhow::Result<()> {
203+ unimplemented!()
38204 }
39205
40− async fn receiver(&mut self) -> Result<(), std::io::Error> {
41− let mut headers: HashMap<String, String> = HashMap::default();
206+ // will_save / will_save_wait_until
207+
208+ pub async fn text_document_did_save(&mut self) -> anyhow::Result<()> {
209+ unimplemented!()
210+ }
211+
212+ pub async fn text_document_did_close(&mut self) -> anyhow::Result<()> {
213+ unimplemented!()
214+ }
215+}
216+
217+enum Payload {
218+ Request {
219+ chan: Sender<anyhow::Result<Value>>,
220+ value: jsonrpc::MethodCall,
221+ },
222+ Notification(jsonrpc::Notification),
223+}
224+
225+struct Transport {
226+ incoming: Sender<Message>,
227+ outgoing: Receiver<Payload>,
228+
229+ pending_requests: HashMap<jsonrpc::Id, Sender<anyhow::Result<Value>>>,
230+ headers: HashMap<String, String>,
231+
232+ writer: BufWriter<ChildStdin>,
233+ reader: BufReader<ChildStdout>,
234+}
235+
236+impl Transport {
237+ pub fn start(
238+ ex: &Executor,
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();
244+
245+ let transport = Self {
246+ reader,
247+ writer,
248+ incoming,
249+ outgoing,
250+ pending_requests: Default::default(),
251+ headers: Default::default(),
252+ };
253+
254+ ex.spawn(transport.duplex()).detach();
255+
256+ (rx, tx)
257+ }
258+
259+ async fn recv(
260+ reader: &mut (impl AsyncBufRead + Unpin),
261+ headers: &mut HashMap<String, String>,
262+ ) -> Result<Message, std::io::Error> {
263+ // read headers
42264 loop {
43− // read headers
44− loop {
45− let mut header = String::new();
46− // detect pipe closed if 0
47− self.reader.read_line(&mut header).await?;
48− let header = header.trim();
49−
50− if header.is_empty() {
51− break;
52− }
265+ let mut header = String::new();
266+ // detect pipe closed if 0
267+ reader.read_line(&mut header).await?;
268+ let header = header.trim();
53269
54− let parts: Vec<&str> = header.split(": ").collect();
55− if parts.len() != 2 {
56− // return Err(Error::new(ErrorKind::Other, "Failed to parse header"));
57− panic!()
58− }
59− headers.insert(parts[0].to_string(), parts[1].to_string());
270+ if header.is_empty() {
271+ break;
60272 }
61273
62− // find content-length
274+ let parts: Vec<&str> = header.split(": ").collect();
275+ if parts.len() != 2 {
276+ // return Err(Error::new(ErrorKind::Other, "Failed to parse header"));
277+ panic!()
278+ }
279+ headers.insert(parts[0].to_string(), parts[1].to_string());
280+ }
281+
282+ // find content-length
283+ let content_length = headers.get("Content-Length").unwrap().parse().unwrap();
284+
285+ let mut content = vec![0; content_length];
286+ reader.read_exact(&mut content).await?;
287+ let msg = String::from_utf8(content).unwrap();
288+
289+ // read data
290+
291+ // try parsing as output (server response) or call (server request)
292+ let output: serde_json::Result<Message> = serde_json::from_str(&msg);
63293
64− // read data
65− // decode via serde_json decoding into jsonrpc_core Output
66− break;
294+ Ok(output?)
295+ }
296+
297+ pub async fn send_payload(&mut self, payload: Payload) -> anyhow::Result<()> {
298+ match payload {
299+ Payload::Request { chan, value } => {
300+ self.pending_requests.insert(value.id.clone(), chan);
301+
302+ let json = serde_json::to_string(&value)?;
303+ self.send(json).await
304+ }
305+ Payload::Notification(value) => {
306+ let json = serde_json::to_string(&value)?;
307+ self.send(json).await
308+ }
67309 }
310+ }
311+
312+ pub async fn send(&mut self, request: String) -> anyhow::Result<()> {
313+ println!("-> {}", request);
314+
315+ // send the headers
316+ self.writer
317+ .write_all(format!("Content-Length: {}\r\n\r\n", request.len()).as_bytes())
318+ .await?;
319+
320+ // send the body
321+ self.writer.write_all(request.as_bytes()).await?;
322+
323+ self.writer.flush().await?;
68324
69325 Ok(())
70326 }
327+
328+ pub async fn recv_response(&mut self, output: jsonrpc::Output) -> anyhow::Result<()> {
329+ match output {
330+ jsonrpc::Output::Success(jsonrpc::Success { id, result, .. }) => {
331+ println!("<- {}", result);
332+
333+ let tx = self
334+ .pending_requests
335+ .remove(&id)
336+ .expect("pending_request with id not found!");
337+ tx.send(Ok(result)).await?;
338+ }
339+ jsonrpc::Output::Failure(_) => panic!("recv fail"),
340+ msg => unimplemented!("{:?}", msg),
341+ }
342+ Ok(())
343+ }
344+
345+ pub async fn duplex(mut self) {
346+ loop {
347+ select! {
348+ // client -> server
349+ msg = self.outgoing.next().fuse() => {
350+ if msg.is_none() {
351+ break;
352+ }
353+ let msg = msg.unwrap();
354+
355+ self.send_payload(msg).await.unwrap();
356+ }
357+ // server <- client
358+ msg = Self::recv(&mut self.reader, &mut self.headers).fuse() => {
359+ if msg.is_err() {
360+ break;
361+ }
362+ let msg = msg.unwrap();
363+
364+ match msg {
365+ Message::Output(output) => self.recv_response(output).await.unwrap(),
366+ Message::Notification(_) => {
367+ // dispatch
368+ }
369+ Message::Call(_) => {
370+ // dispatch
371+ }
372+ };
373+ }
374+ }
375+ }
376+ }
71377}