Unnamed repository; edit this file 'description' to name the repository.
Diffstat (limited to 'crates/proc-macro-api/src/process.rs')
-rw-r--r--crates/proc-macro-api/src/process.rs180
1 files changed, 88 insertions, 92 deletions
diff --git a/crates/proc-macro-api/src/process.rs b/crates/proc-macro-api/src/process.rs
index 95b12d0b24..7f0cd05c80 100644
--- a/crates/proc-macro-api/src/process.rs
+++ b/crates/proc-macro-api/src/process.rs
@@ -28,12 +28,18 @@ pub(crate) struct ProcMacroServerProcess {
exited: OnceLock<AssertUnwindSafe<ServerError>>,
}
-#[derive(Debug)]
-enum Protocol {
+#[derive(Debug, Clone)]
+pub(crate) enum Protocol {
LegacyJson { mode: SpanMode },
Postcard { mode: SpanMode },
}
+impl Default for Protocol {
+ fn default() -> Self {
+ Protocol::Postcard { mode: SpanMode::Id }
+ }
+}
+
/// Maintains the state of the proc-macro server process.
#[derive(Debug)]
struct ProcessSrvState {
@@ -49,54 +55,83 @@ impl ProcMacroServerProcess {
env: impl IntoIterator<
Item = (impl AsRef<std::ffi::OsStr>, &'a Option<impl 'a + AsRef<std::ffi::OsStr>>),
> + Clone,
+ protocol: Protocol,
) -> io::Result<ProcMacroServerProcess> {
- let create_srv = || {
- let mut process = Process::run(process_path, env.clone())?;
+ let mut srv = {
+ let mut process = match Process::run(process_path, env.clone(), &protocol) {
+ Ok(process) => process,
+ Err(e) => {
+ // fallback
+ if matches!(protocol, Protocol::Postcard { .. }) {
+ // retry with json
+ return Self::run(
+ process_path,
+ env,
+ Protocol::LegacyJson { mode: SpanMode::Id },
+ );
+ }
+ return Err(e);
+ }
+ };
let (stdin, stdout) = process.stdio().expect("couldn't access child stdio");
- io::Result::Ok(ProcMacroServerProcess {
+ ProcMacroServerProcess {
state: Mutex::new(ProcessSrvState { process, stdin, stdout }),
version: 0,
- protocol: Protocol::LegacyJson { mode: SpanMode::Id },
+ protocol: protocol.clone(),
exited: OnceLock::new(),
- })
+ }
};
- let mut srv = create_srv()?;
tracing::info!("sending proc-macro server version check");
- match srv.version_check() {
- Ok(v) if v > version::CURRENT_API_VERSION => {
- #[allow(clippy::disallowed_methods)]
- let process_version = Command::new(process_path)
- .arg("--version")
- .output()
- .map(|output| String::from_utf8_lossy(&output.stdout).trim().to_owned())
- .unwrap_or_else(|_| "unknown version".to_owned());
- Err(io::Error::other(format!(
- "Your installed proc-macro server is too new for your rust-analyzer. API version: {}, server version: {process_version}. \
- This will prevent proc-macro expansion from working. Please consider updating your rust-analyzer to ensure compatibility with your current toolchain.",
- version::CURRENT_API_VERSION
- )))
- }
- Ok(v) => {
- tracing::info!("Proc-macro server version: {v}");
- srv.version = v;
- if srv.version >= version::RUST_ANALYZER_SPAN_SUPPORT
- && let Ok(mode) = srv.enable_rust_analyzer_spans()
- {
- if srv.version >= version::POSTCARD_WIRE {
- srv.protocol = Protocol::Postcard { mode };
- } else {
- srv.protocol = Protocol::LegacyJson { mode };
- }
- }
- tracing::info!("Proc-macro server protocol: {:?}", srv.protocol);
- Ok(srv)
- }
+ let version = match srv.version_check() {
+ Ok(v) => v,
Err(e) => {
+ if matches!(protocol, Protocol::Postcard { .. }) {
+ // retry with json
+ return Self::run(
+ process_path,
+ env,
+ Protocol::LegacyJson { mode: SpanMode::Id },
+ );
+ }
+
tracing::info!(%e, "proc-macro version check failed");
- Err(io::Error::other(format!("proc-macro server version check failed: {e}")))
+ return Err(io::Error::other(format!(
+ "proc-macro server version check failed: {e}"
+ )));
}
+ };
+
+ if version > version::CURRENT_API_VERSION {
+ #[allow(clippy::disallowed_methods)]
+ let process_version = Command::new(process_path)
+ .arg("--version")
+ .output()
+ .map(|out| String::from_utf8_lossy(&out.stdout).trim().to_owned())
+ .unwrap_or_else(|_| "unknown version".to_owned());
+
+ return Err(io::Error::other(format!(
+ "Your installed proc-macro server is too new for your rust-analyzer. API version: {}, server version: {process_version}. \
+ This will prevent proc-macro expansion from working. Please consider updating your rust-analyzer to ensure compatibility with your current toolchain.",
+ version::CURRENT_API_VERSION
+ )));
+ }
+
+ tracing::info!("proc-macro server version: {version}");
+
+ srv.version = version;
+
+ if version >= version::RUST_ANALYZER_SPAN_SUPPORT
+ && let Ok(mode) = srv.enable_rust_analyzer_spans()
+ {
+ srv.protocol = match protocol {
+ Protocol::Postcard { .. } => Protocol::Postcard { mode },
+ Protocol::LegacyJson { .. } => Protocol::LegacyJson { mode },
+ };
}
+
+ tracing::info!("proc-macro server protocol: {:?}", srv.protocol);
+ Ok(srv)
}
/// Returns the server error if the process has exited.
@@ -148,18 +183,21 @@ impl ProcMacroServerProcess {
}
}
- pub(crate) fn send_task<Request, Response>(
+ pub(crate) fn send_task<Request, Response, Buf>(
&self,
serialize_req: impl FnOnce(
&mut dyn Write,
&mut dyn BufRead,
Request,
- &mut String,
+ &mut Buf,
) -> Result<Option<Response>, ServerError>,
req: Request,
- ) -> Result<Response, ServerError> {
+ ) -> Result<Response, ServerError>
+ where
+ Buf: Default,
+ {
let state = &mut *self.state.lock().unwrap();
- let mut buf = String::new();
+ let mut buf = Buf::default();
serialize_req(&mut state.stdin, &mut state.stdout, req, &mut buf)
.and_then(|res| {
res.ok_or_else(|| {
@@ -201,55 +239,6 @@ impl ProcMacroServerProcess {
}
})
}
-
- pub(crate) fn send_task_bin<Request, Response>(
- &self,
- serialize_req: impl FnOnce(
- &mut dyn Write,
- &mut dyn BufRead,
- Request,
- &mut Vec<u8>,
- ) -> Result<Option<Response>, ServerError>,
- req: Request,
- ) -> Result<Response, ServerError> {
- let state = &mut *self.state.lock().unwrap();
- let mut buf = Vec::<u8>::new();
- serialize_req(&mut state.stdin, &mut state.stdout, req, &mut buf)
- .and_then(|res| {
- res.ok_or_else(|| ServerError {
- message: "proc-macro server did not respond with data".to_owned(),
- io: Some(Arc::new(io::Error::new(
- io::ErrorKind::BrokenPipe,
- "proc-macro server did not respond with data",
- ))),
- })
- })
- .map_err(|e| {
- if e.io.as_ref().map(|it| it.kind()) == Some(io::ErrorKind::BrokenPipe) {
- match state.process.child.try_wait() {
- Ok(None) | Err(_) => e,
- Ok(Some(status)) => {
- let mut msg = String::new();
- if !status.success()
- && let Some(stderr) = state.process.child.stderr.as_mut()
- {
- _ = stderr.read_to_string(&mut msg);
- }
- let server_error = ServerError {
- message: format!(
- "proc-macro server exited with {status}{}{msg}",
- if msg.is_empty() { "" } else { ": " }
- ),
- io: None,
- };
- self.exited.get_or_init(|| AssertUnwindSafe(server_error)).0.clone()
- }
- }
- } else {
- e
- }
- })
- }
}
/// Manages the execution of the proc-macro server process.
@@ -265,8 +254,9 @@ impl Process {
env: impl IntoIterator<
Item = (impl AsRef<std::ffi::OsStr>, &'a Option<impl 'a + AsRef<std::ffi::OsStr>>),
>,
+ protocol: &Protocol,
) -> io::Result<Process> {
- let child = JodChild(mk_child(path, env)?);
+ let child = JodChild(mk_child(path, env, protocol)?);
Ok(Process { child })
}
@@ -286,9 +276,15 @@ fn mk_child<'a>(
extra_env: impl IntoIterator<
Item = (impl AsRef<std::ffi::OsStr>, &'a Option<impl 'a + AsRef<std::ffi::OsStr>>),
>,
+ protocol: &Protocol,
) -> io::Result<Child> {
#[allow(clippy::disallowed_methods)]
let mut cmd = Command::new(path);
+ if matches!(protocol, Protocol::LegacyJson { .. }) {
+ cmd.args(["--format", "json"]);
+ } else {
+ cmd.args(["--format", "postcard"]);
+ }
for env in extra_env {
match env {
(key, Some(val)) => cmd.env(key, val),