Skip to main content

proc_macro/bridge/
server.rs

1//! Server-side traits.
2
3use std::cell::Cell;
4use std::sync::mpsc;
5
6use super::*;
7
8pub(super) struct HandleStore<S: Server> {
9    token_stream: handle::OwnedStore<MarkedTokenStream<S>>,
10    span: handle::InternedStore<MarkedSpan<S>>,
11}
12
13impl<S: Server> HandleStore<S> {
14    fn new(handle_counters: &'static client::HandleCounters) -> Self {
15        HandleStore {
16            token_stream: handle::OwnedStore::new(&handle_counters.token_stream),
17            span: handle::InternedStore::new(&handle_counters.span),
18        }
19    }
20}
21
22pub(super) type MarkedTokenStream<S> = Marked<<S as Server>::TokenStream, client::TokenStream>;
23pub(super) type MarkedSpan<S> = Marked<<S as Server>::Span, client::Span>;
24pub(super) type MarkedSymbol<S> = Marked<<S as Server>::Symbol, client::Symbol>;
25
26impl<S: Server> Encode<HandleStore<S>> for MarkedTokenStream<S> {
27    fn encode(self, w: &mut Buffer, s: &mut HandleStore<S>) {
28        s.token_stream.alloc(self).encode(w, s);
29    }
30}
31
32impl<S: Server> Decode<'_, '_, HandleStore<S>> for MarkedTokenStream<S> {
33    fn decode(r: &mut &[u8], s: &mut HandleStore<S>) -> Self {
34        s.token_stream.take(handle::Handle::decode(r, &mut ()))
35    }
36}
37
38impl<'s, S: Server> Decode<'_, 's, HandleStore<S>> for &'s MarkedTokenStream<S> {
39    fn decode(r: &mut &[u8], s: &'s mut HandleStore<S>) -> Self {
40        &s.token_stream[handle::Handle::decode(r, &mut ())]
41    }
42}
43
44impl<S: Server> Encode<HandleStore<S>> for MarkedSpan<S> {
45    fn encode(self, w: &mut Buffer, s: &mut HandleStore<S>) {
46        s.span.alloc(self).encode(w, s);
47    }
48}
49
50impl<S: Server> Decode<'_, '_, HandleStore<S>> for MarkedSpan<S> {
51    fn decode(r: &mut &[u8], s: &mut HandleStore<S>) -> Self {
52        s.span.copy(handle::Handle::decode(r, &mut ()))
53    }
54}
55
56macro_rules! define_server {
57    (
58        $(fn $method:ident($($arg:ident: $arg_ty:ty),* $(,)?) $(-> $ret_ty:ty)?;)*
59    ) => {
60        pub trait Server {
61            type TokenStream: 'static + Clone + Default;
62            type Span: 'static + Copy + Eq + Hash;
63            type Symbol: 'static;
64
65            fn globals(&mut self) -> ExpnGlobals<Self::Span>;
66
67            /// Intern a symbol received from RPC
68            fn intern_symbol(ident: &str) -> Self::Symbol;
69
70            /// Recover the string value of a symbol, and invoke a callback with it.
71            fn with_symbol_string(symbol: &Self::Symbol, f: impl FnOnce(&str));
72
73            $(fn $method(&mut self, $($arg: $arg_ty),*) $(-> $ret_ty)?;)*
74        }
75    }
76}
77with_api!(define_server, Self::TokenStream, Self::Span, Self::Symbol);
78
79// FIXME(eddyb) `pub` only for `ExecutionStrategy` below.
80pub struct Dispatcher<S: Server> {
81    handle_store: HandleStore<S>,
82    server: S,
83}
84
85macro_rules! define_dispatcher {
86    (
87        $(fn $method:ident($($arg:ident: $arg_ty:ty),* $(,)?) $(-> $ret_ty:ty)?;)*
88    ) => {
89        impl<S: Server> Dispatcher<S> {
90            fn dispatch(&mut self, mut buf: Buffer) -> Buffer {
91                let Dispatcher { handle_store, server } = self;
92
93                let mut reader = &buf[..];
94                match ApiTags::decode(&mut reader, &mut ()) {
95                    $(ApiTags::$method => {
96                        let mut call_method = || {
97                            $(let $arg = <$arg_ty>::decode(&mut reader, handle_store).unmark();)*
98                            let r = server.$method($($arg),*);
99                            $(let r: $ret_ty = Mark::mark(r);)?
100                            r
101                        };
102                        // HACK(eddyb) don't use `panic::catch_unwind` in a panic.
103                        // If client and server happen to use the same `std`,
104                        // `catch_unwind` asserts that the panic counter was 0,
105                        // even when the closure passed to it didn't panic.
106                        let r = if thread::panicking() {
107                            Ok(call_method())
108                        } else {
109                            panic::catch_unwind(panic::AssertUnwindSafe(call_method))
110                                .map_err(PanicMessage::from)
111                        };
112
113                        buf.clear();
114                        r.encode(&mut buf, handle_store);
115                    })*
116                }
117                buf
118            }
119        }
120    }
121}
122with_api!(define_dispatcher, MarkedTokenStream<S>, MarkedSpan<S>, MarkedSymbol<S>);
123
124// This trait is currently only implemented and used once, inside of this crate.
125// We keep it public to allow implementing more complex execution strategies in
126// the future, such as wasm proc-macros.
127pub trait ExecutionStrategy {
128    fn run_bridge_and_client(
129        &self,
130        dispatcher: &mut Dispatcher<impl Server>,
131        input: Buffer,
132        run_client: extern "C" fn(BridgeConfig<'_>) -> Buffer,
133        force_show_panics: bool,
134    ) -> Buffer;
135}
136
137thread_local! {
138    /// While running a proc-macro with the same-thread executor, this flag will
139    /// be set, forcing nested proc-macro invocations (e.g. due to
140    /// `TokenStream::expand_expr`) to be run using a cross-thread executor.
141    ///
142    /// This is required as the thread-local state in the proc_macro client does
143    /// not handle being re-entered, and will invalidate all `Symbol`s when
144    /// entering a nested macro.
145    static ALREADY_RUNNING_SAME_THREAD: Cell<bool> = const { Cell::new(false) };
146}
147
148/// Keep `ALREADY_RUNNING_SAME_THREAD` (see also its documentation)
149/// set to `true`, preventing same-thread reentrance.
150struct RunningSameThreadGuard(());
151
152impl RunningSameThreadGuard {
153    fn new() -> Self {
154        let already_running = ALREADY_RUNNING_SAME_THREAD.replace(true);
155        assert!(
156            !already_running,
157            "same-thread nesting (\"reentrance\") of proc macro executions is not supported"
158        );
159        RunningSameThreadGuard(())
160    }
161}
162
163impl Drop for RunningSameThreadGuard {
164    fn drop(&mut self) {
165        ALREADY_RUNNING_SAME_THREAD.set(false);
166    }
167}
168
169pub struct MaybeCrossThread {
170    pub cross_thread: bool,
171}
172
173pub const SAME_THREAD: MaybeCrossThread = MaybeCrossThread { cross_thread: false };
174pub const CROSS_THREAD: MaybeCrossThread = MaybeCrossThread { cross_thread: true };
175
176impl ExecutionStrategy for MaybeCrossThread {
177    fn run_bridge_and_client(
178        &self,
179        dispatcher: &mut Dispatcher<impl Server>,
180        input: Buffer,
181        run_client: extern "C" fn(BridgeConfig<'_>) -> Buffer,
182        force_show_panics: bool,
183    ) -> Buffer {
184        if self.cross_thread || ALREADY_RUNNING_SAME_THREAD.get() {
185            let (mut server, mut client) = MessagePipe::new();
186
187            let join_handle = thread::spawn(move || {
188                let mut dispatch = |b: Buffer| -> Buffer {
189                    client.send(b);
190                    client.recv().expect("server died while client waiting for reply")
191                };
192
193                run_client(BridgeConfig {
194                    input,
195                    dispatch: (&mut dispatch).into(),
196                    force_show_panics,
197                })
198            });
199
200            while let Some(b) = server.recv() {
201                server.send(dispatcher.dispatch(b));
202            }
203
204            join_handle.join().unwrap()
205        } else {
206            let _guard = RunningSameThreadGuard::new();
207
208            let mut dispatch = |buf| dispatcher.dispatch(buf);
209
210            run_client(BridgeConfig { input, dispatch: (&mut dispatch).into(), force_show_panics })
211        }
212    }
213}
214
215/// A message pipe used for communicating between server and client threads.
216struct MessagePipe<T> {
217    tx: mpsc::SyncSender<T>,
218    rx: mpsc::Receiver<T>,
219}
220
221impl<T> MessagePipe<T> {
222    /// Creates a new pair of endpoints for the message pipe.
223    fn new() -> (Self, Self) {
224        let (tx1, rx1) = mpsc::sync_channel(1);
225        let (tx2, rx2) = mpsc::sync_channel(1);
226        (MessagePipe { tx: tx1, rx: rx2 }, MessagePipe { tx: tx2, rx: rx1 })
227    }
228
229    /// Send a message to the other endpoint of this pipe.
230    fn send(&mut self, value: T) {
231        self.tx.send(value).unwrap();
232    }
233
234    /// Receive a message from the other endpoint of this pipe.
235    ///
236    /// Returns `None` if the other end of the pipe has been destroyed, and no
237    /// message was received.
238    fn recv(&mut self) -> Option<T> {
239        self.rx.recv().ok()
240    }
241}
242
243fn run_server<
244    S: Server,
245    I: Encode<HandleStore<S>>,
246    O: for<'a, 's> Decode<'a, 's, HandleStore<S>>,
247>(
248    strategy: &impl ExecutionStrategy,
249    handle_counters: &'static client::HandleCounters,
250    server: S,
251    input: I,
252    run_client: extern "C" fn(BridgeConfig<'_>) -> Buffer,
253    force_show_panics: bool,
254) -> Result<O, PanicMessage> {
255    let mut dispatcher = Dispatcher { handle_store: HandleStore::new(handle_counters), server };
256
257    let globals = dispatcher.server.globals();
258
259    let mut buf = Buffer::new();
260    (<ExpnGlobals<MarkedSpan<S>> as Mark>::mark(globals), input)
261        .encode(&mut buf, &mut dispatcher.handle_store);
262
263    buf = strategy.run_bridge_and_client(&mut dispatcher, buf, run_client, force_show_panics);
264
265    Result::decode(&mut &buf[..], &mut dispatcher.handle_store)
266}
267
268impl client::Client<crate::TokenStream, crate::TokenStream> {
269    pub fn run<S>(
270        &self,
271        strategy: &impl ExecutionStrategy,
272        server: S,
273        input: S::TokenStream,
274        force_show_panics: bool,
275    ) -> Result<S::TokenStream, PanicMessage>
276    where
277        S: Server,
278    {
279        let client::Client { handle_counters, run, _marker } = *self;
280        run_server(
281            strategy,
282            handle_counters,
283            server,
284            <MarkedTokenStream<S>>::mark(input),
285            run,
286            force_show_panics,
287        )
288        .map(|s| <Option<MarkedTokenStream<S>>>::unmark(s).unwrap_or_default())
289    }
290}
291
292impl client::Client<(crate::TokenStream, crate::TokenStream), crate::TokenStream> {
293    pub fn run<S>(
294        &self,
295        strategy: &impl ExecutionStrategy,
296        server: S,
297        input: S::TokenStream,
298        input2: S::TokenStream,
299        force_show_panics: bool,
300    ) -> Result<S::TokenStream, PanicMessage>
301    where
302        S: Server,
303    {
304        let client::Client { handle_counters, run, _marker } = *self;
305        run_server(
306            strategy,
307            handle_counters,
308            server,
309            (<MarkedTokenStream<S>>::mark(input), <MarkedTokenStream<S>>::mark(input2)),
310            run,
311            force_show_panics,
312        )
313        .map(|s| <Option<MarkedTokenStream<S>>>::unmark(s).unwrap_or_default())
314    }
315}