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::process::{Command, Stdio};
9
10use serde_json::Value;
11
12use crate::LspTransport;
13use crate::error::Result;
14use crate::probe::Probe;
15
16use super::parse::{self, Definition, Method};
17
18/// Queries `rust-analyzer` for all available methods on a given type type expression.
19///
20/// This spins up an ephemeral LSP session, generates a mock workspace via a [`Probe`],
21/// triggers a completion request at the appropriate line/column location, and parses the results.
22///
23/// # Environment Variables
24///
25/// * `RUST_METH_DEBUG` - If set, logs raw LSP method lifecycle events to standard error.
26///
27/// # Errors
28///
29/// Returns an error if:
30/// * Spawning the `rust-analyzer` subprocess fails.
31/// * The LSP server communication channels break.
32/// * The server returns an unexpectedly structured or malformed JSON payload.
33pub fn query_methods(
34    type_name: &str,
35    ra_path: &std::path::Path,
36    deps: Option<&str>,
37) -> Result<Vec<Method>> {
38    let probe = Probe::new_with_deps(type_name, deps)?;
39    let mut child = Command::new(ra_path)
40        .stdin(Stdio::piped())
41        .stdout(Stdio::piped())
42        .stderr(Stdio::null())
43        .spawn()?;
44    let mut lsp = LspTransport::new(&mut child)?;
45    let pid = std::process::id();
46
47    // ── 1. initialize ────────────────────────────────────────────────────────
48    lsp.send(&LspTransport::initialize(pid, &probe.root_uri()))?;
49    lsp.recv_until(20, |msg| {
50        (msg["id"] == 1 && msg["result"].is_object()).then_some(())
51    })?;
52
53    // ── 2. initialized notification ──────────────────────────────────────────
54    lsp.send(&LspTransport::initialized())?;
55
56    // ── 3. didOpen ───────────────────────────────────────────────────────────
57    lsp.send(&LspTransport::did_open(&probe.src_uri(), &probe.source()?))?;
58
59    // ── 4. Wait for RA to finish indexing ────────────────────────────────────
60    wait_for_indexing(&mut lsp)?;
61
62    // ── 5. completion — retry until RA returns items ──────────────────────────
63    // RA may return isIncomplete+empty if it isn't fully ready yet.
64    let completion_response = retry_lsp_request(
65        &mut lsp,
66        10,
67        |req_id| LspTransport::completion(req_id, &probe.src_uri(), probe.dot_line, probe.dot_col),
68        |msg| {
69            msg["result"]["items"]
70                .as_array()
71                .is_some_and(|a| !a.is_empty())
72        },
73    )?;
74
75    // ── 6. shutdown / exit ────────────────────────────────────────────────────
76    lsp.send(&LspTransport::shutdown(13))?;
77    let _ = lsp.recv_until(10, |msg| (msg["id"] == 13).then_some(()));
78    lsp.send(&LspTransport::exit())?;
79    let _ = child.wait();
80
81    // ── 7. Parse completion items ─────────────────────────────────────────────
82    parse::parse_methods(&completion_response)
83}
84
85/// Queries `rust-analyzer` for the precise upstream source file declaration layout of a specific method.
86///
87/// Under the hood, this sets up a mock environment containing an isolated invocation of your method,
88/// queries `textDocument/definition`, and intercepts the target file location coordinates.
89///
90/// # Errors
91///
92/// Returns an error if the underlying LSP runtime breaks, or if `rust-analyzer` encounters structural errors.
93/// If a method exists but has no discoverable source code location definitions, it evaluates cleanly into `Ok(None)`.
94pub fn query_definition(
95    type_name: &str,
96    method_name: &str,
97    ra_path: &std::path::Path,
98    deps: Option<&str>,
99) -> Result<Option<Definition>> {
100    let probe = Probe::for_definition_with_deps(type_name, method_name, deps)?;
101    let mut child = Command::new(ra_path)
102        .stdin(Stdio::piped())
103        .stdout(Stdio::piped())
104        .stderr(Stdio::null())
105        .spawn()?;
106    let mut lsp = LspTransport::new(&mut child)?;
107    let pid = std::process::id();
108
109    // Send didOpen immediately after initialized, don't wait
110    lsp.send(&LspTransport::initialize(pid, &probe.root_uri()))?;
111    lsp.recv_until(20, |msg| {
112        (msg["id"] == 1 && msg["result"].is_object()).then_some(())
113    })?;
114
115    // Send both notifications back-to-back (no wait needed)
116    lsp.send(&LspTransport::initialized())?;
117    lsp.send(&LspTransport::did_open(&probe.src_uri(), &probe.source()?))?;
118
119    // Now wait for indexing
120    wait_for_indexing(&mut lsp)?;
121
122    // Retry on "content modified" - RA rejects requests while it's still
123    // processing the file. Same pattern as the completion retry loop.
124    let response = retry_lsp_request(
125        &mut lsp,
126        10,
127        |req_id| LspTransport::definition(req_id, &probe.src_uri(), probe.dot_line, probe.dot_col),
128        |msg| {
129            let is_error = msg["error"]["code"].as_i64().is_some();
130            let is_null = msg["result"].is_null();
131            !is_error && !is_null
132        },
133    )?;
134
135    lsp.send(&LspTransport::shutdown(13))?;
136    let _ = lsp.recv_until(10, |msg| (msg["id"] == 13).then_some(()));
137    lsp.send(&LspTransport::exit())?;
138    let _ = child.wait();
139
140    Ok(parse::parse_definition(&response))
141}
142
143/// Wait until rust-analyzer is ready to serve completions.
144///
145/// RA doesn't always send $/progress. On fast/warm projects it skips straight
146/// to publishing diagnostics. We treat any of these as "ready":
147///   - $/progress with value.kind == "end"
148///   - experimental/serverStatus with quiescent == true
149///   - workspace/diagnostic/refresh
150///   - textDocument/publishDiagnostics
151fn wait_for_indexing(lsp: &mut LspTransport) -> Result<()> {
152    let debug = std::env::var("RUST_METH_DEBUG").is_ok();
153    let start = std::time::Instant::now();
154    let timeout = std::time::Duration::from_secs(10); // Hard timeout
155    lsp.recv_until(200, |msg| {
156        // Timeout escape hatch
157        if start.elapsed() > timeout {
158            return Some(()); // Give up and try anyway
159        }
160        let method = msg["method"].as_str().unwrap_or("");
161        if debug {
162            eprintln!("[debug] {method}");
163        }
164        match method {
165            "$/progress" => {
166                if msg["params"]["value"]["kind"] == "end" {
167                    Some(())
168                } else {
169                    None
170                }
171            }
172            "experimental/serverStatus" => {
173                if msg["params"]["quiescent"] == true {
174                    Some(())
175                } else {
176                    None
177                }
178            }
179            // These are strong signals that indexing is done
180            "textDocument/publishDiagnostics" | "workspace/diagnostic/refresh" => Some(()),
181            _ => None,
182        }
183    })
184    .or(Ok(()))
185}
186
187fn retry_lsp_request<F, G>(
188    lsp: &mut LspTransport,
189    max_attempts: u64,
190    mut make_request: F,
191    mut is_success: G,
192) -> Result<Value>
193where
194    F: FnMut(u64) -> Value,   // takes req_id, returns the request to send
195    G: FnMut(&Value) -> bool, // returns true when response is good
196{
197    let mut result = Value::Null;
198    for attempt in 1..=max_attempts {
199        let req_id = attempt + 2;
200        lsp.send(&make_request(req_id))?;
201        let msg = lsp.recv_until(50, |msg| (msg["id"] == req_id).then(|| msg.clone()))?;
202        if is_success(&msg) {
203            result = msg;
204            break;
205        }
206        if attempt < max_attempts {
207            if std::env::var("RUST_METH_DEBUG").is_ok() {
208                eprintln!("(attempt {attempt}: not ready, retrying…)");
209            }
210            std::thread::sleep(std::time::Duration::from_millis(500));
211        }
212    }
213    Ok(result)
214}