1use std::{
4 fmt::Debug,
5 io::{self, BufRead, BufReader, Read, Write},
6 panic::AssertUnwindSafe,
7 process::{Child, ChildStdin, ChildStdout, Command, Stdio},
8 sync::{
9 Arc, Mutex, OnceLock,
10 atomic::{AtomicU32, Ordering},
11 },
12};
13
14use paths::AbsPath;
15use semver::Version;
16use span::Span;
17use stdx::JodChild;
18
19use crate::{
20 ProcMacroKind, ProtocolFormat,
21 bidirectional_protocol::{
22 self, SubCallback,
23 msg::{BidirectionalMessage, SubResponse},
24 reject_subrequests,
25 },
26 client::{ProcMacro, ServerError},
27 legacy_protocol::{self, msg::SpanMode},
28 version,
29};
30
31pub(crate) struct ProcMacroServerProcess {
33 state: Mutex<ProcessSrvState>,
36 version: u32,
37 protocol: Protocol,
38 exited: OnceLock<AssertUnwindSafe<ServerError>>,
40 active: AtomicU32,
41}
42
43impl std::fmt::Debug for ProcMacroServerProcess {
44 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
45 f.debug_struct("ProcMacroServerProcess")
46 .field("version", &self.version)
47 .field("protocol", &self.protocol)
48 .field("exited", &self.exited)
49 .finish()
50 }
51}
52
53#[derive(Debug, Clone)]
54pub(crate) enum Protocol {
55 LegacyJson { mode: SpanMode },
56 BidirectionalPostcardPrototype { mode: SpanMode },
57}
58
59pub trait ProcessExit: Send + Sync {
60 fn exit_err(&mut self) -> Option<ServerError>;
61}
62
63impl ProcessExit for Process {
64 fn exit_err(&mut self) -> Option<ServerError> {
65 match self.child.try_wait() {
66 Ok(None) | Err(_) => None,
67 Ok(Some(status)) => {
68 let mut msg = String::new();
69 if !status.success()
70 && let Some(stderr) = self.child.stderr.as_mut()
71 {
72 _ = stderr.read_to_string(&mut msg);
73 }
74 Some(ServerError {
75 message: format!(
76 "proc-macro server exited with {status}{}{msg}",
77 if msg.is_empty() { "" } else { ": " }
78 ),
79 io: None,
80 })
81 }
82 }
83 }
84}
85
86pub(crate) struct ProcessSrvState {
88 process: Box<dyn ProcessExit>,
89 stdin: Box<dyn Write + Send + Sync>,
90 stdout: Box<dyn BufRead + Send + Sync>,
91}
92
93impl ProcMacroServerProcess {
94 pub(crate) fn spawn<'a>(
96 process_path: &AbsPath,
97 env: impl IntoIterator<
98 Item = (impl AsRef<std::ffi::OsStr>, &'a Option<impl 'a + AsRef<std::ffi::OsStr>>),
99 > + Clone,
100 version: Option<&Version>,
101 ) -> io::Result<ProcMacroServerProcess> {
102 Self::run(
103 |format| {
104 let mut process = Process::run(
105 process_path,
106 env.clone(),
107 format.map(|format| format.to_string()).as_deref(),
108 )?;
109 let (stdin, stdout) = process.stdio().expect("couldn't access child stdio");
110
111 Ok((Box::new(process), Box::new(stdin), Box::new(stdout)))
112 },
113 version,
114 || {
115 #[expect(clippy::disallowed_methods)]
116 Command::new(process_path)
117 .arg("--version")
118 .output()
119 .map(|output| String::from_utf8_lossy(&output.stdout).trim().to_owned())
120 .unwrap_or_else(|_| "unknown version".to_owned())
121 },
122 )
123 }
124
125 pub(crate) fn run(
127 spawn: impl Fn(
128 Option<ProtocolFormat>,
129 ) -> io::Result<(
130 Box<dyn ProcessExit>,
131 Box<dyn Write + Send + Sync>,
132 Box<dyn BufRead + Send + Sync>,
133 )>,
134 version: Option<&Version>,
135 binary_server_version: impl Fn() -> String,
136 ) -> io::Result<ProcMacroServerProcess> {
137 const VERSION: Version = Version::new(1, 93, 0);
138 let has_working_format_flag = version.map_or(false, |v| {
140 if v.pre.as_str() == "nightly" { *v > VERSION } else { *v >= VERSION }
141 });
142
143 let formats: &[_] = if std::env::var_os("RUST_ANALYZER_USE_POSTCARD").is_some()
144 && has_working_format_flag
145 {
146 &[
147 Some(ProtocolFormat::BidirectionalPostcardPrototype),
148 Some(ProtocolFormat::JsonLegacy),
149 ]
150 } else {
151 &[None]
152 };
153
154 let mut err = None;
155 for &format in formats {
156 let create_srv = || {
157 let (process, stdin, stdout) = spawn(format)?;
158
159 io::Result::Ok(ProcMacroServerProcess {
160 state: Mutex::new(ProcessSrvState { process, stdin, stdout }),
161 version: 0,
162 protocol: match format {
163 Some(ProtocolFormat::BidirectionalPostcardPrototype) => {
164 Protocol::BidirectionalPostcardPrototype { mode: SpanMode::Id }
165 }
166 Some(ProtocolFormat::JsonLegacy) | None => {
167 Protocol::LegacyJson { mode: SpanMode::Id }
168 }
169 },
170 exited: OnceLock::new(),
171 active: AtomicU32::new(0),
172 })
173 };
174 let mut srv = create_srv()?;
175 tracing::info!("sending proc-macro server version check");
176 match srv.version_check(Some(&reject_subrequests)) {
177 Ok(v) if v > version::CURRENT_API_VERSION => {
178 let process_version = binary_server_version();
179 err = Some(io::Error::other(format!(
180 "Your installed proc-macro server is too new for your rust-analyzer. API version: {}, server version: {process_version}. \
181 This will prevent proc-macro expansion from working. Please consider updating your rust-analyzer to ensure compatibility with your current toolchain.",
182 version::CURRENT_API_VERSION
183 )));
184 }
185 Ok(v) => {
186 tracing::info!("Proc-macro server version: {v}");
187 srv.version = v;
188 if srv.version >= version::RUST_ANALYZER_SPAN_SUPPORT
189 && let Ok(new_mode) =
190 srv.enable_rust_analyzer_spans(Some(&reject_subrequests))
191 {
192 match &mut srv.protocol {
193 Protocol::LegacyJson { mode }
194 | Protocol::BidirectionalPostcardPrototype { mode } => *mode = new_mode,
195 }
196 }
197 tracing::info!("Proc-macro server protocol: {:?}", srv.protocol);
198 return Ok(srv);
199 }
200 Err(e) => {
201 tracing::info!(%e, "proc-macro version check failed");
202 err = Some(io::Error::other(format!(
203 "proc-macro server version check failed: {e}"
204 )))
205 }
206 }
207 }
208 Err(err.unwrap())
209 }
210
211 pub(crate) fn find_proc_macros(
213 &self,
214 dylib_path: &AbsPath,
215 ) -> Result<Result<Vec<(String, ProcMacroKind)>, String>, ServerError> {
216 match self.protocol {
217 Protocol::LegacyJson { .. } => legacy_protocol::find_proc_macros(self, dylib_path),
218
219 Protocol::BidirectionalPostcardPrototype { .. } => {
220 bidirectional_protocol::find_proc_macros(self, dylib_path, &|_| {
221 Ok(SubResponse::Cancel {
222 reason: String::from(
223 "Server should not do a sub request when loading proc-macros",
224 ),
225 })
226 })
227 }
228 }
229 }
230
231 pub(crate) fn exited(&self) -> Option<&ServerError> {
233 self.exited.get().map(|it| &it.0)
234 }
235
236 pub(crate) fn version(&self) -> u32 {
238 self.version
239 }
240
241 pub(crate) fn rust_analyzer_spans(&self) -> bool {
243 match self.protocol {
244 Protocol::LegacyJson { mode } | Protocol::BidirectionalPostcardPrototype { mode } => {
245 mode == SpanMode::RustAnalyzer
246 }
247 }
248 }
249
250 fn version_check(&self, callback: Option<SubCallback<'_>>) -> Result<u32, ServerError> {
252 match self.protocol {
253 Protocol::LegacyJson { .. } => legacy_protocol::version_check(self),
254 Protocol::BidirectionalPostcardPrototype { .. } => {
255 let cb = callback.expect("callback required for bidirectional protocol");
256 bidirectional_protocol::version_check(self, cb)
257 }
258 }
259 }
260
261 fn enable_rust_analyzer_spans(
263 &self,
264 callback: Option<SubCallback<'_>>,
265 ) -> Result<SpanMode, ServerError> {
266 match self.protocol {
267 Protocol::LegacyJson { .. } => legacy_protocol::enable_rust_analyzer_spans(self),
268 Protocol::BidirectionalPostcardPrototype { .. } => {
269 let cb = callback.expect("callback required for bidirectional protocol");
270 bidirectional_protocol::enable_rust_analyzer_spans(self, cb)
271 }
272 }
273 }
274
275 pub(crate) fn expand(
276 &self,
277 proc_macro: &ProcMacro,
278 subtree: tt::SubtreeView<'_>,
279 attr: Option<tt::SubtreeView<'_>>,
280 env: Vec<(String, String)>,
281 def_site: Span,
282 call_site: Span,
283 mixed_site: Span,
284 current_dir: String,
285 callback: Option<SubCallback<'_>>,
286 ) -> Result<Result<tt::TopSubtree, String>, ServerError> {
287 self.active.fetch_add(1, Ordering::AcqRel);
288 let result = match self.protocol {
289 Protocol::LegacyJson { .. } => legacy_protocol::expand(
290 proc_macro,
291 self,
292 subtree,
293 attr,
294 env,
295 def_site,
296 call_site,
297 mixed_site,
298 current_dir,
299 ),
300 Protocol::BidirectionalPostcardPrototype { .. } => bidirectional_protocol::expand(
301 proc_macro,
302 self,
303 subtree,
304 attr,
305 env,
306 def_site,
307 call_site,
308 mixed_site,
309 current_dir,
310 callback.expect("callback required for bidirectional protocol"),
311 ),
312 };
313
314 self.active.fetch_sub(1, Ordering::AcqRel);
315 result
316 }
317
318 pub(crate) fn send_task_legacy<Request, Response>(
319 &self,
320 send: impl FnOnce(
321 &mut dyn Write,
322 &mut dyn BufRead,
323 Request,
324 &mut String,
325 ) -> Result<Option<Response>, ServerError>,
326 req: Request,
327 ) -> Result<Response, ServerError> {
328 self.with_locked_io(String::new(), |writer, reader, buf| {
329 send(writer, reader, req, buf).and_then(|res| {
330 res.ok_or_else(|| {
331 let message = "proc-macro server did not respond with data".to_owned();
332 ServerError {
333 io: Some(Arc::new(io::Error::new(
334 io::ErrorKind::BrokenPipe,
335 message.clone(),
336 ))),
337 message,
338 }
339 })
340 })
341 })
342 }
343
344 fn with_locked_io<R, B>(
345 &self,
346 mut buf: B,
347 f: impl FnOnce(&mut dyn Write, &mut dyn BufRead, &mut B) -> Result<R, ServerError>,
348 ) -> Result<R, ServerError> {
349 let state = &mut *self.state.lock().unwrap();
350 f(&mut state.stdin, &mut state.stdout, &mut buf).map_err(|e| {
351 if e.io.as_ref().map(|it| it.kind()) == Some(io::ErrorKind::BrokenPipe) {
352 match state.process.exit_err() {
353 None => e,
354 Some(server_error) => {
355 self.exited.get_or_init(|| AssertUnwindSafe(server_error)).0.clone()
356 }
357 }
358 } else {
359 e
360 }
361 })
362 }
363
364 pub(crate) fn run_bidirectional(
365 &self,
366 initial: BidirectionalMessage,
367 callback: SubCallback<'_>,
368 ) -> Result<BidirectionalMessage, ServerError> {
369 self.with_locked_io(Vec::new(), |writer, reader, buf| {
370 bidirectional_protocol::run_conversation(writer, reader, buf, initial, callback)
371 })
372 }
373
374 pub(crate) fn number_of_active_req(&self) -> u32 {
375 self.active.load(Ordering::Acquire)
376 }
377}
378
379#[derive(Debug)]
381struct Process {
382 child: JodChild,
383}
384
385impl Process {
386 fn run<'a>(
388 path: &AbsPath,
389 env: impl IntoIterator<
390 Item = (impl AsRef<std::ffi::OsStr>, &'a Option<impl 'a + AsRef<std::ffi::OsStr>>),
391 >,
392 format: Option<&str>,
393 ) -> io::Result<Process> {
394 let child = JodChild(mk_child(path, env, format)?);
395 Ok(Process { child })
396 }
397
398 fn stdio(&mut self) -> Option<(ChildStdin, BufReader<ChildStdout>)> {
400 let stdin = self.child.stdin.take()?;
401 let stdout = self.child.stdout.take()?;
402 let read = BufReader::new(stdout);
403
404 Some((stdin, read))
405 }
406}
407
408fn mk_child<'a>(
410 path: &AbsPath,
411 extra_env: impl IntoIterator<
412 Item = (impl AsRef<std::ffi::OsStr>, &'a Option<impl 'a + AsRef<std::ffi::OsStr>>),
413 >,
414 format: Option<&str>,
415) -> io::Result<Child> {
416 #[allow(clippy::disallowed_methods)]
417 let mut cmd = Command::new(path);
418 for env in extra_env {
419 match env {
420 (key, Some(val)) => cmd.env(key, val),
421 (key, None) => cmd.env_remove(key),
422 };
423 }
424 if let Some(format) = format {
425 cmd.arg("--format");
426 cmd.arg(format);
427 }
428 cmd.env("RUST_ANALYZER_INTERNALS_DO_NOT_USE", "this is unstable")
429 .stdin(Stdio::piped())
430 .stdout(Stdio::piped())
431 .stderr(Stdio::inherit());
432 if cfg!(windows) {
433 let mut path_var = std::ffi::OsString::new();
434 path_var.push(path.parent().unwrap().parent().unwrap());
435 path_var.push("\\bin;");
436 path_var.push(std::env::var_os("PATH").unwrap_or_default());
437 cmd.env("PATH", path_var);
438 }
439 cmd.spawn()
440}