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.
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.
11 //! Server-side traits.
15 // FIXME(eddyb) generate the definition of `HandleStore` in `server.rs`.
16 use super::client::HandleStore;
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 {
22 (type TokenStream: 'static + Clone;);
23 (type TokenStreamBuilder) =>
24 (type TokenStreamBuilder: 'static;);
25 (type TokenStreamIter) =>
26 (type TokenStreamIter: 'static + Clone;);
28 (type Group: 'static + Clone;);
30 (type Punct: 'static + Copy + Eq + Hash;);
32 (type Ident: 'static + Copy + Eq + Hash;);
34 (type Literal: 'static + Clone;);
36 (type SourceFile: 'static + Clone;);
38 (type MultiSpan: 'static;);
40 (type Diagnostic: 'static;);
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)*;)
50 macro_rules! declare_server_traits {
52 $(fn $method:ident($($arg:ident: $arg_ty:ty),* $(,)*) $(-> $ret_ty:ty)*;)*
55 $(associated_item!(type $name);)*
58 $(pub trait $name: Types {
59 $(associated_item!(fn $method(&mut self, $($arg: $arg_ty),*) $(-> $ret_ty)*);)*
62 pub trait Server: Types $(+ $name)* {}
63 impl<S: Types $(+ $name)*> Server for S {}
66 with_api!(Self, self_, declare_server_traits);
68 pub(super) struct MarkedTypes<S: Types>(S);
70 macro_rules! define_mark_types_impls {
72 $(fn $method:ident($($arg:ident: $arg_ty:ty),* $(,)*) $(-> $ret_ty:ty)*;)*
74 impl<S: Types> Types for MarkedTypes<S> {
75 $(type $name = Marked<S::$name, client::$name>;)*
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()),*))
85 with_api!(Self, self_, define_mark_types_impls);
87 struct Dispatcher<S: Types> {
88 handle_store: HandleStore<S>,
92 macro_rules! define_dispatcher_impl {
94 $(fn $method:ident($($arg:ident: $arg_ty:ty),* $(,)*) $(-> $ret_ty:ty)*;)*
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.
100 fn dispatch(&mut self, b: Buffer<u8>) -> Buffer<u8>;
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;
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),*)
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() {
123 panic::catch_unwind(panic::AssertUnwindSafe(call_method))
124 .map_err(PanicMessage::from)
128 r.encode(&mut b, handle_store);
137 with_api!(Self, self_, define_dispatcher_impl);
139 pub trait ExecutionStrategy {
140 fn run_bridge_and_client<D: Copy + Send + 'static>(
142 dispatcher: &mut impl DispatcherTrait,
144 run_client: extern "C" fn(Bridge, D) -> Buffer<u8>,
149 pub struct SameThread;
151 impl ExecutionStrategy for SameThread {
152 fn run_bridge_and_client<D: Copy + Send + 'static>(
154 dispatcher: &mut impl DispatcherTrait,
156 run_client: extern "C" fn(Bridge, D) -> Buffer<u8>,
159 let mut dispatch = |b| dispatcher.dispatch(b);
163 cached_buffer: input,
164 dispatch: (&mut dispatch).into(),
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.
174 pub struct CrossThread1;
176 impl ExecutionStrategy for CrossThread1 {
177 fn run_bridge_and_client<D: Copy + Send + 'static>(
179 dispatcher: &mut impl DispatcherTrait,
181 run_client: extern "C" fn(Bridge, D) -> Buffer<u8>,
184 use std::sync::mpsc::channel;
186 let (req_tx, req_rx) = channel();
187 let (res_tx, res_rx) = channel();
189 let join_handle = thread::spawn(move || {
190 let mut dispatch = |b| {
191 req_tx.send(b).unwrap();
192 res_rx.recv().unwrap()
197 cached_buffer: input,
198 dispatch: (&mut dispatch).into(),
205 res_tx.send(dispatcher.dispatch(b)).unwrap();
208 join_handle.join().unwrap()
212 pub struct CrossThread2;
214 impl ExecutionStrategy for CrossThread2 {
215 fn run_bridge_and_client<D: Copy + Send + 'static>(
217 dispatcher: &mut impl DispatcherTrait,
219 run_client: extern "C" fn(Bridge, D) -> Buffer<u8>,
222 use std::sync::{Arc, Mutex};
229 let mut state = Arc::new(Mutex::new(State::Res(Buffer::new())));
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();
239 if let State::Res(b) = &mut *state2.lock().unwrap() {
247 cached_buffer: input,
248 dispatch: (&mut dispatch).into(),
253 // Wake up the server so it can exit the dispatch loop.
255 server_thread.unpark();
260 // Check whether `state2` was dropped, to know when to stop.
261 while Arc::get_mut(&mut state).is_none() {
263 let mut b = match &mut *state.lock().unwrap() {
264 State::Req(b) => b.take(),
267 b = dispatcher.dispatch(b.take());
268 *state.lock().unwrap() = State::Res(b);
269 join_handle.thread().unpark();
272 join_handle.join().unwrap()
278 I: Encode<HandleStore<MarkedTypes<S>>>,
279 O: for<'a, 's> DecodeMut<'a, 's, HandleStore<MarkedTypes<S>>>,
280 D: Copy + Send + 'static,
282 strategy: &impl ExecutionStrategy,
283 handle_counters: &'static client::HandleCounters,
286 run_client: extern "C" fn(Bridge, D) -> Buffer<u8>,
288 ) -> Result<O, PanicMessage> {
289 let mut dispatcher = Dispatcher {
290 handle_store: HandleStore::new(handle_counters),
291 server: MarkedTypes(server),
294 let mut b = Buffer::new();
295 input.encode(&mut b, &mut dispatcher.handle_store);
297 b = strategy.run_bridge_and_client(&mut dispatcher, b, run_client, client_data);
299 Result::decode(&mut &b[..], &mut dispatcher.handle_store)
302 impl client::Client<fn(::TokenStream) -> ::TokenStream> {
303 pub fn run<S: Server>(
305 strategy: &impl ExecutionStrategy,
307 input: S::TokenStream,
308 ) -> Result<S::TokenStream, PanicMessage> {
316 get_handle_counters(),
318 <MarkedTypes<S> as Types>::TokenStream::mark(input),
322 .map(<MarkedTypes<S> as Types>::TokenStream::unmark)
326 impl client::Client<fn(::TokenStream, ::TokenStream) -> ::TokenStream> {
327 pub fn run<S: Server>(
329 strategy: &impl ExecutionStrategy,
331 input: S::TokenStream,
332 input2: S::TokenStream,
333 ) -> Result<S::TokenStream, PanicMessage> {
341 get_handle_counters(),
344 <MarkedTypes<S> as Types>::TokenStream::mark(input),
345 <MarkedTypes<S> as Types>::TokenStream::mark(input2),
350 .map(<MarkedTypes<S> as Types>::TokenStream::unmark)