use std::collections::BTreeSet;
use std::process::{Command, Stdio};
use std::time;
use serde_json::Value;
use crate::error::Result;
use crate::probe::Probe;
use crate::{LspTransport, error};
use super::parse::{self, Definition, Method};
pub fn query_methods(
type_name: &str,
ra_path: &std::path::Path,
deps: Option<&str>,
) -> Result<Vec<Method>> {
query_methods_inner(type_name, ra_path, deps)
}
#[allow(clippy::needless_collect)]
#[must_use]
pub fn query_methods_batch<'a>(
queries: &[(&'a str, Option<&'a str>)],
ra_path: &std::path::Path,
) -> Vec<(&'a str, Result<Vec<Method>>)> {
std::thread::scope(|s| {
let handles: Vec<_> = queries
.iter()
.map(|&(type_name, deps)| {
s.spawn(move || (type_name, query_methods_inner(type_name, ra_path, deps)))
})
.collect();
handles
.into_iter()
.map(|h| h.join().expect("query thread should not panic"))
.collect()
})
}
fn query_methods_inner(
type_name: &str,
ra_path: &std::path::Path,
deps: Option<&str>,
) -> Result<Vec<Method>> {
use crate::probe::cache::ra_version;
use crate::results_cache::{load_results, save_results};
let effective_deps = deps.map(str::to_owned).or_else(|| {
if type_name.contains("::")
&& type_name
.split("::")
.next()
.and_then(|s| s.chars().next())
.is_some_and(|c| c.is_ascii_lowercase())
{
let crate_name = type_name.split("::").next().unwrap_or("");
Some(format!(r#"{crate_name} = "*""#))
} else {
None
}
});
let ra_version = ra_version(ra_path);
if let Some(methods) = load_results(type_name, effective_deps.as_deref(), &ra_version) {
return Ok(methods);
}
let probe = Probe::new_with_deps_cached(type_name, deps, ra_path)?;
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()?))?;
let diag_msg = wait_for_indexing(&mut lsp, &probe.src_uri());
check_diagnostics_for_type_error(type_name, diag_msg.as_ref())?;
let completion_response = retry_lsp_request(
&mut lsp,
20,
type_name,
|req_id| LspTransport::completion(req_id, &probe.src_uri(), probe.dot_line, probe.dot_col),
|msg| {
let items = msg["result"]["items"]
.as_array()
.cloned()
.unwrap_or_default();
if std::env::var("RUST_METH_DEBUG").is_ok() {
for item in &items {
eprintln!(
"[debug] completion label={:?} kind={:?}",
item["label"], item["kind"]
);
}
}
!items.is_empty() && !is_blanket_fallback(&items)
},
)?;
lsp.send(&LspTransport::shutdown(13))?;
let _ = lsp.recv_until(10, |msg| (msg["id"] == 13).then_some(()));
lsp.send(&LspTransport::exit())?;
let _ = child.wait();
let methods = parse::parse_methods(&completion_response)?;
save_results(type_name, effective_deps.as_deref(), &ra_version, &methods);
Ok(methods)
}
fn check_diagnostics_for_type_error(type_name: &str, diag_msg: Option<&Value>) -> Result<()> {
let Some(msg) = diag_msg else { return Ok(()) };
let diagnostics = msg["params"]["diagnostics"]
.as_array()
.map_or(&[][..], Vec::as_slice);
for diag in diagnostics {
if diag["severity"].as_u64() != Some(1) {
continue;
}
if let Some(rendered) = diag["data"]["rendered"].as_str()
&& (rendered.contains("configured out") || rendered.contains("gated behind"))
{
return Err(crate::error::RustMethError::FeatureGated {
type_name: type_name.to_string(),
message: rendered.to_string(),
});
}
let message = diag["message"].as_str().unwrap_or("");
if message.contains("cannot find type") || message.contains("not found in") {
return Err(crate::error::RustMethError::TypeNotFound {
type_name: type_name.to_string(),
message: message.to_string(),
});
}
}
Ok(())
}
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_cached(type_name, method_name, deps, ra_path)?;
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(5000, |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, &probe.src_uri());
let response = retry_lsp_request(
&mut lsp,
60,
type_name,
|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, probe_uri: &str) -> Option<Value> {
let debug = std::env::var("RUST_METH_DEBUG").is_ok();
let mut last_diag: Option<Value> = None;
let mut done = false;
let drain_start = time::Instant::now();
let _ = lsp.recv_until(20, |msg| {
if drain_start.elapsed() > time::Duration::from_mins(2) {
return Some(());
}
let method = msg["method"].as_str().unwrap_or("");
if debug {
eprintln!("[debug] {method}");
}
match method {
"$/progress" => {
if msg["params"]["value"]["kind"] == "end" {
done = true;
Some(())
} else {
None
}
}
"experimental/serverStatus" => {
if msg["params"]["quiescent"] == true {
done = true;
Some(())
} else {
None
}
}
"workspace/diagnostic/refresh" => {
done = true;
Some(())
}
"textDocument/publishDiagnostics" => {
if debug {
eprintln!(
"[debug] diagnostics: {}",
serde_json::to_string_pretty(&msg["params"]).unwrap_or_default()
);
}
let is_probe_file = msg["params"]["uri"].as_str() == Some(probe_uri);
let has_type_error = is_probe_file
&& msg["params"]["diagnostics"]
.as_array()
.is_some_and(|diags| {
diags.iter().any(|d| {
d["severity"].as_u64() == Some(1)
&& d["message"].as_str().is_some_and(|m| {
m.contains("cannot find type") || m.contains("not found in")
})
})
});
if has_type_error || (is_probe_file && last_diag.is_none()) {
last_diag = Some(msg.clone());
}
None
}
_ => None,
}
});
let _ = done;
last_diag
}
fn retry_lsp_request<F, G>(
lsp: &mut LspTransport,
max_attempts: u64,
type_name: &str,
mut make_request: F,
mut is_success: G,
) -> Result<Value>
where
F: FnMut(u64) -> Value, G: FnMut(&Value) -> bool, {
let start = time::Instant::now();
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) {
return Ok(msg);
}
if attempt < max_attempts {
std::thread::sleep(time::Duration::from_millis(500));
}
}
Err(error::RustMethError::Timeout {
type_name: type_name.to_string(),
waited_secs: start.elapsed().as_secs(),
})
}
const BLANKET_FALLBACK_METHODS: &[&str] = &[
"clamp",
"clone",
"clone_from",
"clone_into",
"cmp",
"eq",
"ge",
"gt",
"into",
"le",
"lt",
"max",
"min",
"ne",
"not",
"partial_cmp",
"to_owned",
"to_string",
"try_into",
];
fn is_blanket_fallback(items: &[Value]) -> bool {
let names: BTreeSet<&str> = items
.iter()
.filter_map(|i| i["label"].as_str())
.map(|label| label.split('(').next().unwrap_or(label).trim())
.collect();
let fallback: BTreeSet<&str> = BLANKET_FALLBACK_METHODS.iter().copied().collect();
!names.is_empty() && names == fallback
}