1 //! lib-proc-macro server-side traits
3 //! Copy from <https://github.com/rust-lang/rust/blob/6050e523bae6de61de4e060facc43dc512adaccd/src/libproc_macro/bridge/server.rs>
4 //! augmented with removing unstable features
8 // FIXME(eddyb) generate the definition of `HandleStore` in `server.rs`.
9 use super::client::HandleStore;
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;);
17 (type TokenStream: 'static + Clone;);
18 (type TokenStreamBuilder) =>
19 (type TokenStreamBuilder: 'static;);
20 (type TokenStreamIter) =>
21 (type TokenStreamIter: 'static + Clone;);
23 (type Group: 'static + Clone;);
25 (type Punct: 'static + Copy + Eq + Hash;);
27 (type Ident: 'static + Copy + Eq + Hash;);
29 (type Literal: 'static + Clone;);
31 (type SourceFile: 'static + Clone;);
33 (type MultiSpan: 'static;);
35 (type Diagnostic: 'static;);
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)*;)
45 macro_rules! declare_server_traits {
47 $(fn $method:ident($($arg:ident: $arg_ty:ty),* $(,)?) $(-> $ret_ty:ty)?;)*
50 $(associated_item!(type $name);)*
53 $(pub trait $name: Types {
54 $(associated_item!(fn $method(&mut self, $($arg: $arg_ty),*) $(-> $ret_ty)?);)*
57 pub trait Server: Types $(+ $name)* {}
58 impl<S: Types $(+ $name)*> Server for S {}
61 with_api!(Self, self_, declare_server_traits);
63 pub(super) struct MarkedTypes<S: Types>(S);
65 macro_rules! define_mark_types_impls {
67 $(fn $method:ident($($arg:ident: $arg_ty:ty),* $(,)?) $(-> $ret_ty:ty)?;)*
69 impl<S: Types> Types for MarkedTypes<S> {
70 $(type $name = Marked<S::$name, client::$name>;)*
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()),*))
80 with_api!(Self, self_, define_mark_types_impls);
82 struct Dispatcher<S: Types> {
83 handle_store: HandleStore<S>,
87 macro_rules! define_dispatcher_impl {
89 $(fn $method:ident($($arg:ident: $arg_ty:ty),* $(,)?) $(-> $ret_ty:ty)?;)*
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.
95 fn dispatch(&mut self, b: Buffer<u8>) -> Buffer<u8>;
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;
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),*)
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() {
118 panic::catch_unwind(panic::AssertUnwindSafe(call_method))
119 .map_err(PanicMessage::from)
123 r.encode(&mut b, handle_store);
132 with_api!(Self, self_, define_dispatcher_impl);
134 pub trait ExecutionStrategy {
135 fn run_bridge_and_client<D: Copy + Send + 'static>(
137 dispatcher: &mut impl DispatcherTrait,
139 run_client: extern "C" fn(Bridge<'_>, D) -> Buffer<u8>,
141 force_show_panics: bool,
145 pub struct SameThread;
147 impl ExecutionStrategy for SameThread {
148 fn run_bridge_and_client<D: Copy + Send + 'static>(
150 dispatcher: &mut impl DispatcherTrait,
152 run_client: extern "C" fn(Bridge<'_>, D) -> Buffer<u8>,
154 force_show_panics: bool,
156 let mut dispatch = |b| dispatcher.dispatch(b);
159 Bridge { cached_buffer: input, dispatch: (&mut dispatch).into(), force_show_panics },
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.
168 pub struct CrossThread1;
170 impl ExecutionStrategy for CrossThread1 {
171 fn run_bridge_and_client<D: Copy + Send + 'static>(
173 dispatcher: &mut impl DispatcherTrait,
175 run_client: extern "C" fn(Bridge<'_>, D) -> Buffer<u8>,
177 force_show_panics: bool,
179 use std::sync::mpsc::channel;
181 let (req_tx, req_rx) = channel();
182 let (res_tx, res_rx) = channel();
184 let join_handle = thread::spawn(move || {
185 let mut dispatch = |b| {
186 req_tx.send(b).unwrap();
187 res_rx.recv().unwrap()
192 cached_buffer: input,
193 dispatch: (&mut dispatch).into(),
201 res_tx.send(dispatcher.dispatch(b)).unwrap();
204 join_handle.join().unwrap()
208 pub struct CrossThread2;
210 impl ExecutionStrategy for CrossThread2 {
211 fn run_bridge_and_client<D: Copy + Send + 'static>(
213 dispatcher: &mut impl DispatcherTrait,
215 run_client: extern "C" fn(Bridge<'_>, D) -> Buffer<u8>,
217 force_show_panics: bool,
219 use std::sync::{Arc, Mutex};
226 let mut state = Arc::new(Mutex::new(State::Res(Buffer::new())));
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();
236 if let State::Res(b) = &mut *state2.lock().unwrap() {
244 cached_buffer: input,
245 dispatch: (&mut dispatch).into(),
251 // Wake up the server so it can exit the dispatch loop.
253 server_thread.unpark();
258 // Check whether `state2` was dropped, to know when to stop.
259 while Arc::get_mut(&mut state).is_none() {
261 let mut b = match &mut *state.lock().unwrap() {
262 State::Req(b) => b.take(),
265 b = dispatcher.dispatch(b.take());
266 *state.lock().unwrap() = State::Res(b);
267 join_handle.thread().unpark();
270 join_handle.join().unwrap()
276 I: Encode<HandleStore<MarkedTypes<S>>>,
277 O: for<'a, 's> DecodeMut<'a, 's, HandleStore<MarkedTypes<S>>>,
278 D: Copy + Send + 'static,
280 strategy: &impl ExecutionStrategy,
281 handle_counters: &'static client::HandleCounters,
284 run_client: extern "C" fn(Bridge<'_>, D) -> Buffer<u8>,
286 force_show_panics: bool,
287 ) -> Result<O, PanicMessage> {
289 Dispatcher { handle_store: HandleStore::new(handle_counters), server: MarkedTypes(server) };
291 let mut b = Buffer::new();
292 input.encode(&mut b, &mut dispatcher.handle_store);
294 b = strategy.run_bridge_and_client(
302 Result::decode(&mut &b[..], &mut dispatcher.handle_store)
305 impl client::Client<fn(crate::TokenStream) -> crate::TokenStream> {
306 pub fn run<S: Server>(
308 strategy: &impl ExecutionStrategy,
310 input: S::TokenStream,
311 force_show_panics: bool,
312 ) -> Result<S::TokenStream, PanicMessage> {
313 let client::Client { get_handle_counters, run, f } = *self;
316 get_handle_counters(),
318 <MarkedTypes<S> as Types>::TokenStream::mark(input),
323 .map(<MarkedTypes<S> as Types>::TokenStream::unmark)
327 impl client::Client<fn(crate::TokenStream, crate::TokenStream) -> crate::TokenStream> {
328 pub fn run<S: Server>(
330 strategy: &impl ExecutionStrategy,
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;
339 get_handle_counters(),
342 <MarkedTypes<S> as Types>::TokenStream::mark(input),
343 <MarkedTypes<S> as Types>::TokenStream::mark(input2),
349 .map(<MarkedTypes<S> as Types>::TokenStream::unmark)