Skip to main content

rust_meth_lib/
analyzer.rs

1// Orchestrates the full LSP session:
2//   1. Spawn rust-analyzer
3//   2. initialize / initialized handshake
4//   3. textDocument/didOpen
5//   4. Wait for indexing to complete
6//   5. textDocument/completion (with retry)
7//   6. Extract Method items from the response
8//   7. shutdown / exit
9
10use 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
20/// LSP `CompletionItemKind` value corresponding to a Method.
21const KIND_METHOD: u64 = 2;
22
23static RA_PATH_CACHE: OnceLock<PathBuf> = OnceLock::new();
24
25/// Represents a method extracted from a `rust-analyzer` completion list.
26#[derive(serde::Serialize)]
27pub struct Method {
28    /// The plain name of the method (e.g., `"len"`).
29    pub name: String,
30    /// The full method signature hint provided by the LSP server (e.g., `"pub const fn len(&self) -> usize"`).
31    pub detail: Option<String>,
32    /// Markdown or plaintext documentation extracted from the item.
33    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
50/// Locates the `rust-analyzer` binary.
51///
52/// It first searches the system `PATH` env variable using the system `which` utility.
53/// If missing, it attempts to fall back to the active toolchain's binary directory
54/// using `rustup which rust-analyzer`.
55///
56/// # Errors
57///
58/// Returns an error if `rust-analyzer` cannot be found via either mechanism,
59/// providing user-friendly instructions on how to install it.
60pub 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
83/// Queries `rust-analyzer` for all available methods on a given type type expression.
84///
85/// This spins up an ephemeral LSP session, generates a mock workspace via a [`Probe`],
86/// triggers a completion request at the appropriate line/column location, and parses the results.
87///
88/// # Environment Variables
89///
90/// * `RUST_METH_DEBUG` - If set, logs raw LSP method lifecycle events to standard error.
91///
92/// # Errors
93///
94/// Returns an error if:
95/// * Spawning the `rust-analyzer` subprocess fails.
96/// * The LSP server communication channels break.
97/// * The server returns an unexpectedly structured or malformed JSON payload.
98// pub fn query_methods(type_name: &str, ra_path: &std::path::Path) -> anyhow::Result<Vec<Method>> {
99//     let probe = Probe::new(type_name)?;
100pub 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    // ── 1. initialize ────────────────────────────────────────────────────────
116    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    // ── 2. initialized notification ──────────────────────────────────────────
122    lsp.send(&LspTransport::initialized())?;
123
124    // ── 3. didOpen ───────────────────────────────────────────────────────────
125    lsp.send(&LspTransport::did_open(&probe.src_uri(), &probe.source()?))?;
126
127    // ── 4. Wait for RA to finish indexing ────────────────────────────────────
128    wait_for_indexing(&mut lsp)?;
129
130    // ── 5. completion — retry until RA returns items ──────────────────────────
131    // RA may return isIncomplete+empty if it isn't fully ready yet.
132    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    // ── 6. shutdown / exit ────────────────────────────────────────────────────
144    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    // ── 7. Parse completion items ─────────────────────────────────────────────
150    parse_methods(&completion_response)
151}
152
153/// Wait until rust-analyzer is ready to serve completions.
154///
155/// RA doesn't always send $/progress. On fast/warm projects it skips straight
156/// to publishing diagnostics. We treat any of these as "ready":
157///   - $/progress with value.kind == "end"
158///   - experimental/serverStatus with quiescent == true
159///   - workspace/diagnostic/refresh
160///   - textDocument/publishDiagnostics
161fn 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); // Hard timeout
165
166    lsp.recv_until(200, |msg| {
167        // Timeout escape hatch
168        if start.elapsed() > timeout {
169            return Some(()); // Give up and try anyway
170        }
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            // These are strong signals that indexing is done
193            "textDocument/publishDiagnostics" | "workspace/diagnostic/refresh" => Some(()),
194            _ => None,
195        }
196    })
197    .or(Ok(()))
198}
199
200/// Filters, sanitizes, and deduplicates the raw JSON arrays returned by the LSP completion query.
201///
202/// # Errors
203///
204/// Returns an error if the provided JSON response does not conform to the expected LSP
205/// completion shape (missing both a top-level `result` array and an `items` sub-array).
206pub 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/// Contains source definition location mappings returned by an LSP `textDocument/definition` call.
244#[must_use]
245pub struct Definition {
246    /// A shortened path string tailored for display terminals (e.g., `"library/core/src/num/uint_macros.rs"`).
247    pub path: String,
248    /// The unadulterated, absolute path prefix on the local filesystem.
249    pub full_path: String,
250    /// 0-indexed line number where the source item is declared.
251    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,   // takes req_id, returns the request to send
262    G: FnMut(&Value) -> bool, // returns true when response is good
263{
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
283/// Queries `rust-analyzer` for the precise upstream source file declaration layout of a specific method.
284///
285/// Under the hood, this sets up a mock environment containing an isolated invocation of your method,
286/// queries `textDocument/definition`, and intercepts the target file location coordinates.
287///
288/// # Errors
289///
290/// Returns an error if the underlying LSP runtime breaks, or if `rust-analyzer` encounters structural errors.
291/// If a method exists but has no discoverable source code location definitions, it evaluates cleanly into `Ok(None)`.
292pub 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    // Send didOpen immediately after initialized, don't wait
310    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    // Send both notifications back-to-back (no wait needed)
316    lsp.send(&LspTransport::initialized())?;
317    lsp.send(&LspTransport::did_open(&probe.src_uri(), &probe.source()?))?;
318
319    // Now wait for indexing
320    wait_for_indexing(&mut lsp)?;
321
322    // Retry on "content modified" - RA rejects requests while it's still
323    // processing the file. Same pattern as the completion retry loop.
324    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/// Normalizes the location array or object mapping payload returned by the LSP server into a [`Definition`].
344///
345/// # Panics
346///
347/// Panics if the line position value returned by the LSP protocol fails to map cleanly into a `u32`.
348#[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    // ── parse_methods ────────────────────────────────────────────────────────
391
392    #[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        // kind 2 = Method, kind 5 = Field, kind 9 = Module
402        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        // Some LSP servers return `result` as a plain array
484        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    // These simulate what rust-analyzer returns for third-party crate types:
516    // the label contains the full signature e.g. `"as_str(…)"`.
517
518    #[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    // ── parse_definition ─────────────────────────────────────────────────────
535
536    #[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        // path should start at "library/" not "/"
602        assert!(def.path.starts_with("library/"));
603        assert!(!def.path.starts_with('/'));
604    }
605
606    #[test]
607    fn parse_definition_src_path_fallback() {
608        // A third-party crate source — has /src/ but no /library/
609        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}