1 //! Server-side traits.
5 // FIXME(eddyb) generate the definition of `HandleStore` in `server.rs`.
6 use super::client::HandleStore;
8 /// Declare an associated item of one of the traits below, optionally
9 /// adjusting it (i.e., adding bounds to types and default bodies to methods).
10 macro_rules! associated_item {
12 (type TokenStream: 'static + Clone;);
13 (type TokenStreamBuilder) =>
14 (type TokenStreamBuilder: 'static;);
15 (type TokenStreamIter) =>
16 (type TokenStreamIter: 'static + Clone;);
18 (type Group: 'static + Clone;);
20 (type Punct: 'static + Copy + Eq + Hash;);
22 (type Ident: 'static + Copy + Eq + Hash;);
24 (type Literal: 'static + Clone;);
26 (type SourceFile: 'static + Clone;);
28 (type MultiSpan: 'static;);
30 (type Diagnostic: 'static;);
32 (type Span: 'static + Copy + Eq + Hash;);
33 (fn drop(&mut self, $arg:ident: $arg_ty:ty)) =>
34 (fn drop(&mut self, $arg: $arg_ty) { mem::drop($arg) });
35 (fn clone(&mut self, $arg:ident: $arg_ty:ty) -> $ret_ty:ty) =>
36 (fn clone(&mut self, $arg: $arg_ty) -> $ret_ty { $arg.clone() });
37 ($($item:tt)*) => ($($item)*;)
40 macro_rules! declare_server_traits {
42 $(fn $method:ident($($arg:ident: $arg_ty:ty),* $(,)?) $(-> $ret_ty:ty)?;)*
45 $(associated_item!(type $name);)*
48 $(pub trait $name: Types {
49 $(associated_item!(fn $method(&mut self, $($arg: $arg_ty),*) $(-> $ret_ty)?);)*
52 pub trait Server: Types $(+ $name)* {}
53 impl<S: Types $(+ $name)*> Server for S {}
56 with_api!(Self, self_, declare_server_traits);
58 pub(super) struct MarkedTypes<S: Types>(S);
60 macro_rules! define_mark_types_impls {
62 $(fn $method:ident($($arg:ident: $arg_ty:ty),* $(,)?) $(-> $ret_ty:ty)?;)*
64 impl<S: Types> Types for MarkedTypes<S> {
65 $(type $name = Marked<S::$name, client::$name>;)*
68 $(impl<S: $name> $name for MarkedTypes<S> {
69 $(fn $method(&mut self, $($arg: $arg_ty),*) $(-> $ret_ty)? {
70 <_>::mark($name::$method(&mut self.0, $($arg.unmark()),*))
75 with_api!(Self, self_, define_mark_types_impls);
77 struct Dispatcher<S: Types> {
78 handle_store: HandleStore<S>,
82 macro_rules! define_dispatcher_impl {
84 $(fn $method:ident($($arg:ident: $arg_ty:ty),* $(,)?) $(-> $ret_ty:ty)?;)*
86 // FIXME(eddyb) `pub` only for `ExecutionStrategy` below.
87 pub trait DispatcherTrait {
88 // HACK(eddyb) these are here to allow `Self::$name` to work below.
90 fn dispatch(&mut self, b: Buffer<u8>) -> Buffer<u8>;
93 impl<S: Server> DispatcherTrait for Dispatcher<MarkedTypes<S>> {
94 $(type $name = <MarkedTypes<S> as Types>::$name;)*
95 fn dispatch(&mut self, mut b: Buffer<u8>) -> Buffer<u8> {
96 let Dispatcher { handle_store, server } = self;
98 let mut reader = &b[..];
99 match api_tags::Method::decode(&mut reader, &mut ()) {
100 $(api_tags::Method::$name(m) => match m {
101 $(api_tags::$name::$method => {
102 let mut call_method = || {
103 reverse_decode!(reader, handle_store; $($arg: $arg_ty),*);
104 $name::$method(server, $($arg),*)
106 // HACK(eddyb) don't use `panic::catch_unwind` in a panic.
107 // If client and server happen to use the same `libstd`,
108 // `catch_unwind` asserts that the panic counter was 0,
109 // even when the closure passed to it didn't panic.
110 let r = if thread::panicking() {
113 panic::catch_unwind(panic::AssertUnwindSafe(call_method))
114 .map_err(PanicMessage::from)
118 r.encode(&mut b, handle_store);
127 with_api!(Self, self_, define_dispatcher_impl);
129 pub trait ExecutionStrategy {
130 fn run_bridge_and_client<D: Copy + Send + 'static>(
132 dispatcher: &mut impl DispatcherTrait,
134 run_client: extern "C" fn(Bridge<'_>, D) -> Buffer<u8>,
139 pub struct SameThread;
141 impl ExecutionStrategy for SameThread {
142 fn run_bridge_and_client<D: Copy + Send + 'static>(
144 dispatcher: &mut impl DispatcherTrait,
146 run_client: extern "C" fn(Bridge<'_>, D) -> Buffer<u8>,
149 let mut dispatch = |b| dispatcher.dispatch(b);
151 run_client(Bridge { cached_buffer: input, dispatch: (&mut dispatch).into() }, client_data)
155 // NOTE(eddyb) Two implementations are provided, the second one is a bit
156 // faster but neither is anywhere near as fast as same-thread execution.
158 pub struct CrossThread1;
160 impl ExecutionStrategy for CrossThread1 {
161 fn run_bridge_and_client<D: Copy + Send + 'static>(
163 dispatcher: &mut impl DispatcherTrait,
165 run_client: extern "C" fn(Bridge<'_>, D) -> Buffer<u8>,
168 use std::sync::mpsc::channel;
170 let (req_tx, req_rx) = channel();
171 let (res_tx, res_rx) = channel();
173 let join_handle = thread::spawn(move || {
174 let mut dispatch = |b| {
175 req_tx.send(b).unwrap();
176 res_rx.recv().unwrap()
180 Bridge { cached_buffer: input, dispatch: (&mut dispatch).into() },
186 res_tx.send(dispatcher.dispatch(b)).unwrap();
189 join_handle.join().unwrap()
193 pub struct CrossThread2;
195 impl ExecutionStrategy for CrossThread2 {
196 fn run_bridge_and_client<D: Copy + Send + 'static>(
198 dispatcher: &mut impl DispatcherTrait,
200 run_client: extern "C" fn(Bridge<'_>, D) -> Buffer<u8>,
203 use std::sync::{Arc, Mutex};
210 let mut state = Arc::new(Mutex::new(State::Res(Buffer::new())));
212 let server_thread = thread::current();
213 let state2 = state.clone();
214 let join_handle = thread::spawn(move || {
215 let mut dispatch = |b| {
216 *state2.lock().unwrap() = State::Req(b);
217 server_thread.unpark();
220 if let State::Res(b) = &mut *state2.lock().unwrap() {
227 Bridge { cached_buffer: input, dispatch: (&mut dispatch).into() },
231 // Wake up the server so it can exit the dispatch loop.
233 server_thread.unpark();
238 // Check whether `state2` was dropped, to know when to stop.
239 while Arc::get_mut(&mut state).is_none() {
241 let mut b = match &mut *state.lock().unwrap() {
242 State::Req(b) => b.take(),
245 b = dispatcher.dispatch(b.take());
246 *state.lock().unwrap() = State::Res(b);
247 join_handle.thread().unpark();
250 join_handle.join().unwrap()
256 I: Encode<HandleStore<MarkedTypes<S>>>,
257 O: for<'a, 's> DecodeMut<'a, 's, HandleStore<MarkedTypes<S>>>,
258 D: Copy + Send + 'static,
260 strategy: &impl ExecutionStrategy,
261 handle_counters: &'static client::HandleCounters,
264 run_client: extern "C" fn(Bridge<'_>, D) -> Buffer<u8>,
266 ) -> Result<O, PanicMessage> {
268 Dispatcher { handle_store: HandleStore::new(handle_counters), server: MarkedTypes(server) };
270 let mut b = Buffer::new();
271 input.encode(&mut b, &mut dispatcher.handle_store);
273 b = strategy.run_bridge_and_client(&mut dispatcher, b, run_client, client_data);
275 Result::decode(&mut &b[..], &mut dispatcher.handle_store)
278 impl client::Client<fn(crate::TokenStream) -> crate::TokenStream> {
279 pub fn run<S: Server>(
281 strategy: &impl ExecutionStrategy,
283 input: S::TokenStream,
284 ) -> Result<S::TokenStream, PanicMessage> {
285 let client::Client { get_handle_counters, run, f } = *self;
288 get_handle_counters(),
290 <MarkedTypes<S> as Types>::TokenStream::mark(input),
294 .map(<MarkedTypes<S> as Types>::TokenStream::unmark)
298 impl client::Client<fn(crate::TokenStream, crate::TokenStream) -> crate::TokenStream> {
299 pub fn run<S: Server>(
301 strategy: &impl ExecutionStrategy,
303 input: S::TokenStream,
304 input2: S::TokenStream,
305 ) -> Result<S::TokenStream, PanicMessage> {
306 let client::Client { get_handle_counters, run, f } = *self;
309 get_handle_counters(),
312 <MarkedTypes<S> as Types>::TokenStream::mark(input),
313 <MarkedTypes<S> as Types>::TokenStream::mark(input2),
318 .map(<MarkedTypes<S> as Types>::TokenStream::unmark)