1use std::collections::BTreeSet;
9use std::process::{Command, Stdio};
10use std::time;
11
12use serde_json::Value;
13
14use crate::error::Result;
15use crate::probe::Probe;
16use crate::{LspTransport, error};
17
18use super::parse::{self, Definition, Method};
19
20pub fn query_methods(
36 type_name: &str,
37 ra_path: &std::path::Path,
38 deps: Option<&str>,
39) -> Result<Vec<Method>> {
40 query_methods_inner(type_name, ra_path, deps)
41}
42
43#[allow(clippy::needless_collect)]
76#[must_use]
77pub fn query_methods_batch<'a>(
78 queries: &[(&'a str, Option<&'a str>)],
79 ra_path: &std::path::Path,
80) -> Vec<(&'a str, Result<Vec<Method>>)> {
81 std::thread::scope(|s| {
82 let handles: Vec<_> = queries
83 .iter()
84 .map(|&(type_name, deps)| {
85 s.spawn(move || (type_name, query_methods_inner(type_name, ra_path, deps)))
86 })
87 .collect(); handles
90 .into_iter()
91 .map(|h| h.join().expect("query thread should not panic"))
92 .collect()
93 })
94}
95
96fn query_methods_inner(
98 type_name: &str,
99 ra_path: &std::path::Path,
100 deps: Option<&str>,
101) -> Result<Vec<Method>> {
102 use crate::probe::cache::ra_version;
103 use crate::results_cache::{load_results, save_results};
104
105 let effective_deps = deps.map(str::to_owned).or_else(|| {
107 if type_name.contains("::")
108 && type_name
109 .split("::")
110 .next()
111 .and_then(|s| s.chars().next())
112 .is_some_and(|c| c.is_ascii_lowercase())
113 {
114 let crate_name = type_name.split("::").next().unwrap_or("");
115 Some(format!(r#"{crate_name} = "*""#))
116 } else {
117 None
118 }
119 });
120
121 let ra_version = ra_version(ra_path);
122 if let Some(methods) = load_results(type_name, effective_deps.as_deref(), &ra_version) {
123 return Ok(methods);
124 }
125
126 let probe = Probe::new_with_deps_cached(type_name, deps, ra_path)?;
127 let mut child = Command::new(ra_path)
128 .stdin(Stdio::piped())
129 .stdout(Stdio::piped())
130 .stderr(Stdio::null())
131 .spawn()?;
132 let mut lsp = LspTransport::new(&mut child)?;
133 let pid = std::process::id();
134
135 lsp.send(&LspTransport::initialize(pid, &probe.root_uri()))?;
136 lsp.recv_until(20, |msg| {
137 (msg["id"] == 1 && msg["result"].is_object()).then_some(())
138 })?;
139
140 lsp.send(&LspTransport::initialized())?;
141
142 lsp.send(&LspTransport::did_open(&probe.src_uri(), &probe.source()?))?;
143
144 let diag_msg = wait_for_indexing(&mut lsp, &probe.src_uri());
145 check_diagnostics_for_type_error(type_name, diag_msg.as_ref())?;
146
147 let completion_response = retry_lsp_request(
149 &mut lsp,
150 20,
151 type_name,
152 |req_id| LspTransport::completion(req_id, &probe.src_uri(), probe.dot_line, probe.dot_col),
153 |msg| {
154 let items = msg["result"]["items"]
155 .as_array()
156 .cloned()
157 .unwrap_or_default();
158 if std::env::var("RUST_METH_DEBUG").is_ok() {
159 for item in &items {
160 eprintln!(
161 "[debug] completion label={:?} kind={:?}",
162 item["label"], item["kind"]
163 );
164 }
165 }
166 !items.is_empty() && !is_blanket_fallback(&items)
167 },
168 )?;
169
170 lsp.send(&LspTransport::shutdown(13))?;
171 let _ = lsp.recv_until(10, |msg| (msg["id"] == 13).then_some(()));
172 lsp.send(&LspTransport::exit())?;
173 let _ = child.wait();
174
175 let methods = parse::parse_methods(&completion_response)?;
176 save_results(type_name, effective_deps.as_deref(), &ra_version, &methods);
177 Ok(methods)
178}
179
180fn check_diagnostics_for_type_error(type_name: &str, diag_msg: Option<&Value>) -> Result<()> {
182 let Some(msg) = diag_msg else { return Ok(()) };
183
184 let diagnostics = msg["params"]["diagnostics"]
185 .as_array()
186 .map_or(&[][..], Vec::as_slice);
187
188 for diag in diagnostics {
189 if diag["severity"].as_u64() != Some(1) {
191 continue;
192 }
193
194 if let Some(rendered) = diag["data"]["rendered"].as_str()
198 && (rendered.contains("configured out") || rendered.contains("gated behind"))
199 {
200 return Err(crate::error::RustMethError::FeatureGated {
201 type_name: type_name.to_string(),
202 message: rendered.to_string(),
203 });
204 }
205
206 let message = diag["message"].as_str().unwrap_or("");
207 if message.contains("cannot find type") || message.contains("not found in") {
209 return Err(crate::error::RustMethError::TypeNotFound {
210 type_name: type_name.to_string(),
211 message: message.to_string(),
212 });
213 }
214 }
215 Ok(())
216}
217
218pub fn query_definition(
228 type_name: &str,
229 method_name: &str,
230 ra_path: &std::path::Path,
231 deps: Option<&str>,
232) -> Result<Option<Definition>> {
233 let probe = Probe::for_definition_with_deps_cached(type_name, method_name, deps, ra_path)?;
234 let mut child = Command::new(ra_path)
235 .stdin(Stdio::piped())
236 .stdout(Stdio::piped())
237 .stderr(Stdio::null())
238 .spawn()?;
239 let mut lsp = LspTransport::new(&mut child)?;
240 let pid = std::process::id();
241
242 lsp.send(&LspTransport::initialize(pid, &probe.root_uri()))?;
244 lsp.recv_until(5000, |msg| {
245 (msg["id"] == 1 && msg["result"].is_object()).then_some(())
246 })?;
247
248 lsp.send(&LspTransport::initialized())?;
250 lsp.send(&LspTransport::did_open(&probe.src_uri(), &probe.source()?))?;
251
252 wait_for_indexing(&mut lsp, &probe.src_uri());
254
255 let response = retry_lsp_request(
258 &mut lsp,
259 60,
260 type_name,
261 |req_id| LspTransport::definition(req_id, &probe.src_uri(), probe.dot_line, probe.dot_col),
262 |msg| {
263 let is_error = msg["error"]["code"].as_i64().is_some();
264 let is_null = msg["result"].is_null();
265 !is_error && !is_null
266 },
267 )?;
268
269 lsp.send(&LspTransport::shutdown(13))?;
270 let _ = lsp.recv_until(10, |msg| (msg["id"] == 13).then_some(()));
271 lsp.send(&LspTransport::exit())?;
272 let _ = child.wait();
273
274 Ok(parse::parse_definition(&response))
275}
276
277fn wait_for_indexing(lsp: &mut LspTransport, probe_uri: &str) -> Option<Value> {
286 let debug = std::env::var("RUST_METH_DEBUG").is_ok();
287 let mut last_diag: Option<Value> = None;
290 let mut done = false;
291
292 let drain_start = time::Instant::now();
293 let _ = lsp.recv_until(20, |msg| {
294 if drain_start.elapsed() > time::Duration::from_mins(2) {
296 return Some(());
297 }
298 let method = msg["method"].as_str().unwrap_or("");
299 if debug {
300 eprintln!("[debug] {method}");
301 }
302 match method {
303 "$/progress" => {
304 if msg["params"]["value"]["kind"] == "end" {
305 done = true;
306 Some(())
307 } else {
308 None
309 }
310 }
311 "experimental/serverStatus" => {
312 if msg["params"]["quiescent"] == true {
313 done = true;
314 Some(())
315 } else {
316 None
317 }
318 }
319
320 "workspace/diagnostic/refresh" => {
321 done = true;
322 Some(())
323 }
324 "textDocument/publishDiagnostics" => {
325 if debug {
326 eprintln!(
327 "[debug] diagnostics: {}",
328 serde_json::to_string_pretty(&msg["params"]).unwrap_or_default()
329 );
330 }
331
332 let is_probe_file = msg["params"]["uri"].as_str() == Some(probe_uri);
333 let has_type_error = is_probe_file
334 && msg["params"]["diagnostics"]
335 .as_array()
336 .is_some_and(|diags| {
337 diags.iter().any(|d| {
338 d["severity"].as_u64() == Some(1)
339 && d["message"].as_str().is_some_and(|m| {
340 m.contains("cannot find type") || m.contains("not found in")
341 })
342 })
343 });
344 if has_type_error || (is_probe_file && last_diag.is_none()) {
345 last_diag = Some(msg.clone());
346 }
347 None
348 }
349 _ => None,
350 }
351 });
352 let _ = done;
353
354 last_diag
355}
356
357fn retry_lsp_request<F, G>(
358 lsp: &mut LspTransport,
359 max_attempts: u64,
360 type_name: &str,
361 mut make_request: F,
362 mut is_success: G,
363) -> Result<Value>
364where
365 F: FnMut(u64) -> Value, G: FnMut(&Value) -> bool, {
368 let start = time::Instant::now();
369 for attempt in 1..=max_attempts {
370 let req_id = attempt + 2;
371 lsp.send(&make_request(req_id))?;
372 let msg = lsp.recv_until(50, |msg| (msg["id"] == req_id).then(|| msg.clone()))?;
373 if is_success(&msg) {
374 return Ok(msg);
375 }
376 if attempt < max_attempts {
377 std::thread::sleep(time::Duration::from_millis(500));
378 }
379 }
380 Err(error::RustMethError::Timeout {
381 type_name: type_name.to_string(),
382 waited_secs: start.elapsed().as_secs(),
383 })
384}
385
386const BLANKET_FALLBACK_METHODS: &[&str] = &[
391 "clamp",
392 "clone",
393 "clone_from",
394 "clone_into",
395 "cmp",
396 "eq",
397 "ge",
398 "gt",
399 "into",
400 "le",
401 "lt",
402 "max",
403 "min",
404 "ne",
405 "not",
406 "partial_cmp",
407 "to_owned",
408 "to_string",
409 "try_into",
410];
411
412fn is_blanket_fallback(items: &[Value]) -> bool {
413 let names: BTreeSet<&str> = items
414 .iter()
415 .filter_map(|i| i["label"].as_str())
416 .map(|label| label.split('(').next().unwrap_or(label).trim())
417 .collect();
418 let fallback: BTreeSet<&str> = BLANKET_FALLBACK_METHODS.iter().copied().collect();
419 !names.is_empty() && names == fallback
420}