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
6 use super::super::TokenStream as CrateTokenStream;
9 // FIXME(eddyb) generate the definition of `HandleStore` in `server.rs`.
10 use super::client::HandleStore;
12 /// Declare an associated item of one of the traits below, optionally
13 /// adjusting it (i.e., adding bounds to types and default bodies to methods).
14 macro_rules! associated_item {
15 (type FreeFunctions) =>
16 (type FreeFunctions: 'static;);
18 (type TokenStream: 'static + Clone;);
19 (type TokenStreamBuilder) =>
20 (type TokenStreamBuilder: 'static;);
21 (type TokenStreamIter) =>
22 (type TokenStreamIter: 'static + Clone;);
24 (type Group: 'static + Clone;);
26 (type Punct: 'static + Copy + Eq + Hash;);
28 (type Ident: 'static + Copy + Eq + Hash;);
30 (type Literal: 'static + Clone;);
32 (type SourceFile: 'static + Clone;);
34 (type MultiSpan: 'static;);
36 (type Diagnostic: 'static;);
38 (type Span: 'static + Copy + Eq + Hash;);
39 (fn drop(&mut self, $arg:ident: $arg_ty:ty)) =>
40 (fn drop(&mut self, $arg: $arg_ty) { mem::drop($arg) });
41 (fn clone(&mut self, $arg:ident: $arg_ty:ty) -> $ret_ty:ty) =>
42 (fn clone(&mut self, $arg: $arg_ty) -> $ret_ty { $arg.clone() });
43 ($($item:tt)*) => ($($item)*;)
46 macro_rules! declare_server_traits {
48 $(fn $method:ident($($arg:ident: $arg_ty:ty),* $(,)?) $(-> $ret_ty:ty)?;)*
51 $(associated_item!(type $name);)*
54 $(pub trait $name: Types {
55 $(associated_item!(fn $method(&mut self, $($arg: $arg_ty),*) $(-> $ret_ty)?);)*
58 pub trait Server: Types $(+ $name)* {}
59 impl<S: Types $(+ $name)*> Server for S {}
62 with_api!(Self, self_, declare_server_traits);
64 pub(super) struct MarkedTypes<S: Types>(S);
66 macro_rules! define_mark_types_impls {
68 $(fn $method:ident($($arg:ident: $arg_ty:ty),* $(,)?) $(-> $ret_ty:ty)?;)*
70 impl<S: Types> Types for MarkedTypes<S> {
71 $(type $name = Marked<S::$name, client::$name>;)*
74 $(impl<S: $name> $name for MarkedTypes<S> {
75 $(fn $method(&mut self, $($arg: $arg_ty),*) $(-> $ret_ty)? {
76 <_>::mark($name::$method(&mut self.0, $($arg.unmark()),*))
81 with_api!(Self, self_, define_mark_types_impls);
83 struct Dispatcher<S: Types> {
84 handle_store: HandleStore<S>,
88 macro_rules! define_dispatcher_impl {
90 $(fn $method:ident($($arg:ident: $arg_ty:ty),* $(,)?) $(-> $ret_ty:ty)?;)*
92 // FIXME(eddyb) `pub` only for `ExecutionStrategy` below.
93 pub trait DispatcherTrait {
94 // HACK(eddyb) these are here to allow `Self::$name` to work below.
96 fn dispatch(&mut self, b: Buffer<u8>) -> Buffer<u8>;
99 impl<S: Server> DispatcherTrait for Dispatcher<MarkedTypes<S>> {
100 $(type $name = <MarkedTypes<S> as Types>::$name;)*
101 fn dispatch(&mut self, mut b: Buffer<u8>) -> Buffer<u8> {
102 let Dispatcher { handle_store, server } = self;
104 let mut reader = &b[..];
105 match api_tags::Method::decode(&mut reader, &mut ()) {
106 $(api_tags::Method::$name(m) => match m {
107 $(api_tags::$name::$method => {
108 let mut call_method = || {
109 reverse_decode!(reader, handle_store; $($arg: $arg_ty),*);
110 $name::$method(server, $($arg),*)
112 // HACK(eddyb) don't use `panic::catch_unwind` in a panic.
113 // If client and server happen to use the same `libstd`,
114 // `catch_unwind` asserts that the panic counter was 0,
115 // even when the closure passed to it didn't panic.
116 let r = if thread::panicking() {
119 panic::catch_unwind(panic::AssertUnwindSafe(call_method))
120 .map_err(PanicMessage::from)
124 r.encode(&mut b, handle_store);
133 with_api!(Self, self_, define_dispatcher_impl);
135 pub trait ExecutionStrategy {
136 fn run_bridge_and_client<D: Copy + Send + 'static>(
138 dispatcher: &mut impl DispatcherTrait,
140 run_client: extern "C" fn(Bridge<'_>, D) -> Buffer<u8>,
142 force_show_panics: bool,
146 pub struct SameThread;
148 impl ExecutionStrategy for SameThread {
149 fn run_bridge_and_client<D: Copy + Send + 'static>(
151 dispatcher: &mut impl DispatcherTrait,
153 run_client: extern "C" fn(Bridge<'_>, D) -> Buffer<u8>,
155 force_show_panics: bool,
157 let mut dispatch = |b| dispatcher.dispatch(b);
160 Bridge { cached_buffer: input, dispatch: (&mut dispatch).into(), force_show_panics },
166 // NOTE(eddyb) Two implementations are provided, the second one is a bit
167 // faster but neither is anywhere near as fast as same-thread execution.
169 pub struct CrossThread1;
171 impl ExecutionStrategy for CrossThread1 {
172 fn run_bridge_and_client<D: Copy + Send + 'static>(
174 dispatcher: &mut impl DispatcherTrait,
176 run_client: extern "C" fn(Bridge<'_>, D) -> Buffer<u8>,
178 force_show_panics: bool,
180 use std::sync::mpsc::channel;
182 let (req_tx, req_rx) = channel();
183 let (res_tx, res_rx) = channel();
185 let join_handle = thread::spawn(move || {
186 let mut dispatch = |b| {
187 req_tx.send(b).unwrap();
188 res_rx.recv().unwrap()
193 cached_buffer: input,
194 dispatch: (&mut dispatch).into(),
202 res_tx.send(dispatcher.dispatch(b)).unwrap();
205 join_handle.join().unwrap()
209 pub struct CrossThread2;
211 impl ExecutionStrategy for CrossThread2 {
212 fn run_bridge_and_client<D: Copy + Send + 'static>(
214 dispatcher: &mut impl DispatcherTrait,
216 run_client: extern "C" fn(Bridge<'_>, D) -> Buffer<u8>,
218 force_show_panics: bool,
220 use std::sync::{Arc, Mutex};
227 let mut state = Arc::new(Mutex::new(State::Res(Buffer::new())));
229 let server_thread = thread::current();
230 let state2 = state.clone();
231 let join_handle = thread::spawn(move || {
232 let mut dispatch = |b| {
233 *state2.lock().unwrap() = State::Req(b);
234 server_thread.unpark();
237 if let State::Res(b) = &mut *state2.lock().unwrap() {
245 cached_buffer: input,
246 dispatch: (&mut dispatch).into(),
252 // Wake up the server so it can exit the dispatch loop.
254 server_thread.unpark();
259 // Check whether `state2` was dropped, to know when to stop.
260 while Arc::get_mut(&mut state).is_none() {
262 let mut b = match &mut *state.lock().unwrap() {
263 State::Req(b) => b.take(),
266 b = dispatcher.dispatch(b.take());
267 *state.lock().unwrap() = State::Res(b);
268 join_handle.thread().unpark();
271 join_handle.join().unwrap()
277 I: Encode<HandleStore<MarkedTypes<S>>>,
278 O: for<'a, 's> DecodeMut<'a, 's, HandleStore<MarkedTypes<S>>>,
279 D: Copy + Send + 'static,
281 strategy: &impl ExecutionStrategy,
282 handle_counters: &'static client::HandleCounters,
285 run_client: extern "C" fn(Bridge<'_>, D) -> Buffer<u8>,
287 force_show_panics: bool,
288 ) -> Result<O, PanicMessage> {
290 Dispatcher { handle_store: HandleStore::new(handle_counters), server: MarkedTypes(server) };
292 let mut b = Buffer::new();
293 input.encode(&mut b, &mut dispatcher.handle_store);
295 b = strategy.run_bridge_and_client(
303 Result::decode(&mut &b[..], &mut dispatcher.handle_store)
306 impl client::Client<fn(CrateTokenStream) -> CrateTokenStream> {
307 pub fn run<S: Server>(
309 strategy: &impl ExecutionStrategy,
311 input: S::TokenStream,
312 force_show_panics: bool,
313 ) -> Result<S::TokenStream, PanicMessage> {
314 let client::Client { get_handle_counters, run, f } = *self;
317 get_handle_counters(),
319 <MarkedTypes<S> as Types>::TokenStream::mark(input),
324 .map(<MarkedTypes<S> as Types>::TokenStream::unmark)
328 impl client::Client<fn(CrateTokenStream, CrateTokenStream) -> CrateTokenStream> {
329 pub fn run<S: Server>(
331 strategy: &impl ExecutionStrategy,
333 input: S::TokenStream,
334 input2: S::TokenStream,
335 force_show_panics: bool,
336 ) -> Result<S::TokenStream, PanicMessage> {
337 let client::Client { get_handle_counters, run, f } = *self;
340 get_handle_counters(),
343 <MarkedTypes<S> as Types>::TokenStream::mark(input),
344 <MarkedTypes<S> as Types>::TokenStream::mark(input2),
350 .map(<MarkedTypes<S> as Types>::TokenStream::unmark)