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 //! Client-side types.
15 macro_rules! define_handles {
17 'owned: $($oty:ident,)*
18 'interned: $($ity:ident,)*
21 #[allow(non_snake_case)]
22 pub struct HandleCounters {
23 $($oty: AtomicUsize,)*
24 $($ity: AtomicUsize,)*
28 // FIXME(#53451) public to work around `Cannot create local mono-item` ICE.
29 pub extern "C" fn get() -> &'static Self {
30 static COUNTERS: HandleCounters = HandleCounters {
31 $($oty: AtomicUsize::new(1),)*
32 $($ity: AtomicUsize::new(1),)*
38 // FIXME(eddyb) generate the definition of `HandleStore` in `server.rs`.
40 #[allow(non_snake_case)]
41 pub(super) struct HandleStore<S: server::Types> {
42 $($oty: handle::OwnedStore<S::$oty>,)*
43 $($ity: handle::InternedStore<S::$ity>,)*
46 impl<S: server::Types> HandleStore<S> {
47 pub(super) fn new(handle_counters: &'static HandleCounters) -> Self {
49 $($oty: handle::OwnedStore::new(&handle_counters.$oty),)*
50 $($ity: handle::InternedStore::new(&handle_counters.$ity),)*
57 pub(crate) struct $oty(handle::Handle);
58 impl !Send for $oty {}
59 impl !Sync for $oty {}
61 // Forward `Drop::drop` to the inherent `drop` method.
68 impl<S> Encode<S> for $oty {
69 fn encode(self, w: &mut Writer, s: &mut S) {
76 impl<S: server::Types> DecodeMut<'_, '_, HandleStore<server::MarkedTypes<S>>>
77 for Marked<S::$oty, $oty>
79 fn decode(r: &mut Reader, s: &mut HandleStore<server::MarkedTypes<S>>) -> Self {
80 s.$oty.take(handle::Handle::decode(r, &mut ()))
84 impl<S> Encode<S> for &$oty {
85 fn encode(self, w: &mut Writer, s: &mut S) {
90 impl<S: server::Types> Decode<'_, 's, HandleStore<server::MarkedTypes<S>>>
91 for &'s Marked<S::$oty, $oty>
93 fn decode(r: &mut Reader, s: &'s HandleStore<server::MarkedTypes<S>>) -> Self {
94 &s.$oty[handle::Handle::decode(r, &mut ())]
98 impl<S> Encode<S> for &mut $oty {
99 fn encode(self, w: &mut Writer, s: &mut S) {
104 impl<S: server::Types> DecodeMut<'_, 's, HandleStore<server::MarkedTypes<S>>>
105 for &'s mut Marked<S::$oty, $oty>
107 fn decode(r: &mut Reader, s: &'s mut HandleStore<server::MarkedTypes<S>>) -> Self {
108 &mut s.$oty[handle::Handle::decode(r, &mut ())]
112 impl<S: server::Types> Encode<HandleStore<server::MarkedTypes<S>>>
113 for Marked<S::$oty, $oty>
115 fn encode(self, w: &mut Writer, s: &mut HandleStore<server::MarkedTypes<S>>) {
116 s.$oty.alloc(self).encode(w, s);
120 impl<S> DecodeMut<'_, '_, S> for $oty {
121 fn decode(r: &mut Reader, s: &mut S) -> Self {
122 $oty(handle::Handle::decode(r, s))
129 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
130 pub(crate) struct $ity(handle::Handle);
131 impl !Send for $ity {}
132 impl !Sync for $ity {}
134 impl<S> Encode<S> for $ity {
135 fn encode(self, w: &mut Writer, s: &mut S) {
140 impl<S: server::Types> DecodeMut<'_, '_, HandleStore<server::MarkedTypes<S>>>
141 for Marked<S::$ity, $ity>
143 fn decode(r: &mut Reader, s: &mut HandleStore<server::MarkedTypes<S>>) -> Self {
144 s.$ity.copy(handle::Handle::decode(r, &mut ()))
148 impl<S: server::Types> Encode<HandleStore<server::MarkedTypes<S>>>
149 for Marked<S::$ity, $ity>
151 fn encode(self, w: &mut Writer, s: &mut HandleStore<server::MarkedTypes<S>>) {
152 s.$ity.alloc(self).encode(w, s);
156 impl<S> DecodeMut<'_, '_, S> for $ity {
157 fn decode(r: &mut Reader, s: &mut S) -> Self {
158 $ity(handle::Handle::decode(r, s))
181 // FIXME(eddyb) generate these impls by pattern-matching on the
182 // names of methods - also could use the presence of `fn drop`
183 // to distinguish between 'owned and 'interned, above.
184 // Alternatively, special 'modes" could be listed of types in with_api
185 // instead of pattern matching on methods, here and in server decl.
187 impl Clone for TokenStream {
188 fn clone(&self) -> Self {
193 impl Clone for TokenStreamIter {
194 fn clone(&self) -> Self {
199 impl Clone for Group {
200 fn clone(&self) -> Self {
205 impl Clone for Literal {
206 fn clone(&self) -> Self {
211 // FIXME(eddyb) `Literal` should not expose internal `Debug` impls.
212 impl fmt::Debug for Literal {
213 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
214 f.write_str(&self.debug())
218 impl Clone for SourceFile {
219 fn clone(&self) -> Self {
224 impl fmt::Debug for Span {
225 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
226 f.write_str(&self.debug())
230 macro_rules! define_client_side {
232 $(fn $method:ident($($arg:ident: $arg_ty:ty),* $(,)*) $(-> $ret_ty:ty)*;)*
235 $(pub(crate) fn $method($($arg: $arg_ty),*) $(-> $ret_ty)* {
236 Bridge::with(|bridge| {
237 let mut b = bridge.cached_buffer.take();
240 api_tags::Method::$name(api_tags::$name::$method).encode(&mut b, &mut ());
241 reverse_encode!(b; $($arg),*);
243 b = bridge.dispatch.call(b);
245 let r = Result::<_, PanicMessage>::decode(&mut &b[..], &mut ());
247 bridge.cached_buffer = b;
249 r.unwrap_or_else(|e| panic::resume_unwind(e.into()))
255 with_api!(self, self, define_client_side);
257 enum BridgeState<'a> {
258 /// No server is currently connected to this client.
261 /// A server is connected and available for requests.
262 Connected(Bridge<'a>),
264 /// Access to the bridge is being exclusively acquired
265 /// (e.g., during `BridgeState::with`).
271 impl<'a> scoped_cell::ApplyL<'a> for BridgeStateL {
272 type Out = BridgeState<'a>;
276 static BRIDGE_STATE: scoped_cell::ScopedCell<BridgeStateL> =
277 scoped_cell::ScopedCell::new(BridgeState::NotConnected);
280 impl BridgeState<'_> {
281 /// Take exclusive control of the thread-local
282 /// `BridgeState`, and pass it to `f`, mutably.
283 /// The state will be restored after `f` exits, even
284 /// by panic, including modifications made to it by `f`.
286 /// N.B., while `f` is running, the thread-local state
287 /// is `BridgeState::InUse`.
288 fn with<R>(f: impl FnOnce(&mut BridgeState) -> R) -> R {
289 BRIDGE_STATE.with(|state| {
290 state.replace(BridgeState::InUse, |mut state| {
291 // FIXME(#52812) pass `f` directly to `replace` when `RefMutL` is gone
299 fn enter<R>(self, f: impl FnOnce() -> R) -> R {
300 // Hide the default panic output within `proc_macro` expansions.
301 // NB. the server can't do this because it may use a different libstd.
302 static HIDE_PANICS_DURING_EXPANSION: Once = Once::new();
303 HIDE_PANICS_DURING_EXPANSION.call_once(|| {
304 let prev = panic::take_hook();
305 panic::set_hook(Box::new(move |info| {
306 let hide = BridgeState::with(|state| match state {
307 BridgeState::NotConnected => false,
308 BridgeState::Connected(_) | BridgeState::InUse => true,
316 BRIDGE_STATE.with(|state| state.set(BridgeState::Connected(self), f))
319 fn with<R>(f: impl FnOnce(&mut Bridge) -> R) -> R {
320 BridgeState::with(|state| match state {
321 BridgeState::NotConnected => {
322 panic!("procedural macro API is used outside of a procedural macro");
324 BridgeState::InUse => {
325 panic!("procedural macro API is used while it's already in use");
327 BridgeState::Connected(bridge) => f(bridge),
332 /// A client-side "global object" (usually a function pointer),
333 /// which may be using a different `proc_macro` from the one
334 /// used by the server, but can be interacted with compatibly.
336 /// N.B., `F` must have FFI-friendly memory layout (e.g., a pointer).
337 /// The call ABI of function pointers used for `F` doesn't
338 /// need to match between server and client, since it's only
339 /// passed between them and (eventually) called by the client.
341 #[derive(Copy, Clone)]
342 pub struct Client<F> {
343 pub(super) get_handle_counters: extern "C" fn() -> &'static HandleCounters,
344 pub(super) run: extern "C" fn(Bridge, F) -> Buffer<u8>,
348 // FIXME(#53451) public to work around `Cannot create local mono-item` ICE,
349 // affecting not only the function itself, but also the `BridgeState` `thread_local!`.
350 pub extern "C" fn __run_expand1(
352 f: fn(::TokenStream) -> ::TokenStream,
354 // The initial `cached_buffer` contains the input.
355 let mut b = bridge.cached_buffer.take();
357 panic::catch_unwind(panic::AssertUnwindSafe(|| {
359 let reader = &mut &b[..];
360 let input = TokenStream::decode(reader, &mut ());
362 // Put the `cached_buffer` back in the `Bridge`, for requests.
363 Bridge::with(|bridge| bridge.cached_buffer = b.take());
365 let output = f(::TokenStream(input)).0;
367 // Take the `cached_buffer` back out, for the output value.
368 b = Bridge::with(|bridge| bridge.cached_buffer.take());
370 // HACK(eddyb) Separate encoding a success value (`Ok(output)`)
371 // from encoding a panic (`Err(e: PanicMessage)`) to avoid
372 // having handles outside the `bridge.enter(|| ...)` scope, and
373 // to catch panics that could happen while encoding the success.
375 // Note that panics should be impossible beyond this point, but
376 // this is defensively trying to avoid any accidental panicking
377 // reaching the `extern "C"` (which should `abort` but may not
378 // at the moment, so this is also potentially preventing UB).
380 Ok::<_, ()>(output).encode(&mut b, &mut ());
383 .map_err(PanicMessage::from)
384 .unwrap_or_else(|e| {
386 Err::<(), _>(e).encode(&mut b, &mut ());
391 impl Client<fn(::TokenStream) -> ::TokenStream> {
392 pub const fn expand1(f: fn(::TokenStream) -> ::TokenStream) -> Self {
394 get_handle_counters: HandleCounters::get,
401 // FIXME(#53451) public to work around `Cannot create local mono-item` ICE,
402 // affecting not only the function itself, but also the `BridgeState` `thread_local!`.
403 pub extern "C" fn __run_expand2(
405 f: fn(::TokenStream, ::TokenStream) -> ::TokenStream,
407 // The initial `cached_buffer` contains the input.
408 let mut b = bridge.cached_buffer.take();
410 panic::catch_unwind(panic::AssertUnwindSafe(|| {
412 let reader = &mut &b[..];
413 let input = TokenStream::decode(reader, &mut ());
414 let input2 = TokenStream::decode(reader, &mut ());
416 // Put the `cached_buffer` back in the `Bridge`, for requests.
417 Bridge::with(|bridge| bridge.cached_buffer = b.take());
419 let output = f(::TokenStream(input), ::TokenStream(input2)).0;
421 // Take the `cached_buffer` back out, for the output value.
422 b = Bridge::with(|bridge| bridge.cached_buffer.take());
424 // HACK(eddyb) Separate encoding a success value (`Ok(output)`)
425 // from encoding a panic (`Err(e: PanicMessage)`) to avoid
426 // having handles outside the `bridge.enter(|| ...)` scope, and
427 // to catch panics that could happen while encoding the success.
429 // Note that panics should be impossible beyond this point, but
430 // this is defensively trying to avoid any accidental panicking
431 // reaching the `extern "C"` (which should `abort` but may not
432 // at the moment, so this is also potentially preventing UB).
434 Ok::<_, ()>(output).encode(&mut b, &mut ());
437 .map_err(PanicMessage::from)
438 .unwrap_or_else(|e| {
440 Err::<(), _>(e).encode(&mut b, &mut ());
445 impl Client<fn(::TokenStream, ::TokenStream) -> ::TokenStream> {
446 pub const fn expand2(f: fn(::TokenStream, ::TokenStream) -> ::TokenStream) -> Self {
448 get_handle_counters: HandleCounters::get,
456 #[derive(Copy, Clone)]
459 trait_name: &'static str,
460 attributes: &'static [&'static str],
461 client: Client<fn(::TokenStream) -> ::TokenStream>,
466 client: Client<fn(::TokenStream, ::TokenStream) -> ::TokenStream>,
471 client: Client<fn(::TokenStream) -> ::TokenStream>,
476 pub const fn custom_derive(
477 trait_name: &'static str,
478 attributes: &'static [&'static str],
479 expand: fn(::TokenStream) -> ::TokenStream,
481 ProcMacro::CustomDerive {
484 client: Client::expand1(expand),
490 expand: fn(::TokenStream, ::TokenStream) -> ::TokenStream,
494 client: Client::expand2(expand),
498 pub const fn bang(name: &'static str, expand: fn(::TokenStream) -> ::TokenStream) -> Self {
501 client: Client::expand1(expand),