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    use crate::probe::cache::ra_version;
103    use crate::results_cache::{load_results, save_results};
104
105    // Infer effective deps the same way Probe does, so the cache key matches.
106    let effective_deps = deps.map(str::to_owned).or_else(|| {
107        if type_name.contains("::")
108            && type_name
109                .split("::")
110                .next()
111                .and_then(|s| s.chars().next())
112                .is_some_and(|c| c.is_ascii_lowercase())
113        {
114            let crate_name = type_name.split("::").next().unwrap_or("");
115            Some(format!(r#"{crate_name} = "*""#))
116        } else {
117            None
118        }
119    });
120
121    let ra_version = ra_version(ra_path);
122    if let Some(methods) = load_results(type_name, effective_deps.as_deref(), &ra_version) {
123        return Ok(methods);
124    }
125
126    let probe = Probe::new_with_deps_cached(type_name, deps, ra_path)?;
127    let mut child = Command::new(ra_path)
128        .stdin(Stdio::piped())
129        .stdout(Stdio::piped())
130        .stderr(Stdio::null())
131        .spawn()?;
132    let mut lsp = LspTransport::new(&mut child)?;
133    let pid = std::process::id();
134
135    lsp.send(&LspTransport::initialize(pid, &probe.root_uri()))?;
136    lsp.recv_until(20, |msg| {
137        (msg["id"] == 1 && msg["result"].is_object()).then_some(())
138    })?;
139
140    lsp.send(&LspTransport::initialized())?;
141
142    lsp.send(&LspTransport::did_open(&probe.src_uri(), &probe.source()?))?;
143
144    let diag_msg = wait_for_indexing(&mut lsp, &probe.src_uri());
145    check_diagnostics_for_type_error(type_name, diag_msg.as_ref())?;
146
147    // RA may return isIncomplete+empty if it isn't fully ready yet.
148    let completion_response = retry_lsp_request(
149        &mut lsp,
150        20,
151        type_name,
152        |req_id| LspTransport::completion(req_id, &probe.src_uri(), probe.dot_line, probe.dot_col),
153        |msg| {
154            let items = msg["result"]["items"]
155                .as_array()
156                .cloned()
157                .unwrap_or_default();
158            if std::env::var("RUST_METH_DEBUG").is_ok() {
159                for item in &items {
160                    eprintln!(
161                        "[debug] completion label={:?} kind={:?}",
162                        item["label"], item["kind"]
163                    );
164                }
165            }
166            !items.is_empty() && !is_blanket_fallback(&items)
167        },
168    )?;
169
170    lsp.send(&LspTransport::shutdown(13))?;
171    let _ = lsp.recv_until(10, |msg| (msg["id"] == 13).then_some(()));
172    lsp.send(&LspTransport::exit())?;
173    let _ = child.wait();
174
175    let methods = parse::parse_methods(&completion_response)?;
176    save_results(type_name, effective_deps.as_deref(), &ra_version, &methods);
177    Ok(methods)
178}
179
180/// Use diagnostics to find the error type
181fn check_diagnostics_for_type_error(type_name: &str, diag_msg: Option<&Value>) -> Result<()> {
182    let Some(msg) = diag_msg else { return Ok(()) };
183
184    let diagnostics = msg["params"]["diagnostics"]
185        .as_array()
186        .map_or(&[][..], Vec::as_slice);
187
188    for diag in diagnostics {
189        // severity 1 = Error in LSP
190        if diag["severity"].as_u64() != Some(1) {
191            continue;
192        }
193
194        // Feature-gated items resolve structurally but were compiled out,
195        // check this before the generic "not found" check, since the two
196        // are easy to conflate (both stem from E04xx "cannot find" codes).
197        if let Some(rendered) = diag["data"]["rendered"].as_str()
198            && (rendered.contains("configured out") || rendered.contains("gated behind"))
199        {
200            return Err(crate::error::RustMethError::FeatureGated {
201                type_name: type_name.to_string(),
202                message: rendered.to_string(),
203            });
204        }
205
206        let message = diag["message"].as_str().unwrap_or("");
207        // RA reports unknown types as "cannot find type `X` in this scope"
208        if message.contains("cannot find type") || message.contains("not found in") {
209            return Err(crate::error::RustMethError::TypeNotFound {
210                type_name: type_name.to_string(),
211                message: message.to_string(),
212            });
213        }
214    }
215    Ok(())
216}
217
218/// Queries `rust-analyzer` for the precise upstream source file declaration layout of a specific method.
219///
220/// Under the hood, this sets up a mock environment containing an isolated invocation of your method,
221/// queries `textDocument/definition`, and intercepts the target file location coordinates.
222///
223/// # Errors
224///
225/// Returns an error if the underlying LSP runtime breaks, or if `rust-analyzer` encounters structural errors.
226/// If a method exists but has no discoverable source code location definitions, it evaluates cleanly into `Ok(None)`.
227pub fn query_definition(
228    type_name: &str,
229    method_name: &str,
230    ra_path: &std::path::Path,
231    deps: Option<&str>,
232) -> Result<Option<Definition>> {
233    let probe = Probe::for_definition_with_deps_cached(type_name, method_name, deps, ra_path)?;
234    let mut child = Command::new(ra_path)
235        .stdin(Stdio::piped())
236        .stdout(Stdio::piped())
237        .stderr(Stdio::null())
238        .spawn()?;
239    let mut lsp = LspTransport::new(&mut child)?;
240    let pid = std::process::id();
241
242    // Send didOpen immediately after initialized, don't wait
243    lsp.send(&LspTransport::initialize(pid, &probe.root_uri()))?;
244    lsp.recv_until(5000, |msg| {
245        (msg["id"] == 1 && msg["result"].is_object()).then_some(())
246    })?;
247
248    // Send both notifications back-to-back (no wait needed)
249    lsp.send(&LspTransport::initialized())?;
250    lsp.send(&LspTransport::did_open(&probe.src_uri(), &probe.source()?))?;
251
252    // Now wait for indexing
253    wait_for_indexing(&mut lsp, &probe.src_uri());
254
255    // Retry on "content modified" - RA rejects requests while it's still
256    // processing the file. Same pattern as the completion retry loop.
257    let response = retry_lsp_request(
258        &mut lsp,
259        60,
260        type_name,
261        |req_id| LspTransport::definition(req_id, &probe.src_uri(), probe.dot_line, probe.dot_col),
262        |msg| {
263            let is_error = msg["error"]["code"].as_i64().is_some();
264            let is_null = msg["result"].is_null();
265            !is_error && !is_null
266        },
267    )?;
268
269    lsp.send(&LspTransport::shutdown(13))?;
270    let _ = lsp.recv_until(10, |msg| (msg["id"] == 13).then_some(()));
271    lsp.send(&LspTransport::exit())?;
272    let _ = child.wait();
273
274    Ok(parse::parse_definition(&response))
275}
276
277/// Wait until rust-analyzer is ready to serve completions.
278///
279/// RA doesn't always send $/progress. On fast/warm projects it skips straight
280/// to publishing diagnostics. We treat any of these as "ready":
281///   - $/progress with value.kind == "end"
282///   - experimental/serverStatus with quiescent == true
283///   - workspace/diagnostic/refresh
284///   - textDocument/publishDiagnostics
285fn wait_for_indexing(lsp: &mut LspTransport, probe_uri: &str) -> Option<Value> {
286    let debug = std::env::var("RUST_METH_DEBUG").is_ok();
287    // Accumulate the last publishDiagnostics message seen.
288    // Wait untill RA signals it's truly done.
289    let mut last_diag: Option<Value> = None;
290    let mut done = false;
291
292    let drain_start = time::Instant::now();
293    let _ = lsp.recv_until(20, |msg| {
294        // Timeout escape hatch
295        if drain_start.elapsed() > time::Duration::from_mins(2) {
296            return Some(());
297        }
298        let method = msg["method"].as_str().unwrap_or("");
299        if debug {
300            eprintln!("[debug] {method}");
301        }
302        match method {
303            "$/progress" => {
304                if msg["params"]["value"]["kind"] == "end" {
305                    done = true;
306                    Some(())
307                } else {
308                    None
309                }
310            }
311            "experimental/serverStatus" => {
312                if msg["params"]["quiescent"] == true {
313                    done = true;
314                    Some(())
315                } else {
316                    None
317                }
318            }
319
320            "workspace/diagnostic/refresh" => {
321                done = true;
322                Some(())
323            }
324            "textDocument/publishDiagnostics" => {
325                if debug {
326                    eprintln!(
327                        "[debug] diagnostics: {}",
328                        serde_json::to_string_pretty(&msg["params"]).unwrap_or_default()
329                    );
330                }
331
332                let is_probe_file = msg["params"]["uri"].as_str() == Some(probe_uri);
333                let has_type_error = is_probe_file
334                    && msg["params"]["diagnostics"]
335                        .as_array()
336                        .is_some_and(|diags| {
337                            diags.iter().any(|d| {
338                                d["severity"].as_u64() == Some(1)
339                                    && d["message"].as_str().is_some_and(|m| {
340                                        m.contains("cannot find type") || m.contains("not found in")
341                                    })
342                            })
343                        });
344                if has_type_error || (is_probe_file && last_diag.is_none()) {
345                    last_diag = Some(msg.clone());
346                }
347                None
348            }
349            _ => None,
350        }
351    });
352    let _ = done;
353
354    last_diag
355}
356
357fn retry_lsp_request<F, G>(
358    lsp: &mut LspTransport,
359    max_attempts: u64,
360    type_name: &str,
361    mut make_request: F,
362    mut is_success: G,
363) -> Result<Value>
364where
365    F: FnMut(u64) -> Value,   // takes req_id, returns the request to send
366    G: FnMut(&Value) -> bool, // returns true when response is good
367{
368    let start = time::Instant::now();
369    for attempt in 1..=max_attempts {
370        let req_id = attempt + 2;
371        lsp.send(&make_request(req_id))?;
372        let msg = lsp.recv_until(50, |msg| (msg["id"] == req_id).then(|| msg.clone()))?;
373        if is_success(&msg) {
374            return Ok(msg);
375        }
376        if attempt < max_attempts {
377            std::thread::sleep(time::Duration::from_millis(500));
378        }
379    }
380    Err(error::RustMethError::Timeout {
381        type_name: type_name.to_string(),
382        waited_secs: start.elapsed().as_secs(),
383    })
384}
385
386/// The generic blanket-impl completions RA returns for any type it can't
387/// fully resolve yet (still indexing) or can't resolve at all (unknown type).
388/// If completion results are *exactly* this set, treat it as "not ready":
389/// never treat it as a legitimate answer.
390const BLANKET_FALLBACK_METHODS: &[&str] = &[
391    "clamp",
392    "clone",
393    "clone_from",
394    "clone_into",
395    "cmp",
396    "eq",
397    "ge",
398    "gt",
399    "into",
400    "le",
401    "lt",
402    "max",
403    "min",
404    "ne",
405    "not",
406    "partial_cmp",
407    "to_owned",
408    "to_string",
409    "try_into",
410];
411
412fn is_blanket_fallback(items: &[Value]) -> bool {
413    let names: BTreeSet<&str> = items
414        .iter()
415        .filter_map(|i| i["label"].as_str())
416        .map(|label| label.split('(').next().unwrap_or(label).trim())
417        .collect();
418    let fallback: BTreeSet<&str> = BLANKET_FALLBACK_METHODS.iter().copied().collect();
419    !names.is_empty() && names == fallback
420}