1use std::path::PathBuf;
11use std::process::{Command, Stdio};
12use std::sync::OnceLock;
13
14use crate::error::{Result, RustMethError};
15use serde_json::Value;
16
17use crate::LspTransport;
18use crate::probe::Probe;
19
20const KIND_METHOD: u64 = 2;
22
23static RA_PATH_CACHE: OnceLock<PathBuf> = OnceLock::new();
24
25#[derive(serde::Serialize)]
27pub struct Method {
28 pub name: String,
30 pub detail: Option<String>,
32 pub documentation: Option<String>,
34}
35
36fn rustup_rust_analyzer() -> Option<PathBuf> {
37 let out = Command::new("rustup")
38 .args(["which", "rust-analyzer"])
39 .output()
40 .ok()?;
41
42 if !out.status.success() {
43 return None;
44 }
45
46 let path = String::from_utf8_lossy(&out.stdout).trim().to_string();
47 (!path.is_empty()).then(|| path.into())
48}
49
50pub fn find_rust_analyzer() -> Result<PathBuf> {
62 if let Some(path) = RA_PATH_CACHE.get() {
63 return Ok(path.clone());
64 }
65 let path = if let Ok(path) = which("rust-analyzer") {
66 path
67 } else if let Some(path) = rustup_rust_analyzer() {
68 path
69 } else {
70 return Err(RustMethError::RustAnalyzerNotFound);
71 };
72 Ok(RA_PATH_CACHE.get_or_init(|| path).clone())
73}
74
75#[cfg(unix)]
76fn which(name: &str) -> Result<std::path::PathBuf> {
77 let out = Command::new("which").arg(name).output()?;
78 if !out.status.success() {
79 return Err(RustMethError::RustAnalyzerNotFound);
80 }
81 let s = String::from_utf8_lossy(&out.stdout).trim().to_string();
82 Ok(s.into())
83}
84
85pub fn query_methods(
103 type_name: &str,
104 ra_path: &std::path::Path,
105 deps: Option<&str>,
106) -> Result<Vec<Method>> {
107 let probe = Probe::new_with_deps(type_name, deps)?;
108 let mut child = Command::new(ra_path)
109 .stdin(Stdio::piped())
110 .stdout(Stdio::piped())
111 .stderr(Stdio::null())
112 .spawn()?;
113
114 let mut lsp = LspTransport::new(&mut child);
115 let pid = std::process::id();
116
117 lsp.send(&LspTransport::initialize(pid, &probe.root_uri()))?;
119 lsp.recv_until(20, |msg| {
120 (msg["id"] == 1 && msg["result"].is_object()).then_some(())
121 })?;
122
123 lsp.send(&LspTransport::initialized())?;
125
126 lsp.send(&LspTransport::did_open(&probe.src_uri(), &probe.source()?))?;
128
129 wait_for_indexing(&mut lsp)?;
131
132 let completion_response = {
135 let mut response = Value::Null;
136 for attempt in 1..=10u64 {
137 let req_id = attempt + 2;
138 lsp.send(&LspTransport::completion(
139 req_id,
140 &probe.src_uri(),
141 probe.dot_line,
142 probe.dot_col,
143 ))?;
144
145 let msg = lsp.recv_until(50, |msg| (msg["id"] == req_id).then(|| msg.clone()))?;
146
147 let has_items = msg["result"]["items"]
148 .as_array()
149 .is_some_and(|a| !a.is_empty());
150
151 if has_items {
152 response = msg;
153 break;
154 }
155
156 if attempt < 10 {
166 std::thread::sleep(std::time::Duration::from_millis(500));
167 }
168 }
169 response
170 };
171
172 lsp.send(&LspTransport::shutdown(13))?;
174 let _ = lsp.recv_until(10, |msg| (msg["id"] == 13).then_some(()));
175 lsp.send(&LspTransport::exit())?;
176 let _ = child.wait();
177
178 parse_methods(&completion_response)
180}
181
182fn wait_for_indexing(lsp: &mut LspTransport) -> Result<()> {
191 let debug = std::env::var("RUST_METH_DEBUG").is_ok();
192 let start = std::time::Instant::now();
193 let timeout = std::time::Duration::from_secs(10); lsp.recv_until(200, |msg| {
196 if start.elapsed() > timeout {
198 return Some(()); }
200
201 let method = msg["method"].as_str().unwrap_or("");
202 if debug {
203 eprintln!("[debug] {method}");
204 }
205
206 match method {
207 "$/progress" => {
208 if msg["params"]["value"]["kind"] == "end" {
209 Some(())
210 } else {
211 None
212 }
213 }
214 "experimental/serverStatus" => {
215 if msg["params"]["quiescent"] == true {
216 Some(())
217 } else {
218 None
219 }
220 }
221 "textDocument/publishDiagnostics" | "workspace/diagnostic/refresh" => Some(()),
223 _ => None,
224 }
225 })
226 .or(Ok(()))
227}
228
229pub fn parse_methods(response: &Value) -> Result<Vec<Method>> {
236 let result = &response["result"];
237 let items: &[Value] = match result {
238 Value::Array(arr) => arr.as_slice(),
239 obj if obj["items"].is_array() => obj["items"].as_array().map_or(&[], Vec::as_slice),
240 _ => return Err(RustMethError::UnexpectedResponseShape(response.to_string())),
241 };
242
243 let mut methods: Vec<Method> = Vec::with_capacity(items.len() / 2);
244
245 for item in items {
246 if item["kind"].as_u64() != Some(KIND_METHOD) {
247 continue;
248 }
249 let name = item["label"]
250 .as_str()
251 .unwrap_or("")
252 .split('(')
253 .next()
254 .unwrap_or("")
255 .trim()
256 .to_string();
257 if name.is_empty() {
258 continue;
259 }
260 methods.push(Method {
261 name,
262 detail: item["detail"].as_str().map(str::to_string),
263 documentation: item["documentation"]["value"].as_str().map(str::to_string),
264 });
265 }
266
267 methods.sort_unstable_by(|a, b| a.name.cmp(&b.name));
268 methods.dedup_by(|a, b| a.name == b.name);
269 Ok(methods)
270}
271
272#[must_use]
274pub struct Definition {
275 pub path: String,
277 pub full_path: String,
279 pub line: u32,
281}
282
283pub fn query_definition(
293 type_name: &str,
294 method_name: &str,
295 ra_path: &std::path::Path,
296 deps: Option<&str>,
297) -> anyhow::Result<Option<Definition>> {
298 let probe = Probe::for_definition_with_deps(type_name, method_name, deps)?;
299
300 let mut child = Command::new(ra_path)
301 .stdin(Stdio::piped())
302 .stdout(Stdio::piped())
303 .stderr(Stdio::null())
304 .spawn()?;
305
306 let mut lsp = LspTransport::new(&mut child);
307 let pid = std::process::id();
308
309 lsp.send(&LspTransport::initialize(pid, &probe.root_uri()))?;
311 lsp.recv_until(20, |msg| {
312 (msg["id"] == 1 && msg["result"].is_object()).then_some(())
313 })?;
314
315 lsp.send(&LspTransport::initialized())?;
317 lsp.send(&LspTransport::did_open(&probe.src_uri(), &probe.source()?))?;
318
319 wait_for_indexing(&mut lsp)?;
321
322 let response = {
325 let mut result = Value::Null;
326 for attempt in 1..=10u64 {
327 let req_id = attempt + 2;
328 lsp.send(&LspTransport::definition(
329 req_id,
330 &probe.src_uri(),
331 probe.dot_line,
332 probe.dot_col,
333 ))?;
334
335 let msg = lsp.recv_until(50, |msg| (msg["id"] == req_id).then(|| msg.clone()))?;
336
337 let is_error = msg["error"]["code"].as_i64().is_some();
339 let is_null = msg["result"].is_null();
340
341 if !is_error && !is_null {
342 result = msg;
343 break;
344 }
345
346 if attempt < 10 {
347 if std::env::var("RUST_METH_DEBUG").is_ok() {
348 eprintln!("(attempt {attempt}: not ready, retrying…)");
349 }
350 std::thread::sleep(std::time::Duration::from_millis(500));
351 }
352 }
353 result
354 };
355
356 lsp.send(&LspTransport::shutdown(13))?;
357 let _ = lsp.recv_until(10, |msg| (msg["id"] == 13).then_some(()));
358 lsp.send(&LspTransport::exit())?;
359 let _ = child.wait();
360
361 Ok(parse_definition(&response))
362}
363
364#[must_use]
370pub fn parse_definition(response: &Value) -> Option<Definition> {
371 let result = &response["result"];
372 let location: &Value = match result {
373 Value::Array(arr) if !arr.is_empty() => &arr[0],
374 single if single.is_object() => single,
375 _ => return None,
376 };
377
378 let uri = location["uri"].as_str().unwrap_or("");
379 if uri.is_empty() {
380 return None;
381 }
382
383 let line = u32::try_from(location["range"]["start"]["line"].as_u64().unwrap_or(0))
384 .expect("LSP definition line should fit in u32");
385
386 let full_path_str = uri.strip_prefix("file://").unwrap_or(uri);
387
388 let path = full_path_str
389 .find("/library/")
390 .or_else(|| full_path_str.find("/src/"))
391 .map_or_else(
392 || full_path_str.to_string(),
393 |idx| full_path_str[idx + 1..].to_string(),
394 );
395
396 let full_path = full_path_str.to_string();
397
398 Some(Definition {
399 path,
400 full_path,
401 line,
402 })
403}
404
405#[cfg(test)]
406#[allow(clippy::unwrap_used)]
407mod tests {
408 use super::*;
409 use serde_json::json;
410
411 #[test]
414 fn parse_methods_empty_items_returns_empty_vec() {
415 let resp = json!({ "result": { "items": [], "isIncomplete": false } });
416 let methods = parse_methods(&resp).unwrap();
417 assert!(methods.is_empty());
418 }
419
420 #[test]
421 fn parse_methods_filters_non_method_kinds() {
422 let resp = json!({
424 "result": {
425 "items": [
426 { "kind": 2, "label": "len(…)" },
427 { "kind": 5, "label": "capacity" },
428 { "kind": 9, "label": "Clone" }
429 ]
430 }
431 });
432 let methods = parse_methods(&resp).unwrap();
433 assert_eq!(methods.len(), 1);
434 assert_eq!(methods[0].name, "len");
435 }
436
437 #[test]
438 fn parse_methods_deduplicates_same_name() {
439 let resp = json!({
440 "result": {
441 "items": [
442 { "kind": 2, "label": "clone(…)" },
443 { "kind": 2, "label": "clone(…)" }
444 ]
445 }
446 });
447 let methods = parse_methods(&resp).unwrap();
448 assert_eq!(methods.len(), 1);
449 assert_eq!(methods[0].name, "clone");
450 }
451
452 #[test]
453 fn parse_methods_returns_sorted_names() {
454 let resp = json!({
455 "result": {
456 "items": [
457 { "kind": 2, "label": "zip(…)" },
458 { "kind": 2, "label": "map(…)" },
459 { "kind": 2, "label": "filter(…)" }
460 ]
461 }
462 });
463 let methods = parse_methods(&resp).unwrap();
464 let names: Vec<&str> = methods.iter().map(|m| m.name.as_str()).collect();
465 assert_eq!(names, ["filter", "map", "zip"]);
466 }
467
468 #[test]
469 fn parse_methods_preserves_detail_and_documentation() {
470 let resp = json!({
471 "result": {
472 "items": [{
473 "kind": 2,
474 "label": "len(…)",
475 "detail": "pub fn len(&self) -> usize",
476 "documentation": { "value": "Returns the number of elements." }
477 }]
478 }
479 });
480 let methods = parse_methods(&resp).unwrap();
481 assert_eq!(methods.len(), 1);
482 assert_eq!(
483 methods[0].detail.as_deref(),
484 Some("pub fn len(&self) -> usize")
485 );
486 assert_eq!(
487 methods[0].documentation.as_deref(),
488 Some("Returns the number of elements.")
489 );
490 }
491
492 #[test]
493 fn parse_methods_no_detail_or_docs_is_none() {
494 let resp = json!({
495 "result": { "items": [{ "kind": 2, "label": "len(…)" }] }
496 });
497 let methods = parse_methods(&resp).unwrap();
498 assert!(methods[0].detail.is_none());
499 assert!(methods[0].documentation.is_none());
500 }
501
502 #[test]
503 fn parse_methods_array_result_form() {
504 let resp = json!({
506 "result": [
507 { "kind": 2, "label": "len(…)" },
508 { "kind": 2, "label": "is_empty(…)" }
509 ]
510 });
511 let methods = parse_methods(&resp).unwrap();
512 assert_eq!(methods.len(), 2);
513 }
514
515 #[test]
516 fn parse_methods_skips_empty_label() {
517 let resp = json!({
518 "result": {
519 "items": [
520 { "kind": 2, "label": "" },
521 { "kind": 2, "label": "len(…)" }
522 ]
523 }
524 });
525 let methods = parse_methods(&resp).unwrap();
526 assert_eq!(methods.len(), 1);
527 assert_eq!(methods[0].name, "len");
528 }
529
530 #[test]
531 fn parse_methods_unexpected_shape_returns_error() {
532 let resp = json!({ "result": "this_is_not_valid" });
533 assert!(parse_methods(&resp).is_err());
534 }
535
536 #[test]
540 fn parse_methods_third_party_label_stripped_at_paren() {
541 let resp = json!({
542 "result": {
543 "items": [
544 { "kind": 2, "label": "as_str(…)", "detail": "pub fn as_str(&self) -> &str" },
545 { "kind": 2, "label": "as_object(…)" }
546 ]
547 }
548 });
549 let methods = parse_methods(&resp).unwrap();
550 let names: Vec<&str> = methods.iter().map(|m| m.name.as_str()).collect();
551 assert!(names.contains(&"as_str"));
552 assert!(names.contains(&"as_object"));
553 }
554
555 #[test]
558 fn parse_definition_array_form() {
559 let resp = json!({
560 "result": [{
561 "uri": "file:///home/user/.rustup/toolchains/stable/library/core/src/num/mod.rs",
562 "range": {
563 "start": { "line": 42, "character": 0 },
564 "end": { "line": 42, "character": 10 }
565 }
566 }]
567 });
568 let def = parse_definition(&resp).unwrap();
569 assert_eq!(def.line, 42);
570 assert!(def.path.starts_with("library/"));
571 assert!(!def.full_path.starts_with("file://"));
572 }
573
574 #[test]
575 fn parse_definition_object_form() {
576 let resp = json!({
577 "result": {
578 "uri": "file:///home/user/.rustup/toolchains/stable/library/core/src/str/mod.rs",
579 "range": {
580 "start": { "line": 99, "character": 4 },
581 "end": { "line": 99, "character": 20 }
582 }
583 }
584 });
585 let def = parse_definition(&resp).unwrap();
586 assert_eq!(def.line, 99);
587 assert!(def.path.starts_with("library/"));
588 }
589
590 #[test]
591 fn parse_definition_null_result_returns_none() {
592 let resp = json!({ "result": null });
593 assert!(parse_definition(&resp).is_none());
594 }
595
596 #[test]
597 fn parse_definition_empty_array_returns_none() {
598 let resp = json!({ "result": [] });
599 assert!(parse_definition(&resp).is_none());
600 }
601
602 #[test]
603 fn parse_definition_empty_uri_returns_none() {
604 let resp = json!({
605 "result": [{
606 "uri": "",
607 "range": { "start": { "line": 0, "character": 0 }, "end": { "line": 0, "character": 0 } }
608 }]
609 });
610 assert!(parse_definition(&resp).is_none());
611 }
612
613 #[test]
614 fn parse_definition_strips_library_prefix_from_path() {
615 let resp = json!({
616 "result": [{
617 "uri": "file:///home/user/.rustup/toolchains/stable/library/core/src/num/mod.rs",
618 "range": { "start": { "line": 0, "character": 0 }, "end": { "line": 0, "character": 0 } }
619 }]
620 });
621 let def = parse_definition(&resp).unwrap();
622 assert!(def.path.starts_with("library/"));
624 assert!(!def.path.starts_with('/'));
625 }
626
627 #[test]
628 fn parse_definition_src_path_fallback() {
629 let resp = json!({
631 "result": [{
632 "uri": "file:///home/user/myproject/src/main.rs",
633 "range": { "start": { "line": 5, "character": 0 }, "end": { "line": 5, "character": 0 } }
634 }]
635 });
636 let def = parse_definition(&resp).unwrap();
637 assert!(def.path.starts_with("src/"));
638 assert_eq!(def.line, 5);
639 }
640
641 #[test]
642 fn parse_definition_full_path_does_not_start_with_file_scheme() {
643 let resp = json!({
644 "result": [{
645 "uri": "file:///home/user/project/src/lib.rs",
646 "range": { "start": { "line": 1, "character": 0 }, "end": { "line": 1, "character": 0 } }
647 }]
648 });
649 let def = parse_definition(&resp).unwrap();
650 assert!(!def.full_path.starts_with("file://"));
651 assert!(def.full_path.starts_with('/'));
652 }
653}