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 let probe = Probe::new_with_deps(type_name, deps)?;
103 let mut child = Command::new(ra_path)
104 .stdin(Stdio::piped())
105 .stdout(Stdio::piped())
106 .stderr(Stdio::null())
107 .spawn()?;
108 let mut lsp = LspTransport::new(&mut child)?;
109 let pid = std::process::id();
110 lsp.send(&LspTransport::initialize(pid, &probe.root_uri()))?;
112 lsp.recv_until(20, |msg| {
113 (msg["id"] == 1 && msg["result"].is_object()).then_some(())
114 })?;
115 lsp.send(&LspTransport::initialized())?;
117 lsp.send(&LspTransport::did_open(&probe.src_uri(), &probe.source()?))?;
119 let diag_msg = wait_for_indexing(&mut lsp, &probe.src_uri());
121 check_diagnostics_for_type_error(type_name, diag_msg.as_ref())?;
122 let completion_response = retry_lsp_request(
125 &mut lsp,
126 20,
127 type_name,
128 |req_id| LspTransport::completion(req_id, &probe.src_uri(), probe.dot_line, probe.dot_col),
129 |msg| {
130 let items = msg["result"]["items"]
131 .as_array()
132 .cloned()
133 .unwrap_or_default();
134 if std::env::var("RUST_METH_DEBUG").is_ok() {
135 for item in &items {
136 eprintln!(
137 "[debug] completion label={:?} kind={:?}",
138 item["label"], item["kind"]
139 );
140 }
141 }
142 !items.is_empty() && !is_blanket_fallback(&items)
143 },
144 )?;
145 lsp.send(&LspTransport::shutdown(13))?;
147 let _ = lsp.recv_until(10, |msg| (msg["id"] == 13).then_some(()));
148 lsp.send(&LspTransport::exit())?;
149 let _ = child.wait();
150 parse::parse_methods(&completion_response)
152}
153
154fn check_diagnostics_for_type_error(type_name: &str, diag_msg: Option<&Value>) -> Result<()> {
156 let Some(msg) = diag_msg else { return Ok(()) };
157
158 let diagnostics = msg["params"]["diagnostics"]
159 .as_array()
160 .map_or(&[][..], Vec::as_slice);
161
162 for diag in diagnostics {
163 if diag["severity"].as_u64() != Some(1) {
165 continue;
166 }
167
168 if let Some(rendered) = diag["data"]["rendered"].as_str()
172 && (rendered.contains("configured out") || rendered.contains("gated behind"))
173 {
174 return Err(crate::error::RustMethError::FeatureGated {
175 type_name: type_name.to_string(),
176 message: rendered.to_string(),
177 });
178 }
179
180 let message = diag["message"].as_str().unwrap_or("");
181 if message.contains("cannot find type") || message.contains("not found in") {
183 return Err(crate::error::RustMethError::TypeNotFound {
184 type_name: type_name.to_string(),
185 message: message.to_string(),
186 });
187 }
188 }
189 Ok(())
190}
191
192pub fn query_definition(
202 type_name: &str,
203 method_name: &str,
204 ra_path: &std::path::Path,
205 deps: Option<&str>,
206) -> Result<Option<Definition>> {
207 let probe = Probe::for_definition_with_deps(type_name, method_name, deps)?;
208 let mut child = Command::new(ra_path)
209 .stdin(Stdio::piped())
210 .stdout(Stdio::piped())
211 .stderr(Stdio::null())
212 .spawn()?;
213 let mut lsp = LspTransport::new(&mut child)?;
214 let pid = std::process::id();
215
216 lsp.send(&LspTransport::initialize(pid, &probe.root_uri()))?;
218 lsp.recv_until(5000, |msg| {
219 (msg["id"] == 1 && msg["result"].is_object()).then_some(())
220 })?;
221
222 lsp.send(&LspTransport::initialized())?;
224 lsp.send(&LspTransport::did_open(&probe.src_uri(), &probe.source()?))?;
225
226 wait_for_indexing(&mut lsp, &probe.src_uri());
228
229 let response = retry_lsp_request(
232 &mut lsp,
233 60,
234 type_name,
235 |req_id| LspTransport::definition(req_id, &probe.src_uri(), probe.dot_line, probe.dot_col),
236 |msg| {
237 let is_error = msg["error"]["code"].as_i64().is_some();
238 let is_null = msg["result"].is_null();
239 !is_error && !is_null
240 },
241 )?;
242
243 lsp.send(&LspTransport::shutdown(13))?;
244 let _ = lsp.recv_until(10, |msg| (msg["id"] == 13).then_some(()));
245 lsp.send(&LspTransport::exit())?;
246 let _ = child.wait();
247
248 Ok(parse::parse_definition(&response))
249}
250
251fn wait_for_indexing(lsp: &mut LspTransport, probe_uri: &str) -> Option<Value> {
260 let debug = std::env::var("RUST_METH_DEBUG").is_ok();
261 let mut last_diag: Option<Value> = None;
264 let mut done = false;
265
266 let drain_start = time::Instant::now();
267 let _ = lsp.recv_until(20, |msg| {
268 if drain_start.elapsed() > time::Duration::from_mins(2) {
270 return Some(());
271 }
272 let method = msg["method"].as_str().unwrap_or("");
273 if debug {
274 eprintln!("[debug] {method}");
275 }
276 match method {
277 "$/progress" => {
278 if msg["params"]["value"]["kind"] == "end" {
279 done = true;
280 Some(())
281 } else {
282 None
283 }
284 }
285 "experimental/serverStatus" => {
286 if msg["params"]["quiescent"] == true {
287 done = true;
288 Some(())
289 } else {
290 None
291 }
292 }
293
294 "workspace/diagnostic/refresh" => {
295 done = true;
296 Some(())
297 }
298 "textDocument/publishDiagnostics" => {
299 if debug {
300 eprintln!(
301 "[debug] diagnostics: {}",
302 serde_json::to_string_pretty(&msg["params"]).unwrap_or_default()
303 );
304 }
305
306 let is_probe_file = msg["params"]["uri"].as_str() == Some(probe_uri);
307 let has_type_error = is_probe_file
308 && msg["params"]["diagnostics"]
309 .as_array()
310 .is_some_and(|diags| {
311 diags.iter().any(|d| {
312 d["severity"].as_u64() == Some(1)
313 && d["message"].as_str().is_some_and(|m| {
314 m.contains("cannot find type") || m.contains("not found in")
315 })
316 })
317 });
318 if has_type_error || (is_probe_file && last_diag.is_none()) {
319 last_diag = Some(msg.clone());
320 }
321 None
322 }
323 _ => None,
324 }
325 });
326 let _ = done;
327
328 last_diag
329}
330
331fn retry_lsp_request<F, G>(
332 lsp: &mut LspTransport,
333 max_attempts: u64,
334 type_name: &str,
335 mut make_request: F,
336 mut is_success: G,
337) -> Result<Value>
338where
339 F: FnMut(u64) -> Value, G: FnMut(&Value) -> bool, {
342 let start = time::Instant::now();
343 for attempt in 1..=max_attempts {
344 let req_id = attempt + 2;
345 lsp.send(&make_request(req_id))?;
346 let msg = lsp.recv_until(50, |msg| (msg["id"] == req_id).then(|| msg.clone()))?;
347 if is_success(&msg) {
348 return Ok(msg);
349 }
350 if attempt < max_attempts {
351 std::thread::sleep(time::Duration::from_millis(500));
352 }
353 }
354 Err(error::RustMethError::Timeout {
355 type_name: type_name.to_string(),
356 waited_secs: start.elapsed().as_secs(),
357 })
358}
359
360const BLANKET_FALLBACK_METHODS: &[&str] = &[
365 "clamp",
366 "clone",
367 "clone_from",
368 "clone_into",
369 "cmp",
370 "eq",
371 "ge",
372 "gt",
373 "into",
374 "le",
375 "lt",
376 "max",
377 "min",
378 "ne",
379 "not",
380 "partial_cmp",
381 "to_owned",
382 "to_string",
383 "try_into",
384];
385
386fn is_blanket_fallback(items: &[Value]) -> bool {
387 let names: BTreeSet<&str> = items
388 .iter()
389 .filter_map(|i| i["label"].as_str())
390 .map(|label| label.split('(').next().unwrap_or(label).trim())
391 .collect();
392 let fallback: BTreeSet<&str> = BLANKET_FALLBACK_METHODS.iter().copied().collect();
393 !names.is_empty() && names == fallback
394}