rust_meth_lib/analyzer/
session.rs1use 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
18pub 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 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 lsp.send(&LspTransport::initialized())?;
55
56 lsp.send(&LspTransport::did_open(&probe.src_uri(), &probe.source()?))?;
58
59 wait_for_indexing(&mut lsp)?;
61
62 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 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 parse::parse_methods(&completion_response)
83}
84
85pub 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 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 lsp.send(&LspTransport::initialized())?;
117 lsp.send(&LspTransport::did_open(&probe.src_uri(), &probe.source()?))?;
118
119 wait_for_indexing(&mut lsp)?;
121
122 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
143fn 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); lsp.recv_until(200, |msg| {
156 if start.elapsed() > timeout {
158 return Some(()); }
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 "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, G: FnMut(&Value) -> bool, {
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}