1 //! Handle process life-time and message passing for proc-macro client
4 convert::{TryFrom, TryInto},
5 ffi::{OsStr, OsString},
6 io::{self, BufRead, BufReader, Write},
8 process::{Child, Command, Stdio},
12 use crossbeam_channel::{bounded, Receiver, Sender};
16 msg::{ErrorCode, Message, Request, Response, ResponseError},
17 rpc::{ListMacrosResult, ListMacrosTask, ProcMacroKind},
20 #[derive(Debug, Default)]
21 pub(crate) struct ProcMacroProcessSrv {
22 inner: Weak<Sender<Task>>,
26 pub(crate) struct ProcMacroProcessThread {
27 // XXX: drop order is significant
28 sender: Arc<Sender<Task>>,
29 handle: jod_thread::JoinHandle<()>,
32 impl ProcMacroProcessSrv {
34 process_path: PathBuf,
35 args: impl IntoIterator<Item = impl AsRef<OsStr>>,
36 ) -> io::Result<(ProcMacroProcessThread, ProcMacroProcessSrv)> {
37 let process = Process::run(process_path, args)?;
39 let (task_tx, task_rx) = bounded(0);
40 let handle = jod_thread::Builder::new()
41 .name("ProcMacroClientThread".to_owned())
43 client_loop(task_rx, process);
45 .expect("failed to spawn thread");
47 let task_tx = Arc::new(task_tx);
48 let srv = ProcMacroProcessSrv { inner: Arc::downgrade(&task_tx) };
49 let thread = ProcMacroProcessThread { handle, sender: task_tx };
54 pub(crate) fn find_proc_macros(
57 ) -> Result<Vec<(String, ProcMacroKind)>, tt::ExpansionError> {
58 let task = ListMacrosTask { lib: dylib_path.to_path_buf() };
60 let result: ListMacrosResult = self.send_task(Request::ListMacro(task))?;
64 pub(crate) fn send_task<R>(&self, req: Request) -> Result<R, tt::ExpansionError>
66 R: TryFrom<Response, Error = &'static str>,
68 let (result_tx, result_rx) = bounded(0);
69 let sender = match self.inner.upgrade() {
70 None => return Err(tt::ExpansionError::Unknown("proc macro process is closed".into())),
74 .send(Task { req, result_tx })
75 .map_err(|_| tt::ExpansionError::Unknown("proc macro server crashed".into()))?;
79 .map_err(|_| tt::ExpansionError::Unknown("proc macro server crashed".into()))?;
82 Some(Response::Error(err)) => Err(tt::ExpansionError::ExpansionError(err.message)),
83 Some(res) => Ok(res.try_into().map_err(|err| {
84 tt::ExpansionError::Unknown(format!("Fail to get response, reason : {:#?} ", err))
86 None => Err(tt::ExpansionError::Unknown("Empty result".into())),
91 fn client_loop(task_rx: Receiver<Task>, mut process: Process) {
92 let (mut stdin, mut stdout) = process.stdio().expect("couldn't access child stdio");
94 let mut buf = String::new();
96 for Task { req, result_tx } in task_rx {
97 match send_request(&mut stdin, &mut stdout, req, &mut buf) {
98 Ok(res) => result_tx.send(res).unwrap(),
101 "proc macro server crashed, server process state: {:?}, server request error: {:?}",
102 process.child.try_wait(),
105 let res = Response::Error(ResponseError {
106 code: ErrorCode::ServerErrorEnd,
107 message: "proc macro server crashed".into(),
109 result_tx.send(res.into()).unwrap();
119 result_tx: Sender<Option<Response>>,
129 args: impl IntoIterator<Item = impl AsRef<OsStr>>,
130 ) -> io::Result<Process> {
131 let args: Vec<OsString> = args.into_iter().map(|s| s.as_ref().into()).collect();
132 let child = JodChild(mk_child(&path, &args)?);
133 Ok(Process { child })
136 fn stdio(&mut self) -> Option<(impl Write, impl BufRead)> {
137 let stdin = self.child.stdin.take()?;
138 let stdout = self.child.stdout.take()?;
139 let read = BufReader::new(stdout);
145 fn mk_child(path: &Path, args: impl IntoIterator<Item = impl AsRef<OsStr>>) -> io::Result<Child> {
148 .stdin(Stdio::piped())
149 .stdout(Stdio::piped())
150 .stderr(Stdio::inherit())
155 mut writer: &mut impl Write,
156 mut reader: &mut impl BufRead,
159 ) -> io::Result<Option<Response>> {
160 req.write(&mut writer)?;
161 Response::read(&mut reader, buf)