This commit is contained in:
2026-05-24 07:01:53 +02:00
parent 9b1acb8cc3
commit 831fa544fc
2 changed files with 59 additions and 39 deletions
+16 -25
View File
@@ -7,10 +7,9 @@ use std::fs;
use std::path::{Component, PathBuf}; use std::path::{Component, PathBuf};
use std::sync::Arc; use std::sync::Arc;
use serde_json::Value; use lsp_types::request::GotoDefinition;
use tokio::sync::Mutex; use tokio::sync::Mutex;
use tower_lsp::jsonrpc::Result; use tower_lsp::jsonrpc::Result;
use tower_lsp::lsp_types::request::Request;
use tower_lsp::lsp_types::*; use tower_lsp::lsp_types::*;
use tower_lsp::{Client, LanguageServer, LspService, Server}; use tower_lsp::{Client, LanguageServer, LspService, Server};
@@ -237,37 +236,29 @@ impl LanguageServer for Backend {
.log_message(MessageType::INFO, format!("Found at {position}")) .log_message(MessageType::INFO, format!("Found at {position}"))
.await; .await;
self.rust_analyzer let res = self
.rust_analyzer
.lock() .lock()
.await .await
.send( .request::<GotoDefinition>(lsp_types::GotoDefinitionParams {
request::GotoDefinition::METHOD, text_document_position_params: lsp_types::TextDocumentPositionParams {
lsp_types::GotoDefinitionParams { position: lsp_types::Position {
text_document_position_params: lsp_types::TextDocumentPositionParams { line: line as u32,
position: lsp_types::Position { character: character as u32,
line: line as u32, },
character: character as u32, text_document: lsp_types::TextDocumentIdentifier {
}, uri: Url::from_file_path(from_mist_to_rust(file_path))
text_document: lsp_types::TextDocumentIdentifier { .expect("failed to generate rs url"),
uri: Url::from_file_path(from_mist_to_rust(file_path))
.expect("failed to generate rs url"),
},
}, },
partial_result_params: lsp_types::PartialResultParams::default(),
work_done_progress_params: lsp_types::WorkDoneProgressParams::default(),
}, },
) partial_result_params: lsp_types::PartialResultParams::default(),
work_done_progress_params: lsp_types::WorkDoneProgressParams::default(),
})
.await .await
.expect("Failed to send to rust"); .expect("Failed to send to rust");
self.client self.client
.log_message( .log_message(MessageType::INFO, format!("{:?}", res))
MessageType::INFO,
format!(
"{:?}",
self.rust_analyzer.lock().await.read::<Value>().await
),
)
.await; .await;
Ok(None) Ok(None)
+43 -14
View File
@@ -1,4 +1,4 @@
use std::{path::PathBuf, process::Stdio}; use std::{collections::HashMap, path::PathBuf, process::Stdio, sync::Arc};
use lsp_types::{ use lsp_types::{
ClientCapabilities, InitializeParams, InitializedParams, Url, WorkspaceFolder, ClientCapabilities, InitializeParams, InitializedParams, Url, WorkspaceFolder,
@@ -6,15 +6,16 @@ use lsp_types::{
request::{self, Request}, request::{self, Request},
}; };
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use serde_json::json; use serde_json::{Value, json};
use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader}; use tokio::{
io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader},
sync::{Mutex, mpsc::Sender},
};
#[derive(Deserialize)] #[derive(Deserialize)]
pub struct JsonRpcResponse<T> { pub struct JsonRpcResponse<T> {
pub jsonrpc: String, pub jsonrpc: String,
// id can be a number or null, so we use serde_json::Value to be safe pub id: Option<usize>,
pub id: serde_json::Value,
// We only unpack the result if it exists
pub result: Option<T>, pub result: Option<T>,
pub error: Option<JsonRpcError>, pub error: Option<JsonRpcError>,
} }
@@ -29,7 +30,8 @@ pub struct JsonRpcError {
#[derive(Debug)] #[derive(Debug)]
pub struct RustAnalyzer { pub struct RustAnalyzer {
stdin: tokio::process::ChildStdin, stdin: tokio::process::ChildStdin,
stdout: BufReader<tokio::process::ChildStdout>, stdout: Arc<Mutex<BufReader<tokio::process::ChildStdout>>>,
pending: Arc<Mutex<HashMap<usize, Sender<String>>>>,
id: usize, id: usize,
} }
@@ -82,11 +84,12 @@ impl RustAnalyzer {
.spawn()?; .spawn()?;
let stdin = child.stdin.take().unwrap(); let stdin = child.stdin.take().unwrap();
let stdout = BufReader::new(child.stdout.take().unwrap()); let stdout = Arc::new(Mutex::new(BufReader::new(child.stdout.take().unwrap())));
Ok(Self { Ok(Self {
stdin, stdin,
stdout, stdout,
pending: Arc::new(Mutex::new(HashMap::new())),
id: 0, id: 0,
}) })
} }
@@ -95,11 +98,11 @@ impl RustAnalyzer {
&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>> {
self.send(R::METHOD, params).await?; let id = self.send(R::METHOD, params).await?;
self.read().await self.read(id).await
} }
pub async fn send<T: Serialize>(&mut self, method: &str, req: T) -> std::io::Result<()> { 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
@@ -114,14 +117,40 @@ impl RustAnalyzer {
"params": req, "params": req,
}), }),
) )
.await .await?;
Ok(id)
} }
pub async fn read<T>(&mut self) -> Result<T, Box<dyn std::error::Error>> pub async fn read<T>(&mut self, id: usize) -> Result<T, Box<dyn std::error::Error>>
where where
T: for<'de> serde::Deserialize<'de>, T: for<'de> serde::Deserialize<'de>,
{ {
let raw_string = read_lsp_message(&mut self.stdout).await?; 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 {
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
.get(&envelope.id.unwrap())
.unwrap()
.send(raw_string)
.await
.unwrap();
});
}
let raw_string = rx.recv().await.expect("Failed to receive");
let envelope: JsonRpcResponse<T> = serde_json::from_str(&raw_string)?; let envelope: JsonRpcResponse<T> = serde_json::from_str(&raw_string)?;