]> git.lizzy.rs Git - rust.git/blob - crates/proc_macro_api/src/process.rs
Reap proc macro server instances
[rust.git] / crates / proc_macro_api / src / process.rs
1 //! Handle process life-time and message passing for proc-macro client
2
3 use std::{
4     convert::{TryFrom, TryInto},
5     ffi::{OsStr, OsString},
6     io::{self, BufRead, BufReader, Write},
7     path::{Path, PathBuf},
8     process::{Child, Command, Stdio},
9     sync::{Arc, Weak},
10 };
11
12 use crossbeam_channel::{bounded, Receiver, Sender};
13 use stdx::JodChild;
14
15 use crate::{
16     msg::{ErrorCode, Message, Request, Response, ResponseError},
17     rpc::{ListMacrosResult, ListMacrosTask, ProcMacroKind},
18 };
19
20 #[derive(Debug, Default)]
21 pub(crate) struct ProcMacroProcessSrv {
22     inner: Weak<Sender<Task>>,
23 }
24
25 #[derive(Debug)]
26 pub(crate) struct ProcMacroProcessThread {
27     // XXX: drop order is significant
28     sender: Arc<Sender<Task>>,
29     handle: jod_thread::JoinHandle<()>,
30 }
31
32 impl ProcMacroProcessSrv {
33     pub(crate) fn run(
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)?;
38
39         let (task_tx, task_rx) = bounded(0);
40         let handle = jod_thread::spawn(move || {
41             client_loop(task_rx, process);
42         });
43
44         let task_tx = Arc::new(task_tx);
45         let srv = ProcMacroProcessSrv { inner: Arc::downgrade(&task_tx) };
46         let thread = ProcMacroProcessThread { handle, sender: task_tx };
47
48         Ok((thread, srv))
49     }
50
51     pub(crate) fn find_proc_macros(
52         &self,
53         dylib_path: &Path,
54     ) -> Result<Vec<(String, ProcMacroKind)>, tt::ExpansionError> {
55         let task = ListMacrosTask { lib: dylib_path.to_path_buf() };
56
57         let result: ListMacrosResult = self.send_task(Request::ListMacro(task))?;
58         Ok(result.macros)
59     }
60
61     pub(crate) fn send_task<R>(&self, req: Request) -> Result<R, tt::ExpansionError>
62     where
63         R: TryFrom<Response, Error = &'static str>,
64     {
65         let (result_tx, result_rx) = bounded(0);
66         let sender = match self.inner.upgrade() {
67             None => return Err(tt::ExpansionError::Unknown("proc macro process is closed".into())),
68             Some(it) => it,
69         };
70         sender
71             .send(Task { req, result_tx })
72             .map_err(|_| tt::ExpansionError::Unknown("proc macro server crashed".into()))?;
73
74         let res = result_rx
75             .recv()
76             .map_err(|_| tt::ExpansionError::Unknown("proc macro server crashed".into()))?;
77
78         match res {
79             Some(Response::Error(err)) => {
80                 return Err(tt::ExpansionError::ExpansionError(err.message));
81             }
82             Some(res) => Ok(res.try_into().map_err(|err| {
83                 tt::ExpansionError::Unknown(format!("Fail to get response, reason : {:#?} ", err))
84             })?),
85             None => Err(tt::ExpansionError::Unknown("Empty result".into())),
86         }
87     }
88 }
89
90 fn client_loop(task_rx: Receiver<Task>, mut process: Process) {
91     let (mut stdin, mut stdout) = process.stdio().expect("couldn't access child stdio");
92
93     for Task { req, result_tx } in task_rx {
94         match send_request(&mut stdin, &mut stdout, req) {
95             Ok(res) => result_tx.send(res).unwrap(),
96             Err(err) => {
97                 log::error!(
98                     "proc macro server crashed, server process state: {:?}, server request error: {:?}",
99                     process.child.try_wait(),
100                     err
101                 );
102                 let res = Response::Error(ResponseError {
103                     code: ErrorCode::ServerErrorEnd,
104                     message: "proc macro server crashed".into(),
105                 });
106                 result_tx.send(res.into()).unwrap();
107                 // Exit the thread.
108                 break;
109             }
110         }
111     }
112 }
113
114 struct Task {
115     req: Request,
116     result_tx: Sender<Option<Response>>,
117 }
118
119 struct Process {
120     child: JodChild,
121 }
122
123 impl Process {
124     fn run(
125         path: PathBuf,
126         args: impl IntoIterator<Item = impl AsRef<OsStr>>,
127     ) -> io::Result<Process> {
128         let args: Vec<OsString> = args.into_iter().map(|s| s.as_ref().into()).collect();
129         let child = JodChild(mk_child(&path, &args)?);
130         Ok(Process { child })
131     }
132
133     fn stdio(&mut self) -> Option<(impl Write, impl BufRead)> {
134         let stdin = self.child.stdin.take()?;
135         let stdout = self.child.stdout.take()?;
136         let read = BufReader::new(stdout);
137
138         Some((stdin, read))
139     }
140 }
141
142 fn mk_child(path: &Path, args: impl IntoIterator<Item = impl AsRef<OsStr>>) -> io::Result<Child> {
143     Command::new(&path)
144         .args(args)
145         .stdin(Stdio::piped())
146         .stdout(Stdio::piped())
147         .stderr(Stdio::inherit())
148         .spawn()
149 }
150
151 fn send_request(
152     mut writer: &mut impl Write,
153     mut reader: &mut impl BufRead,
154     req: Request,
155 ) -> io::Result<Option<Response>> {
156     req.write(&mut writer)?;
157     Ok(Response::read(&mut reader)?)
158 }