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> {
61 if let Some(path) = RA_PATH_CACHE.get() {
62 return Ok(path.clone());
63 }
64
65 let path = which("rust-analyzer")
66 .ok()
67 .or_else(rustup_rust_analyzer)
68 .ok_or(RustMethError::RustAnalyzerNotFound)?;
69
70 Ok(RA_PATH_CACHE.get_or_init(|| path).clone())
71}
72
73#[cfg(unix)]
74fn which(name: &str) -> Result<std::path::PathBuf> {
75 let out = Command::new("which").arg(name).output()?;
76 if !out.status.success() {
77 return Err(RustMethError::RustAnalyzerNotFound);
78 }
79 let s = String::from_utf8_lossy(&out.stdout).trim().to_string();
80 Ok(s.into())
81}
82
83pub fn query_methods(
101 type_name: &str,
102 ra_path: &std::path::Path,
103 deps: Option<&str>,
104) -> Result<Vec<Method>> {
105 let probe = Probe::new_with_deps(type_name, deps)?;
106 let mut child = Command::new(ra_path)
107 .stdin(Stdio::piped())
108 .stdout(Stdio::piped())
109 .stderr(Stdio::null())
110 .spawn()?;
111
112 let mut lsp = LspTransport::new(&mut child);
113 let pid = std::process::id();
114
115 lsp.send(&LspTransport::initialize(pid, &probe.root_uri()))?;
117 lsp.recv_until(20, |msg| {
118 (msg["id"] == 1 && msg["result"].is_object()).then_some(())
119 })?;
120
121 lsp.send(&LspTransport::initialized())?;
123
124 lsp.send(&LspTransport::did_open(&probe.src_uri(), &probe.source()?))?;
126
127 wait_for_indexing(&mut lsp)?;
129
130 let completion_response = retry_lsp_request(
133 &mut lsp,
134 10,
135 |req_id| LspTransport::completion(req_id, &probe.src_uri(), probe.dot_line, probe.dot_col),
136 |msg| {
137 msg["result"]["items"]
138 .as_array()
139 .is_some_and(|a| !a.is_empty())
140 },
141 )?;
142
143 lsp.send(&LspTransport::shutdown(13))?;
145 let _ = lsp.recv_until(10, |msg| (msg["id"] == 13).then_some(()));
146 lsp.send(&LspTransport::exit())?;
147 let _ = child.wait();
148
149 parse_methods(&completion_response)
151}
152
153fn wait_for_indexing(lsp: &mut LspTransport) -> Result<()> {
162 let debug = std::env::var("RUST_METH_DEBUG").is_ok();
163 let start = std::time::Instant::now();
164 let timeout = std::time::Duration::from_secs(10); lsp.recv_until(200, |msg| {
167 if start.elapsed() > timeout {
169 return Some(()); }
171
172 let method = msg["method"].as_str().unwrap_or("");
173 if debug {
174 eprintln!("[debug] {method}");
175 }
176
177 match method {
178 "$/progress" => {
179 if msg["params"]["value"]["kind"] == "end" {
180 Some(())
181 } else {
182 None
183 }
184 }
185 "experimental/serverStatus" => {
186 if msg["params"]["quiescent"] == true {
187 Some(())
188 } else {
189 None
190 }
191 }
192 "textDocument/publishDiagnostics" | "workspace/diagnostic/refresh" => Some(()),
194 _ => None,
195 }
196 })
197 .or(Ok(()))
198}
199
200pub fn parse_methods(response: &Value) -> Result<Vec<Method>> {
207 let result = &response["result"];
208 let items: &[Value] = match result {
209 Value::Array(arr) => arr.as_slice(),
210 obj if obj["items"].is_array() => obj["items"].as_array().map_or(&[], Vec::as_slice),
211 _ => return Err(RustMethError::UnexpectedResponseShape(response.to_string())),
212 };
213
214 let mut methods: Vec<Method> = Vec::with_capacity(items.len() / 2);
215
216 for item in items {
217 if item["kind"].as_u64() != Some(KIND_METHOD) {
218 continue;
219 }
220 let name = item["label"]
221 .as_str()
222 .unwrap_or("")
223 .split('(')
224 .next()
225 .unwrap_or("")
226 .trim()
227 .to_string();
228 if name.is_empty() {
229 continue;
230 }
231 methods.push(Method {
232 name,
233 detail: item["detail"].as_str().map(str::to_string),
234 documentation: item["documentation"]["value"].as_str().map(str::to_string),
235 });
236 }
237
238 methods.sort_unstable_by(|a, b| a.name.cmp(&b.name));
239 methods.dedup_by(|a, b| a.name == b.name);
240 Ok(methods)
241}
242
243#[must_use]
245pub struct Definition {
246 pub path: String,
248 pub full_path: String,
250 pub line: u32,
252}
253
254fn retry_lsp_request<F, G>(
255 lsp: &mut LspTransport,
256 max_attempts: u64,
257 mut make_request: F,
258 mut is_success: G,
259) -> Result<Value>
260where
261 F: FnMut(u64) -> Value, G: FnMut(&Value) -> bool, {
264 let mut result = Value::Null;
265 for attempt in 1..=max_attempts {
266 let req_id = attempt + 2;
267 lsp.send(&make_request(req_id))?;
268 let msg = lsp.recv_until(50, |msg| (msg["id"] == req_id).then(|| msg.clone()))?;
269 if is_success(&msg) {
270 result = msg;
271 break;
272 }
273 if attempt < max_attempts {
274 if std::env::var("RUST_METH_DEBUG").is_ok() {
275 eprintln!("(attempt {attempt}: not ready, retrying…)");
276 }
277 std::thread::sleep(std::time::Duration::from_millis(500));
278 }
279 }
280 Ok(result)
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) -> 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 = retry_lsp_request(
325 &mut lsp,
326 10,
327 |req_id| LspTransport::definition(req_id, &probe.src_uri(), probe.dot_line, probe.dot_col),
328 |msg| {
329 let is_error = msg["error"]["code"].as_i64().is_some();
330 let is_null = msg["result"].is_null();
331 !is_error && !is_null
332 },
333 )?;
334
335 lsp.send(&LspTransport::shutdown(13))?;
336 let _ = lsp.recv_until(10, |msg| (msg["id"] == 13).then_some(()));
337 lsp.send(&LspTransport::exit())?;
338 let _ = child.wait();
339
340 Ok(parse_definition(&response))
341}
342
343#[must_use]
349pub fn parse_definition(response: &Value) -> Option<Definition> {
350 let result = &response["result"];
351 let location: &Value = match result {
352 Value::Array(arr) if !arr.is_empty() => &arr[0],
353 single if single.is_object() => single,
354 _ => return None,
355 };
356
357 let uri = location["uri"].as_str().unwrap_or("");
358 if uri.is_empty() {
359 return None;
360 }
361
362 let line = u32::try_from(location["range"]["start"]["line"].as_u64().unwrap_or(0))
363 .expect("LSP definition line should fit in u32");
364
365 let full_path_str = uri.strip_prefix("file://").unwrap_or(uri);
366
367 let path = full_path_str
368 .find("/library/")
369 .or_else(|| full_path_str.find("/src/"))
370 .map_or_else(
371 || full_path_str.to_string(),
372 |idx| full_path_str[idx + 1..].to_string(),
373 );
374
375 let full_path = full_path_str.to_string();
376
377 Some(Definition {
378 path,
379 full_path,
380 line,
381 })
382}
383
384#[cfg(test)]
385#[allow(clippy::unwrap_used)]
386mod tests {
387 use super::*;
388 use serde_json::json;
389
390 #[test]
393 fn parse_methods_empty_items_returns_empty_vec() {
394 let resp = json!({ "result": { "items": [], "isIncomplete": false } });
395 let methods = parse_methods(&resp).unwrap();
396 assert!(methods.is_empty());
397 }
398
399 #[test]
400 fn parse_methods_filters_non_method_kinds() {
401 let resp = json!({
403 "result": {
404 "items": [
405 { "kind": 2, "label": "len(…)" },
406 { "kind": 5, "label": "capacity" },
407 { "kind": 9, "label": "Clone" }
408 ]
409 }
410 });
411 let methods = parse_methods(&resp).unwrap();
412 assert_eq!(methods.len(), 1);
413 assert_eq!(methods[0].name, "len");
414 }
415
416 #[test]
417 fn parse_methods_deduplicates_same_name() {
418 let resp = json!({
419 "result": {
420 "items": [
421 { "kind": 2, "label": "clone(…)" },
422 { "kind": 2, "label": "clone(…)" }
423 ]
424 }
425 });
426 let methods = parse_methods(&resp).unwrap();
427 assert_eq!(methods.len(), 1);
428 assert_eq!(methods[0].name, "clone");
429 }
430
431 #[test]
432 fn parse_methods_returns_sorted_names() {
433 let resp = json!({
434 "result": {
435 "items": [
436 { "kind": 2, "label": "zip(…)" },
437 { "kind": 2, "label": "map(…)" },
438 { "kind": 2, "label": "filter(…)" }
439 ]
440 }
441 });
442 let methods = parse_methods(&resp).unwrap();
443 let names: Vec<&str> = methods.iter().map(|m| m.name.as_str()).collect();
444 assert_eq!(names, ["filter", "map", "zip"]);
445 }
446
447 #[test]
448 fn parse_methods_preserves_detail_and_documentation() {
449 let resp = json!({
450 "result": {
451 "items": [{
452 "kind": 2,
453 "label": "len(…)",
454 "detail": "pub fn len(&self) -> usize",
455 "documentation": { "value": "Returns the number of elements." }
456 }]
457 }
458 });
459 let methods = parse_methods(&resp).unwrap();
460 assert_eq!(methods.len(), 1);
461 assert_eq!(
462 methods[0].detail.as_deref(),
463 Some("pub fn len(&self) -> usize")
464 );
465 assert_eq!(
466 methods[0].documentation.as_deref(),
467 Some("Returns the number of elements.")
468 );
469 }
470
471 #[test]
472 fn parse_methods_no_detail_or_docs_is_none() {
473 let resp = json!({
474 "result": { "items": [{ "kind": 2, "label": "len(…)" }] }
475 });
476 let methods = parse_methods(&resp).unwrap();
477 assert!(methods[0].detail.is_none());
478 assert!(methods[0].documentation.is_none());
479 }
480
481 #[test]
482 fn parse_methods_array_result_form() {
483 let resp = json!({
485 "result": [
486 { "kind": 2, "label": "len(…)" },
487 { "kind": 2, "label": "is_empty(…)" }
488 ]
489 });
490 let methods = parse_methods(&resp).unwrap();
491 assert_eq!(methods.len(), 2);
492 }
493
494 #[test]
495 fn parse_methods_skips_empty_label() {
496 let resp = json!({
497 "result": {
498 "items": [
499 { "kind": 2, "label": "" },
500 { "kind": 2, "label": "len(…)" }
501 ]
502 }
503 });
504 let methods = parse_methods(&resp).unwrap();
505 assert_eq!(methods.len(), 1);
506 assert_eq!(methods[0].name, "len");
507 }
508
509 #[test]
510 fn parse_methods_unexpected_shape_returns_error() {
511 let resp = json!({ "result": "this_is_not_valid" });
512 assert!(parse_methods(&resp).is_err());
513 }
514
515 #[test]
519 fn parse_methods_third_party_label_stripped_at_paren() {
520 let resp = json!({
521 "result": {
522 "items": [
523 { "kind": 2, "label": "as_str(…)", "detail": "pub fn as_str(&self) -> &str" },
524 { "kind": 2, "label": "as_object(…)" }
525 ]
526 }
527 });
528 let methods = parse_methods(&resp).unwrap();
529 let names: Vec<&str> = methods.iter().map(|m| m.name.as_str()).collect();
530 assert!(names.contains(&"as_str"));
531 assert!(names.contains(&"as_object"));
532 }
533
534 #[test]
537 fn parse_definition_array_form() {
538 let resp = json!({
539 "result": [{
540 "uri": "file:///home/user/.rustup/toolchains/stable/library/core/src/num/mod.rs",
541 "range": {
542 "start": { "line": 42, "character": 0 },
543 "end": { "line": 42, "character": 10 }
544 }
545 }]
546 });
547 let def = parse_definition(&resp).unwrap();
548 assert_eq!(def.line, 42);
549 assert!(def.path.starts_with("library/"));
550 assert!(!def.full_path.starts_with("file://"));
551 }
552
553 #[test]
554 fn parse_definition_object_form() {
555 let resp = json!({
556 "result": {
557 "uri": "file:///home/user/.rustup/toolchains/stable/library/core/src/str/mod.rs",
558 "range": {
559 "start": { "line": 99, "character": 4 },
560 "end": { "line": 99, "character": 20 }
561 }
562 }
563 });
564 let def = parse_definition(&resp).unwrap();
565 assert_eq!(def.line, 99);
566 assert!(def.path.starts_with("library/"));
567 }
568
569 #[test]
570 fn parse_definition_null_result_returns_none() {
571 let resp = json!({ "result": null });
572 assert!(parse_definition(&resp).is_none());
573 }
574
575 #[test]
576 fn parse_definition_empty_array_returns_none() {
577 let resp = json!({ "result": [] });
578 assert!(parse_definition(&resp).is_none());
579 }
580
581 #[test]
582 fn parse_definition_empty_uri_returns_none() {
583 let resp = json!({
584 "result": [{
585 "uri": "",
586 "range": { "start": { "line": 0, "character": 0 }, "end": { "line": 0, "character": 0 } }
587 }]
588 });
589 assert!(parse_definition(&resp).is_none());
590 }
591
592 #[test]
593 fn parse_definition_strips_library_prefix_from_path() {
594 let resp = json!({
595 "result": [{
596 "uri": "file:///home/user/.rustup/toolchains/stable/library/core/src/num/mod.rs",
597 "range": { "start": { "line": 0, "character": 0 }, "end": { "line": 0, "character": 0 } }
598 }]
599 });
600 let def = parse_definition(&resp).unwrap();
601 assert!(def.path.starts_with("library/"));
603 assert!(!def.path.starts_with('/'));
604 }
605
606 #[test]
607 fn parse_definition_src_path_fallback() {
608 let resp = json!({
610 "result": [{
611 "uri": "file:///home/user/myproject/src/main.rs",
612 "range": { "start": { "line": 5, "character": 0 }, "end": { "line": 5, "character": 0 } }
613 }]
614 });
615 let def = parse_definition(&resp).unwrap();
616 assert!(def.path.starts_with("src/"));
617 assert_eq!(def.line, 5);
618 }
619
620 #[test]
621 fn parse_definition_full_path_does_not_start_with_file_scheme() {
622 let resp = json!({
623 "result": [{
624 "uri": "file:///home/user/project/src/lib.rs",
625 "range": { "start": { "line": 1, "character": 0 }, "end": { "line": 1, "character": 0 } }
626 }]
627 });
628 let def = parse_definition(&resp).unwrap();
629 assert!(!def.full_path.starts_with("file://"));
630 assert!(def.full_path.starts_with('/'));
631 }
632}