]> git.lizzy.rs Git - rust.git/blob - src/libproc_macro/bridge/client.rs
Account for `ty::Error` when suggesting `impl Trait` or `Box<dyn Trait>`
[rust.git] / src / libproc_macro / bridge / client.rs
1 //! Client-side types.
2
3 use super::*;
4
5 macro_rules! define_handles {
6     (
7         'owned: $($oty:ident,)*
8         'interned: $($ity:ident,)*
9     ) => {
10         #[repr(C)]
11         #[allow(non_snake_case)]
12         pub struct HandleCounters {
13             $($oty: AtomicUsize,)*
14             $($ity: AtomicUsize,)*
15         }
16
17         impl HandleCounters {
18             // FIXME(eddyb) use a reference to the `static COUNTERS`, intead of
19             // a wrapper `fn` pointer, once `const fn` can reference `static`s.
20             extern "C" fn get() -> &'static Self {
21                 static COUNTERS: HandleCounters = HandleCounters {
22                     $($oty: AtomicUsize::new(1),)*
23                     $($ity: AtomicUsize::new(1),)*
24                 };
25                 &COUNTERS
26             }
27         }
28
29         // FIXME(eddyb) generate the definition of `HandleStore` in `server.rs`.
30         #[repr(C)]
31         #[allow(non_snake_case)]
32         pub(super) struct HandleStore<S: server::Types> {
33             $($oty: handle::OwnedStore<S::$oty>,)*
34             $($ity: handle::InternedStore<S::$ity>,)*
35         }
36
37         impl<S: server::Types> HandleStore<S> {
38             pub(super) fn new(handle_counters: &'static HandleCounters) -> Self {
39                 HandleStore {
40                     $($oty: handle::OwnedStore::new(&handle_counters.$oty),)*
41                     $($ity: handle::InternedStore::new(&handle_counters.$ity),)*
42                 }
43             }
44         }
45
46         $(
47             #[repr(C)]
48             pub(crate) struct $oty(handle::Handle);
49             impl !Send for $oty {}
50             impl !Sync for $oty {}
51
52             // Forward `Drop::drop` to the inherent `drop` method.
53             impl Drop for $oty {
54                 fn drop(&mut self) {
55                     $oty(self.0).drop();
56                 }
57             }
58
59             impl<S> Encode<S> for $oty {
60                 fn encode(self, w: &mut Writer, s: &mut S) {
61                     let handle = self.0;
62                     mem::forget(self);
63                     handle.encode(w, s);
64                 }
65             }
66
67             impl<S: server::Types> DecodeMut<'_, '_, HandleStore<server::MarkedTypes<S>>>
68                 for Marked<S::$oty, $oty>
69             {
70                 fn decode(r: &mut Reader<'_>, s: &mut HandleStore<server::MarkedTypes<S>>) -> Self {
71                     s.$oty.take(handle::Handle::decode(r, &mut ()))
72                 }
73             }
74
75             impl<S> Encode<S> for &$oty {
76                 fn encode(self, w: &mut Writer, s: &mut S) {
77                     self.0.encode(w, s);
78                 }
79             }
80
81             impl<S: server::Types> Decode<'_, 's, HandleStore<server::MarkedTypes<S>>>
82                 for &'s Marked<S::$oty, $oty>
83             {
84                 fn decode(r: &mut Reader<'_>, s: &'s HandleStore<server::MarkedTypes<S>>) -> Self {
85                     &s.$oty[handle::Handle::decode(r, &mut ())]
86                 }
87             }
88
89             impl<S> Encode<S> for &mut $oty {
90                 fn encode(self, w: &mut Writer, s: &mut S) {
91                     self.0.encode(w, s);
92                 }
93             }
94
95             impl<S: server::Types> DecodeMut<'_, 's, HandleStore<server::MarkedTypes<S>>>
96                 for &'s mut Marked<S::$oty, $oty>
97             {
98                 fn decode(
99                     r: &mut Reader<'_>,
100                     s: &'s mut HandleStore<server::MarkedTypes<S>>
101                 ) -> Self {
102                     &mut s.$oty[handle::Handle::decode(r, &mut ())]
103                 }
104             }
105
106             impl<S: server::Types> Encode<HandleStore<server::MarkedTypes<S>>>
107                 for Marked<S::$oty, $oty>
108             {
109                 fn encode(self, w: &mut Writer, s: &mut HandleStore<server::MarkedTypes<S>>) {
110                     s.$oty.alloc(self).encode(w, s);
111                 }
112             }
113
114             impl<S> DecodeMut<'_, '_, S> for $oty {
115                 fn decode(r: &mut Reader<'_>, s: &mut S) -> Self {
116                     $oty(handle::Handle::decode(r, s))
117                 }
118             }
119         )*
120
121         $(
122             #[repr(C)]
123             #[derive(Copy, Clone, PartialEq, Eq, Hash)]
124             pub(crate) struct $ity(handle::Handle);
125             impl !Send for $ity {}
126             impl !Sync for $ity {}
127
128             impl<S> Encode<S> for $ity {
129                 fn encode(self, w: &mut Writer, s: &mut S) {
130                     self.0.encode(w, s);
131                 }
132             }
133
134             impl<S: server::Types> DecodeMut<'_, '_, HandleStore<server::MarkedTypes<S>>>
135                 for Marked<S::$ity, $ity>
136             {
137                 fn decode(r: &mut Reader<'_>, s: &mut HandleStore<server::MarkedTypes<S>>) -> Self {
138                     s.$ity.copy(handle::Handle::decode(r, &mut ()))
139                 }
140             }
141
142             impl<S: server::Types> Encode<HandleStore<server::MarkedTypes<S>>>
143                 for Marked<S::$ity, $ity>
144             {
145                 fn encode(self, w: &mut Writer, s: &mut HandleStore<server::MarkedTypes<S>>) {
146                     s.$ity.alloc(self).encode(w, s);
147                 }
148             }
149
150             impl<S> DecodeMut<'_, '_, S> for $ity {
151                 fn decode(r: &mut Reader<'_>, s: &mut S) -> Self {
152                     $ity(handle::Handle::decode(r, s))
153                 }
154             }
155         )*
156     }
157 }
158 define_handles! {
159     'owned:
160     TokenStream,
161     TokenStreamBuilder,
162     TokenStreamIter,
163     Group,
164     Literal,
165     SourceFile,
166     MultiSpan,
167     Diagnostic,
168
169     'interned:
170     Punct,
171     Ident,
172     Span,
173 }
174
175 // FIXME(eddyb) generate these impls by pattern-matching on the
176 // names of methods - also could use the presence of `fn drop`
177 // to distinguish between 'owned and 'interned, above.
178 // Alternatively, special 'modes" could be listed of types in with_api
179 // instead of pattern matching on methods, here and in server decl.
180
181 impl Clone for TokenStream {
182     fn clone(&self) -> Self {
183         self.clone()
184     }
185 }
186
187 impl Clone for TokenStreamIter {
188     fn clone(&self) -> Self {
189         self.clone()
190     }
191 }
192
193 impl Clone for Group {
194     fn clone(&self) -> Self {
195         self.clone()
196     }
197 }
198
199 impl Clone for Literal {
200     fn clone(&self) -> Self {
201         self.clone()
202     }
203 }
204
205 // FIXME(eddyb) `Literal` should not expose internal `Debug` impls.
206 impl fmt::Debug for Literal {
207     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
208         f.write_str(&self.debug())
209     }
210 }
211
212 impl Clone for SourceFile {
213     fn clone(&self) -> Self {
214         self.clone()
215     }
216 }
217
218 impl fmt::Debug for Span {
219     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
220         f.write_str(&self.debug())
221     }
222 }
223
224 macro_rules! define_client_side {
225     ($($name:ident {
226         $(fn $method:ident($($arg:ident: $arg_ty:ty),* $(,)?) $(-> $ret_ty:ty)*;)*
227     }),* $(,)?) => {
228         $(impl $name {
229             $(pub(crate) fn $method($($arg: $arg_ty),*) $(-> $ret_ty)* {
230                 Bridge::with(|bridge| {
231                     let mut b = bridge.cached_buffer.take();
232
233                     b.clear();
234                     api_tags::Method::$name(api_tags::$name::$method).encode(&mut b, &mut ());
235                     reverse_encode!(b; $($arg),*);
236
237                     b = bridge.dispatch.call(b);
238
239                     let r = Result::<_, PanicMessage>::decode(&mut &b[..], &mut ());
240
241                     bridge.cached_buffer = b;
242
243                     r.unwrap_or_else(|e| panic::resume_unwind(e.into()))
244                 })
245             })*
246         })*
247     }
248 }
249 with_api!(self, self, define_client_side);
250
251 enum BridgeState<'a> {
252     /// No server is currently connected to this client.
253     NotConnected,
254
255     /// A server is connected and available for requests.
256     Connected(Bridge<'a>),
257
258     /// Access to the bridge is being exclusively acquired
259     /// (e.g., during `BridgeState::with`).
260     InUse,
261 }
262
263 enum BridgeStateL {}
264
265 impl<'a> scoped_cell::ApplyL<'a> for BridgeStateL {
266     type Out = BridgeState<'a>;
267 }
268
269 thread_local! {
270     static BRIDGE_STATE: scoped_cell::ScopedCell<BridgeStateL> =
271         scoped_cell::ScopedCell::new(BridgeState::NotConnected);
272 }
273
274 impl BridgeState<'_> {
275     /// Take exclusive control of the thread-local
276     /// `BridgeState`, and pass it to `f`, mutably.
277     /// The state will be restored after `f` exits, even
278     /// by panic, including modifications made to it by `f`.
279     ///
280     /// N.B., while `f` is running, the thread-local state
281     /// is `BridgeState::InUse`.
282     fn with<R>(f: impl FnOnce(&mut BridgeState<'_>) -> R) -> R {
283         BRIDGE_STATE.with(|state| {
284             state.replace(BridgeState::InUse, |mut state| {
285                 // FIXME(#52812) pass `f` directly to `replace` when `RefMutL` is gone
286                 f(&mut *state)
287             })
288         })
289     }
290 }
291
292 impl Bridge<'_> {
293     fn enter<R>(self, f: impl FnOnce() -> R) -> R {
294         // Hide the default panic output within `proc_macro` expansions.
295         // NB. the server can't do this because it may use a different libstd.
296         static HIDE_PANICS_DURING_EXPANSION: Once = Once::new();
297         HIDE_PANICS_DURING_EXPANSION.call_once(|| {
298             let prev = panic::take_hook();
299             panic::set_hook(Box::new(move |info| {
300                 let hide = BridgeState::with(|state| match state {
301                     BridgeState::NotConnected => false,
302                     BridgeState::Connected(_) | BridgeState::InUse => true,
303                 });
304                 if !hide {
305                     prev(info)
306                 }
307             }));
308         });
309
310         BRIDGE_STATE.with(|state| state.set(BridgeState::Connected(self), f))
311     }
312
313     fn with<R>(f: impl FnOnce(&mut Bridge<'_>) -> R) -> R {
314         BridgeState::with(|state| match state {
315             BridgeState::NotConnected => {
316                 panic!("procedural macro API is used outside of a procedural macro");
317             }
318             BridgeState::InUse => {
319                 panic!("procedural macro API is used while it's already in use");
320             }
321             BridgeState::Connected(bridge) => f(bridge),
322         })
323     }
324 }
325
326 /// A client-side "global object" (usually a function pointer),
327 /// which may be using a different `proc_macro` from the one
328 /// used by the server, but can be interacted with compatibly.
329 ///
330 /// N.B., `F` must have FFI-friendly memory layout (e.g., a pointer).
331 /// The call ABI of function pointers used for `F` doesn't
332 /// need to match between server and client, since it's only
333 /// passed between them and (eventually) called by the client.
334 #[repr(C)]
335 #[derive(Copy, Clone)]
336 pub struct Client<F> {
337     // FIXME(eddyb) use a reference to the `static COUNTERS`, intead of
338     // a wrapper `fn` pointer, once `const fn` can reference `static`s.
339     pub(super) get_handle_counters: extern "C" fn() -> &'static HandleCounters,
340     pub(super) run: extern "C" fn(Bridge<'_>, F) -> Buffer<u8>,
341     pub(super) f: F,
342 }
343
344 /// Client-side helper for handling client panics, entering the bridge,
345 /// deserializing input and serializing output.
346 // FIXME(eddyb) maybe replace `Bridge::enter` with this?
347 fn run_client<A: for<'a, 's> DecodeMut<'a, 's, ()>, R: Encode<()>>(
348     mut bridge: Bridge<'_>,
349     f: impl FnOnce(A) -> R,
350 ) -> Buffer<u8> {
351     // The initial `cached_buffer` contains the input.
352     let mut b = bridge.cached_buffer.take();
353
354     panic::catch_unwind(panic::AssertUnwindSafe(|| {
355         bridge.enter(|| {
356             let reader = &mut &b[..];
357             let input = A::decode(reader, &mut ());
358
359             // Put the `cached_buffer` back in the `Bridge`, for requests.
360             Bridge::with(|bridge| bridge.cached_buffer = b.take());
361
362             let output = f(input);
363
364             // Take the `cached_buffer` back out, for the output value.
365             b = Bridge::with(|bridge| bridge.cached_buffer.take());
366
367             // HACK(eddyb) Separate encoding a success value (`Ok(output)`)
368             // from encoding a panic (`Err(e: PanicMessage)`) to avoid
369             // having handles outside the `bridge.enter(|| ...)` scope, and
370             // to catch panics that could happen while encoding the success.
371             //
372             // Note that panics should be impossible beyond this point, but
373             // this is defensively trying to avoid any accidental panicking
374             // reaching the `extern "C"` (which should `abort` but may not
375             // at the moment, so this is also potentially preventing UB).
376             b.clear();
377             Ok::<_, ()>(output).encode(&mut b, &mut ());
378         })
379     }))
380     .map_err(PanicMessage::from)
381     .unwrap_or_else(|e| {
382         b.clear();
383         Err::<(), _>(e).encode(&mut b, &mut ());
384     });
385     b
386 }
387
388 impl Client<fn(crate::TokenStream) -> crate::TokenStream> {
389     pub const fn expand1(f: fn(crate::TokenStream) -> crate::TokenStream) -> Self {
390         extern "C" fn run(
391             bridge: Bridge<'_>,
392             f: impl FnOnce(crate::TokenStream) -> crate::TokenStream,
393         ) -> Buffer<u8> {
394             run_client(bridge, |input| f(crate::TokenStream(input)).0)
395         }
396         Client { get_handle_counters: HandleCounters::get, run, f }
397     }
398 }
399
400 impl Client<fn(crate::TokenStream, crate::TokenStream) -> crate::TokenStream> {
401     pub const fn expand2(
402         f: fn(crate::TokenStream, crate::TokenStream) -> crate::TokenStream,
403     ) -> Self {
404         extern "C" fn run(
405             bridge: Bridge<'_>,
406             f: impl FnOnce(crate::TokenStream, crate::TokenStream) -> crate::TokenStream,
407         ) -> Buffer<u8> {
408             run_client(bridge, |(input, input2)| {
409                 f(crate::TokenStream(input), crate::TokenStream(input2)).0
410             })
411         }
412         Client { get_handle_counters: HandleCounters::get, run, f }
413     }
414 }
415
416 #[repr(C)]
417 #[derive(Copy, Clone)]
418 pub enum ProcMacro {
419     CustomDerive {
420         trait_name: &'static str,
421         attributes: &'static [&'static str],
422         client: Client<fn(crate::TokenStream) -> crate::TokenStream>,
423     },
424
425     Attr {
426         name: &'static str,
427         client: Client<fn(crate::TokenStream, crate::TokenStream) -> crate::TokenStream>,
428     },
429
430     Bang {
431         name: &'static str,
432         client: Client<fn(crate::TokenStream) -> crate::TokenStream>,
433     },
434 }
435
436 impl ProcMacro {
437     pub fn name(&self) -> &'static str {
438         match self {
439             ProcMacro::CustomDerive { trait_name, .. } => trait_name,
440             ProcMacro::Attr { name, .. } => name,
441             ProcMacro::Bang { name, .. } => name,
442         }
443     }
444
445     pub const fn custom_derive(
446         trait_name: &'static str,
447         attributes: &'static [&'static str],
448         expand: fn(crate::TokenStream) -> crate::TokenStream,
449     ) -> Self {
450         ProcMacro::CustomDerive { trait_name, attributes, client: Client::expand1(expand) }
451     }
452
453     pub const fn attr(
454         name: &'static str,
455         expand: fn(crate::TokenStream, crate::TokenStream) -> crate::TokenStream,
456     ) -> Self {
457         ProcMacro::Attr { name, client: Client::expand2(expand) }
458     }
459
460     pub const fn bang(
461         name: &'static str,
462         expand: fn(crate::TokenStream) -> crate::TokenStream,
463     ) -> Self {
464         ProcMacro::Bang { name, client: Client::expand1(expand) }
465     }
466 }