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);
153 cached_buffer: input,
154 dispatch: (&mut dispatch).into(),
161 // NOTE(eddyb) Two implementations are provided, the second one is a bit
162 // faster but neither is anywhere near as fast as same-thread execution.
164 pub struct CrossThread1;
166 impl ExecutionStrategy for CrossThread1 {
167 fn run_bridge_and_client<D: Copy + Send + 'static>(
169 dispatcher: &mut impl DispatcherTrait,
171 run_client: extern "C" fn(Bridge<'_>, D) -> Buffer<u8>,
174 use std::sync::mpsc::channel;
176 let (req_tx, req_rx) = channel();
177 let (res_tx, res_rx) = channel();
179 let join_handle = thread::spawn(move || {
180 let mut dispatch = |b| {
181 req_tx.send(b).unwrap();
182 res_rx.recv().unwrap()
187 cached_buffer: input,
188 dispatch: (&mut dispatch).into(),
195 res_tx.send(dispatcher.dispatch(b)).unwrap();
198 join_handle.join().unwrap()
202 pub struct CrossThread2;
204 impl ExecutionStrategy for CrossThread2 {
205 fn run_bridge_and_client<D: Copy + Send + 'static>(
207 dispatcher: &mut impl DispatcherTrait,
209 run_client: extern "C" fn(Bridge<'_>, D) -> Buffer<u8>,
212 use std::sync::{Arc, Mutex};
219 let mut state = Arc::new(Mutex::new(State::Res(Buffer::new())));
221 let server_thread = thread::current();
222 let state2 = state.clone();
223 let join_handle = thread::spawn(move || {
224 let mut dispatch = |b| {
225 *state2.lock().unwrap() = State::Req(b);
226 server_thread.unpark();
229 if let State::Res(b) = &mut *state2.lock().unwrap() {
237 cached_buffer: input,
238 dispatch: (&mut dispatch).into(),
243 // Wake up the server so it can exit the dispatch loop.
245 server_thread.unpark();
250 // Check whether `state2` was dropped, to know when to stop.
251 while Arc::get_mut(&mut state).is_none() {
253 let mut b = match &mut *state.lock().unwrap() {
254 State::Req(b) => b.take(),
257 b = dispatcher.dispatch(b.take());
258 *state.lock().unwrap() = State::Res(b);
259 join_handle.thread().unpark();
262 join_handle.join().unwrap()
268 I: Encode<HandleStore<MarkedTypes<S>>>,
269 O: for<'a, 's> DecodeMut<'a, 's, HandleStore<MarkedTypes<S>>>,
270 D: Copy + Send + 'static,
272 strategy: &impl ExecutionStrategy,
273 handle_counters: &'static client::HandleCounters,
276 run_client: extern "C" fn(Bridge<'_>, D) -> Buffer<u8>,
278 ) -> Result<O, PanicMessage> {
279 let mut dispatcher = Dispatcher {
280 handle_store: HandleStore::new(handle_counters),
281 server: MarkedTypes(server),
284 let mut b = Buffer::new();
285 input.encode(&mut b, &mut dispatcher.handle_store);
287 b = strategy.run_bridge_and_client(&mut dispatcher, b, run_client, client_data);
289 Result::decode(&mut &b[..], &mut dispatcher.handle_store)
292 impl client::Client<fn(crate::TokenStream) -> crate::TokenStream> {
293 pub fn run<S: Server>(
295 strategy: &impl ExecutionStrategy,
297 input: S::TokenStream,
298 ) -> Result<S::TokenStream, PanicMessage> {
306 get_handle_counters(),
308 <MarkedTypes<S> as Types>::TokenStream::mark(input),
312 .map(<MarkedTypes<S> as Types>::TokenStream::unmark)
316 impl client::Client<fn(crate::TokenStream, crate::TokenStream) -> crate::TokenStream> {
317 pub fn run<S: Server>(
319 strategy: &impl ExecutionStrategy,
321 input: S::TokenStream,
322 input2: S::TokenStream,
323 ) -> Result<S::TokenStream, PanicMessage> {
331 get_handle_counters(),
334 <MarkedTypes<S> as Types>::TokenStream::mark(input),
335 <MarkedTypes<S> as Types>::TokenStream::mark(input2),
340 .map(<MarkedTypes<S> as Types>::TokenStream::unmark)