Skip to content

Commit 60481a5

Browse files
Rollup merge of rust-lang#157076 - bjorn3:proc_macro_refactors4, r=petrochenkov
Various proc-macro related code cleanups Some are just misc cleanups. Others are to make the proc-macro ABI and RPC interface a bit less target dependent. I've got some local changes that change the ABI to what is effectively a single `&[extern "C" fn(BridgeConfig<'_>) -> Buffer]` export.
2 parents 72a509f + d31c731 commit 60481a5

5 files changed

Lines changed: 50 additions & 63 deletions

File tree

compiler/rustc_metadata/src/rmeta/encoder.rs

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2036,7 +2036,6 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
20362036

20372037
let def_id = id.to_def_id();
20382038
self.tables.def_kind.set_some(def_id.index, DefKind::Macro(macro_kind.into()));
2039-
self.tables.proc_macro.set_some(def_id.index, macro_kind);
20402039
self.encode_attrs(id);
20412040
record!(self.tables.def_keys[def_id] <- def_key);
20422041
record!(self.tables.def_ident_span[def_id] <- span);

compiler/rustc_metadata/src/rmeta/mod.rs

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -464,7 +464,6 @@ define_tables! {
464464
variant_data: Table<DefIndex, LazyValue<VariantData>>,
465465
assoc_container: Table<DefIndex, LazyValue<ty::AssocContainer>>,
466466
macro_definition: Table<DefIndex, LazyValue<ast::DelimArgs>>,
467-
proc_macro: Table<DefIndex, MacroKind>,
468467
deduced_param_attrs: Table<DefIndex, LazyArray<DeducedParamAttrs>>,
469468
collect_return_position_impl_trait_in_trait_tys: Table<DefIndex, LazyValue<DefIdMap<ty::EarlyBinder<'static, Ty<'static>>>>>,
470469
doc_link_resolutions: Table<DefIndex, LazyValue<DocLinkResMap>>,

library/proc_macro/src/bridge/client.rs

Lines changed: 23 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -2,19 +2,9 @@
22
33
use std::cell::RefCell;
44
use std::marker::PhantomData;
5-
use std::sync::atomic::AtomicU32;
65

76
use super::*;
87

9-
#[repr(C)]
10-
pub(super) struct HandleCounters {
11-
pub(super) token_stream: AtomicU32,
12-
pub(super) span: AtomicU32,
13-
}
14-
15-
static COUNTERS: HandleCounters =
16-
HandleCounters { token_stream: AtomicU32::new(1), span: AtomicU32::new(1) };
17-
188
pub(crate) struct TokenStream {
199
handle: handle::Handle,
2010
}
@@ -47,6 +37,18 @@ impl<S> Decode<'_, '_, S> for TokenStream {
4737
}
4838
}
4939

40+
impl Encode<()> for crate::TokenStream {
41+
fn encode(self, w: &mut Buffer, s: &mut ()) {
42+
self.0.encode(w, s)
43+
}
44+
}
45+
46+
impl Decode<'_, '_, ()> for crate::TokenStream {
47+
fn decode(r: &mut &[u8], s: &mut ()) -> Self {
48+
crate::TokenStream(Some(Decode::decode(r, s)))
49+
}
50+
}
51+
5052
#[derive(Copy, Clone, PartialEq, Eq, Hash)]
5153
pub(crate) struct Span {
5254
handle: handle::Handle,
@@ -209,8 +211,6 @@ pub(crate) fn is_available() -> bool {
209211
/// and forcing the use of APIs that take/return `S::TokenStream`, server-side.
210212
#[repr(C)]
211213
pub struct Client<I, O> {
212-
pub(super) handle_counters: &'static HandleCounters,
213-
214214
pub(super) run: extern "C" fn(BridgeConfig<'_>) -> Buffer,
215215

216216
pub(super) _marker: PhantomData<fn(I) -> O>,
@@ -243,14 +243,13 @@ fn maybe_install_panic_hook(force_show_panics: bool) {
243243

244244
/// Client-side helper for handling client panics, entering the bridge,
245245
/// deserializing input and serializing output.
246-
// FIXME(eddyb) maybe replace `Bridge::enter` with this?
247-
fn run_client<A: for<'a, 's> Decode<'a, 's, ()>, R: Encode<()>>(
246+
fn run_client<A: for<'a, 's> Decode<'a, 's, ()>>(
248247
config: BridgeConfig<'_>,
249-
f: impl FnOnce(A) -> R,
248+
f: impl FnOnce(A) -> crate::TokenStream,
250249
) -> Buffer {
251250
let BridgeConfig { input: mut buf, dispatch, force_show_panics, .. } = config;
252251

253-
panic::catch_unwind(panic::AssertUnwindSafe(|| {
252+
let res = panic::catch_unwind(panic::AssertUnwindSafe(|| {
254253
maybe_install_panic_hook(force_show_panics);
255254

256255
// Make sure the symbol store is empty before decoding inputs.
@@ -267,23 +266,12 @@ fn run_client<A: for<'a, 's> Decode<'a, 's, ()>, R: Encode<()>>(
267266
// Take the `cached_buffer` back out, for the output value.
268267
buf = RefCell::into_inner(state).cached_buffer;
269268

270-
// HACK(eddyb) Separate encoding a success value (`Ok(output)`)
271-
// from encoding a panic (`Err(e: PanicMessage)`) to avoid
272-
// having handles outside the `bridge.enter(|| ...)` scope, and
273-
// to catch panics that could happen while encoding the success.
274-
//
275-
// Note that panics should be impossible beyond this point, but
276-
// this is defensively trying to avoid any accidental panicking
277-
// reaching the `extern "C"` (which should `abort` but might not
278-
// at the moment, so this is also potentially preventing UB).
279-
buf.clear();
280-
Ok::<_, ()>(output).encode(&mut buf, &mut ());
281-
}))
282-
.map_err(PanicMessage::from)
283-
.unwrap_or_else(|e| {
284-
buf.clear();
285-
Err::<(), _>(e).encode(&mut buf, &mut ());
286-
});
269+
output
270+
}));
271+
272+
// Serialize response of type `Result<R, PanicMessage>`.
273+
buf.clear();
274+
res.map_err(PanicMessage::from).encode(&mut buf, &mut ());
287275

288276
// Now that a response has been serialized, invalidate all symbols
289277
// registered with the interner.
@@ -294,9 +282,8 @@ fn run_client<A: for<'a, 's> Decode<'a, 's, ()>, R: Encode<()>>(
294282
impl Client<crate::TokenStream, crate::TokenStream> {
295283
pub const fn expand1(f: impl Fn(crate::TokenStream) -> crate::TokenStream + Copy) -> Self {
296284
Client {
297-
handle_counters: &COUNTERS,
298285
run: super::selfless_reify::reify_to_extern_c_fn_hrt_bridge(move |bridge| {
299-
run_client(bridge, |input| f(crate::TokenStream(Some(input))).0)
286+
run_client(bridge, |input| f(input))
300287
}),
301288
_marker: PhantomData,
302289
}
@@ -308,11 +295,8 @@ impl Client<(crate::TokenStream, crate::TokenStream), crate::TokenStream> {
308295
f: impl Fn(crate::TokenStream, crate::TokenStream) -> crate::TokenStream + Copy,
309296
) -> Self {
310297
Client {
311-
handle_counters: &COUNTERS,
312298
run: super::selfless_reify::reify_to_extern_c_fn_hrt_bridge(move |bridge| {
313-
run_client(bridge, |(input, input2)| {
314-
f(crate::TokenStream(Some(input)), crate::TokenStream(Some(input2))).0
315-
})
299+
run_client(bridge, |(input, input2)| f(input, input2))
316300
}),
317301
_marker: PhantomData,
318302
}

library/proc_macro/src/bridge/rpc.rs

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -15,20 +15,30 @@ pub(super) trait Decode<'a, 's, S>: Sized {
1515
}
1616

1717
macro_rules! rpc_encode_decode {
18-
(le $ty:ty) => {
18+
(le $ty:ident $size:literal) => {
1919
impl<S> Encode<S> for $ty {
2020
fn encode(self, w: &mut Buffer, _: &mut S) {
21-
w.extend_from_array(&self.to_le_bytes());
21+
const N: usize = size_of::<$ty>();
22+
23+
// We can pad with zeros without changing the value because of
24+
// little endian encoding.
25+
let mut bytes = [0; $size];
26+
bytes[..N].copy_from_slice(&self.to_le_bytes());
27+
28+
w.extend_from_array(&bytes);
2229
}
2330
}
2431

2532
impl<S> Decode<'_, '_, S> for $ty {
2633
fn decode(r: &mut &[u8], _: &mut S) -> Self {
2734
const N: usize = size_of::<$ty>();
35+
const {
36+
assert!(N <= $size);
37+
}
2838

2939
let mut bytes = [0; N];
3040
bytes.copy_from_slice(&r[..N]);
31-
*r = &r[N..];
41+
*r = &r[$size..];
3242

3343
Self::from_le_bytes(bytes)
3444
}
@@ -108,8 +118,8 @@ impl<S> Decode<'_, '_, S> for u8 {
108118
}
109119
}
110120

111-
rpc_encode_decode!(le u32);
112-
rpc_encode_decode!(le usize);
121+
rpc_encode_decode!(le u32 4);
122+
rpc_encode_decode!(le usize 8);
113123

114124
impl<S> Encode<S> for bool {
115125
fn encode(self, w: &mut Buffer, s: &mut S) {

library/proc_macro/src/bridge/server.rs

Lines changed: 12 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
//! Server-side traits.
22
33
use std::cell::Cell;
4+
use std::sync::atomic::AtomicU32;
45
use std::sync::mpsc;
56

67
use super::*;
@@ -11,10 +12,13 @@ pub(super) struct HandleStore<S: Server> {
1112
}
1213

1314
impl<S: Server> HandleStore<S> {
14-
fn new(handle_counters: &'static client::HandleCounters) -> Self {
15+
fn new() -> Self {
16+
static TOKEN_STREAM: AtomicU32 = AtomicU32::new(1);
17+
static SPAN: AtomicU32 = AtomicU32::new(1);
18+
1519
HandleStore {
16-
token_stream: handle::OwnedStore::new(&handle_counters.token_stream),
17-
span: handle::InternedStore::new(&handle_counters.span),
20+
token_stream: handle::OwnedStore::new(&TOKEN_STREAM),
21+
span: handle::InternedStore::new(&SPAN),
1822
}
1923
}
2024
}
@@ -246,13 +250,12 @@ fn run_server<
246250
O: for<'a, 's> Decode<'a, 's, HandleStore<S>>,
247251
>(
248252
strategy: &impl ExecutionStrategy,
249-
handle_counters: &'static client::HandleCounters,
250253
server: S,
251254
input: I,
252255
run_client: extern "C" fn(BridgeConfig<'_>) -> Buffer,
253256
force_show_panics: bool,
254257
) -> Result<O, PanicMessage> {
255-
let mut dispatcher = Dispatcher { handle_store: HandleStore::new(handle_counters), server };
258+
let mut dispatcher = Dispatcher { handle_store: HandleStore::new(), server };
256259

257260
let globals = dispatcher.server.globals();
258261

@@ -276,16 +279,9 @@ impl client::Client<crate::TokenStream, crate::TokenStream> {
276279
where
277280
S: Server,
278281
{
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())
282+
let client::Client { run, _marker } = *self;
283+
run_server(strategy, server, <MarkedTokenStream<S>>::mark(input), run, force_show_panics)
284+
.map(|s| <Option<MarkedTokenStream<S>>>::unmark(s).unwrap_or_default())
289285
}
290286
}
291287

@@ -301,10 +297,9 @@ impl client::Client<(crate::TokenStream, crate::TokenStream), crate::TokenStream
301297
where
302298
S: Server,
303299
{
304-
let client::Client { handle_counters, run, _marker } = *self;
300+
let client::Client { run, _marker } = *self;
305301
run_server(
306302
strategy,
307-
handle_counters,
308303
server,
309304
(<MarkedTokenStream<S>>::mark(input), <MarkedTokenStream<S>>::mark(input2)),
310305
run,

0 commit comments

Comments
 (0)