remove envelop and keep it simple

This commit is contained in:
bit-aloo 2025-12-22 20:04:35 +05:30
parent 2a6cc5c9fc
commit a79fa074fe
No known key found for this signature in database
5 changed files with 94 additions and 139 deletions

View file

@ -12,8 +12,8 @@ use span::{FileId, Span};
use crate::{
Codec, ProcMacro, ProcMacroKind, ServerError,
bidirectional_protocol::msg::{
Envelope, ExpandMacro, ExpandMacroData, ExpnGlobals, Kind, Payload, Request,
Response, SubRequest, SubResponse,
BidirectionalMessage, ExpandMacro, ExpandMacroData, ExpnGlobals, Request, Response,
SubRequest, SubResponse,
},
legacy_protocol::{
SpanMode,
@ -37,10 +37,9 @@ pub fn run_conversation<C: Codec>(
writer: &mut dyn Write,
reader: &mut dyn BufRead,
buf: &mut C::Buf,
initial: Payload,
msg: BidirectionalMessage,
callbacks: &mut dyn ClientCallbacks,
) -> Result<Payload, ServerError> {
let msg = Envelope { kind: Kind::Request, payload: initial };
) -> Result<BidirectionalMessage, ServerError> {
let encoded = C::encode(&msg).map_err(wrap_encode)?;
C::write(writer, &encoded).map_err(wrap_io("failed to write initial request"))?;
@ -53,25 +52,21 @@ pub fn run_conversation<C: Codec>(
});
};
let msg: Envelope = C::decode(b).map_err(wrap_decode)?;
let msg: BidirectionalMessage = C::decode(b).map_err(wrap_decode)?;
match (msg.kind, msg.payload) {
(Kind::SubRequest, Payload::SubRequest(sr)) => {
match msg {
BidirectionalMessage::Response(response) => {
return Ok(BidirectionalMessage::Response(response));
}
BidirectionalMessage::SubRequest(sr) => {
let resp = callbacks.handle_sub_request(sr)?;
let reply =
Envelope { kind: Kind::SubResponse, payload: Payload::SubResponse(resp) };
let reply = BidirectionalMessage::SubResponse(resp);
let encoded = C::encode(&reply).map_err(wrap_encode)?;
C::write(writer, &encoded).map_err(wrap_io("failed to write sub-response"))?;
}
(Kind::Response, payload) => {
return Ok(payload);
}
(kind, payload) => {
_ => {
return Err(ServerError {
message: format!(
"unexpected message kind {:?} with payload {:?}",
kind, payload
),
message: format!("unexpected message {:?}", msg),
io: None,
});
}
@ -92,7 +87,7 @@ fn wrap_decode(err: io::Error) -> ServerError {
}
pub(crate) fn version_check(srv: &ProcMacroServerProcess) -> Result<u32, ServerError> {
let request = Payload::Request(Request::ApiVersionCheck {});
let request = BidirectionalMessage::Request(Request::ApiVersionCheck {});
struct NoCallbacks;
impl ClientCallbacks for NoCallbacks {
@ -106,7 +101,7 @@ pub(crate) fn version_check(srv: &ProcMacroServerProcess) -> Result<u32, ServerE
let response_payload = run_request(srv, request, &mut callbacks)?;
match response_payload {
Payload::Response(Response::ApiVersionCheck(version)) => Ok(version),
BidirectionalMessage::Response(Response::ApiVersionCheck(version)) => Ok(version),
other => {
Err(ServerError { message: format!("unexpected response: {:?}", other), io: None })
}
@ -117,8 +112,9 @@ pub(crate) fn version_check(srv: &ProcMacroServerProcess) -> Result<u32, ServerE
pub(crate) fn enable_rust_analyzer_spans(
srv: &ProcMacroServerProcess,
) -> Result<SpanMode, ServerError> {
let request =
Payload::Request(Request::SetConfig(ServerConfig { span_mode: SpanMode::RustAnalyzer }));
let request = BidirectionalMessage::Request(Request::SetConfig(ServerConfig {
span_mode: SpanMode::RustAnalyzer,
}));
struct NoCallbacks;
impl ClientCallbacks for NoCallbacks {
@ -132,7 +128,9 @@ pub(crate) fn enable_rust_analyzer_spans(
let response_payload = run_request(srv, request, &mut callbacks)?;
match response_payload {
Payload::Response(Response::SetConfig(ServerConfig { span_mode })) => Ok(span_mode),
BidirectionalMessage::Response(Response::SetConfig(ServerConfig { span_mode })) => {
Ok(span_mode)
}
_ => Err(ServerError { message: "unexpected response".to_owned(), io: None }),
}
}
@ -142,8 +140,9 @@ pub(crate) fn find_proc_macros(
srv: &ProcMacroServerProcess,
dylib_path: &AbsPath,
) -> Result<Result<Vec<(String, ProcMacroKind)>, String>, ServerError> {
let request =
Payload::Request(Request::ListMacros { dylib_path: dylib_path.to_path_buf().into() });
let request = BidirectionalMessage::Request(Request::ListMacros {
dylib_path: dylib_path.to_path_buf().into(),
});
struct NoCallbacks;
impl ClientCallbacks for NoCallbacks {
@ -157,7 +156,7 @@ pub(crate) fn find_proc_macros(
let response_payload = run_request(srv, request, &mut callbacks)?;
match response_payload {
Payload::Response(Response::ListMacros(it)) => Ok(it),
BidirectionalMessage::Response(Response::ListMacros(it)) => Ok(it),
_ => Err(ServerError { message: "unexpected response".to_owned(), io: None }),
}
}
@ -179,7 +178,7 @@ pub(crate) fn expand(
let def_site = span_data_table.insert_full(def_site).0;
let call_site = span_data_table.insert_full(call_site).0;
let mixed_site = span_data_table.insert_full(mixed_site).0;
let task = Payload::Request(Request::ExpandMacro(Box::new(ExpandMacro {
let task = BidirectionalMessage::Request(Request::ExpandMacro(Box::new(ExpandMacro {
data: ExpandMacroData {
macro_body: FlatTree::from_subtree(subtree, version, &mut span_data_table),
macro_name: proc_macro.name.to_string(),
@ -225,7 +224,7 @@ pub(crate) fn expand(
let response_payload = run_request(&proc_macro.process, task, &mut callbacks)?;
match response_payload {
Payload::Response(Response::ExpandMacro(it)) => Ok(it
BidirectionalMessage::Response(Response::ExpandMacro(it)) => Ok(it
.map(|tree| {
let mut expanded = FlatTree::to_subtree_resolved(tree, version, &span_data_table);
if proc_macro.needs_fixup_change() {
@ -234,7 +233,7 @@ pub(crate) fn expand(
expanded
})
.map_err(|msg| msg.0)),
Payload::Response(Response::ExpandMacroExtended(it)) => Ok(it
BidirectionalMessage::Response(Response::ExpandMacroExtended(it)) => Ok(it
.map(|resp| {
let mut expanded = FlatTree::to_subtree_resolved(
resp.tree,
@ -253,9 +252,9 @@ pub(crate) fn expand(
fn run_request(
srv: &ProcMacroServerProcess,
msg: Payload,
msg: BidirectionalMessage,
callbacks: &mut dyn ClientCallbacks,
) -> Result<Payload, ServerError> {
) -> Result<BidirectionalMessage, ServerError> {
if let Some(server_error) = srv.exited() {
return Err(server_error.clone());
}

View file

@ -8,20 +8,6 @@ use crate::{
legacy_protocol::msg::{FlatTree, Message, PanicMessage, ServerConfig},
};
#[derive(Debug, Serialize, Deserialize)]
pub struct Envelope {
pub kind: Kind,
pub payload: Payload,
}
#[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq)]
pub enum Kind {
Request,
Response,
SubRequest,
SubResponse,
}
#[derive(Debug, Serialize, Deserialize)]
pub enum SubRequest {
SourceText { file_id: u32, start: u32, end: u32 },
@ -33,7 +19,7 @@ pub enum SubResponse {
}
#[derive(Debug, Serialize, Deserialize)]
pub enum Payload {
pub enum BidirectionalMessage {
Request(Request),
Response(Response),
SubRequest(SubRequest),
@ -102,4 +88,4 @@ impl ExpnGlobals {
}
}
impl Message for Envelope {}
impl Message for BidirectionalMessage {}

View file

@ -4,9 +4,7 @@ use std::{
io::{self, BufRead, BufReader, Read, Write},
panic::AssertUnwindSafe,
process::{Child, ChildStdin, ChildStdout, Command, Stdio},
sync::{
Arc, Mutex, OnceLock,
},
sync::{Arc, Mutex, OnceLock},
};
use base_db::SourceDatabase;
@ -17,10 +15,7 @@ use stdx::JodChild;
use crate::{
Codec, ProcMacro, ProcMacroKind, ServerError,
bidirectional_protocol::{
self, ClientCallbacks,
msg::Payload,
},
bidirectional_protocol::{self, ClientCallbacks, msg::BidirectionalMessage},
legacy_protocol::{self, SpanMode},
version,
};
@ -71,7 +66,10 @@ impl ProcMacroServerProcess {
&& has_working_format_flag
{
&[
(Some("postcard-new"), Protocol::BidirectionalPostcardPrototype { mode: SpanMode::Id }),
(
Some("postcard-new"),
Protocol::BidirectionalPostcardPrototype { mode: SpanMode::Id },
),
(Some("postcard-legacy"), Protocol::LegacyPostcard { mode: SpanMode::Id }),
(Some("json-legacy"), Protocol::LegacyJson { mode: SpanMode::Id }),
]
@ -222,19 +220,17 @@ impl ProcMacroServerProcess {
current_dir,
)
}
Protocol::BidirectionalPostcardPrototype { .. } => {
bidirectional_protocol::expand(
proc_macro,
db,
subtree,
attr,
env,
def_site,
call_site,
mixed_site,
current_dir,
)
}
Protocol::BidirectionalPostcardPrototype { .. } => bidirectional_protocol::expand(
proc_macro,
db,
subtree,
attr,
env,
def_site,
call_site,
mixed_site,
current_dir,
),
}
}
@ -300,13 +296,11 @@ impl ProcMacroServerProcess {
pub(crate) fn run_bidirectional<C: Codec>(
&self,
initial: Payload,
initial: BidirectionalMessage,
callbacks: &mut dyn ClientCallbacks,
) -> Result<Payload, ServerError> {
) -> Result<BidirectionalMessage, ServerError> {
self.with_locked_io::<C, _>(|writer, reader, buf| {
bidirectional_protocol::run_conversation::<C>(
writer, reader, buf, initial, callbacks,
)
bidirectional_protocol::run_conversation::<C>(writer, reader, buf, initial, callbacks)
})
}
}

View file

@ -57,11 +57,7 @@ enum ProtocolFormat {
impl ValueEnum for ProtocolFormat {
fn value_variants<'a>() -> &'a [Self] {
&[
ProtocolFormat::JsonLegacy,
ProtocolFormat::PostcardLegacy,
ProtocolFormat::PostcardNew,
]
&[ProtocolFormat::JsonLegacy, ProtocolFormat::PostcardLegacy, ProtocolFormat::PostcardNew]
}
fn to_possible_value(&self) -> Option<clap::builder::PossibleValue> {

View file

@ -63,54 +63,46 @@ fn run_new<C: Codec>() -> io::Result<()> {
let mut span_mode = legacy::SpanMode::Id;
'outer: loop {
let req_opt = bidirectional::Envelope::read::<_, C>(&mut stdin, &mut buf)?;
let req_opt = bidirectional::BidirectionalMessage::read::<_, C>(&mut stdin, &mut buf)?;
let Some(req) = req_opt else {
break 'outer;
};
match (req.kind, req.payload) {
(bidirectional::Kind::Request, bidirectional::Payload::Request(request)) => {
match request {
bidirectional::Request::ListMacros { dylib_path } => {
let res = srv.list_macros(&dylib_path).map(|macros| {
macros
.into_iter()
.map(|(name, kind)| (name, macro_kind_to_api(kind)))
.collect()
});
match req {
bidirectional::BidirectionalMessage::Request(request) => match request {
bidirectional::Request::ListMacros { dylib_path } => {
let res = srv.list_macros(&dylib_path).map(|macros| {
macros
.into_iter()
.map(|(name, kind)| (name, macro_kind_to_api(kind)))
.collect()
});
send_response::<_, C>(
&mut stdout,
bidirectional::Response::ListMacros(res),
)?;
}
bidirectional::Request::ApiVersionCheck {} => {
send_response::<_, C>(
&mut stdout,
bidirectional::Response::ApiVersionCheck(CURRENT_API_VERSION),
)?;
}
bidirectional::Request::SetConfig(config) => {
span_mode = config.span_mode;
send_response::<_, C>(
&mut stdout,
bidirectional::Response::SetConfig(config),
)?;
}
bidirectional::Request::ExpandMacro(task) => {
handle_expand::<_, _, C>(
&srv,
&mut stdin,
&mut stdout,
&mut buf,
span_mode,
*task,
)?;
}
send_response::<_, C>(&mut stdout, bidirectional::Response::ListMacros(res))?;
}
}
bidirectional::Request::ApiVersionCheck {} => {
send_response::<_, C>(
&mut stdout,
bidirectional::Response::ApiVersionCheck(CURRENT_API_VERSION),
)?;
}
bidirectional::Request::SetConfig(config) => {
span_mode = config.span_mode;
send_response::<_, C>(&mut stdout, bidirectional::Response::SetConfig(config))?;
}
bidirectional::Request::ExpandMacro(task) => {
handle_expand::<_, _, C>(
&srv,
&mut stdin,
&mut stdout,
&mut buf,
span_mode,
*task,
)?;
}
},
_ => continue,
}
}
@ -265,11 +257,8 @@ fn handle_expand_ra<W: std::io::Write, R: std::io::BufRead, C: Codec>(
loop {
if let Ok(res) = result_rx.try_recv() {
send_response::<_, C>(
stdout,
bidirectional::Response::ExpandMacroExtended(res),
)
.unwrap();
send_response::<_, C>(stdout, bidirectional::Response::ExpandMacroExtended(res))
.unwrap();
break;
}
@ -282,7 +271,7 @@ fn handle_expand_ra<W: std::io::Write, R: std::io::BufRead, C: Codec>(
send_subrequest::<_, C>(stdout, from_srv_req(subreq)).unwrap();
let resp_opt = bidirectional::Envelope::read::<_, C>(stdin, buf).unwrap();
let resp_opt = bidirectional::BidirectionalMessage::read::<_, C>(stdin, buf).unwrap();
let resp = match resp_opt {
Some(env) => env,
None => {
@ -290,11 +279,8 @@ fn handle_expand_ra<W: std::io::Write, R: std::io::BufRead, C: Codec>(
}
};
match (resp.kind, resp.payload) {
(
bidirectional::Kind::SubResponse,
bidirectional::Payload::SubResponse(subresp),
) => {
match resp {
bidirectional::BidirectionalMessage::SubResponse(subresp) => {
let _ = subresp_tx.send(from_client_res(subresp));
}
_ => {
@ -466,10 +452,7 @@ fn send_response<W: std::io::Write, C: Codec>(
stdout: &mut W,
resp: bidirectional::Response,
) -> io::Result<()> {
let resp = bidirectional::Envelope {
kind: bidirectional::Kind::Response,
payload: bidirectional::Payload::Response(resp),
};
let resp = bidirectional::BidirectionalMessage::Response(resp);
resp.write::<W, C>(stdout)
}
@ -477,9 +460,6 @@ fn send_subrequest<W: std::io::Write, C: Codec>(
stdout: &mut W,
resp: bidirectional::SubRequest,
) -> io::Result<()> {
let resp = bidirectional::Envelope {
kind: bidirectional::Kind::SubRequest,
payload: bidirectional::Payload::SubRequest(resp),
};
let resp = bidirectional::BidirectionalMessage::SubRequest(resp);
resp.write::<W, C>(stdout)
}