rust-meth 0.2.0

Discover methods available on any Rust type with fuzzy filtering, inline documentation, interactive selection, and go-to-definition into standard library source code.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
// Orchestrates the full LSP session:
//   1. Spawn rust-analyzer
//   2. initialize / initialized handshake
//   3. textDocument/didOpen
//   4. Wait for indexing to complete
//   5. textDocument/completion (with retry)
//   6. Extract Method items from the response
//   7. shutdown / exit

use std::path::PathBuf;
use std::process::{Command, Stdio};
use std::sync::OnceLock;

use serde_json::Value;

use crate::lsp::LspTransport;
use crate::probe::Probe;

/// LSP `CompletionItemKind` value corresponding to a Method.
const KIND_METHOD: u64 = 2;

static RA_PATH_CACHE: OnceLock<PathBuf> = OnceLock::new();

/// Represents a method extracted from a `rust-analyzer` completion list.
#[derive(serde::Serialize)]
pub struct Method {
    /// The plain name of the method (e.g., `"len"`).
    pub name: String,
    /// The full method signature hint provided by the LSP server (e.g., `"pub const fn len(&self) -> usize"`).
    pub detail: Option<String>,
    /// Markdown or plaintext documentation extracted from the item.
    pub documentation: Option<String>,
}

fn rustup_rust_analyzer() -> Option<PathBuf> {
    let out = Command::new("rustup")
        .args(["which", "rust-analyzer"])
        .output()
        .ok()?;

    if !out.status.success() {
        return None;
    }

    let path = String::from_utf8_lossy(&out.stdout).trim().to_string();
    (!path.is_empty()).then(|| path.into())
}

/// Locates the `rust-analyzer` binary.
///
/// It first searches the system `PATH` env variable using the system `which` utility.
/// If missing, it attempts to fall back to the active toolchain's binary directory
/// using `rustup which rust-analyzer`.
///
/// # Errors
///
/// Returns an error if `rust-analyzer` cannot be found via either mechanism,
/// providing user-friendly instructions on how to install it.
///
pub fn find_rust_analyzer() -> anyhow::Result<PathBuf> {
    if let Some(path) = RA_PATH_CACHE.get() {
        return Ok(path.clone());
    }
    let path = if let Ok(path) = which("rust-analyzer") {
        path
    } else if let Some(path) = rustup_rust_analyzer() {
        path
    } else {
        anyhow::bail!(
            "rust-analyzer not found.\n\
             Install it with: rustup component add rust-analyzer\n\
             or ensure it is on your PATH."
        )
    };
    Ok(RA_PATH_CACHE.get_or_init(|| path).clone())
}

#[cfg(unix)]
fn which(name: &str) -> anyhow::Result<std::path::PathBuf> {
    let out = Command::new("which").arg(name).output()?;
    anyhow::ensure!(out.status.success(), "not found");
    let s = String::from_utf8_lossy(&out.stdout).trim().to_string();
    Ok(s.into())
}

/// Queries `rust-analyzer` for all available methods on a given type type expression.
///
/// This spins up an ephemeral LSP session, generates a mock workspace via a [`Probe`],
/// triggers a completion request at the appropriate line/column location, and parses the results.
///
/// # Environment Variables
///
/// * `RUST_METH_DEBUG` - If set, logs raw LSP method lifecycle events to standard error.
///
/// # Errors
///
/// Returns an error if:
/// * Spawning the `rust-analyzer` subprocess fails.
/// * The LSP server communication channels break.
/// * The server returns an unexpectedly structured or malformed JSON payload.
// pub fn query_methods(type_name: &str, ra_path: &std::path::Path) -> anyhow::Result<Vec<Method>> {
//     let probe = Probe::new(type_name)?;
pub fn query_methods(
    type_name: &str,
    ra_path: &std::path::Path,
    deps: Option<&str>,
) -> anyhow::Result<Vec<Method>> {
    let probe = Probe::new_with_deps(type_name, deps)?;
    let mut child = Command::new(ra_path)
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::null())
        .spawn()?;

    let mut lsp = LspTransport::new(&mut child);
    let pid = std::process::id();

    // ── 1. initialize ────────────────────────────────────────────────────────
    lsp.send(&LspTransport::initialize(pid, &probe.root_uri()))?;
    lsp.recv_until(20, |msg| {
        (msg["id"] == 1 && msg["result"].is_object()).then_some(())
    })?;

    // ── 2. initialized notification ──────────────────────────────────────────
    lsp.send(&LspTransport::initialized())?;

    // ── 3. didOpen ───────────────────────────────────────────────────────────
    lsp.send(&LspTransport::did_open(&probe.src_uri(), &probe.source()?))?;

    // ── 4. Wait for RA to finish indexing ────────────────────────────────────
    wait_for_indexing(&mut lsp)?;

    // ── 5. completion — retry until RA returns items ──────────────────────────
    // RA may return isIncomplete+empty if it isn't fully ready yet.
    let completion_response = {
        let mut response = Value::Null;
        for attempt in 1..=10u64 {
            let req_id = attempt + 2;
            lsp.send(&LspTransport::completion(
                req_id,
                &probe.src_uri(),
                probe.dot_line,
                probe.dot_col,
            ))?;

            let msg = lsp.recv_until(50, |msg| (msg["id"] == req_id).then(|| msg.clone()))?;

            let has_items = msg["result"]["items"]
                .as_array()
                .is_some_and(|a| !a.is_empty());

            if has_items {
                response = msg;
                break;
            }

            if attempt < 10 {
                let delay = match attempt {
                    1 => 50,  // 50ms - RA might be ready immediately
                    2 => 100, // 100ms
                    3 => 200, // 200ms
                    _ => 300, // 300ms for later attempts
                };
                std::thread::sleep(std::time::Duration::from_millis(delay));
            }
            // if attempt < 10 {
            //     std::thread::sleep(std::time::Duration::from_millis(500));
            // }
        }
        response
    };

    // ── 6. shutdown / exit ────────────────────────────────────────────────────
    lsp.send(&LspTransport::shutdown(13))?;
    let _ = lsp.recv_until(10, |msg| (msg["id"] == 13).then_some(()));
    lsp.send(&LspTransport::exit())?;
    let _ = child.wait();

    // ── 7. Parse completion items ─────────────────────────────────────────────
    parse_methods(&completion_response)
}

/// Wait until rust-analyzer is ready to serve completions.
///
/// RA doesn't always send $/progress. On fast/warm projects it skips straight
/// to publishing diagnostics. We treat any of these as "ready":
///   - $/progress with value.kind == "end"
///   - experimental/serverStatus with quiescent == true
///   - workspace/diagnostic/refresh
///   - textDocument/publishDiagnostics
fn wait_for_indexing(lsp: &mut LspTransport) -> anyhow::Result<()> {
    let debug = std::env::var("RUST_METH_DEBUG").is_ok();
    let start = std::time::Instant::now();
    let timeout = std::time::Duration::from_secs(10); // Hard timeout

    lsp.recv_until(200, |msg| {
        // Timeout escape hatch
        if start.elapsed() > timeout {
            return Some(()); // Give up and try anyway
        }

        let method = msg["method"].as_str().unwrap_or("");
        if debug {
            eprintln!("[debug] {method}");
        }

        match method {
            "$/progress" => {
                if msg["params"]["value"]["kind"] == "end" {
                    Some(())
                } else {
                    None
                }
            }
            "experimental/serverStatus" => {
                if msg["params"]["quiescent"] == true {
                    Some(())
                } else {
                    None
                }
            }
            // These are strong signals that indexing is done
            "textDocument/publishDiagnostics" | "workspace/diagnostic/refresh" => Some(()),
            _ => None,
        }
    })
    .or(Ok(()))
}

/// Filters, sanitizes, and deduplicates the raw JSON arrays returned by the LSP completion query.
///
/// # Errors
///
/// Returns an error if the provided JSON response does not conform to the expected LSP
/// completion shape (missing both a top-level `result` array and an `items` sub-array).
pub fn parse_methods(response: &Value) -> anyhow::Result<Vec<Method>> {
    let result = &response["result"];
    let items: &[Value] = match result {
        Value::Array(arr) => arr.as_slice(),
        obj if obj["items"].is_array() => obj["items"].as_array().map_or(&[], Vec::as_slice),
        _ => anyhow::bail!("Unexpected completion response shape: {response}"),
    };

    let mut methods: Vec<Method> = Vec::with_capacity(items.len() / 2);

    for item in items {
        if item["kind"].as_u64() != Some(KIND_METHOD) {
            continue;
        }
        let name = item["label"]
            .as_str()
            .unwrap_or("")
            .split('(')
            .next()
            .unwrap_or("")
            .trim()
            .to_string();
        if name.is_empty() {
            continue;
        }
        methods.push(Method {
            name,
            detail: item["detail"].as_str().map(str::to_string),
            documentation: item["documentation"]["value"].as_str().map(str::to_string),
        });
    }

    methods.sort_unstable_by(|a, b| a.name.cmp(&b.name));
    methods.dedup_by(|a, b| a.name == b.name);
    Ok(methods)
}

/// Contains source definition location mappings returned by an LSP `textDocument/definition` call.
#[must_use]
pub struct Definition {
    /// A shortened path string tailored for display terminals (e.g., `"library/core/src/num/uint_macros.rs"`).
    pub path: String,
    /// The unadulterated, absolute path prefix on the local filesystem.
    pub full_path: String,
    /// 0-indexed line number where the source item is declared.
    pub line: u32,
}

/// Queries `rust-analyzer` for the precise upstream source file declaration layout of a specific method.
///
/// Under the hood, this sets up a mock environment containing an isolated invocation of your method,
/// queries `textDocument/definition`, and intercepts the target file location coordinates.
///
/// # Errors
///
/// Returns an error if the underlying LSP runtime breaks, or if `rust-analyzer` encounters structural errors.
/// If a method exists but has no discoverable source code location definitions, it evaluates cleanly into `Ok(None)`.
pub fn query_definition(
    type_name: &str,
    method_name: &str,
    ra_path: &std::path::Path,
    deps: Option<&str>,
) -> anyhow::Result<Option<Definition>> {
    let probe = Probe::for_definition_with_deps(type_name, method_name, deps)?;

    let mut child = Command::new(ra_path)
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::null())
        .spawn()?;

    let mut lsp = LspTransport::new(&mut child);
    let pid = std::process::id();

    // Send didOpen immediately after initialized, don't wait
    lsp.send(&LspTransport::initialize(pid, &probe.root_uri()))?;
    lsp.recv_until(20, |msg| {
        (msg["id"] == 1 && msg["result"].is_object()).then_some(())
    })?;

    // Send both notifications back-to-back (no wait needed)
    lsp.send(&LspTransport::initialized())?;
    lsp.send(&LspTransport::did_open(&probe.src_uri(), &probe.source()?))?;

    // Now wait for indexing
    wait_for_indexing(&mut lsp)?;

    // Retry on "content modified" - RA rejects requests while it's still
    // processing the file. Same pattern as the completion retry loop.
    let response = {
        let mut result = Value::Null;
        for attempt in 1..=10u64 {
            let req_id = attempt + 2;
            lsp.send(&LspTransport::definition(
                req_id,
                &probe.src_uri(),
                probe.dot_line,
                probe.dot_col,
            ))?;

            let msg = lsp.recv_until(50, |msg| (msg["id"] == req_id).then(|| msg.clone()))?;

            // -32801 = content modified, -32800 = request cancelled. Both mean retry.
            let is_error = msg["error"]["code"].as_i64().is_some();
            let is_null = msg["result"].is_null();

            if !is_error && !is_null {
                result = msg;
                break;
            }

            if attempt < 10 {
                if std::env::var("RUST_METH_DEBUG").is_ok() {
                    eprintln!("(attempt {attempt}: not ready, retrying…)");
                }
                std::thread::sleep(std::time::Duration::from_millis(500));
            }
        }
        result
    };

    lsp.send(&LspTransport::shutdown(13))?;
    let _ = lsp.recv_until(10, |msg| (msg["id"] == 13).then_some(()));
    lsp.send(&LspTransport::exit())?;
    let _ = child.wait();

    Ok(parse_definition(&response))
}

/// Normalizes the location array or object mapping payload returned by the LSP server into a [`Definition`].
///
/// # Panics
///
/// Panics if the line position value returned by the LSP protocol fails to map cleanly into a `u32`.
#[must_use]
pub fn parse_definition(response: &Value) -> Option<Definition> {
    let result = &response["result"];
    let location: &Value = match result {
        Value::Array(arr) if !arr.is_empty() => &arr[0],
        single if single.is_object() => single,
        _ => return None,
    };

    let uri = location["uri"].as_str().unwrap_or("");
    if uri.is_empty() {
        return None;
    }

    let line = u32::try_from(location["range"]["start"]["line"].as_u64().unwrap_or(0))
        .expect("LSP definition line should fit in u32");

    let full_path_str = uri.strip_prefix("file://").unwrap_or(uri);

    let path = full_path_str
        .find("/library/")
        .or_else(|| full_path_str.find("/src/"))
        .map_or_else(
            || full_path_str.to_string(),
            |idx| full_path_str[idx + 1..].to_string(),
        );

    let full_path = full_path_str.to_string();

    Some(Definition {
        path,
        full_path,
        line,
    })
}

#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
    use super::*;
    use serde_json::json;

    // ── parse_methods ────────────────────────────────────────────────────────

    #[test]
    fn parse_methods_empty_items_returns_empty_vec() {
        let resp = json!({ "result": { "items": [], "isIncomplete": false } });
        let methods = parse_methods(&resp).unwrap();
        assert!(methods.is_empty());
    }

    #[test]
    fn parse_methods_filters_non_method_kinds() {
        // kind 2 = Method, kind 5 = Field, kind 9 = Module
        let resp = json!({
            "result": {
                "items": [
                    { "kind": 2, "label": "len(…)" },
                    { "kind": 5, "label": "capacity" },
                    { "kind": 9, "label": "Clone" }
                ]
            }
        });
        let methods = parse_methods(&resp).unwrap();
        assert_eq!(methods.len(), 1);
        assert_eq!(methods[0].name, "len");
    }

    #[test]
    fn parse_methods_deduplicates_same_name() {
        let resp = json!({
            "result": {
                "items": [
                    { "kind": 2, "label": "clone(…)" },
                    { "kind": 2, "label": "clone(…)" }
                ]
            }
        });
        let methods = parse_methods(&resp).unwrap();
        assert_eq!(methods.len(), 1);
        assert_eq!(methods[0].name, "clone");
    }

    #[test]
    fn parse_methods_returns_sorted_names() {
        let resp = json!({
            "result": {
                "items": [
                    { "kind": 2, "label": "zip(…)" },
                    { "kind": 2, "label": "map(…)" },
                    { "kind": 2, "label": "filter(…)" }
                ]
            }
        });
        let methods = parse_methods(&resp).unwrap();
        let names: Vec<&str> = methods.iter().map(|m| m.name.as_str()).collect();
        assert_eq!(names, ["filter", "map", "zip"]);
    }

    #[test]
    fn parse_methods_preserves_detail_and_documentation() {
        let resp = json!({
            "result": {
                "items": [{
                    "kind": 2,
                    "label": "len(…)",
                    "detail": "pub fn len(&self) -> usize",
                    "documentation": { "value": "Returns the number of elements." }
                }]
            }
        });
        let methods = parse_methods(&resp).unwrap();
        assert_eq!(methods.len(), 1);
        assert_eq!(
            methods[0].detail.as_deref(),
            Some("pub fn len(&self) -> usize")
        );
        assert_eq!(
            methods[0].documentation.as_deref(),
            Some("Returns the number of elements.")
        );
    }

    #[test]
    fn parse_methods_no_detail_or_docs_is_none() {
        let resp = json!({
            "result": { "items": [{ "kind": 2, "label": "len(…)" }] }
        });
        let methods = parse_methods(&resp).unwrap();
        assert!(methods[0].detail.is_none());
        assert!(methods[0].documentation.is_none());
    }

    #[test]
    fn parse_methods_array_result_form() {
        // Some LSP servers return `result` as a plain array
        let resp = json!({
            "result": [
                { "kind": 2, "label": "len(…)" },
                { "kind": 2, "label": "is_empty(…)" }
            ]
        });
        let methods = parse_methods(&resp).unwrap();
        assert_eq!(methods.len(), 2);
    }

    #[test]
    fn parse_methods_skips_empty_label() {
        let resp = json!({
            "result": {
                "items": [
                    { "kind": 2, "label": "" },
                    { "kind": 2, "label": "len(…)" }
                ]
            }
        });
        let methods = parse_methods(&resp).unwrap();
        assert_eq!(methods.len(), 1);
        assert_eq!(methods[0].name, "len");
    }

    #[test]
    fn parse_methods_unexpected_shape_returns_error() {
        let resp = json!({ "result": "this_is_not_valid" });
        assert!(parse_methods(&resp).is_err());
    }

    // These simulate what rust-analyzer returns for third-party crate types:
    // the label contains the full signature e.g. `"as_str(…)"`.

    #[test]
    fn parse_methods_third_party_label_stripped_at_paren() {
        let resp = json!({
            "result": {
                "items": [
                    { "kind": 2, "label": "as_str(…)", "detail": "pub fn as_str(&self) -> &str" },
                    { "kind": 2, "label": "as_object(…)" }
                ]
            }
        });
        let methods = parse_methods(&resp).unwrap();
        let names: Vec<&str> = methods.iter().map(|m| m.name.as_str()).collect();
        assert!(names.contains(&"as_str"));
        assert!(names.contains(&"as_object"));
    }

    // ── parse_definition ─────────────────────────────────────────────────────

    #[test]
    fn parse_definition_array_form() {
        let resp = json!({
            "result": [{
                "uri": "file:///home/user/.rustup/toolchains/stable/library/core/src/num/mod.rs",
                "range": {
                    "start": { "line": 42, "character": 0 },
                    "end":   { "line": 42, "character": 10 }
                }
            }]
        });
        let def = parse_definition(&resp).unwrap();
        assert_eq!(def.line, 42);
        assert!(def.path.starts_with("library/"));
        assert!(!def.full_path.starts_with("file://"));
    }

    #[test]
    fn parse_definition_object_form() {
        let resp = json!({
            "result": {
                "uri": "file:///home/user/.rustup/toolchains/stable/library/core/src/str/mod.rs",
                "range": {
                    "start": { "line": 99, "character": 4 },
                    "end":   { "line": 99, "character": 20 }
                }
            }
        });
        let def = parse_definition(&resp).unwrap();
        assert_eq!(def.line, 99);
        assert!(def.path.starts_with("library/"));
    }

    #[test]
    fn parse_definition_null_result_returns_none() {
        let resp = json!({ "result": null });
        assert!(parse_definition(&resp).is_none());
    }

    #[test]
    fn parse_definition_empty_array_returns_none() {
        let resp = json!({ "result": [] });
        assert!(parse_definition(&resp).is_none());
    }

    #[test]
    fn parse_definition_empty_uri_returns_none() {
        let resp = json!({
            "result": [{
                "uri": "",
                "range": { "start": { "line": 0, "character": 0 }, "end": { "line": 0, "character": 0 } }
            }]
        });
        assert!(parse_definition(&resp).is_none());
    }

    #[test]
    fn parse_definition_strips_library_prefix_from_path() {
        let resp = json!({
            "result": [{
                "uri": "file:///home/user/.rustup/toolchains/stable/library/core/src/num/mod.rs",
                "range": { "start": { "line": 0, "character": 0 }, "end": { "line": 0, "character": 0 } }
            }]
        });
        let def = parse_definition(&resp).unwrap();
        // path should start at "library/" not "/"
        assert!(def.path.starts_with("library/"));
        assert!(!def.path.starts_with('/'));
    }

    #[test]
    fn parse_definition_src_path_fallback() {
        // A third-party crate source — has /src/ but no /library/
        let resp = json!({
            "result": [{
                "uri": "file:///home/user/myproject/src/main.rs",
                "range": { "start": { "line": 5, "character": 0 }, "end": { "line": 5, "character": 0 } }
            }]
        });
        let def = parse_definition(&resp).unwrap();
        assert!(def.path.starts_with("src/"));
        assert_eq!(def.line, 5);
    }

    #[test]
    fn parse_definition_full_path_does_not_start_with_file_scheme() {
        let resp = json!({
            "result": [{
                "uri": "file:///home/user/project/src/lib.rs",
                "range": { "start": { "line": 1, "character": 0 }, "end": { "line": 1, "character": 0 } }
            }]
        });
        let def = parse_definition(&resp).unwrap();
        assert!(!def.full_path.starts_with("file://"));
        assert!(def.full_path.starts_with('/'));
    }
}