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.
60///
61pub 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
85/// Queries `rust-analyzer` for all available methods on a given type type expression.
86///
87/// This spins up an ephemeral LSP session, generates a mock workspace via a [`Probe`],
88/// triggers a completion request at the appropriate line/column location, and parses the results.
89///
90/// # Environment Variables
91///
92/// * `RUST_METH_DEBUG` - If set, logs raw LSP method lifecycle events to standard error.
93///
94/// # Errors
95///
96/// Returns an error if:
97/// * Spawning the `rust-analyzer` subprocess fails.
98/// * The LSP server communication channels break.
99/// * The server returns an unexpectedly structured or malformed JSON payload.
100// pub fn query_methods(type_name: &str, ra_path: &std::path::Path) -> anyhow::Result<Vec<Method>> {
101//     let probe = Probe::new(type_name)?;
102pub 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    // ── 1. initialize ────────────────────────────────────────────────────────
118    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    // ── 2. initialized notification ──────────────────────────────────────────
124    lsp.send(&LspTransport::initialized())?;
125
126    // ── 3. didOpen ───────────────────────────────────────────────────────────
127    lsp.send(&LspTransport::did_open(&probe.src_uri(), &probe.source()?))?;
128
129    // ── 4. Wait for RA to finish indexing ────────────────────────────────────
130    wait_for_indexing(&mut lsp)?;
131
132    // ── 5. completion — retry until RA returns items ──────────────────────────
133    // RA may return isIncomplete+empty if it isn't fully ready yet.
134    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 {
157                let delay = match attempt {
158                    1 => 50,  // 50ms - RA might be ready immediately
159                    2 => 100, // 100ms
160                    3 => 200, // 200ms
161                    _ => 300, // 300ms for later attempts
162                };
163                std::thread::sleep(std::time::Duration::from_millis(delay));
164            }
165            // if attempt < 10 {
166            //     std::thread::sleep(std::time::Duration::from_millis(500));
167            // }
168        }
169        response
170    };
171
172    // ── 6. shutdown / exit ────────────────────────────────────────────────────
173    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    // ── 7. Parse completion items ─────────────────────────────────────────────
179    parse_methods(&completion_response)
180}
181
182/// Wait until rust-analyzer is ready to serve completions.
183///
184/// RA doesn't always send $/progress. On fast/warm projects it skips straight
185/// to publishing diagnostics. We treat any of these as "ready":
186///   - $/progress with value.kind == "end"
187///   - experimental/serverStatus with quiescent == true
188///   - workspace/diagnostic/refresh
189///   - textDocument/publishDiagnostics
190fn 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); // Hard timeout
194
195    lsp.recv_until(200, |msg| {
196        // Timeout escape hatch
197        if start.elapsed() > timeout {
198            return Some(()); // Give up and try anyway
199        }
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            // These are strong signals that indexing is done
222            "textDocument/publishDiagnostics" | "workspace/diagnostic/refresh" => Some(()),
223            _ => None,
224        }
225    })
226    .or(Ok(()))
227}
228
229/// Filters, sanitizes, and deduplicates the raw JSON arrays returned by the LSP completion query.
230///
231/// # Errors
232///
233/// Returns an error if the provided JSON response does not conform to the expected LSP
234/// completion shape (missing both a top-level `result` array and an `items` sub-array).
235pub 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/// Contains source definition location mappings returned by an LSP `textDocument/definition` call.
273#[must_use]
274pub struct Definition {
275    /// A shortened path string tailored for display terminals (e.g., `"library/core/src/num/uint_macros.rs"`).
276    pub path: String,
277    /// The unadulterated, absolute path prefix on the local filesystem.
278    pub full_path: String,
279    /// 0-indexed line number where the source item is declared.
280    pub line: u32,
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) -> 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    // 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 = {
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            // -32801 = content modified, -32800 = request cancelled. Both mean retry.
338            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/// Normalizes the location array or object mapping payload returned by the LSP server into a [`Definition`].
365///
366/// # Panics
367///
368/// Panics if the line position value returned by the LSP protocol fails to map cleanly into a `u32`.
369#[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    // ── parse_methods ────────────────────────────────────────────────────────
412
413    #[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        // kind 2 = Method, kind 5 = Field, kind 9 = Module
423        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        // Some LSP servers return `result` as a plain array
505        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    // These simulate what rust-analyzer returns for third-party crate types:
537    // the label contains the full signature e.g. `"as_str(…)"`.
538
539    #[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    // ── parse_definition ─────────────────────────────────────────────────────
556
557    #[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        // path should start at "library/" not "/"
623        assert!(def.path.starts_with("library/"));
624        assert!(!def.path.starts_with('/'));
625    }
626
627    #[test]
628    fn parse_definition_src_path_fallback() {
629        // A third-party crate source — has /src/ but no /library/
630        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}