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