Working request

This commit is contained in:
2026-05-24 07:34:04 +02:00
parent 8b0f2ac1b9
commit f181806f65
2 changed files with 95 additions and 70 deletions
+22 -5
View File
@@ -235,6 +235,26 @@ impl LanguageServer for Backend {
.log_message(MessageType::INFO, format!("Found at {position}")) .log_message(MessageType::INFO, format!("Found at {position}"))
.await; .await;
let uri =
Url::from_file_path(from_mist_to_rust(file_path)).expect("failed to generate rs url");
self.rust_analyzer
.lock()
.await
.notify(
"textDocument/didOpen",
DidOpenTextDocumentParams {
text_document: TextDocumentItem {
uri: uri.clone(),
language_id: "rust".into(),
version: 1,
text: output,
},
},
)
.await
.expect("Failed to init req");
let res = self let res = self
.rust_analyzer .rust_analyzer
.lock() .lock()
@@ -245,10 +265,7 @@ impl LanguageServer for Backend {
line: line as u32, line: line as u32,
character: character as u32, character: character as u32,
}, },
text_document: lsp_types::TextDocumentIdentifier { text_document: lsp_types::TextDocumentIdentifier { uri },
uri: Url::from_file_path(from_mist_to_rust(file_path))
.expect("failed to generate rs url"),
},
}, },
partial_result_params: lsp_types::PartialResultParams::default(), partial_result_params: lsp_types::PartialResultParams::default(),
work_done_progress_params: lsp_types::WorkDoneProgressParams::default(), work_done_progress_params: lsp_types::WorkDoneProgressParams::default(),
@@ -257,7 +274,7 @@ impl LanguageServer for Backend {
.expect("Failed to send to rust"); .expect("Failed to send to rust");
self.client self.client
.log_message(MessageType::INFO, format!("{:?}", res)) .log_message(MessageType::INFO, format!("OUTPUT: {:?}", res))
.await; .await;
Ok(None) Ok(None)
+73 -65
View File
@@ -1,10 +1,10 @@
use std::{collections::HashMap, path::PathBuf, process::Stdio, sync::Arc}; use std::{collections::HashMap, path::PathBuf, process::Stdio, sync::Arc};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize, de::DeserializeOwned};
use serde_json::{Value, json}; use serde_json::{Value, json};
use tokio::{ use tokio::{
io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader}, io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader},
sync::{Mutex, mpsc::Sender}, sync::{Mutex, oneshot},
}; };
use tower_lsp::lsp_types::{ use tower_lsp::lsp_types::{
self, ClientCapabilities, InitializeParams, InitializedParams, Url, WorkspaceFolder, self, ClientCapabilities, InitializeParams, InitializedParams, Url, WorkspaceFolder,
@@ -27,11 +27,12 @@ pub struct JsonRpcError {
pub data: Option<serde_json::Value>, pub data: Option<serde_json::Value>,
} }
type PendingMap = Arc<Mutex<HashMap<usize, oneshot::Sender<Value>>>>;
#[derive(Debug)] #[derive(Debug)]
pub struct RustAnalyzer { pub struct RustAnalyzer {
stdin: tokio::process::ChildStdin, stdin: tokio::process::ChildStdin,
stdout: Arc<Mutex<BufReader<tokio::process::ChildStdout>>>, pending: PendingMap,
pending: Arc<Mutex<HashMap<usize, Sender<String>>>>,
id: usize, id: usize,
} }
@@ -84,12 +85,63 @@ impl RustAnalyzer {
.spawn()?; .spawn()?;
let stdin = child.stdin.take().unwrap(); let stdin = child.stdin.take().unwrap();
let stdout = Arc::new(Mutex::new(BufReader::new(child.stdout.take().unwrap()))); let stdout = child.stdout.take().unwrap();
let pending: PendingMap = Arc::new(Mutex::new(HashMap::new()));
let pending_clone = pending.clone();
tokio::spawn(async move {
let mut stdout = BufReader::new(stdout);
loop {
let raw = match read_lsp_message(&mut stdout).await {
Ok(v) => v,
Err(err) => {
eprintln!("LSP read error: {err}");
break;
}
};
let value: Value = match serde_json::from_str(&raw) {
Ok(v) => v,
Err(err) => {
eprintln!("Invalid JSON from rust-analyzer: {err}");
continue;
}
};
if value.get("method").is_some() {
continue;
}
let id = value.get("id").and_then(|v| v.as_u64()).map(|v| v as usize);
match id {
Some(id) => {
let tx = pending_clone.lock().await.remove(&id);
match tx {
Some(tx) => {
let _ = tx.send(value);
}
None => {
eprintln!("({:?}) {}", pending_clone, value);
eprintln!("Received response for unknown request id {id}");
}
}
}
None => {
// notification or server request
eprintln!("Received server notification/request: {raw}");
}
}
}
});
Ok(Self { Ok(Self {
stdin, stdin,
stdout, pending,
pending: Arc::new(Mutex::new(HashMap::new())),
id: 0, id: 0,
}) })
} }
@@ -97,81 +149,39 @@ impl RustAnalyzer {
pub async fn request<R: Request>( pub async fn request<R: Request>(
&mut self, &mut self,
params: R::Params, params: R::Params,
) -> Result<R::Result, Box<dyn std::error::Error>> { ) -> Result<R::Result, Box<dyn std::error::Error>>
let id = self.send(R::METHOD, params).await?; where
self.read(id).await R::Result: DeserializeOwned,
} {
pub async fn send<T: Serialize>(&mut self, method: &str, req: T) -> std::io::Result<usize> {
let id = { let id = {
self.id += 1; self.id += 1;
self.id self.id
}; };
let (tx, rx) = oneshot::channel();
self.pending.lock().await.insert(id, tx);
send_lsp_message( send_lsp_message(
&mut self.stdin, &mut self.stdin,
&json!({ &json!({
"jsonrpc": "2.0", "jsonrpc": "2.0",
"id": id, "id": id,
"method": method, "method": R::METHOD,
"params": req, "params": params,
}), }),
) )
.await?; .await?;
Ok(id) let value = rx.await?;
}
pub async fn read<T>(&mut self, id: usize) -> Result<T, Box<dyn std::error::Error>> let envelope: JsonRpcResponse<R::Result> = serde_json::from_value(value)?;
where
T: for<'de> serde::Deserialize<'de>,
{
let (tx, mut rx) = tokio::sync::mpsc::channel(16);
self.pending.lock().await.insert(id, tx);
if self.pending.lock().await.len() == 1 {
let stdout = self.stdout.clone();
let pending = self.pending.clone();
tokio::spawn(async move {
loop {
let raw_string = read_lsp_message(&mut *stdout.lock().await).await.unwrap();
let envelope: JsonRpcResponse<Value> =
serde_json::from_str(&raw_string).unwrap();
pending
.lock()
.await
.remove(&envelope.id.unwrap())
.unwrap()
.send(raw_string)
.await
.unwrap();
if pending.lock().await.len() == 0 {
break;
}
}
});
}
let raw_string = rx.recv().await.expect("Failed to receive");
let envelope: JsonRpcResponse<T> = serde_json::from_str(&raw_string)?;
if let Some(err) = envelope.error { if let Some(err) = envelope.error {
return Err(format!("LSP Error ({}): {}", err.code, err.message).into()); return Err(format!("LSP Error ({}): {}", err.code, err.message).into());
} }
envelope.result.ok_or_else(|| { envelope.result.ok_or_else(|| "missing result".into())
format!(
"LSP response missing both result and error fields. Raw: {}",
raw_string
)
.into()
})
} }
pub async fn notify<T: Serialize>(&mut self, method: &str, req: T) -> std::io::Result<()> { pub async fn notify<T: Serialize>(&mut self, method: &str, req: T) -> std::io::Result<()> {
@@ -213,9 +223,7 @@ impl RustAnalyzer {
..Default::default() ..Default::default()
}; };
let response = self.request::<request::Initialize>(init_params).await; self.request::<request::Initialize>(init_params).await?;
eprintln!("<- Received: initialize response {response:?}");
Ok(()) Ok(())
} }