]> git.lizzy.rs Git - rust.git/blob - crates/proc_macro_srv/src/proc_macro_nightly/bridge/server.rs
check rustc major version == 1 not < 1
[rust.git] / crates / proc_macro_srv / src / proc_macro_nightly / bridge / server.rs
1 //! lib-proc-macro server-side traits
2 //!
3 //! Copy from <https://github.com/rust-lang/rust/blob/6050e523bae6de61de4e060facc43dc512adaccd/src/libproc_macro/bridge/server.rs>
4 //! augmented with removing unstable features
5
6 use super::*;
7
8 // FIXME(eddyb) generate the definition of `HandleStore` in `server.rs`.
9 use super::client::HandleStore;
10
11 /// Declare an associated item of one of the traits below, optionally
12 /// adjusting it (i.e., adding bounds to types and default bodies to methods).
13 macro_rules! associated_item {
14     (type FreeFunctions) =>
15         (type FreeFunctions: 'static;);
16     (type TokenStream) =>
17         (type TokenStream: 'static + Clone;);
18     (type TokenStreamBuilder) =>
19         (type TokenStreamBuilder: 'static;);
20     (type TokenStreamIter) =>
21         (type TokenStreamIter: 'static + Clone;);
22     (type Group) =>
23         (type Group: 'static + Clone;);
24     (type Punct) =>
25         (type Punct: 'static + Copy + Eq + Hash;);
26     (type Ident) =>
27         (type Ident: 'static + Copy + Eq + Hash;);
28     (type Literal) =>
29         (type Literal: 'static + Clone;);
30     (type SourceFile) =>
31         (type SourceFile: 'static + Clone;);
32     (type MultiSpan) =>
33         (type MultiSpan: 'static;);
34     (type Diagnostic) =>
35         (type Diagnostic: 'static;);
36     (type Span) =>
37         (type Span: 'static + Copy + Eq + Hash;);
38     (fn drop(&mut self, $arg:ident: $arg_ty:ty)) =>
39         (fn drop(&mut self, $arg: $arg_ty) { mem::drop($arg) });
40     (fn clone(&mut self, $arg:ident: $arg_ty:ty) -> $ret_ty:ty) =>
41         (fn clone(&mut self, $arg: $arg_ty) -> $ret_ty { $arg.clone() });
42     ($($item:tt)*) => ($($item)*;)
43 }
44
45 macro_rules! declare_server_traits {
46     ($($name:ident {
47         $(fn $method:ident($($arg:ident: $arg_ty:ty),* $(,)?) $(-> $ret_ty:ty)?;)*
48     }),* $(,)?) => {
49         pub trait Types {
50             $(associated_item!(type $name);)*
51         }
52
53         $(pub trait $name: Types {
54             $(associated_item!(fn $method(&mut self, $($arg: $arg_ty),*) $(-> $ret_ty)?);)*
55         })*
56
57         pub trait Server: Types $(+ $name)* {}
58         impl<S: Types $(+ $name)*> Server for S {}
59     }
60 }
61 with_api!(Self, self_, declare_server_traits);
62
63 pub(super) struct MarkedTypes<S: Types>(S);
64
65 macro_rules! define_mark_types_impls {
66     ($($name:ident {
67         $(fn $method:ident($($arg:ident: $arg_ty:ty),* $(,)?) $(-> $ret_ty:ty)?;)*
68     }),* $(,)?) => {
69         impl<S: Types> Types for MarkedTypes<S> {
70             $(type $name = Marked<S::$name, client::$name>;)*
71         }
72
73         $(impl<S: $name> $name for MarkedTypes<S> {
74             $(fn $method(&mut self, $($arg: $arg_ty),*) $(-> $ret_ty)? {
75                 <_>::mark($name::$method(&mut self.0, $($arg.unmark()),*))
76             })*
77         })*
78     }
79 }
80 with_api!(Self, self_, define_mark_types_impls);
81
82 struct Dispatcher<S: Types> {
83     handle_store: HandleStore<S>,
84     server: S,
85 }
86
87 macro_rules! define_dispatcher_impl {
88     ($($name:ident {
89         $(fn $method:ident($($arg:ident: $arg_ty:ty),* $(,)?) $(-> $ret_ty:ty)?;)*
90     }),* $(,)?) => {
91         // FIXME(eddyb) `pub` only for `ExecutionStrategy` below.
92         pub trait DispatcherTrait {
93             // HACK(eddyb) these are here to allow `Self::$name` to work below.
94             $(type $name;)*
95             fn dispatch(&mut self, b: Buffer<u8>) -> Buffer<u8>;
96         }
97
98         impl<S: Server> DispatcherTrait for Dispatcher<MarkedTypes<S>> {
99             $(type $name = <MarkedTypes<S> as Types>::$name;)*
100             fn dispatch(&mut self, mut b: Buffer<u8>) -> Buffer<u8> {
101                 let Dispatcher { handle_store, server } = self;
102
103                 let mut reader = &b[..];
104                 match api_tags::Method::decode(&mut reader, &mut ()) {
105                     $(api_tags::Method::$name(m) => match m {
106                         $(api_tags::$name::$method => {
107                             let mut call_method = || {
108                                 reverse_decode!(reader, handle_store; $($arg: $arg_ty),*);
109                                 $name::$method(server, $($arg),*)
110                             };
111                             // HACK(eddyb) don't use `panic::catch_unwind` in a panic.
112                             // If client and server happen to use the same `libstd`,
113                             // `catch_unwind` asserts that the panic counter was 0,
114                             // even when the closure passed to it didn't panic.
115                             let r = if thread::panicking() {
116                                 Ok(call_method())
117                             } else {
118                                 panic::catch_unwind(panic::AssertUnwindSafe(call_method))
119                                     .map_err(PanicMessage::from)
120                             };
121
122                             b.clear();
123                             r.encode(&mut b, handle_store);
124                         })*
125                     }),*
126                 }
127                 b
128             }
129         }
130     }
131 }
132 with_api!(Self, self_, define_dispatcher_impl);
133
134 pub trait ExecutionStrategy {
135     fn run_bridge_and_client<D: Copy + Send + 'static>(
136         &self,
137         dispatcher: &mut impl DispatcherTrait,
138         input: Buffer<u8>,
139         run_client: extern "C" fn(Bridge<'_>, D) -> Buffer<u8>,
140         client_data: D,
141         force_show_panics: bool,
142     ) -> Buffer<u8>;
143 }
144
145 pub struct SameThread;
146
147 impl ExecutionStrategy for SameThread {
148     fn run_bridge_and_client<D: Copy + Send + 'static>(
149         &self,
150         dispatcher: &mut impl DispatcherTrait,
151         input: Buffer<u8>,
152         run_client: extern "C" fn(Bridge<'_>, D) -> Buffer<u8>,
153         client_data: D,
154         force_show_panics: bool,
155     ) -> Buffer<u8> {
156         let mut dispatch = |b| dispatcher.dispatch(b);
157
158         run_client(
159             Bridge { cached_buffer: input, dispatch: (&mut dispatch).into(), force_show_panics },
160             client_data,
161         )
162     }
163 }
164
165 // NOTE(eddyb) Two implementations are provided, the second one is a bit
166 // faster but neither is anywhere near as fast as same-thread execution.
167
168 pub struct CrossThread1;
169
170 impl ExecutionStrategy for CrossThread1 {
171     fn run_bridge_and_client<D: Copy + Send + 'static>(
172         &self,
173         dispatcher: &mut impl DispatcherTrait,
174         input: Buffer<u8>,
175         run_client: extern "C" fn(Bridge<'_>, D) -> Buffer<u8>,
176         client_data: D,
177         force_show_panics: bool,
178     ) -> Buffer<u8> {
179         use std::sync::mpsc::channel;
180
181         let (req_tx, req_rx) = channel();
182         let (res_tx, res_rx) = channel();
183
184         let join_handle = thread::spawn(move || {
185             let mut dispatch = |b| {
186                 req_tx.send(b).unwrap();
187                 res_rx.recv().unwrap()
188             };
189
190             run_client(
191                 Bridge {
192                     cached_buffer: input,
193                     dispatch: (&mut dispatch).into(),
194                     force_show_panics,
195                 },
196                 client_data,
197             )
198         });
199
200         for b in req_rx {
201             res_tx.send(dispatcher.dispatch(b)).unwrap();
202         }
203
204         join_handle.join().unwrap()
205     }
206 }
207
208 pub struct CrossThread2;
209
210 impl ExecutionStrategy for CrossThread2 {
211     fn run_bridge_and_client<D: Copy + Send + 'static>(
212         &self,
213         dispatcher: &mut impl DispatcherTrait,
214         input: Buffer<u8>,
215         run_client: extern "C" fn(Bridge<'_>, D) -> Buffer<u8>,
216         client_data: D,
217         force_show_panics: bool,
218     ) -> Buffer<u8> {
219         use std::sync::{Arc, Mutex};
220
221         enum State<T> {
222             Req(T),
223             Res(T),
224         }
225
226         let mut state = Arc::new(Mutex::new(State::Res(Buffer::new())));
227
228         let server_thread = thread::current();
229         let state2 = state.clone();
230         let join_handle = thread::spawn(move || {
231             let mut dispatch = |b| {
232                 *state2.lock().unwrap() = State::Req(b);
233                 server_thread.unpark();
234                 loop {
235                     thread::park();
236                     if let State::Res(b) = &mut *state2.lock().unwrap() {
237                         break b.take();
238                     }
239                 }
240             };
241
242             let r = run_client(
243                 Bridge {
244                     cached_buffer: input,
245                     dispatch: (&mut dispatch).into(),
246                     force_show_panics,
247                 },
248                 client_data,
249             );
250
251             // Wake up the server so it can exit the dispatch loop.
252             drop(state2);
253             server_thread.unpark();
254
255             r
256         });
257
258         // Check whether `state2` was dropped, to know when to stop.
259         while Arc::get_mut(&mut state).is_none() {
260             thread::park();
261             let mut b = match &mut *state.lock().unwrap() {
262                 State::Req(b) => b.take(),
263                 _ => continue,
264             };
265             b = dispatcher.dispatch(b.take());
266             *state.lock().unwrap() = State::Res(b);
267             join_handle.thread().unpark();
268         }
269
270         join_handle.join().unwrap()
271     }
272 }
273
274 fn run_server<
275     S: Server,
276     I: Encode<HandleStore<MarkedTypes<S>>>,
277     O: for<'a, 's> DecodeMut<'a, 's, HandleStore<MarkedTypes<S>>>,
278     D: Copy + Send + 'static,
279 >(
280     strategy: &impl ExecutionStrategy,
281     handle_counters: &'static client::HandleCounters,
282     server: S,
283     input: I,
284     run_client: extern "C" fn(Bridge<'_>, D) -> Buffer<u8>,
285     client_data: D,
286     force_show_panics: bool,
287 ) -> Result<O, PanicMessage> {
288     let mut dispatcher =
289         Dispatcher { handle_store: HandleStore::new(handle_counters), server: MarkedTypes(server) };
290
291     let mut b = Buffer::new();
292     input.encode(&mut b, &mut dispatcher.handle_store);
293
294     b = strategy.run_bridge_and_client(
295         &mut dispatcher,
296         b,
297         run_client,
298         client_data,
299         force_show_panics,
300     );
301
302     Result::decode(&mut &b[..], &mut dispatcher.handle_store)
303 }
304
305 impl client::Client<fn(crate::TokenStream) -> crate::TokenStream> {
306     pub fn run<S: Server>(
307         &self,
308         strategy: &impl ExecutionStrategy,
309         server: S,
310         input: S::TokenStream,
311         force_show_panics: bool,
312     ) -> Result<S::TokenStream, PanicMessage> {
313         let client::Client { get_handle_counters, run, f } = *self;
314         run_server(
315             strategy,
316             get_handle_counters(),
317             server,
318             <MarkedTypes<S> as Types>::TokenStream::mark(input),
319             run,
320             f,
321             force_show_panics,
322         )
323         .map(<MarkedTypes<S> as Types>::TokenStream::unmark)
324     }
325 }
326
327 impl client::Client<fn(crate::TokenStream, crate::TokenStream) -> crate::TokenStream> {
328     pub fn run<S: Server>(
329         &self,
330         strategy: &impl ExecutionStrategy,
331         server: S,
332         input: S::TokenStream,
333         input2: S::TokenStream,
334         force_show_panics: bool,
335     ) -> Result<S::TokenStream, PanicMessage> {
336         let client::Client { get_handle_counters, run, f } = *self;
337         run_server(
338             strategy,
339             get_handle_counters(),
340             server,
341             (
342                 <MarkedTypes<S> as Types>::TokenStream::mark(input),
343                 <MarkedTypes<S> as Types>::TokenStream::mark(input2),
344             ),
345             run,
346             f,
347             force_show_panics,
348         )
349         .map(<MarkedTypes<S> as Types>::TokenStream::unmark)
350     }
351 }