Skip to content

Commit 0ad6b6d

Browse files
bors[bot]Veetaha
andauthored
Merge #4061
4061: ra_proc_macro: cleanups here and there r=edwin0cheng a=Veetaha r? @edwin0cheng Co-authored-by: veetaha <[email protected]> Co-authored-by: Veetaha <[email protected]>
2 parents cd6d788 + fc460b1 commit 0ad6b6d

File tree

12 files changed

+142
-191
lines changed

12 files changed

+142
-191
lines changed

crates/ra_proc_macro/src/lib.rs

Lines changed: 7 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
//!
33
//! We separate proc-macro expanding logic to an extern program to allow
44
//! different implementations (e.g. wasm or dylib loading). And this crate
5-
//! is used to provide basic infrastructure for communication between two
5+
//! is used to provide basic infrastructure for communication between two
66
//! processes: Client (RA itself), Server (the external program)
77
88
mod rpc;
@@ -13,6 +13,7 @@ use process::{ProcMacroProcessSrv, ProcMacroProcessThread};
1313
use ra_tt::{SmolStr, Subtree};
1414
use std::{
1515
ffi::OsStr,
16+
io,
1617
path::{Path, PathBuf},
1718
sync::Arc,
1819
};
@@ -57,14 +58,10 @@ pub struct ProcMacroClient {
5758
}
5859

5960
impl ProcMacroClient {
60-
pub fn extern_process<I, S>(
61-
process_path: &Path,
62-
args: I,
63-
) -> Result<ProcMacroClient, std::io::Error>
64-
where
65-
I: IntoIterator<Item = S>,
66-
S: AsRef<OsStr>,
67-
{
61+
pub fn extern_process(
62+
process_path: PathBuf,
63+
args: impl IntoIterator<Item = impl AsRef<OsStr>>,
64+
) -> io::Result<ProcMacroClient> {
6865
let (thread, process) = ProcMacroProcessSrv::run(process_path, args)?;
6966
Ok(ProcMacroClient {
7067
kind: ProcMacroClientKind::Process { process: Arc::new(process), thread },
@@ -84,7 +81,7 @@ impl ProcMacroClient {
8481
ProcMacroClientKind::Process { process, .. } => {
8582
let macros = match process.find_proc_macros(dylib_path) {
8683
Err(err) => {
87-
eprintln!("Fail to find proc macro. Error: {:#?}", err);
84+
eprintln!("Failed to find proc macros. Error: {:#?}", err);
8885
return vec![];
8986
}
9087
Ok(macros) => macros,

crates/ra_proc_macro/src/msg.rs

Lines changed: 16 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
//! Defines messages for cross-process message based on `ndjson` wire protocol
1+
//! Defines messages for cross-process message passing based on `ndjson` wire protocol
22
33
use std::{
44
convert::TryFrom,
@@ -31,7 +31,7 @@ macro_rules! impl_try_from_response {
3131
fn try_from(value: Response) -> Result<Self, Self::Error> {
3232
match value {
3333
Response::$tag(res) => Ok(res),
34-
_ => Err("Fail to convert from response"),
34+
_ => Err(concat!("Failed to convert response to ", stringify!($tag))),
3535
}
3636
}
3737
}
@@ -53,18 +53,16 @@ pub enum ErrorCode {
5353
ExpansionError,
5454
}
5555

56-
pub trait Message: Sized + Serialize + DeserializeOwned {
57-
fn read(r: &mut impl BufRead) -> io::Result<Option<Self>> {
58-
let text = match read_json(r)? {
59-
None => return Ok(None),
60-
Some(text) => text,
61-
};
62-
let msg = serde_json::from_str(&text)?;
63-
Ok(Some(msg))
56+
pub trait Message: Serialize + DeserializeOwned {
57+
fn read(inp: &mut impl BufRead) -> io::Result<Option<Self>> {
58+
Ok(match read_json(inp)? {
59+
None => None,
60+
Some(text) => Some(serde_json::from_str(&text)?),
61+
})
6462
}
65-
fn write(self, w: &mut impl Write) -> io::Result<()> {
63+
fn write(self, out: &mut impl Write) -> io::Result<()> {
6664
let text = serde_json::to_string(&self)?;
67-
write_json(w, &text)
65+
write_json(out, &text)
6866
}
6967
}
7068

@@ -73,15 +71,12 @@ impl Message for Response {}
7371

7472
fn read_json(inp: &mut impl BufRead) -> io::Result<Option<String>> {
7573
let mut buf = String::new();
76-
if inp.read_line(&mut buf)? == 0 {
77-
return Ok(None);
78-
}
79-
// Remove ending '\n'
80-
let buf = &buf[..buf.len() - 1];
81-
if buf.is_empty() {
82-
return Ok(None);
83-
}
84-
Ok(Some(buf.to_string()))
74+
inp.read_line(&mut buf)?;
75+
buf.pop(); // Remove traling '\n'
76+
Ok(match buf.len() {
77+
0 => None,
78+
_ => Some(buf),
79+
})
8580
}
8681

8782
fn write_json(out: &mut impl Write, msg: &str) -> io::Result<()> {

crates/ra_proc_macro/src/process.rs

Lines changed: 13 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -45,24 +45,23 @@ impl Drop for Process {
4545
}
4646

4747
impl Process {
48-
fn run<I, S>(process_path: &Path, args: I) -> Result<Process, io::Error>
49-
where
50-
I: IntoIterator<Item = S>,
51-
S: AsRef<OsStr>,
52-
{
53-
let child = Command::new(process_path.clone())
48+
fn run(
49+
process_path: PathBuf,
50+
args: impl IntoIterator<Item = impl AsRef<OsStr>>,
51+
) -> io::Result<Process> {
52+
let child = Command::new(&process_path)
5453
.args(args)
5554
.stdin(Stdio::piped())
5655
.stdout(Stdio::piped())
5756
.stderr(Stdio::null())
5857
.spawn()?;
5958

60-
Ok(Process { path: process_path.into(), child })
59+
Ok(Process { path: process_path, child })
6160
}
6261

63-
fn restart(&mut self) -> Result<(), io::Error> {
62+
fn restart(&mut self) -> io::Result<()> {
6463
let _ = self.child.kill();
65-
self.child = Command::new(self.path.clone())
64+
self.child = Command::new(&self.path)
6665
.stdin(Stdio::piped())
6766
.stdout(Stdio::piped())
6867
.stderr(Stdio::null())
@@ -80,14 +79,10 @@ impl Process {
8079
}
8180

8281
impl ProcMacroProcessSrv {
83-
pub fn run<I, S>(
84-
process_path: &Path,
85-
args: I,
86-
) -> Result<(ProcMacroProcessThread, ProcMacroProcessSrv), io::Error>
87-
where
88-
I: IntoIterator<Item = S>,
89-
S: AsRef<OsStr>,
90-
{
82+
pub fn run(
83+
process_path: PathBuf,
84+
args: impl IntoIterator<Item = impl AsRef<OsStr>>,
85+
) -> io::Result<(ProcMacroProcessThread, ProcMacroProcessSrv)> {
9186
let process = Process::run(process_path, args)?;
9287

9388
let (task_tx, task_rx) = bounded(0);
@@ -201,7 +196,7 @@ fn send_request(
201196
mut writer: &mut impl Write,
202197
mut reader: &mut impl BufRead,
203198
req: Request,
204-
) -> Result<Option<Response>, io::Error> {
199+
) -> io::Result<Option<Response>> {
205200
req.write(&mut writer)?;
206201
Ok(Response::read(&mut reader)?)
207202
}

crates/ra_proc_macro/src/rpc.rs

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
1-
//! Data struture serialization related stuffs for RPC
1+
//! Data struture serialization related stuff for RPC
22
//!
3-
//! Define all necessary rpc serialization data structure,
4-
//! which include ra_tt related data and some task messages.
5-
//! Although adding Serialize and Deserialize trait to ra_tt directly seem to be much easier,
6-
//! we deliberately duplicate the ra_tt struct with #[serde(with = "XXDef")]
3+
//! Defines all necessary rpc serialization data structures,
4+
//! which includes `ra_tt` related data and some task messages.
5+
//! Although adding `Serialize` and `Deserialize` traits to `ra_tt` directly seems
6+
//! to be much easier, we deliberately duplicate `ra_tt` structs with `#[serde(with = "XXDef")]`
77
//! for separation of code responsibility.
88
99
use ra_tt::{
@@ -34,15 +34,15 @@ pub struct ListMacrosResult {
3434
pub struct ExpansionTask {
3535
/// Argument of macro call.
3636
///
37-
/// In custom derive that would be a struct or enum; in attribute-like macro - underlying
37+
/// In custom derive this will be a struct or enum; in attribute-like macro - underlying
3838
/// item; in function-like macro - the macro body.
3939
#[serde(with = "SubtreeDef")]
4040
pub macro_body: Subtree,
4141

42-
/// Names of macros to expand.
42+
/// Name of macro to expand.
4343
///
44-
/// In custom derive those are names of derived traits (`Serialize`, `Getters`, etc.). In
45-
/// attribute-like and functiona-like macros - single name of macro itself (`show_streams`).
44+
/// In custom derive this is the name of the derived trait (`Serialize`, `Getters`, etc.).
45+
/// In attribute-like and function-like macros - single name of macro itself (`show_streams`).
4646
pub macro_name: String,
4747

4848
/// Possible attributes for the attribute-like macros.

crates/ra_proc_macro_srv/src/cli.rs

Lines changed: 23 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -2,55 +2,43 @@
22
33
use crate::{expand_task, list_macros};
44
use ra_proc_macro::msg::{self, Message};
5-
65
use std::io;
76

8-
fn read_request() -> Result<Option<msg::Request>, io::Error> {
9-
let stdin = io::stdin();
10-
let mut stdin = stdin.lock();
11-
msg::Request::read(&mut stdin)
12-
}
13-
14-
fn write_response(res: Result<msg::Response, String>) -> Result<(), io::Error> {
15-
let msg: msg::Response = match res {
16-
Ok(res) => res,
17-
Err(err) => msg::Response::Error(msg::ResponseError {
18-
code: msg::ErrorCode::ExpansionError,
19-
message: err,
20-
}),
21-
};
22-
23-
let stdout = io::stdout();
24-
let mut stdout = stdout.lock();
25-
msg.write(&mut stdout)
26-
}
27-
287
pub fn run() {
298
loop {
309
let req = match read_request() {
3110
Err(err) => {
32-
eprintln!("Read message error on ra_proc_macro_srv: {}", err.to_string());
11+
eprintln!("Read message error on ra_proc_macro_srv: {}", err);
3312
continue;
3413
}
3514
Ok(None) => continue,
3615
Ok(Some(req)) => req,
3716
};
3817

39-
match req {
40-
msg::Request::ListMacro(task) => {
41-
if let Err(err) =
42-
write_response(list_macros(&task).map(|it| msg::Response::ListMacro(it)))
43-
{
44-
eprintln!("Write message error on list macro: {}", err);
45-
}
46-
}
18+
let res = match req {
19+
msg::Request::ListMacro(task) => Ok(msg::Response::ListMacro(list_macros(&task))),
4720
msg::Request::ExpansionMacro(task) => {
48-
if let Err(err) =
49-
write_response(expand_task(&task).map(|it| msg::Response::ExpansionMacro(it)))
50-
{
51-
eprintln!("Write message error on expansion macro: {}", err);
52-
}
21+
expand_task(&task).map(msg::Response::ExpansionMacro)
5322
}
23+
};
24+
25+
let msg = res.unwrap_or_else(|err| {
26+
msg::Response::Error(msg::ResponseError {
27+
code: msg::ErrorCode::ExpansionError,
28+
message: err,
29+
})
30+
});
31+
32+
if let Err(err) = write_response(msg) {
33+
eprintln!("Write message error: {}", err);
5434
}
5535
}
5636
}
37+
38+
fn read_request() -> io::Result<Option<msg::Request>> {
39+
msg::Request::read(&mut io::stdin().lock())
40+
}
41+
42+
fn write_response(msg: msg::Response) -> io::Result<()> {
43+
msg.write(&mut io::stdout().lock())
44+
}

0 commit comments

Comments
 (0)