1use std::cell::Cell;
4use std::marker::PhantomData;
5
6use super::*;
7
8macro_rules! define_server_handles {
9 (
10 'owned: $($oty:ident,)*
11 'interned: $($ity:ident,)*
12 ) => {
13 #[allow(non_snake_case)]
14 pub(super) struct HandleStore<S: Types> {
15 $($oty: handle::OwnedStore<S::$oty>,)*
16 $($ity: handle::InternedStore<S::$ity>,)*
17 }
18
19 impl<S: Types> HandleStore<S> {
20 fn new(handle_counters: &'static client::HandleCounters) -> Self {
21 HandleStore {
22 $($oty: handle::OwnedStore::new(&handle_counters.$oty),)*
23 $($ity: handle::InternedStore::new(&handle_counters.$ity),)*
24 }
25 }
26 }
27
28 $(
29 impl<S: Types> Encode<HandleStore<MarkedTypes<S>>> for Marked<S::$oty, client::$oty> {
30 fn encode(self, w: &mut Writer, s: &mut HandleStore<MarkedTypes<S>>) {
31 s.$oty.alloc(self).encode(w, s);
32 }
33 }
34
35 impl<S: Types> DecodeMut<'_, '_, HandleStore<MarkedTypes<S>>>
36 for Marked<S::$oty, client::$oty>
37 {
38 fn decode(r: &mut Reader<'_>, s: &mut HandleStore<MarkedTypes<S>>) -> Self {
39 s.$oty.take(handle::Handle::decode(r, &mut ()))
40 }
41 }
42
43 impl<'s, S: Types> Decode<'_, 's, HandleStore<MarkedTypes<S>>>
44 for &'s Marked<S::$oty, client::$oty>
45 {
46 fn decode(r: &mut Reader<'_>, s: &'s HandleStore<MarkedTypes<S>>) -> Self {
47 &s.$oty[handle::Handle::decode(r, &mut ())]
48 }
49 }
50
51 impl<'s, S: Types> DecodeMut<'_, 's, HandleStore<MarkedTypes<S>>>
52 for &'s mut Marked<S::$oty, client::$oty>
53 {
54 fn decode(
55 r: &mut Reader<'_>,
56 s: &'s mut HandleStore<MarkedTypes<S>>
57 ) -> Self {
58 &mut s.$oty[handle::Handle::decode(r, &mut ())]
59 }
60 }
61 )*
62
63 $(
64 impl<S: Types> Encode<HandleStore<MarkedTypes<S>>> for Marked<S::$ity, client::$ity> {
65 fn encode(self, w: &mut Writer, s: &mut HandleStore<MarkedTypes<S>>) {
66 s.$ity.alloc(self).encode(w, s);
67 }
68 }
69
70 impl<S: Types> DecodeMut<'_, '_, HandleStore<MarkedTypes<S>>>
71 for Marked<S::$ity, client::$ity>
72 {
73 fn decode(r: &mut Reader<'_>, s: &mut HandleStore<MarkedTypes<S>>) -> Self {
74 s.$ity.copy(handle::Handle::decode(r, &mut ()))
75 }
76 }
77 )*
78 }
79}
80with_api_handle_types!(define_server_handles);
81
82pub trait Types {
83 type FreeFunctions: 'static;
84 type TokenStream: 'static + Clone;
85 type Span: 'static + Copy + Eq + Hash;
86 type Symbol: 'static;
87}
88
89macro_rules! associated_fn {
92 (fn drop(&mut self, $arg:ident: $arg_ty:ty)) =>
93 (fn drop(&mut self, $arg: $arg_ty) { mem::drop($arg) });
94
95 (fn clone(&mut self, $arg:ident: $arg_ty:ty) -> $ret_ty:ty) =>
96 (fn clone(&mut self, $arg: $arg_ty) -> $ret_ty { $arg.clone() });
97
98 ($($item:tt)*) => ($($item)*;)
99}
100
101macro_rules! declare_server_traits {
102 ($($name:ident {
103 $(fn $method:ident($($arg:ident: $arg_ty:ty),* $(,)?) $(-> $ret_ty:ty)?;)*
104 }),* $(,)?) => {
105 $(pub trait $name: Types {
106 $(associated_fn!(fn $method(&mut self, $($arg: $arg_ty),*) $(-> $ret_ty)?);)*
107 })*
108
109 pub trait Server: Types $(+ $name)* {
110 fn globals(&mut self) -> ExpnGlobals<Self::Span>;
111
112 fn intern_symbol(ident: &str) -> Self::Symbol;
114
115 fn with_symbol_string(symbol: &Self::Symbol, f: impl FnOnce(&str));
117 }
118 }
119}
120with_api!(Self, self_, declare_server_traits);
121
122pub(super) struct MarkedTypes<S: Types>(S);
123
124impl<S: Server> Server for MarkedTypes<S> {
125 fn globals(&mut self) -> ExpnGlobals<Self::Span> {
126 <_>::mark(Server::globals(&mut self.0))
127 }
128 fn intern_symbol(ident: &str) -> Self::Symbol {
129 <_>::mark(S::intern_symbol(ident))
130 }
131 fn with_symbol_string(symbol: &Self::Symbol, f: impl FnOnce(&str)) {
132 S::with_symbol_string(symbol.unmark(), f)
133 }
134}
135
136macro_rules! define_mark_types_impls {
137 ($($name:ident {
138 $(fn $method:ident($($arg:ident: $arg_ty:ty),* $(,)?) $(-> $ret_ty:ty)?;)*
139 }),* $(,)?) => {
140 impl<S: Types> Types for MarkedTypes<S> {
141 $(type $name = Marked<S::$name, client::$name>;)*
142 }
143
144 $(impl<S: $name> $name for MarkedTypes<S> {
145 $(fn $method(&mut self, $($arg: $arg_ty),*) $(-> $ret_ty)? {
146 <_>::mark($name::$method(&mut self.0, $($arg.unmark()),*))
147 })*
148 })*
149 }
150}
151with_api!(Self, self_, define_mark_types_impls);
152
153struct Dispatcher<S: Types> {
154 handle_store: HandleStore<S>,
155 server: S,
156}
157
158macro_rules! define_dispatcher_impl {
159 ($($name:ident {
160 $(fn $method:ident($($arg:ident: $arg_ty:ty),* $(,)?) $(-> $ret_ty:ty)?;)*
161 }),* $(,)?) => {
162 pub trait DispatcherTrait {
164 $(type $name;)*
166
167 fn dispatch(&mut self, buf: Buffer) -> Buffer;
168 }
169
170 impl<S: Server> DispatcherTrait for Dispatcher<MarkedTypes<S>> {
171 $(type $name = <MarkedTypes<S> as Types>::$name;)*
172
173 fn dispatch(&mut self, mut buf: Buffer) -> Buffer {
174 let Dispatcher { handle_store, server } = self;
175
176 let mut reader = &buf[..];
177 match api_tags::Method::decode(&mut reader, &mut ()) {
178 $(api_tags::Method::$name(m) => match m {
179 $(api_tags::$name::$method => {
180 let mut call_method = || {
181 $(let $arg = <$arg_ty>::decode(&mut reader, handle_store);)*
182 $name::$method(server, $($arg),*)
183 };
184 let r = if thread::panicking() {
189 Ok(call_method())
190 } else {
191 panic::catch_unwind(panic::AssertUnwindSafe(call_method))
192 .map_err(PanicMessage::from)
193 };
194
195 buf.clear();
196 r.encode(&mut buf, handle_store);
197 })*
198 }),*
199 }
200 buf
201 }
202 }
203 }
204}
205with_api!(Self, self_, define_dispatcher_impl);
206
207pub trait ExecutionStrategy {
208 fn run_bridge_and_client(
209 &self,
210 dispatcher: &mut impl DispatcherTrait,
211 input: Buffer,
212 run_client: extern "C" fn(BridgeConfig<'_>) -> Buffer,
213 force_show_panics: bool,
214 ) -> Buffer;
215}
216
217thread_local! {
218 static ALREADY_RUNNING_SAME_THREAD: Cell<bool> = const { Cell::new(false) };
226}
227
228struct RunningSameThreadGuard(());
231
232impl RunningSameThreadGuard {
233 fn new() -> Self {
234 let already_running = ALREADY_RUNNING_SAME_THREAD.replace(true);
235 assert!(
236 !already_running,
237 "same-thread nesting (\"reentrance\") of proc macro executions is not supported"
238 );
239 RunningSameThreadGuard(())
240 }
241}
242
243impl Drop for RunningSameThreadGuard {
244 fn drop(&mut self) {
245 ALREADY_RUNNING_SAME_THREAD.set(false);
246 }
247}
248
249pub struct MaybeCrossThread<P> {
250 cross_thread: bool,
251 marker: PhantomData<P>,
252}
253
254impl<P> MaybeCrossThread<P> {
255 pub const fn new(cross_thread: bool) -> Self {
256 MaybeCrossThread { cross_thread, marker: PhantomData }
257 }
258}
259
260impl<P> ExecutionStrategy for MaybeCrossThread<P>
261where
262 P: MessagePipe<Buffer> + Send + 'static,
263{
264 fn run_bridge_and_client(
265 &self,
266 dispatcher: &mut impl DispatcherTrait,
267 input: Buffer,
268 run_client: extern "C" fn(BridgeConfig<'_>) -> Buffer,
269 force_show_panics: bool,
270 ) -> Buffer {
271 if self.cross_thread || ALREADY_RUNNING_SAME_THREAD.get() {
272 <CrossThread<P>>::new().run_bridge_and_client(
273 dispatcher,
274 input,
275 run_client,
276 force_show_panics,
277 )
278 } else {
279 SameThread.run_bridge_and_client(dispatcher, input, run_client, force_show_panics)
280 }
281 }
282}
283
284pub struct SameThread;
285
286impl ExecutionStrategy for SameThread {
287 fn run_bridge_and_client(
288 &self,
289 dispatcher: &mut impl DispatcherTrait,
290 input: Buffer,
291 run_client: extern "C" fn(BridgeConfig<'_>) -> Buffer,
292 force_show_panics: bool,
293 ) -> Buffer {
294 let _guard = RunningSameThreadGuard::new();
295
296 let mut dispatch = |buf| dispatcher.dispatch(buf);
297
298 run_client(BridgeConfig { input, dispatch: (&mut dispatch).into(), force_show_panics })
299 }
300}
301
302pub struct CrossThread<P>(PhantomData<P>);
303
304impl<P> CrossThread<P> {
305 pub const fn new() -> Self {
306 CrossThread(PhantomData)
307 }
308}
309
310impl<P> ExecutionStrategy for CrossThread<P>
311where
312 P: MessagePipe<Buffer> + Send + 'static,
313{
314 fn run_bridge_and_client(
315 &self,
316 dispatcher: &mut impl DispatcherTrait,
317 input: Buffer,
318 run_client: extern "C" fn(BridgeConfig<'_>) -> Buffer,
319 force_show_panics: bool,
320 ) -> Buffer {
321 let (mut server, mut client) = P::new();
322
323 let join_handle = thread::spawn(move || {
324 let mut dispatch = |b: Buffer| -> Buffer {
325 client.send(b);
326 client.recv().expect("server died while client waiting for reply")
327 };
328
329 run_client(BridgeConfig { input, dispatch: (&mut dispatch).into(), force_show_panics })
330 });
331
332 while let Some(b) = server.recv() {
333 server.send(dispatcher.dispatch(b));
334 }
335
336 join_handle.join().unwrap()
337 }
338}
339
340pub trait MessagePipe<T>: Sized {
342 fn new() -> (Self, Self);
344
345 fn send(&mut self, value: T);
347
348 fn recv(&mut self) -> Option<T>;
353}
354
355fn run_server<
356 S: Server,
357 I: Encode<HandleStore<MarkedTypes<S>>>,
358 O: for<'a, 's> DecodeMut<'a, 's, HandleStore<MarkedTypes<S>>>,
359>(
360 strategy: &impl ExecutionStrategy,
361 handle_counters: &'static client::HandleCounters,
362 server: S,
363 input: I,
364 run_client: extern "C" fn(BridgeConfig<'_>) -> Buffer,
365 force_show_panics: bool,
366) -> Result<O, PanicMessage> {
367 let mut dispatcher =
368 Dispatcher { handle_store: HandleStore::new(handle_counters), server: MarkedTypes(server) };
369
370 let globals = dispatcher.server.globals();
371
372 let mut buf = Buffer::new();
373 (globals, input).encode(&mut buf, &mut dispatcher.handle_store);
374
375 buf = strategy.run_bridge_and_client(&mut dispatcher, buf, run_client, force_show_panics);
376
377 Result::decode(&mut &buf[..], &mut dispatcher.handle_store)
378}
379
380impl client::Client<crate::TokenStream, crate::TokenStream> {
381 pub fn run<S>(
382 &self,
383 strategy: &impl ExecutionStrategy,
384 server: S,
385 input: S::TokenStream,
386 force_show_panics: bool,
387 ) -> Result<S::TokenStream, PanicMessage>
388 where
389 S: Server,
390 S::TokenStream: Default,
391 {
392 let client::Client { handle_counters, run, _marker } = *self;
393 run_server(
394 strategy,
395 handle_counters,
396 server,
397 <MarkedTypes<S> as Types>::TokenStream::mark(input),
398 run,
399 force_show_panics,
400 )
401 .map(|s| <Option<<MarkedTypes<S> as Types>::TokenStream>>::unmark(s).unwrap_or_default())
402 }
403}
404
405impl client::Client<(crate::TokenStream, crate::TokenStream), crate::TokenStream> {
406 pub fn run<S>(
407 &self,
408 strategy: &impl ExecutionStrategy,
409 server: S,
410 input: S::TokenStream,
411 input2: S::TokenStream,
412 force_show_panics: bool,
413 ) -> Result<S::TokenStream, PanicMessage>
414 where
415 S: Server,
416 S::TokenStream: Default,
417 {
418 let client::Client { handle_counters, run, _marker } = *self;
419 run_server(
420 strategy,
421 handle_counters,
422 server,
423 (
424 <MarkedTypes<S> as Types>::TokenStream::mark(input),
425 <MarkedTypes<S> as Types>::TokenStream::mark(input2),
426 ),
427 run,
428 force_show_panics,
429 )
430 .map(|s| <Option<<MarkedTypes<S> as Types>::TokenStream>>::unmark(s).unwrap_or_default())
431 }
432}