use std::process::{Command, Stdio};
use serde_json::Value;
use crate::LspTransport;
use crate::error::Result;
use crate::probe::Probe;
use super::parse::{self, Definition, Method};
pub fn query_methods(
type_name: &str,
ra_path: &std::path::Path,
deps: Option<&str>,
) -> Result<Vec<Method>> {
let probe = Probe::new_with_deps(type_name, deps)?;
let mut child = Command::new(ra_path)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::null())
.spawn()?;
let mut lsp = LspTransport::new(&mut child)?;
let pid = std::process::id();
lsp.send(&LspTransport::initialize(pid, &probe.root_uri()))?;
lsp.recv_until(20, |msg| {
(msg["id"] == 1 && msg["result"].is_object()).then_some(())
})?;
lsp.send(&LspTransport::initialized())?;
lsp.send(&LspTransport::did_open(&probe.src_uri(), &probe.source()?))?;
wait_for_indexing(&mut lsp)?;
let completion_response = retry_lsp_request(
&mut lsp,
10,
|req_id| LspTransport::completion(req_id, &probe.src_uri(), probe.dot_line, probe.dot_col),
|msg| {
msg["result"]["items"]
.as_array()
.is_some_and(|a| !a.is_empty())
},
)?;
lsp.send(&LspTransport::shutdown(13))?;
let _ = lsp.recv_until(10, |msg| (msg["id"] == 13).then_some(()));
lsp.send(&LspTransport::exit())?;
let _ = child.wait();
parse::parse_methods(&completion_response)
}
pub fn query_definition(
type_name: &str,
method_name: &str,
ra_path: &std::path::Path,
deps: Option<&str>,
) -> Result<Option<Definition>> {
let probe = Probe::for_definition_with_deps(type_name, method_name, deps)?;
let mut child = Command::new(ra_path)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::null())
.spawn()?;
let mut lsp = LspTransport::new(&mut child)?;
let pid = std::process::id();
lsp.send(&LspTransport::initialize(pid, &probe.root_uri()))?;
lsp.recv_until(20, |msg| {
(msg["id"] == 1 && msg["result"].is_object()).then_some(())
})?;
lsp.send(&LspTransport::initialized())?;
lsp.send(&LspTransport::did_open(&probe.src_uri(), &probe.source()?))?;
wait_for_indexing(&mut lsp)?;
let response = retry_lsp_request(
&mut lsp,
10,
|req_id| LspTransport::definition(req_id, &probe.src_uri(), probe.dot_line, probe.dot_col),
|msg| {
let is_error = msg["error"]["code"].as_i64().is_some();
let is_null = msg["result"].is_null();
!is_error && !is_null
},
)?;
lsp.send(&LspTransport::shutdown(13))?;
let _ = lsp.recv_until(10, |msg| (msg["id"] == 13).then_some(()));
lsp.send(&LspTransport::exit())?;
let _ = child.wait();
Ok(parse::parse_definition(&response))
}
fn wait_for_indexing(lsp: &mut LspTransport) -> Result<()> {
let debug = std::env::var("RUST_METH_DEBUG").is_ok();
let start = std::time::Instant::now();
let timeout = std::time::Duration::from_secs(10); lsp.recv_until(200, |msg| {
if start.elapsed() > timeout {
return Some(()); }
let method = msg["method"].as_str().unwrap_or("");
if debug {
eprintln!("[debug] {method}");
}
match method {
"$/progress" => {
if msg["params"]["value"]["kind"] == "end" {
Some(())
} else {
None
}
}
"experimental/serverStatus" => {
if msg["params"]["quiescent"] == true {
Some(())
} else {
None
}
}
"textDocument/publishDiagnostics" | "workspace/diagnostic/refresh" => Some(()),
_ => None,
}
})
.or(Ok(()))
}
fn retry_lsp_request<F, G>(
lsp: &mut LspTransport,
max_attempts: u64,
mut make_request: F,
mut is_success: G,
) -> Result<Value>
where
F: FnMut(u64) -> Value, G: FnMut(&Value) -> bool, {
let mut result = Value::Null;
for attempt in 1..=max_attempts {
let req_id = attempt + 2;
lsp.send(&make_request(req_id))?;
let msg = lsp.recv_until(50, |msg| (msg["id"] == req_id).then(|| msg.clone()))?;
if is_success(&msg) {
result = msg;
break;
}
if attempt < max_attempts {
if std::env::var("RUST_METH_DEBUG").is_ok() {
eprintln!("(attempt {attempt}: not ready, retrying…)");
}
std::thread::sleep(std::time::Duration::from_millis(500));
}
}
Ok(result)
}