Skip to main content

rust_meth_lib/analyzer/
session.rs

1//! Orchestrates `rust-analyzer` LSP sessions.
2//!
3//! Each public function here spins up an ephemeral `rust-analyzer` subprocess,
4//! drives it through the handshake, asks one question (completion or
5//! definition), and tears it back down. The two query functions are
6//! intentionally similar in shape, see the module-level note below.
7
8use std::collections::BTreeSet;
9use std::process::{Command, Stdio};
10use std::time;
11
12use serde_json::Value;
13
14use crate::error::Result;
15use crate::probe::Probe;
16use crate::{LspTransport, error};
17
18use super::parse::{self, Definition, Method};
19
20/// Queries `rust-analyzer` for all available methods on a given type type expression.
21///
22/// This spins up an ephemeral LSP session, generates a mock workspace via a [`Probe`],
23/// triggers a completion request at the appropriate line/column location, and parses the results.
24///
25/// # Environment Variables
26///
27/// * `RUST_METH_DEBUG` - If set, logs raw LSP method lifecycle events to standard error.
28///
29/// # Errors
30///
31/// Returns an error if:
32/// * Spawning the `rust-analyzer` subprocess fails.
33/// * The LSP server communication channels break.
34/// * The server returns an unexpectedly structured or malformed JSON payload.
35pub fn query_methods(
36    type_name: &str,
37    ra_path: &std::path::Path,
38    deps: Option<&str>,
39) -> Result<Vec<Method>> {
40    query_methods_inner(type_name, ra_path, deps)
41}
42
43/// Queries `rust-analyzer` for methods on multiple types in parallel.
44///
45/// Spawns one thread per query using [`std::thread::scope`]. Each query runs
46/// an independent `rust-analyzer` subprocess, so failures are per-type and do
47/// not abort the batch. Results are returned in the same order as `queries`.
48///
49/// # Example
50///
51/// ```no_run
52/// use rust_meth_lib::analyzer::{find_rust_analyzer, query_methods_batch};
53///
54/// let ra_path = find_rust_analyzer().unwrap();
55/// let queries = &[
56///     ("Vec<u8>", None),
57///     ("String", None),
58///     ("HashMap<String, u32>", None),
59/// ];
60/// for (type_name, result) in query_methods_batch(queries, &ra_path) {
61///     match result {
62///         Ok(methods) => println!("{type_name}: {} methods", methods.len()),
63///         Err(e) => eprintln!("{type_name}: {e}"),
64///     }
65/// }
66/// ```
67/// # Environment Variables
68///
69/// * `RUST_METH_DEBUG` - If set, logs raw LSP method lifecycle events to standard error.
70///
71/// ## Panics
72///
73/// Panics if any of the spawned background threads for processing queries panics
74/// or fails to join (e.g., due to an unhandled thread fault during the LSP session).
75#[allow(clippy::needless_collect)]
76#[must_use]
77pub fn query_methods_batch<'a>(
78    queries: &[(&'a str, Option<&'a str>)],
79    ra_path: &std::path::Path,
80) -> Vec<(&'a str, Result<Vec<Method>>)> {
81    std::thread::scope(|s| {
82        let handles: Vec<_> = queries
83            .iter()
84            .map(|&(type_name, deps)| {
85                s.spawn(move || (type_name, query_methods_inner(type_name, ra_path, deps)))
86            })
87            .collect(); // <-- all threads spawned before any are joined
88
89        handles
90            .into_iter()
91            .map(|h| h.join().expect("query thread should not panic"))
92            .collect()
93    })
94}
95
96/// Inner implementation shared by [`query_methods`] and [`query_methods_batch`].
97fn query_methods_inner(
98    type_name: &str,
99    ra_path: &std::path::Path,
100    deps: Option<&str>,
101) -> Result<Vec<Method>> {
102    let probe = Probe::new_with_deps(type_name, deps)?;
103    let mut child = Command::new(ra_path)
104        .stdin(Stdio::piped())
105        .stdout(Stdio::piped())
106        .stderr(Stdio::null())
107        .spawn()?;
108    let mut lsp = LspTransport::new(&mut child)?;
109    let pid = std::process::id();
110    // ── 1. initialize ────────────────────────────────────────────────────────
111    lsp.send(&LspTransport::initialize(pid, &probe.root_uri()))?;
112    lsp.recv_until(20, |msg| {
113        (msg["id"] == 1 && msg["result"].is_object()).then_some(())
114    })?;
115    // ── 2. initialized notification ──────────────────────────────────────────
116    lsp.send(&LspTransport::initialized())?;
117    // ── 3. didOpen ───────────────────────────────────────────────────────────
118    lsp.send(&LspTransport::did_open(&probe.src_uri(), &probe.source()?))?;
119    // ── 4. Wait for RA to finish indexing ────────────────────────────────────
120    let diag_msg = wait_for_indexing(&mut lsp, &probe.src_uri());
121    check_diagnostics_for_type_error(type_name, diag_msg.as_ref())?;
122    // ── 5. completion — retry until RA returns items ──────────────────────────
123    // RA may return isIncomplete+empty if it isn't fully ready yet.
124    let completion_response = retry_lsp_request(
125        &mut lsp,
126        20,
127        type_name,
128        |req_id| LspTransport::completion(req_id, &probe.src_uri(), probe.dot_line, probe.dot_col),
129        |msg| {
130            let items = msg["result"]["items"]
131                .as_array()
132                .cloned()
133                .unwrap_or_default();
134            if std::env::var("RUST_METH_DEBUG").is_ok() {
135                for item in &items {
136                    eprintln!(
137                        "[debug] completion label={:?} kind={:?}",
138                        item["label"], item["kind"]
139                    );
140                }
141            }
142            !items.is_empty() && !is_blanket_fallback(&items)
143        },
144    )?;
145    // ── 6. shutdown / exit ────────────────────────────────────────────────────
146    lsp.send(&LspTransport::shutdown(13))?;
147    let _ = lsp.recv_until(10, |msg| (msg["id"] == 13).then_some(()));
148    lsp.send(&LspTransport::exit())?;
149    let _ = child.wait();
150    // ── 7. Parse completion items ─────────────────────────────────────────────
151    parse::parse_methods(&completion_response)
152}
153
154/// Use diagnostics to find the error type
155fn check_diagnostics_for_type_error(type_name: &str, diag_msg: Option<&Value>) -> Result<()> {
156    let Some(msg) = diag_msg else { return Ok(()) };
157
158    let diagnostics = msg["params"]["diagnostics"]
159        .as_array()
160        .map_or(&[][..], Vec::as_slice);
161
162    for diag in diagnostics {
163        // severity 1 = Error in LSP
164        if diag["severity"].as_u64() != Some(1) {
165            continue;
166        }
167
168        // Feature-gated items resolve structurally but were compiled out,
169        // check this before the generic "not found" check, since the two
170        // are easy to conflate (both stem from E04xx "cannot find" codes).
171        if let Some(rendered) = diag["data"]["rendered"].as_str()
172            && (rendered.contains("configured out") || rendered.contains("gated behind"))
173        {
174            return Err(crate::error::RustMethError::FeatureGated {
175                type_name: type_name.to_string(),
176                message: rendered.to_string(),
177            });
178        }
179
180        let message = diag["message"].as_str().unwrap_or("");
181        // RA reports unknown types as "cannot find type `X` in this scope"
182        if message.contains("cannot find type") || message.contains("not found in") {
183            return Err(crate::error::RustMethError::TypeNotFound {
184                type_name: type_name.to_string(),
185                message: message.to_string(),
186            });
187        }
188    }
189    Ok(())
190}
191
192/// Queries `rust-analyzer` for the precise upstream source file declaration layout of a specific method.
193///
194/// Under the hood, this sets up a mock environment containing an isolated invocation of your method,
195/// queries `textDocument/definition`, and intercepts the target file location coordinates.
196///
197/// # Errors
198///
199/// Returns an error if the underlying LSP runtime breaks, or if `rust-analyzer` encounters structural errors.
200/// If a method exists but has no discoverable source code location definitions, it evaluates cleanly into `Ok(None)`.
201pub fn query_definition(
202    type_name: &str,
203    method_name: &str,
204    ra_path: &std::path::Path,
205    deps: Option<&str>,
206) -> Result<Option<Definition>> {
207    let probe = Probe::for_definition_with_deps(type_name, method_name, deps)?;
208    let mut child = Command::new(ra_path)
209        .stdin(Stdio::piped())
210        .stdout(Stdio::piped())
211        .stderr(Stdio::null())
212        .spawn()?;
213    let mut lsp = LspTransport::new(&mut child)?;
214    let pid = std::process::id();
215
216    // Send didOpen immediately after initialized, don't wait
217    lsp.send(&LspTransport::initialize(pid, &probe.root_uri()))?;
218    lsp.recv_until(5000, |msg| {
219        (msg["id"] == 1 && msg["result"].is_object()).then_some(())
220    })?;
221
222    // Send both notifications back-to-back (no wait needed)
223    lsp.send(&LspTransport::initialized())?;
224    lsp.send(&LspTransport::did_open(&probe.src_uri(), &probe.source()?))?;
225
226    // Now wait for indexing
227    wait_for_indexing(&mut lsp, &probe.src_uri());
228
229    // Retry on "content modified" - RA rejects requests while it's still
230    // processing the file. Same pattern as the completion retry loop.
231    let response = retry_lsp_request(
232        &mut lsp,
233        60,
234        type_name,
235        |req_id| LspTransport::definition(req_id, &probe.src_uri(), probe.dot_line, probe.dot_col),
236        |msg| {
237            let is_error = msg["error"]["code"].as_i64().is_some();
238            let is_null = msg["result"].is_null();
239            !is_error && !is_null
240        },
241    )?;
242
243    lsp.send(&LspTransport::shutdown(13))?;
244    let _ = lsp.recv_until(10, |msg| (msg["id"] == 13).then_some(()));
245    lsp.send(&LspTransport::exit())?;
246    let _ = child.wait();
247
248    Ok(parse::parse_definition(&response))
249}
250
251/// Wait until rust-analyzer is ready to serve completions.
252///
253/// RA doesn't always send $/progress. On fast/warm projects it skips straight
254/// to publishing diagnostics. We treat any of these as "ready":
255///   - $/progress with value.kind == "end"
256///   - experimental/serverStatus with quiescent == true
257///   - workspace/diagnostic/refresh
258///   - textDocument/publishDiagnostics
259fn wait_for_indexing(lsp: &mut LspTransport, probe_uri: &str) -> Option<Value> {
260    let debug = std::env::var("RUST_METH_DEBUG").is_ok();
261    // Accumulate the last publishDiagnostics message seen.
262    // Wait untill RA signals it's truly done.
263    let mut last_diag: Option<Value> = None;
264    let mut done = false;
265
266    let drain_start = time::Instant::now();
267    let _ = lsp.recv_until(20, |msg| {
268        // Timeout escape hatch
269        if drain_start.elapsed() > time::Duration::from_mins(2) {
270            return Some(());
271        }
272        let method = msg["method"].as_str().unwrap_or("");
273        if debug {
274            eprintln!("[debug] {method}");
275        }
276        match method {
277            "$/progress" => {
278                if msg["params"]["value"]["kind"] == "end" {
279                    done = true;
280                    Some(())
281                } else {
282                    None
283                }
284            }
285            "experimental/serverStatus" => {
286                if msg["params"]["quiescent"] == true {
287                    done = true;
288                    Some(())
289                } else {
290                    None
291                }
292            }
293
294            "workspace/diagnostic/refresh" => {
295                done = true;
296                Some(())
297            }
298            "textDocument/publishDiagnostics" => {
299                if debug {
300                    eprintln!(
301                        "[debug] diagnostics: {}",
302                        serde_json::to_string_pretty(&msg["params"]).unwrap_or_default()
303                    );
304                }
305
306                let is_probe_file = msg["params"]["uri"].as_str() == Some(probe_uri);
307                let has_type_error = is_probe_file
308                    && msg["params"]["diagnostics"]
309                        .as_array()
310                        .is_some_and(|diags| {
311                            diags.iter().any(|d| {
312                                d["severity"].as_u64() == Some(1)
313                                    && d["message"].as_str().is_some_and(|m| {
314                                        m.contains("cannot find type") || m.contains("not found in")
315                                    })
316                            })
317                        });
318                if has_type_error || (is_probe_file && last_diag.is_none()) {
319                    last_diag = Some(msg.clone());
320                }
321                None
322            }
323            _ => None,
324        }
325    });
326    let _ = done;
327
328    last_diag
329}
330
331fn retry_lsp_request<F, G>(
332    lsp: &mut LspTransport,
333    max_attempts: u64,
334    type_name: &str,
335    mut make_request: F,
336    mut is_success: G,
337) -> Result<Value>
338where
339    F: FnMut(u64) -> Value,   // takes req_id, returns the request to send
340    G: FnMut(&Value) -> bool, // returns true when response is good
341{
342    let start = time::Instant::now();
343    for attempt in 1..=max_attempts {
344        let req_id = attempt + 2;
345        lsp.send(&make_request(req_id))?;
346        let msg = lsp.recv_until(50, |msg| (msg["id"] == req_id).then(|| msg.clone()))?;
347        if is_success(&msg) {
348            return Ok(msg);
349        }
350        if attempt < max_attempts {
351            std::thread::sleep(time::Duration::from_millis(500));
352        }
353    }
354    Err(error::RustMethError::Timeout {
355        type_name: type_name.to_string(),
356        waited_secs: start.elapsed().as_secs(),
357    })
358}
359
360/// The generic blanket-impl completions RA returns for any type it can't
361/// fully resolve yet (still indexing) or can't resolve at all (unknown type).
362/// If completion results are *exactly* this set, treat it as "not ready":
363/// never treat it as a legitimate answer.
364const BLANKET_FALLBACK_METHODS: &[&str] = &[
365    "clamp",
366    "clone",
367    "clone_from",
368    "clone_into",
369    "cmp",
370    "eq",
371    "ge",
372    "gt",
373    "into",
374    "le",
375    "lt",
376    "max",
377    "min",
378    "ne",
379    "not",
380    "partial_cmp",
381    "to_owned",
382    "to_string",
383    "try_into",
384];
385
386fn is_blanket_fallback(items: &[Value]) -> bool {
387    let names: BTreeSet<&str> = items
388        .iter()
389        .filter_map(|i| i["label"].as_str())
390        .map(|label| label.split('(').next().unwrap_or(label).trim())
391        .collect();
392    let fallback: BTreeSet<&str> = BLANKET_FALLBACK_METHODS.iter().copied().collect();
393    !names.is_empty() && names == fallback
394}